MQTTVERSION_3_1_1 paho.mqtt.c 例子
时间: 2024-09-09 13:16:55 浏览: 58
MQTT (Message Queuing Telemetry Transport) 版本 3.1.1 是一个轻量级的消息发布/订阅协议,常用于物联网(IoT)设备通信,因为它对带宽和内存的需求较小。`paho.mqtt.c` 是由 Eclipse Paho 组织维护的一个 C 语言 MQTT 客户端库。
下面是一个简单的使用 `paho.mqtt.c` 实现 MQTT v3.1.1 版本连接、订阅和发布的示例:
```c
#include <stdio.h>
#include "mqtt_client.h"
#define MQTT_BROKER "your_mqtt_broker_address"
#define CLIENT_ID "client_id"
#define TOPIC "your_topic"
#define USERNAME ""
#define PASSWORD ""
int on_connect(mqtt_client* client, void* data, int rc) {
if (rc == 0) {
printf("Connected to broker with result code %d\n", rc);
mqtt_client_set_last_will(client, TOPIC, "Offline message", strlen("Offline message"));
} else {
printf("Connection failed: %d\n", rc);
}
return 1; // continue connecting
}
int main() {
mqtt_client_options options = {0};
options.on_connect = on_connect;
options.username_pw_set = (USERNAME != "");
options.username = USERNAME;
options.password = PASSWORD;
mqtt_client* client = mqtt_client_create((char*)CLIENT_ID, MQTT_BROKER, &options);
if (!client) {
printf("Failed to create MQTT client.\n");
return -1;
}
if (mqtt_client_connect(client) != MQTT_SUCCESS) {
printf("Failed to connect to broker.\n");
mqtt_client_destroy(client);
return -1;
}
// Subscribe to topic
mqtt_client_subscribe(client, TOPIC, 0);
// Publish a message
char message[] = "Hello from MQTT";
mqtt_client_publish(client, TOPIC, strlen(message), message);
// Keep the connection open for demonstration purposes
mqtt_client_loop_forever(client);
mqtt_client_destroy(client);
return 0;
}
```
在这个例子中,我们首先初始化客户端选项并设置回调函数`on_connect`,当连接成功或失败时会调用这个函数。然后创建`mqtt_client`实例,尝试连接到指定的MQTT服务器。接着订阅主题,并发送一条消息。最后,使用`mqtt_client_loop_forever`保持客户端运行,直到手动停止。
阅读全文