Skip to content

Commit 2635b3f

Browse files
committed
Fix returned numbers in PDO.__iter__().
The base iterators of rx and tx return a 1-based sequence, while the wrapping PDO class allows only mapping or communication record index numbers to identify a PdoMap object. Return the mapping record's index from the iterator to avoid ambiguity. Add tests to verify the returned objects are actually the RPDO and TPDO members (in this order), with strictly increasing index numbers.
1 parent 60c417b commit 2635b3f

File tree

2 files changed

+18
-1
lines changed

2 files changed

+18
-1
lines changed

canopen/pdo/__init__.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,10 @@ def __init__(self, node, rpdo: PdoBase, tpdo: PdoBase):
4343
self.map.maps[self.tx.com_offset + (key - 1)] = value
4444

4545
def __iter__(self) -> Iterator[int]:
46-
return itertools.chain(self.rx, self.tx)
46+
return itertools.chain(
47+
(self.rx.map_offset + i - 1 for i in self.rx),
48+
(self.tx.map_offset + i - 1 for i in self.tx),
49+
)
4750

4851
def __len__(self) -> int:
4952
return len(self.rx) + len(self.tx)

test/test_pdo.py

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -79,6 +79,20 @@ def test_pdo_getitem(self):
7979
self.assertRaises(KeyError, lambda: node.pdo[0x1BFF])
8080
self.assertRaises(KeyError, lambda: node.tpdo[0x1BFF])
8181

82+
def test_pdo_iterate(self):
83+
node = self.node
84+
pdo_iter = iter(node.pdo.items())
85+
prev = 0 # To check strictly increasing record index number
86+
for rpdo, (index, pdo) in zip(node.rpdo.values(), pdo_iter):
87+
self.assertIs(rpdo, pdo)
88+
self.assertGreater(index, prev)
89+
prev = index
90+
# Continue consuming from pdo_iter
91+
for tpdo, (index, pdo) in zip(node.tpdo.values(), pdo_iter):
92+
self.assertIs(tpdo, pdo)
93+
self.assertGreater(index, prev)
94+
prev = index
95+
8296
def test_pdo_maps_iterate(self):
8397
node = self.node
8498
self.assertEqual(len(node.pdo), sum(1 for _ in node.pdo))

0 commit comments

Comments
 (0)