server/backend/mlmAccess.py

59 lines
2 KiB
Python
Raw Normal View History

2021-08-18 16:48:17 +00:00
import paho.mqtt.client as mqtt
from dbHelper import MaDbHelper
2021-08-18 17:08:57 +00:00
import random
import string
2021-08-18 16:48:17 +00:00
class MlmAccess:
def __init__(self):
self._initDb()
self._initMqtt()
def _initDb(self):
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):
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
print("connecting to broker")
print(self.mqtt.connect("localhost", 1883, 60))
self.mqtt.loop_forever()
2021-08-18 17:08:57 +00:00
def _handleActorPairRequest(self, id):
print(f"Pair request for type actor with ID {id}")
2021-08-18 17:11:31 +00:00
if not self.db.userExists(f"actor-{id}"):
2021-08-18 17:08:57 +00:00
password = ''.join(random.choices(string.ascii_uppercase + string.digits, k=10))
self.db.addUser(f"actor-{id}", password, [f"mlmAccess/actor/{id}/status"], [f"mlmAccess/actor/{id}/action"])
self.mqtt.publish("mlmAccess/pair/response/actor", password)
else:
self.mqtt.publish("mlmAccess/pair/response/actor", "")
2021-08-18 16:48:17 +00:00
def _mqttOnConnect(self, client, userdata, flags, rc):
print("Connected with result code "+str(rc))
if rc != 0:
print("")
print(client.subscribe("mlmAccess/pair/request/actor"))
def _mqttOnMessage(self, client, userdata, message):
2021-08-18 17:08:57 +00:00
if message.topic == "mlmAccess/pair/request/actor":
self._handleActorPairRequest(str(message.payload.decode("utf-8")))
2021-08-18 16:48:17 +00:00
if __name__ == "__main__":
MlmAccess()