Skip to content

Commit b14b494

Browse files
committed
fix: resolve the precision issue of float data
1 parent 106901c commit b14b494

File tree

2 files changed

+13
-5
lines changed

2 files changed

+13
-5
lines changed

src/aceinna/devices/parsers/open_field_parser.py

Lines changed: 12 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,9 @@
11
import math
22
import struct
3+
import decimal
34

45

5-
def do_decode_value(data_type, data):
6+
def do_decode_value(data_type, data, conf):
67
if data_type == 'uint64':
78
try:
89
pack_item = struct.pack('8B', *data)
@@ -38,7 +39,14 @@ def do_decode_value(data_type, data):
3839
pack_item = struct.pack('4B', *data)
3940
except: # pylint: disable=bare-except
4041
return False
41-
return struct.unpack('<f', pack_item)[0]
42+
43+
unpack_value = struct.unpack('<f', pack_item)[0]
44+
# use decimal, float type is a special case
45+
if conf and conf['value_accuracy']:
46+
precision = conf['value_accuracy']
47+
decimal_wrapped = decimal.Decimal(unpack_value)
48+
unpack_value = float(round(decimal_wrapped, precision))
49+
return unpack_value
4250
elif data_type == 'uint16':
4351
try:
4452
pack_item = struct.pack('2B', *data)
@@ -104,8 +112,8 @@ def do_decode_value(data_type, data):
104112
return False
105113

106114

107-
def decode_value(data_type, data):
108-
ret_value = do_decode_value(data_type, data)
115+
def decode_value(data_type, data, conf=None):
116+
ret_value = do_decode_value(data_type, data, conf)
109117

110118
if not isinstance(ret_value, float):
111119
return ret_value

src/aceinna/devices/parsers/open_packet_parser.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -104,7 +104,7 @@ def get_parameters_by_block_parser(payload, user_configuration):
104104
data_len = data_len + 2
105105
elif param_type == 'uint32' or param_type == 'int32' or param_type == 'float':
106106
value = decode_value(
107-
param_type, payload[data_len:data_len + 4])
107+
param_type, payload[data_len:data_len + 4], exist_param_conf)
108108
data_len = data_len + 4
109109
elif param_type == 'uint64' or param_type == 'int64' or param_type == 'double':
110110
value = decode_value(

0 commit comments

Comments
 (0)