mirror of
https://gitlab.com/sfz.aalen/infra/fabaccess.git
synced 2025-03-13 15:31:45 +01:00
33 lines
994 B
Python
33 lines
994 B
Python
|
from paho.mqtt import client as mqtt_client
|
||
|
|
||
|
import config
|
||
|
|
||
|
|
||
|
def on_connect(client, userdata, flags, rc):
|
||
|
if rc == 0:
|
||
|
print("Connected to MQTT Broker!")
|
||
|
else:
|
||
|
raise Exception("Failed to connect, return code %d\n", rc)
|
||
|
|
||
|
|
||
|
class MQTTHelper():
|
||
|
def __init__(self, client_name: str, username: str, password: str, broker: str, port: int):
|
||
|
client = mqtt_client.Client(client_name)
|
||
|
if username and password:
|
||
|
client.username_pw_set(username, password)
|
||
|
else:
|
||
|
print("Connecting to MQTT without credentials")
|
||
|
client.on_connect = on_connect
|
||
|
try:
|
||
|
client.connect(broker, port)
|
||
|
except Exception as e:
|
||
|
raise Exception(f"Error connecting to MQTT {broker}:{port}") from e
|
||
|
self.client = client
|
||
|
|
||
|
def subscribe(self, topic: str, handler):
|
||
|
self.client.subscribe(topic)
|
||
|
self.client.on_message = handler
|
||
|
|
||
|
def loop_forever(self):
|
||
|
self.client.loop_forever()
|