57 lines
1.8 KiB
Python
57 lines
1.8 KiB
Python
""" Module to Publish Sensor Data to MQTT """
|
|
|
|
import paho.mqtt.client as paho
|
|
from copy import copy
|
|
|
|
class MQTT(object):
|
|
""" Class to Represent a Client to a single MQTT Broker """
|
|
|
|
def __init__(self, host, port=1883, base="sensor/", user=None, passwd=None, certfile=None):
|
|
""" Initialize Class
|
|
|
|
Arguments:
|
|
host : MQTT Broker Hostname (mandatory)
|
|
port: MQTT Broker Port
|
|
base: Base MQTT Topic
|
|
user: Username
|
|
pass: Passwort (mandatory if user is set)
|
|
certfile: Path to CA-Cert File of the broker. TLS if used if set
|
|
"""
|
|
|
|
self.__base = base
|
|
self.__client = paho.Client()
|
|
self.__client.on_connect = self.__on_connect
|
|
if user != None and passwd != None:
|
|
self.__client.username_pw_set(user, passwd)
|
|
if certfile != None:
|
|
self.__client.tls_set(certfile)
|
|
|
|
try:
|
|
self.__client.connect(host, port, 60)
|
|
self.__client.loop_start()
|
|
except:
|
|
print("Error Setting up MQTT Client")
|
|
raise RuntimeError
|
|
|
|
def __del__(self):
|
|
self.__client.loop_stop()
|
|
self.__client.disconnect()
|
|
|
|
def __on_connect(self, client, userdata, ret, dummy):
|
|
""" Do Something when MQTT Connection is established """
|
|
print("Connected with result code "+str(ret))
|
|
|
|
def notify(self, msg):
|
|
""" Publish Sensor data to MQTT
|
|
|
|
Arguments:
|
|
msg: Object Representation of the Sensor Data
|
|
"""
|
|
tmp = copy(msg)
|
|
|
|
sid = tmp['sid']
|
|
tmp.pop('sid', None)
|
|
|
|
for stype, svalue in tmp.items():
|
|
self.__client.publish(self.__base + str(sid) + "/" + stype, str(svalue), 2, True)
|