You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@plc4x.apache.org by sr...@apache.org on 2018/03/16 17:34:53 UTC
[incubator-plc4x] branch master updated: improved testing of serial
protocol
This is an automated email from the ASF dual-hosted git repository.
sruehl pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/incubator-plc4x.git
The following commit(s) were added to refs/heads/master by this push:
new 306bc3b improved testing of serial protocol
306bc3b is described below
commit 306bc3bcdc09e6cc49b70abef6c06fcc013db2b7
Author: Sebastian Rühl <sr...@apache.org>
AuthorDate: Fri Mar 16 18:34:50 2018 +0100
improved testing of serial protocol
---
.../java/ads/protocol/Payload2SerialProtocol.java | 9 ++-
...load2SerialProtocolExampleConversationTest.java | 10 +--
.../java/ads/protocol/util/DigestUtilTest.java | 82 ++++++++++++++++++++++
.../org/apache/plc4x/java/ads/util/Assert.java | 77 ++++++++++++++++++++
4 files changed, 172 insertions(+), 6 deletions(-)
diff --git a/plc4j/protocols/ads/src/main/java/org/apache/plc4x/java/ads/protocol/Payload2SerialProtocol.java b/plc4j/protocols/ads/src/main/java/org/apache/plc4x/java/ads/protocol/Payload2SerialProtocol.java
index 30a166c..6326891 100644
--- a/plc4j/protocols/ads/src/main/java/org/apache/plc4x/java/ads/protocol/Payload2SerialProtocol.java
+++ b/plc4j/protocols/ads/src/main/java/org/apache/plc4x/java/ads/protocol/Payload2SerialProtocol.java
@@ -32,6 +32,9 @@ import org.slf4j.LoggerFactory;
import java.util.List;
+import static java.lang.Integer.toHexString;
+import static org.apache.commons.lang3.StringUtils.leftPad;
+
public class Payload2SerialProtocol extends MessageToMessageCodec<ByteBuf, ByteBuf> {
private static final Logger LOGGER = LoggerFactory.getLogger(Payload2TcpProtocol.class);
@@ -79,7 +82,11 @@ public class Payload2SerialProtocol extends MessageToMessageCodec<ByteBuf, ByteB
}
int calculatedCrc16 = DigestUtil.calculateCrc16(magicCookie, transmitterAddress, receiverAddress, fragmentNumber, userDataLength, userData);
if (!crc.equals(CRC.of(calculatedCrc16))) {
- throw new PlcProtocolException("CRC checksum wrong");
+ throw new PlcProtocolException("CRC checksum wrong. Got "
+ + "0x" + leftPad(toHexString(crc.getAsInt()), 4, "0")
+ + " expected "
+ + "0x" + leftPad(toHexString(calculatedCrc16), 4, "0")
+ );
}
if (byteBuf.readableBytes() > 0) {
diff --git a/plc4j/protocols/ads/src/test/java/org/apache/plc4x/java/ads/protocol/Payload2SerialProtocolExampleConversationTest.java b/plc4j/protocols/ads/src/test/java/org/apache/plc4x/java/ads/protocol/Payload2SerialProtocolExampleConversationTest.java
index 67a92a0..2eeb1d4 100644
--- a/plc4j/protocols/ads/src/test/java/org/apache/plc4x/java/ads/protocol/Payload2SerialProtocolExampleConversationTest.java
+++ b/plc4j/protocols/ads/src/test/java/org/apache/plc4x/java/ads/protocol/Payload2SerialProtocolExampleConversationTest.java
@@ -40,7 +40,7 @@ import org.junit.rules.ErrorCollector;
import java.util.ArrayList;
import java.util.Arrays;
-import static org.hamcrest.Matchers.equalTo;
+import static org.apache.plc4x.java.ads.util.Assert.byteArrayEqualsTo;
/**
* @see <a href="https://infosys.beckhoff.com/content/1033/tcadsamsserialspec/html/tcamssericalspec,0xsample.htm?id=60692407917020132">example</a>
@@ -98,7 +98,7 @@ public class Payload2SerialProtocolExampleConversationTest {
AmsSerialFrame amsSerialFrame = AmsSerialFrame.of(FragmentNumber.of((byte) 0x06), UserData.of(amsPacket.getBytes()));
System.out.println(amsSerialFrame.dump());
System.err.println(ByteValue.of(exampleRequest).dump());
- errorCollector.checkThat(exampleRequest, equalTo(amsSerialFrame.getBytes()));
+ errorCollector.checkThat(amsSerialFrame.getBytes(), byteArrayEqualsTo(exampleRequest));
SUT.encode(null, amsPacket.getByteBuf(), new ArrayList<>());
// PLC --> Terminal : Acknowledge:
@@ -118,7 +118,7 @@ public class Payload2SerialProtocolExampleConversationTest {
AmsSerialAcknowledgeFrame amsSerialAcknowledgeFrame = AmsSerialAcknowledgeFrame.of(amsSerialFrame.getTransmitterAddress(), amsSerialFrame.getReceiverAddress(), amsSerialFrame.getFragmentNumber());
System.out.println(amsSerialAcknowledgeFrame.dump());
System.err.println(ByteValue.of(exampleAckResponse).dump());
- errorCollector.checkThat(exampleAckResponse, equalTo(amsSerialAcknowledgeFrame.getBytes()));
+ errorCollector.checkThat(amsSerialAcknowledgeFrame.getBytes(), byteArrayEqualsTo(exampleAckResponse));
SUT.decode(null, amsSerialAcknowledgeFrame.getByteBuf(), new ArrayList<>());
// PLC sends data:
@@ -152,12 +152,12 @@ public class Payload2SerialProtocolExampleConversationTest {
AmsNetId.of(Arrays.copyOfRange(exampleResponse, 14, 20)),
AmsPort.of(Arrays.copyOfRange(exampleResponse, 20, 22)),
Invoke.of(0x07),
- Result.of(0x02),
+ Result.of(0x00),
Data.of((byte) 0xAF, (byte) 0x27)
);
AmsSerialFrame amsResponseSerialFrame = AmsSerialFrame.of(FragmentNumber.of((byte) 0xEC), UserData.of(amsResponsePacket.getBytes()));
System.out.println(amsResponseSerialFrame.dump());
System.err.println(ByteValue.of(exampleResponse).dump());
- errorCollector.checkThat(exampleResponse, equalTo(amsResponseSerialFrame.getBytes()));
+ errorCollector.checkThat(amsResponseSerialFrame.getBytes(), byteArrayEqualsTo(exampleResponse));
}
}
diff --git a/plc4j/protocols/ads/src/test/java/org/apache/plc4x/java/ads/protocol/util/DigestUtilTest.java b/plc4j/protocols/ads/src/test/java/org/apache/plc4x/java/ads/protocol/util/DigestUtilTest.java
index 73f3328..7db07c4 100644
--- a/plc4j/protocols/ads/src/test/java/org/apache/plc4x/java/ads/protocol/util/DigestUtilTest.java
+++ b/plc4j/protocols/ads/src/test/java/org/apache/plc4x/java/ads/protocol/util/DigestUtilTest.java
@@ -18,12 +18,19 @@
*/
package org.apache.plc4x.java.ads.protocol.util;
+import com.github.snksoft.crc.CRC;
import io.netty.buffer.Unpooled;
+import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
+import org.junit.Ignore;
import org.junit.Test;
+import java.nio.ByteBuffer;
+import java.util.Arrays;
import java.util.stream.IntStream;
+import java.util.stream.Stream;
+import static org.apache.plc4x.java.ads.util.Assert.assertByteEquals;
import static org.junit.Assert.assertEquals;
public class DigestUtilTest {
@@ -54,4 +61,79 @@ public class DigestUtilTest {
System.out.println(col1 + "\t\t" + col2 + "\t\t" + col3 + "\t\t" + col4 + "\t\t" + col5 + "\t\t" + col6 + "\t\t" + col7 + "\t\t" + col8);
}
}
+
+ @Ignore("This test is used to find proper crc parameters and can be run manually")
+ @Test
+ public void findRightAdsCrc() throws Exception {
+ int[] exampleResponseInt = {
+ /*Magic Cookie */ 0x01, 0xA5,
+ /*Sender */ 0x00,
+ /*Empfaenger */ 0x00,
+ /*Fragmentnummer */ 0xEC,
+ /*Anzahl Daten */ 0x2A,
+ /*NetID Empfaenger */ 0xC0, 0xA8, 0x64, 0x9C, 0x01, 0x01,
+ /*Portnummer */ 0x01, 0x80,
+ /*NetID Sender */ 0xC0, 0xA8, 0x64, 0xAE, 0x01, 0x01,
+ /*Portnummer */ 0x21, 0x03,
+ /*Response Lesen */ 0x02, 0x00,
+ /*Status */ 0x05, 0x00,
+ /*Anzahl Daten */ 0x0A, 0x00, 0x00, 0x00,
+ /*Fehlercode */ 0x00, 0x00, 0x00, 0x00,
+ /*InvokeID */ 0x07, 0x00, 0x00, 0x00,
+ /*Ergebnis */ 0x00, 0x00, 0x00, 0x00,
+ /*Anzahl Daten */ 0x02, 0x00, 0x00, 0x00,
+ /*Daten */ 0xAF, 0x27,
+ /*Checksumme */ 0x04, 0xA9,
+ };
+ byte[] exampleResponse = ArrayUtils.toPrimitive(Arrays
+ .stream(exampleResponseInt)
+ .mapToObj(value -> (byte) value)
+ .toArray(Byte[]::new));
+ int crcField1Index = exampleResponse.length - 2;
+ assertByteEquals((byte) 0x04, exampleResponse[crcField1Index]);
+ int crcField2Index = exampleResponse.length - 1;
+ assertByteEquals((byte) 0xA9, exampleResponse[crcField2Index]);
+
+ IntStream.range(0, 0xFFFF).forEach(polynomial -> {
+ //int polynomial = 0x8005;
+ IntStream.of(0x0000, 0xFFFF).forEach(init -> {
+ //int init = 0x0000;
+ Stream.of(true, false).forEach(reflectIn -> {
+ //boolean reflectIn = true;
+ Stream.of(true, false).forEach(reflectOut -> {
+ //boolean reflectOut = true;
+ // TODO: check if we can check for finalxor at all
+ int finalXor = 0x0;
+ CRC.Parameters params = new CRC.Parameters(16, polynomial, init, reflectIn, reflectOut, finalXor);
+ String paramString = ""
+ + "polynomial=0x" + StringUtils.leftPad(Integer.toHexString(polynomial), 4, '0')
+ + ", init=0x" + StringUtils.leftPad(Integer.toHexString(init), 4, '0')
+ + ", reflectIn=" + reflectIn
+ + ", reflectOut=" + reflectOut
+ + ", finalXor=" + StringUtils.leftPad(Integer.toHexString(finalXor), 4, '0') + "";
+ CRC crcCalculator = new CRC(params);
+ long currentCrc = crcCalculator.update(crcCalculator.init(), Arrays.copyOfRange(exampleResponse, 0, crcField1Index));
+ short crc16 = crcCalculator.finalCRC16(currentCrc);
+ ByteBuffer buffer = ByteBuffer.allocate(2);
+ buffer.putShort(crc16);
+ byte[] bytes = buffer.array();
+ byte msb = bytes[0];
+ byte lsb = bytes[1];
+ if (lsb == exampleResponse[crcField1Index] && msb == exampleResponse[crcField2Index]) {
+ System.out.println("We found a LE: " + paramString);
+ }
+ if (lsb == exampleResponse[crcField2Index] && msb == exampleResponse[crcField1Index]) {
+ System.out.println("We found a BE " + paramString);
+ }
+ if (lsb == exampleResponse[crcField1Index] || msb == exampleResponse[crcField2Index]) {
+ //System.out.println("We found a LE one of them");
+ } else if (lsb == exampleResponse[crcField2Index] || msb == exampleResponse[crcField1Index]) {
+ //System.out.println("We found a BE one of them");
+ }
+ });
+ });
+ });
+ }
+ );
+ }
}
\ No newline at end of file
diff --git a/plc4j/protocols/ads/src/test/java/org/apache/plc4x/java/ads/util/Assert.java b/plc4j/protocols/ads/src/test/java/org/apache/plc4x/java/ads/util/Assert.java
new file mode 100644
index 0000000..86c10cc
--- /dev/null
+++ b/plc4j/protocols/ads/src/test/java/org/apache/plc4x/java/ads/util/Assert.java
@@ -0,0 +1,77 @@
+/*
+ Licensed to the Apache Software Foundation (ASF) under one
+ or more contributor license agreements. See the NOTICE file
+ distributed with this work for additional information
+ regarding copyright ownership. The ASF licenses this file
+ to you under the Apache License, Version 2.0 (the
+ "License"); you may not use this file except in compliance
+ with the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing,
+ software distributed under the License is distributed on an
+ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ KIND, either express or implied. See the License for the
+ specific language governing permissions and limitations
+ under the License.
+ */
+package org.apache.plc4x.java.ads.util;
+
+import org.apache.plc4x.java.ads.api.util.ByteValue;
+import org.hamcrest.Description;
+import org.hamcrest.Matcher;
+import org.hamcrest.core.IsEqual;
+
+import java.io.IOException;
+
+import static java.lang.Integer.toHexString;
+import static org.apache.commons.lang3.StringUtils.leftPad;
+import static org.junit.Assert.assertEquals;
+
+public class Assert {
+
+ public static void assertByteEquals(byte expected, byte actual) throws Exception {
+ String expectedHex = "0x" + leftPad(toHexString(expected), 2, '0');
+ String actualHex = "0x" + leftPad(toHexString(actual), 2, '0');
+ assertEquals(expectedHex, actualHex);
+ }
+
+ public static void assertByteEquals(byte[] expected, byte[] actual) throws Exception {
+ String expectedHex = cleanHexDump(ByteValue.of(expected).dump());
+ String actualHex = cleanHexDump(ByteValue.of(actual).dump());
+ assertEquals(expectedHex, actualHex);
+ }
+
+ public static Matcher<byte[]> byteArrayEqualsTo(byte[] expected) {
+ return new IsEqual<byte[]>(expected) {
+ @Override
+ public void describeTo(Description description) {
+ try {
+ String dump = ByteValue.of(expected).dump();
+ description.appendText("\n").appendText(cleanHexDump(dump));
+ } catch (IOException e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ @Override
+ public void describeMismatch(Object item, Description description) {
+ if (item == null || !(item instanceof byte[])) {
+ super.describeMismatch(item, description);
+ return;
+ }
+ try {
+ String dump = ByteValue.of((byte[]) item).dump();
+ description.appendText("was ").appendText("\n").appendText(cleanHexDump(dump));
+ } catch (IOException e) {
+ throw new RuntimeException(e);
+ }
+ }
+ };
+ }
+
+ private static String cleanHexDump(String in) {
+ return in.replaceAll("@.*\\{", "@XXXXXXXX{");
+ }
+}
--
To stop receiving notification emails like this one, please contact
sruehl@apache.org.