AllWize Library
serial2mqtt.py
Go to the documentation of this file.
1 #
2 #
3 # AllWize - WIZE 2 Serial Bridge with CayenneLPP
4 #
5 # Listens to messages in the serial port, decodes using CayenneLPP and forwards them to an MQTT broker.
6 # Requires pyserial, paho-mqtt and python-cayennelpp packages:
7 #
8 # `pip install pyserial paho-mqtt python-cayennelpp`.
9 #
10 # You might also need to give permissions to the dialout group to the current user
11 # if on Linux /Raspberry Pi): `sudo adduser $USER dialout`
12 #
13 # Copyright (C) 2018-2020 by AllWize <github@allwize.io>
14 #
15 # This program is free software: you can redistribute it and/or modify
16 # it under the terms of the GNU General Public License as published by
17 # the Free Software Foundation, either version 3 of the License, or
18 # (at your option) any later version.
19 #
20 # This program is distributed in the hope that it will be useful,
21 # but WITHOUT ANY WARRANTY; without even the implied warranty of
22 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
23 # GNU Lesser General Public License for more details.
24 #
25 # You should have received a copy of the GNU Lesser General Public License
26 # along with this program. If not, see <http://www.gnu.org/licenses/>.
27 #
28 
29 import serial
30 import paho.mqtt.client as mqtt
31 from python_cayennelpp.decoder import decode
32 
33 # configuration
34 SERIAL_PORT = "/dev/ttyACM0"
35 SERIAL_BAUD = 115200
36 
37 MQTT_TOPIC = "device/%s/payload"
38 MQTT_SERVER = "localhost"
39 MQTT_PORT = 1883
40 #MQTT_USER =
41 #MQTT_PASS =
42 MQTT_QOS = 2
43 MQTT_RETAIN = 0
44 
45 def send(topic, payload):
46  print("[MQTT] Sending %s => %s" % (topic, payload))
47  client.publish(topic, payload, MQTT_QOS, MQTT_RETAIN)
48 
49 # parse message
50 def parse(data):
51 
52  parts = data.rstrip().split(",")
53  if len(parts) != 4:
54  print("[PARSER] Wrong number of fields")
55  return
56  device = parts[0]
57  counter = parts[1]
58  rssi = parts[2]
59  payload = parts[3]
60  fields = decode(payload)
61 
62  for f in fields:
63  name = f["name"].replace(' ', '_').lower()
64  if isinstance(f["value"], dict):
65  for k, v in f["value"].items():
66  name = k.replace(' ', '_').lower()
67  topic = "device/%s/%s" % (device, name)
68  send(topic, v)
69 
70  else:
71  topic = "device/%s/%s" % (device, name)
72  send(topic, f["value"])
73 
74 # callback functions
75 def on_connect(client, userdata, flags, rc):
76  print("[MQTT] Connected")
77 
78 client = mqtt.Client()
79 client.on_connect = on_connect
80 print("[MQTT] Connecting...")
81 client.connect(MQTT_SERVER, MQTT_PORT, 60)
82 
83 # connect to device
84 ser = serial.Serial(SERIAL_PORT, SERIAL_BAUD, timeout=0.5)
85 while True:
86  line = ser.readline()
87  if len(line) and line[0] != "#":
88  print("[SERIAL] Received %s" % line.rstrip())
89  parse(line)
90  client.loop()