#include "WIFI.h"
#include "cmsis_os.h"
#include "remote.h"
#include "ML307A.h"
#include "main.h"
#include "uType.h"
#include "cmsis_os.h"

char WIFIresponseBuf[256]; // AT指令应答的局部缓冲区
char WIFIresponseBuf_2[256]; // AT指令应答的局部缓冲区
extern circle_buf_t uart3CircleBuf;  // 环形缓冲区管理结构体
extern int g_cip_id; // TCP_IP分配的端口号

extern uint8_t terminalId[7];
extern uint8_t g_board_id[6];
extern uint16_t Register_Serial_number;// 注册消息流水号
extern uint16_t Heartbeat_Serial_number;// 心跳消息流水号
extern uint16_t response_Serial_number;// 通用应答消息流水号
extern uint16_t sensorline_Serial_number;// 掉线上传消息流水号
extern uint16_t systemlevel_Serial_number;// 预警等级消息流水号
extern uint16_t Temperature_Serial_number;// 温度数据消息流水号
extern uint16_t Pressure_CO_H2_Serial_number;// 压气数据消息流水号
extern uint8_t g_remote_databuffer[450];
extern char g_remote_atbuffer[512];
extern uint8_t systemlevel_body[12];
extern uint8_t General_response[5];
extern uint8_t temp_body[424];
extern uint8_t prc0h2_body[62];
extern uint8_t license[9];
extern time_t epoch_time;
extern uint8_t sensor_status[6];  // 传感器在线情况初始化全 0，0为掉线，1为在线
extern uint32_t adc_val; // ADC读取电压
extern uint8_t voltage_int;
extern uint8_t percent;
extern uint8_t flash_temp_prc0h2[512]; // 存入flash的温度和压力数据
extern uint16_t trigger_info[3]; // 存储触发信息

uint8_t sendCmd_WIFI(char *pCmd, char *pRes1, char *pRes2, uint32_t timeOut, uint8_t sendNum)
{
    uint8_t i;
    uint32_t time;
    uint8_t receivedByte;

    memset(WIFIresponseBuf_2, 0, sizeof(WIFIresponseBuf_2)); // 清空临时缓冲区

    for (i = 0; i < sendNum; i++)
    {
        time = timeOut * 10; // 计算超时时间

//        // ★ 发送前丢弃旧数据 ★
//        __HAL_UART_DISABLE_IT(&huart1, UART_IT_IDLE); // 可选：保护指针修改
//        uart1CircleBuf.r = uart1CircleBuf.w;          // 丢弃旧数据
//        __HAL_UART_ENABLE_IT(&huart1, UART_IT_IDLE);

        USART_SendString(&huart3, pCmd); // 发送 AT 指令
        osDelay(50);                    // 等待模块返回

        uint8_t matchFlag = 0;

        while (time--)
        {
            uint8_t gotNewData = 0;

            // 读取环形缓冲区内的新数据
            while (circle_buf_read(&uart3CircleBuf, &receivedByte) == 0)
            {
                gotNewData = 1;

                uint16_t len = strlen(WIFIresponseBuf_2);
                if (len < sizeof(WIFIresponseBuf_2) - 1)
                {
                    WIFIresponseBuf_2[len] = receivedByte;
                    WIFIresponseBuf_2[len + 1] = '\0'; // 字符串结束符
                }
            }

            if (gotNewData)
            {
                // 每次有新数据都检测是否有完整的行
                char *lineStart = WIFIresponseBuf_2;
                while (1)
                {
                    // 查找是否有一行结束符
                    char *lineEnd = strstr(lineStart, "\r\n");
                    if (lineEnd == NULL)
                        break; // 没有完整行，等待更多数据

                    // 截断这一行，形成完整字符串
                    *lineEnd = '\0';

                    // 打印完整行
                    printf("%s\n", lineStart);

                    // 判断是否有匹配到成功应答
                    if ((pRes1 && strstr(lineStart, pRes1) != NULL) ||
                        (pRes2 && strstr(lineStart, pRes2) != NULL))
                    {
                        matchFlag = 1;
                    }

                    // 移动到下一行
                    lineStart = lineEnd + 2;
                }

                // 剩下的内容移动到buffer头部（继续拼接未完整行）
                uint16_t remainLen = strlen(lineStart);
                memmove(WIFIresponseBuf_2, lineStart, remainLen + 1); // +1 包含结束符
            }

            osDelay(10);
        }

        if (matchFlag)
        {
            printf("%s\n", WIFIresponseBuf_2); // 打印剩余数据
            return 1; // 任意一个匹配成功
        }

        printf("Timeout_!: %s\n", WIFIresponseBuf_2); // 超时打印
    }

    return 0;
}

