天天看點

mqtt client python example

This is a simple example showing how to use the [Paho MQTT Python client](https://eclipse.org/paho/clients/python/) to send data to Azure IoT Hub. You need to assemble the rights credentials and configure TLS and the MQTT protocol version appropriately.

 send_iot-hub_paho_mqtt.py

 

 The following code will subscribe on topic f and republish on topic f2

  用戶端程式偶爾需要發佈訊息,不須與 mqtt broker 保持連線的情形,可用 <code>single()</code> 或 <code>multiple()</code> 方法。這種作法比較省電

  當用戶端程式,例如感應器服務程式,經常或短週期地持續發佈訊息時,則應用連線式設計。

  實作時,可先用 mosquitto_sub 訂閱主題,以監看訊息是否送出。

本節實作一個類似 mosquitto_sub 的程式,訂閱主題 “tw/rocksaying/#” 。它也是一個服務程式的基礎骨架。

  

大部份 MQTT 用戶端服務程式需要同時監看與發佈訊息。例如一個感應器服務程式,它一邊得監看主題以接收來自其他程式的動作請求;另一邊得讀取感應器狀態後發佈到主題上。

Paho 提供的範例程式使用 <code>loop_start()</code> 方法進入內建的待命執行緒,再讓設計者於主執行緒中讀取感應器狀態與發佈訊息。如下所示: