Skip to content

Commit

Permalink
Refactor linktest thread.
Browse files Browse the repository at this point in the history
  • Loading branch information
farhanmustar committed Nov 11, 2024
1 parent d3693cf commit 6678acd
Showing 1 changed file with 27 additions and 17 deletions.
44 changes: 27 additions & 17 deletions secsgem/hsms/handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,8 @@ def onConnect(event, data):
self.systemCounter = random.randint(0, (2 ** 32) - 1)

# repeating linktest variables
self.linktestTimer = None
self.linktestEvent = None
self.linktestThread = None
self.linktestTimeout = 30

# select request thread for active connections, to avoid blocking state changes
Expand Down Expand Up @@ -158,12 +159,6 @@ def _send_select_req_thread(self):
if response is None:
self.logger.warning("select request failed")

def _start_linktest_timer(self):
self.linktestTimer = threading.Timer(self.linktestTimeout, self._on_linktest_timer)
self.linktestTimer.daemon = True # kill thread automatically on main program termination
self.linktestTimer.name = "secsgem_hsmsHandler_linktestTimer"
self.linktestTimer.start()

def _on_state_connect(self):
"""
Handle connection state model got event connect.
Expand All @@ -189,10 +184,7 @@ def _on_state_disconnect(self):
:type data: object
"""
# stop linktest timer
if self.linktestTimer:
self.linktestTimer.cancel()

self.linktestTimer = None
self._stop_linktest_timer()

def _on_state_select(self):
"""
Expand All @@ -208,13 +200,31 @@ def _on_state_select(self):
if hasattr(self, '_on_hsms_select') and callable(getattr(self, '_on_hsms_select')):
self._on_hsms_select()

def _on_linktest_timer(self):
"""Linktest time timed out, so send linktest request."""
# send linktest request and wait for response
self.send_linktest_req()
def _start_linktest_timer(self):
if self.linktestEvent:
return

# restart the timer
self._start_linktest_timer()
self.linktestEvent = threading.Event()
self.linktestThread = threading.Thread(target=self._linktest_thread)
self.linktestThread.daemon = True # kill thread automatically on main program termination
self.linktestThread.name = "secsgem_hsmsHandler_linktestTimer"
self.linktestThread.start()

def _stop_linktest_timer(self):
if not self.linktestEvent:
return

self.linktestEvent.set()
self.linktestThread.join()

self.linktestEvent = None
self.linktestThread = None

def _linktest_thread(self):

while not self.linktestEvent.wait(self.linktestTimeout):
# send linktest request and wait for response
self.send_linktest_req()

def on_connection_established(self, _):
"""Handle connection was established event."""
Expand Down

0 comments on commit 6678acd

Please sign in to comment.