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