mqtt客户端c代码订阅
时间: 2023-10-05 22:14:34 浏览: 62
以下是一个简单的MQTT客户端C代码,用于订阅主题:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "MQTTClient.h"
#define ADDRESS "tcp://localhost:1883"
#define CLIENTID "ExampleClientSub"
#define TOPIC "test/topic"
#define QOS 1
#define TIMEOUT 10000L
volatile MQTTClient_deliveryToken deliveredtoken;
void delivered(void *context, MQTTClient_deliveryToken dt) {
printf("Message with token value %d delivery confirmed\n", dt);
deliveredtoken = dt;
}
int msgarrvd(void *context, char *topicName, int topicLen, MQTTClient_message *message) {
printf("Message arrived\n");
printf(" topic: %s\n", topicName);
printf(" message: ");
char* payloadptr = message->payload;
for (int i = 0; i < message->payloadlen; i++) {
putchar(*payloadptr++);
}
putchar('\n');
MQTTClient_freeMessage(&message);
MQTTClient_free(topicName);
return 1;
}
void connlost(void *context, char *cause) {
printf("\nConnection lost\n");
printf(" cause: %s\n", cause);
}
int main(int argc, char* argv[]) {
MQTTClient client;
MQTTClient_connectOptions conn_opts = MQTTClient_connectOptions_initializer;
int rc;
MQTTClient_create(&client, ADDRESS, CLIENTID, MQTTCLIENT_PERSISTENCE_NONE, NULL);
conn_opts.keepAliveInterval = 20;
conn_opts.cleansession = 1;
MQTTClient_setCallbacks(client, NULL, connlost, msgarrvd, delivered);
if ((rc = MQTTClient_connect(client, &conn_opts)) != MQTTCLIENT_SUCCESS) {
printf("Failed to connect, return code %d\n", rc);
exit(EXIT_FAILURE);
}
printf("Subscribing to topic %s\nfor client %s using QoS%d\n\n", TOPIC, CLIENTID, QOS);
MQTTClient_subscribe(client, TOPIC, QOS);
printf("Press Q<Enter> to quit\n\n");
while (getchar() != 'Q') {}
MQTTClient_disconnect(client, 10000);
MQTTClient_destroy(&client);
return rc;
}
```
此代码使用Eclipse Paho MQTT C客户端库,它提供了一个简单的API来连接到MQTT代理并订阅主题。在此示例中,客户端连接到本地主机上的MQTT代理,并订阅名为“test/topic”的主题。当代理发布与此主题相关的消息时,客户端将调用msgarrvd函数来处理该消息。如果连接丢失,connlost函数将被调用。在主函数中,客户端将等待用户按下Q键来退出程序。
阅读全文