smart-green-house-server-an.../how_to_use_mqtt/sub1.c

82 lines
2.8 KiB
C
Raw Permalink Normal View History

2023-10-24 17:19:13 +08:00
#include <mosquitto.h>
#include <pthread.h>
#include <signal.h>
#include <stdbool.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
struct mosquitto* client;
int isRunning = 1;
pthread_t main_th_id;
void connect_callback(struct mosquitto* mosq, void* args, int rc) {
if (rc == 0) {
printf("连接MQTT服务成功!\n");
} else {
printf("连接MQTT服务失败!\n");
}
}
void on_subscribe(struct mosquitto* mosq,
void* obj,
int mid,
int qos_count,
const int* granted_qos) {
printf("-订阅的消息ID为--%d 成功, Qos的granted: %d--\n", mid,
*granted_qos);
}
void on_message(struct mosquitto* mosq,
void* obj,
const struct mosquitto_message* message) {
printf("收到%s(%d)的消息: %s\n", message->topic, message->mid,
(char*)message->payload);
if (strncmp((char*)message->payload, "exit", 4) == 0) {
isRunning = 0;
mosquitto_loop_stop(client, true);
}
}
int main(int argc, char const* argv[]) {
main_th_id = pthread_self();
// 1. 初始化mosquitto的库环境
mosquitto_lib_init(); // 初始化(固定格式)
// 使用mosquitto库函数前要先初始化使用之后要清除。
// 2. 创建mosquitto的客户端
unsigned char userdata[128] = "1";
client = mosquitto_new("166", true, userdata); // 创建客户端句柄
// struct mosquitto* mosquitto_new(
// const char *id,//用户自定义标识ID
// bool clean_session, //断开后是否保留订阅信息true/false
// void *userdata //回调参数
// );
// d可以为NULLclean_session的标识必须是true, userdata也可以是NULL
if (client == NULL) {
printf("创建mqtt客户端失败!\n");
perror("mosquitto_new\n");
return -1;
}
mosquitto_connect_callback_set(client, connect_callback);
mosquitto_subscribe_callback_set(client, on_subscribe);
mosquitto_message_callback_set(client, on_message);
// 3. 连接mqtt broker
int flag = mosquitto_connect(client, "10.12.156.19", 1883, 60);
if (flag == MOSQ_ERR_SUCCESS) {
printf("-----连接MQTT 服务器成功!-----\n");
}
int msgId = 1;
// 开始订阅信息
flag = mosquitto_subscribe(client, &msgId, "dht11", 0);
if (flag == MOSQ_ERR_SUCCESS) {
printf("订阅消息ID: %d 成功, 等待消息!\n", msgId);
}
while (isRunning) {
// 处理网络事件
mosquitto_loop_start(client); // 接收网络数据
usleep(500);
}
// 关闭mosquitto的客户端
mosquitto_destroy(client);
// 最后清理库环境
mosquitto_lib_cleanup();
return 0;
}