69 lines
No EOL
2.4 KiB
Python
69 lines
No EOL
2.4 KiB
Python
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')
|
|
|
|
class MlmAccess:
|
|
def __init__(self):
|
|
logging.info("=== MlmAccess ===")
|
|
|
|
self._initDb()
|
|
self._initMqtt()
|
|
|
|
self._pairingHanlder = MaPairingHandler(self._mqtt, self._db)
|
|
|
|
self._mqtt.loop_forever()
|
|
|
|
def _initDb(self):
|
|
logging.info("Initializing Database")
|
|
self._db = MaDbHelper()
|
|
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)
|
|
|
|
def _initMqtt(self):
|
|
logging.info("Initializing MQTT")
|
|
self._mqtt = client = mqtt.Client(client_id="backend")
|
|
self._mqtt.username_pw_set("backend", "backend")
|
|
|
|
self._mqtt.on_connect = self._mqttOnConnect
|
|
self._mqtt.on_message = self._mqttOnMessage
|
|
|
|
self._mqtt.connect("localhost", 1883, 60)
|
|
|
|
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)
|
|
|
|
# call hooks of child objects
|
|
self._pairingHanlder._mqttOnConnect(client, userdata, flags, rc)
|
|
|
|
def _mqttOnMessage(self, client, userdata, message):
|
|
topic = message.topic
|
|
topic = topic.replace("mlmAccess/", "")
|
|
messageContent = str(message.payload.decode("utf-8"))
|
|
|
|
logging.info(f"Message on topic {topic}: {messageContent}")
|
|
|
|
if topic.startswith("pair"):
|
|
self._pairingHanlder.handlePairingRequest(topic, messageContent)
|
|
|
|
if __name__ == "__main__":
|
|
MlmAccess() |