Skip to content

Commit 829f462

Browse files
authored
SyncProducer: Prevent from starting another periodic task (fixes #582) (#600)
Raise a RuntimeError when a SYNC transmission task has previously been started. Make sure to clear the internal _task attribute when stopping, to make the check work.
1 parent be9c56d commit 829f462

File tree

2 files changed

+23
-3
lines changed

2 files changed

+23
-3
lines changed

canopen/sync.py

Lines changed: 13 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -15,32 +15,42 @@ class SyncProducer:
1515
def __init__(self, network: canopen.network.Network):
1616
self.network = network
1717
self.period: Optional[float] = None
18-
self._task = None
18+
self._task: Optional[canopen.network.PeriodicMessageTask] = None
1919

2020
def transmit(self, count: Optional[int] = None):
2121
"""Send out a SYNC message once.
2222
2323
:param count:
2424
Counter to add in message.
25+
:raises ValueError:
26+
If the counter value does not fit in one byte.
2527
"""
26-
data = [count] if count is not None else []
28+
data = bytes([count]) if count is not None else b""
2729
self.network.send_message(self.cob_id, data)
2830

2931
def start(self, period: Optional[float] = None):
3032
"""Start periodic transmission of SYNC message in a background thread.
3133
3234
:param period:
3335
Period of SYNC message in seconds.
36+
:raises RuntimeError:
37+
If a periodic transmission is already started.
38+
:raises ValueError:
39+
If no period is set via argument nor the instance attribute.
3440
"""
41+
if self._task is not None:
42+
raise RuntimeError("Periodic SYNC transmission task already running")
43+
3544
if period is not None:
3645
self.period = period
3746

3847
if not self.period:
3948
raise ValueError("A valid transmission period has not been given")
4049

41-
self._task = self.network.send_periodic(self.cob_id, [], self.period)
50+
self._task = self.network.send_periodic(self.cob_id, b"", self.period)
4251

4352
def stop(self):
4453
"""Stop periodic transmission of SYNC message."""
4554
if self._task is not None:
4655
self._task.stop()
56+
self._task = None

test/test_sync.py

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -74,6 +74,16 @@ def periodicity():
7474
if msg is not None:
7575
self.assertIsNone(self.net.bus.recv(TIMEOUT))
7676

77+
def test_sync_producer_restart(self):
78+
self.sync.start(PERIOD)
79+
self.addCleanup(self.sync.stop)
80+
# Cannot start again while running
81+
with self.assertRaises(RuntimeError):
82+
self.sync.start(PERIOD)
83+
# Can restart after stopping
84+
self.sync.stop()
85+
self.sync.start(PERIOD)
86+
7787

7888
if __name__ == "__main__":
7989
unittest.main()

0 commit comments

Comments
 (0)