㈠ 保姆级快速搭建一套基于Linux环境下的MQTT开发程序模版(基于腾讯云IoT Explorer)
步骤一:创建设备
1. 登录腾讯云IoT Explorer控制台,选择“设备管理”页面,点击“添加设备”按钮。
2. 在弹出的对话框中输入设备名称,选择所属产品,点击“确定”按钮。
3. 在设备列表中找到新创建的设备,点击“查看”按钮,在设备详情页面中复制设备的Device Secret。
步骤二:安装MQTT客户端
1. 在Linux环境下安装MQTT客户端库(以Paho C库为例)。
sudo apt-get install libssl-dev
sudo apt-get install libpaho-mqtt-dev
2. 创建一个MQTT客户端,连接到腾讯云IoT Explorer的MQTT服务器。
#include "MQTTClient.h"
#define ADDRESS "ssl://[ProctID].
iotcloud.tencentdevices.com:8883"
#define CLIENTID "[DeviceName]"
#define USERNAME "[ProctID][DeviceName]"
#define PASSWORD "[DeviceSecret]"
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;
MQTTClient_create(&client, ADDRESS, CLIENTID, MQTTCLIENT_PERSISTENCE_NONE, NULL);
conn_opts.keepAliveInterval = 20;
conn_opts.cleansession = 1;
conn_opts.username = USERNAME;
conn_opts.password = PASSWORD;
if ((rc = MQTTClient_connect(client, &conn_opts)) != MQTTCLIENT_SUCCESS)
{
printf("Failed to connect, return code %d ", rc);
exit(EXIT_FAILURE);
}
// TODO: 在此处添加MQTT消息的订阅和发布代码
MQTTClient_disconnect(client, 10000);
MQTTClient_destroy(&client);
return rc;
}
步骤三:订阅MQTT消息
1. 在main函数中添加MQTT消息的订阅代码。
// 订阅主题为"[ProctID]/[DeviceName]/user/update"的MQTT消息
rc = MQTTClient_subscribe(client, "[ProctID]/[DeviceName]/user/update", 1);
if (rc != MQTTCLIENT_SUCCESS)
{
printf("Failed to subscribe, return code %d ", rc);
exit(EXIT_FAILURE);
}
while (1)
{
// 等待MQTT消息的到来
...
}
2. 在MQTT消息到达时,调用回调函数处理消息。
void messageArrived(void *context, char *topicName, int topicLen, MQTTClient_message *message)
{
// 处理MQTT消息
printf("Message arrived: %.*s ", message->payloadlen, (char*)message->payload);
MQTTClient_freeMessage(&message);
MQTTClient_free(topicName);
}
int main(int argc, char* argv[])
{
...
// 注册MQTT消息到达的回调函数
MQTTClient_setCallbacks(client, NULL, NULL, messageArrived, NULL);
// 订阅主题为"[ProctID]/[DeviceName]/user/update"的MQTT消息
rc = MQTTClient_subscribe(client, "[ProctID]/[DeviceName]/user/update", 1);
if (rc != MQTTCLIENT_SUCCESS)
{
printf("Failed to subscribe, return code %d ", rc);
exit(EXIT_FAILURE);
}
while (1)
{
// 等待MQTT消息的到来
rc = MQTTClient_receive(client, 1000);
if (rc != MQTTCLIENT_SUCCESS && rc != MQTTCLIENT_TOPICNAME_TRUNCATED)
{
printf("Failed to receive, return code %d ", rc);
break;
}
}
...
}
步骤四:发布MQTT消息
1. 在main函数中添加MQTT消息的发布代码。
// 发布主题为"[ProctID]/[DeviceName]/user/update"的MQTT消息
pubmsg.payload = "Hello, World!";
pubmsg.payloadlen = strlen(pubmsg.payload);
pubmsg.qos = 1;
pubmsg.retained = 0;
MQTTClient_publishMessage(client, "[ProctID]/[DeviceName]/user/update", &pubmsg, &token);
rc = MQTTClient_waitForCompletion(client, token, 10000);
if (rc != MQTTCLIENT_SUCCESS)
{
printf("Failed to publish, return code %d ", rc);
exit(EXIT_FAILURE);
}
2. 运行程序,查看MQTT消息的订阅和发布情况。
gcc -o mqtt_client mqtt_client.c -lpaho-mqtt3cs
./mqtt_client