加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
yyz_lamp.c 2.47 KB
一键复制 编辑 原始数据 按行查看 历史
刘煜 提交于 2024-06-21 08:56 . LIT update
#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;
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化