|
| 1 | +package com.digitalpetri.modbus.client; |
| 2 | + |
| 3 | +import static org.junit.jupiter.api.Assertions.assertEquals; |
| 4 | +import static org.junit.jupiter.api.Assertions.assertThrows; |
| 5 | + |
| 6 | +import com.digitalpetri.modbus.MbapHeader; |
| 7 | +import com.digitalpetri.modbus.ModbusTcpFrame; |
| 8 | +import com.digitalpetri.modbus.exceptions.ModbusException; |
| 9 | +import java.nio.ByteBuffer; |
| 10 | +import java.util.concurrent.CompletableFuture; |
| 11 | +import java.util.concurrent.CompletionStage; |
| 12 | +import java.util.concurrent.ExecutionException; |
| 13 | +import java.util.function.Consumer; |
| 14 | +import org.junit.jupiter.api.Test; |
| 15 | + |
| 16 | +public class ModbusTcpClientTest { |
| 17 | + |
| 18 | + /** |
| 19 | + * Tests handling of an erroneous empty response PDU. |
| 20 | + * |
| 21 | + * @see <a |
| 22 | + * href="https://github.com/digitalpetri/modbus/issues/121">https://github.com/digitalpetri/modbus/issues/121</a> |
| 23 | + */ |
| 24 | + @Test |
| 25 | + void emptyResponsePdu() { |
| 26 | + var transport = new TestTransport(); |
| 27 | + var client = ModbusTcpClient.create(transport); |
| 28 | + |
| 29 | + CompletionStage<byte[]> cs = client.sendRawAsync(1, new byte[] {0x04, 0x03, 0x00, 0x00, 0x01}); |
| 30 | + |
| 31 | + transport.frameReceiver.accept( |
| 32 | + new ModbusTcpFrame(new MbapHeader(0, 1, 1, 1), ByteBuffer.allocate(0))); |
| 33 | + |
| 34 | + ExecutionException ex = |
| 35 | + assertThrows(ExecutionException.class, () -> cs.toCompletableFuture().get()); |
| 36 | + |
| 37 | + ModbusException cause = (ModbusException) ex.getCause(); |
| 38 | + assertEquals("empty response PDU", cause.getMessage()); |
| 39 | + } |
| 40 | + |
| 41 | + private static class TestTransport implements ModbusTcpClientTransport { |
| 42 | + |
| 43 | + boolean connected = false; |
| 44 | + ModbusTcpFrame lastFrameSent; |
| 45 | + Consumer<ModbusTcpFrame> frameReceiver; |
| 46 | + |
| 47 | + @Override |
| 48 | + public CompletionStage<Void> connect() { |
| 49 | + connected = true; |
| 50 | + return CompletableFuture.completedFuture(null); |
| 51 | + } |
| 52 | + |
| 53 | + @Override |
| 54 | + public CompletionStage<Void> disconnect() { |
| 55 | + connected = false; |
| 56 | + return CompletableFuture.completedFuture(null); |
| 57 | + } |
| 58 | + |
| 59 | + @Override |
| 60 | + public boolean isConnected() { |
| 61 | + return connected; |
| 62 | + } |
| 63 | + |
| 64 | + @Override |
| 65 | + public CompletionStage<Void> send(ModbusTcpFrame frame) { |
| 66 | + lastFrameSent = frame; |
| 67 | + return CompletableFuture.completedFuture(null); |
| 68 | + } |
| 69 | + |
| 70 | + @Override |
| 71 | + public void receive(Consumer<ModbusTcpFrame> frameReceiver) { |
| 72 | + this.frameReceiver = frameReceiver; |
| 73 | + } |
| 74 | + } |
| 75 | +} |
0 commit comments