修改后的全部代码:
https://blog.csdn.net/cainiaofu/article/details/114262377?spm=1001.2014.3001.5501
1、首先,编写LED驱动,生成设备节点
我的led设备系节点是:/dev/dtsled
2、修改源码
注:源码位于src/mqtt/example/mqtt_example.c,在此基础上进行修改。
//云端下发数据函数
void example_message_arrive(void *pcontext, void *pclient, iotx_mqtt_event_msg_pt msg)
{
int fd;
const char *leds = "/dev/dtsled";
cJSON *json = NULL;
cJSON *json_params = NULL;
cJSON *json_id = NULL;
cJSON *json_led = NULL;
iotx_mqtt_topic_info_t *topic_info = (iotx_mqtt_topic_info_pt) msg->msg;
switch (msg->event_type) {
case IOTX_MQTT_EVENT_PUBLISH_RECEIVED:
EXAMPLE_TRACE("Topic : %.*s", topic_info->topic_len, topic_info->ptopic);
EXAMPLE_TRACE("Payload: %.*s", topic_info->payload_len, topic_info->payload);
EXAMPLE_TRACE("\n");
/*函数:cJSON_Parse,用于解析数据包
使用该函数会通过malloc()函数在内存中开辟一个空间,使用完成需要手动释放,cJSON_Delete(json);
*/
json = cJSON_Parse(topic_info->payload);
if (!json)
{
HAL_Printf("Error before: [%s]\r\n",cJSON_GetErrorPtr());
}
else
{
json_id = cJSON_GetObjectItem(json , "id");
if(json_id->type == cJSON_String)
{
HAL_Printf("id:%s\r\n", json_id->valuestring);
}
json_params = cJSON_GetObjectItem(json , "params");
if(json_params)
{
/*cJSON_GetObjectItem()函数
从cJSON结构体中查找某个子节点名称(键名称),如果查找成功可把该子节点序列化到cJSON结构体中。
结构体的成员有:*/
typedef struct cJSON {
struct cJSON*next,*prev; /* 遍历数组或对象链的前向或后向链表指针*/
struct cJSON *child; /*数组或对象的孩子节点*/
int type; /* key的类型*/
char *valuestring; /*字符串值*/
int valueint; /* 整数值*/
char *string; /* key的名字*/
} cJSON;
*/
if(cJSON_GetObjectItem(json_params, "led"))
{
json_led = cJSON_GetObjectItem(json_params, "led");
if(json_led->type == cJSON_Number)
{
HAL_Printf("LED:%d\r\n", json_led->valueint);
if((fd = open(leds, O_RDWR|O_NOCTTY|O_NDELAY))<0)
HAL_Printf("open %s failed\n",leds);
else{
write(fd,&(json_led->valueint), 4);
HAL_Printf("ioctl %s success, led %d\n",leds,json_led->valueint);
}
close(fd);
}
}
}
cJSON_Delete(json);
break;
default:
break;
}
}
//订阅指定的topic,即表示可以接收运平台上,哪些Topic的报文
int example_subscribe(void *handle)
{
int res = 0;
//需要订阅的主题 /thing/service/property/set:表示设备属性设置(用于云向客户端发送指令。eg:开灯,关灯),权限是订阅
const char *fmt = "/sys/%s/%s/thing/service/property/set" ;
char *topic = NULL;
int topic_len = 0;
topic_len = strlen(fmt) + strlen(DEMO_PRODUCT_KEY) + strlen(DEMO_DEVICE_NAME) + 1;
topic = HAL_Malloc(topic_len);
if (topic == NULL) {
EXAMPLE_TRACE("memory not enough");
return -1;
}
memset(topic, 0, topic_len);
HAL_Snprintf(topic, topic_len, fmt, DEMO_PRODUCT_KEY, DEMO_DEVICE_NAME);
//订阅函数
res = IOT_MQTT_Subscribe(handle, topic, IOTX_MQTT_QOS0, example_message_arrive, NULL);
if (res < 0) {
EXAMPLE_TRACE("subscribe failed");
HAL_Free(topic);
return -1;
}
HAL_Free(topic);
return 0;
}
3、效果演示:
https://www.bilibili.com/video/BV1RX4y1G7ZF/