Python MQTT

透過 Python 傳送數據到 Mosquitto MQTT Broker

pip3 install paho-mqtt
import paho.mqtt.client as mqtt
import time
import json
import random
#變數設定
MQTT_TOPIC = "Sensor/BedRoom/Temperature"  
MQTT_SERVER = "192.168.43.61"  
MQTT_PORT = 1883  
MQTT_ALIVE = 60  

#------------
#mqtt client 物件
mqtt_client=mqtt.Client()
#連線MQTT Server
mqtt_client.connect(MQTT_SERVER, MQTT_PORT, MQTT_ALIVE)

while True:
    temp=random.randint(0,30)
    payload={
        "Topic":MQTT_TOPIC,
        "溫度":temp
    }
    print("目標 topic:"+MQTT_TOPIC+"=>溫度:"+str(temp))
    #送出topic訊息,須加入ensure_ascii=False讓中文正常顯示
    mqtt_client.publish(MQTT_TOPIC, json.dumps(payload, ensure_ascii=False),qos=1)
    time.sleep(10)  

MQTT Server端測試

mosquitto_sub -t "Sensor/BedRoom/Temperature"
{"Topic": "Sensor/BedRoom/Temperature", "\u6eab\u5ea6": 3}
{"Topic": "Sensor/BedRoom/Temperature", "\u6eab\u5ea6": 24}
{"Topic": "Sensor/BedRoom/Temperature", "\u6eab\u5ea6": 16}

#加入ensure_ascii=False
{"Topic": "Sensor/BedRoom/Temperature", "溫度": 21}
{"Topic": "Sensor/BedRoom/Temperature", "溫度": 13}

Node-Red mqtt接收測試

Last updated