mqtt-sensord/mqtt_sensord/mqttlib/paho_mqtt.py

30 lines
874 B
Python
Raw Normal View History

2019-07-09 22:01:39 +02:00
import json
import paho.mqtt.client as mqtt
from .base import MQTTClientBase
class MQTTClient(MQTTClientBase):
def _connect(self):
self._mqtt = mqtt.Client(self.client_id)
self._mqtt.username_pw_set(self.user, self.password)
2021-01-10 23:32:09 +01:00
self._mqtt.on_connect = self.on_connect
2019-07-09 22:01:39 +02:00
self._mqtt.connect(self.host)
2021-01-10 23:32:09 +01:00
def on_connect(self, *args, **kwargs):
#print("Connected! client={} userdata={} msg={}".format(client, userdata, msg))
print("Connected!", *args, **kwargs)
2019-07-09 22:01:39 +02:00
def send_data(self, topic, data):
self._mqtt.publish(topic, json.dumps(data))
2019-07-31 22:31:50 +02:00
def set_callback(self, callback):
self._mqtt.on_message = lambda client, userdata, msg: callback(msg.topic, msg.payload.decode())
def process_mqtt(self):
self._mqtt.loop(0.01)
def subscribe(self, topic):
self._mqtt.subscribe(topic)