使用 paho mqtt c实现MQTT发布
时间: 2023-07-27 09:06:15 浏览: 91
好的,这里提供一个简单的示例代码,使用 paho mqtt c 实现 MQTT 发布:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "MQTTClient.h"
#define ADDRESS "tcp://localhost:1883"
#define CLIENTID "ExampleClientPub"
#define TOPIC "test/topic"
#define QOS 1
#define TIMEOUT 10000L
int main(int argc, char* argv[])
{
MQTTClient client;
MQTTClient_connectOptions conn_opts = MQTTClient_connectOptions_initializer;
MQTTClient_message pubmsg = MQTTClient_message_initializer;
MQTTClient_deliveryToken token;
int rc;
// 创建 MQTT 客户端
MQTTClient_create(&client, ADDRESS, CLIENTID, MQTTCLIENT_PERSISTENCE_NONE, NULL);
// 设置连接选项
conn_opts.keepAliveInterval = 20;
conn_opts.cleansession = 1;
// 连接到 MQTT 代理服务器
if ((rc = MQTTClient_connect(client, &conn_opts)) != MQTTCLIENT_SUCCESS) {
printf("Failed to connect, return code %d\n", rc);
exit(EXIT_FAILURE);
}
// 发布消息
pubmsg.payload = "Hello, MQTT!";
pubmsg.payloadlen = strlen(pubmsg.payload);
pubmsg.qos = QOS;
pubmsg.retained = 0;
MQTTClient_publishMessage(client, TOPIC, &pubmsg, &token);
printf("Waiting for publication of %s\n"
"on topic %s for client with ClientID: %s\n",
pubmsg.payload, TOPIC, CLIENTID);
rc = MQTTClient_waitForCompletion(client, token, TIMEOUT);
printf("Message with delivery token %d delivered\n", token);
// 断开连接并清理
MQTTClient_disconnect(client, 10000);
MQTTClient_destroy(&client);
return rc;
}
```
这个示例代码实现了连接到本地的 MQTT 代理服务器,发布一条消息到 `test/topic` 主题,然后断开连接并清理。如果需要更改主题、代理服务器地址、客户端ID 等参数,请自行修改代码。
阅读全文