訂閱程式碼:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 | import paho.mqtt.client as mqtt import json # MQTT broker 設定 BROKER = "broker.mqttgo.io" PORT = 1883 TOPIC = "sensor/light" CLIENT_ID = "LightSensorSubscriber" # 當接收到消息時的回調函數 def on_message(client, userdata, msg): try: # 解碼消息並解析光線亮度 payload = json.loads(msg.payload.decode()) light_intensity = payload.get("light_intensity", 0) print(f"Received light intensity: {light_intensity}") # 判斷亮度是否低於 256 if light_intensity < 256: print("點亮電燈") except Exception as e: print(f"Error processing message: {e}") # 建立 MQTT 客戶端 client = mqtt.Client(CLIENT_ID) # 設置回調函數 client.on_message = on_message def subscribe_to_light_data(): try: client.connect(BROKER, PORT, 60) print(f"Connected to MQTT broker: {BROKER}") # 訂閱主題 client.subscribe(TOPIC) print(f"Subscribed to topic: {TOPIC}") # 進入阻塞循環等待消息 client.loop_forever() except KeyboardInterrupt: print("\nDisconnected from broker.") client.disconnect() if __name__ == "__main__": subscribe_to_light_data() |
說明
on_message
回調函數
當收到主題上的消息時,會解析light_intensity
數值。如果亮度低於 256,輸出「點亮電燈」。JSON 格式處理
確保發佈的訊息格式正確(如{"light_intensity": <value>}
)。訂閱程式使用json.loads
解析訊息。執行訂閱程式
啟動程式後,它會持續監聽sensor/light
主題上的數據。測試
啟動發佈程式和訂閱程式後,當亮度低於 256 時,應該在訂閱程式中看到「點亮電燈」的輸出。
如果有其他需求或問題,隨時告訴我!
執行結果:
再問ChatGPT:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 | import paho.mqtt.client as mqtt import random import time import json # 用於 JSON 格式化 # MQTT broker 設定 BROKER = "broker.mqttgo.io" PORT = 1883 TOPIC = "sensor/light" CLIENT_ID = "LightSensorPublisher" # 建立 MQTT 客戶端 client = mqtt.Client(CLIENT_ID) def publish_light_data(): try: client.connect(BROKER, PORT, 60) print(f"Connected to MQTT broker: {BROKER}") while True: # 模擬光線亮度數據 (0 到 1000 lux) light_intensity = random.randint(0, 1000) payload = {"light_intensity": light_intensity} # 將數據轉換為 JSON 字串 client.publish(TOPIC, json.dumps(payload)) print(f"Published: {payload} to topic {TOPIC}") time.sleep(5) # 每 5 秒發佈一次 except KeyboardInterrupt: print("\nDisconnected from broker.") client.disconnect() if __name__ == "__main__": publish_light_data() |
訂閱程式(保持不變)
訂閱程式的解析邏輯已經正確,無需修改。
發佈端執行結果:
發佈端執行結果:
接收端執行結果:
MQTTGO的畫面:
沒有留言:
張貼留言