pyModbusTCP icon indicating copy to clipboard operation
pyModbusTCP copied to clipboard

auto open and auto close

Open amarco opened this issue 9 months ago • 1 comments

I am new to pyModbusTCP and I am wondering if I have to poll 20 different registers which are not in continuous order by register number and I use auto open and auto close set to TRUE do I have to worry about calling open() and close() on my client for each transaction. I am polling all register every hour. I am just wondering what people find are best practices for reliable communication over tcp/ip.

amarco avatar May 11 '24 13:05 amarco

Hi, it's a bit difficult to advise you, as it largely depends on the behavior of the device to which you are connecting. I would say that since you are exchanging a small amount of data every hour, I would manage the socket manually. This avoid to keep the socket open for a long time without any exchange on it.

Like this:

import time
from pyModbusTCP.client import ModbusClient


# init modbus client
c = ModbusClient(host='localhost', auto_open=False, auto_close=False)

# polling loop
while True:
    # open TCP socket
    if c.open():
        # modbus i/o
        ret_read = c.read_holding_registers(0)
        if ret_read:
            print(f'@0 = {ret_read[0]}')
        ret_read = c.read_holding_registers(100)
        if ret_read:
            print(f'@100 = {ret_read[0]}')
        # [...]
        # clean TCP close
        c.close()
    else:
        print('unable to connect to device')
    # wait next polling
    time.sleep(3600)

sourceperl avatar May 14 '24 08:05 sourceperl