2 * Copyright (c) 2010-2020 Contributors to the openHAB project
4 * See the NOTICE file(s) distributed with this work for additional
7 * This program and the accompanying materials are made available under the
8 * terms of the Eclipse Public License 2.0 which is available at
9 * http://www.eclipse.org/legal/epl-2.0
11 * SPDX-License-Identifier: EPL-2.0
13 package org.openhab.io.transport.modbus.test;
15 import static org.hamcrest.CoreMatchers.*;
16 import static org.junit.Assert.assertThat;
17 import static org.mockito.ArgumentMatchers.any;
18 import static org.mockito.Mockito.*;
21 import java.net.DatagramSocket;
22 import java.net.InetAddress;
23 import java.net.Socket;
24 import java.net.SocketException;
25 import java.net.UnknownHostException;
26 import java.util.HashMap;
27 import java.util.function.LongSupplier;
29 import org.apache.commons.lang.NotImplementedException;
30 import org.junit.After;
31 import org.junit.Assert;
32 import org.junit.Before;
33 import org.mockito.MockitoAnnotations;
34 import org.mockito.Spy;
35 import org.openhab.core.test.java.JavaTest;
36 import org.openhab.io.transport.modbus.endpoint.ModbusSlaveEndpoint;
37 import org.openhab.io.transport.modbus.endpoint.ModbusTCPSlaveEndpoint;
38 import org.openhab.io.transport.modbus.internal.ModbusManagerImpl;
40 import gnu.io.SerialPort;
41 import net.wimpi.modbus.Modbus;
42 import net.wimpi.modbus.ModbusCoupler;
43 import net.wimpi.modbus.ModbusIOException;
44 import net.wimpi.modbus.io.ModbusTransport;
45 import net.wimpi.modbus.msg.ModbusRequest;
46 import net.wimpi.modbus.net.ModbusSerialListener;
47 import net.wimpi.modbus.net.ModbusTCPListener;
48 import net.wimpi.modbus.net.ModbusUDPListener;
49 import net.wimpi.modbus.net.SerialConnection;
50 import net.wimpi.modbus.net.SerialConnectionFactory;
51 import net.wimpi.modbus.net.TCPSlaveConnection;
52 import net.wimpi.modbus.net.TCPSlaveConnection.ModbusTCPTransportFactory;
53 import net.wimpi.modbus.net.TCPSlaveConnectionFactory;
54 import net.wimpi.modbus.net.UDPSlaveTerminal;
55 import net.wimpi.modbus.net.UDPSlaveTerminal.ModbusUDPTransportFactoryImpl;
56 import net.wimpi.modbus.net.UDPSlaveTerminalFactory;
57 import net.wimpi.modbus.net.UDPTerminal;
58 import net.wimpi.modbus.procimg.SimpleProcessImage;
59 import net.wimpi.modbus.util.AtomicCounter;
60 import net.wimpi.modbus.util.SerialParameters;
63 * @author Sami Salonen - Initial contribution
65 public class IntegrationTestSupport extends JavaTest {
67 public enum ServerType {
75 * Serial is system dependent
77 public static final ServerType[] TEST_SERVERS = new ServerType[] { ServerType.TCP
82 // One can perhaps test SERIAL with https://github.com/freemed/tty0tty
83 // and using those virtual ports? Not the same thing as real serial device of course
84 private static String SERIAL_SERVER_PORT = "/dev/pts/7";
85 private static String SERIAL_CLIENT_PORT = "/dev/pts/8";
87 private static SerialParameters SERIAL_PARAMETERS_CLIENT = new SerialParameters(SERIAL_CLIENT_PORT, 115200,
88 SerialPort.FLOWCONTROL_NONE, SerialPort.FLOWCONTROL_NONE, SerialPort.DATABITS_8, SerialPort.STOPBITS_1,
89 SerialPort.PARITY_NONE, Modbus.SERIAL_ENCODING_ASCII, false, 1000);
91 private static SerialParameters SERIAL_PARAMETERS_SERVER = new SerialParameters(SERIAL_SERVER_PORT,
92 SERIAL_PARAMETERS_CLIENT.getBaudRate(), SERIAL_PARAMETERS_CLIENT.getFlowControlIn(),
93 SERIAL_PARAMETERS_CLIENT.getFlowControlOut(), SERIAL_PARAMETERS_CLIENT.getDatabits(),
94 SERIAL_PARAMETERS_CLIENT.getStopbits(), SERIAL_PARAMETERS_CLIENT.getParity(),
95 SERIAL_PARAMETERS_CLIENT.getEncoding(), SERIAL_PARAMETERS_CLIENT.isEcho(), 1000);
98 System.setProperty("org.slf4j.simpleLogger.defaultLogLevel", "trace");
99 System.setProperty("gnu.io.rxtx.SerialPorts", SERIAL_SERVER_PORT + File.pathSeparator + SERIAL_CLIENT_PORT);
103 * Max time to wait for connections/requests from client
105 protected int MAX_WAIT_REQUESTS_MILLIS = 1000;
108 * The server runs in single thread, only one connection is accepted at a time.
109 * This makes the tests as strict as possible -- connection must be closed.
111 private static final int SERVER_THREADS = 1;
112 protected static int SLAVE_UNIT_ID = 1;
114 private static AtomicCounter udpServerIndex = new AtomicCounter(0);
117 protected TCPSlaveConnectionFactory tcpConnectionFactory = new TCPSlaveConnectionFactoryImpl();
120 protected UDPSlaveTerminalFactory udpTerminalFactory = new UDPSlaveTerminalFactoryImpl();
123 protected SerialConnectionFactory serialConnectionFactory = new SerialConnectionFactoryImpl();
125 protected ResultCaptor<ModbusRequest> modbustRequestCaptor;
127 protected ModbusTCPListener tcpListener;
128 protected ModbusUDPListener udpListener;
129 protected ModbusSerialListener serialListener;
130 protected SimpleProcessImage spi;
131 protected int tcpModbusPort = -1;
132 protected int udpModbusPort = -1;
133 protected ServerType serverType = ServerType.TCP;
134 protected long artificialServerWait = 0;
136 protected NonOSGIModbusManager modbusManager;
138 private Thread serialServerThread = new Thread("ModbusTransportTestsSerialServer") {
141 serialListener = new ModbusSerialListener(SERIAL_PARAMETERS_SERVER);
145 protected static InetAddress localAddress() throws UnknownHostException {
146 return InetAddress.getByName("127.0.0.1");
150 public void setUp() throws Exception {
151 modbustRequestCaptor = new ResultCaptor<>(new LongSupplier() {
154 public long getAsLong() {
155 return artificialServerWait;
158 MockitoAnnotations.initMocks(this);
159 modbusManager = new NonOSGIModbusManager();
164 public void tearDown() {
166 modbusManager.close();
169 protected void waitForRequests(int expectedRequestCount) {
171 () -> assertThat(modbustRequestCaptor.getAllReturnValues().size(), is(equalTo(expectedRequestCount))),
172 MAX_WAIT_REQUESTS_MILLIS, 10);
175 protected void waitForConnectionsReceived(int expectedConnections) {
176 waitForAssert(() -> {
177 if (ServerType.TCP.equals(serverType)) {
178 verify(tcpConnectionFactory, times(expectedConnections)).create(any(Socket.class));
179 } else if (ServerType.UDP.equals(serverType)) {
181 // verify(udpTerminalFactory, times(expectedConnections)).create(any(InetAddress.class),
182 // any(Integer.class));
183 } else if (ServerType.SERIAL.equals(serverType)) {
186 throw new NotImplementedException();
188 }, MAX_WAIT_REQUESTS_MILLIS, 10);
191 private void startServer() throws UnknownHostException, InterruptedException {
192 spi = new SimpleProcessImage();
193 ModbusCoupler.getReference().setProcessImage(spi);
194 ModbusCoupler.getReference().setMaster(false);
195 ModbusCoupler.getReference().setUnitID(SLAVE_UNIT_ID);
197 if (ServerType.TCP.equals(serverType)) {
199 } else if (ServerType.UDP.equals(serverType)) {
201 } else if (ServerType.SERIAL.equals(serverType)) {
204 throw new NotImplementedException();
208 private void stopServer() {
209 if (ServerType.TCP.equals(serverType)) {
211 } else if (ServerType.UDP.equals(serverType)) {
213 System.err.println(udpModbusPort);
214 } else if (ServerType.SERIAL.equals(serverType)) {
216 serialServerThread.join(100);
217 } catch (InterruptedException e) {
218 System.err.println("Serial server thread .join() interrupted! Will interrupt it now.");
220 serialServerThread.interrupt();
222 throw new NotImplementedException();
226 private void startUDPServer() throws UnknownHostException, InterruptedException {
227 udpListener = new ModbusUDPListener(localAddress(), udpTerminalFactory);
228 for (int portCandidate = 10000 + udpServerIndex.increment(); portCandidate < 20000; portCandidate++) {
230 DatagramSocket socket = new DatagramSocket(portCandidate);
232 udpListener.setPort(portCandidate);
234 } catch (SocketException e) {
240 waitForUDPServerStartup();
241 Assert.assertNotSame(-1, udpModbusPort);
242 Assert.assertNotSame(0, udpModbusPort);
245 private void waitForUDPServerStartup() throws InterruptedException {
246 // Query server port. It seems to take time (probably due to thread starting)
247 waitFor(() -> udpListener.getLocalPort() > 0, 5, 10_000);
248 udpModbusPort = udpListener.getLocalPort();
251 private void startTCPServer() throws UnknownHostException, InterruptedException {
252 // Serve single user at a time
253 tcpListener = new ModbusTCPListener(SERVER_THREADS, localAddress(), tcpConnectionFactory);
255 tcpListener.setPort(0);
257 // Query server port. It seems to take time (probably due to thread starting)
258 waitForTCPServerStartup();
259 Assert.assertNotSame(-1, tcpModbusPort);
260 Assert.assertNotSame(0, tcpModbusPort);
263 private void waitForTCPServerStartup() throws InterruptedException {
264 waitFor(() -> tcpListener.getLocalPort() > 0, 10_000, 5);
265 tcpModbusPort = tcpListener.getLocalPort();
268 private void startSerialServer() throws UnknownHostException, InterruptedException {
269 serialServerThread.start();
273 public ModbusSlaveEndpoint getEndpoint() {
274 assert tcpModbusPort > 0;
275 return new ModbusTCPSlaveEndpoint("127.0.0.1", tcpModbusPort);
279 * Transport factory that spies the created transport items
281 public class SpyingModbusTCPTransportFactory extends ModbusTCPTransportFactory {
284 public ModbusTransport create(Socket socket) {
285 ModbusTransport transport = spy(super.create(socket));
286 // Capture requests produced by our server transport
288 doAnswer(modbustRequestCaptor).when(transport).readRequest();
289 } catch (ModbusIOException e) {
290 throw new RuntimeException(e);
296 public class SpyingModbusUDPTransportFactory extends ModbusUDPTransportFactoryImpl {
299 public ModbusTransport create(UDPTerminal terminal) {
300 ModbusTransport transport = spy(super.create(terminal));
301 // Capture requests produced by our server transport
303 doAnswer(modbustRequestCaptor).when(transport).readRequest();
304 } catch (ModbusIOException e) {
305 throw new RuntimeException(e);
311 public class TCPSlaveConnectionFactoryImpl implements TCPSlaveConnectionFactory {
314 public TCPSlaveConnection create(Socket socket) {
315 return new TCPSlaveConnection(socket, new SpyingModbusTCPTransportFactory());
319 public class UDPSlaveTerminalFactoryImpl implements UDPSlaveTerminalFactory {
322 public UDPSlaveTerminal create(InetAddress interfac, int port) {
323 UDPSlaveTerminal terminal = new UDPSlaveTerminal(interfac, new SpyingModbusUDPTransportFactory(), 1);
324 terminal.setLocalPort(port);
329 public class SerialConnectionFactoryImpl implements SerialConnectionFactory {
331 public SerialConnection create(SerialParameters parameters) {
332 SerialConnection serialConnection = new SerialConnection(parameters) {
334 public ModbusTransport getModbusTransport() {
335 ModbusTransport transport = spy(super.getModbusTransport());
337 doAnswer(modbustRequestCaptor).when(transport).readRequest();
338 } catch (ModbusIOException e) {
339 throw new RuntimeException(e);
344 return serialConnection;
348 public static class NonOSGIModbusManager extends ModbusManagerImpl implements AutoCloseable {
349 public NonOSGIModbusManager() {
350 activate(new HashMap<>());
354 public void close() {