1.设备属性上报
authord15521469561 <1731678236@qq.com>
Fri, 15 May 2026 01:23:08 +0000 (09:23 +0800)
committerd15521469561 <1731678236@qq.com>
Fri, 15 May 2026 01:23:08 +0000 (09:23 +0800)
2.topic整理
3.串口协议解析优化
4.mqtt逻辑优化
5.配网广播优化

main/ble.c
main/https_ota.c
main/project_common.c
main/project_common.h
main/uart.c
main/user_flash.c
main/user_flash.h
main/user_http.c
main/user_mqtt.c
main/user_mqtt.h
main/wifi.c

index 52146ba..d3ff797 100644 (file)
@@ -171,6 +171,7 @@ void Ble_Start_Nimble_NetWork(void)
                     if(common_storage.net_info.mqtt_url_len !=0)
                     {
                         #if ENABLE_WIFI_FUNC
+                        common_setting.ble_status.nimble_flag=1; //代表当前配网成功
                         Wifi_Queue_Send(0, 3, 0);
                         #endif
                         
@@ -197,14 +198,15 @@ void Ble_Enable_Status_Check(void)
     EventBits_t ble_bits = xEventGroupWaitBits(ble_event_group, BLE_ON_BIT | BLE_OFF_BIT, pdFALSE, pdFALSE, 0);
     if((ble_bits & BLE_ON_BIT) != 0)
     {
-        ESP_LOGI(BLE_TAG, "BLE_ON_BIT: %d", common_setting.ble_status.ble_state);
+        ESP_LOGI(BLE_TAG, "BLE_ON_BIT: %d", common_setting.ble_status.ble_adv_flag);
         xEventGroupClearBits(ble_event_group, BLE_ON_BIT);
-        if(common_setting.ble_status.ble_state == 0)//蓝牙开始广播并打开蓝牙开始配网
+        if(common_setting.ble_status.ble_adv_flag == 0)//蓝牙开始广播并打开蓝牙开始配网
         {
             // 开始配网
+            common_setting.ble_status.nimble_flag = 0; //清除配网成功标识
+            common_setting.ble_status.ble_adv_flag = 1;
             common_setting.ble_status.ble_state = 1;
             common_setting.ble_enable_tick = 0;
-            common_setting.ble_status.nimble_flag=1;
 
             common_setting.net_pairing_info.http_url_flag = 0;
             common_setting.net_pairing_info.http_token_flag = 0;
@@ -216,9 +218,9 @@ void Ble_Enable_Status_Check(void)
     }
     else if((ble_bits & BLE_OFF_BIT) != 0)
     {
-        ESP_LOGI(BLE_TAG, "stop_ble: %d", common_setting.ble_status.ble_state);
+        ESP_LOGI(BLE_TAG, "stop_ble: %d", common_setting.ble_status.ble_adv_flag);
         xEventGroupClearBits(ble_event_group, BLE_OFF_BIT);
-        if(common_setting.ble_status.ble_state > 0)
+        if(common_setting.ble_status.ble_adv_flag > 0) //关闭蓝牙广播
         {
             // 停止配网
             int ret = nimble_port_stop();
@@ -231,7 +233,7 @@ void Ble_Enable_Status_Check(void)
                 nimble_port_deinit();
                 common_setting.ble_status.ble_state = 0;
                 common_setting.ble_enable_tick = 0;
-                common_setting.ble_status.nimble_flag=0;
+                common_setting.ble_status.ble_adv_flag=0;
                 ESP_LOGI(BLE_TAG, "nimble_port_stop\n");
             }
             else
@@ -243,7 +245,7 @@ void Ble_Enable_Status_Check(void)
     }
 
     // 30分钟无配网动作则关闭蓝牙
-    if(common_setting.ble_status.ble_state > 0)
+    if(common_setting.ble_status.ble_adv_flag > 0)
     {
         common_setting.ble_enable_tick += MAIN_LOOP_INTERVAL;
         if(common_setting.ble_enable_tick > (30*60*1000))
index dd96a33..5eb2c4f 100644 (file)
@@ -251,7 +251,7 @@ uint8_t Https_Ota_Version_Check(void)
 }
 void Https_Ota_Start(void)
 {
-    if(g_ota_status != 0 && common_setting.https_ota_cfg.https_ota_start_flag == 1)
+    if(g_ota_status != 0 || common_setting.https_ota_cfg.https_ota_start_flag == 1)
     {
         ESP_LOGI(HTTPS_OTA, "ota is started\n");
         return;
index 77eb438..4f1848b 100644 (file)
@@ -1,5 +1,7 @@
 #include "project_common.h"
 #include "ble.h"
+#include "user_mqtt.h"
+#include "user_flash.h"
 static const char *COMMON_TAG = "COMMON";
 
 const FW_FILE_HEADER_T firmware_header = 
@@ -479,20 +481,20 @@ void Ble_Pairing_Handle(uint8_t *data ,uint16_t len, uint8_t host_type)
                     }
                     
                     common_setting.wifi_status.cur_ssid_len = wifi_ssid_len;
-                    memset(common_setting.wifi_status.cur_ssid,0,32);
+                    memset(common_setting.wifi_status.cur_ssid,0,sizeof(common_setting.wifi_status.cur_ssid));
                     memcpy(common_setting.wifi_status.cur_ssid, wifi_ssid, wifi_ssid_len);
                     common_setting.wifi_status.cur_ssid[wifi_ssid_len]='\0';
                     common_setting.wifi_status.cur_pwd_len = wifi_pwd_len;
-                    memset(common_setting.wifi_status.cur_pwd,0,64);
+                    memset(common_setting.wifi_status.cur_pwd,0,sizeof(common_setting.wifi_status.cur_pwd));
                     memcpy(common_setting.wifi_status.cur_pwd, wifi_pwd, wifi_pwd_len);
                     common_setting.wifi_status.cur_pwd[wifi_pwd_len]='\0';
                     ESP_LOGI(COMMON_TAG, "wifi ssid len: %d\n", wifi_ssid_len);
                     
-                    memset(common_storage.net_info.wifi_ssid,0,32);
+                    memset(common_storage.net_info.wifi_ssid,0,sizeof(common_storage.net_info.wifi_ssid));
                     common_storage.net_info.wifi_ssid_len=wifi_ssid_len;
                     memcpy(common_storage.net_info.wifi_ssid, wifi_ssid, wifi_ssid_len);
 
-                    memset(common_storage.net_info.wifi_pwd,0,64);
+                    memset(common_storage.net_info.wifi_pwd,0,sizeof(common_storage.net_info.wifi_pwd));
                     memcpy(common_storage.net_info.wifi_pwd, wifi_pwd, wifi_pwd_len);
                     common_storage.net_info.wifi_pwd_len=wifi_pwd_len;
 
@@ -800,7 +802,7 @@ void Ble_Pairing_Handle(uint8_t *data ,uint16_t len, uint8_t host_type)
                         uint16_t copy_len = (packet_bytes < (USER_ID_MAX_LEN - start_byte)) ? packet_bytes : (USER_ID_MAX_LEN - start_byte);
                         if(total_len > USER_ID_MAX_LEN)
                         {
-                            total_len=USER_ID_MAX_LEN;
+                            total_len = USER_ID_MAX_LEN;
                             // 类型错误
                             net_pairing_reply.content[5] |= 0x10;
                             ESP_LOGI(COMMON_TAG, "net pair info type err\n");
@@ -809,6 +811,9 @@ void Ble_Pairing_Handle(uint8_t *data ,uint16_t len, uint8_t host_type)
                         
                         memcpy(common_setting.net_pairing_info.user_id, &data[13], total_len);
                         common_setting.net_pairing_info.user_id[total_len]='\0';
+
+                        // memcpy(common_storage.net_info.user_id, &data[13], total_len);
+                        // common_storage.net_info.user_id[total_len]='\0';
                     
                         if(data[9] == 1)
                         {
@@ -896,7 +901,7 @@ void Ble_Pairing_Handle(uint8_t *data ,uint16_t len, uint8_t host_type)
                 if (len < 5) break;
                 if(data[4] == 1) // 开启蓝牙配网
                 {
-                    if(common_setting.ble_status.ble_state == 0){
+                    if(common_setting.ble_status.ble_adv_flag == 0){
                         xEventGroupSetBits(ble_event_group, BLE_ON_BIT);
                     }
                     
@@ -904,7 +909,9 @@ void Ble_Pairing_Handle(uint8_t *data ,uint16_t len, uint8_t host_type)
                 }
                 else if(data[4] == 0) // 关闭蓝牙配网
                 {
-                    xEventGroupSetBits(ble_event_group, BLE_OFF_BIT);
+                    if(common_setting.ble_status.ble_adv_flag == 1){
+                        xEventGroupSetBits(ble_event_group, BLE_OFF_BIT);
+                    }
                     ESP_LOGI(COMMON_TAG, "ble off by app\n");
                 }
             }
@@ -923,6 +930,19 @@ void Ble_Pairing_Handle(uint8_t *data ,uint16_t len, uint8_t host_type)
                 }
             }
             break;
+            //清除配网信息
+            case COMMON_BLE_CLEAR_NETWORK_INFOR_CMD: 
+            {
+                common_setting.ble_status.nimble_flag=0;
+                Wifi_Stop();
+                Mqtt_Disconnect();
+                User_Erase_NotReset();
+                if(common_setting.ble_status.ble_adv_flag == 0) //蓝牙广播关闭状态重新打开
+                {
+                    xEventGroupSetBits(ble_event_group, BLE_ON_BIT);
+                }
+            }
+            break;
             // 欺骗编译器,勿删
             case COMMON_BLE_END_CMD:
             {
index d260bc1..65205d7 100644 (file)
@@ -62,7 +62,7 @@
 
 // 最终对外版本
 #define FW_VERSION                             (FW_VERSION_B)          // 固件版本 //10.22         // 固件版本 //10.22         // 固件版本 //10.22         // 固件版本 //0A00 10.00 10.21
-#define BUILD_VERSION                  (0x0009)        // 编译测试版本
+#define BUILD_VERSION                  (0x000A)        // 编译测试版本
 #define DEVICE_VID                  (0x36E6)        // 设备厂商代码
 #define DEVICE_PID                  (0xEC01)        // 设备型号代码
 #define LWIP_LOCAL_HOSTNAME         "PXN-Device"    // WIFI本地主机名称
 #define ESP_WIFI_SCAN_AUTH_MODE_THRESHOLD WIFI_AUTH_WAPI_PSK
 #endif
 
+#define ENABLE_CHECK_BLE_STATUS  0
 
 //是否需要同步sntp网络时间
 #define ENABLE_SYNC_SNTP_TIME       0
@@ -134,7 +135,7 @@ typedef enum
     COMMON_BLE_NETWORK_AUTHENT_CMD = 0x16, //network authentication 
 
 
-
+    COMMON_BLE_CLEAR_NETWORK_INFOR_CMD = 0x17, //clear network infor;
 
 
 
@@ -207,6 +208,7 @@ typedef union
 }__attribute__((packed)) SSL_CERT_T;
 
 #define HTTP_TOKEN_MAX   255
+#define USER_ID_MAX_LEN 20
 typedef union
 {
     struct
@@ -231,6 +233,7 @@ typedef union
         uint8_t user_id_flag;
         uint8_t http_token_str[HTTP_TOKEN_MAX-1];
 
+        char user_id[USER_ID_MAX_LEN+1];
 
     };
 }__attribute__((packed)) NET_INFO_T;
@@ -271,8 +274,9 @@ typedef struct
 
 typedef struct
 {
-    uint8_t ble_state; // 0:关闭   1:广播   2:已连接
-    uint8_t nimble_flag;//1打开配网 0关闭配网
+    uint8_t ble_state;  // 0:蓝牙断开   1:连接中 2:连接成功
+    uint8_t nimble_flag; // 0:配网失败 1: 配网成功
+    uint8_t ble_adv_flag; //1:开启广播 0: 关闭广播
 }__attribute__((packed)) BLE_STATUS_T;
 
 typedef struct
@@ -347,8 +351,9 @@ typedef struct
 {
     uint8_t heart_beat_enable:1;
     uint8_t mcu_info_got_flag:1;
-    uint8_t mcu_platform_mode;
-    uint8_t reserved:6;
+    uint8_t mcu_platform_mode:1;
+    uint8_t clear_network_info:1;
+    uint8_t reserved:4;
     
     // UNIVERSAL
     uint32_t heart_beat_interval; // ms
index f61c300..0894e26 100644 (file)
@@ -53,6 +53,92 @@ void Uart_Tx_Queue_Process(void)
         // ESP_LOG_BUFFER_HEX(UART_TAG, uart_tx_data.buffer, uart_tx_data.size);
     }
 }
+#define  RX_CACHE_MAX_LEN  256
+//uart接收数据
+
+static uint8_t  rx_cache[RX_CACHE_MAX_LEN] = {0};
+static uint32_t rx_cache_len = 0;
+static uint8_t  rx_timeout_cnt = 0;
+// =====================  =====================
+#if 0
+
+void Uart_Rx_Queue_Process(void)
+{
+    static UART_RECV_DATA_T uart_rx_tmp_struct = {0};
+
+    // 1. 从队列取一包数据
+    if(xQueueReceive(uart_rx_queue_handle, &uart_rx_tmp_struct, 0) == pdTRUE)
+    {
+        // 拼包:把新收到的数据追加到缓存
+        if (rx_cache_len + uart_rx_tmp_struct.size < RX_CACHE_MAX_LEN)
+        {
+            memcpy(&rx_cache[rx_cache_len], uart_rx_tmp_struct.buffer, uart_rx_tmp_struct.size);
+            rx_cache_len += uart_rx_tmp_struct.size;
+            rx_timeout_cnt=2;
+        }
+    }
+    if(rx_timeout_cnt > 0)
+    {
+        rx_timeout_cnt--;
+        if(rx_timeout_cnt == 0 && rx_cache_len > 0)
+        {
+            uint16_t uart_buf_offset = 0;
+            while(uart_buf_offset < rx_cache_len)
+            {
+                
+                // ESP_LOGI(COMMON_TAG, "uart_buf_offset recv2 %d %d",uart_buf_offset,uart_rx_size);
+                if(rx_cache[uart_buf_offset] == FRAMEHEAD_PANEL_TO_IOT)
+                {
+                    //uart_rx_data[uart_buf_offset+1] //data
+                    //uart_rx_data[uart_buf_offset+2] len
+                    //uart_rx_data[uart_buf_offset]+2-1) crc
+                    // Crc8_ROHC_Cal(&data[1], len-2) == data[len-1]
+                    if(uart_buf_offset+4 > rx_cache_len || rx_cache_len < 4) 
+                    {
+                        break;
+                    }
+                    uint8_t len = rx_cache[uart_buf_offset+2];//长度字段
+                    //f2 00 00 c2 f2 00 01 0f c2
+                    //f2 00 01 0f c2
+                    uint16_t full_len = 1+1+1+len+1;//header+cmd+len类型+实际数据的长度+crc 无论len是否为0 full_len一定要大于4
+                    if(len == 0)
+                    {
+                        full_len = 1+1+1+1;//header+cmd+len类型+crc
+                    }else{
+                        full_len = 1+1+1+len+1;//header+cmd+len类型+实际数据的长度+crc
+                    }
+                    if(uart_buf_offset + full_len > UART_BUF_SIZE)//254+4 > 256 //防止溢出
+                    {
+                        break;
+                    }
+                    // ESP_LOGI(COMMON_TAG, "uart_buf_offset recv3 %d %d",uart_buf_offset,uart_rx_size);
+                    //if(crcr8(data,len) == crc)
+                    //f2 00 00 00 crc uart_buf_offset=0
+                    //f2 00 01 0f c2
+                    
+                    uint8_t crc_cal = Crc8_ROHC_Cal(&rx_cache[uart_buf_offset + 1],len+2);//00 cmd+len类型
+                    uint8_t crc_pkt = rx_cache[uart_buf_offset + full_len-1];//1+1+2=4
+                    if(crc_cal == crc_pkt)
+                    {
+                        // ESP_LOGI(COMMON_TAG, "uart_buf_offset recv5 %d %d",uart_buf_offset,uart_rx_size);
+                        Uart_Pairing_Handle(&rx_cache[uart_buf_offset],full_len, HOST_TYPE_UART);
+
+                    }
+                    //header+cmd+len+crc
+                    uart_buf_offset=uart_buf_offset+full_len;
+                }
+                else
+                {
+                    uart_buf_offset++;
+                }
+            }
+            rx_cache_len=0;
+        }
+    }
+
+
+}
+#else
 void Uart_Rx_Queue_Process(void)
 {
     static UART_RECV_DATA_T uart_rx_tmp_struct = {0};
@@ -121,42 +207,91 @@ void Uart_Rx_Queue_Process(void)
 
 
 
+}
+
+// 直接解析完整帧
+void Uart_Recv_Handle(uint8_t *data, uint16_t len)
+{
+    uint16_t offset = 0;
+    while (offset < len)
+    {
+        if (data[offset] != FRAMEHEAD_PANEL_TO_IOT)
+        {
+            offset++;
+            continue;
+        }
+
+        if (offset + 4 > len) break;
+
+        uint8_t  plen     = data[offset+2];
+        uint16_t full_len = 1+1+1+plen+1;
+
+        if (full_len > len - offset) break;
 
+        uint8_t crc = Crc8_ROHC_Cal(&data[offset+1], plen+2);
+        if (crc == data[offset + full_len -1])
+        {
+            // 这里一定是完整帧!
+            Uart_Pairing_Handle(&data[offset], full_len, HOST_TYPE_UART);
+        }
+
+        offset += full_len;
+    }
 }
+#endif
+
+
 void Uart_Task(void *arg)
 {
     esp_log_level_set(UART_TAG, ESP_LOG_INFO);
     memset(uart_rx_data, 0x00, sizeof(uart_rx_data));
     static UART_RECV_DATA_T uart_rx_data_struct = {0};
-
     while (1)
     {
-        const int uart_rx_size = uart_read_bytes(UART_NUM_1, uart_rx_data_struct.buffer, UART_BUF_SIZE, 1 / portTICK_PERIOD_MS);
+        static uint8_t read_buf[256]={0};
+        const int uart_rx_size = uart_read_bytes(UART_NUM_1, read_buf, UART_BUF_SIZE,0);//2/ portTICK_PERIOD_MS);
         if (uart_rx_size > 0)
         {
-            // ESP_LOGI(UART_TAG, "Received %d bytes: ", uart_rx_size);
-            // ESP_LOG_BUFFER_HEX(UART_TAG, uart_rx_data, uart_rx_size);
+            // ESP_LOGI(UART_TAG, "Received %d bytes: %d\n", uart_rx_size,rx_timeout_cnt);
             uart_rx_data_struct.size = uart_rx_size;
-            if(uart_rx_queue_handle){
-                xQueueSend(uart_rx_queue_handle, &uart_rx_data_struct, 0);
+            // Uart_Recv_Handle(uart_rx_data_struct.buffer,uart_rx_size);
+            if (rx_cache_len + uart_rx_size < RX_CACHE_MAX_LEN)
+            {
+                memcpy(&rx_cache[rx_cache_len], read_buf, uart_rx_size);
+                rx_cache_len += uart_rx_size;
+                rx_timeout_cnt = 2;
+               
+            }
+           
+        }
+        if(rx_timeout_cnt > 0)
+        {
+            rx_timeout_cnt--;
+            if(rx_timeout_cnt == 0 && rx_cache_len > 0)
+            {
+                // if(uart_rx_queue_handle){
+                //     xQueueSend(uart_rx_queue_handle, &uart_rx_data_struct, 0);
+                // }
+                Uart_Recv_Handle(rx_cache,rx_cache_len);
+                rx_cache_len=0;
+                memset(rx_cache,0x00,sizeof(rx_cache));
             }
-                
         }
-        
         Uart_Tx_Queue_Process();
        
         Uart_Rx_Queue_Process();
-        vTaskDelay(1 / portTICK_PERIOD_MS);
+        vTaskDelay(1/ portTICK_PERIOD_MS);
     }
 }
 void Uart_Pairing_Handle(uint8_t *data ,uint16_t len, uint8_t host_type)
 {
-    // ESP_LOG_BUFFER_HEX(COMMON_TAG,data,len);
+    // 
     //串口-ESP PROTUCOL协议指令解析
     if(len >= 4 && len <= UART_BUF_SIZE && data[0] == FRAMEHEAD_PANEL_TO_IOT && Crc8_ROHC_Cal(&data[1], len-2) == data[len-1] && host_type == HOST_TYPE_UART)
     {
         if(data[1] != 0xb7)
         {
+            // ESP_LOG_BUFFER_HEX(COMMON_TAG,data,len);
             ESP_LOGI(COMMON_TAG, "uart recv %d bytes:cmd %0x", len, data[1]);
         }
         // ESP_LOGI(COMMON_TAG, "Read %d bytes:", len);
@@ -283,10 +418,17 @@ void Uart_Pairing_Handle(uint8_t *data ,uint16_t len, uint8_t host_type)
             break;
             
             // 属性上报
+            //F2 07 30 4F 01 05 07 00 23 46 46 30 30 30 30 50 01 05 07 00 23 34 36 43 33 44 43 50 01 05 07 00 23 34 36 43 33 44 43 51 01 05 07 00 23 46 41 35 35 30 30 0C 
             case COMMON_UART_PROPERTY_REPORT_CMD:
             {
-                // mqtt_upload_len = data[2];
-                // memcpy(mqtt_upload_data, &data[3], data[2]);
+                // cmd = data[1];
+                // len = data[2];
+                // data = data[3];
+                
+                uart_send_iot_data(data[1],&data[3],data[2]);
+                
+                
+
             }
             break;
 
@@ -355,8 +497,7 @@ void Uart_Pairing_Handle(uint8_t *data ,uint16_t len, uint8_t host_type)
             {
                 //通过mqtt发送给上位机
                 #if ENABLE_MQTT_FUNC
-                ESP_LOG_BUFFER_HEX(COMMON_TAG, data, len);
-                Mqtt_Get_Key_Led_Color(data+3,data[2]-1);//从第三个字节开始 不包含crc和之前的协议字段
+                
                 #endif
             }
             break;
index 3fabb25..3e6fe8d 100644 (file)
@@ -101,6 +101,51 @@ void User_Erase_Nimble_NetWork_Infor(void)
        User_Flash_Erase(UF_OFFSET_CERT_CLIENT_KEY_ADDR,FLASH_SEC_SIZE);
        User_Flash_Erase(UF_OFFSET_CERT_SERVER_CRT_ADDR,FLASH_SEC_SIZE);
 }
+
+//清除信息不需要重启设备
+void User_Erase_NotReset(void)
+{
+       ESP_LOGI(FLASH_TAG,"User_Erase_NotReset");
+       //清除信息
+       User_Erase_Nimble_NetWork_Infor();
+       //read wifi 信息
+       User_Flash_Check();
+
+       memset(common_setting.wifi_status.cur_ssid,0,sizeof(common_setting.wifi_status.cur_ssid));
+       common_setting.wifi_status.cur_ssid_len = 0;
+       memset(common_setting.wifi_status.cur_pwd,0,sizeof(common_setting.wifi_status.cur_pwd));
+       common_setting.wifi_status.cur_pwd_len = 0;
+
+       memset(common_storage.net_info.wifi_ssid,0,sizeof(common_storage.net_info.wifi_ssid));
+       common_storage.net_info.wifi_ssid_len=0;
+       memset(common_storage.net_info.wifi_pwd,0,sizeof(common_storage.net_info.wifi_pwd));
+       common_storage.net_info.wifi_pwd_len=0;
+
+       common_storage.net_info.wifi_info_flag=0;
+
+       memset(common_setting.net_pairing_info.http_url, 0x00,sizeof(common_setting.net_pairing_info.http_url));
+       common_setting.net_pairing_info.http_url_length = 0;
+    common_setting.net_pairing_info.http_url_flag = 0;
+
+       memset(common_setting.net_pairing_info.http_token, 0x00,sizeof(common_setting.net_pairing_info.http_token));
+       common_setting.net_pairing_info.http_token_length = 0;
+    common_setting.net_pairing_info.http_token_flag = 0;
+
+
+       memset(common_setting.net_pairing_info.user_id, 0x00,sizeof(common_setting.net_pairing_info.user_id));
+       common_setting.net_pairing_info.user_id_flag = 0;
+    common_storage.net_info.user_id_flag =0;
+
+       memset(common_setting.net_pairing_info.mqtt_sub_url, 0x00, sizeof(common_setting.net_pairing_info.mqtt_sub_url));
+       common_setting.net_pairing_info.mqtt_sub_url_length = 0;
+    common_setting.net_pairing_info.mqtt_sub_url_flag = 0;
+
+       memset(common_setting.net_pairing_info.serial_number, 0x00, sizeof(common_setting.net_pairing_info.serial_number));
+       common_setting.net_pairing_info.serial_number_length = 0;
+       common_setting.net_pairing_info.serial_number_flag = 0;
+       
+       
+}
 esp_err_t User_Flash_Erase(size_t offset, size_t size)
 {      
        esp_err_t err = 0;
index 53c4aa0..5102148 100644 (file)
@@ -34,4 +34,5 @@ void User_Erase_Nimble_NetWork_Infor(void);
 esp_err_t User_Flash_Write_With_Flag(uint32_t addr, uint32_t flag, void* data, uint16_t size);
 esp_err_t User_Flash_Read_Check(uint32_t addr, uint32_t flag, void* buf, uint16_t size);
 esp_err_t User_Flash_Erase(size_t offset, size_t size);
+void User_Erase_NotReset(void);
 #endif
index 906da09..882ee8e 100644 (file)
@@ -49,7 +49,7 @@ static esp_err_t _http_event_handler(esp_http_client_event_t *evt)
 static char http_download_cache[MAX_HTTP_OUTPUT_BUFFER+1] = {0};
 #define HTTP_DOWNLOAD_CER_FUNC_ENABLE 1
 
-#define HTTP_RETRY_NUMBER_MAX (5) //HTTP请求失败重试次数最大值
+#define HTTP_RETRY_NUMBER_MAX (3) //HTTP请求失败重试次数最大值
 
 #define HTTP_GET_MQTT_URL_CER_ENABLE 1 //设备请求下发mqtt地址 证书
 
@@ -65,9 +65,34 @@ esp_ota_handle_t s_ota_handle = 0;
 
 static void Http_Download_Task_Cb(void *pvParameters)
 {
+    #if ENABLE_CHECK_BLE_STATUS
+    if(common_setting.ble_status.ble_state == 0)
+    {    
+        User_Erase_NotReset();//清除配网信息
+        vTaskDelete(NULL);
+    }
+    #endif
+    if(common_setting.net_pairing_info.http_url_flag == 0 || common_setting.net_pairing_info.http_token_flag == 0 || common_setting.net_pairing_info.serial_number_flag == 0)
+    {
+        User_Erase_NotReset();//清除配网信息
+        vTaskDelete(NULL);
+    }
     uint8_t success_bit = 0;
+    uint8_t ret = 0;
     for(uint8_t cert_type=0;cert_type<3;cert_type++)
     {
+        ret=0;
+        if(common_setting.net_pairing_info.http_url_flag == 0 || common_setting.net_pairing_info.http_token_flag == 0 || common_setting.net_pairing_info.serial_number_flag == 0)
+        {
+            
+            break;
+        }
+        #if ENABLE_CHECK_BLE_STATUS
+        if(common_setting.ble_status.ble_state == 0)
+        {    
+            break;
+        }
+        #endif
         if(http_get_cert_task_param.url[cert_type][strlen(&http_get_cert_task_param.url[cert_type][0])-1] == ' ')
         {
             http_get_cert_task_param.url[cert_type][strlen(&http_get_cert_task_param.url[cert_type][0])-1] = 0;
@@ -88,6 +113,19 @@ static void Http_Download_Task_Cb(void *pvParameters)
         esp_http_client_handle_t http_client = NULL; // 提前定义
         for(uint8_t retry=0;retry<HTTP_RETRY_NUMBER_MAX;retry++)
         {
+            if(common_setting.net_pairing_info.http_url_flag == 0 || common_setting.net_pairing_info.http_token_flag == 0 || common_setting.net_pairing_info.serial_number_flag == 0)
+            {
+                err = ESP_FAIL;
+                break;
+            }
+            #if ENABLE_CHECK_BLE_STATUS
+            if(common_setting.ble_status.ble_state == 0)
+            {    
+                err = ESP_FAIL;
+                break;
+                
+            }
+            #endif
             ESP_LOGI(HTTP_DOWNLOAD_TASK_TAG, "get cer on: %" PRIu32 " bytes", esp_get_free_heap_size());
             // printf("剩余堆内存: %" PRIu32, esp_get_free_heap_size());
             http_client = esp_http_client_init(&http_config);
@@ -193,26 +231,45 @@ static void Http_Download_Task_Cb(void *pvParameters)
         }
         vTaskDelay(50 / portTICK_PERIOD_MS);
     }
-
-
+    if(common_setting.net_pairing_info.http_url_flag == 0 || common_setting.net_pairing_info.http_token_flag == 0 || common_setting.net_pairing_info.serial_number_flag == 0)
+    {
+        User_Erase_NotReset();//清除配网信息
+        vTaskDelete(NULL);
+    }
+    #if ENABLE_CHECK_BLE_STATUS
+    if(common_setting.ble_status.ble_state == 0)
+    {    
+        
+        User_Erase_NotReset();//清除配网信息
+        vTaskDelete(NULL);
+    }
+    #endif
     if(success_bit == ((1 << SSL_CLIENT_CRT) | (1 << SSL_CLIENT_KEY) | (1 << SSL_SERVER_CRT)))
     {
-        //成功
-        // Ble_Queue_Send(0xFF, 0xFF);
         #if (USER_TEST_ENABLE) //开机直连测试使用
         common_storage.net_info.serial_number_flag = 1;
         common_storage.net_info.wifi_info_flag = 1;
         #endif
         #if (NIMBLE_NETWORK_MODE)
         //回复配网状态
+        #if ENABLE_CHECK_BLE_STATUS
+        
+        //请求服务器做绑定动作 在当前线程请求绑定接口
+        #else
+        // common_setting.net_pairing_info.http_url_flag=0;
+        // common_setting.net_pairing_info.http_token_flag = 0;
+        // common_setting.net_pairing_info.user_id_flag = 0;
         network_request_replay(NETWORK_HTTPS_DOWNLOAD_CERTIFICATE_OK);
         vTaskDelay(200);
         xEventGroupSetBits(ble_event_group, BLE_OFF_BIT);//关闭蓝牙配网
         vTaskDelay(100);
-        #endif
         ESP_LOGI(HTTP_TAG, "download mqtt \n");
-        common_setting.mqtt_user_cfg.mqtt_start_flag=1;
+        common_setting.ble_status.nimble_flag=1;
         xEventGroupSetBits(common_event_group, COMMON_MQTT_CONNECT_BIT);
+        #endif
+       
+        #endif
+       
     }else{
         //失败
         network_request_replay(NETWORK_HTTPS_DOWNLOAD_CERTIFICATE_FAILED);
@@ -234,8 +291,6 @@ static void Http_Get_Url_Task_Cb(void *pvParameters)
     {
         ESP_LOGI(HTTP_TAG, "param wrong:%d %d %d %d %d %d\n", common_setting.net_pairing_info.http_url_flag, common_setting.net_pairing_info.http_token_flag, common_setting.net_pairing_info.user_id_flag, common_setting.mcu_info_got_flag, common_setting.net_pairing_info.http_url_length, common_setting.net_pairing_info.http_token_length);
         vTaskDelete(NULL);
-        
-        return;
     }
     //
     uint8_t result = 0;
@@ -262,7 +317,11 @@ static void Http_Get_Url_Task_Cb(void *pvParameters)
     {
         result = 0;
         
+        #if ENABLE_CHECK_BLE_STATUS
+        if(common_setting.net_pairing_info.http_url_flag == 0 || common_setting.net_pairing_info.http_token_flag == 0 || common_setting.ble_status.ble_state == 0)
+        #else
         if(common_setting.net_pairing_info.http_url_flag == 0 || common_setting.net_pairing_info.http_token_flag == 0)
+        #endif
         {
             result = 3;
             break;
@@ -438,13 +497,14 @@ static void Http_Get_Url_Task_Cb(void *pvParameters)
         // ESP_LOGI(HTTP_TAG, "\nHTTP STEP 1.......GET serialNumber=deviceID............%d\n", result);
         ESP_LOGI(HTTP_TAG, "\nH.GET serialNumber=deviceID..%d %" PRIu32 " bytes",result,esp_get_free_heap_size());
         network_request_replay(NETWORK_HTTPS_GET_SERIALNUMBER_FAILED);
-        vTaskDelay(1000);
+        vTaskDelay(500);
+        User_Erase_NotReset();//清除配网信息
         vTaskDelete(NULL);
         return;
     }
     #endif
     network_request_replay(NETWORK_HTTPS_GET_SERIALNUMBER_OK);
-    vTaskDelay(1000);
+    vTaskDelay(500);
     //put
     //report token  mac rssi
     #if HTTP_PUT_REPORT_MAC_RSSI_ENABLE
@@ -461,6 +521,17 @@ static void Http_Get_Url_Task_Cb(void *pvParameters)
     for(uint8_t retry=0;retry<HTTP_RETRY_NUMBER_MAX;retry++)
     {
         result = 0;
+        
+        #if ENABLE_CHECK_BLE_STATUS
+        if(common_setting.net_pairing_info.http_url_flag == 0 || common_setting.net_pairing_info.http_token_flag == 0 || common_setting.ble_status.ble_state == 0)
+        #else
+        if(common_setting.net_pairing_info.http_url_flag == 0 || common_setting.net_pairing_info.http_token_flag == 0 || common_setting.net_pairing_info.serial_number_flag == 0)
+        #endif
+        {
+            result = 3;
+            break;
+        }
+        
         http_client=NULL;
         char url[HTTP_REQUEST_RUL_LEN] = {0};
         const char path[] = "/iot/device/";
@@ -558,7 +629,7 @@ static void Http_Get_Url_Task_Cb(void *pvParameters)
         if(result == 1)
         {
             network_request_replay(NETWORK_HTTPS_PUT_DEVICE_INFO_OK);
-            vTaskDelay(1000);
+            vTaskDelay(500);
             break;
         }
         vTaskDelay(50);
@@ -571,7 +642,8 @@ static void Http_Get_Url_Task_Cb(void *pvParameters)
         ESP_LOGI(HTTP_TAG, "\nPUT...%d %" PRIu32 " bytes",result,esp_get_free_heap_size());
         
         network_request_replay(NETWORK_HTTPS_PUT_DEVICE_INFO_FAILED);
-        vTaskDelay(1000);
+        vTaskDelay(500);
+        User_Erase_NotReset();//清除配网信息
         vTaskDelete(NULL);
         return;
     }
@@ -584,11 +656,20 @@ static void Http_Get_Url_Task_Cb(void *pvParameters)
     {
         result = 0;
         http_client = NULL;
+        #if ENABLE_CHECK_BLE_STATUS
+        if(common_setting.net_pairing_info.http_url_flag == 0 || common_setting.net_pairing_info.http_token_flag == 0 || \
+            common_setting.net_pairing_info.serial_number_flag == 0 || common_setting.ble_status.ble_state == 0)
+        {
+            result = 3;
+            break;
+        }
+        #else
         if(common_setting.net_pairing_info.http_url_flag == 0 || common_setting.net_pairing_info.http_token_flag == 0 || common_setting.net_pairing_info.serial_number_flag == 0)
         {
             result = 3;
             break;
         }
+        #endif
         
         char url[HTTP_REQUEST_RUL_LEN] = {0};
         const char path[] = "/iot/device/getDeviceBySerialNumber/";
@@ -761,13 +842,12 @@ static void Http_Get_Url_Task_Cb(void *pvParameters)
             esp_http_client_cleanup(http_client);
             http_client=NULL;
         }
-        
 
         // 结果
         if(result == 1)
         {
             network_request_replay(NETWORK_HTTPS_GET_CER_URL_OK);
-            vTaskDelay(1000);
+            vTaskDelay(500);
             break;
         }
         vTaskDelay(50);
@@ -779,13 +859,20 @@ static void Http_Get_Url_Task_Cb(void *pvParameters)
         // ESP_LOGI(HTTP_TAG, "HTTP_TAG1 memory head size: %" PRIu32 " bytes", esp_get_free_heap_size());
         //GET 配置配网服务器下发成功 下发证书 mqtt地址
         network_request_replay(NETWORK_HTTPS_GET_CER_URL_FAILED);
-        vTaskDelay(1000);
+        vTaskDelay(500);
+        User_Erase_NotReset();//清除配网信息
         vTaskDelete(NULL);
         return;
     }
     #endif
 
-    
+    #if ENABLE_CHECK_BLE_STATUS
+    if(common_setting.ble_status.ble_state == 0)
+    {
+        User_Erase_NotReset();//清除配网信息
+        vTaskDelete(NULL);
+    }
+    #endif
     if(pClientCrt != NULL && pClientkey != NULL && pServerCrt != NULL && pMqttSubUrl != NULL && result == 1)
     {
         result = 0;
index 318a90f..9ed16d3 100644 (file)
@@ -9,20 +9,29 @@ static const char *MQTT_TAG = "MQTT";
 #define REPLY_STATUS_OK 1
 #define REPLY_STATUS_FAIL 0
 // 发送队列静态内存
-uint8_t  mqtt_send_queue_storage[MQTT_SEND_QUEUE_LENGTH * sizeof(mqtt_send_msg_t)];
-QueueHandle_t mqtt_send_queue_handle=NULL;
-StaticQueue_t mqtt_send_queue_buffer;
+uint8_t  mqtt_dev_report_queue_storage[MQTT_SEND_QUEUE_LENGTH * sizeof(mqtt_dev_report_msg_t)];
+QueueHandle_t mqtt_dev_report_queue_handle=NULL;
+StaticQueue_t mqtt_dev_report_queue_buffer;
 
 uint8_t mqtt_recv_queue_storage[MQTT_RECV_QUEUE_LENGTH * sizeof(mqtt_recv_msg_t)];
 QueueHandle_t mqtt_recv_queue_handle=NULL;
 StaticQueue_t mqtt_recv_queue_buffer;
 static uint8_t retry_connect_cnt = 0;
 
-// MQTT_LOOP
+// MQTT 任务
 TaskHandle_t mqtt_connect_task_handler;
 StackType_t mqtt_connect_task_stack[MQTT_CONNECT_TASK_STACK];
 StaticTask_t mqtt_connect_task_tcb;
 
+mqtt_pulish_data_t publish_data;
+
+//多任务安全标识
+static uint8_t mqtt_init_task_flag = 0;
+static uint8_t mqtt_send_data_count = 0;
+static uint8_t mqtt_init_flag = 0;
+static char topic_str[64] = {0};
+static char topic_compare[65]={0}; //最新的服务下发的topic 设备根据这个做topic区分数据上报
+static char cloud_msgID[64]="cloud_0196415f3b1f7e2ab7f72c4e8f91c0a2";  //应答需要用云端下发的msgID
 
 static void log_error_if_nonzero(const char *message, int error_code)
 {
@@ -42,10 +51,65 @@ static void log_error_if_nonzero(const char *message, int error_code)
  * @param event_data The data for the event, esp_mqtt_event_handle_t.
  */
 
-static uint8_t mqtt_init_task_flag = 0;
-static uint8_t mqtt_send_data_count = 0;
-static uint8_t mqtt_init_flag = 0;
-static char topic_str[64]={0};
+
+// 通用:根据场景生成发布 Topic
+const char* get_publish_topic(TOPIC_TYPE type)
+{
+    // 
+    static char pub_topic[64] = {0};
+    memset(pub_topic, 0, sizeof(pub_topic));
+
+    const char *suffix = NULL;
+    switch (type) {
+        case TOPIC_PROPERTY_POST:   suffix = "/property/post" ;     break; //云端
+        case TOPIC_PROPERTY_REPLY:   suffix = "/property/reply";    break; //设备
+        case TOPIC_PROPERTY_REPORT:  suffix = "/property/report";   break; //设备
+        case TOPIC_SERVICE_POST:     suffix = "/service/post";      break; //云端
+        case TOPIC_SERVICE_REPLY:    suffix = "/service/reply";     break; //设备
+
+        default: return NULL;
+    }
+
+    snprintf(pub_topic, sizeof(pub_topic)-1, "topic/%s/%04X%s",
+        (char *)common_storage.net_info.serial_number,
+        common_setting.mcu_info.pid,
+        suffix);
+    return pub_topic;
+}
+
+const char *service_property_set="thing.service.property.set";
+const char *property_set_replay="thing.service.property.set.reply";
+const char *property_post = "thing.event.property.post";
+const char *service_invoke = "thing.service.calibration.invoke";
+const char *dev_invoke_replay = "thing.service.calibration.invoke.reply";
+//获取方式请求mode
+const char *get_methon(uint8_t methon_mode)
+{
+    switch (methon_mode)
+    {
+        //设备属性设置应答和服务属性下发设置
+        case METHON_SERVICE_PROPERTY_SET:
+            return service_property_set;
+
+        case METHON_SERVICE_PROPERTY_SET_REPLAY:
+            return property_set_replay;
+        
+        //设备事件主动上报methon
+        case METHON_EVENT_PROPERTY_POST:
+            return property_post;
+
+        //服务事件下发和设备事件应答服务
+        case METHON_SERVICE_CALIBRATION_INVOKE:
+            return service_invoke;
+        case METHON_SERVICE_CALIBRATION_INVOKE_REPLAY:
+            return dev_invoke_replay;
+        
+
+        default:
+            return "";
+    }
+
+}
 #define MQTT_USER_DEFAULT_TOPIC     0
 static void mqtt_event_handler(void *handler_args, esp_event_base_t base, int32_t event_id, void *event_data)
 {
@@ -65,16 +129,22 @@ static void mqtt_event_handler(void *handler_args, esp_event_base_t base, int32_
         snprintf(topic_str,sizeof(topic_str),"%s",MQTT_TOPIC);
         msg_id = esp_mqtt_client_subscribe(mqtt_client, topic_str, 0);
         #else
-        snprintf(topic_str,sizeof(topic_str),"topic/%s/%04X/property/post",(char *)common_storage.net_info.serial_number,common_setting.mcu_info.pid);
-        msg_id = esp_mqtt_client_subscribe(mqtt_client, topic_str, 0);
+        // snprintf(topic_str,sizeof(topic_str),"topic/%s/%04X/property/post",(char *)common_storage.net_info.serial_number,common_setting.mcu_info.pid);
+        
+        // msg_id = esp_mqtt_client_subscribe(mqtt_client, get_publish_topic(TOPIC_PROPERTY_REPLY), 1);
+        // ESP_LOGI(MQTT_TAG, "订阅属性下发: msg_id=%d topic=%s", msg_id, sub_topic[0]);
+        
+        
+        msg_id = esp_mqtt_client_subscribe(mqtt_client,get_publish_topic(TOPIC_PROPERTY_POST), 0);
+
+
         #endif
-        ESP_LOGI(MQTT_TAG, "send subscribe msg_id=%d topic_str=%s", msg_id,topic_str);
+        ESP_LOGI(MQTT_TAG, "send subscribe msg_id=%d get_publish_topic(TOPIC_PROPERTY_POST)=%s", msg_id,get_publish_topic(TOPIC_PROPERTY_POST));
         break;
     case MQTT_EVENT_DISCONNECTED:
         common_setting.mqtt_user_cfg.mqtt_connect_flag = 0;
         common_setting.mqtt_user_cfg.mqtt_sub_flag = 0;
         Mqtt_Send_Connect_Status();
-        // xEventGroupSetBits(common_event_group, COMMON_MQTT_DISCONNECT_BIT);//
         ESP_LOGI(MQTT_TAG, "MQTT_EVENT_DISCONNECTED");
         break;
 
@@ -125,12 +195,8 @@ void Mqtt_Send_Connect_Status(void)//包含心跳
 {
     uint8_t heart_beat_data[2] = {0};//数据
     heart_beat_data[0]=COMMON_MQTT_STATUS;//状态类型
-    if(Mqtt_Get_Connect_Flag())
-    {
-        heart_beat_data[1]=0x01;//mqtt连接状态
-    }else{
-        heart_beat_data[1]=0x00;
-    }
+    
+    heart_beat_data[1]=Mqtt_Get_Connect_Flag() ? 0x01:0x00;//mqtt连接状态
     Uart_Reply_Send(COMMON_UART_HEART_CMD, heart_beat_data, sizeof(heart_beat_data), HOST_TYPE_UART);//(cmd, pbuf, len, host_type);
 }
 
@@ -138,7 +204,7 @@ void Mqtt_Send_Connect_Status(void)//包含心跳
 static esp_err_t Mqtt_App_Init(void)
 {
     esp_err_t err = ESP_FAIL;
-    if(common_setting.wifi_status.wifi_state != 1)
+    if(common_setting.wifi_status.wifi_state != 1 || common_setting.ble_status.nimble_flag == 0)
     {
         ESP_LOGI(MQTT_TAG, "wifi disconnected");
         return ESP_FAIL;
@@ -187,6 +253,7 @@ static esp_err_t Mqtt_App_Init(void)
     common_setting.mqtt_cfg.credentials.client_id = (const char *)pid_str;
     #endif
     ESP_LOGI(MQTT_TAG, "Mqtt init %s",pid_str);
+    common_setting.mqtt_cfg.task.priority = 2;
     common_setting.mqtt_client_handle = esp_mqtt_client_init(&common_setting.mqtt_cfg);
     if(common_setting.mqtt_client_handle == NULL){
         ESP_LOGI(MQTT_TAG, "client_handle null\n");
@@ -217,268 +284,6 @@ uint8_t Mqtt_Get_Connect_Flag(void)
     }
     return 0;
 }
-// MQTT发送按键灯颜色
-static esp_err_t _http_event_handler(esp_http_client_event_t *evt)
-{
-    switch (evt->event_id) {
-    case HTTP_EVENT_ERROR:
-        // ESP_LOGI(HTTP_TAG, "HTTP_EVENT_ERROR");
-        break;
-    case HTTP_EVENT_ON_CONNECTED:
-        // ESP_LOGI(HTTP_TAG, "HTTP_EVENT_ON_CONNECTED");
-        break;
-    case HTTP_EVENT_HEADER_SENT:
-        // ESP_LOGI(HTTP_TAG, "HTTP_EVENT_HEADER_SENT");
-        break;
-    case HTTP_EVENT_ON_HEADER:
-        // ESP_LOGI(HTTP_TAG, "HTTP_EVENT_ON_HEADER, key=%s, value=%s", evt->header_key, evt->header_value);
-        break;
-    case HTTP_EVENT_ON_DATA:
-        // ESP_LOGI(HTTP_TAG, "HTTP_EVENT_ON_DATA, len=%d", evt->data_len);
-        // if (!esp_http_client_is_chunked_response(evt->client)) 
-        // {
-        //     printf("%.*s", evt->data_len, (char*)evt->data);
-        //     uint8_t *data = (uint8_t*)evt->data;
-        //     for(uint32_t i=0;i<evt->data_len;i++)
-        //     {
-        //         printf("%02x ", *(data++));
-        //     }
-        //     printf("\n");
-        // }
-        break;
-    case HTTP_EVENT_ON_FINISH:
-        // ESP_LOGI(HTTP_TAG, "HTTP_EVENT_ON_FINISH");
-        break;
-    case HTTP_EVENT_DISCONNECTED:
-        // ESP_LOGI(HTTP_TAG, "HTTP_EVENT_DISCONNECTED");
-        break;
-    case HTTP_EVENT_REDIRECT:
-        // ESP_LOGI(HTTP_TAG, "HTTP_EVENT_REDIRECT");
-        break;
-    }
-    return ESP_OK;
-}
-void Mqtt_Get_Key_Led_Color(uint8_t *color_data,uint16_t color_len)
-{
-    return;
-    
-    // f2 0d 84 7f 01 05 03 00 36 34 30 30 41 30 80 0105 03 00 34 36 43 33 44 43 81 01 05 03 00 46 41 35 35 30 30 
-    // 82 01 05 03 00 46 46 30 30 30 30 83 01 05 03 00 30 30 46 46 30 30 84 01 05 03 00 30 30 30 30 46 46 
-    // 85 01 05 03 00 46 30 35 41 36 3986 01 05 03 00 38 32 46 41 41 46 87 01 05 03 0041 46 30 30 38 43 
-    // 88 01 05 03 00 46 30 33 43 30 30 89 01 05 03 00 46 46 42 34 30 30 8a 01 05 03 00 39 42 46 46 35 30 
-    // 22
-    uint8_t uart_reply_data[1]={0};
-    //没有订阅成 没有连接wifi 没有连接mqtt 直接返回NULL
-    // if(!Mqtt_Get_Connect_Flag() || color_data == NULL || color_len == 0 || color_len < 8) 
-    // {
-    //     uart_reply_data[0] = REPLY_STATUS_FAIL;
-    //     Uart_Reply_Send(COMMON_UART_GET_KEY_COLOR_CMD,uart_reply_data, sizeof(uart_reply_data), HOST_TYPE_UART);
-    //     ESP_LOGI(MQTT_TAG, "Mqtt_Get_Key_Led_Color!!!%d\n",color_len);
-    //     // ESP_LOG_BUFFER_HEX(MQTT_TAG, color_data, color_len);
-    //     return;
-    // }
-    char pid_str[6] = {0};
-    char vid_str[6] = {0};
-    char wifi_soc[15] = {"Unknown"};
-
-    // PID、VID 大写十六进制格式
-    snprintf(pid_str, sizeof(pid_str), "%04X", common_setting.mcu_info.pid);
-    snprintf(vid_str, sizeof(vid_str), "%04X", common_setting.mcu_info.vid);
-
-    // 获取芯片型号
-    // get_chip_info(wifi_soc, &chip_len);
-    esp_chip_info_t chip_info;
-    esp_chip_info(&chip_info);
-
-    // 打印型号(数字 → 转成文字)
-    char *chip_name = "Unknown";
-    switch(chip_info.model) {
-       
-        case CHIP_ESP32C2:      chip_name = "ESP32-C2";   break;
-        case CHIP_ESP32 :       chip_name = "ESP32";        break;//!< ESP32
-        case CHIP_ESP32S2:      chip_name = "ESP32-S2";     break; //!< ESP32-S2
-        case CHIP_ESP32S3:      chip_name = "ESP32-S3";     break; //!< ESP32-S3
-        case CHIP_ESP32C3:      chip_name = "ESP32-C3";     break; //!< ESP32-C3
-        case CHIP_ESP32C6:      chip_name = "ESP32-C6";     break; //!< ESP32-C6
-        case CHIP_ESP32H2 :      chip_name = "ESP32-H2";    break;  //!< ESP32-H2
-        case CHIP_ESP32P4:      chip_name = "ESP32-P4";     break;  //!< ESP32-P4
-        case CHIP_ESP32C61:      chip_name = "ESP32-C61";   break;  //!< ESP32-C61
-        case CHIP_ESP32C5:      chip_name = "ESP32-C5";     break; //!< ESP32-C5
-        case CHIP_ESP32H21:      chip_name = "ESP32-H21";   break; //!< ESP32-H21
-        case CHIP_ESP32H4:      chip_name = "ESP32-H4";     break; //!< ESP32-H4
-        case CHIP_POSIX_LINUX:      chip_name = "POSIX_LINUX";break;  //!< The code is running on POSIX/Linux simulator
-        default:
-        break;
-    }
-
-    strcpy(wifi_soc, chip_name);
-
-    // 版本号格式化 0x0015 → V0021
-    char fw_ver[8] = {0}, wifi_ver[8] = {0};
-    snprintf(fw_ver, sizeof(fw_ver), "%04u", common_setting.mcu_info.fw_version);
-    snprintf(wifi_ver, sizeof(wifi_ver), "%04u", (unsigned int)FW_VERSION);
-    if(FW_VERSION > 9999)
-    {
-       snprintf(wifi_ver, sizeof(wifi_ver), "%s","9999");
-    }
-    // ===================== 构建正确的 JSON =====================
-    cJSON *root = cJSON_CreateObject();
-    if (root == NULL) return;
-    
-
-    // 把设备信息加到里面
-    cJSON_AddStringToObject(root, "pid", pid_str);
-    cJSON_AddStringToObject(root, "vid", vid_str);
-    cJSON_AddStringToObject(root, "wifi_soc", wifi_soc);
-    cJSON_AddStringToObject(root, "fw_version", fw_ver);
-    cJSON_AddStringToObject(root, "wifi_version", wifi_ver);
-    cJSON_AddStringToObject(root, "serial_id", (char *)common_storage.net_info.serial_number);
-    cJSON_AddNumberToObject(root, "connected_platform", common_setting.mcu_platform_mode);
-    cJSON_AddNumberToObject(root, "power_on", 0);
-    cJSON *pRoot = cJSON_CreateObject();
-    // cJSON_AddItemToObject(root,""thingsModelValue": "string",");
-    if(pRoot == NULL)
-    {
-        if(root != NULL)
-        {
-            cJSON_Delete(root);
-        }
-        
-        return;
-    }
-    cJSON_AddItemToObject(root,"thingsModelValue",pRoot);
-
-    
-    char key[8]={0};//65535
-    uint16_t len = 0;
-    
-    char value[32]={0};//8个字节也就是16字符 ff ff ff ff ff ff ff ff
-
-    for(int i=0;i<color_len/11;i++)
-    {
-        uint8_t dpid_h = color_data[i*11 + 0];   // 高8位 0x01
-        uint8_t dpid_l = color_data[i*11 + 1];   // 低8位 0x7F
-        uint16_t dpid = (dpid_h << 8) | dpid_l; // 0x017F = 383
-        //17
-        snprintf(key,sizeof(key),"%d", dpid);
-        if(color_data[i*8+2] == 5) //数据类型
-        {
-            //
-        }
-        uint8_t d_h = color_data[i*11 + 3];   // 高8位 0x7f
-        uint8_t d_l = color_data[i*11 + 4];   // 低8位 0x01
-
-        uint16_t data_len = (d_h << 8) |d_l;
-        ESP_LOGI(MQTT_TAG, "Mqtt_Get_Key_Led_Color!!!%d\n",data_len);
-        // ESP_LOGI(MQTT_TAG,"COLOR LEN:%d",data_len);
-        // uint8_t r = color_data[i*8 + 5]; 5 6 7 8 9 10
-        // uint8_t g = color_data[i*8 + 6];
-        // uint8_t b = color_data[i*8 + 7];
-        if(data_len > 32-1)
-        {
-            data_len=32-1;
-        }
-        memset(value,0,sizeof(value));
-        sprintf(&value[0],"%s","#");
-        memcpy(&value[1],&color_data[i*11+5],data_len);
-        value[data_len]='\0';
-        snprintf(key,sizeof(key),"%d",dpid);
-        cJSON_AddStringToObject(pRoot, key, value);
-    }
-    char *json_str = cJSON_PrintUnformatted(root);
-    cJSON_Delete(root);
-    uint16_t json_str_len = strlen(json_str);
-    if(json_str_len == 0 || json_str_len >= MQTT_SEND_RECV_DATA_BUF_SIZE)
-    {
-        ESP_LOGI(MQTT_TAG, "key led is large:%s %d\n", json_str,strlen(json_str));
-        if(json_str != NULL)
-        {
-            free(json_str);
-        }
-        json_str = NULL;
-        //回复串口信息
-        
-        uart_reply_data[0] = REPLY_STATUS_FAIL;
-        Uart_Reply_Send(COMMON_UART_GET_KEY_COLOR_CMD,uart_reply_data, sizeof(uart_reply_data), HOST_TYPE_UART);
-        return;
-    }
-    mqtt_send_msg_t send_msg={0};
-    memcpy(send_msg.data,json_str,json_str_len);
-    ESP_LOGI(MQTT_TAG, "key led:%s\n", json_str);
-
-
-    esp_http_client_config_t http_config = 
-    {
-        .event_handler = _http_event_handler,
-        .disable_auto_redirect = true,
-        .keep_alive_enable = true,
-    };
-    const char path[] = "/iot/device/";
-    char url[128] = {0};
-    memset(url, 0x00, sizeof(url));
-    //PATH 10 255-10
-    // if(common_setting.net_pairing_info.http_url_length < (sizeof(url) - sizeof(path))){
-    //     memcpy(url, common_setting.net_pairing_info.http_url, sizeof(url)-common_setting.net_pairing_info.http_url_length);
-    //     memcpy(&url[common_setting.net_pairing_info.http_url_length], path, strlen(path));
-    // }
-    snprintf(url,sizeof(url)-1,"%s",path);
-    esp_http_client_handle_t http_client = NULL;
-    http_config.url = url;
-    http_client = esp_http_client_init(&http_config);
-    if(http_client == NULL)
-    {
-
-        ESP_LOGI(MQTT_TAG, "%s http_config.url = %s",__func__, http_config.url);
-        
-        
-    }
-    esp_http_client_set_header(http_client, "Authorization", (const char*)common_setting.net_pairing_info.http_token);
-    esp_http_client_set_method(http_client, HTTP_METHOD_PUT);
-    esp_http_client_set_header(http_client, "Content-Type", "application/json");
-
-    esp_http_client_set_post_field(http_client, json_str, strlen(json_str));
-    esp_err_t err = esp_http_client_perform(http_client);
-    int result = 0;
-    if (err == ESP_OK)
-    {
-        int status_code = esp_http_client_get_status_code(http_client);
-        int read_len = esp_http_client_get_content_length(http_client);
-        if(status_code == 200)
-        {
-            result =  1;
-        }
-        else
-        {
-            result =  2;
-        }
-        ESP_LOGI(MQTT_TAG, "PUT Status = %d, content_length = %d", status_code, read_len);
-    }
-    else
-    {
-        result = 2;
-        
-    }
-    free(json_str);
-    json_str = NULL;
-    memcpy(send_msg.topic, topic_str, strlen(topic_str));
-    
-    if(mqtt_send_queue_handle==NULL)
-    {
-        ESP_LOGI(MQTT_TAG, "mqtt_send_queue_handle is null\n");
-        return;
-    }
-    if (xQueueSend(mqtt_send_queue_handle, &send_msg, 0) != pdPASS) {
-        // ESP_LOGW(MQTT_TAG, "QUEUE is full\n");
-        uart_reply_data[0] = REPLY_STATUS_FAIL;
-        Uart_Reply_Send(COMMON_UART_GET_KEY_COLOR_CMD,uart_reply_data, sizeof(uart_reply_data), HOST_TYPE_UART);
-    }else{
-        
-        uart_reply_data[0] = REPLY_STATUS_OK;
-        Uart_Reply_Send(COMMON_UART_GET_KEY_COLOR_CMD,uart_reply_data, sizeof(uart_reply_data), HOST_TYPE_UART);
-    }
-
-    return;
-}
 
 //开机连上mqtt订阅成功之后发送主控信息
 static uint8_t mqtt_send_mcu_info_flag = 0;//发送主控信息标志,1表示已发送过,0表示未发送过
@@ -493,23 +298,26 @@ void Mqtt_Send_Mcu_Info(void)
     {
         return;
     }
-    char pid_str[6] = {0};
-    char vid_str[6] = {0};
-    char wifi_soc[15] = {"Unknown"};
-
-    // PID、VID 大写十六进制格式
-    snprintf(pid_str, sizeof(pid_str), "%04X", common_setting.mcu_info.pid);
-    snprintf(vid_str, sizeof(vid_str), "%04X", common_setting.mcu_info.vid);
+    char pid_str[10] = {0};
+    char vid_str[10] = {0};
+    char wifi_soc[16] = {"Unknown"};
 
+    
     // 获取芯片型号
     uint8_t chip_len = 0;
     get_chip_info(wifi_soc, &chip_len);
     if (chip_len == 0) {
         strcpy(wifi_soc, "Unknown");
     }
+    // PID、VID 大写十六进制格式
+    snprintf(pid_str, sizeof(pid_str), "%04X", common_setting.mcu_info.pid);
+    snprintf(vid_str, sizeof(vid_str), "%04X", common_setting.mcu_info.vid);
+
+    
+    
 
     // 版本号格式化 0x0015 → V0021
-    char fw_ver[8] = {0}, wifi_ver[8] = {0};
+    char fw_ver[12] = {0}, wifi_ver[12] = {0};
     snprintf(fw_ver, sizeof(fw_ver), "0x%04X", common_setting.mcu_info.fw_version);
     snprintf(wifi_ver, sizeof(wifi_ver), "0x%04X", (unsigned int)FW_VERSION);
     
@@ -541,7 +349,7 @@ void Mqtt_Send_Mcu_Info(void)
     char *post_data = cJSON_Print(root);
     // char *post_data = cJSON_PrintUnformatted(root);
     cJSON_Delete(root);
-
+    root=NULL;
     if (post_data == NULL) return;
 
     
@@ -552,43 +360,61 @@ void Mqtt_Send_Mcu_Info(void)
         post_data=NULL;
         return;
     }
-    if(strlen(post_data) == 0 || strlen(topic_str) == 0)
+    if(strlen(post_data) == 0 || strlen(get_publish_topic(TOPIC_PROPERTY_POST)) == 0)
     {
-        ESP_LOGI(MQTT_TAG, "len no %d", strlen(topic_str),strlen(post_data));
+        ESP_LOGI(MQTT_TAG, "len no %d", strlen(get_publish_topic(TOPIC_PROPERTY_POST)),strlen(post_data));
         free(post_data);
         post_data=NULL;
         return;
     }
-    mqtt_send_msg_t send_msg={0};
+    static mqtt_send_msg_t send_msg={0};
     memcpy(send_msg.data,post_data,strlen(post_data));
-    ESP_LOGI(MQTT_TAG, "CJSON:%s", post_data);
-    free(post_data);
-    post_data = NULL;
+    ESP_LOGI(MQTT_TAG, "CJSON:%s", post_data);
+    
 
-    memcpy(send_msg.topic,topic_str,strlen(topic_str));
+    memcpy(send_msg.topic,get_publish_topic(TOPIC_PROPERTY_POST),strlen(get_publish_topic(TOPIC_PROPERTY_POST)));
     
-    if(mqtt_send_queue_handle==NULL)
+    if(mqtt_dev_report_queue_handle==NULL)
     {
         ESP_LOGI(MQTT_TAG, "Mqtt_Send_Mcu_Info is null\n");
         return;
     }
-    if (xQueueSend(mqtt_send_queue_handle, &send_msg, 0) != pdPASS) {
-        // ESP_LOGW(MQTT_TAG, "QUEUE is full\n");
-        mqtt_send_mcu_info_flag = 1;
-    }else{
-        ESP_LOGI(MQTT_TAG, "Send Data OK\n");
-        mqtt_send_mcu_info_flag = 0;
-    }
+    user_esp_mqtt_client_publish(send_msg.data,strlen(send_msg.data),send_msg.topic);
+    free(post_data);
+    post_data = NULL;
+    mqtt_send_mcu_info_flag=0;
+    return;
 }
+void mqtt_get_dev_test(uint16_t *dpid,uint8_t num);
 void Mqtt_Send_Data(void)
 {
     // return;
-
+    // ESP_LOGI(MQTT_TAG,"HR!!!!!",mqtt_send_data_count);
     if(mqtt_send_data_count >= 60)
     {
-        mqtt_send_data_count=0;
-        Mqtt_Send_Mcu_Info();   
+        
+        // ESP_LOGI(MQTT_TAG,"HR!!!!!");
+        // Wifi_Stop();
+        // Mqtt_Disconnect();
+        // User_Erase_NotReset();
+
+        Mqtt_Send_Mcu_Info();  
+        mqtt_send_data_count=0; 
+    }
+    if(mqtt_send_data_count % 7 == 0)
+    {
+        uint16_t test_dpid[25]={335,336,336,337,338,339,340,341,400,401,745,746,747,271,272,273,274,275,745,746,275,276,277,278,279};
+    
+        mqtt_get_dev_test(test_dpid,25);
+        // mqtt_parse_recv_data(NULL,0);
     }
+    else if(mqtt_send_data_count % 15 == 0)
+    {
+        // mqtt_parse_recv_data(NULL,1);
+
+    }
+
+
     mqtt_send_data_count++;
 }
 // 接收mqtt发过来的数据
@@ -667,27 +493,45 @@ void Mqtt_Connect_Status_Check(void)
 //断开wifi连接同时断开mqtt连接 释放mqtt资源
 void Mqtt_Disconnect(void)
 {
-    if(mqtt_init_flag == 1&& common_setting.mqtt_client_handle != NULL && (common_setting.mqtt_user_cfg.mqtt_start_flag == 1 || \
-    common_setting.wifi_status.connect_mode == 3))
+    if(mqtt_init_flag != 1)
+    {
+        return;
+    }
+    if(common_setting.mqtt_client_handle == NULL)
     {
-        
-        esp_mqtt_client_stop(common_setting.mqtt_client_handle);
-        
-        //
-        vTaskDelay(pdMS_TO_TICKS(150));
-        
-        //释放资源
-        esp_mqtt_client_destroy(common_setting.mqtt_client_handle);
-        
-       
-        common_setting.mqtt_client_handle = NULL;
         mqtt_init_flag = 0;
-        retry_connect_cnt = 0;
-        common_setting.mqtt_user_cfg.mqtt_connect_flag = 0;
-        common_setting.mqtt_user_cfg.mqtt_sub_flag = 0;
-        
-        ESP_LOGW(MQTT_TAG, "MQTT STOP");
+        return;
+    }
+    mqtt_init_flag = 0;
+    esp_mqtt_client_stop(common_setting.mqtt_client_handle);
+    //
+    vTaskDelay(pdMS_TO_TICKS(100));
+    //反注册事件+销毁客户端
+    esp_mqtt_client_unregister_event(common_setting.mqtt_client_handle, ESP_EVENT_ANY_ID, mqtt_event_handler);
+    //释放资源
+    esp_mqtt_client_destroy(common_setting.mqtt_client_handle);
+    
+    // 2. 删掉 MQTT 任务
+    if (mqtt_connect_task_handler != NULL) {
+        vTaskDelete(mqtt_connect_task_handler);
+        mqtt_connect_task_handler = NULL;
+    }
+
+    // 3. 删掉所有 MQTT 队列
+    if (mqtt_dev_report_queue_handle != NULL) {
+        vQueueDelete(mqtt_dev_report_queue_handle);
+        mqtt_dev_report_queue_handle = NULL;
     }
+    if (mqtt_recv_queue_handle != NULL) {
+        vQueueDelete(mqtt_recv_queue_handle);
+        mqtt_recv_queue_handle = NULL;
+    }
+    common_setting.mqtt_client_handle = NULL;
+    retry_connect_cnt = 0;
+    common_setting.mqtt_user_cfg.mqtt_connect_flag = 0;
+    common_setting.mqtt_user_cfg.mqtt_sub_flag = 0;
+    mqtt_init_flag = 0;
+    ESP_LOGW(MQTT_TAG, "MQTT STOP");
 }
 // 解析 MQTT 下发的 JSON 数据
 // 是否是纯数字
@@ -708,7 +552,7 @@ bool is_pure_number(const char *str)
     }
     return true;
 }
-char msgID[64]={0}; 
+
 // 云端 version 转 16 进制版本号(例如 1.03 → 0x0103)
 uint16_t version_str_to_hex(char *version)
 {
@@ -716,7 +560,7 @@ uint16_t version_str_to_hex(char *version)
     {
         return 0xffff;
     }
-    if(strlen(version)==0 || version[0] == ' ')
+    if(strlen(version)==0)
     {
         ESP_LOGI(MQTT_TAG,"len err%s\n", version);   // 1
         return 0xffff;
@@ -729,9 +573,7 @@ uint16_t version_str_to_hex(char *version)
         ESP_LOGI(MQTT_TAG,"不合法%s\n", version);   // 1
         return 0xffff;
     }
-    char major_str[10] = {0};
-    strncpy(major_str, version, dot - version); // 复制 "1"
-    int major = atoi(major_str);       // 转成数字 1
+    int major = atoi(version);       // 转成数字 10.09 = 10 20.1 =20-
 
 
     // --------------------
@@ -745,105 +587,294 @@ uint16_t version_str_to_hex(char *version)
     // 合成 0x0103
     return (major << 8) | minor;
 }
-static void mqtt_parse_recv_data(char *data, int data_len)
+
+
+char *set_test_json(void)
 {
-    //"method": "thing.service.property.set.reply",
-    
+    // 1. 创建根对象
+    cJSON *root = cJSON_CreateObject();
+    if (root == NULL)
+        return NULL;
+
+    // ================== 生成时间戳 ==================
+    time_t Time_Sec = Get_Time_Stamp();
+    static char time_str[16] = {0};
+    snprintf(time_str, sizeof(time_str)-1, "%lld", Time_Sec);
+
+    // ================== 1. 创建 data 对象 ==================
+    cJSON *data = cJSON_CreateObject();
+    cJSON_AddItemToObject(root, "data", data);  // root -> data
+
+    // ================== 2. data 下面加 topic ==================
+    cJSON_AddStringToObject(data, "topic", "topic/PXN1LJ1QUR078E/A00B/property/post");
+
+    // ================== 3. 创建 payload ==================
+    cJSON *payload = cJSON_CreateObject();
+    cJSON_AddItemToObject(data, "payload", payload);  // data -> payload
+
+    // ================== 4. payload 内部字段 ==================
+    cJSON_AddStringToObject(payload, "msgId", "cloud_e84fc0b190cd426690893a9a118ab2cd");
+    cJSON_AddStringToObject(payload, "method", "thing.service.property.set");
+    cJSON_AddStringToObject(payload, "time", time_str);
+    cJSON_AddStringToObject(payload, "serialNumber", "PXN1LJ1QUR078E");
+    cJSON_AddStringToObject(payload, "productId", "A00B");
+
+    // ================== 5. 创建 params 数组 ==================
+    cJSON *params = cJSON_CreateArray();
+    cJSON_AddItemToObject(payload, "params", params);
+
+    // 示例["345","346","347"]
+    for(uint16_t i = 17;i < 18;i++)
+    {
+        char key[10]={0};
+        snprintf(key,sizeof(key),"%d",i);
+        cJSON *s = cJSON_CreateObject();
+        if (s) {
+            cJSON_AddNumberToObject(s, key, i*2);
+            cJSON_AddItemToArray(params, s);
+            // cJSON_AddItemToObject(s,key,i*2);
+        }
+    }
+
+    // for(uint16_t i =843;i<878;i++)
+    // {
+    //     char str[16];
+    //     sprintf(str, "%d", i);
+    //     cJSON *s = cJSON_CreateString(str);
+    //     if (s) {
+    //         cJSON_AddItemToArray(params, s);
+    //     }
+    // }
+
+    // for(uint16_t i =745;i<748;i++)
+    // {
+    //     char str[16];
+    //     sprintf(str, "%d", i);
+    //     cJSON *s = cJSON_CreateString(str);
+    //     if (s) {
+    //         cJSON_AddItemToArray(params, s);
+    //     }
+    // }
+
+    // for(uint16_t i =735;i<754;i++)
+    // {
+    //     char str[16];
+    //     sprintf(str, "%d", i);
+    //     cJSON *s = cJSON_CreateString(str);
+    //     if (s) {
+    //         cJSON_AddItemToArray(params, s);
+    //     }
+    // }
+
+    // for(uint16_t i =761;i<764;i++)
+    // {
+    //     char str[16];
+    //     sprintf(str, "%d", i);
+    //     cJSON *s = cJSON_CreateString(str);
+    //     if (s) {
+    //         cJSON_AddItemToArray(params, s);
+    //     }
+    // }
     
+    // for(uint16_t i =769;i<772;i++)
+    // {
+    //     char str[16];
+    //     sprintf(str, "%d", i);
+    //     cJSON *s = cJSON_CreateString(str);
+    //     if (s) {
+    //         cJSON_AddItemToArray(params, s);
+    //     }
+    // }
 
-    // 安全判断
-    if (data == NULL || data_len <= 0 || data_len > MQTT_DATA_BUF_SIZE) {
-        ESP_LOGW(MQTT_TAG, "parese too len:%d\n",data_len);
-        return;
-    }
 
-    // ========== cJSON 解析(安全版)==========
-    cJSON *root = cJSON_Parse(data);
-    if (root == NULL) {
-        ESP_LOGW(MQTT_TAG, "JSON error");
-        return;
-    }
 
+
+
+
+    // // 示例:添加 { "736": "50" }
+    // cJSON *p1 = cJSON_CreateObject();
+    // cJSON_AddNumberToObject(p1, "736", 50);
+    // cJSON_AddItemToArray(params, p1);
+
+    // // 示例:添加 { "737": "89" }
+    // cJSON *p2 = cJSON_CreateObject();
+    // cJSON_AddNumberToObject(p2, "737", 89);
+    // cJSON_AddItemToArray(params, p2);
+
+    // ================== 打印看结果 ==================
+    char *out = cJSON_Print(root);
+    ESP_LOGI(MQTT_TAG,"%s\n", out);
     
 
-    //请求方式
-    cJSON *method = cJSON_GetObjectItem(root, "method");//
-    if (method != NULL && cJSON_IsString(method)) {
-        if(strcmp("thing.service.property.set",method->valuestring) == 0)
-        {
-            cJSON *msgId = cJSON_GetObjectItem(root, "msgId");//
-            if (msgId != NULL && cJSON_IsString(msgId)) {
-                snprintf(msgID,sizeof(msgID)-1,"%s",msgId->valuestring);
-                // ===================== 构建正确的 JSON =====================
-                cJSON *r_root = cJSON_CreateObject();
-                if (r_root != NULL) {
-                    
-                    time_t now = Get_Time_Stamp();  // 64位时间戳
-
-                    char stamp_str[32];
-                    // 转成字符串
-                    sprintf(stamp_str, "%lld", now);  
-
-                    // 以字符串加入
-                    cJSON_AddStringToObject(r_root, "time", stamp_str); 
-                    cJSON_AddStringToObject(r_root, "method", "thing.service.property.set.reply"); //属性设置回复
-                    cJSON_AddStringToObject(r_root, "msgId", msgId->valuestring);
-                    cJSON_AddStringToObject(r_root, "serialNumber", (const char *)common_storage.net_info.serial_number);
-                    char pid[10] = {0};
-                    sprintf(pid,"%04x",common_setting.mcu_info.pid);
-                    cJSON_AddStringToObject(r_root, "productId",pid );
-                    cJSON_AddNumberToObject(r_root, "code", 0);
-                    cJSON_AddStringToObject(r_root, "message", "ok");
-
-                    //
-                    char *json_r = cJSON_Print(r_root);
-                    cJSON_Delete(r_root);
-                    r_root=NULL;
-                    if(strlen(json_r))
-                    {
-                        
-                        mqtt_send_msg_t send_msg={0};
-                        memcpy(send_msg.data,json_r,strlen(json_r));
-                        ESP_LOGI(MQTT_TAG, "CJSON:%s", json_r);
-                        if(json_r)
-                        {
-                            free(json_r);
-                            json_r = NULL;
-                        }
-                        memcpy(send_msg.topic,topic_str,strlen(topic_str));
-                        // esp_ble_tx_power_set(ESP_BLE_PWR_TYPE_DEFAULT,ESP_PWR_LVL_P9);
-                        if(mqtt_send_queue_handle==NULL)
-                        {
-                            ESP_LOGI(MQTT_TAG, "replay error\n");
-                            return;
-                        }
-                        //回复服务器
-                        xQueueSend(mqtt_send_queue_handle, &send_msg, 0);
-                    }  
-                }
-            }
-            vTaskDelay(5);
+    // 销毁
+    cJSON_Delete(root);
+    return out;
+}
+
+char *get_test_json(void)
+{
+    // 1. 创建根对象
+    cJSON *root = cJSON_CreateObject();
+    if (root == NULL)
+        return NULL;
+
+    // ================== 生成时间戳 ==================
+    time_t Time_Sec = Get_Time_Stamp();
+    static char time_str[16] = {0};
+    snprintf(time_str, sizeof(time_str)-1, "%lld", Time_Sec);
+
+    // ================== 1. 创建 data 对象 ==================
+    cJSON *data = cJSON_CreateObject();
+    cJSON_AddItemToObject(root, "data", data);  // root -> data
+
+    // ================== 2. data 下面加 topic ==================
+    cJSON_AddStringToObject(data, "topic", "topic/PXN1LJ1QUR078E/A00B/property/post");
+
+    // ================== 3. 创建 payload ==================
+    cJSON *payload = cJSON_CreateObject();
+    cJSON_AddItemToObject(data, "payload", payload);  // data -> payload
+
+    // ================== 4. payload 内部字段 ==================
+    cJSON_AddStringToObject(payload, "msgId", "cloud_e84fc0b190cd426690893a9a118ab2cd");
+    cJSON_AddStringToObject(payload, "method", "thing.service.property.set");
+    cJSON_AddStringToObject(payload, "time", time_str);
+    cJSON_AddStringToObject(payload, "serialNumber", "PXN1LJ1QUR078E");
+    cJSON_AddStringToObject(payload, "productId", "A00B");
+
+    // ================== 5. 创建 params 数组 ==================
+    cJSON *params = cJSON_CreateArray();
+    cJSON_AddItemToObject(payload, "params", params);
+
+    // 示例["345","346","347"]
+    for(uint16_t i =17;i<28;i++)
+    {
+        char str[16];
+        sprintf(str, "%d", i);
+        cJSON *s = cJSON_CreateString(str);
+        if (s) {
+            cJSON_AddItemToArray(params, s);
         }
     }
 
-    // 示例 1:解析字符串类型
-    //===========清除配网指令=========================//
-    cJSON *reset = cJSON_GetObjectItem(root, "otareset");//清除配网标识字符串 int
-    if (reset != NULL && cJSON_IsNumber(reset)) {
-        ESP_LOGI(MQTT_TAG, "otareset: %d", reset->valueint);
-        int otareset = 0;
-        otareset = reset->valueint;
-        if(otareset == 1)
-        {
-            //1.清除flash
-            //2.重启设备
-            User_Erase_Nimble_NetWork_Infor();
-            vTaskDelay(pdMS_TO_TICKS(100));
-            if(root != NULL)
+    // for(uint16_t i =843;i<878;i++)
+    // {
+    //     char str[16];
+    //     sprintf(str, "%d", i);
+    //     cJSON *s = cJSON_CreateString(str);
+    //     if (s) {
+    //         cJSON_AddItemToArray(params, s);
+    //     }
+    // }
+
+    // for(uint16_t i =745;i<748;i++)
+    // {
+    //     char str[16];
+    //     sprintf(str, "%d", i);
+    //     cJSON *s = cJSON_CreateString(str);
+    //     if (s) {
+    //         cJSON_AddItemToArray(params, s);
+    //     }
+    // }
+
+    // for(uint16_t i =735;i<754;i++)
+    // {
+    //     char str[16];
+    //     sprintf(str, "%d", i);
+    //     cJSON *s = cJSON_CreateString(str);
+    //     if (s) {
+    //         cJSON_AddItemToArray(params, s);
+    //     }
+    // }
+
+    // for(uint16_t i =761;i<764;i++)
+    // {
+    //     char str[16];
+    //     sprintf(str, "%d", i);
+    //     cJSON *s = cJSON_CreateString(str);
+    //     if (s) {
+    //         cJSON_AddItemToArray(params, s);
+    //     }
+    // }
+    
+    // for(uint16_t i =769;i<772;i++)
+    // {
+    //     char str[16];
+    //     sprintf(str, "%d", i);
+    //     cJSON *s = cJSON_CreateString(str);
+    //     if (s) {
+    //         cJSON_AddItemToArray(params, s);
+    //     }
+    // }
+
+
+
+
+
+
+    // // 示例:添加 { "736": "50" }
+    // cJSON *p1 = cJSON_CreateObject();
+    // cJSON_AddNumberToObject(p1, "736", 50);
+    // cJSON_AddItemToArray(params, p1);
+
+    // // 示例:添加 { "737": "89" }
+    // cJSON *p2 = cJSON_CreateObject();
+    // cJSON_AddNumberToObject(p2, "737", 89);
+    // cJSON_AddItemToArray(params, p2);
+
+    // ================== 打印看结果 ==================
+    char *out = cJSON_Print(root);
+    ESP_LOGI(MQTT_TAG,"%s\n", out);
+    
+
+    // 销毁
+    cJSON_Delete(root);
+    return out;
+}
+
+void mqtt_parse_recv_data(char *buf, int data_len)
+{
+    
+    // // 安全判断
+    // if (buf == NULL || data_len <= 0 || data_len > MQTT_DATA_BUF_SIZE) {
+    //     ESP_LOGW(MQTT_TAG, "parese too len:%d\n",data_len);
+    //     return;
+    // }
+    
+    if(buf == NULL)return;
+    // ========== cJSON 解析(安全版)==========
+    cJSON *root = cJSON_Parse(buf);
+    if (root == NULL) {
+        ESP_LOGW(MQTT_TAG, "JSON error");
+
+        return;
+    }
+
+    cJSON *payload_root  = cJSON_GetObjectItem(root, "data");//
+    if (payload_root  == NULL && !cJSON_IsObject(payload_root )) {
+        
+        cJSON_Delete(root);
+        return;
+    }
+
+    //请求方式
+    
+    // 示例 1:解析字符串类型
+    //===========清除配网指令=========================//
+    cJSON *reset = cJSON_GetObjectItem(payload_root , "otareset");//清除配网标识字符串 int
+    if (reset != NULL && cJSON_IsNumber(reset)) {
+        ESP_LOGI(MQTT_TAG, "otareset: %d", reset->valueint);
+        if(reset->valueint)
+        {
+            //1.清除flash
+            //2.重启设备
+            User_Erase_Nimble_NetWork_Infor();
+            vTaskDelay(pdMS_TO_TICKS(100));
+            if(root != NULL)
             {
                 cJSON_Delete(root);
                 root=NULL;
             }
+           
             esp_restart();//重启模组
             return;
         }
@@ -875,39 +906,51 @@ static void mqtt_parse_recv_data(char *data, int data_len)
     // }
     // cJSON *payload = cJSON_GetObjectItem(root, "payload");//
     if (1) {
-        cJSON *filePath = cJSON_GetObjectItem(root, "filePath");
-        if (filePath != NULL && cJSON_IsString(filePath)) {
-            cJSON *version = cJSON_GetObjectItem(root, "version");
-            if ((version != NULL && cJSON_IsString(version)) ) 
+        //OTA升级
+        cJSON *filePath = cJSON_GetObjectItem(payload_root , "filePath");
+        if (filePath != NULL && cJSON_IsString(filePath) && filePath->valuestring != NULL) {
+            cJSON *version = cJSON_GetObjectItem(payload_root , "version");
+            if ((version != NULL && cJSON_IsString(version) && version->valuestring != NULL) ) 
             {
                 // version->valuestring = "10.165";
                 // const char* version = "10.165";
                 uint16_t new_version = version_str_to_hex(version->valuestring);
                 // 核心:把 0x0A15 转成浮点数 10.21
-                ESP_LOGI(MQTT_TAG, "固件版本: %s %04x FW_VERSION:%04x", version->valuestring,new_version,FW_VERSION);
+                ESP_LOGI(MQTT_TAG, "ver: %s %04x FW_VERSION:%04x", version->valuestring,new_version,FW_VERSION);
                 if(new_version != FW_VERSION && new_version != 0xffff)
                 {
                     //开启ota线程
                     #if ENABLE_HTTPS_OTA_FUNC
-                    const char *ota_url = filePath->valuestring;
+                    // const char *ota_url = filePath->valuestring;
                     // static const char *filePath="https://pxn-iot.s3.us-east-2.amazonaws.com/iot01/2026/04/27/69ef076479113dba3ec8e375.bin";//https://pxn-iot.s3.us-east-2.amazonaws.com/iot01/2026/04/20/69e589eb7a67c1057c3d452e.bin";
-                    uint8_t filePath_Len = strlen(ota_url);
-                    if(filePath_Len > sizeof(https_ota_url)-1)
-                    {   
-                        filePath_Len = sizeof(https_ota_url)-1;
-                    }
-                    
-                    memcpy(https_ota_url,ota_url,filePath_Len);
-                    https_ota_url[filePath_Len] = '\0';
-                    ESP_LOGI(MQTT_TAG, "ota_url:%s", https_ota_url);
-                    if(root != NULL)
-                    {
+                    uint8_t url_len = strlen(filePath->valuestring);
+                    if (url_len > 0 && url_len < sizeof(https_ota_url)-1) {
+                        strncpy(https_ota_url, filePath->valuestring, url_len);
+                        https_ota_url[url_len] = '\0';
+                        ESP_LOGI(MQTT_TAG, "OTA URL: %s", https_ota_url);
                         cJSON_Delete(root);
                         root=NULL;
+                        
+                        Https_Ota_Start();
+                        return;
                     }
-                    Https_Ota_Start();
+                    // uint8_t filePath_Len = strlen(ota_url);
+                    // if(filePath_Len > sizeof(https_ota_url)-1)
+                    // {   
+                    //     filePath_Len = sizeof(https_ota_url)-1;
+                    // }
+                    
+                    // memcpy(https_ota_url,ota_url,filePath_Len);
+                    // https_ota_url[filePath_Len] = '\0';
+                    // ESP_LOGI(MQTT_TAG, "ota_url:%s", https_ota_url);
+                    // cJSON_Delete(root);
+                    // root=NULL;
+                    // Https_Ota_Start();
                     return;
                     #endif
+                }else{
+
+
                 }
                 
             }else{
@@ -941,194 +984,860 @@ static void mqtt_parse_recv_data(char *data, int data_len)
     //
     //灯光
     //{"productId":"A00B","productName":"WGTL方向盘","prot":[{"736":"50"},{"737":"89"},{"738":"90"}]}
-    //for()
-    //payload = 255-4;固定四个字节 其余是dpid数据格式 dpid (2)+type(1)+len(2)+数据()
-    // {
-    // }
-    // 示例 3:设备属性行解析
-    cJSON *prot_array = cJSON_GetObjectItem(root, "prot");
-    if (prot_array != NULL && cJSON_IsArray(prot_array)) {
+    
+    // 示例 3:设备属性设置下行解析
+    //解析 Topic
+    cJSON *topic = cJSON_GetObjectItem(payload_root, "topic");//
+    if(topic == NULL || !cJSON_IsString(topic) || topic->valuestring == NULL)
+    {
+        
+        cJSON_Delete(root);
+        root = NULL;
+        return;
+    }
+    //解析payload
+    cJSON *payload = cJSON_GetObjectItem(payload_root, "payload");//
+    if(payload == NULL || !cJSON_IsObject(payload))
+    {
         
-        int prot_array_size = cJSON_GetArraySize(prot_array);
-        if(prot_array_size == 0)
+        cJSON_Delete(root);
+        root = NULL;
+        return;
+    }
+    
+    //payload 里面的子数据
+    cJSON *method = cJSON_GetObjectItem(payload, "method");//
+    if (method == NULL || !cJSON_IsString(method) || method->valuestring == NULL) {
+        
+        cJSON_Delete(root);
+        root = NULL;
+        return;
+    }
+
+    cJSON *msgId = cJSON_GetObjectItem(payload, "msgId");//
+    if (msgId == NULL || !cJSON_IsString(msgId) || msgId->valuestring == NULL) {
+       
+        cJSON_Delete(root);
+        root = NULL;
+        return;
+    }
+
+    cJSON *productId = cJSON_GetObjectItem(payload, "productId");//
+    if (productId == NULL || !cJSON_IsString(productId) || productId->valuestring == NULL) {
+        
+        pid_serialNumber_replay_json(msgId->valuestring,NULL,method->valuestring,401);
+        cJSON_Delete(root);
+        root = NULL;
+        return;
+    }
+    else{
+        char pid_str[8] = {0};
+        snprintf(pid_str,sizeof(pid_str)-1,"%04X",common_setting.mcu_info.pid);
+        if(strcmp(pid_str,productId->valuestring) != 0)
         {
+            pid_serialNumber_replay_json(msgId->valuestring,NULL,method->valuestring,401);
+            cJSON_Delete(root);
+            root = NULL;
             return;
         }
-        // 
-        uint8_t type = 1;
-        uint16_t total_data_len = 0;
-        uint16_t dpid = 0;
-        uint32_t value  = 0;
-        int type_len = 0;
-        uint8_t send_data[UART_REPLY_MAX_PAYLOAD_MQTT];
-        memset(send_data,0,UART_REPLY_MAX_PAYLOAD_MQTT);
-        ESP_LOGI(MQTT_TAG,"prot_array_size:%d",prot_array_size);
-        for (int i = 0; i < prot_array_size; i++)
+    }
+
+    cJSON *serialNumber = cJSON_GetObjectItem(payload, "serialNumber");//
+    if (serialNumber == NULL || !cJSON_IsString(serialNumber) || serialNumber->valuestring == NULL) {
+        
+        // {
+        //     "msgId": "cloud_0196415f3b1f7e2ab7f72c4e8f91c0a1",
+        //     "method": "thing.service.property.set.reply",
+        //     "time": 1777517821,
+        //     "serialNumber": "PXN1LJ1QUR078E",
+        //     "productId": "A00B",
+        //     "code": 0
+        // }
+        pid_serialNumber_replay_json(msgId->valuestring,NULL,method->valuestring,401);
+        cJSON_Delete(root);
+        root = NULL;
+        return;
+    }
+    else{
+        char serialNumber_str[34] = {0};
+        snprintf(serialNumber_str,sizeof(serialNumber_str)-1,"%s",(const char *)common_storage.net_info.serial_number);
+        if(strcmp((const char *)serialNumber_str,serialNumber->valuestring) != 0)
         {
-            // 取数组第i个元素(是一个对象)
-            cJSON *pro_item = cJSON_GetArrayItem(prot_array, i);
-            if (pro_item == NULL || !cJSON_IsObject(pro_item)) {
-                ESP_LOGI(MQTT_TAG,"%d not object\n", i);
-                continue;
-            }
-            cJSON *item = pro_item->child;
-            if (item == NULL) continue;
-
-            const char *key_str = item->string;
-            dpid=0;
-            type=1;
-            type_len = 1;
-            if(cJSON_IsString(item) && item->valuestring != NULL && key_str != NULL) //如果是字符串是不定长度 长度为
+            pid_serialNumber_replay_json(msgId->valuestring,NULL,method->valuestring,401);
+            cJSON_Delete(root);
+            root = NULL;
+            return;
+        }
+    }
+
+    //topic/PAXN1LJ1QUR0781/A00B/property/post
+    // {
+    //     "msgId": "cloud_0196415f3b1f7e2ab7f72c4e8f91c0a1",
+    //     "method": "thing.service.property.set",
+    //     "time": 1777517820,
+    //     "serialNumber": "PXN1LJ1QUR078E",
+    //     "productId": "A00B",
+    //     "params": [{"8": 1,},{"735": 80}]
+    // }
+
+    // get_publish_topic(TOPIC_PROPERTY_POST,topic_buf,sizeof(topic_buf)); 属性设置
+    if(strcmp(get_publish_topic(TOPIC_PROPERTY_POST),topic->valuestring) == 0)
+    {
+        
+        strncpy(topic_compare,topic->valuestring,sizeof(topic_compare)-1);
+        if(strcmp(get_methon(METHON_SERVICE_PROPERTY_SET),method->valuestring) == 0) //"thing.service.property.set" 服务下发属性设备参数
+        {
+            
+            if(strlen(msgId->valuestring) != 0)
             {
-                type = 5;
-                type_len= strlen(item->valuestring);//字符串长度
-                if(type_len > 32-1)
-                {
-                    type_len=32-1;
+                
+                strncpy(publish_data.msgid, msgId->valuestring, sizeof(publish_data.msgid)-1);
+                cJSON *params = cJSON_GetObjectItem(payload, "params");//
+                if (params == NULL || !cJSON_IsArray(params)) {
+                    
+                    cJSON_Delete(root);
+                    root = NULL;
+                    return;
                 }
-                if(type_len == 0) //内容是空的
-                {
-                    continue;
+                // mqtt_get_dev_property(params);
+                mqtt_set_dev_property(params);
+            }
+        }
+    }
+    // {
+    //     "msgId": "cloud_0196415f3b1f7e2ab7f72c4e8f91c0a1",
+    //     "method": "thing.service.calibration.invoke",
+    //     "time": 1777517820,
+    //     "serialNumber": "PXN1LJ1QUR078E",
+    //     "productId": "A00B",
+    //     "serviceId": "calibration",
+    //     "input": {
+    //         "mode": 1,
+    //         "timeoutSec": 30
+    //     }
+    // }
+    //"thing.service.calibration.invoke", //服务下发 设备应答
+    else if(strcmp(get_publish_topic(TOPIC_SERVICE_POST),topic->valuestring) == 0)
+    {
+        strncpy(topic_compare,topic->valuestring,sizeof(topic_compare)-1);
+        if(strcmp(get_methon(METHON_SERVICE_CALIBRATION_INVOKE),method->valuestring) == 0) //"thing.service.property.set" 服务下发属性设备参数
+        {
+            if(strlen(msgId->valuestring) != 0)
+            {
+                strncpy(publish_data.msgid, msgId->valuestring, sizeof(publish_data.msgid)-1);
+                cJSON *input = cJSON_GetObjectItem(payload, "input");//
+                if (input == NULL || !cJSON_IsArray(input)) {
+                    
+                    cJSON_Delete(root);
+                    root = NULL;
+                    return;
                 }
-                if (is_pure_number(key_str)) 
-                {
-                    dpid = atoi(key_str);//将key转换成纯数字不能有字母
-                    // ESP_LOGI(MQTT_TAG,"dpid %u\n",dpid);
+                mqtt_set_dev_property(input);
+                cJSON *replay_root = NULL;
+                cJSON *serviceId = cJSON_GetObjectItem(payload, "serviceId");//
+                if (serviceId == NULL || !cJSON_IsString(serviceId) || serviceId->valuestring == NULL) {
+                    replay_root = create_publish_ack_json(publish_data.msgid,NULL,get_methon(METHON_SERVICE_PROPERTY_SET_REPLAY));
+                    
                 }else{
-                    ESP_LOGI(MQTT_TAG,"dpid is zero\n");
-                    continue;
+                    strncpy(publish_data.serviceId, msgId->valuestring, sizeof(publish_data.serviceId)-1);
+                    replay_root = create_publish_ack_json(publish_data.msgid,serviceId->valuestring,get_methon(METHON_SERVICE_PROPERTY_SET_REPLAY));
                 }
                 
-            }else if(cJSON_IsNumber(item) || (cJSON_IsBool(item)))
-            {
-                type = 1;
-                if(item->string == NULL) //KEY 为空 如果是数字不需要判断value是为空
+                if(replay_root)
                 {
-                    continue;
-                }
-                // 1. KEY 必须纯数字 
-                if (is_pure_number(key_str) ) {
-                    value  =  (uint32_t)cJSON_GetNumberValue(item); //item->valueint;//atoi(item->valuestring); //item->valueint;
-                    dpid = atoi(key_str);
-                    if(value <= 0xff)
-                    {
-                        type = 1;
-                        type_len = 1;
-                    }else if(value <= 0xffff)
-                    {
-                        type = 2;
-                        type_len = 2;
-                    }else if(value <= 0xffffffff)
-                    {
-                        type = 4;
-                        type_len = 4;
-                    }else{
-                        ESP_LOGI(MQTT_TAG,"dayu 32byte\n");
-                        continue;
-
+                    cJSON *output = cJSON_CreateObject();
+                    cJSON_AddItemToObject(root, "output", output);  // root -> data
+                    if(output != NULL){
+                        cJSON_AddStringToObject(output, "result", "done");
+                        mqtt_send_publish_json(TOPIC_SERVICE_REPLY,replay_root);
                     }
-                    // ESP_LOGI(MQTT_TAG,"dpid %u value:%u\n",dpid,value);
-                }else{
-                    ESP_LOGI(MQTT_TAG,"is number but dpid is zero\n");
-                    continue;
+                    cJSON_Delete(replay_root);
+                    replay_root = NULL;
                 }
-                    
             }
-            if(dpid <= 0)
+        }
+    }
+    // mqtt_get_dev_test(test_dpid,20);
+    //示例 4:设备属性上报下行解析
+    // mqtt_get_dev_property(root);
+    // 释放
+    
+    if(root != NULL)
+    {
+        cJSON_Delete(root);
+        root=NULL;
+    }
+    
+}
+
+//云端下发设置设备属性值
+void mqtt_set_dev_property(const cJSON *array)
+{
+
+     // {
+    //     "serialNumber": "PXN1LJ1QUR078E",
+    //     "prot": [
+                // { "335": "#ffffff"},
+            // ]
+    
+    
+    if(array == NULL || !cJSON_IsArray(array))
+    {
+        return;
+    }
+    uint16_t array_size = cJSON_GetArraySize(array);
+    if(array_size <= 0)return;
+
+    uint16_t total_data_len = 0;
+    
+    uint8_t send_data[UART_REPLY_MAX_PAYLOAD_MQTT];
+    memset(send_data,0,UART_REPLY_MAX_PAYLOAD_MQTT);
+    ESP_LOGI(MQTT_TAG,"array_size:%d",array_size);
+    for (uint16_t i = 0; i < array_size; i++) //0-65535
+    {
+        // 取数组第i个元素(是一个对象)
+        cJSON *pro_item = cJSON_GetArrayItem(array, i);
+        if (pro_item == NULL || !cJSON_IsObject(pro_item)) {
+            ESP_LOGI(MQTT_TAG,"%d not object\n", i);
+            continue;
+        }
+        cJSON *item = pro_item->child;
+        if (item == NULL) continue;
+
+        const char *key_str = item->string;
+        if(key_str == NULL)continue;
+        uint16_t dpid = 0;
+        uint8_t type = 1;
+        uint32_t value  = 0;
+        int type_len = 0;
+        dpid=0;
+        type=1;
+        type_len = 1;
+        if(cJSON_IsString(item) && item->valuestring != NULL) //如果是字符串是不定长度 长度为
+        {
+            type = 5;
+            type_len= strlen(item->valuestring);//字符串长度
+            if(type_len > 31)
+            {
+                type_len=31;
+            }
+            if(type_len == 0) //内容是空的
             {
-                ESP_LOGI(MQTT_TAG,"dpid is invale\n");
                 continue;
             }
-            //总的长度加上4+当前数据类型的长度
-            if(total_data_len + 5 + type_len > UART_REPLY_MAX_PAYLOAD_MQTT) //去掉header+cmd+len+crc
+            // if (is_pure_number(key_str)) 
+            // {
+            //     dpid = atoi(key_str);//将key转换成纯数字不能有字母
+            //     // ESP_LOGI(MQTT_TAG,"dpid %u\n",dpid);
+            // }else{
+            //     ESP_LOGI(MQTT_TAG,"dpid is zero\n");
+            //     continue;
+            // }
+            
+        }else if(cJSON_IsNumber(item) || (cJSON_IsBool(item)))
+        {
+            type = 1;
+            value  =  (uint32_t)cJSON_GetNumberValue(item);
+            if(value <= 0xff)
             {
-                ESP_LOGI(MQTT_TAG,"i:%d UART_REPLY_MAX_PAYLOAD_MQTT-5 %d len:%d",i,UART_REPLY_MAX_PAYLOAD_MQTT,total_data_len + 5 + type_len);
-                Uart_Reply_Send(COMMON_UART_PROPERTY_SET_CMD,send_data, total_data_len,HOST_TYPE_UART);
-                total_data_len=0;
-                memset(send_data,0,UART_REPLY_MAX_PAYLOAD_MQTT);
-                vTaskDelay(5); 
+                type = 1;
+                type_len = 1;
+            }else if(value <= 0xffff)
+            {
+                type = 2;
+                type_len = 2;
+            }else if(value <= 0xffffffff)
+            {
+                type = 4;
+                type_len = 4;
+            }else{
+                ESP_LOGI(MQTT_TAG,"dayu 32byte\n");
+                continue;
+
             }
+            // 1. KEY 必须纯数字 
+            // if (is_pure_number(key_str) ) {
+            //      //item->valueint;//atoi(item->valuestring); //item->valueint;
+            //     dpid = atoi(key_str);
+                
+            //     // ESP_LOGI(MQTT_TAG,"dpid %u value:%u\n",dpid,value);
+            // }else{
+            //     ESP_LOGI(MQTT_TAG,"is number but dpid is zero\n");
+            //     continue;
+            // }
+                
+        }
+        if (!is_pure_number(key_str)) continue;
+        dpid = atoi(key_str);
+        if(dpid <= 0)
+        {
+            ESP_LOGI(MQTT_TAG,"dpid is invale\n");
+            continue;
+        }
+        //总的长度加上4+当前数据类型的长度
+        if(total_data_len + 5 + type_len > UART_REPLY_MAX_PAYLOAD_MQTT) //去掉header+cmd+len+crc
+        {
+            ESP_LOGI(MQTT_TAG,"i:%d UART_REPLY_MAX_PAYLOAD_MQTT-5 %d len:%d",i,UART_REPLY_MAX_PAYLOAD_MQTT,total_data_len + 5 + type_len);
+            Uart_Reply_Send(COMMON_UART_PROPERTY_SET_CMD,send_data, total_data_len,HOST_TYPE_UART);
+            total_data_len=0;
+            memset(send_data,0,UART_REPLY_MAX_PAYLOAD_MQTT);
+            vTaskDelay(5); 
+        }
 
-            // {
-            //     "serialNumber": "PXN1LJ1QUR078E",
-            //     "prot": [
-                        // { "335": "#ffffff"},
-                        // { "336": "#ff00ff"},
-                        // { "337": "#ff0000"},
-                        // { "338": "#00ff00"},
-                        // { "339": "#00ff00"},
-                        // { "340": "#00ff00"},
-                        // { "341": "#00ff00"},
-                        // { "342": "#00ff00"},
-                        // { "343": "#00ff00"},
-                        // { "344": "#00ff00"},
-                        // { "345": "#00ff00"},
-                    
-// { "271": "#ffffff"},
-// { "272": "#00ff00"},
-// { "273": "#00ff00"},
-// { "274": "#00ff00"},
-// { "275": "#ffffff"},
-// { "276": "#00ff00"},
-// { "277": "#00ff00"},
-// { "278": "#00ff00"},
-// { "279": "#ffffff"},
-// { "280": "#00ff00"},
-// { "281": "#00ff00"},
-// { "282": "#00ff00"},
-// { "283": "#ffffff"},
-// { "284": "#00ff00"},
-// { "285": "#00ff00"},
-            //         {"735":80},
-            //         {"736":70},
-            //         {"737":60},
-            //         {"399":"#ff0000"},
-            //         {"400":"#00ff00"},
-            //         {"401":"#0000ff"},
-
-// {"412":"00ff00"},
-// {"413":"ffffff"},
-// {"414":"ff0000"}
-
-
-            // 737 10 738 50 739 70
-            // total_data_len = 0 0 1 2 3 4 5
-            send_data[total_data_len+0] = dpid & 0xff;
-            send_data[total_data_len+1] = (dpid >> 8 )&0xff;
-            send_data[total_data_len+2] = type;//类型
-            send_data[total_data_len+3] = type_len & 0xff;
-            send_data[total_data_len+4] = (type_len >> 8)& 0xff;
-            if(type != 5) //不是字符串 copy数字
+        // 737 10 738 50 739 70
+        // total_data_len = 0 0 1 2 3 4 5
+        send_data[total_data_len+0] = dpid & 0xff;
+        send_data[total_data_len+1] = (dpid >> 8 )&0xff;
+        send_data[total_data_len+2] = type;//类型
+        send_data[total_data_len+3] = type_len & 0xff;
+        send_data[total_data_len+4] = (type_len >> 8)& 0xff;
+        if(type != 5) //不是字符串 copy数字
+        {
+            memcpy(&send_data[total_data_len+5],&value,type_len);
+        }else{ //copy字符串
+            strncpy((char *)&send_data[total_data_len+5], item->valuestring, type_len);
+        }
+        
+        total_data_len=total_data_len+5+type_len;   //12+1+5=18 18+6=24 24+6=30 30+6=36
+    }
+    if(total_data_len > 0)//发送最后一包
+    {
+        
+        Uart_Reply_Send(COMMON_UART_PROPERTY_SET_CMD,send_data, total_data_len,HOST_TYPE_UART);
+        ESP_LOGI(MQTT_TAG,"send end\n");
+    }
+}
+void mqtt_get_dev_property(const cJSON *array)
+{
+
+    if(array == NULL || !cJSON_IsArray(array)) return;
+    uint16_t array_size = cJSON_GetArraySize(array);
+    if (array_size <= 0) return;
+        // 取数组第i个元素(是一字符串数字)
+    if(array_size > 0)
+    {
+        static uint8_t send_dpid_data[UART_REPLY_MAX_PAYLOAD_MQTT]={0};
+        memset(send_dpid_data,0,UART_REPLY_MAX_PAYLOAD_MQTT);
+        uint16_t send_len = 0;
+        //         字段              字节数               说明  
+        // 帧头              1               模组到主控:0xF1  
+        // 命令              1               0x09    
+        // 数据长度                1               取决于数据字段长度     
+        // 数据              N               dpid    如:0x010203 表示查询3个dpid,分别为:0x01、0x02、0x03
+        // CRC校验           1               CRC8-ROHC       
+        
+        //["dpid1","dpid2","dpid3"...................]
+        for (int i = 0; i < array_size; i++)
+        {
+            // 取数组第i个元素(是一个对象)
+            
+            cJSON *item = cJSON_GetArrayItem(array, i);
+            ESP_LOGI(MQTT_TAG, " %d =%d | =%s",i,item ? item->type : -1,item ? item->valuestring : "null");
+            if (item == NULL || !cJSON_IsString(item) || item->valuestring == NULL) {
+                
+                continue;
+            }
+            if(!is_pure_number(item->valuestring)) continue;
+            char *dpid_str = item->valuestring;
+            
+            if(strlen(dpid_str) == 0)
+            {
+                continue;
+            }
+
+            uint16_t dpid = atoi(dpid_str);
+            if(dpid == 0)
+            {
+                continue;
+            }
+            if(send_len+sizeof(uint16_t) > UART_REPLY_MAX_PAYLOAD_MQTT)
             {
-                memcpy(&send_data[total_data_len+5],&value,type_len);
-            }else{ //copy字符串
-                strncpy((char *)&send_data[total_data_len+5], item->valuestring, type_len);
+                Uart_Reply_Send(COMMON_UART_PROPERTY_BATCH_REPORT_CMD,send_dpid_data, send_len,HOST_TYPE_UART);
+                send_len=0;
+                memset(send_dpid_data,0,UART_REPLY_MAX_PAYLOAD_MQTT);
+                vTaskDelay(10); 
             }
+            send_dpid_data[send_len++] = (dpid >> 8) & 0xFF;
+            send_dpid_data[send_len++] = dpid & 0xFF;
+            ESP_LOGI(MQTT_TAG,"dpid:%d send_len %d\n",dpid,send_len);
             
-            total_data_len=total_data_len+5+type_len;   //12+1+5=18 18+6=24 24+6=30 30+6=36
         }
-        if(total_data_len > 0)//发送最后一包
+        if(send_len > 0)
         {
-            ESP_LOGI(MQTT_TAG,"total_data_len:%d dpid:%u value:%u type:%d type_len:%u\n",total_data_len,dpid,value,type,type_len);
-            Uart_Reply_Send(COMMON_UART_PROPERTY_SET_CMD,send_data, total_data_len,HOST_TYPE_UART);
-            ESP_LOGI(MQTT_TAG,"send end\n");
+            Uart_Reply_Send(COMMON_UART_PROPERTY_BATCH_REPORT_CMD,send_dpid_data, send_len,HOST_TYPE_UART);
+            send_len=0;
         }
     }
-    // 释放
-    if(root != NULL)
+}
+
+
+//云端获取设备属性上报
+// data 是一个数组 ["dpid1","dpid2","dpid3"...........]
+void mqtt_get_dev_test(uint16_t *dpid,uint8_t num)
+{
+
+    uint8_t send_dpid_data[UART_REPLY_MAX_PAYLOAD_MQTT]={0};
+    memset(send_dpid_data,0,UART_REPLY_MAX_PAYLOAD_MQTT);
+    uint16_t send_len = 0;
+    //         字段          字节数               说明  
+    // 帧头          1               模组到主控:0xF1  
+    // 命令          1               0x09    
+    // 数据长度            1               取决于数据字段长度     
+    // 数据          N               dpid    如:0x010203 表示查询3个dpid,分别为:0x01、0x02、0x03
+    // CRC校验               1               CRC8-ROHC       
+    
+    //["dpid1","dpid2","dpid3"...................]
+    for (int i = 0; i < num; i++)
+    {
+        // 取数组第i个元素(是一个对象)
+
+
+        if(send_len+sizeof(uint16_t) > UART_REPLY_MAX_PAYLOAD_MQTT)
+        {
+            Uart_Reply_Send(COMMON_UART_PROPERTY_BATCH_REPORT_CMD,send_dpid_data, send_len,HOST_TYPE_UART);
+            send_len=0;
+            memset(send_dpid_data,0,UART_REPLY_MAX_PAYLOAD_MQTT);
+            vTaskDelay(10); 
+        }
+        send_dpid_data[send_len++] = (dpid[i] >> 8) & 0xFF;
+        send_dpid_data[send_len++] = dpid[i] & 0xFF;
+        ESP_LOGI(MQTT_TAG,"dpid:%d send_len %d\n",dpid[i],send_len);
+        
+    }
+    if(send_len > 0)
+    {
+        Uart_Reply_Send(COMMON_UART_PROPERTY_BATCH_REPORT_CMD,send_dpid_data, send_len,HOST_TYPE_UART);
+        send_len=0;
+    }
+}
+
+
+// 发送一帧完整JSON 带topic root需要发送的json对象 内部转成josn字符串立即发送
+uint8_t mqtt_send_publish_json(TOPIC_TYPE topic_type,cJSON *root)
+{
+    if (!Mqtt_Get_Connect_Flag() || root == NULL) return 0;
+    const char *topic = get_publish_topic(topic_type);
+    if (topic == NULL || strlen(topic) == 0)
+        return 0;
+    // 转成无格式字符串(最小长度)
+    char *json_str = cJSON_PrintUnformatted(root);
+    if (!json_str) return 0;
+    
+    // 
+    mqtt_send_msg_t send_msg={0};
+    memcpy(send_msg.data,json_str,strlen(json_str));
+    ESP_LOGI(MQTT_TAG, "ack CJSON:%s %d", json_str,strlen(json_str));
+    free(json_str);
+    json_str = NULL;
+
+    memcpy(send_msg.topic,topic,strlen(topic));
+    
+    if(mqtt_dev_report_queue_handle==NULL)
+    {
+        return 0;
+    }
+
+    if(user_esp_mqtt_client_publish(send_msg.data,strlen(send_msg.data),send_msg.topic) != pdTRUE)
+    {   
+        ESP_LOGI(MQTT_TAG, "ack faile \n");
+        return 0;
+    }else{
+        return 1;
+        ESP_LOGI(MQTT_TAG, "ack OK\n");
+    }
+    
+}
+    
+//获取json大小
+static uint32_t get_json_size(cJSON *root)
+{
+    if (!root) return 0;
+    
+    char *str = cJSON_PrintUnformatted(root);
+    if (!str) return 0;
+    
+    uint32_t len = strlen(str);
+    free(str);
+    return len;
+}
+
+
+
+
+//设备应答云端公共函数
+// service_id: 传入服务ID 如 "calibration"
+// method: 传入方法名 如 "thing.service.calibration.invoke.reply"
+cJSON* create_publish_ack_json(const char* msgId,const char* service_id, const char* method)
+{
+    cJSON *root = cJSON_CreateObject();
+    if (root == NULL) 
+        return NULL;
+    if(strlen(msgId) == 0)
+    {
+        return NULL;
+    }
+    static char pid_str[8] = {0};
+    snprintf(pid_str, sizeof(pid_str)-1, "%04X", common_setting.mcu_info.pid);
+
+    // 
+    time_t Time_Sec=Get_Time_Stamp();
+    static char time_str[16]={0};
+    snprintf(time_str,sizeof(time_str)-1,"%lld",Time_Sec);
+
+    cJSON_AddStringToObject(root, "msgId", msgId);
+    cJSON_AddStringToObject(root, "method", method);
+    cJSON_AddStringToObject(root, "time", time_str);
+    cJSON_AddStringToObject(root, "productId", pid_str);
+    cJSON_AddStringToObject(root, "serialNumber", (const char *)common_storage.net_info.serial_number);
+    if(service_id != NULL)
+    {
+        if(strlen(service_id)==0)
+        {
+            cJSON_AddStringToObject(root, "serviceId", "calibration");
+        }else{
+            cJSON_AddStringToObject(root, "serviceId", service_id);
+        }
+       
+    }
+    
+    cJSON_AddNumberToObject(root, "code", 0);       // 注意:code 是数字!
+    cJSON_AddStringToObject(root, "message", "ok");
+    return root;
+}
+//不带code message 的回复
+cJSON* create_publish_post_json(const char* msgId,const char* service_id, const char* method)
+{
+    cJSON *root = cJSON_CreateObject();
+    if (root == NULL) 
+        return NULL;
+    if(msgId != NULL)
+    {
+        if(strlen(msgId) == 0)
+        {
+            return NULL; 
+        }
+    }else{
+        return NULL;
+    }
+    static char pid_str[8] = {0};
+    snprintf(pid_str, sizeof(pid_str)-1, "%04X", common_setting.mcu_info.pid);
+
+    // 
+    time_t Time_Sec=Get_Time_Stamp();
+    static char time_str[16]={0};
+    snprintf(time_str,sizeof(time_str)-1,"%lld",Time_Sec);
+
+    cJSON_AddStringToObject(root, "msgId", msgId);
+    cJSON_AddStringToObject(root, "method", method);
+    cJSON_AddStringToObject(root, "time", time_str);
+    cJSON_AddStringToObject(root, "productId", pid_str);
+    cJSON_AddStringToObject(root, "serialNumber", (char *)common_storage.net_info.serial_number);
+    if(service_id != NULL)
+    {
+        if(strlen(service_id)==0)
+        {
+            cJSON_AddStringToObject(root, "serviceId", "calibration");
+        }else{
+            cJSON_AddStringToObject(root, "serviceId", service_id);
+        }
+    }
+    return root;
+}
+
+//pid serialcNumber 不一致应答
+cJSON* pid_serialNumber_replay_json(const char* msgId,const char* service_id, const char* method,uint16_t code)
+{
+    cJSON *root = cJSON_CreateObject();
+    if (root == NULL) 
+        return NULL;
+
+    if(msgId != NULL)
+    {
+        if(strlen(msgId) == 0)
+        {
+            return NULL; 
+        }
+    }else{
+        return NULL;
+    }
+    static char pid_str[8] = {0};
+    snprintf(pid_str, sizeof(pid_str)-1, "%04X", common_setting.mcu_info.pid);
+
+    // 
+    time_t Time_Sec=Get_Time_Stamp();
+    static char time_str[16]={0};
+    snprintf(time_str,sizeof(time_str)-1,"%lld",Time_Sec);
+    cJSON_AddStringToObject(root, "msgId", msgId);
+    cJSON_AddStringToObject(root, "method", method);
+    cJSON_AddStringToObject(root, "time", time_str);
+    cJSON_AddStringToObject(root, "productId", pid_str);
+    cJSON_AddStringToObject(root, "serialNumber", (char *)common_storage.net_info.serial_number);
+    if(service_id != NULL) //如果是服务应答需要加这个字段 不是就不加
+    {
+        if(strlen(service_id)==0)
+        {
+            cJSON_AddStringToObject(root, "serviceId", "calibration");
+        }else{
+            cJSON_AddStringToObject(root, "serviceId", service_id);
+        } 
+    }
+    
+    cJSON_AddNumberToObject(root, "code", code);       // 注意:code 是数字!
+    return root;
+}
+typedef enum{
+    MODE_ACK=0, //应答
+    MODE_REPORT, //主动上报
+
+}ACK_POST;
+//设备属性主动上报 收到0x09之后串口返回的数据通过0x07接收到 发给mqtt服务器
+//cmd 预留
+//data 真实数据 
+//len 数据实际大小
+//格式 dpid type len 数据 type可以不解析预留
+//格式 dpid(2) type(1) len(2) data type==5是字符串需要换成字符串发送给mqtt
+char *get_devMsgId(void)
+{
+    static char msgId[64]={0};
+    uint8_t mac[6] = {0};
+    esp_read_mac(mac, ESP_MAC_BT);//获取mac地址
+    snprintf(&msgId[0], sizeof(msgId)-1,"dev_");
+    uint8_t dev_str_len = strlen("dev_");
+    snprintf(&msgId[4], (sizeof(msgId)-1)-dev_str_len,"%02X%02X-", mac[4], mac[5]);
+    time_t Time_Sec = Get_Time_Stamp();
+    snprintf(&msgId[9],(sizeof(msgId)-1)-dev_str_len-4,"%lld",Time_Sec);
+    return msgId;
+}
+uint8_t dev_report_property(uint8_t cmd,uint8_t *data,uint8_t len)
+{
+    strncpy(publish_data.msgid,cloud_msgID,strlen(cloud_msgID));
+    uint8_t mode = 0; //0是使用云端生成下发的 属于应答 1 是使用设备端生成的 属于设备主动上报的
+    //应答
+    if(strcmp(topic_compare,get_methon(METHON_SERVICE_PROPERTY_SET)) == 0) //属性设置需要应答
+    {
+        mode=MODE_ACK;
+
+    }
+    //主动上报 
+    else if(strcmp(topic_compare,get_methon(METHON_EVENT_PROPERTY_POST)) == 0)
+    {
+        mode=MODE_REPORT;
+    }
+    
+    // {
+    //     "msgId": "dev_078E_12_1777518245123_0007",
+    //     "method": "thing.event.property.post",
+    //     "time": 1777518245,
+    //     "serialNumber": "PXN1LJ1QUR078E",
+    //     "productId": "A00B",
+    //     "params": {
+    //         "735": 80
+    //     }
+    // }
+    // 必须至少1个dpid的最小长度 2+1+2 =5 
+    if (len <= 5 || data == NULL) {
+        return 0;
+    }
+    uint16_t offset = 0;
+
+    // 循环解析所有的DPID(自动处理可变的长度)
+//             DF 02 01 01 00 64 E0 02 01 01 00 64 E1 02 01 01 00 64 00 
+       // ESP_LOGI(MQTT_TAG,"dev_report_dev_property len=%d\n",len);
+    cJSON *root = NULL;
+    switch (mode)
+    {
+        case MODE_ACK:
+            root = create_publish_ack_json(publish_data.msgid,NULL,get_methon(METHON_SERVICE_PROPERTY_SET_REPLAY));
+            /* code */
+            break;
+        case MODE_REPORT:
+
+            root = create_publish_post_json((const char *)get_devMsgId(),NULL,get_methon(METHON_EVENT_PROPERTY_POST));
+            break;
+        
+        default:
+            break;
+    }
+    
+    if (root == NULL) return 0;
+    
+    cJSON *prot_array = cJSON_CreateArray();
+    if(prot_array == NULL)
     {
         cJSON_Delete(root);
-        root=NULL;
+        return 0;
     }
+    cJSON_AddItemToObject(root, "params", prot_array);
+    // 把设备信息加到里面
+    // {
+    //     "prot":[{"key":value},{"key":value},{"key":value}]
+    // }
+
+    while (1)
+    {
+               if(offset+5 > len)
+               {
+                       // ESP_LOGI(MQTT_TAG,"offset+5=%d, len=%d\n",offset+5,len);
+                       break;
+               }
+        // 1. 取 DPID (2个字节) //大端序
+        uint16_t dpid = data[offset + 0] | (data[offset + 1] << 8);
+
+        uint8_t data_type = data[offset+2];//type
+        // 2. 取数据长度(2个字节)
+        uint16_t data_len = data[offset + 3] | (data[offset + 4] << 8);
+
+        // 3. 检查剩余的长度够不够
+        if (offset + 5 + data_len > len || data_len  > 63 || data_len == 0) {
+                       // ESP_LOGI(MQTT_TAG,"offset + 5 + data_len=%d, len=%d\n",offset + 5 + data_len,data_len);
+            break;
+        }
+        static char key[12]= {0};
+        snprintf(key,sizeof(key)-1,"%d",dpid);
+
+        uint32_t current_json_len = get_json_size(root);
+        uint32_t expect_add_len = strlen(key) + data_len + 8; // 8是引号、冒号等符号预留  "":"","":""
+
+               if (current_json_len + expect_add_len >= 512)
+        {
+            // 发送旧包
+            // ESP_LOGI(MQTT_TAG,"current_json_len=%d, expect_add_len=%d\n",current_json_len,expect_add_len);
+            switch (mode)
+            {
+                case MODE_ACK:
+                    mqtt_send_publish_json(TOPIC_PROPERTY_REPLY,root);
+                    /* code */
+                    break;
+                case MODE_REPORT:
+                    mqtt_send_publish_json(TOPIC_PROPERTY_REPORT,root);
+                    break;
+                
+                default:
+                    break;
+            }
+            
+            vTaskDelay(1);
+            // 销毁旧包,建新包
+            cJSON_Delete(root);
+            root = NULL;
+            switch (mode)
+            {
+                case MODE_ACK:
+                    root = create_publish_ack_json(publish_data.msgid,NULL,get_methon(METHON_SERVICE_PROPERTY_SET_REPLAY));
+                    /* code */
+                    break;
+                case MODE_REPORT:
+                    root = create_publish_post_json((const char *)get_devMsgId(),NULL,get_methon(METHON_EVENT_PROPERTY_POST));
+                    break;
+                
+                default:
+                    break;
+            }
+            
     
+            if (root == NULL) return 0;
+            
+            prot_array = cJSON_CreateArray();
+            if(!prot_array)
+            {
+                cJSON_Delete(root);
+                return 0;
+            }
+            cJSON_AddItemToObject(root, "params", prot_array);
+        }
+        
+        cJSON *item = cJSON_CreateObject();
+        if(item == NULL)
+        {
+            break;
+        }
+        if(dpid == 6) //dpid==6是模组的serialNumber 不使用传参的value 使用本地的数据添加json
+        {
+            cJSON_AddStringToObject(item, key,(const char *)common_storage.net_info.serial_number);
+        }else{
+            if(data_type == 5) //字符串
+            {
+                static char str_buf[64] = {0};
+                uint8_t copy_len = data_len > 64 ? 64 : data_len;
+                memcpy(str_buf, &data[offset + 5], copy_len);
+                str_buf[copy_len] = 0; // 强制结束,防止乱码
+
+                // ESP_LOGI(MQTT_TAG, "DPID=%d, 字符串: %s", dpid, str_buf);
+                cJSON_AddStringToObject(item, key, str_buf);
+            }else{ //数字
+                uint32_t value = 0;
+                memcpy(&value,&data[offset + 5],data_len);
+                cJSON_AddNumberToObject(item, key, value);
+            }
+        }
+        cJSON_AddItemToArray(prot_array, item);
+        // ==============================
+        // 根据类型解析数据
+        // ==============================
+        offset+=5+data_len;
+    }
+    // 发送最后一包
+    if (root != NULL)
+    {
+       switch (mode)
+        {
+            case MODE_ACK:
+                mqtt_send_publish_json(TOPIC_PROPERTY_REPLY,root);
+                /* code */
+                break;
+            case MODE_REPORT:
+                mqtt_send_publish_json(TOPIC_PROPERTY_REPORT,root);
+                break;
+            
+            default:
+                break;
+        } 
+        cJSON_Delete(root);
+    }
+   
+    root=NULL;
+    return 1;
+}
+
+
+
+
+uint8_t uart_send_iot_data(uint8_t cmd,uint8_t *data,uint8_t len)
+{
+    if(data == NULL || len == 0 || mqtt_dev_report_queue_handle == NULL)
+    {
+        return 0;
+    }
+    static mqtt_dev_report_msg_t send_msg={0};
+    memcpy(send_msg.data,data,len);
+    send_msg.len = (len > sizeof(send_msg.data)) ? sizeof(send_msg.data):len;
+    send_msg.cmd = cmd;
+    
+    if (xQueueSend(mqtt_dev_report_queue_handle, &send_msg, 0) != pdTRUE) {
+        ESP_LOGW(MQTT_TAG, "rev_dev_data if full\n");
+        return 0;
+    }
+    return 1;
 }
 
 
 
+int user_esp_mqtt_client_publish(char *data,uint16_t data_len,char *topic)
+{
+    if(data == NULL || topic == NULL || data_len == 0 || common_setting.mqtt_client_handle == NULL)
+    {
+        return -1;
+    }
+    int ret = esp_mqtt_client_publish(common_setting.mqtt_client_handle,topic,\
+    data,data_len,0, 0 );
+    return ret;
+
+}
+
 static void Mqtt_Init_Task_Cb(void *p)
 {
-    mqtt_recv_msg_t recv_msg;
-    mqtt_send_msg_t send_msg;
+    static mqtt_recv_msg_t recv_msg;
+    static mqtt_dev_report_msg_t send_msg;
     while (1)
     {
         if(mqtt_recv_queue_handle != NULL){
@@ -1143,16 +1852,30 @@ static void Mqtt_Init_Task_Cb(void *p)
                 // 1. JSON 解析
             }
         }
-        if(mqtt_send_queue_handle != NULL){
-            if (xQueueReceive(mqtt_send_queue_handle, &send_msg, 0) == pdTRUE) {
-                if (common_setting.mqtt_user_cfg.mqtt_connect_flag == 1 && common_setting.wifi_status.wifi_state == 1) {
-                    ESP_LOGI(MQTT_TAG, "queue: msg_id=%s %s", send_msg.topic,send_msg.data);
-                    esp_mqtt_client_publish(common_setting.mqtt_client_handle,send_msg.topic,\
-                        send_msg.data,strlen(send_msg.data),\
-                        0, 0
-                    );
+        //设备上报
+        if(mqtt_dev_report_queue_handle != NULL){
+            if (xQueueReceive(mqtt_dev_report_queue_handle, &send_msg, 0) == pdTRUE) {
+                if (Mqtt_Get_Connect_Flag()) 
+                {
+                    switch (send_msg.cmd)
+                    {
+                        case 0x07:
+                            dev_report_property(send_msg.cmd,send_msg.data,send_msg.len);
+                            break;
+                        
+                        default:
+                            break;
+                    }
                     
                 }
+                // if (common_setting.mqtt_user_cfg.mqtt_connect_flag == 1 && common_setting.wifi_status.wifi_state == 1) {
+                //     ESP_LOGI(MQTT_TAG, "queue: msg_id=%s %s", send_msg.topic,send_msg.data);
+                //     esp_mqtt_client_publish(common_setting.mqtt_client_handle,send_msg.topic,
+                //         send_msg.data,strlen(send_msg.data),
+                //         0, 0
+                //     );
+                    
+                // }
             }
         }
         vTaskDelay(10 / portTICK_PERIOD_MS);
@@ -1167,8 +1890,9 @@ void Mqtt_Init_Task(void)
     mqtt_init_task_flag=1;
 
     mqtt_recv_queue_handle = xQueueCreateStatic(MQTT_RECV_QUEUE_LENGTH, MQTT_RECV_QUEUE_ITEM_SIZE, mqtt_recv_queue_storage, &mqtt_recv_queue_buffer);
-    mqtt_send_queue_handle = xQueueCreateStatic(MQTT_SEND_QUEUE_LENGTH, MQTT_SEND_QUEUE_ITEM_SIZE, mqtt_send_queue_storage, &mqtt_send_queue_buffer);
+    mqtt_dev_report_queue_handle = xQueueCreateStatic(MQTT_SEND_QUEUE_LENGTH, MQTT_SEND_QUEUE_ITEM_SIZE, mqtt_dev_report_queue_storage, &mqtt_dev_report_queue_buffer);
     
+
     
     mqtt_connect_task_handler = xTaskCreateStatic(Mqtt_Init_Task_Cb, "mqtt_task", MQTT_CONNECT_TASK_STACK, NULL, 1, mqtt_connect_task_stack, &mqtt_connect_task_tcb);
      
index aaff9be..291e391 100644 (file)
@@ -4,6 +4,37 @@
 #define ENABLE_MQTT_FUNC 1
 #if ENABLE_MQTT_FUNC
 
+typedef enum{
+    METHON_SERVICE_PROPERTY_SET=0,//服务属性设置下发methon
+    METHON_SERVICE_PROPERTY_SET_REPLAY, //设备属性设置应答
+    
+    METHON_EVENT_PROPERTY_POST, //设备属性事件主动上报
+
+    METHON_SERVICE_CALIBRATION_INVOKE, //云端下发 服务 
+    METHON_SERVICE_CALIBRATION_INVOKE_REPLAY,//设备应答云端下发服务
+
+}METHON_MODE;
+
+typedef enum {
+    TOPIC_PROPERTY_POST=0,    //属性下发
+    TOPIC_PROPERTY_REPLY,    // 属性应答
+
+    TOPIC_PROPERTY_REPORT,   // 主动上报
+    
+    TOPIC_SERVICE_POST,        //服务下发
+    TOPIC_SERVICE_REPLY      // 服务应答
+} TOPIC_TYPE;
+
+#define MSGID_STR_MAX 64
+#define METHON_STR_MAX 64
+#define SERVICEID_STR_MAX 64
+typedef struct {
+    char msgid[MSGID_STR_MAX+1];          // msgid
+    char methon[METHON_STR_MAX+1];       // methon
+    char serviceId[SERVICEID_STR_MAX+1];       // serviceId
+    
+} mqtt_pulish_data_t;
+extern mqtt_pulish_data_t publish_data;
 #define MQTT_SEND_RECV_DATA_BUF_SIZE 512
 
 #define MQTT_TOPIC  "sdk/test/python"
@@ -34,8 +65,15 @@ typedef struct {
     char data[MQTT_SEND_RECV_DATA_BUF_SIZE];
 } mqtt_send_msg_t;
 
+typedef struct {
+    uint8_t len;
+    uint8_t data[MQTT_SEND_RECV_DATA_BUF_SIZE];
+    uint8_t cmd;
+} mqtt_dev_report_msg_t;
+
+
 #define MQTT_RECV_QUEUE_ITEM_SIZE   sizeof(mqtt_recv_msg_t)
-#define MQTT_SEND_QUEUE_ITEM_SIZE   sizeof(mqtt_send_msg_t)
+#define MQTT_SEND_QUEUE_ITEM_SIZE   sizeof(mqtt_dev_report_msg_t)
 #define MQTT_CONNECT_TASK_STACK            (4*1024)
 extern TaskHandle_t mqtt_connect_task_handler;
 extern StackType_t mqtt_connect_task_stack[MQTT_CONNECT_TASK_STACK];
@@ -45,19 +83,27 @@ extern uint8_t mqtt_recv_queue_storage[MQTT_RECV_QUEUE_LENGTH * sizeof(mqtt_recv
 extern QueueHandle_t mqtt_recv_queue_handle;
 extern StaticQueue_t mqtt_recv_queue_buffer;
 
-extern uint8_t  mqtt_send_queue_storage[MQTT_SEND_QUEUE_LENGTH * sizeof(mqtt_send_msg_t)];
-extern QueueHandle_t mqtt_send_queue_handle;
-extern StaticQueue_t mqtt_send_queue_buffer;
-
+extern uint8_t  mqtt_dev_report_queue_storage[MQTT_SEND_QUEUE_LENGTH * sizeof(mqtt_dev_report_msg_t)];
+extern QueueHandle_t mqtt_dev_report_queue_handle;
+extern StaticQueue_t mqtt_dev_report_queue_buffer;
 
+int user_esp_mqtt_client_publish(char *data,uint16_t data_len,char *topic);
 void Mqtt_Connect_Status_Check(void);
 void Mqtt_Send_Data(void);
 void Mqtt_Recv_Data(char *topic,int topic_len,char *data,int data_len);
 void Mqtt_Init_Task(void);
 void Mqtt_Disconnect(void);
-void Mqtt_Get_Key_Led_Color(uint8_t *color_data,uint16_t color_len);
 void Mqtt_Send_Mcu_Info(void);
 uint8_t Mqtt_Get_Connect_Flag(void);
 void Mqtt_Send_Connect_Status(void);//发送mqtt连接状态给主控
+void mqtt_set_dev_property(const cJSON *array);
+void mqtt_get_dev_property(const cJSON *array);
+uint8_t dev_report_property(uint8_t cmd,uint8_t *data,uint8_t len);
+uint8_t uart_send_iot_data(uint8_t cmd,uint8_t *data,uint8_t len);
+cJSON* create_publish_ack_json(const char* msgId,const char* service_id, const char* method);
+cJSON* create_publish_post_json(const char* msgId,const char* service_id, const char* method);
+cJSON* pid_serialNumber_replay_json(const char* msgId,const char* service_id, const char* method,uint16_t code);
+uint8_t mqtt_send_publish_json(TOPIC_TYPE topic_type,cJSON *root);
+void mqtt_parse_recv_data(char *buf, int data_len);
 #endif
 #endif
\ No newline at end of file
index 5e97160..6c78dad 100644 (file)
@@ -96,7 +96,8 @@ static void event_handler(void* arg, esp_event_base_t event_base,
             case WIFI_EVENT_STA_DISCONNECTED:
             {
                 #if ENABLE_MQTT_FUNC
-                Mqtt_Disconnect();
+                //Mqtt_Disconnect();
+                // xEventGroupSetBits(common_event_group, COMMON_MQTT_DISCONNECT_BIT);
                 #endif
                 wifi_event_sta_disconnected_t* disconnected = (wifi_event_sta_disconnected_t*) event_data;
                 ESP_LOGE(WIFI_TAG, "Disconnect reason : %d", disconnected->reason);
@@ -167,13 +168,12 @@ static void event_handler(void* arg, esp_event_base_t event_base,
                 
                 #else
                 #if NIMBLE_NETWORK_MODE
-                if(common_setting.ble_status.nimble_flag) //在配网状态下 不允许连接mqtt
+                if(common_setting.ble_status.ble_adv_flag) //在广播状态下 不允许连接mqtt
                 {
                     xEventGroupSetBits(s_wifi_event_group, WIFI_CONNECTED_BIT);
                 }else{
-                    if(common_setting.wifi_status.connect_mode == 3 || common_setting.mqtt_user_cfg.mqtt_start_flag == 1)//已经连过一次了
+                    if(common_setting.wifi_status.connect_mode == 3 || common_setting.ble_status.nimble_flag == 1)//已经连过一次了
                     {   
-                        
                         xEventGroupSetBits(common_event_group, COMMON_MQTT_CONNECT_BIT);
                     }
                 }
@@ -324,12 +324,8 @@ void Wifi_Stop(void)
         xSemaphoreGive(wifi_scan_mutex);
         common_setting.wifi_status.wifi_mode = 0;
         common_setting.wifi_status.wifi_state = 0;
-        // common_setting.net_pairing_info.http_url_flag = 0;
-        // common_setting.net_pairing_info.http_token_flag = 0;
-        // common_setting.net_pairing_info.user_id_flag = 0;
     }
 }
-
 static void print_auth_mode(int authmode)
 {
     switch (authmode) {
@@ -686,6 +682,7 @@ void Wifi_Enable_Status_Check(void)
         bits_last = (bits&(WIFI_CONNECTED_BIT | WIFI_FAIL_BIT));
         if (bits & WIFI_CONNECTED_BIT)
         {
+            xEventGroupClearBits(s_wifi_event_group, WIFI_CONNECTED_BIT);
             ESP_LOGI(WIFI_TAG, "wifi connected %d\n",common_setting.wifi_status.connect_mode);
             Wifi_Connect_Timerout_Stop();//关闭定时器
             #if (1)
@@ -745,6 +742,7 @@ void Wifi_Enable_Status_Check(void)
         }
         else if (bits & WIFI_FAIL_BIT)
         {
+            
             ESP_LOGI(WIFI_TAG, "wifi connect fail\n");
             Wifi_Connect_Timerout_Stop();//连接失败了就关闭定时器
             if((common_setting.wifi_status.connect_mode == 1 || common_setting.wifi_status.connect_mode == 2))
@@ -755,30 +753,27 @@ void Wifi_Enable_Status_Check(void)
                 // wifi_pairing_reply.send_flag = 1;
                 // wifi_pairing_reply.cmd = 0x15;
                 // wifi_pairing_reply.len = 3;
+                uint8_t fail_reson = 0;
                 if(bits & WIFI_AP_NOT_FOUND_BIT)
                 {
-                    replay_buff[0] = 2;
+                    xEventGroupClearBits(s_wifi_event_group, WIFI_AP_NOT_FOUND_BIT);
+                    fail_reson = 2;
                     // wifi_pairing_reply.content[0] = 2;
                 }
                 else if(bits & WIFI_PWD_FAIL_BIT)
                 {
-                    replay_buff[0] = 3;
-                    // wifi_pairing_reply.content[0] = 3;
+                    xEventGroupClearBits(s_wifi_event_group, WIFI_PWD_FAIL_BIT);
+                    fail_reson = 3;
                 }
-                else
+                else if(bits & WIFI_FAIL_BIT)
                 {
-                    replay_buff[0] = 1;
-                    // wifi_pairing_reply.content[0] = 1;
+                    xEventGroupClearBits(s_wifi_event_group, WIFI_FAIL_BIT);
+                    fail_reson=1;
                 }
+                replay_buff[0] = fail_reson;
                 replay_buff[1] = common_setting.wifi_status.connect_mode-1;
                 replay_buff[2] = common_setting.wifi_status.net_pair_encrypt_profile;
-
-                // wifi_pairing_reply.content[1] = common_setting.wifi_status.connect_mode-1;
-                // wifi_pairing_reply.content[2] = common_setting.wifi_status.net_pair_encrypt_profile;
                 Ble_Pairing_Reply(0x15, replay_buff, 3, HOST_TYPE_BLE);
-
-                // Ble_Pairing_Reply(wifi_pairing_reply.cmd, wifi_pairing_reply.content, wifi_pairing_reply.len, HOST_TYPE_BLE);
-
             }
         }
         else