server/backend/mlmAccess.py

69 lines
2.4 KiB
Python
Raw Normal View History

2021-08-18 16:48:17 +00:00
import paho.mqtt.client as mqtt
from dbHelper import MaDbHelper
from pairingHandler import MaPairingHandler
import logging, coloredlogs
coloredlogs.install(level='INFO', fmt='%(asctime)s - [%(levelname)s] %(message)s')
2021-08-18 16:48:17 +00:00
class MlmAccess:
def __init__(self):
logging.info("=== MlmAccess ===")
2021-08-18 16:48:17 +00:00
self._initDb()
self._initMqtt()
self._pairingHanlder = MaPairingHandler(self._mqtt, self._db)
self._mqtt.loop_forever()
2021-08-18 16:48:17 +00:00
def _initDb(self):
logging.info("Initializing Database")
self._db = MaDbHelper()
2021-08-18 16:48:17 +00:00
initUsers = [
("backend", "backend", ["mlmAccess/#"], ["mlmAccess/#"]),
("pair-actor", "pair-actor", ["mlmAccess/pair/request/actor"], ["mlmAccess/pair/response/actor"])
]
for username, password, publishAclPatterns, subscribeAclPatterns in initUsers:
if not self._db.addUser(username, password, publishAclPatterns, subscribeAclPatterns):
self._db.updateUser(username, password, publishAclPatterns, subscribeAclPatterns)
2021-08-18 16:48:17 +00:00
def _initMqtt(self):
logging.info("Initializing MQTT")
self._mqtt = client = mqtt.Client(client_id="backend")
self._mqtt.username_pw_set("backend", "backend")
2021-08-18 16:48:17 +00:00
self._mqtt.on_connect = self._mqttOnConnect
self._mqtt.on_message = self._mqttOnMessage
2021-08-18 16:48:17 +00:00
self._mqtt.connect("localhost", 1883, 60)
2021-08-18 17:08:57 +00:00
2021-08-18 16:48:17 +00:00
def _mqttOnConnect(self, client, userdata, flags, rc):
if rc != 0:
logging.error(f"Error connecting to MQTT broker: {rc}")
return
logging.info("Successfully connected to MQTT broker")
logging.info("Subscribing to actor subjects:")
for user in self._db.getAllUsers():
if user.startswith("actor-"):
actorSubject = f"mlmAccess/actor/{user.replace('actor-', '')}/status"
logging.info(f"* {actorSubject}")
client.subscribe(actorSubject)
2021-08-18 16:48:17 +00:00
# call hooks of child objects
self._pairingHanlder._mqttOnConnect(client, userdata, flags, rc)
2021-08-18 16:48:17 +00:00
def _mqttOnMessage(self, client, userdata, message):
topic = message.topic
topic = topic.replace("mlmAccess/", "")
messageContent = str(message.payload.decode("utf-8"))
2021-08-18 17:08:57 +00:00
logging.info(f"Message on topic {topic}: {messageContent}")
2021-08-18 16:48:17 +00:00
if topic.startswith("pair"):
self._pairingHanlder.handlePairingRequest(topic, messageContent)
2021-08-18 16:48:17 +00:00
if __name__ == "__main__":
MlmAccess()