void sendATOnly(char *pCmd)
{
    // 保护环形缓冲区（避免主循环或DMA干扰）
    __HAL_UART_DISABLE_IT(&huart3, UART_IT_IDLE);
    uart3CircleBuf.r = uart3CircleBuf.w; // 丢弃旧数据
    __HAL_UART_ENABLE_IT(&huart3, UART_IT_IDLE);

    USART_SendString(&huart3, pCmd);     // 发送 AT 指令
    osDelay(100);                        // 可选延时，让模块处理
}

int extract_cip_port(const char *src)
{
    const char *p = strstr(src, "+CIPSTART:");
    if (p) {
        p += strlen("+CIPSTART:");
        return atoi(p); // 提取冒号后面的数字
    }
    return -1; // 未找到
}

void Send_Heartbeat_WIFI(void) // test
{
    uint8_t send_buffer[64] = {0};  // 拼接缓冲区
    uint8_t hex_payload[] = {0x7E, 0x7E, 0x7E, 0x7E};  // 原始 HEX 数据
    uint16_t payload_len = sizeof(hex_payload);       // 自动获取长度

    uint16_t index = 0;

    int header_len= sprintf((char *)send_buffer, "AT+CIPSEND=%d,%d,0,0,", g_cip_id, payload_len);
		index +=header_len;

    memcpy(send_buffer + index, hex_payload, payload_len);
    index += payload_len;

    send_buffer[index++] = '\r';
    send_buffer[index++] = '\n';

    HAL_UART_Transmit(&huart3, send_buffer, index, 1000);

		printf("%.*s", header_len, send_buffer);
    for (uint16_t i = 0; i < payload_len; i++) {
        printf("%02X", hex_payload[i]);
    }
    printf("\r\n");
}

void Send_WIFI_HEX_Packet(uint8_t *hex_payload, uint16_t payload_len)
{
    uint8_t send_buffer[512] = {0};  
    uint16_t index = 0;

    int header_len = sprintf((char *)send_buffer, "AT+CIPSEND=%d,%d,0,0,", g_cip_id, payload_len);
    index += header_len;

    memcpy(send_buffer + index, hex_payload, payload_len);
    index += payload_len;

    send_buffer[index++] = '\r';
    send_buffer[index++] = '\n';

    HAL_UART_Transmit_DMA(&huart3, send_buffer, index);

    printf("%.*s", header_len, send_buffer);  // 打印 AT+CIPSEND=...
    for (uint16_t i = 0; i < payload_len; i++) {
        printf("%02X", hex_payload[i]);       // 打印 HEX 数据
    }
    printf("\r\n");
}

void Send_WIFI_ASCII_Packet_HEX(const uint8_t *bin_payload, uint16_t bin_len)
{
    uint8_t send_buffer[900] = {0};
    uint16_t index = 0;

    int header_len = sprintf((char *)send_buffer, "AT+CIPSEND=%d,%d,0,0,", g_cip_id, bin_len);
    index += header_len;

    memcpy(send_buffer + index, bin_payload, bin_len);
    index += bin_len;

    send_buffer[index++] = '\r';
    send_buffer[index++] = '\n';

    HAL_UART_Transmit_DMA(&huart3, send_buffer, index);

    printf("%.*s", header_len, send_buffer);  // 打印 AT+CIPSEND=...
    for (uint16_t i = 0; i < bin_len; i++) {
        printf("%02X", bin_payload[i]);       // 打印 HEX 数据
    }
    printf("\r\n");
}


