当服务器发布消息的时候,会进入此函数,对数据进行解析数据,数据格式为json格式,如代码所示。
- u8 MQTT_Publish(unsigned char* data,int len)
- {
- int buflen = sizeof(buf);
- int rc = 0;
- unsigned char dup;
- int qos;
- unsigned char retained = 0;
- unsigned short msgid = 1;
- int payloadlen_in;
- unsigned char* payload_in;
- MQTTString receivedTopic;
-
- cJSON *json , *json_params, *json_id, *json_led, *json_display;
-
- memcpy(buf,data,len);
-
- rc = MQTTDeserialize_publish(&dup, &qos, &retained, &msgid, &receivedTopic,&payload_in, &payloadlen_in, (unsigned char*)buf, buflen); //服务器有推送信息
- printf("message arrived : %s\r\n", payload_in);
-
- json = cJSON_Parse((char *)payload_in); //解析数据包
- if (!json)
- {
- printf("Error before: [%s]\r\n",cJSON_GetErrorPtr());
- }
- else
- {
- json_id = cJSON_GetObjectItem(json , "id");
- if(json_id->type == cJSON_String)
- {
- printf("id:%s\r\n", json_id->valuestring);
- }
- json_params = cJSON_GetObjectItem(json , "params");
- if(json_params)
- {
- if(cJSON_GetObjectItem(json_params, "LED0"))
- {
- json_led = cJSON_GetObjectItem(json_params, "LED0");
- if(json_led->type == cJSON_Number)
- {
- printf("LED:%d\r\n", json_led->valueint);
- if(json_led->valueint == 1)
- {
- LED0 = 0;
- }
- else
- {
- LED0 = 1;
- }
- }
- }
- if(cJSON_GetObjectItem(json_params, "display"))
- {
- json_display = cJSON_GetObjectItem(json_params, "display");
- if (json_display->type == cJSON_String)
- {
- //暂不处理
- }
- }
- }
- }
- cJSON_Delete(json);
-
- return TRUE;
- }
|