mirror of
https://gitlab.com/sfz.aalen/infra/fabaccess.git
synced 2025-03-12 15:01:47 +01:00
62 lines
1.9 KiB
Python
62 lines
1.9 KiB
Python
from paho.mqtt import client as mqtt_client
|
|
from config import Config
|
|
import json
|
|
|
|
class MqttHandler:
|
|
@staticmethod
|
|
def setup(msg_handler):
|
|
MqttHandler.msg_handler = msg_handler
|
|
MqttHandler.client = None
|
|
|
|
@staticmethod
|
|
def connect_mqtt():
|
|
def on_connect(userdata, flags, rc):
|
|
if rc == 0:
|
|
print('Connected to MQTT Broker!')
|
|
else:
|
|
print('Failed to connect, return code %d\n', rc)
|
|
|
|
MqttHandler.client = mqtt_client.Client(Config.client_id)
|
|
MqttHandler.client.username_pw_set('admin', 'user')
|
|
MqttHandler.client.on_connect = on_connect
|
|
MqttHandler.client.connect(Config.broker, Config.port)
|
|
|
|
@staticmethod
|
|
def publish(topic, msg):
|
|
result = MqttHandler.client.publish(topic, msg)
|
|
# result: [0, 1]
|
|
status = result[0]
|
|
if status == 0:
|
|
#print(f'Send `{msg}` to topic `{topic}`')
|
|
pass
|
|
else:
|
|
print(f'Failed to send message to topic {topic}')
|
|
|
|
|
|
@staticmethod
|
|
def subscribe(topic):
|
|
def on_message(client, userdata, msg):
|
|
MqttHandler.msg_handler(msg, client)
|
|
|
|
MqttHandler.client.subscribe(topic)
|
|
MqttHandler.client.on_message = on_message
|
|
|
|
@staticmethod
|
|
def loop():
|
|
MqttHandler.client.loop_forever()
|
|
|
|
@staticmethod
|
|
def switch_plug(PlugID, state):
|
|
MqttHandler.publish(f'/FabLogging/{PlugID}/POWER', 1 if state else 0)
|
|
MqttHandler.publish(f'/aktoren/{PlugID}/cmnd/POWER', 'On' if state else 'OFF')
|
|
|
|
@staticmethod
|
|
def print_to_display(MachineID, status, text):
|
|
message = {
|
|
'Cmd': 'message',
|
|
'MssgID': status,
|
|
'ClrTxt': '',
|
|
'AddnTxt': text,
|
|
}
|
|
MqttHandler.publish(f'/cmnd/reader/{MachineID}', json.dumps(message))
|