void Send_WIFI_ASCII_Packet(const char *ascii_payload)
{
    uint8_t send_buffer[900] = {0};
    uint16_t index = 0;
    uint16_t payload_len = strlen(ascii_payload);
		
//		payload_len += 2;  
		
    // 拼接 CIPSEND 命令
    int header_len = sprintf((char *)send_buffer, "AT+CIPSEND=%d,%d,0,0,", g_cip_id, payload_len+3);
    index += header_len;

    // 拷贝 ASCII 数据
    memcpy(send_buffer + index, ascii_payload, payload_len);
    index += payload_len;

    // 添加 \r\n 结束符
		send_buffer[index++] = '|';	// '|'
    send_buffer[index++] = '\r';	// '\r' 0x0D
    send_buffer[index++] = '\n';	// '\n' 0x0A
		
//		 printf("Send Buffer (Length %d): ", index);
//    for (int i = 0; i < index; i++) {
//        printf("%02X ", send_buffer[i]);
//    }
//    printf("\n");
    // 实际发送
    HAL_UART_Transmit_DMA(&huart3, send_buffer, index);
		
    // 打印内容
    printf("%.*s", header_len, send_buffer);  // 打印 AT+CIPSEND=...
    printf("%.*s\r\n", payload_len, ascii_payload);  // 打印 ASCII 数据
}

void bin_to_hex_ascii(const uint8_t *bin, uint16_t len, char *ascii_out)
{
    for (uint16_t i = 0; i < len; i++)
    {
        sprintf(ascii_out + i * 2, "%02X", bin[i]);
    }
//		ascii_out[len * 2] = '\0';   
//    ascii_out[len * 2 + 1] = '\r'; 
//		ascii_out[len * 2 + 2] = '\n';
}


void WIFI_Send_Register(uint8_t use_ascii_mode) // // 0为发送为原始HEX数据 1为发送为ASCII字符串（HEX字符）
{
    Msg_Header header;
    Register_Body body;
    uint16_t data_len = 0;

    memset(&header, 0, sizeof(Msg_Header));
    header.id = 0x0001;
    memcpy(header.phone_number, g_board_id, 6);
    header.sequence = (Register_Serial_number << 8 & 0xFF00) | (Register_Serial_number >> 8);
    Register_Serial_number++;
    header.attr.length = sizeof(Register_Body);

    memset(&body, 0, sizeof(Register_Body));
    memcpy(body.terminalId, terminalId, 7);
    body.license_color = 0x00;
    memcpy(body.license, license, 9);

    // 开始组包
    g_remote_databuffer[data_len++] = 0x7E;

    memcpy(g_remote_databuffer + data_len, &header, sizeof(Msg_Header));
    data_len += sizeof(Msg_Header);

    memcpy(g_remote_databuffer + data_len, &body, sizeof(Register_Body));
    data_len += sizeof(Register_Body);

    g_remote_databuffer[data_len] = Calculate_Checksum(g_remote_databuffer + 1, data_len - 1);
    data_len++;

    data_len = escape_7E((char *)g_remote_databuffer + 1, data_len - 1); 
    data_len++;

    g_remote_databuffer[data_len++] = 0x7E;
//		g_remote_databuffer[data_len++] = 0x7C;
//		g_remote_databuffer[data_len++] = '\0';
//		g_remote_databuffer[data_len++] = '\r';
//		g_remote_databuffer[data_len++] = '\n';
//		printf("data_len %d\r\n",data_len);

		if (use_ascii_mode)
    {
        char ascii_payload[200] = {0};
        bin_to_hex_ascii(g_remote_databuffer, data_len, ascii_payload); // 124
        Send_WIFI_ASCII_Packet(ascii_payload);
//				Send_WIFI_ASCII_Packet_HEX(g_remote_databuffer, data_len);
    }
    else
    {
        Send_WIFI_HEX_Packet(g_remote_databuffer, data_len);
    }
}

