Add: data receveid on UART as compact JSON are sended to MQTT broker.

Old obsolete script deleted
This commit is contained in:
Pierrick C 2018-08-04 19:04:17 +02:00
parent d7e4705abd
commit 01dd30d2cf
2 changed files with 98 additions and 69 deletions

View File

@ -1,69 +0,0 @@
#!/usr/bin/python3
# -*- coding: UTF8 -*-
# Reception de données depuis un arduino via port série
version = "0.1"
#Configuration du port série
port_serie = "/dev/ttyACM1"
#port_serie_alt = "/dev/ttyACM1"
baud_rate = 115200
#############
import serial
from pprint import pprint
str_line = [] #une ligne de donnée lue sur le port série et prétraitée
data = dict() #une donnée d'un capteur
data_package = dict() #un paquet de donnée à un moment
data_set = dict() #ensemble des paquets de données
with serial.Serial(port_serie, baud_rate) as comm: #, timeout = 0
print("Initialization du microcontroleur en cours...")
while True:
line = comm.readline()
if line == b'###Init_end###\r\n' :
break
else:
print(".")
while True:
line = comm.readline()
if line == b'###Data_start###\r\n' :
break
else:
print("En attente d'un nouveau paquet de données...")
while True:
line = comm.readline()
if line == b'###Data_start###\r\n' :
print("Nouveau paquet de données !")
#break
elif line == b'###Data_end###\r\n' :
print("Fin du paquet de données !")
else:
#Nettoyage des caractères spéciaux inutile (retour chariot...) et
# conversion en liste de chaînes de caractères
str_line = line.decode("ascii").strip().split('\t')
#Mise en tableau de données
data['type'] = str_line[0].strip()
data['sensor'] = str_line[1].strip()
data['value'] = str_line[2].strip()
if len(str_line) > 3 and str_line[3].strip() != "-":
data['unit'] = str_line[3].strip()
else:
data['unit'] = None
if len(str_line) > 4:
data['comment'] = str_line[4]
else:
data['comment'] = None
data_package[data['type'] + "_" + data['sensor']] = data
data = {}
pprint(data_package)

View File

@ -0,0 +1,98 @@
#!/usr/bin/python3
# -*- coding: UTF8 -*-
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
"""
Transmit data from UART (GPIO) to MQTT broker
"""
__version__ = "0.1"
# Dictionnary of data types and units
data_type = {'cput' : "AT",
'temp': "AT",
'time': "TIME",
'hum': "RH",
'press': "AP",
'vbat': "VBAT",
'lat': "COOR",
'lon': "COOR",
'alt': "ALTI",
'pasl': "MSPL",
'qual': "MISC",
'age': "MISC"}
data_unit = {'cput' : "degC",
'temp': "degC",
'time': "",
'hum': "%",
'press': "hPa",
'vbat': "V",
'lat': "deg",
'lon': "deg",
'alt': "m",
'pasl': "hPa",
'qual': "",
'age': "s"}
###########
# Imports #
###########
import serial
import json
import pprint
import paho.mqtt.publish as mqtt
from cameteo_conf import *
########
# Main #
########
# Serial : UART settings
uart_name = "/dev/ttyAMA0" # ttyAMA0 = UART on GPIO
uart_baud_rate = 115200
# MQTT settings
mqtt_client_id = "uart"
mqtt_topic = "feather0"
with serial.Serial(uart_name, uart_baud_rate, timeout=2) as uart:
print(uart.name)
while True:
line = uart.readline()
if line != b'':
# If the line is not empty, it's data and they should be formatted as
# compact JSON as bytes. Lets decode and load everything !
data = json.loads(line.decode('utf8'))
reception_date = datetime.utcnow().strftime("%Y/%m/%d %H:%M:%S ")
#print("{} :\n{}".format(reception_date, data))
# Formatting data for sending to MQTT broker (one source at a time)
for s in data.items():
mqtt_data = []
for d in s[1].items():
payload = json.dumps({"date": reception_date,
"value": d[1],
"unit": data_unit[d[0]],
"type": data_type[d[0]]})
mqtt_data.append({'topic': "{}/{}".format(mqtt_topic, s[0]),
'payload': payload,
'qos': 2,
'retain': True})
pprint.pprint(mqtt_data)
mqtt.multiple(mqtt_data,
hostname= mqtt_host ,
port= mqtt_port ,
client_id= mqtt_client_id ,
auth= mqtt_auth )