AllWize Library
serial2idb.py
Go to the documentation of this file.
1 #
2 #
3 # AllWize - WIZE 2 InfluxDB Bridge with CayenneLPP
4 #
5 # Listens to messages in the serial port and inserts them to an InfluxDB instance.
6 # Requires pyserial, requests and python-cayennelpp packages:
7 #
8 # `pip install pyserial requests python-cayennelpp`.
9 #
10 # You might 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 requests
31 from python_cayennelpp.decoder import decode
32 
33 # configuration
34 SERIAL_PORT = "/dev/ttyACM0"
35 SERIAL_BAUD = 115200
36 
37 IDB_DATABASE = "data"
38 IDB_ENDPOINT = "http://localhost:8086/write?db=bridge"
39 
40 def send(data):
41  print("[IDB] Inserting %s" % data)
42  #requests.post(url = IDB_ENDPOINT, data = data)
43 
44 # parse message
45 def parse(data):
46 
47  parts = data.rstrip().split(",")
48  if len(parts) != 4:
49  print("[PARSER] Wrong number of fields")
50  return
51  device = parts[0]
52  counter = parts[1]
53  rssi = parts[2]
54  payload = parts[3]
55  fields = decode(payload)
56 
57  send("rssi,uid=%s value=%s" % (device, rssi))
58  for f in fields:
59  name = f["name"].replace(' ', '_').lower()
60  if isinstance(f["value"], dict):
61  data = "%s,uid=%s" % (name, device)
62  sep = " "
63  for k, v in f["value"].items():
64  name = k.replace(' ', '_').lower()
65  data = "%s%s%s=%s" % (data, sep, name, v)
66  sep = ","
67  send(data)
68 
69  else:
70  send("%s,uid=%s value=%s" % (name, device, f["value"]))
71 
72 # connect to device
73 ser = serial.Serial(SERIAL_PORT, SERIAL_BAUD, timeout=0.5)
74 while True:
75  line = ser.readline()
76  if len(line) and line[0] != "#":
77  print("[SERIAL] Received %s" % line.rstrip())
78  parse(line)