void WIFI_Send_Heartbeat(uint8_t use_ascii_mode)
{
    Msg_Header header;
    uint16_t data_len = 0;

    memset(&header,0,sizeof(Msg_Header));
		header.id = 0x0200;
		memcpy(header.phone_number, g_board_id, 6);
		header.sequence = (Heartbeat_Serial_number<<8&0xFF00)|(Heartbeat_Serial_number>>8);
		Heartbeat_Serial_number++;
		header.attr.length = 0;
		
		g_remote_databuffer[data_len++] = 0x7E;
		
		memcpy(g_remote_databuffer+data_len, &header, sizeof(Msg_Header));
		data_len += sizeof(Msg_Header);

    g_remote_databuffer[data_len] = Calculate_Checksum(g_remote_databuffer + 1, data_len - 1);
    data_len++;

    data_len = escape_7E((char *)g_remote_databuffer + 1, data_len - 1); 
    data_len++;

    g_remote_databuffer[data_len++] = 0x7E;
//		g_remote_databuffer[data_len++] = 0x7C;
//		g_remote_databuffer[data_len++] = '\r';
//		g_remote_databuffer[data_len++] = '\n';
//		printf("data_len %d\r\n",data_len);

		if (use_ascii_mode)
    {
        char ascii_payload[200] = {0};
        bin_to_hex_ascii(g_remote_databuffer, data_len, ascii_payload);
        Send_WIFI_ASCII_Packet(ascii_payload);
//			Send_WIFI_ASCII_Packet_HEX(g_remote_databuffer, data_len);
    }
    else
    {
        Send_WIFI_HEX_Packet(g_remote_databuffer, data_len);
    }
}

void WIFI_Send_unix(uint8_t use_ascii_mode)
{
    Msg_Header header;
    uint16_t data_len = 0;

    memset(&header,0,sizeof(Msg_Header));
		header.id = 0xFF00;
		memcpy(header.phone_number, g_board_id, 6);
		header.sequence = (Heartbeat_Serial_number<<8&0xFF00)|(Heartbeat_Serial_number>>8);
		Heartbeat_Serial_number++;
		header.attr.length = 0;
		
		g_remote_databuffer[data_len++] = 0x7E;
		
		memcpy(g_remote_databuffer+data_len, &header, sizeof(Msg_Header));
		data_len += sizeof(Msg_Header);

    g_remote_databuffer[data_len] = Calculate_Checksum(g_remote_databuffer + 1, data_len - 1);
    data_len++;

    data_len = escape_7E((char *)g_remote_databuffer + 1, data_len - 1); 
    data_len++;

    g_remote_databuffer[data_len++] = 0x7E;
//		g_remote_databuffer[data_len++] = 0x7C;
//		g_remote_databuffer[data_len++] = '\r';
//		g_remote_databuffer[data_len++] = '\n';
//		printf("data_len %d\r\n",data_len);

		if (use_ascii_mode)
    {
        char ascii_payload[200] = {0};
        bin_to_hex_ascii(g_remote_databuffer, data_len, ascii_payload);
        Send_WIFI_ASCII_Packet(ascii_payload);
//			Send_WIFI_ASCII_Packet_HEX(g_remote_databuffer, data_len);
    }
    else
    {
        Send_WIFI_HEX_Packet(g_remote_databuffer, data_len);
    }
}

