#include "EC800M_GPS.h"
#include "EC800M_4G.h"

int _r = 0;
int _timeout = 1;

// 存放4G数据
char _4G_DATA[_4G_DATA_LENGTH];
int _4G_DATA_LEN;

// 重置4G数据缓冲区
void _4g_reset_data()
{
    memset(_4G_DATA, 0, _4G_DATA_LENGTH);
    _4G_DATA_LEN = 0;
}

void uart_send_string(const char *str)
{
    size_t len = strlen(str);
    uart_write_blocking(EC800M_4G_UART, (const uint8_t *)str, len);

    return;
}

int _4G_uart_read_string(char *_4G_DATA, int *_4G_DATA_LEN)
{
    int _time = 0;
    int timeout = 3000;         // 设置超时时间为3秒，单位为毫秒

    while (1) {
        // 检查是否超时
        if (_time >= timeout) {
            printf("EC800M _4G_uart_read_string() 读取超时\n");
            return -1;
        }

        if (uart_is_readable(EC800M_4G_UART)) {
            if (*_4G_DATA_LEN < _4G_DATA_LENGTH - 1) {
                char c = uart_getc(EC800M_4G_UART);
                _4G_DATA[(*_4G_DATA_LEN)++] = c;
                _4G_DATA[*_4G_DATA_LEN] = '\0';
            }
        } else {
            break;
        }

        sleep_ms(1);            // 稍微延迟一下，等待下一个循环
        _time++;
    }

    return 0;
}

int _4G_uart_read_string_until_response(char *DATA, int *DATA_LEN, const char *expected_response)
{

    int timeout = 10000;        // 设置超时时间为10秒，单位为毫秒

    *DATA_LEN = 0;
    int _time = 0;
    while (1) {
        while (uart_is_readable(EC800M_4G_UART)) {
            if (*DATA_LEN < _4G_DATA_LENGTH) {
                char c = uart_getc(EC800M_4G_UART);
                DATA[(*DATA_LEN)++] = c;
                DATA[*DATA_LEN] = '\0'; // 添加字符串结束符
            }

            if (strstr(DATA, expected_response) != NULL) {
                return 0;       // 找到了预期的响应，退出循环
            } else {
                //printf("%s\n", DATA);
            }
        }
        _time++;
        sleep_ms(1);            // 等待一小段时间再继续读取

        if (_time >= timeout) {
            _time = 0;
            printf("EC800M _4G_uart_read_string_until_response() 读取超时\n");

            return -1;
        }
    }
}

