文檔中心
DOCUMENT CENTER
MQTT 接入

接入介紹

針對實時行要求高的智能硬件, 格物云IoT平臺定義了一套 MQTT 接入的協議, 該協議實現了對設備進行實時請求和反饋, 也包含的實時數據的收集,和屬性的反饋。

接入方案

初始化MQTT客戶端

client.connect("You device ID", product_key, device_token);
  • product_key 為產品的 key
  • device_token 為每個設備唯一的 token

MQTT 請求

每個請求都有唯一的消息 ID, 通過訂閱 /request/+ 來獲取消息, 并發布 /response/:reqid 來完成一個請求。

首先訂閱 /request/+

client.subscribe("/request/+");

反饋結果 /response/:reqid

void onMqttMessage(
        const char* topic, 
        uint8_t * payload, 
        unsigned int length) 
     {
        const size_t len = strlen(topic);
        char new_topic[len + 2];

        // remove "/request/"
        char reqid[len - 9];

        size_t i;

        for (i = 9; i < len; i ++) {
            reqid[i - 9] = topic[i];
        }

        sprintf(new_topic, "/response/%s", reqid);

        client.publish(topic, "{ \"key\": \"value\" }");
     }

發布實時數據

通過發布 /telemetry 的消息來匯報實時數據,數據為 JSON 格式

client.publish("/telemetry", "{ \"temperature\": 30.5 }");

發布實時屬性

通過發布 /attributes 的消息來匯報實時屬性,數據為 JSON 格式

client.publish("/attributes", "{ \"switch_1_state\": 1 }");