void WIFI_Send_systemlevel(uint8_t use_ascii_mode)
{
  uint32_t systemlevelbody_len = 0;
	Msg_Header header;
	uint16_t data_len = 0;
	
	memset(&header,0,sizeof(Msg_Header));
	header.id = 0x0103;
	memcpy(header.phone_number, g_board_id, 6);
	header.sequence = (systemlevel_Serial_number<<8&0xFF00)|(systemlevel_Serial_number>>8);
	systemlevel_Serial_number++;
	header.attr.res = 0x00;
	header.attr.length = 0x0C;
	
	g_remote_databuffer[data_len++] = 0x7E;
	
	memcpy(g_remote_databuffer+data_len, &header, sizeof(Msg_Header));
	data_len += sizeof(Msg_Header);
	
	systemlevel_body[systemlevelbody_len++] = 0x01;
	systemlevel_body[systemlevelbody_len++] = 0xF0;
	systemlevel_body[systemlevelbody_len++] = 0x01;
	systemlevel_body[systemlevelbody_len++] = system_level;
	systemlevel_body[systemlevelbody_len++] = (uint8_t)(trigger_info[0] >> 8); // 传感器类型高字节
	systemlevel_body[systemlevelbody_len++] = (uint8_t)(trigger_info[0]);      // 传感器类型低字节
	systemlevel_body[systemlevelbody_len++] = (uint8_t)(trigger_info[1]);      // 传感器编号低字节
	systemlevel_body[systemlevelbody_len++] = (uint8_t)(trigger_info[2]);      // 触发值低字节
	
	uint32_t epoch_time_value = epoch_time; // 获取 epoch 时间戳
	systemlevel_body[systemlevelbody_len++] = (uint8_t)(epoch_time_value >> 24); // 高字节
	systemlevel_body[systemlevelbody_len++] = (uint8_t)(epoch_time_value >> 16); // 次高字节
	systemlevel_body[systemlevelbody_len++] = (uint8_t)(epoch_time_value >> 8);  // 次低字节
	systemlevel_body[systemlevelbody_len++] = (uint8_t)(epoch_time_value);       // 低字节
	memcpy(g_remote_databuffer + data_len, systemlevel_body, systemlevelbody_len);
  data_len += systemlevelbody_len;

    g_remote_databuffer[data_len] = Calculate_Checksum(g_remote_databuffer + 1, data_len - 1);
    data_len++;

    data_len = escape_7E((char *)g_remote_databuffer + 1, data_len - 1); 
    data_len++;

    g_remote_databuffer[data_len++] = 0x7E;
//		g_remote_databuffer[data_len++] = 0x7C;
//		g_remote_databuffer[data_len++] = '\r';
//		g_remote_databuffer[data_len++] = '\n';
//		printf("data_len %d\r\n",data_len);
		
		if (use_ascii_mode)
    {
        char ascii_payload[200] = {0};
        bin_to_hex_ascii(g_remote_databuffer, data_len, ascii_payload); // 48
        Send_WIFI_ASCII_Packet(ascii_payload);
//			Send_WIFI_ASCII_Packet_HEX(g_remote_databuffer, data_len);
    }
    else
    {
        Send_WIFI_HEX_Packet(g_remote_databuffer, data_len);
    }
}

void WIFI_Send_sensorline(uint8_t use_ascii_mode)
{
  Msg_Header header;
	uint16_t data_len = 0;
	
	memset(&header,0,sizeof(Msg_Header));
	header.id = 0x0009;
	memcpy(header.phone_number, g_board_id, 6);
	header.sequence = (sensorline_Serial_number<<8&0xFF00)|(sensorline_Serial_number>>8);
	sensorline_Serial_number++;
	header.attr.res = 0X00; // 存储高字节
	header.attr.length = 0x0A; // 存储低字节
	
	g_remote_databuffer[data_len++] = 0x7E;
	
	memcpy(g_remote_databuffer+data_len, &header, sizeof(Msg_Header));
	data_len += sizeof(Msg_Header);

	memcpy(g_remote_databuffer + data_len, sensor_status, 6);
  data_len += 6;
	
	uint32_t epoch_time_value = epoch_time; // 获取 epoch 时间戳
	g_remote_databuffer[data_len++] = (uint8_t)(epoch_time_value >> 24); // 高字节
	g_remote_databuffer[data_len++] = (uint8_t)(epoch_time_value >> 16); // 次高字节
	g_remote_databuffer[data_len++] = (uint8_t)(epoch_time_value >> 8);  // 次低字节
	g_remote_databuffer[data_len++] = (uint8_t)(epoch_time_value);       // 低字节

    g_remote_databuffer[data_len] = Calculate_Checksum(g_remote_databuffer + 1, data_len - 1);
    data_len++;

    data_len = escape_7E((char *)g_remote_databuffer + 1, data_len - 1); 
    data_len++;

    g_remote_databuffer[data_len++] = 0x7E;
//		g_remote_databuffer[data_len++] = 0x7C;
//		g_remote_databuffer[data_len++] = '\r';
//		g_remote_databuffer[data_len++] = '\n';
//		printf("data_len %d\r\n",data_len);
		
		if (use_ascii_mode)
    {
        char ascii_payload[200] = {0};
        bin_to_hex_ascii(g_remote_databuffer, data_len, ascii_payload);
        Send_WIFI_ASCII_Packet(ascii_payload);
//			Send_WIFI_ASCII_Packet_HEX(g_remote_databuffer, data_len);
    }
    else
    {
        Send_WIFI_HEX_Packet(g_remote_databuffer, data_len);
    }
}

