Handle exception when the data is not correctly formatted or partial (ie : first start at boot time)
This commit is contained in:
parent
311a36fbdf
commit
dda9f3ed7d
@ -68,29 +68,32 @@ mqtt_topic = "feather0"
|
|||||||
|
|
||||||
with serial.Serial(uart_name, uart_baud_rate, timeout=2) as uart:
|
with serial.Serial(uart_name, uart_baud_rate, timeout=2) as uart:
|
||||||
print(uart.name)
|
print(uart.name)
|
||||||
|
|
||||||
while True:
|
while True:
|
||||||
line = uart.readline()
|
line = uart.readline()
|
||||||
|
|
||||||
if line != b'':
|
if line != b'':
|
||||||
# If the line is not empty, it's data and they should be formatted as
|
# If the line is not empty, it's data and they should be formatted as
|
||||||
# compact JSON as bytes. Lets decode and load everything !
|
# compact JSON as bytes. Lets decode and load everything !
|
||||||
data = json.loads(line.decode('utf8'))
|
try:
|
||||||
reception_date = datetime.utcnow().strftime("%Y/%m/%d %H:%M:%S ")
|
data = json.loads(line.decode('utf8'))
|
||||||
#print("{} :\n{}".format(reception_date, data))
|
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)
|
# Formatting data for sending to MQTT broker (one source at a time)
|
||||||
for s in data.items():
|
for s in data.items():
|
||||||
for d in s[1].items():
|
for d in s[1].items():
|
||||||
payload = json.dumps({"date": reception_date,
|
payload = json.dumps({"date": reception_date,
|
||||||
"value": d[1],
|
"value": d[1],
|
||||||
"unit": data_unit[d[0]],
|
"unit": data_unit[d[0]],
|
||||||
"type": data_type[d[0]]})
|
"type": data_type[d[0]]})
|
||||||
print(payload)
|
print(payload)
|
||||||
mqtt.single("{}/{}".format(mqtt_topic, s[0]),
|
mqtt.single("{}/{}".format(mqtt_topic, s[0]),
|
||||||
payload= payload ,
|
payload= payload ,
|
||||||
qos= 2 ,
|
qos= 2 ,
|
||||||
retain= True ,
|
retain= True ,
|
||||||
hostname= mqtt_host ,
|
hostname= mqtt_host ,
|
||||||
port= mqtt_port ,
|
port= mqtt_port ,
|
||||||
client_id= mqtt_client_id ,
|
client_id= mqtt_client_id ,
|
||||||
auth= mqtt_auth )
|
auth= mqtt_auth )
|
||||||
|
except:
|
||||||
|
print("Bad data:\n{}".format(line))
|
||||||
|
Loading…
Reference in New Issue
Block a user