77import argparse
88import json
99import platform
10+ import decimal
1011import yaml
1112import serial
1213import serial .tools .list_ports
2930LOG_FORMAT = '%(asctime)s %(levelname)s: %(message)s'
3031
3132
33+ class FakeFloat (float ):
34+
35+ def __init__ (self , value ):
36+ self ._value = value
37+
38+ def __repr__ (self ):
39+ return str (self ._value )
40+
41+
42+ def decimal_default (obj ):
43+ if isinstance (obj , decimal .Decimal ):
44+ return FakeFloat (obj )
45+ raise TypeError
46+
47+
3248def mqtt_on_connect (client , userdata , flags , rc ):
3349 logging .info ('Connected to MQTT broker with code %s' , rc )
3450 client .subscribe (userdata ['base_topic' ] + '+/+/+/+/+' )
3551
3652
3753def mqtt_on_message (client , userdata , message ):
3854 subtopic = message .topic [len (userdata ['base_topic' ]):]
39- payload = message .payload if msg .payload else b'null'
55+ payload = message .payload if message .payload else b'null'
4056 userdata ['serial' ].write (b'["' + subtopic .encode ('utf-8' ) + b'",' + payload + b']\n ' )
4157
4258
@@ -56,7 +72,7 @@ def run():
5672 mqttc = paho .mqtt .client .Client (userdata = {'serial' : ser , 'base_topic' : base_topic })
5773 mqttc .on_connect = mqtt_on_connect
5874 mqttc .on_message = mqtt_on_message
59- mqttc .connect (config ['mqtt' ]['host' ], config ['mqtt' ]['port' ], keepalive = 10 )
75+ mqttc .connect (config ['mqtt' ]['host' ], int ( config ['mqtt' ]['port' ]) , keepalive = 10 )
6076 mqttc .loop_start ()
6177
6278 while True :
@@ -68,11 +84,11 @@ def run():
6884 if line :
6985 logging .debug (line )
7086 try :
71- talk = json .loads (line .decode ())
87+ talk = json .loads (line .decode (), parse_float = decimal . Decimal )
7288 except Exception :
7389 logging .error ('Invalid JSON message received from serial port: %s' , line )
7490 try :
75- mqttc .publish (base_topic + talk [0 ], json .dumps (talk [1 ]), qos = 1 )
91+ mqttc .publish (base_topic + talk [0 ], json .dumps (talk [1 ], default = decimal_default ), qos = 1 )
7692 except Exception :
7793 logging .error ('Failed to publish MQTT message: %s' , line )
7894
0 commit comments