aboutsummaryrefslogtreecommitdiff
path: root/rrd/mqtt.py
diff options
context:
space:
mode:
authorElena ``of Valhalla'' Grandi <valhalla@trueelena.org>2023-12-08 10:20:36 +0100
committerElena ``of Valhalla'' Grandi <valhalla@trueelena.org>2023-12-29 07:29:15 +0100
commit5973b7ca26e63880e9d74a52fa9e2ec61c811401 (patch)
tree818b1d3e0a9daeb9561c8771f2dea06e906bf693 /rrd/mqtt.py
parent0a56d27c3b0f590e0eef85666bb0d10d36041089 (diff)
Management command for the mqtt loop
Diffstat (limited to 'rrd/mqtt.py')
-rw-r--r--rrd/mqtt.py64
1 files changed, 64 insertions, 0 deletions
diff --git a/rrd/mqtt.py b/rrd/mqtt.py
new file mode 100644
index 0000000..713d837
--- /dev/null
+++ b/rrd/mqtt.py
@@ -0,0 +1,64 @@
+import logging
+
+import django.conf
+import paho.mqtt.client as mqtt
+
+
+log = logging.getLogger(__name__)
+
+
+class MQTTClient:
+ def __init__(self):
+ self.reconnect = True
+ self.connected = False
+
+ self.client = mqtt.Client()
+ self.client.on_connect = self.on_connect
+ self.client.on_disconnect = self.on_disconnect
+ self.client.on_message = self.on_message
+
+ def loop_forever(self):
+ self.connect()
+ self.client.loop_forever()
+
+ def loop_start(self):
+ self.connect()
+ self.client.loop_start()
+
+ def loop_stop(self):
+ self.disconnect(reconnect=False)
+ self.client.loop_stop()
+
+ def connect(self):
+ try:
+ self.client.connect(
+ django.conf.settings.MQTT_SERVER,
+ django.conf.settings.MQTT_PORT,
+ 60, # TODO: make the keepalive configurable
+ )
+ except OSError as e:
+ log.debug("Could not connect to MQTT server")
+ log.debug(e)
+
+ def disconnect(self, reconnect: bool = True):
+ self.reconnect = reconnect
+ self.client.disconnect()
+
+ def on_connect(self, client, userdata, flags, rc):
+ log.info("Connected to MQTT")
+ self.connected = True
+ client.subscribe(django.conf.settings.MQTT_TOPIC)
+
+ def on_disconnect(self, client, userdata, rc):
+ log.info("Disconnected from MQTT")
+ self.connected = False
+ if self.reconnect:
+ self.connect()
+
+ def on_message(self, client, userdata, msg):
+ print(
+ "Received msg %s %s", msg.topic, msg.payload.decode()
+ )
+ log.debug(
+ "Received msg %s %s", msg.topic, msg.payload.decode()
+ )