首先你會需要安裝套件
pip install paho-mqtt
或者
pip3 install paho-mqtt
Python Publish 程式碼
import paho.mqtt.client as mqtt
import random
import json
import datetime
import time
client_id = "david"
server_ip = "127.0.0.1"
server_port = 1883
publish_uri ="/mqtt/4"
# 設置日期時間的格式
ISOTIMEFORMAT = '%m/%d %H:%M:%S'
# 連線設定
# 初始化地端程式
client = mqtt.Client(client_id=client_id)
# 設定登入帳號密碼
#client.username_pw_set("try","xxxx")
# 設定連線資訊(IP, Port, 連線時間)
client.connect(server_ip, server_port, 60)
while True:
t0 = random.randint(0,30)
t = datetime.datetime.now().strftime(ISOTIMEFORMAT)
payload = {'Temperature' : t0 , 'Time' : t}
print (json.dumps(payload))
#要發布的主題和內容
client.publish(publish_uri, json.dumps(payload))
time.sleep(5)
參考文章: Day27 – 使用 Python 進行 Publish & Subscribe