-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
72 lines (62 loc) · 2.65 KB
/
main.py
File metadata and controls
72 lines (62 loc) · 2.65 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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
import paho.mqtt.client as mqtt
import threading
import time
import json
class ChirpStackClient:
def __init__(self, mqtt_host, mqtt_port, mqtt_username=None, mqtt_password=None):
# MQTT setup
self.mqtt_host = mqtt_host
self.mqtt_port = mqtt_port
self.mqtt_username = mqtt_username
self.mqtt_password = mqtt_password
self.mqtt_client = mqtt.Client()
if mqtt_username and mqtt_password:
self.mqtt_client.username_pw_set(mqtt_username, mqtt_password)
self.mqtt_client.on_connect = self.on_connect
self.mqtt_client.on_message = self.on_message
self.uplink_callback = None
def start_mqtt(self, application_id, dev_eui, uplink_callback=None):
self.uplink_callback = uplink_callback
topic = f"application/{application_id}/device/{dev_eui}/event/#"
# topic = f"application/{application_id}/device/{dev_eui}/event/up"
self.mqtt_client.connect(self.mqtt_host, self.mqtt_port, 60)
self.mqtt_client.subscribe(topic)
print(f"Subscribed to MQTT topic: {topic}")
# Run MQTT loop in a separate thread
threading.Thread(target=self.mqtt_client.loop_forever, daemon=True).start()
def on_connect(self, client, userdata, flags, rc):
if rc == 0:
print("Connected to MQTT broker.")
else:
print(f"Failed to connect to MQTT broker, return code {rc}")
def on_message(self, client, userdata, msg):
print(f"Received uplink on topic {msg.topic}")
try:
payload = json.loads(msg.payload.decode())
print(json.dumps(payload, indent=2))
if self.uplink_callback:
self.uplink_callback(payload)
except Exception as e:
print(f"Error parsing uplink message: {e}")
def main():
# Fill in your details
mqtt_host = "3.92.197.242" # Replace with your MQTT broker
mqtt_port = 1883 # Or 8883 for TLS
mqtt_username = None # Set if needed
mqtt_password = None # Set if needed
application_id = "efacf7b1-e527-4e2d-8fb3-d9d1f9df33d4" # Replace with your application ID
dev_eui = "967d66e98d7e5458" # Replace with your device EUI
client = ChirpStackClient(mqtt_host, mqtt_port, mqtt_username, mqtt_password)
# Uplink (MQTT) example
def handle_uplink(payload):
print("Custom uplink handler:")
print(json.dumps(payload, indent=2))
client.start_mqtt(application_id, dev_eui, uplink_callback=handle_uplink)
# Keep the main thread alive
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
print("Exiting...")
if __name__ == "__main__":
main()