Skip to content

Instantly share code, notes, and snippets.

@agutenkunst
Last active June 10, 2020 07:38
Show Gist options
  • Save agutenkunst/fc2d260ef9aabe34d8a9e8b3e19ae857 to your computer and use it in GitHub Desktop.
Save agutenkunst/fc2d260ef9aabe34d8a9e8b3e19ae857 to your computer and use it in GitHub Desktop.
Run Modbus Tests with Server using pymodbus

Install requirements

sudo apt-get install python3-pymodbus (maybe python2 also works, but I didn't check)

Run

Server Code

(see modbus_server.py)

Client code

(see modbus_client.py)

#!/usr/bin/env python
from pymodbus.client.sync import ModbusTcpClient as ModbusClient
client = ModbusClient('localhost', port=5020)
client.connect()
res = client.read_holding_registers(1, 10, unit=1)
print(res.registers)
#!/usr/bin/env python
from pymodbus.server.sync import StartTcpServer
from pymodbus.datastore import ModbusSequentialDataBlock
from pymodbus.datastore import ModbusSlaveContext, ModbusServerContext
store = ModbusSlaveContext(
di = ModbusSequentialDataBlock(0, [15]*100),
co = ModbusSequentialDataBlock(0, [17]*100),
hr = ModbusSequentialDataBlock(0, [18]*100),
ir = ModbusSequentialDataBlock(0, [19]*100))
context = ModbusServerContext(slaves=store, single=True)
#‘di’ - Discrete Inputs initializer
#‘co’ - Coils initializer
#‘hr’ - Holding Register initializer
#‘ir’ - Input Registers iniatializer
StartTcpServer(context, identity=None, address=("localhost", 5020))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment