forked from theolind/pymysensors
-
Notifications
You must be signed in to change notification settings - Fork 1
/
mqtt.py
60 lines (44 loc) · 1.7 KB
/
mqtt.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
"""Example for using pymysensors with mqtt."""
import paho.mqtt.client as mqtt # pylint: disable=E0401
import mysensors.mysensors as mysensors
class MQTT(object):
"""MQTT client example."""
# pylint: disable=unused-argument
def __init__(self, broker, port, keepalive):
"""Setup MQTT client."""
self.topics = {}
self._mqttc = mqtt.Client()
self._mqttc.connect(broker, port, keepalive)
def publish(self, topic, payload, qos, retain):
"""Publish an MQTT message."""
self._mqttc.publish(topic, payload, qos, retain)
def subscribe(self, topic, callback, qos):
"""Subscribe to an MQTT topic."""
if topic in self.topics:
return
def _message_callback(mqttc, userdata, msg):
"""Callback added to callback list for received message."""
callback(msg.topic, msg.payload.decode('utf-8'), msg.qos)
self._mqttc.subscribe(topic, qos)
self._mqttc.message_callback_add(topic, _message_callback)
self.topics[topic] = callback
def start(self):
"""Run the MQTT client."""
print('Start MQTT client')
self._mqttc.loop_start()
def stop(self):
"""Stop the MQTT client."""
print('Stop MQTT client')
self._mqttc.disconnect()
self._mqttc.loop_stop()
def event(update_type, nid):
"""Callback for mysensors updates."""
print(update_type + " " + str(nid))
MQTTC = MQTT('localhost', 1883, 60)
MQTTC.start()
GATEWAY = mysensors.MQTTGateway(
MQTTC.publish, MQTTC.subscribe, event_callback=event,
protocol_version="2.0", in_prefix='mygateway1-out',
out_prefix='mygateway1-in', retain=True)
GATEWAY.debug = True
GATEWAY.start()