This commit is contained in:
70
src/mqtt_helper.py
Normal file
70
src/mqtt_helper.py
Normal file
@@ -0,0 +1,70 @@
|
||||
#!/usr/bin/env python3
|
||||
import paho.mqtt.client as mqtt
|
||||
import config
|
||||
|
||||
"""
|
||||
MQTT class
|
||||
"""
|
||||
|
||||
__author__ = "@tormakris"
|
||||
__copyright__ = "Copyright 2020, Birbnetes Team"
|
||||
__module_name__ = "mqtt"
|
||||
__version__text__ = "1"
|
||||
|
||||
|
||||
class MQTT:
|
||||
"""
|
||||
MQTT class used to make sending mqtt messages nice and simple
|
||||
"""
|
||||
|
||||
def __init__(self, host=config.MQTT_HOSTNAME, port=config.MQTT_PORT, client_id=config.CLIENT_ID, qos=2,
|
||||
retain=True):
|
||||
"""
|
||||
Init variables
|
||||
:param host:
|
||||
:param port:
|
||||
:param client_id:
|
||||
:param qos:
|
||||
:param retain:
|
||||
"""
|
||||
self.client = None
|
||||
self.host = host
|
||||
self.port = port
|
||||
self.client_id = client_id
|
||||
self.topic = None
|
||||
self.qos = qos
|
||||
self.retain = retain
|
||||
|
||||
def get_topic(self) -> str:
|
||||
"""
|
||||
Set topic
|
||||
:return:
|
||||
"""
|
||||
return self.topic
|
||||
|
||||
def set_topic(self, topic: str) -> None:
|
||||
"""
|
||||
Get current topic
|
||||
:param topic:
|
||||
:return:
|
||||
"""
|
||||
self.topic = topic
|
||||
|
||||
topic = property(get_topic, set_topic)
|
||||
|
||||
def connect(self) -> None:
|
||||
"""
|
||||
Setup client and connect to broker
|
||||
:return:
|
||||
"""
|
||||
self.client = mqtt.Client(client_id=self.client_id, clean_session=True, userdata=None, protocol=mqtt.MQTTv311,
|
||||
transport="tcp")
|
||||
self.client.connect(host=self.host, port=self.port, keepalive=60)
|
||||
|
||||
def publish(self, message: str) -> None:
|
||||
"""
|
||||
Publish a message
|
||||
:param message:
|
||||
:return:
|
||||
"""
|
||||
self.client.publish(self.topic, message, qos=self.qos, retain=self.retain)
|
||||
Reference in New Issue
Block a user