AllWize Library
serial2mqtt.py
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 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 os
27 import sys
28 import glob
29 import serial
30 import paho.mqtt.client as mqtt
31 
32 # configuration
33 SERIAL_PORT = "/dev/ttyACM0"
34 SERIAL_BAUD = 115200
35 MQTT_TOPIC = "team/%s/field_%d"
36 MQTT_SERVER = "localhost"
37 MQTT_PORT = 1883
38 #MQTT_USER =
39 #MQTT_PASS =
40 MQTT_QOS = 2
41 MQTT_RETAIN = 0
42 
43 # parse message
44 def parse(data):
45  parts = data.rstrip().split(",")
46  fields = parts[5:]
47  ci = parts[3]
48  index = 0
49  for payload in fields:
50  index = index + 1
51  topic = MQTT_TOPIC % (ci, index)
52  print("[MQTT] Sending %s => %s" % (topic, payload))
53  client.publish(topic, payload, MQTT_QOS, MQTT_RETAIN)
54 
55 # callback functions
56 def on_connect(client, userdata, flags, rc):
57  print("[MQTT] Connected")
58 
59 client = mqtt.Client()
60 client.on_connect = on_connect
61 print("[MQTT] Connecting...")
62 client.connect(MQTT_SERVER, MQTT_PORT, 60)
63 
64 # connect to device
65 ser = serial.Serial(SERIAL_PORT, SERIAL_BAUD, timeout=0.5)
66 while True:
67  line = ser.readline()
68  if len(line) and line[0] != "#":
69  print("[SERIAL] Received %s" % line.rstrip())
70  parse(line)
71  client.loop()