#include "HC-04.h"
#include "common.h"

uint8_t HC04_DATA[1024] = { 0 };

int HC04_DATA_LEN = 0;

int HC_04_UART_INIT(int pio)
{
    // 初始化UART
    if (pio == 1) {
        uint tx_offset = pio_add_program(HC_04_PIO, &uart_tx_program);
        uart_tx_program_init(HC_04_PIO, HC_04_PIO_SM_TX, tx_offset, HC_04_PIO_TX_PIN, HC_04_PIO_SERIAL_BAUD);

        uint rx_offset = pio_add_program(HC_04_PIO, &uart_rx_program);
        uart_rx_program_init(HC_04_PIO, HC_04_PIO_SM_RX, rx_offset, HC_04_PIO_RX_PIN, HC_04_PIO_SERIAL_BAUD);
    }

    return 0;
}

int HC_04_PIO_UART_TX_DATA(PIO pio, uint sm, char *DATA, int DATA_LEN)
{
    for (int i = 0; i < DATA_LEN; i++) {
        uart_tx_program_putc(pio, sm, DATA[i]);
        sleep_ms(1);
    }

    return 0;
}

int HC_04_PIO_UART_RX_DATA(PIO pio, uint sm, uint8_t * DATA, int DATA_LEN)
{
    char c = '\0';
    int received_count = 0;
    int timeout_ms = 1000;      // 设置较长的超时时间

    while (received_count < DATA_LEN && timeout_ms > 0) {
        if (uart_rx_program_available(pio, sm)) {
            c = uart_rx_program_getc(pio, sm);
            DATA[received_count++] = c;
            //printf("0x%X ", c);
        } else {
            // 没有接收到数据，继续等待
            sleep_ms(2);
            timeout_ms--;
        }
    }

    if (received_count == 0) {
        // 没有接收到有效数据
        return -1;
    }

    return received_count;
}

void HC_04_UART_WRITE(void *p)
{
    (void)p;
    /*
       AT+RESET // 重启
       AT+RX  // 查询模块多个参数

     */

    char _CMD0[] = "AT+RX";     // 查询

    // 发送数据
    HC_04_PIO_UART_TX_DATA(HC_04_PIO, HC_04_PIO_SM_TX, _CMD0, sizeof(_CMD0));

}

void HC_04_UART_READ(void *p)
{
    (void)p;
    //printf("HC-04 Module\n");

    memset(HC04_DATA, 0, 1024);
    if (0 >= HC_04_PIO_UART_RX_DATA(HC_04_PIO, HC_04_PIO_SM_RX, HC04_DATA, 270)) {
        ;
    } else {
        if (0 < strlen((char *)HC04_DATA)) {
            printf("%s\n", HC04_DATA);
            memset(HC04_DATA, 0, 1024);
        }
    }

    return;
}

void HC_04(void *p)
{
    (void)p;
    HC_04_UART_INIT(1);
    while (1) {
        HC_04_UART_WRITE(NULL);
        HC_04_UART_READ(NULL);

        printf("\n");
        vTaskDelay(pdMS_TO_TICKS(3000)); // 非阻塞延时
    }
    
    return ;
}
