#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)
{
* @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)
{
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;
{
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);
}
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;
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");
}
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表示未发送过
{
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);
char *post_data = cJSON_Print(root);
// char *post_data = cJSON_PrintUnformatted(root);
cJSON_Delete(root);
-
+ root=NULL;
if (post_data == NULL) return;
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发过来的数据
//断开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 数据
// 是否是纯数字
}
return true;
}
-char msgID[64]={0};
+
// 云端 version 转 16 进制版本号(例如 1.03 → 0x0103)
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;
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-
// --------------------
// 合成 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;
}
// }
// 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{
//
//灯光
//{"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){
// 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);
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);