Files
digitaltwin1/src/MqttEventPublisher.py
2025-12-15 11:06:36 +01:00

59 lines
2.8 KiB
Python

import paho.mqtt.client as mqtt
import threading
from loguru import logger
from AbstractMqttHandler import AbstractMqttPublisher
def mqttEventPublisherStart(config, processImage):
mqttEventPublisherThread = MqttEventPublisher(config, processImage)
mqttEventPublisherThread.start()
class MqttEventPublisher(AbstractMqttPublisher):
def __init__(self, config, processImage):
super().__init__(config, processImage)
self.disableAnalogInputEventPublishing = self.config["disableAnalogInputEventPublishing"].lower() in [ "true", "on" ]
def localLoop(self):
while not self.killBill:
with self.processImage:
self.processImage.wait()
if self.killBill:
continue
discreteInputChangeset = self.processImage.getChangedDiscreteInputs()
coilInputChangeset = self.processImage.getChangedCoils()
if not self.disableAnalogInputEventPublishing:
analogInputChangeset = self.processImage.getChangedAnalogsInputs()
for discreteInputChangeItem in discreteInputChangeset:
logger.debug("Discrete input {} changed from {} to {}"
.format(discreteInputChangeItem[0],
discreteInputChangeItem[1][1],
discreteInputChangeItem[1][0]))
self.client.publish("{}/{}".format(self.config["digitalInputTopicPrefix"], str(discreteInputChangeItem[0])),
str(discreteInputChangeItem[1][0]),
retain=True)
for coilInputChangeItem in coilInputChangeset:
logger.debug("Coil input {} changed from {} to {}"
.format(coilInputChangeItem[0],
coilInputChangeItem[1][1],
coilInputChangeItem[1][0]))
self.client.publish("{}/{}".format(self.config["coilInputTopicPrefix"], str(coilInputChangeItem[0])),
str(coilInputChangeItem[1][0]),
retain=True)
if not self.disableAnalogInputEventPublishing:
for analogInputChangeItem in analogInputChangeset:
logger.debug("Analog input {} changed from {} to {}"
.format(analogInputChangeItem[0],
analogInputChangeItem[1][1],
analogInputChangeItem[1][0]))
self.client.publish("{}/{}".format(self.config["analogInputEventTopicPrefix"], str(analogInputChangeItem[0])),
str(analogInputChangeItem[1][0]),
retain=True)