void WIFI_Send_Temperature_Data(uint8_t use_ascii_mode,SensorDataBuffer* sensor_data)
{
		uint32_t tempbody_len = 0;
    uint16_t data_len = 0;
    Msg_Header header;
	
		temp_body[tempbody_len++] = 0xF0; // 温度数据的类型标识
		temp_body[tempbody_len++] = 0x0A; // 固定值
		
//		memcpy(&temp_body[tempbody_len], temp_cloud_send_buffer, 390);
//    tempbody_len += 390;  
		
	  for (uint8_t sensorId = 0; sensorId < MAX_TEMP_NODE_NUM; sensorId++) 
    {

			temp_body[tempbody_len++] = 0x00; // 固定值
			temp_body[tempbody_len++] = sensorId + 1; // 传感器编号从 1 开始
			memcpy(temp_body + tempbody_len, sensor_data->temp_data[sensorId], 12);
			tempbody_len += 12;

    }

		uint32_t epoch_time_value = epoch_time; // 获取 epoch 时间戳
		temp_body[tempbody_len++] = (uint8_t)(epoch_time_value >> 24); // 高字节
		temp_body[tempbody_len++] = (uint8_t)(epoch_time_value >> 16); // 次高字节
		temp_body[tempbody_len++] = (uint8_t)(epoch_time_value >> 8);  // 次低字节
		temp_body[tempbody_len++] = (uint8_t)(epoch_time_value);       // 低字节
		
    // 构造 header
    memset(&header, 0, sizeof(Msg_Header));
    header.id = 0x2602;
    memcpy(header.phone_number, g_board_id, 6);
    header.sequence = (Temperature_Serial_number << 8 & 0xFF00) | (Temperature_Serial_number >> 8);
    Temperature_Serial_number++;
//    header.attr.length = tempbody_len ;
		header.attr.res = (uint8_t)(tempbody_len >> 8); // 存储高字节
		header.attr.length = (uint8_t)(tempbody_len & 0xFF); // 存储低字节
	
    // 拼接完整数据
    g_remote_databuffer[data_len++] = 0x7E; // 开始符

    memcpy(g_remote_databuffer + data_len, &header, sizeof(Msg_Header));
    data_len += sizeof(Msg_Header);

    memcpy(g_remote_databuffer + data_len, temp_body, tempbody_len);
    data_len += tempbody_len;

    g_remote_databuffer[data_len] = Calculate_Checksum(g_remote_databuffer + 1, data_len - 1);
    data_len++;

    data_len = escape_7E((char *)g_remote_databuffer + 1, data_len - 1); 
    data_len++;

    g_remote_databuffer[data_len++] = 0x7E;
//		g_remote_databuffer[data_len++] = 0x7C;
//		g_remote_databuffer[data_len++] = '\r';
//		g_remote_databuffer[data_len++] = '\n';
//		printf("data_len %d\r\n",data_len);
		memcpy(flash_temp_prc0h2, g_remote_databuffer, 441);
		if (use_ascii_mode)
    {
        char ascii_payload[900] = {0};
        bin_to_hex_ascii(g_remote_databuffer, data_len, ascii_payload); // 884
        Send_WIFI_ASCII_Packet(ascii_payload);
//			Send_WIFI_ASCII_Packet_HEX(g_remote_databuffer, data_len);
    }
    else
    {
        Send_WIFI_HEX_Packet(g_remote_databuffer, data_len);
    }
}

