由于这个问题涉及的是一个完整的系统设计,我们将提供一个核心函数的示例,展示如何使用MQTT客户端发布和订阅消息。
#include <iostream>
#include <memory>
#include <string>
#include "MQTTClient.h"
// MQTT 客户端回调函数
void messageArrived(void* context, char* topicName, int topicLen, MQTTClient_message* message) {
std::cout << "Message arrived: " << topicName << " " << message->payload << std::endl;
MQTTClient_freeMessage(&message);
MQTTClient_free(topicName);
}
int main() {
MQTTClient client;
MQTTClient_createOptions createOpts = MQTTClient_createOptions_initializer;
MQTTClient_connectOptions connOpts = MQTTClient_connectOptions_initializer;
int rc;
MQTTClient_create(&client, "tcp://iot.eclipse.org:1883", CLIENTID, MQTTCLIENT_PERSISTENCE_NONE, NULL);
createOpts.sendWhileDisconnected = 1;
rc = MQTTClient_setCallbacks(client, NULL, NULL, messageArrived, NULL);
connOpts.keepAliveInterval = 20;
connOpts.cleansession = 1;
connOpts.username = "use-token-auth";
connOpts.password = "YOUR_MQTT_TOKEN";
rc = MQTTClient_connect(client, &connOpts);
if (rc != MQTTCLIENT_SUCCESS) {
std::cout << "Failed to connect, return code " << rc << std::endl;
MQTTClient_destroy(&client);
return -1;
}
rc = MQTTClient_subscribe(client, "factory/telemetry", 2);
if (rc != MQTTCLIENT_SUCCESS) {
std::cout << "Failed to subscribe, return code " << rc << std::endl;
MQTTClient_disconnect(client, 10000);
MQTTClient_destroy(&client);
return -1;
}
// 发布消息的代码示例
MQTTClient_message pubmsg = MQTTClient_message_initializer;
pubmsg.payload = "{\"temperature\": 22}";
pubmsg.payloadlen = strlen(pubmsg.payload);
pubmsg.qos = 2;
pubmsg.retained = 0;
rc = MQTTClient_publishMessage(client, "factory/telemetry", &pubmsg, NULL);
// 处理逻辑,比如设备运行状态更新等
MQTTClient_unsubscribe(client, "factory/telemetry");
MQTTClient_disconnect(client, 10000);
MQTTClient_destroy(&client);
return rc;
}
这段代码展示了如何使用Eclipse 的MQTT.org服务器,连接到MQTT代理,订阅一个主题并发布消息。这是物联网系统中常见的一个操作,其中设备通过MQTT发送数据,并且服务端可以通过订阅相应的主题来接收这些数据。这个例子使用了MQTT客户端库的C++接口,展示了如何在C++中使用MQTT进行消息的发送和接收。