#include <iostream>
#include "pico/stdlib.h"
#include "../../radio-switch.h"

#include <time.h>

#define BUFFER_SIZ 1024

// 闪烁LED
static void light()
{
    const uint LED_PIN = PICO_DEFAULT_LED_PIN;
    gpio_init(LED_PIN);
    gpio_set_dir(LED_PIN, GPIO_OUT);
    gpio_put(LED_PIN, 1);
    sleep_ms(100);
    gpio_put(LED_PIN, 0);
    sleep_ms(100);

}

static char pool[] = {
    '1', '2', '3', '4', '5', '6', '7', '8', '9'
};

// 随即数
static int RAND()
{
    int PASSWD_LEN = 3;
    char password[BUFFER_SIZ];
    int i = 0;
    FILE *fp;

    memset(password, 0, BUFFER_SIZ);
    srand(time(NULL));

    while (i != PASSWD_LEN) {
        password[i++] = pool[rand() % sizeof(pool)];
    }

    //printf("%d\n", atoi(password));

    return atoi(password);
}

int main(void)
{

    const uint RADIO_TRANSMIT_PIN = 16; // 433发射模块引脚
    const uint BUTTON = 17;     // 按钮发射

    const uint PULSE_LENGTH = 169; // set this to PULSELENGTH RECIEVED
    const uint REPEAT_TRANSMIT = 4; // set this to whatever works best for you.    // 重复发送
    const uint PROTOCOL = 1;    // set this to PROTOCOL RECIEVED
    const uint BIT_LENGTH = 24; // set this to BIT LENGTH RECIEVED

    stdio_init_all();
    gpio_init(RADIO_TRANSMIT_PIN);
    RCSwitch mySwitch = RCSwitch();
    mySwitch.enableTransmit(RADIO_TRANSMIT_PIN);
    mySwitch.setProtocol(PROTOCOL);
    mySwitch.setPulseLength(PULSE_LENGTH);
    mySwitch.setRepeatTransmit(REPEAT_TRANSMIT);

    int RANDOM = 30;
    int LOOP_NUM = 1;           // 循环发送次数

    const int but = 55001;

    stdio_uart_init_full(uart0, 115200, 6, 7);

    while (1) {
        //fprintf(uart0_handle, "Hello from uart0!\r\n");

        //if (1 == gpio_get(BUTTON)) {                // 按钮按下
        for (int i = 0; i <= LOOP_NUM; i++) {
            RANDOM = RAND();
            light();            // 灯闪烁

            sleep_ms(RANDOM * 2 / 3); // 等待随机时间

            mySwitch.send(but, BIT_LENGTH); // 第一次发射
            sleep_ms(130);

            //mySwitch.send(but+1, BIT_LENGTH);   // 第二次发射
            //sleep_ms(130);
        }
        //}

        sleep_ms(3000);
    }

    return 0;
}
