fabaccess/fab_access/mqtt_helper.py
Philipp Fruck bb144d78bc
refactor python codebase
variable configuration through config.py and code splitting into
multiple files. Also added requirements.txt and gitignore.
2022-11-01 21:44:04 +01:00

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()