代码拉取完成,页面将自动刷新
同步操作将从 刘煜/FSMP1A开发板示例代码 强制同步,此操作会覆盖自 Fork 仓库以来所做的任何修改,且无法恢复!!!
确定后同步将在后台操作,完成时将刷新页面,请耐心等待。
#include "file.h"
#include <cjson/cJSON.h>
#include <mosquitto.h>
#include <stdlib.h>
#include <unistd.h> //sleep
#include <stdio.h>
#include <string.h> //strlen
const char* topic_pub = "1718787027582/Device2AIOTSIM";
const char* topic_sub = "1718787027582/AIOTSIM2Device";
const char* led_path = "/sys/class/leds/led1/brightness";
const char* client_id = "askduhkegfeiuw";
//消息处理函数
void on_message(struct mosquitto * client, void * data, const struct mosquitto_message * msg)
{
printf("Topic: %s\n", msg->topic);
//打印消息主题
if (strcmp(msg->topic, topic_sub))
{
//不是订阅的主题
printf("Topic: %s\n", msg->topic);
}
//将JSON字符串转为C的结构体
cJSON* obj = cJSON_ParseWithLength(msg->payload, msg->payloadlen);
if (!obj)
{
//JSON字符串解析失败
printf("JSON: %*s\n", msg->payloadlen, msg->payload);
return;
}
printf("JSON: %*s\n", msg->payloadlen, msg->payload);
cJSON* lamp = cJSON_GetObjectItem(obj, "lamp");
if (!lamp)
{
printf("lamp property not found\n");
return;
}
if (cJSON_IsTrue(lamp))
{
//开灯
write_file(led_path, "1");
}
if (cJSON_IsFalse(lamp))
{
//关灯
write_file(led_path, "0");
}
}
int main()
{
//初始化函数库
mosquitto_lib_init();
//创建客户端
struct mosquitto* client = mosquitto_new(client_id, true, NULL);
if (!client)
{
perror("mosquitto_new");
mosquitto_lib_cleanup();
return EXIT_FAILURE;
}
//注册消息处理函数
mosquitto_message_callback_set(client, on_message);
//连接服务器
int error = mosquitto_connect(client, "mqtt.yyzlab.com.cn", 1883, 60);
if (error != MOSQ_ERR_SUCCESS)
{
printf("mosquitto_connect: %s\n", mosquitto_strerror(error));
mosquitto_destroy(client);
mosquitto_lib_cleanup();
return EXIT_FAILURE;
}
printf("connected to MQTT broker\n");
//订阅主题
error = mosquitto_subscribe(client, NULL, topic_sub, 0);
if (error != MOSQ_ERR_SUCCESS)
{
printf("mosquitto_subscribe: %s\n", mosquitto_strerror(error));
}
//启动心跳线程
mosquitto_loop_start(client);
while(1)
{
sleep(5);
}
mosquitto_loop_stop(client, false);
//销毁客户端
mosquitto_destroy(client);
//清理函数库
mosquitto_lib_cleanup();
return EXIT_SUCCESS;
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。