From 9a095d49cc1e003d376f1d86b76c2d59436713fd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20S=C3=A1nchez-Gallego?= Date: Tue, 5 Dec 2023 22:38:39 +0000 Subject: [PATCH] Try-excepts attemps to write to modbus --- python/lvmecp/modbus.py | 32 +++++++++++++++++++------------- 1 file changed, 19 insertions(+), 13 deletions(-) diff --git a/python/lvmecp/modbus.py b/python/lvmecp/modbus.py index 397428d..65a7511 100644 --- a/python/lvmecp/modbus.py +++ b/python/lvmecp/modbus.py @@ -162,23 +162,29 @@ async def set(self, value: int | bool): else: raise ValueError(f"Invalid block mode {self.mode!r}.") - if self.client.connected: - resp = await func(self.address, value) # type: ignore - else: - async with self.modbus: + try: + if self.client.connected: resp = await func(self.address, value) # type: ignore + else: + async with self.modbus: + resp = await func(self.address, value) # type: ignore - if resp.function_code > 0x80: - msg = ( - f"Invalid response for element " - f"{self.name!r}: 0x{resp.function_code:02X}." - ) + if resp.function_code > 0x80: + msg = ( + f"Invalid response for element " + f"{self.name!r}: 0x{resp.function_code:02X}." + ) + else: + return - if ntries >= MAX_RETRIES: - raise ValueError(msg) + except Exception as err: + msg = f"Error raised while setting {self.name!r}: {err}" - warnings.warn(msg, ECPWarning) - await asyncio.sleep(0.5) + if ntries >= MAX_RETRIES: + raise ValueError(msg) + + warnings.warn(msg, ECPWarning) + await asyncio.sleep(0.5) class Modbus(dict[str, ModbusRegister]):