Skip to content
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

fix: prevent multiple tasks from using the same connection #5

Merged
merged 2 commits into from
Oct 23, 2024
Merged
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
5 changes: 4 additions & 1 deletion tcp_modbus_aio/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -446,6 +446,8 @@ async def send_modbus_message(
raise ModbusConcurrencyError(
f"Failed to acquire lock to send request {msg_str} to modbus device {self.host}"
)

i_have_lock = True
time_budget_remaining -= lock_t()

try:
Expand Down Expand Up @@ -528,6 +530,7 @@ async def send_modbus_message(

# release the lock before retrying (so we can re-get it)
self._comms_lock.release()
i_have_lock = False # Don't release someone elses lock in the finally

return await self.send_modbus_message(
request_function,
Expand All @@ -539,7 +542,7 @@ async def send_modbus_message(
f"Request {msg_str} failed to {self.host}:{self.port} ({type(e).__name__}({e}))"
) from e
finally:
if self._comms_lock.locked():
if self._comms_lock.locked() and i_have_lock:
self._comms_lock.release()

self._consecutive_timeouts = 0
Expand Down