From dda9f3ed7dfca510ef1f4dbae070c2e591f14181 Mon Sep 17 00:00:00 2001 From: Pierrick C Date: Sat, 4 Aug 2018 22:20:19 +0200 Subject: [PATCH] Handle exception when the data is not correctly formatted or partial (ie : first start at boot time) --- raspberry/python/uart2mqtt.py | 43 +++++++++++++++++++---------------- 1 file changed, 23 insertions(+), 20 deletions(-) diff --git a/raspberry/python/uart2mqtt.py b/raspberry/python/uart2mqtt.py index f7dac8a..77bf8ae 100644 --- a/raspberry/python/uart2mqtt.py +++ b/raspberry/python/uart2mqtt.py @@ -68,29 +68,32 @@ 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)) + try: + 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(): - 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]]}) - print(payload) - mqtt.single("{}/{}".format(mqtt_topic, s[0]), - payload= payload , - qos= 2 , - retain= True , - hostname= mqtt_host , - port= mqtt_port , - client_id= mqtt_client_id , - auth= mqtt_auth ) + # Formatting data for sending to MQTT broker (one source at a time) + for s in data.items(): + 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]]}) + print(payload) + mqtt.single("{}/{}".format(mqtt_topic, s[0]), + payload= payload , + qos= 2 , + retain= True , + hostname= mqtt_host , + port= mqtt_port , + client_id= mqtt_client_id , + auth= mqtt_auth ) + except: + print("Bad data:\n{}".format(line))