-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathmqttClient.py
More file actions
44 lines (30 loc) · 1.36 KB
/
mqttClient.py
File metadata and controls
44 lines (30 loc) · 1.36 KB
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
import logging
import paho.mqtt.client as mq
import simplejson as json
import datetime
class mqClient():
def __init__(self, config, serno):
self.log = logging.getLogger(__name__)
self.topic = 'wn_{}/raw'.format(serno)
if config.has_section('mqtt'):
self.broker_url = config.get('mqtt', 'broker')
self.log.info("MQTT logging enabled to broker: {}".format(self.broker_url))
self.client = mq.Client()
self.client.on_connect = self.on_connect
self.client.loop_start()
self.client.connect_async(self.broker_url)
else:
self.client = None
self.broker_url = None
self.log.info("MQTT not enabled (set [mqtt] broker = ... )")
def on_connect(self, client, userdata, flags, rc):
self.log.info("MQTT connected with result: {}".format(rc))
def close(self):
if self.client:
self.client.loop_stop()
self.client = None
def pub(self, data):
if self.client:
s = json.dumps(data, default=datetime.datetime.isoformat)
self.log.debug("send: " + s)
self.client.publish(self.topic, s)