Cameteo/raspberry/python/uart2mqtt.py
2018-08-04 19:04:17 +02:00

99 lines
3.3 KiB
Python

#!/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 )