opcua-with-python/opcua2mqtt/MqttPublish.py

36 lines
1.3 KiB
Python
Raw Normal View History

2022-02-04 19:46:15 +01:00
from threading import Event
from loguru import logger
from MqttBase import AbstractMqttPublisher
2022-02-09 18:07:11 +01:00
from AbstractDataObject import InvalidDataObjectException
2022-02-04 19:46:15 +01:00
from queue import Empty
2022-02-04 23:19:49 +01:00
import json
2022-02-04 19:46:15 +01:00
LOOP_SLICE = 0.1 # seconds
class MqttPublish(AbstractMqttPublisher):
2022-02-09 18:07:11 +01:00
def __init__(self, config, stats, queue):
2022-02-04 19:46:15 +01:00
super().__init__(config)
self.queue = queue
2022-02-09 18:07:11 +01:00
self.stats = stats
2022-02-04 19:46:15 +01:00
self.topicPre = self.config["publishTopicPrefix"]
def localLoop(self):
while not self.killBill:
try:
dataObject = self.queue.get(timeout=LOOP_SLICE)
2022-02-09 18:07:11 +01:00
topic = self.topicPre + '/' + dataObject.getTopicPart()
payload = dataObject.getPayload()
self.client.publish(topic, payload)
logger.debug("mqtt message sent: {} -> {}".format(topic, payload))
self.stats.incMqttRequests()
2022-02-04 19:46:15 +01:00
except Empty:
2022-02-05 11:08:49 +01:00
# just evaluate the killBill at the top of the loop again
pass
2022-02-09 18:07:11 +01:00
except InvalidDataObjectException as e:
self.stats.incMqttErrors()
logger.error(f"InvalidDataObjectException received in MQTT local loop: {e}")
2022-02-04 23:06:43 +01:00
except Exception as e:
2022-02-09 18:07:11 +01:00
self.stats.incMqttErrors()
2022-02-04 23:06:43 +01:00
logger.error(f"Exception {type(e)} received in MQTT local loop: {e}")
2022-02-04 19:46:15 +01:00