-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmqtt_monitor.py
More file actions
45 lines (38 loc) · 1.29 KB
/
mqtt_monitor.py
File metadata and controls
45 lines (38 loc) · 1.29 KB
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
import paho.mqtt.client as mqtt
import time
# การตั้งค่า Broker MQTT (ดึงมาจากโค้ด Arduino ของคุณ)
BROKER = "broker.hivemq.com"
PORT = 1883
TOPIC = "esp32/light_control"
def on_connect(client, userdata, flags, rc):
if rc == 0:
print("Connected to MQTT Broker!")
# Subscribe to the topic
client.subscribe(TOPIC)
print(f"Listening on topic: {TOPIC}")
else:
print(f"Failed to connect, return code {rc}")
def on_message(client, userdata, msg):
try:
payload = msg.payload.decode()
print(f"--------------------------------")
print(f"Topic: {msg.topic}")
print(f"Message: {payload}")
print(f"Time: {time.strftime('%H:%M:%S')}")
except Exception as e:
print(f"Error decoding message: {e}")
# สร้าง Client
client = mqtt.Client()
# กำหนด Callback functions
client.on_connect = on_connect
client.on_message = on_message
print(f"Connecting to {BROKER}...")
try:
client.connect(BROKER, PORT, 60)
# วนลูปรับข้อมูลไปเรื่อยๆ
client.loop_forever()
except KeyboardInterrupt:
print("\nDisconnecting...")
client.disconnect()
except Exception as e:
print(f"An error occurred: {e}")