aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorElena ``of Valhalla'' Grandi <valhalla@trueelena.org>2023-07-16 20:59:01 +0200
committerElena ``of Valhalla'' Grandi <valhalla@trueelena.org>2023-07-16 20:59:01 +0200
commit126259b4c418c763ddc8a450ef17148cf4c018ad (patch)
tree8c37922c90492cae5ae0f9589a636f690b2ef582
parentc6786b2ba652f555798725e2e7d692f5c7658a11 (diff)
Start receiving mqtt messages
-rw-r--r--kerbana/__init__.py5
-rw-r--r--kerbana/config.py8
-rw-r--r--kerbana/mqtt.py46
3 files changed, 58 insertions, 1 deletions
diff --git a/kerbana/__init__.py b/kerbana/__init__.py
index ea7f5cf..8d47d35 100644
--- a/kerbana/__init__.py
+++ b/kerbana/__init__.py
@@ -4,7 +4,7 @@ from typing import Optional
import flask
import toml
-from . import config
+from . import config, mqtt
def create_app(test_config: Optional[config.Config] = None):
@@ -45,6 +45,9 @@ def create_app(test_config: Optional[config.Config] = None):
else:
app.config.from_object(test_config)
+ mqtt_client = mqtt.MQTTClient(app)
+ mqtt_client.connect()
+
@app.route('/')
def root():
return "Hello World!"
diff --git a/kerbana/config.py b/kerbana/config.py
index 2ccaabc..93b0e54 100644
--- a/kerbana/config.py
+++ b/kerbana/config.py
@@ -3,6 +3,12 @@
class Config:
SECRET_KEY = "dev"
+ MQTT_SERVER = "test.mosquitto.org"
+ MQTT_PORT = 1883
+ MQTT_USER = None
+ MQTT_PASSWORD = None
+ MQTT_TOPIC = "kerbana/#"
+
class DefaultConfig(Config):
pass
@@ -10,3 +16,5 @@ class DefaultConfig(Config):
class TestConfig(Config):
TESTING = True
+
+ MQTT_SERVER = "mqtt.invalid.org"
diff --git a/kerbana/mqtt.py b/kerbana/mqtt.py
new file mode 100644
index 0000000..9747de3
--- /dev/null
+++ b/kerbana/mqtt.py
@@ -0,0 +1,46 @@
+import paho.mqtt.client as mqtt
+from flask import Flask
+
+
+class MQTTClient:
+ def __init__(self, app: Flask):
+ self.app = app
+ 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 connect(self):
+ try:
+ self.client.connect(
+ self.app.config["MQTT_SERVER"],
+ self.app.config["MQTT_PORT"],
+ 60, # TODO: make the keepalive configurable
+ )
+ except OSError as e:
+ self.app.logger.warning("Could not connect to MQTT server")
+ self.app.logger.warning(e)
+ self.client.loop_start()
+
+ def disconnect(self, reconnect: bool = True):
+ self.client.loop_stop()
+ self.client.disconnect()
+ self.reconnect = reconnect
+
+ def on_connect(self, client, userdata, flags, rc):
+ self.app.logger.warning("Connected to MQTT")
+ self.connected = True
+ client.subscribe(self.app.config["MQTT_TOPIC"])
+
+ def on_disconnect(self, client, userdata, flags, rc):
+ self.connected = False
+ if self.reconnect:
+ self.connect()
+
+ def on_message(self, client, userdata, msg):
+ self.app.logger.warning(
+ "Received msg %s %s", msg.topic, msg.payload.decode()
+ )