-
Notifications
You must be signed in to change notification settings - Fork 110
How to create a Modbus Slave
Steve O'Hara edited this page Jul 5, 2016
·
2 revisions
From v2.2.0 this has become an almost trivial operation. j2mod supports running multiple simultaneous slaves using multiple transports and supporting multiple process images and unit identities.
So let's get the vocabulary sorted;
- Slave - this is a Modbus end point, a device that will communicate with a Master
- Transport - TCP, UDP or Serial (RTU/ASCII)
- Process Image - a set of registers
- Unit ID - a unique identity number (0-255) that allows a single Slave to support multiple devices
The pattern is as follows;
- Create a ModbusSlave from the ModbusSlaveFactory
- Add ProcessImage objects to it
- Open the slave (make it start listening on the port)
- ...
- Close the slave
// Create your register set
ProcessImage image = makeMyProcessImage();
// Create a slave to listen on port 502 and create a pool of 5 listener threads
// This will create a new slave or return you the same slave already assigned to this port
ModbusSlave slave = ModbusSlaveFactory.createTCPSlave(502, 5);
// Add the register set to the slave for unit ID 1
// Each slave can have multiple process images but they must have a unique Unit ID within the slave
slave.addProcessImage(1, image);
// Start the slave listening on the port - this will throw an error if the socket is already in use
slave.open();
.....
// Close the slave - closes the socket and stops listening
slave.close();
ProcessImage image = makeMyProcessImage();
ModbusSlave slave = ModbusSlaveFactory.createTCPSlave(502, 5);
slave.addProcessImage(1, image);
slave.open();
.....
// Closes all slaves (means we don't have to carry around a reference to the slave)
ModbusSlaveFactory.close();
ProcessImage image = makeMyProcessImage();
ProcessImage image1 = makeMyProcessImageAgain();
ModbusSlave slave502 = ModbusSlaveFactory.createTCPSlave(502, 5);
slave502.addProcessImage(1, image);
slave502.addProcessImage(2, image1);
slave502.open();
ModbusSlave slave503 = ModbusSlaveFactory.createUDPSlave(503);
slave503.addProcessImage(1, image);
slave503.open();
.....
ModbusSlaveFactory.close();