PyModbus - trigger an action/function when holding register is read

313 Views Asked by At

I've setup a running Pymodbus server based on the 'Updating Server' (v2.5.3) example. https://pymodbus.readthedocs.io/en/v2.5.3/source/example/updating_server.html Everything works ok.

Now i want to trigger a function (which will simply increment a value by 1), when (any) client is requesting to read/poll the contents of the holdingregisters. Console output, when client requests function code 3

My knowledge of Pymodbus is limited, so any help would be great.

1

There are 1 best solutions below

0
ZombieGreedo On

There is likely a way to overload the StartTCPServer function, though looking through the source code it seems tricky since it's built on asyncio (not like that's bad, just less conducive to easily overloading this one thing you're trying to do).

However there are several modbus libraries you can use, and sourceperl's pyModbusTCP makes it very easy to do exactly what you're trying to do. Check out the example https://github.com/sourceperl/pyModbusTCP/blob/master/examples/server_change_log.py

There they use the built-in hooks for doing just that, but you can get easily overload any part of the server if you wanted to for example capture the incoming modbus message before it gets processed.