Skip to content

Commit

Permalink
Add timeout for wait for reconnect for Modbus TCP.
Browse files Browse the repository at this point in the history
  • Loading branch information
kratochvil01 committed Aug 28, 2024
1 parent 07b5dc9 commit 66f874b
Showing 1 changed file with 6 additions and 3 deletions.
9 changes: 6 additions & 3 deletions evok/modbus_unipi.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ class ModbusException(Exception):

class EvokModbusSerialClient(AsyncModbusSerialClient):
def __init__(self, port: str, framer: Type[ModbusFramer] = ModbusRtuFramer, baudrate: int = 19200,
bytesize: int = 8, parity: str = "N", stopbits: int = 1, **kwargs: Any) -> None:
bytesize: int = 8, parity: str = "N", stopbits: int = 1, timeout: float = 1, **kwargs: Any) -> None:
super().__init__(port, framer, baudrate, bytesize, parity, stopbits, retries=0, **kwargs)
for method_name in ['read_holding_registers', 'read_input_registers', 'write_register', 'write_registers',
'write_coil', 'connect']:
Expand All @@ -30,6 +30,7 @@ def __init__(self, port: str, framer: Type[ModbusFramer] = ModbusRtuFramer, baud
self.lock = asyncio.Lock()
self.stime = time.time()
self.block_count = 0
self.__timeout = timeout

def __runtime(self):
return int((time.time()-self.stime)*1000)
Expand All @@ -51,7 +52,7 @@ async def ret(*args, **kwargs):

class EvokModbusTcpClient(AsyncModbusTcpClient):
def __init__(self, host: str, port: int = 502, framer: Type[ModbusFramer] = ModbusSocketFramer,
source_address: Tuple[str, int] = None, **kwargs: Any) -> None:
source_address: Tuple[str, int] = None, timeout: float = 1, **kwargs: Any) -> None:
super().__init__(host, port, framer, source_address, retries=0, **kwargs)
for method_name in ['read_holding_registers', 'read_input_registers', 'write_register', 'write_registers',
'write_coil']:
Expand All @@ -60,10 +61,12 @@ def __init__(self, host: str, port: int = 502, framer: Type[ModbusFramer] = Modb
self.lock = asyncio.Lock()
self.stime = time.time()
self.block_count = 0
self.__timeout = timeout

def __block(self, operation: Callable):
async def ret(*args, **kwargs):
while not self.connected:
start_stamp = time.time()
while not self.connected and time.time() - start_stamp < self.__timeout:
await asyncio.sleep(0.001)
aret = await operation(*args, **kwargs)
if type(aret) in exception_classes:
Expand Down

0 comments on commit 66f874b

Please sign in to comment.