int EC800M_4G_INIT()
{
    // AT+CFUN=1,1
    //uart_send_string("AT+CFUN=1,1\r\n");

    // AT+CGREG=2
    uart_send_string("AT+CGREG=2\r\n");
    sleep_ms(10);
    if (-1 == _4G_uart_read_string_until_response(_4G_DATA, &_4G_DATA_LEN, "OK")) {
        printf("EC800M Module 4G AT+QIACT? Timeout!\n");
        return -1;
    }
    printf("%s %d\n", _4G_DATA, _4G_DATA_LEN);

    // AT+CGATT=1
    uart_send_string("AT+CGATT=1\r\n");
    sleep_ms(10);
    if (-1 == _4G_uart_read_string_until_response(_4G_DATA, &_4G_DATA_LEN, "OK")) {
        printf("EC800M Module 4G AT+CGATT=1 Timeout!\n");
        return -1;
    }
    printf("%s %d\n", _4G_DATA, _4G_DATA_LEN);

    // AT+CEREG=2
    uart_send_string("AT+CEREG=2\r\n");
    sleep_ms(10);
    if (-1 == _4G_uart_read_string_until_response(_4G_DATA, &_4G_DATA_LEN, "OK")) {
        printf("EC800M Module 4G AT+CEREG=2 Timeout!\n");
        return -1;
    }
    printf("%s %d\n", _4G_DATA, _4G_DATA_LEN);

    // AT+QICSGP=1
    uart_send_string("AT+QICSGP=1\r\n");
    //sleep_ms(10);
    if (-1 == _4G_uart_read_string_until_response(_4G_DATA, &_4G_DATA_LEN, "OK")) {
        printf("EC800M Module 4G AT+QICSGP=1 Timeout!\n");
        return -1;
    }
    printf("%s %d\n", _4G_DATA, _4G_DATA_LEN);

    // AT+QIACT=1
    uart_send_string("AT+QIACT=1\r\n");
    sleep_ms(10);
    if (-1 == _4G_uart_read_string(_4G_DATA, &_4G_DATA_LEN)) {
        return -1;
    }
    printf("%s %d\n", _4G_DATA, _4G_DATA_LEN);

    // AT+QIACT?
    uart_send_string("AT+QIACT?\r\n");
    if (-1 == _4G_uart_read_string_until_response(_4G_DATA, &_4G_DATA_LEN, "OK")) {
        printf("EC800M Module 4G AT+QIACT? Timeout!\n");
        return -1;
    }
    printf("%s %d\n", _4G_DATA, _4G_DATA_LEN);

    // AT+QIDEACT=1
    uart_send_string("AT+QIDEACT=1\r\n");
    if (-1 == _4G_uart_read_string_until_response(_4G_DATA, &_4G_DATA_LEN, "OK")) {
        printf("EC800M Module 4G AT+QIDEACT=1 Timeout!\n");
        return -1;
    }
    printf("%s %d\n", _4G_DATA, _4G_DATA_LEN);

    // AT+QIOPEN=1,0,"TCP","47.240.75.93",8009,0,1
    uart_send_string("AT+QIOPEN=1,0,\"TCP\",\"123.60.29.178\",8009,0,1\r\n");
    if (-1 == _4G_uart_read_string_until_response(_4G_DATA, &_4G_DATA_LEN, "0,0")) {
        printf("EC800M Module 4G \"AT+QIOPEN=1,0,\"TCP\",\"123.60.29.178\",8009,0,1\r\n\" Timeout!\n");
        return -1;
    }
    printf("%s %d\n", _4G_DATA, _4G_DATA_LEN);

/*
    // AT+QISTATE=1,0
    uart_send_string("AT+QISTATE=1,0\r\n");
    if (-1 == _4G_uart_read_string(_4G_DATA, &_4G_DATA_LEN)) {
        printf("EC800M Module 4G AT+QISTATE=1,0 Timeout!\n");
        return -1;
    }
    printf("%s %d\n", _4G_DATA, _4G_DATA_LEN);
*/

    return 1;
}

int receive_data(char *input_string)
{
    char temp_buffer[270] = { 0 };
    char received_data[270] = { 0 };
    int received_data_length = 0;
    int step = 1;
    char *token = NULL;
    char *start = NULL;
    char *end = NULL;
    size_t temp_length = 0;

    // 在指针不为NULL时才进行后续操作
    start = strstr(input_string, "QIURC");
    if (start == NULL) {
        printf("Error: 'QIURC' not found\n");
        return -1;              // 返回错误代码
    }

    end = strstr(start, "\r\n");
    if (end == NULL) {
        printf("Error: '\\r\\n' not found\n");
        return -1;              // 返回错误代码
    }

    temp_length = end - start;  // 计算子字符串的长度
    if (temp_length >= sizeof(temp_buffer)) {
        printf("Error: Substring length exceeds buffer size\n");
        return -1;              // 返回错误代码
    }
    // 复制子字符串到 TEMP 中
    memcpy(temp_buffer, start, temp_length);
    temp_buffer[temp_length] = '\0'; // 添加字符串结束标志

    // 使用 strtok 解析 TEMP 字符串
    token = strtok(temp_buffer, ",");
    while (token != NULL) {
        if (step == 3) {
            received_data_length = atoi(token);
        }
        token = strtok(NULL, ",");
        step++;
    }

    // 检查 received_data_length 是否为有效值
    if (received_data_length <= 0 || received_data_length >= (int)sizeof(received_data)) {
        printf("Error: Invalid received_data_length value\n");
        return -1;              // 返回错误代码
    }
    // 复制数据到 received_data 中
    memcpy(received_data, end + 2, received_data_length);
    received_data[received_data_length] = '\0'; // 添加字符串结束标志

    printf("%s", received_data);

    return 0;                   // 返回成功代码
}

