Skip to content

Commit

Permalink
Improve locking mechanism
Browse files Browse the repository at this point in the history
  • Loading branch information
albireox committed Nov 18, 2023
1 parent 80e49eb commit e39632e
Showing 1 changed file with 13 additions and 4 deletions.
17 changes: 13 additions & 4 deletions python/lvmecp/modbus.py
Original file line number Diff line number Diff line change
Expand Up @@ -257,13 +257,10 @@ async def disconnect(self):
async def __aenter__(self):
"""Initialises the connection to the server."""

# Acquire the lock, but also don't allow it to block for too long.
try:
await asyncio.wait_for(self.lock.acquire(), 10)
except asyncio.TimeoutError:
log.warning("Timed out waiting for lock to be released. Forcing release.")
self.lock.release()
await self.lock.acquire()
raise RuntimeError("Timed out waiting for lock to be released.")

try:
await self.connect()
Expand All @@ -273,6 +270,11 @@ async def __aenter__(self):

raise

# Schedule a task to release the lock after 5 seconds. This is a safeguard
# in case something fails and the connection is never closed and the lock
# not released.
asyncio.create_task(self.unlock_on_timeout())

async def __aexit__(self, exc_type, exc, tb):
"""Closes the connection to the server."""

Expand All @@ -282,6 +284,13 @@ async def __aexit__(self, exc_type, exc, tb):
if self.lock.locked():
self.lock.release()

async def unlock_on_timeout(self):
"""Removes the lock after an amount of time."""

await asyncio.sleep(10)
if self.lock.locked():
self.lock.release()

async def get_all(self):
"""Returns a dictionary with all the registers."""

Expand Down

0 comments on commit e39632e

Please sign in to comment.