fabaccess/fab_access/mqtt_client.py
2022-11-03 21:33:54 +01:00

63 lines
2.0 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(client, 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.mqtt_client_id)
MqttHandler.client.username_pw_set('admin', 'user')
MqttHandler.client.on_connect = on_connect
MqttHandler.client.username_pw_set(Config.mqtt_user_name, Config.mqtt_password)
MqttHandler.client.connect(Config.mqtt_broker, Config.mqtt_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))