Skip to content

SyncProducer: Prevent from starting another periodic task (fixes #582) #600

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 13 additions & 3 deletions canopen/sync.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,32 +15,42 @@ class SyncProducer:
def __init__(self, network: canopen.network.Network):
self.network = network
self.period: Optional[float] = None
self._task = None
self._task: Optional[canopen.network.PeriodicMessageTask] = None

def transmit(self, count: Optional[int] = None):
"""Send out a SYNC message once.

:param count:
Counter to add in message.
:raises ValueError:
If the counter value does not fit in one byte.
"""
data = [count] if count is not None else []
data = bytes([count]) if count is not None else b""
self.network.send_message(self.cob_id, data)

def start(self, period: Optional[float] = None):
"""Start periodic transmission of SYNC message in a background thread.

:param period:
Period of SYNC message in seconds.
:raises RuntimeError:
If a periodic transmission is already started.
:raises ValueError:
If no period is set via argument nor the instance attribute.
"""
if self._task is not None:
raise RuntimeError("Periodic SYNC transmission task already running")

if period is not None:
self.period = period

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

self._task = self.network.send_periodic(self.cob_id, [], self.period)
self._task = self.network.send_periodic(self.cob_id, b"", self.period)

def stop(self):
"""Stop periodic transmission of SYNC message."""
if self._task is not None:
self._task.stop()
self._task = None
10 changes: 10 additions & 0 deletions test/test_sync.py
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,16 @@ def periodicity():
if msg is not None:
self.assertIsNone(self.net.bus.recv(TIMEOUT))

def test_sync_producer_restart(self):
self.sync.start(PERIOD)
self.addCleanup(self.sync.stop)
# Cannot start again while running
with self.assertRaises(RuntimeError):
self.sync.start(PERIOD)
# Can restart after stopping
self.sync.stop()
self.sync.start(PERIOD)


if __name__ == "__main__":
unittest.main()
Loading