2023-08-07 11:39:15 +00:00
|
|
|
import json
|
|
|
|
import logging
|
|
|
|
import re
|
|
|
|
from queue import Queue
|
|
|
|
|
|
|
|
import paho.mqtt.client as mqtt
|
|
|
|
|
|
|
|
LOG = logging.getLogger('MQTTQueue')
|
|
|
|
|
2023-08-07 12:48:18 +00:00
|
|
|
|
2023-08-07 11:39:15 +00:00
|
|
|
class MQTTQueue:
|
2023-08-07 18:05:20 +00:00
|
|
|
def __init__(self, config, queue):
|
|
|
|
self.config = config
|
2023-08-07 11:39:15 +00:00
|
|
|
self.client = mqtt.Client()
|
|
|
|
self.queue = queue
|
|
|
|
|
|
|
|
self.client.on_connect = self.on_connect
|
|
|
|
self.client.on_disconnect = self.on_disconnect
|
|
|
|
self.client.on_message = self.on_mqtt_message
|
|
|
|
|
|
|
|
def start(self):
|
2023-08-08 04:26:35 +00:00
|
|
|
if self.config.mqtt.user and self.config.mqtt.password:
|
2023-08-07 18:05:20 +00:00
|
|
|
self.client.username_pw_set(
|
2023-08-08 04:26:35 +00:00
|
|
|
self.config.mqtt.user, self.config.mqtt.password
|
2023-08-07 18:05:20 +00:00
|
|
|
)
|
2023-08-07 11:39:15 +00:00
|
|
|
|
2023-08-08 04:26:35 +00:00
|
|
|
self.client.connect(self.config.mqtt.host, 1883, 60)
|
2023-08-07 11:39:15 +00:00
|
|
|
self.client.loop_start()
|
|
|
|
|
|
|
|
def stop(self):
|
|
|
|
self.client.loop_stop()
|
|
|
|
self.client.disconnect()
|
|
|
|
|
|
|
|
def on_connect(self, client, userdata, flags, rc):
|
2023-08-08 04:26:35 +00:00
|
|
|
LOG.info(f'Connected to {self.config.mqtt.host} with code {rc}')
|
2023-08-07 11:39:15 +00:00
|
|
|
|
2023-08-08 04:26:35 +00:00
|
|
|
self.client.subscribe(self.config.mqtt.topic)
|
2023-08-07 18:05:20 +00:00
|
|
|
LOG.info(f'Subscribed')
|
2023-08-07 11:39:15 +00:00
|
|
|
|
|
|
|
def on_disconnect(self, client, userdata, rc):
|
2023-08-08 04:26:35 +00:00
|
|
|
LOG.warning(f'Disconnected from {self.config.mqtt.host} with code {rc}')
|
2023-08-07 11:39:15 +00:00
|
|
|
|
|
|
|
def on_mqtt_message(self, client, userdata, msg):
|
|
|
|
try:
|
|
|
|
data = json.loads(msg.payload.decode('utf-8'))
|
|
|
|
|
|
|
|
text = re.sub(r'\<[a-z\/]+\>', '', data['msg'])
|
|
|
|
|
2023-08-07 12:48:18 +00:00
|
|
|
self.queue.put(
|
|
|
|
(
|
|
|
|
data['level'].lower(),
|
|
|
|
data['component'],
|
|
|
|
text,
|
|
|
|
)
|
|
|
|
)
|
2023-08-07 11:39:15 +00:00
|
|
|
except Exception as e:
|
|
|
|
LOG.exception(msg.payload)
|