// 查询Socket状态
int CHECK_TCP_STATUS()
{
    char RECV[270] = { 0 };
    int RECV_LEN = 0;
    int step = 1;
    int socket_state = 0;

    printf("Query Socket status!!!\n");

    uart_send_string("AT+QISTATE=1,0\r\n");
    if (-1 == _4G_uart_read_string_until_response(RECV, &RECV_LEN, "OK")) {
        printf("EC800M Module 4G AT+QISTATE=1,0 Timeout!\n");
        return -1;
    }
    printf("%s %d\n", RECV, RECV_LEN);

    char *token = strtok(RECV, ",");
    while (token != NULL) {
        if (step == 7) {
            socket_state = atoi(token);
        }
        token = strtok(NULL, ",");
        step++;
    }

    printf("socket_state: %d\n", socket_state);

    return socket_state;
}

// 重新连接TCP
int TCP_RESTART()
{
    char RECV[270] = { 0 };
    int RECV_LEN = 0;

    printf("Re-establish TCP!!!\n");

    uart_send_string("AT+QICLOSE=0\r\n");
    if (-1 == _4G_uart_read_string_until_response(RECV, &RECV_LEN, "OK")) {
        printf("EC800M Module 4G AT+QICLOSE=0 Timeout!\n");
        return -1;
    }
    printf("%s %d\n", RECV, RECV_LEN);

    uart_send_string("AT+QIOPEN=1,0,\"TCP\",\"123.60.29.178\",8009,0,1\r\n");
    if (-1 == _4G_uart_read_string_until_response(RECV, &RECV_LEN, "0,0")) {
        printf("EC800M Module 4G AT+QICLOSE=0 Timeout!\n");
        return -1;
    }
    printf("%s %d\n", RECV, RECV_LEN);

    sleep_ms(3000);
    return 0;
}

#include <stdbool.h>
// 全局变量，表示TCP连接是否已经成功建立过
bool tcp_connection_established = false;

int establish_tcp_connection()
{
    // 如果TCP连接已经成功建立过，则直接返回成功
    if (tcp_connection_established) {
        printf("TCP connection already established.\n");
        return 0;
    }

    int _r = EC800M_4G_INIT();  // 第一次建立TCP
    int retry_count = 0;        // 重试计数器

    while (_r == -1 && retry_count < TCP_MAX_RETRY) {
        printf("TCP establishment failed! Retrying...\n");
        _r = EC800M_4G_INIT();  // 重新建立TCP连接
        retry_count++;
        sleep_ms(9000);         // 等待一段时间后重试
    }

    if (_r == -1) {
        printf("Failed to establish TCP connection after %d retries.\n", TCP_MAX_RETRY);
        return -1;              // 返回连接失败
    } else {
        printf("TCP connection established successfully.\n");
        // 标记TCP连接已经成功建立过
        tcp_connection_established = true;
        return 0;               // 返回连接成功
    }
}

int EC800M_4G_RECV(char *string)
{
    char RECV[1024] = { 0 };
    int RECV_LEN = 0;
    uint8_t CTRLZ[1];

    uart_send_string("AT+QISEND=0\r\n");
    sleep_ms(100);
    uart_send_string(string);

    CTRLZ[0] = 0X1A;
    uart_write_blocking(EC800M_4G_UART, CTRLZ, 1);

    if (-1 == _4G_uart_read_string_until_response(RECV, &RECV_LEN, "SEND OK")) {
        printf("EC800M Module 4G  AT+QISEND=0 Timeout!\n");
        _timeout++;
        if (2 != CHECK_TCP_STATUS()) {
            if (-1 == TCP_RESTART()) {
                printf("TCP RESTART ERROR!\n");
            }
        }
    } else {
        receive_data(RECV);

        if (2 != CHECK_TCP_STATUS()) {
            if (-1 == TCP_RESTART()) {
                printf("TCP RESTART ERROR!\n");
            }
        }
    }

    sleep_ms(3000);
    return 0;
}

void EC800M_4G(void *p)
{
    (void)p;
    
    EC800M_UART_INIT();

    while (1) {
        printf("EC800M Module 4G\n");

        int result = establish_tcp_connection();
        if (result == 0) {
            ;
        }
        EC800M_4G_RECV("abcd\r\n");
        EC800M_4G_RECV("aixiao.me\r\n");
        
        
        
        EC800M_GPS(NULL);

        vTaskDelay(pdMS_TO_TICKS(3000)); // 非阻塞延时
    }

    return;
}
