sourceperl / pyModbusTCP

A simple Modbus/TCP library for Python
MIT License
308 stars 106 forks source link

auto open and auto close #83

Closed amarco closed 4 months ago

amarco commented 6 months ago

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.

sourceperl commented 6 months ago

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)