2022-11-03 00:41:51 +01:00
|
|
|
from paho.mqtt import client as mqtt_client
|
|
|
|
from config import Config
|
|
|
|
import json
|
2022-11-12 16:04:24 +00:00
|
|
|
import random
|
|
|
|
import string
|
2022-11-03 00:41:51 +01:00
|
|
|
|
|
|
|
class MqttHandler:
|
2022-11-12 16:04:24 +00:00
|
|
|
|
2022-11-03 00:41:51 +01:00
|
|
|
@staticmethod
|
|
|
|
def setup(msg_handler):
|
|
|
|
MqttHandler.msg_handler = msg_handler
|
|
|
|
MqttHandler.client = None
|
|
|
|
|
|
|
|
@staticmethod
|
|
|
|
def connect_mqtt():
|
2022-11-03 21:33:54 +01:00
|
|
|
def on_connect(client, userdata, flags, rc):
|
2022-11-03 00:41:51 +01:00
|
|
|
if rc == 0:
|
|
|
|
print('Connected to MQTT Broker!')
|
|
|
|
else:
|
|
|
|
print('Failed to connect, return code %d\n', rc)
|
|
|
|
|
2022-11-12 16:09:46 +00:00
|
|
|
def get_random_string(length):
|
|
|
|
# choose from all lowercase letter
|
|
|
|
letters = string.ascii_lowercase
|
|
|
|
result_str = ''.join(random.choice(letters) for i in range(length))
|
|
|
|
return(result_str)
|
|
|
|
|
2024-10-16 16:11:58 +00:00
|
|
|
MqttHandler.client = mqtt_client.Client(mqtt_client.CallbackAPIVersion.VERSION1)
|
2022-11-03 00:41:51 +01:00
|
|
|
MqttHandler.client.username_pw_set('admin', 'user')
|
|
|
|
MqttHandler.client.on_connect = on_connect
|
2022-11-03 21:21:23 +01:00
|
|
|
MqttHandler.client.username_pw_set(Config.mqtt_user_name, Config.mqtt_password)
|
|
|
|
MqttHandler.client.connect(Config.mqtt_broker, Config.mqtt_port)
|
2022-11-03 00:41:51 +01:00
|
|
|
|
|
|
|
@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)
|
2022-12-06 21:09:55 +00:00
|
|
|
MqttHandler.publish(f'/cmnd/{PlugID}/POWER', 'On' if state else 'OFF')
|
2022-11-03 00:41:51 +01:00
|
|
|
|
|
|
|
@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))
|