Skip to content

Commit 2a4544a

Browse files
friederschueleracolombbizfsc
authored
eds: Fix signed integer limit parsing for all bit widths, log errors (#658)
* eds: fix LowLimit/HighLimit parsing for all signed integer types - Reimplement _calc_bit_length() (only handled INTEGER8/16/32/64) using the same structure types used in ODVariable. - Log a warning instead of silently ignoring invalid limit values - Add EDS test entries in sample.eds for INTEGER24/40/48/56 with hex-encoded negative limits - Extend test_record_with_limits and add test_invalid_limit_logs_warning * Enhance test coverage for _revert_variable() branches (without default_raw). * Renamed _convert_variable → _decode_from_eds and _revert_variable → _encode_to_eds Co-authored-by: André Colomb <src@andre.colomb.de> Co-authored-by: Frieder Schüler <frieder.schueler@bizerba.com>
1 parent ea0efa4 commit 2a4544a

3 files changed

Lines changed: 167 additions & 53 deletions

File tree

‎canopen/objectdictionary/eds.py‎

Lines changed: 51 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -205,14 +205,11 @@ def import_from_node(node_id: int, network: canopen.network.Network):
205205

206206

207207
def _calc_bit_length(data_type: int) -> int:
208-
if data_type == datatypes.INTEGER8:
209-
return 8
210-
elif data_type == datatypes.INTEGER16:
211-
return 16
212-
elif data_type == datatypes.INTEGER32:
213-
return 32
214-
elif data_type == datatypes.INTEGER64:
215-
return 64
208+
if data_type in datatypes.INTEGER_TYPES:
209+
st = ODVariable.STRUCT_TYPES[data_type]
210+
if isinstance(st, datatypes.IntegerN):
211+
return st.width
212+
return st.size * 8
216213
else:
217214
raise ValueError(
218215
f"Invalid data_type 0x{data_type:04X}, expecting an integer data_type."
@@ -221,15 +218,29 @@ def _calc_bit_length(data_type: int) -> int:
221218

222219
def _signed_int_from_hex(hex_str, bit_length):
223220
number = int(hex_str, 0)
224-
max_value = (1 << (bit_length - 1)) - 1
221+
min_signed = -(1 << (bit_length - 1))
222+
max_signed = (1 << (bit_length - 1)) - 1
223+
max_unsigned = (1 << bit_length) - 1
225224

226-
if number > max_value:
227-
return number - (1 << bit_length)
228-
else:
225+
if number < min_signed:
226+
raise ValueError(
227+
f"Value {hex_str!r} is out of range for a {bit_length}-bit signed integer"
228+
)
229+
if number < 0:
230+
# Negative literal (e.g. LowLimit=-32768 or -0x8000)
229231
return number
230232

233+
if number > max_unsigned:
234+
raise ValueError(
235+
f"Value {hex_str!r} is out of range for a {bit_length}-bit signed integer"
236+
)
237+
if number > max_signed:
238+
# Unsigned hex literal, two's-complement (e.g. LowLimit=0xFFFF → -1 for INTEGER16)
239+
return number - (1 << bit_length)
240+
return number
241+
231242

232-
def _convert_variable(node_id: int, var_type: int, value: Any) -> Any:
243+
def _decode_from_eds(node_id: int, var_type: int, value: Any) -> Any:
233244
if var_type in (datatypes.OCTET_STRING, datatypes.DOMAIN):
234245
return bytes.fromhex(value)
235246
elif var_type in (datatypes.VISIBLE_STRING, datatypes.UNICODE_STRING):
@@ -245,7 +256,7 @@ def _convert_variable(node_id: int, var_type: int, value: Any) -> Any:
245256
return int(value, 0)
246257

247258

248-
def _revert_variable(var_type: int, value: Any) -> Any:
259+
def _encode_to_eds(var_type: int, value: Any) -> Any:
249260
if value is None:
250261
return None
251262
if var_type in (datatypes.OCTET_STRING, datatypes.DOMAIN):
@@ -309,7 +320,10 @@ def build_variable(
309320
else:
310321
var.min = int(min_string, 0)
311322
except ValueError:
312-
pass
323+
logger.warning(
324+
"Invalid LowLimit %r for %s (0x%X), ignoring",
325+
min_string, var.name, var.index,
326+
)
313327
if eds.has_option(section, "HighLimit"):
314328
try:
315329
max_string = eds.get(section, "HighLimit")
@@ -318,38 +332,44 @@ def build_variable(
318332
else:
319333
var.max = int(max_string, 0)
320334
except ValueError:
321-
pass
335+
logger.warning(
336+
"Invalid HighLimit %r for %s (0x%X), ignoring",
337+
max_string, var.name, var.index,
338+
)
322339
if eds.has_option(section, "DefaultValue"):
323340
try:
324341
var.default_raw = eds.get(section, "DefaultValue")
325342
if '$NODEID' in var.default_raw:
326343
var.relative = True
327-
var.default = _convert_variable(node_id, var.data_type, var.default_raw)
344+
var.default = _decode_from_eds(node_id, var.data_type, var.default_raw)
328345
except ValueError:
329-
pass
346+
logger.warning(
347+
"Invalid DefaultValue %r for %s (0x%X), ignoring",
348+
var.default_raw, var.name, var.index,
349+
)
330350
if eds.has_option(section, "ParameterValue"):
331351
try:
332352
var.value_raw = eds.get(section, "ParameterValue")
333-
var.value = _convert_variable(node_id, var.data_type, var.value_raw)
353+
var.value = _decode_from_eds(node_id, var.data_type, var.value_raw)
334354
except ValueError:
335-
pass
355+
logger.warning(
356+
"Invalid ParameterValue %r for %s (0x%X), ignoring",
357+
var.value_raw, var.name, var.index,
358+
)
336359
# Factor, Description and Unit are not standard according to the CANopen specifications, but
337360
# they are implemented in the python canopen package, so we can at least try to use them
338361
if eds.has_option(section, "Factor"):
339362
try:
340363
var.factor = float(eds.get(section, "Factor"))
341364
except ValueError:
342-
pass
365+
logger.warning(
366+
"Invalid Factor %r for %s (0x%X), ignoring",
367+
eds.get(section, "Factor"), var.name, var.index,
368+
)
343369
if eds.has_option(section, "Description"):
344-
try:
345-
var.description = eds.get(section, "Description")
346-
except ValueError:
347-
pass
370+
var.description = eds.get(section, "Description")
348371
if eds.has_option(section, "Unit"):
349-
try:
350-
var.unit = eds.get(section, "Unit")
351-
except ValueError:
352-
pass
372+
var.unit = eds.get(section, "Unit")
353373
return var
354374

355375

@@ -400,15 +420,15 @@ def export_variable(var, eds):
400420
if getattr(var, 'default_raw', None) is not None:
401421
eds.set(section, "DefaultValue", var.default_raw)
402422
elif getattr(var, 'default', None) is not None:
403-
eds.set(section, "DefaultValue", _revert_variable(
423+
eds.set(section, "DefaultValue", _encode_to_eds(
404424
var.data_type, var.default))
405425

406426
if device_commisioning:
407427
if getattr(var, 'value_raw', None) is not None:
408428
eds.set(section, "ParameterValue", var.value_raw)
409429
elif getattr(var, 'value', None) is not None:
410430
eds.set(section, "ParameterValue",
411-
_revert_variable(var.data_type, var.value))
431+
_encode_to_eds(var.data_type, var.value))
412432

413433
eds.set(section, "DataType", f"0x{var.data_type:04X}")
414434
eds.set(section, "PDOMapping", hex(var.pdo_mappable))

‎test/sample.eds‎

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -967,6 +967,24 @@ HighLimit=0x0A
967967
LowLimit=0x02
968968
PDOMapping=0
969969

970+
[3022]
971+
ParameterName=UNSIGNED16 decimal limits
972+
ObjectType=0x7
973+
DataType=0x06
974+
AccessType=rw
975+
LowLimit=100
976+
HighLimit=1000
977+
PDOMapping=0
978+
979+
[3023]
980+
ParameterName=INTEGER16 decimal limits
981+
ObjectType=0x7
982+
DataType=0x03
983+
AccessType=rw
984+
LowLimit=-100
985+
HighLimit=100
986+
PDOMapping=0
987+
970988
[3030]
971989
ParameterName=INTEGER32 only negative values
972990
ObjectType=0x7
@@ -976,6 +994,42 @@ HighLimit=0xFFFFFFFF
976994
LowLimit=0x80000000
977995
PDOMapping=0
978996

997+
[3031]
998+
ParameterName=INTEGER24 value range -1 to 0
999+
ObjectType=0x7
1000+
DataType=0x10
1001+
AccessType=rw
1002+
HighLimit=0x000000
1003+
LowLimit=0xFFFFFF
1004+
PDOMapping=0
1005+
1006+
[3032]
1007+
ParameterName=INTEGER40 value range -1 to 0
1008+
ObjectType=0x7
1009+
DataType=0x12
1010+
AccessType=rw
1011+
HighLimit=0x0000000000
1012+
LowLimit=0xFFFFFFFFFF
1013+
PDOMapping=0
1014+
1015+
[3033]
1016+
ParameterName=INTEGER48 value range -1 to 0
1017+
ObjectType=0x7
1018+
DataType=0x13
1019+
AccessType=rw
1020+
HighLimit=0x000000000000
1021+
LowLimit=0xFFFFFFFFFFFF
1022+
PDOMapping=0
1023+
1024+
[3034]
1025+
ParameterName=INTEGER56 value range -1 to 0
1026+
ObjectType=0x7
1027+
DataType=0x14
1028+
AccessType=rw
1029+
HighLimit=0x00000000000000
1030+
LowLimit=0xFFFFFFFFFFFFFF
1031+
PDOMapping=0
1032+
9791033
[3040]
9801034
ParameterName=INTEGER64 value range -10 to +10
9811035
ObjectType=0x7

‎test/test_eds.py‎

Lines changed: 62 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,10 @@
1+
import io
12
import os
23
import unittest
4+
from configparser import RawConfigParser
35

46
import canopen
5-
from canopen.objectdictionary.eds import _signed_int_from_hex
7+
from canopen.objectdictionary.eds import _signed_int_from_hex, build_variable
68
from canopen.utils import pretty_index
79

810
from .util import DATATYPES_EDS, SAMPLE_EDS, tmp_file
@@ -70,8 +72,6 @@ def test_load_implicit_nodeid(self):
7072
self.assertEqual(od.node_id, 16)
7173

7274
def test_load_implicit_nodeid_fallback(self):
73-
import io
74-
7575
# First, remove the NodeID option from DeviceComissioning.
7676
with open(SAMPLE_EDS) as f:
7777
lines = [L for L in f.readlines() if not L.startswith("NodeID=")]
@@ -93,8 +93,6 @@ def test_load_baudrate(self):
9393
self.assertEqual(od.bitrate, 500_000)
9494

9595
def test_load_baudrate_fallback(self):
96-
import io
97-
9896
# Remove the Baudrate option.
9997
with open(SAMPLE_EDS) as f:
10098
lines = [L for L in f.readlines() if not L.startswith("Baudrate=")]
@@ -136,18 +134,23 @@ def test_record(self):
136134
self.assertFalse(var.is_domain)
137135

138136
def test_record_with_limits(self):
139-
int8 = self.od[0x3020]
140-
self.assertEqual(int8.min, 0)
141-
self.assertEqual(int8.max, 127)
142-
uint8 = self.od[0x3021]
143-
self.assertEqual(uint8.min, 2)
144-
self.assertEqual(uint8.max, 10)
145-
int32 = self.od[0x3030]
146-
self.assertEqual(int32.min, -2147483648)
147-
self.assertEqual(int32.max, -1)
148-
int64 = self.od[0x3040]
149-
self.assertEqual(int64.min, -10)
150-
self.assertEqual(int64.max, +10)
137+
cases = [
138+
(0x3020, 0, 127), # _ INTEGER8 hex limits
139+
(0x3021, 2, 10), # _ UNSIGNED8 hex limits
140+
(0x3022, 100, 1000), # _ UNSIGNED16 decimal limits
141+
(0x3023, -100, 100), # _ INTEGER16 decimal limits
142+
(0x3030, -2147483648, -1), # _ INTEGER32 hex limits
143+
(0x3031, -1, 0), # _ INTEGER24 hex limits
144+
(0x3032, -1, 0), # _ INTEGER40 hex limits
145+
(0x3033, -1, 0), # _ INTEGER48 hex limits
146+
(0x3034, -1, 0), # _ INTEGER56 hex limits
147+
(0x3040, -10, +10), # _ INTEGER64 hex limits
148+
]
149+
for index, expected_min, expected_max in cases:
150+
with self.subTest(index=f"0x{index:04X}"):
151+
var = self.od[index]
152+
self.assertEqual(var.min, expected_min)
153+
self.assertEqual(var.max, expected_max)
151154

152155
def test_signed_int_from_hex(self):
153156
for data_type, test_cases in self.test_data.items():
@@ -156,6 +159,37 @@ def test_signed_int_from_hex(self):
156159
result = _signed_int_from_hex('0x' + test_case["hex_str"], test_case["bit_length"])
157160
self.assertEqual(result, test_case["expected"])
158161

162+
def test_signed_int_from_hex_accepts_decimal(self):
163+
# Negative decimal values are valid EDS literals (CiA 306 allows both formats).
164+
self.assertEqual(_signed_int_from_hex("-1", 8), -1)
165+
self.assertEqual(_signed_int_from_hex("-128", 8), -128)
166+
self.assertEqual(_signed_int_from_hex("-2147483648", 32), -2147483648)
167+
168+
def test_signed_int_from_hex_rejects_out_of_range(self):
169+
with self.assertRaises(ValueError):
170+
_signed_int_from_hex("0xFFFF", 8) # 16-bit value into 8-bit field
171+
with self.assertRaises(ValueError):
172+
_signed_int_from_hex("-129", 8) # below minimum for 8-bit signed
173+
174+
def test_build_variable_range_warnings(self):
175+
eds = RawConfigParser()
176+
cases = [
177+
("2003", "LowLimit", str(-0xFFFF)), # INTEGER16 < signed min
178+
("2003", "HighLimit", "0x10000"), # INTEGER16 > unsigned max
179+
("2001", "DefaultValue", "SOMETHING"), # BOOLEAN non-numeric
180+
("2003", "DefaultValue", "SOMETHING"), # INTEGER16 non-numeric
181+
("2006", "ParameterValue", ""), # UNSIGNED16 empty
182+
]
183+
for index, option, value in cases:
184+
with self.subTest(index=index, option=option, value=value):
185+
# Fresh version for mutating temporarily
186+
eds.clear()
187+
eds.read(DATATYPES_EDS)
188+
eds[index][option] = value
189+
with self.assertLogs(level="WARN") as cm:
190+
build_variable(eds, index, node_id=42, object_type=7, index=int(index, 16))
191+
self.assertRegex(cm.output[0], option)
192+
159193
def test_array_compact_subobj(self):
160194
array = self.od[0x1003]
161195
self.assertIsInstance(array, canopen.objectdictionary.ODArray)
@@ -240,7 +274,6 @@ def test_read_domain_subobject(self):
240274

241275
def test_roundtrip_domain_objects(self):
242276
# ObjectType==DOMAIN survive an EDS export/import round-trip
243-
import io
244277
with io.StringIO() as dest:
245278
canopen.export_od(self.od, dest, 'eds')
246279
dest.name = 'mock.eds'
@@ -251,6 +284,17 @@ def test_roundtrip_domain_objects(self):
251284
self.assertTrue(od2[0x3063].is_domain)
252285
self.assertTrue(od2[0x3064][1].is_domain)
253286

287+
def test_export_without_raw_default_values(self):
288+
od = canopen.import_od(DATATYPES_EDS)
289+
# Make sure the values are not cached in raw form
290+
for var in od.values():
291+
try:
292+
delattr(var, 'default_raw')
293+
except AttributeError:
294+
pass
295+
with io.StringIO() as dest:
296+
canopen.export_od(od, dest, 'eds')
297+
254298

255299
def test_comments(self):
256300
self.assertEqual(self.od.comments,
@@ -271,7 +315,6 @@ def test_export_eds_to_file(self):
271315
self.verify_od(dest, doctype)
272316

273317
def test_export_eds_to_file_unknown_extension(self):
274-
import io
275318
for suffix in ".txt", "":
276319
with tmp_file(suffix=suffix) as tmp:
277320
dest = tmp.name
@@ -294,7 +337,6 @@ def test_export_eds_to_file_unknown_extension(self):
294337
self.verify_od(buf, "eds")
295338

296339
def test_export_eds_unknown_doctype(self):
297-
import io
298340
filelike_object = io.StringIO()
299341
self.addCleanup(filelike_object.close)
300342
for dest in "filename", None, filelike_object:
@@ -307,7 +349,6 @@ def test_export_eds_unknown_doctype(self):
307349
os.stat(dest)
308350

309351
def test_export_eds_to_filelike_object(self):
310-
import io
311352
for doctype in "eds", "dcf":
312353
with io.StringIO() as dest:
313354
with self.subTest(dest=dest, doctype=doctype):
@@ -321,7 +362,6 @@ def test_export_eds_to_filelike_object(self):
321362

322363
def test_export_eds_to_stdout(self):
323364
import contextlib
324-
import io
325365
with contextlib.redirect_stdout(io.StringIO()) as f:
326366
ret = canopen.export_od(self.od, None, "eds")
327367
self.assertIsNone(ret)

0 commit comments

Comments
 (0)