void WIFI_Send_Pressure_CO_H2_Data(uint8_t use_ascii_mode, SensorDataBuffer* sensor_data) 
{
		uint8_t body_len = 0;
    uint16_t data_len = 0;
    Msg_Header header;

//		prc0h2_body[body_len++] = 0xF0; // 压力数据类型标识
//    prc0h2_body[body_len++] = 0x0C; // 固定值
		prc0h2_body[0] = 0xF0; // 压力数据类型标识
    prc0h2_body[1] = 0x0C; // 固定值
		body_len = 2;
    // 拼接压力数据
    for (uint8_t sensorId = 0; sensorId < MAX_PRESSURE_NODE_NUM; sensorId++) 
    {
//        if (sensor_data->pressure_valid[sensorId]) 
//        {
            
            prc0h2_body[body_len++] = 0x00; // 固定值
            prc0h2_body[body_len++] = sensorId + 1; // 传感器编号从 1 开始
            memcpy(prc0h2_body + body_len, sensor_data->pressure_data[sensorId], 2);
            body_len += 2;
//        }
    }

		prc0h2_body[body_len++] = 0xF0; // CO 数据类型标识
    prc0h2_body[body_len++] = 0x08; // 固定值
    // 拼接 CO 数据
    for (uint8_t sensorId = 0; sensorId < MAX_CO_NODE_NUM; sensorId++) 
    {
//        if (sensor_data->co_valid[sensorId]) 
//        {
            
            prc0h2_body[body_len++] = 0x00; // 固定值
            prc0h2_body[body_len++] = sensorId + 1; // 传感器编号从 1 开始
            memcpy(prc0h2_body + body_len, sensor_data->co_data[sensorId], 4);
            body_len += 4;
//        }
    }

		prc0h2_body[body_len++] = 0xF0; // H2 数据类型标识
    prc0h2_body[body_len++] = 0x06; // 固定值
    // 拼接 H2 数据
    for (uint8_t sensorId = 0; sensorId < MAX_H2_NODE_NUM; sensorId++) 
    {
//        if (sensor_data->h2_valid[sensorId]) 
//        {
            
            prc0h2_body[body_len++] = 0x00; // 固定值
            prc0h2_body[body_len++] = sensorId + 1; // 传感器编号从 1 开始
            memcpy(prc0h2_body + body_len, sensor_data->h2_data[sensorId], 4);
            body_len += 4;
//        }
    }
		prc0h2_body[body_len++] = 0xF0; // 电压数据类型标识
    prc0h2_body[body_len++] = 0x05; // 固定值
		prc0h2_body[body_len++] = voltage_int; // 电压
    prc0h2_body[body_len++] = percent; // 电量百分比
		
		uint32_t epoch_time_value = epoch_time; // 获取 epoch 时间戳
		prc0h2_body[body_len++] = (uint8_t)(epoch_time_value >> 24); // 高字节
		prc0h2_body[body_len++] = (uint8_t)(epoch_time_value >> 16); // 次高字节
		prc0h2_body[body_len++] = (uint8_t)(epoch_time_value >> 8);  // 次低字节
		prc0h2_body[body_len++] = (uint8_t)(epoch_time_value);       // 低字节

		// 构造 header
    memset(&header, 0, sizeof(Msg_Header));
    header.id = 0x2602;
    memcpy(header.phone_number, g_board_id, 6);
    header.sequence = (Pressure_CO_H2_Serial_number << 8 & 0xFF00) | (Pressure_CO_H2_Serial_number >> 8);
    Pressure_CO_H2_Serial_number++;
    header.attr.length = body_len;

    // 拼接完整数据
    g_remote_databuffer[data_len++] = 0x7E; // 开始符

    memcpy(g_remote_databuffer + data_len, &header, sizeof(Msg_Header));
    data_len += sizeof(Msg_Header);

    memcpy(g_remote_databuffer + data_len, prc0h2_body, body_len);
    data_len += body_len;

    g_remote_databuffer[data_len] = Calculate_Checksum(g_remote_databuffer + 1, data_len - 1);
    data_len++;

    data_len = escape_7E((char *)g_remote_databuffer + 1, data_len - 1); 
    data_len++;

    g_remote_databuffer[data_len++] = 0x7E;
//		g_remote_databuffer[data_len++] = 0x7C;
//		g_remote_databuffer[data_len++] = '\r';
//		g_remote_databuffer[data_len++] = '\n';
//		printf("data_len %d\r\n",data_len);

		// 从 g_remote_databuffer[13] 开始复制 64 字节到 flash_temp_prc0h2[441]
		memcpy(&flash_temp_prc0h2[441], &g_remote_databuffer[13], 64);
		if (use_ascii_mode)
    {
        char ascii_payload[200] = {0};
        bin_to_hex_ascii(g_remote_databuffer, data_len, ascii_payload); // 156
        Send_WIFI_ASCII_Packet(ascii_payload);
//			Send_WIFI_ASCII_Packet_HEX(g_remote_databuffer, data_len);
    }
    else
    {
        Send_WIFI_HEX_Packet(g_remote_databuffer, data_len);
    }
}

