2024年11月18日 星期一

利用ChatGPT產生發布MQTT主題的Python程式


 本文利用ChatGPT來產生物聯網MQTT之Python程式,其提示語和所產生的程式如下:


程式碼:


 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
import paho.mqtt.client as mqtt
import random
import time

# 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}
            client.publish(TOPIC, str(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()


把上述程式利用Python IDLE來執行,發生下列錯誤的問題。

把上述問題,詢問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
import paho.mqtt.client as mqtt
import random
import time

# MQTT broker 設定
BROKER = "broker.mqttgo.io"
PORT = 1883
TOPIC = "sensor/light"
CLIENT_ID = "LightSensorPublisher"

# 建立 MQTT 客戶端
client = mqtt.Client(client_id=CLIENT_ID, protocol=mqtt.MQTTv311, callback_api_version=5)

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}
            client.publish(TOPIC, str(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()



經測試方法1,發生下列問題。


採用方法2,重新安裝paho-mqtt套件。

執行結果:


MQTTGO broker的畫面如本文最上圖,記得要按下連線鈕,並訂閱sensor/light主題。

沒有留言:

張貼留言