diff options
author | Elena ``of Valhalla'' Grandi <valhalla@trueelena.org> | 2023-12-09 15:26:02 +0100 |
---|---|---|
committer | Elena ``of Valhalla'' Grandi <valhalla@trueelena.org> | 2023-12-29 07:29:15 +0100 |
commit | 27bc8de7c7f8e29ba10324b56fef9fc4e80a9fd6 (patch) | |
tree | 4616e597b77995c7870c1b803999616394c14b9e /rrd/mqtt.py | |
parent | f2916ba1e749dc3aca47a256e1472e5032e2c9c8 (diff) |
Start recording mqtt data in rss.
Diffstat (limited to 'rrd/mqtt.py')
-rw-r--r-- | rrd/mqtt.py | 30 |
1 files changed, 21 insertions, 9 deletions
diff --git a/rrd/mqtt.py b/rrd/mqtt.py index de679ce..09589c3 100644 --- a/rrd/mqtt.py +++ b/rrd/mqtt.py @@ -1,7 +1,11 @@ +import datetime import logging -import django.conf import paho.mqtt.client as mqtt +import slugify +from django.conf import settings + +from . import models log = logging.getLogger(__name__) @@ -31,13 +35,13 @@ class MQTTClient: def connect(self): try: self.client.connect( - django.conf.settings.MQTT_SERVER, - django.conf.settings.MQTT_PORT, + settings.MQTT_SERVER, + settings.MQTT_PORT, 60, # TODO: make the keepalive configurable ) except OSError as e: - log.debug("Could not connect to MQTT server") - log.debug(e) + log.warning("Could not connect to MQTT server") + log.warning(e) def disconnect(self, reconnect: bool = True): self.reconnect = reconnect @@ -46,7 +50,7 @@ class MQTTClient: def on_connect(self, client, userdata, flags, rc): log.info("Connected to MQTT") self.connected = True - client.subscribe(django.conf.settings.MQTT_TOPIC) + client.subscribe(settings.MQTT_TOPIC + "#") def on_disconnect(self, client, userdata, rc): log.info("Disconnected from MQTT") @@ -55,9 +59,17 @@ class MQTTClient: 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() ) + ts = int(datetime.datetime.now().timestamp()) + topic = msg.topic.removeprefix(settings.MQTT_TOPIC) + dss = models.DataSource.objects.filter(topic=topic) + if not dss: + dss = [models.DataSource.objects.create( + topic=topic, + path=slugify.slugify(topic) + ".rrd", + )] + dss[0].save() + for ds in dss: + ds.update(ts, msg.payload.decode()) |