pylokid/library/mqtt.py

48 lines
1.8 KiB
Python
Raw Normal View History

2017-12-30 18:19:40 +00:00
#!/usr/bin/env python3
""" MQTT Functions """
import logging
2018-01-04 20:29:03 +00:00
import json
2017-12-30 18:19:40 +00:00
import paho.mqtt.client as mqtt
class MQTTClient:
""" MQTT Client """
def __init__(self, server, username, password, base_topic):
2017-12-30 18:19:40 +00:00
self.logger = logging.getLogger(__name__)
self.logger.info('Connecting to MQTT broker %s', server)
2017-12-30 18:19:40 +00:00
try:
self.mqtt_client = mqtt.Client('pylokid')
self.mqtt_client.username_pw_set(username, password=password)
self.mqtt_client.tls_set()
self.mqtt_client.connect(server, 8883, 60)
self.mqtt_client.loop_start()
except Exception as err:
self.logger.error('MQTT connection failed - exiting: %s', str(err))
2017-12-30 18:19:40 +00:00
raise SystemExit(1)
self.logger.info('MQTT connection successfull')
self.base_topic = base_topic
2017-12-30 18:19:40 +00:00
def send_message(self, f_type, f_id, pdf_data=None, pdf_file=None):
2017-12-30 18:19:40 +00:00
""" Publish a message over MQTT """
if f_type == 'Einsatzausdruck_FW':
try:
2018-01-18 21:45:14 +00:00
topic = "{0}/Einsatzausdruck_FW/{1}/".format(self.base_topic, f_id)
2018-01-18 22:14:26 +00:00
self.logger.info('[%s] Publishing information on MQTT topic %s', f_id, topic)
2018-01-04 20:29:03 +00:00
self.mqtt_client.publish(topic + 'json', json.dumps(pdf_data))
2018-01-03 11:32:37 +00:00
## Publish the PDF blob
2018-01-04 20:29:03 +00:00
pdf_fh = open(pdf_file, 'rb')
pdf_binary = pdf_fh.read()
self.mqtt_client.publish(topic + 'pdf', bytes(pdf_binary))
except IndexError as err:
self.logger.info('[%s] Cannot publish information: %s', f_id, err)
elif f_type == 'Einsatzprotokoll':
2018-01-18 21:45:14 +00:00
topic = "{0}/Einsatzprotokoll/{1}/".format(self.base_topic, f_id)
2018-01-18 22:14:26 +00:00
self.logger.info('[%s] Publishing information on MQTT topic %s', f_id, topic)
2018-01-18 21:45:14 +00:00
self.mqtt_client.publish(topic + 'json', '{}')