㈠ 保姆級快速搭建一套基於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