Feature Request: run the main loop of start() method of TcpSlave/UdpSlave in another thread
-
Thanks for you guys' easy-of-use Modbus implementation at the beginning!
Recently I have been developing a web system used to test Modbus (TCP) devices. What I want to implement now is to offer system users an API to create some Modbus slaves running on the server.
However, when I want to return whether the new slave is started successfully (IMO, main loop start can means success) to the frontend, it turns out thattcpSlave.start()
won't end until an exception happened. If I run this method in a new thread, still I cannot detect whether the slave is started successfully or the port has been occupied. Ways like setting a timeout are not elegant IMO. I think if the main loop of this method is run in a new thread instead of the main thread calling the method, it will be much more convenient for me to use this method.Regarding code:
/** {@inheritDoc} */ @Override public void start() throws ModbusInitException { try { serverSocket = new ServerSocket(port); Socket socket; while (true) { socket = serverSocket.accept(); TcpConnectionHandler handler = new TcpConnectionHandler(socket); executorService.execute(handler); synchronized (listConnections) { listConnections.add(handler); } } } catch (IOException e) { throw new ModbusInitException(e); } }
-
@gbccccc first you need to define what "new slave is started successfully means".
If just binding to the port and waiting for connections is enough then you can assume that if you call the method and a
ModbusInitException
is thrown then it is not running. Otherwise it is bound to the port and waiting for connections.If you want to know that something is connected you could extend the TcpSlave class like this:
public class MonitoredTcpSlave extends TcpSlave { public MonitoredTcpSlave(int port, boolean encapsulated) { super(port, encapsulated); } public boolean hasConnection() { return !listConnections.isEmpty(); } }
As a last resort you could create your own TcpSlave by extending
com.serotonin.modbus4j.ModbusSlaveSet.ModbusSlaveSet