You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@plc4x.apache.org by cd...@apache.org on 2019/09/24 08:45:51 UTC

[plc4x] branch develop updated (2da3281 -> 86d833b)

This is an automated email from the ASF dual-hosted git repository.

cdutz pushed a change to branch develop
in repository https://gitbox.apache.org/repos/asf/plc4x.git.


    from 2da3281  - Adjusted the connector to latest feedback from Confluent
     new 05157ad  - Added a new Udp driver base
     new d9e805c  - Added filtering capabilities by ip, port and protocol id to the pcap channel
     new 54e8980  - Fixed a bug in handling of ternary terms
     new 9c203b8  - Fixed some bugs in the code generation helper for non uint types (Were mostly all missing a "(")
     new 7525f2c  - Changed the templates for the IO classes to no longer implement the MessageIO or MessageInput interfaces - The parse and serialize methods now take all arguments as real arguments and no longer as var args object array - No instances of IO modules are needed as now the parse and serialize methods are static (Needed to avoid stack overflows if types embed themselves) - Number of minor improvements
     new b10bb73  - Made the discriminator values in typeSwitch elements optional (resulting in a "default" case)
     new dc22f3a  - Changed the templates for the IO classes to no longer implement the MessageIO or MessageInput interfaces - The parse and serialize methods now take all arguments as real arguments and no longer as var args object array - No instances of IO modules are needed as now the parse and serialize methods are static (Needed to avoid stack overflows if types embed themselves) - Number of minor improvements
     new 2eb67c0  - Improved and fine-tuned the GeneratedDriverByteToMessageCodec to allow checking if enough data is available and to remove the rest of faulty packages after failing to decode. - Added a protocolHandler property to the RawSocketChannelFactory - Added filter capabilities to the PcapSocket stuff - Added a speed-factor to slow down or speed up the pcap replay
     new 5c8bc05  - Adjusted the existing dirvers to latest changes
     new 333c0f9  - Updated the version of commons-configuration to 2.6 - Updated the version of commons-text to 1.8 - Updated the version of jna to 5.3.1
     new 86d833b  - Continued working on the BACnet driver

The 11 revisions listed above as "new" are entirely new to this
repository and will be described in separate emails.  The revisions
listed as "add" were already present in the repository and have only
been added to this reference.


Summary of changes:
 .../language/java/JavaLanguageTemplateHelper.java  |  36 +-
 .../main/resources/templates/java/io-template.ftlh |  60 ++--
 .../plugins/codegenerator/language/mspec/MSpec.g4  |   4 +-
 .../mspec/expression/ExpressionStringListener.java |   2 +-
 .../mspec/parser/MessageFormatListener.java        |  13 +-
 plc4j/protocols/driver-bases/base/pom.xml          |   4 +
 .../base/GeneratedDriverByteToMessageCodec.java    |  19 +-
 .../java/base/connection/PcapChannelFactory.java   |  11 +-
 plc4j/protocols/driver-bases/pom.xml               |   1 +
 .../base/connection/RawSocketChannelFactory.java   |  11 +-
 plc4j/protocols/driver-bases/{tcp => udp}/pom.xml  |   6 +-
 .../base/connection/UdpSocketChannelFactory.java}  |  15 +-
 .../org/apache/plc4x/java/utils/MessageInput.java  |   2 +-
 .../org/apache/plc4x/java/utils/MessageOutput.java |   2 +-
 .../utils/pcapsockets/netty/PcapSocketAddress.java |  27 +-
 .../utils/pcapsockets/netty/PcapSocketChannel.java |  29 +-
 .../pcapsockets/netty/PcapSocketChannelConfig.java |  20 +-
 .../protocol/test/ProtocolTestsuiteRunner.java     |  33 +-
 .../utils/rawsockets/netty/RawSocketAddress.java   |   1 -
 .../rawsockets}/netty/UdpIpPacketHandler.java      |   4 +-
 pom.xml                                            |   6 +-
 .../resources/protocols/bacnetip/bacnetip.mspec    | 397 ++++++++++++++++++---
 .../plc4x/java/abeth/protocol/AbEthProtocol.java   |  27 +-
 sandbox/test-java-bacnetip-driver/pom.xml          |  13 +-
 .../java/bacnetip/PassiveBacNetIpDriver.java}      |  35 +-
 .../bacnetip/connection/BacNetIpFieldHandler.java} |  10 +-
 .../connection/PassiveBacNetIpPlcConnection.java}  |  53 +--
 .../plc4x/java/bacnetip/model/BacNetIpField.java}  |  29 +-
 .../java/bacnetip/protocol/BacNetIpProtocol.java   |  62 ++++
 .../java/bacnetip/protocol/HelloWorldProtocol.java |  61 ++++
 .../services/org.apache.plc4x.java.spi.PlcDriver   |   2 +-
 .../plc4x/java/bacnetip/ManualBacNetDecoder.java   |  22 +-
 .../java/bacnetip/PassiveBacNetIpDriverManual.java |  39 ++
 .../plc4x/java/df1/protocol/Df1Protocol.java       |   2 +-
 .../plc4x/javapassive/s7/PassiveS7PlcDriver.java   |   5 +-
 .../s7/connection/PassiveS7PlcConnection.java      |   3 +-
 36 files changed, 835 insertions(+), 231 deletions(-)
 copy plc4j/protocols/driver-bases/{tcp => udp}/pom.xml (92%)
 copy plc4j/protocols/driver-bases/{tcp/src/main/java/org/apache/plc4x/java/base/connection/TcpSocketChannelFactory.java => udp/src/main/java/org/apache/plc4x/java/base/connection/UdpSocketChannelFactory.java} (89%)
 copy plc4j/utils/{pcap-sockets/src/main/java/org/apache/plc4x/java/utils/pcapsockets => raw-sockets/src/main/java/org/apache/plc4x/java/utils/rawsockets}/netty/UdpIpPacketHandler.java (92%)
 copy sandbox/{test-java-ab-eth-driver/src/main/java/org/apache/plc4x/java/abeth/AbEthDriver.java => test-java-bacnetip-driver/src/main/java/org/apache/plc4x/java/bacnetip/PassiveBacNetIpDriver.java} (60%)
 copy sandbox/{test-java-ab-eth-driver/src/main/java/org/apache/plc4x/java/abeth/connection/AbEthFieldHandler.java => test-java-bacnetip-driver/src/main/java/org/apache/plc4x/java/bacnetip/connection/BacNetIpFieldHandler.java} (80%)
 copy sandbox/{test-java-ab-eth-driver/src/main/java/org/apache/plc4x/java/abeth/connection/AbEthPlcConnection.java => test-java-bacnetip-driver/src/main/java/org/apache/plc4x/java/bacnetip/connection/PassiveBacNetIpPlcConnection.java} (67%)
 copy sandbox/{test-java-ab-eth-driver/src/main/java/org/apache/plc4x/java/abeth/connection/AbEthFieldHandler.java => test-java-bacnetip-driver/src/main/java/org/apache/plc4x/java/bacnetip/model/BacNetIpField.java} (52%)
 create mode 100644 sandbox/test-java-bacnetip-driver/src/main/java/org/apache/plc4x/java/bacnetip/protocol/BacNetIpProtocol.java
 create mode 100644 sandbox/test-java-bacnetip-driver/src/main/java/org/apache/plc4x/java/bacnetip/protocol/HelloWorldProtocol.java
 copy {plc4j/api/src/test => sandbox/test-java-bacnetip-driver/src/main}/resources/META-INF/services/org.apache.plc4x.java.spi.PlcDriver (93%)
 copy plc4j/examples/dummy-driver/src/main/java/org/apache/plc4x/java/examples/dummydriver/model/DummyField.java => sandbox/test-java-bacnetip-driver/src/test/java/org/apache/plc4x/java/bacnetip/ManualBacNetDecoder.java (55%)
 create mode 100644 sandbox/test-java-bacnetip-driver/src/test/java/org/apache/plc4x/java/bacnetip/PassiveBacNetIpDriverManual.java


[plc4x] 11/11: - Continued working on the BACnet driver

Posted by cd...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

cdutz pushed a commit to branch develop
in repository https://gitbox.apache.org/repos/asf/plc4x.git

commit 86d833b1b5e016ce8640c7da3dec8e82517c3979
Author: Christofer Dutz <ch...@c-ware.de>
AuthorDate: Tue Sep 24 10:02:26 2019 +0200

    - Continued working on the BACnet driver
---
 .../resources/protocols/bacnetip/bacnetip.mspec    | 397 ++++++++++++++++++---
 sandbox/test-java-bacnetip-driver/pom.xml          |  13 +-
 .../plc4x/java/bacnetip/PassiveBacNetIpDriver.java |  75 ++++
 .../bacnetip/connection/BacNetIpFieldHandler.java  |  36 ++
 .../connection/PassiveBacNetIpPlcConnection.java   | 115 ++++++
 .../plc4x/java/bacnetip/model/BacNetIpField.java   |  47 +++
 .../java/bacnetip/protocol/BacNetIpProtocol.java   |  62 ++++
 .../java/bacnetip/protocol/HelloWorldProtocol.java |  61 ++++
 .../services/org.apache.plc4x.java.spi.PlcDriver   |  19 +
 .../plc4x/java/bacnetip/ManualBacNetDecoder.java   |  35 ++
 .../java/bacnetip/PassiveBacNetIpDriverManual.java |  39 ++
 11 files changed, 856 insertions(+), 43 deletions(-)

diff --git a/protocols/bacnetip/src/main/resources/protocols/bacnetip/bacnetip.mspec b/protocols/bacnetip/src/main/resources/protocols/bacnetip/bacnetip.mspec
index 8f517af..6e99211 100644
--- a/protocols/bacnetip/src/main/resources/protocols/bacnetip/bacnetip.mspec
+++ b/protocols/bacnetip/src/main/resources/protocols/bacnetip/bacnetip.mspec
@@ -30,7 +30,10 @@
         ]
         ['0x03' BVLCReadBroadcastDistributionTableAck
         ]
-        ['0x04' BVLCForwardedNPDU
+        ['0x04' BVLCForwardedNPDU [uint 16 'bvlcLength']
+            [array  uint 8  'ip' count '4']
+            [simple uint 16 'port']
+            [simple NPDU    'npdu' ['bvlcLength - 10']]
         ]
         ['0x05' BVLCRegisterForeignDevice
         ]
@@ -42,38 +45,51 @@
         ]
         ['0x09' BVLCDistributeBroadcastToNetwork
         ]
-        ['0x0A' BVLCOriginalUnicastNPDU
+        ['0x0A' BVLCOriginalUnicastNPDU [uint 16 'bvlcLength']
+            [simple NPDU 'npdu' ['bvlcLength - 4']]
         ]
-        ['0x0B' BVLCOriginalBroadcastNPDU
+        ['0x0B' BVLCOriginalBroadcastNPDU [uint 16 'bvlcLength']
+            [simple NPDU 'npdu' ['bvlcLength - 4']]
         ]
         ['0x0C' BVLCSecureBVLL
         ]
     ]
 ]
 
-[type 'NPDU'
-    [simple   uint 8 'protocolVersionNumber']
-    [simple   bit    'messageTypeFieldPresent']
-    [reserved uint 1 '0']
-    [simple   bit    'destinationSpecified']
-    [reserved uint 1 '0']
-    [simple   bit    'sourceSpecified']
-    [reserved uint 1 '0']
-    [simple   bit    'expectingReply']
-    [simple   uint 2 'networkPriority']
-    [optional uint 16 'destinationNetworkAddress' 'destinationSpecified']
-    [optional uint 8  'destinationLength'         'destinationSpecified']
-    [optional Address 'destinationAddress'        'destinationSpecified && (destinationLength > 0)']
-    [optional uint 16 'sourceNetworkAddress'      'sourceSpecified']
-    [optional uint 8  'sourceLength'              'sourceSpecified']
-    [optional Address 'sourceAddress'             'sourceSpecified && (sourceLength > 0)']
-    [optional uint 8  'hopCount'                  'destinationSpecified || sourceSpecified']
-    [optional uint 8  'messageType'               'messageTypeFieldPresent']
-    [optional uint 16 'vendorId'                  'messageTypeFieldPresent']
-    [simple   APDU    'apdu']
+[type 'NPDU' [uint 16 'npduLength']
+    [simple   uint 8        'protocolVersionNumber']
+    [simple   bit           'messageTypeFieldPresent']
+    [reserved uint 1        '0']
+    [simple   bit           'destinationSpecified']
+    [reserved uint 1        '0']
+    [simple   bit           'sourceSpecified']
+    [simple   bit           'expectingReply']
+    [simple   uint 2        'networkPriority']
+    [optional uint 16       'destinationNetworkAddress' 'destinationSpecified']
+    [optional uint 8        'destinationLength'         'destinationSpecified']
+    [array    uint 8        'destinationAddress' count  'destinationSpecified ? destinationLength : 0']
+    [optional uint 16       'sourceNetworkAddress'      'sourceSpecified']
+    [optional uint 8        'sourceLength'              'sourceSpecified']
+    [array    uint 8        'sourceAddress' count       'sourceSpecified ? sourceLength : 0']
+    [optional uint 8        'hopCount'                  'destinationSpecified']
+    [optional NLM           'nlm'                       'messageTypeFieldPresent' ['npduLength - (2 + (sourceSpecified ? 3 + sourceLength : 0) + (destinationSpecified ? 3 + destinationLength: 0) + ((destinationSpecified || sourceSpecified) ? 1 : 0))']]
+    [optional APDU          'apdu'                      '!messageTypeFieldPresent' ['npduLength - (2 + (sourceSpecified ? 3 + sourceLength : 0) + (destinationSpecified ? 3 + destinationLength: 0) + ((destinationSpecified || sourceSpecified) ? 1 : 0))']]
 ]
 
-[discriminatedType 'APDU'
+[discriminatedType 'NLM' [uint 16 'apduLength']
+    [discriminator uint 8  'messageType']
+    [optional      uint 16 'vendorId' '(messageType >= 128) && (messageType <= 255)']
+    [typeSwitch 'messageType'
+        ['0x0' NLMWhoIsRouterToNetwork [uint 8  'messageType']
+            [array uint 16 'destinationNetworkAddress' length 'apduLength - (((messageType >= 128) && (messageType <= 255)) ? 3 : 1)']
+        ]
+        ['0x1' NLMIAmRouterToNetwork [uint 8  'messageType']
+            [array uint 16 'destinationNetworkAddress' length 'apduLength - (((messageType >= 128) && (messageType <= 255)) ? 3 : 1)']
+        ]
+    ]
+]
+
+[discriminatedType 'APDU' [uint 16 'apduLength']
     [discriminator uint 4 'apduType']
     [typeSwitch 'apduType'
         ['0x0' APDUConfirmedRequest
@@ -83,15 +99,14 @@
             [reserved uint 2 '0']
             [simple   uint 3 'maxSegmentsAccepted']
             [simple   uint 4 'maxApduLengthAccepted']
-            [simple   uint 6 'invokeId']
+            [simple   uint 8 'invokeId']
             [optional uint 8 'sequenceNumber' 'segmentedMessage']
             [optional uint 8 'proposedWindowSize' 'segmentedMessage']
-            [simple   BACnetConfirmedServiceRequest 'serviceRequest']
+            [simple   BACnetConfirmedServiceRequest 'serviceRequest' ['apduLength - (3 + (segmentedMessage ? 2 : 0))']]
         ]
         ['0x1' APDUUnconfirmedRequest
             [reserved uint 4 '0']
-            [simple   uint 8 'serviceChoice']
-            [simple   BACnetUnconfirmedServiceRequest 'serviceRequest']
+            [simple   BACnetUnconfirmedServiceRequest 'serviceRequest' ['apduLength - 1']]
         ]
         ['0x2' APDUSimpleAck
             [reserved uint 4 '0']
@@ -105,7 +120,6 @@
             [simple   uint 8 'originalInvokeId']
             [optional uint 8 'sequenceNumber'     'segmentedMessage']
             [optional uint 8 'proposedWindowSize' 'segmentedMessage']
-            [simple   uint 8 'serviceChoice']
             [simple   BACnetServiceAck 'serviceAck']
         ]
         ['0x4' APDUSegmentAck
@@ -119,7 +133,6 @@
         ['0x5' APDUError
             [reserved uint 4 '0x00']
             [simple   uint 8 'originalInvokeId']
-            [simple   uint 8 'errorChoice']
             [simple   BACnetError  'error']
         ]
         ['0x6' APDUReject
@@ -136,17 +149,26 @@
     ]
 ]
 
-[discriminatedType 'BACnetConfirmedServiceRequest'
+[discriminatedType 'BACnetConfirmedServiceRequest' [uint 16 'len']
     [discriminator uint 8 'serviceChoice']
     [typeSwitch 'serviceChoice'
         ['0x00' BACnetConfirmedServiceRequestAcknowledgeAlarm
         ]
         ['0x01' BACnetConfirmedServiceRequestConfirmedCOVNotification
-            subscriber-process-identifier (Unsigned32)
-            initiating-device-identifier (BACnetObjectIdentifier)
-            monitored-object-identifier (BACnetObjectIdentifier)
-            time-remaining (Unsigned)
-            list-of-values (SEQUENCE OF BACnetPropertyValue)
+            [const uint 8 'subscriberProcessIdentifierHeader' '0x09']
+            [simple uint 8 'subscriberProcessIdentifier']
+            [const uint 8 'monitoredObjectIdentifierHeader' '0x1C']
+            [simple uint 10 'monitoredObjectType']
+            [simple uint 22 'monitoredObjectInstanceNumber']
+            [const uint 8 'issueConfirmedNotificationsHeader' '0x2C']
+            [simple uint 10 'issueConfirmedNotificationsType']
+            [simple uint 22 'issueConfirmedNotificationsInstanceNumber']
+            [const uint 5 'lifetimeHeader' '0x07']
+            [simple uint 3 'lifetimeLength']
+            [array int 8 'lifetimeSeconds' count 'lifetimeLength']
+            [const uint 8 'listOfValuesOpeningTag' '0x4E']
+            [array BACnetTagWithContent 'notifications' length 'len - 18']
+            [const uint 8 'listOfValuesClosingTag' '0x4F']
         ]
         ['0x1F' BACnetConfirmedServiceRequestConfirmedCOVNotificationMultiple
         ]
@@ -160,10 +182,21 @@
         ['0x1B' BACnetConfirmedServiceRequestLifeSafetyOperation
         ]
         ['0x05' BACnetConfirmedServiceRequestSubscribeCOV
+            [const uint 8 'subscriberProcessIdentifierHeader' '0x09']
+            [simple uint 8 'subscriberProcessIdentifier']
+            [const uint 8 'monitoredObjectIdentifierHeader' '0x1C']
+            [simple uint 10 'monitoredObjectType']
+            [simple uint 22 'monitoredObjectInstanceNumber']
+            [const uint 8 'issueConfirmedNotificationsHeader' '0x29']
+            [const uint 7 'issueConfirmedNotificationsSkipBits' '0x00']
+            [simple bit 'issueConfirmedNotifications']
+            [const uint 5 'lifetimeHeader' '0x07']
+            [simple uint 3 'lifetimeLength']
+            [array int 8 'lifetimeSeconds' count 'lifetimeLength']
         ]
-        ['0x0C' BACnetConfirmedServiceRequestSubscribeCOVProperty
+        ['0x1C' BACnetConfirmedServiceRequestSubscribeCOVProperty
         ]
-        ['0x0E' BACnetConfirmedServiceRequestSubscribeCOVPropertyMultiple
+        ['0x1E' BACnetConfirmedServiceRequestSubscribeCOVPropertyMultiple
         ]
 
         ['0x06' BACnetConfirmedServiceRequestAtomicReadFile
@@ -180,12 +213,28 @@
         ['0x0B' BACnetConfirmedServiceRequestDeleteObject
         ]
         ['0x0C' BACnetConfirmedServiceRequestReadProperty
+            [const uint 8 'objectIdentifierHeader' '0x0C']
+            [simple uint 10 'objectType']
+            [simple uint 22 'objectInstanceNumber']
+            [const uint 5 'propertyIdentifierHeader' '0x03']
+            [simple uint 3 'propertyIdentifierLength']
+            [array int 8 'propertyIdentifier' count 'propertyIdentifierLength']
         ]
         ['0x0E' BACnetConfirmedServiceRequestReadPropertyMultiple
         ]
         ['0x1A' BACnetConfirmedServiceRequestReadRange
         ]
         ['0x0F' BACnetConfirmedServiceRequestWriteProperty
+            [const uint 8 'objectIdentifierHeader' '0x0C']
+            [simple uint 10 'objectType']
+            [simple uint 22 'objectInstanceNumber']
+            [const uint 5 'propertyIdentifierHeader' '0x03']
+            [simple uint 3 'propertyIdentifierLength']
+            [array int 8 'propertyIdentifier' count 'propertyIdentifierLength']
+            [const uint 8 'openingTag' '0x3E']
+            [simple BACnetTag 'val']
+            [const uint 8 'closingTag' '0x3F']
+            [optional BACnetTag 'priority' 'curPos < (len - 1)']
         ]
         ['0x10' BACnetConfirmedServiceRequestWritePropertyMultiple
         ]
@@ -218,6 +267,7 @@
         ['0x1B' BACnetConfirmedServiceRequestLifeSafetyOperation
         ]
         ['0x1C' BACnetConfirmedServiceRequestSubscribeCOVProperty
+
         ]
         ['0x1D' BACnetConfirmedServiceRequestGetEventInformation
         ]
@@ -229,10 +279,20 @@
     ]
 ]
 
-[discriminatedType 'BACnetUnconfirmedServiceRequest'
+[discriminatedType 'BACnetUnconfirmedServiceRequest' [uint 16 'len']
     [discriminator uint 8 'serviceChoice']
     [typeSwitch 'serviceChoice'
         ['0x00' BACnetUnconfirmedServiceRequestIAm
+            [const uint 8 'objectIdentifierHeader' '0xC4']
+            [simple uint 10 'objectType']
+            [simple uint 22 'objectInstanceNumber']
+            [const uint 5 'maximumApduLengthAcceptedHeader' '0x04']
+            [simple uint 3 'maximumApduLengthAcceptedLength']
+            [array int 8 'maximumApduLengthAccepted' count 'maximumApduLengthAcceptedLength']
+            [const uint 8 'segmentationSupportedHeader' '0x91']
+            [simple uint 8 'segmentationSupported']
+            [const uint 8 'vendorIdHeader' '0x21']
+            [simple uint 8 'vendorId']
         ]
         ['0x01' BACnetUnconfirmedServiceRequestIHave
         ]
@@ -241,14 +301,35 @@
         ['0x03' BACnetUnconfirmedServiceRequestUnconfirmedEventNotification
         ]
         ['0x04' BACnetUnconfirmedServiceRequestUnconfirmedPrivateTransfer
+            [const uint 8 'vendorIdHeader' '0x09']
+            [simple uint 8 'vendorId']
+            [const uint 8 'serviceNumberHeader' '0x1A']
+            [simple uint 16 'serviceNumber']
+            [const uint 8 'listOfValuesOpeningTag' '0x2E']
+            [array int 8 'values' length 'len - 8']
+            [const uint 8 'listOfValuesClosingTag' '0x2F']
         ]
         ['0x05' BACnetUnconfirmedServiceRequestUnconfirmedTextMessage
         ]
         ['0x06' BACnetUnconfirmedServiceRequestTimeSynchronization
         ]
         ['0x07' BACnetUnconfirmedServiceRequestWhoHas
+            [const uint 8 'deviceInstanceLowLimitHeader' '0x0B']
+            [simple uint 24 'deviceInstanceLowLimit']
+            [const uint 8 'deviceInstanceHighLimitHeader' '0x1B']
+            [simple uint 24 'deviceInstanceHighLimit']
+            [const uint 8 'objectNameHeader' '0x3D']
+            [implicit uint 8 'objectNameLength' 'COUNT(objectName) + 1']
+            [simple uint 8 'objectNameCharacterSet']
+            [array int 8 'objectName' length 'objectNameLength - 1']
         ]
         ['0x08' BACnetUnconfirmedServiceRequestWhoIs
+            [const uint 5 'deviceInstanceRangeLowLimitHeader' '0x01']
+            [simple uint 3 'deviceInstanceRangeLowLimitLength']
+            [array int 8 'deviceInstanceRangeLowLimit' count 'deviceInstanceRangeLowLimitLength']
+            [const uint 5 'deviceInstanceRangeHighLimitHeader' '0x03']
+            [simple uint 3 'deviceInstanceRangeHighLimitLength']
+            [array int 8 'deviceInstanceRangeHighLimit' count 'deviceInstanceRangeHighLimitLength']
         ]
         ['0x09' BACnetUnconfirmedServiceRequestUTCTimeSynchronization
         ]
@@ -259,7 +340,65 @@
     ]
 ]
 
-[type 'BACnetServiceAck'
+[discriminatedType 'BACnetServiceAck'
+    [discriminator   uint 8 'serviceChoice']
+    [typeSwitch 'serviceChoice'
+        ['0x03' BACnetServiceAckGetAlarmSummary
+
+        ]
+        ['0x04' BACnetServiceAckGetEnrollmentSummary
+
+        ]
+        ['0x1D' BACnetServiceAckGetEventInformation
+
+        ]
+
+        ['0x06' BACnetServiceAckAtomicReadFile
+
+        ]
+        ['0x07' BACnetServiceAckAtomicWriteFile
+
+        ]
+
+        ['0x0A' BACnetServiceAckCreateObject
+
+        ]
+        ['0x0C' BACnetServiceAckReadProperty
+            [const uint 8 'objectIdentifierHeader' '0x0C']
+            [simple uint 10 'objectType']
+            [simple uint 22 'objectInstanceNumber']
+            [const uint 5 'propertyIdentifierHeader' '0x03']
+            [simple uint 3 'propertyIdentifierLength']
+            [array int 8 'propertyIdentifier' count 'propertyIdentifierLength']
+            [const uint 8 'openingTag' '0x3E']
+            [simple BACnetTag 'val']
+            [const uint 8 'closingTag' '0x3F']
+        ]
+        ['0x0E' BACnetServiceAckReadPropertyMultiple
+
+        ]
+        ['0x1A' BACnetServiceAckReadRange
+
+        ]
+
+        ['0x12' BACnetServiceAckConfirmedPrivateTransfer
+
+        ]
+
+        ['0x15' BACnetServiceAckVTOpen
+
+        ]
+        ['0x17' BACnetServiceAckVTData
+
+        ]
+
+        ['0x18' BACnetServiceAckRemovedAuthenticate
+
+        ]
+        ['0x0D' BACnetServiceAckRemovedReadPropertyConditional
+
+        ]
+    ]
 ]
 
 [discriminatedType 'BACnetConfirmedServiceACK'
@@ -319,6 +458,12 @@
         ['0x0A' BACnetErrorCreateObject
         ]
         ['0x0C' BACnetErrorReadProperty
+            [const uint 5 'errorClassHeader' '0x12']
+            [simple uint 3 'errorClassLength']
+            [array int 8 'errorClass' count 'errorClassLength']
+            [const uint 5 'errorCodeHeader' '0x12']
+            [simple uint 3 'errorCodeLength']
+            [array int 8 'errorCode' count 'errorCodeLength']
         ]
         ['0x0E' BACnetErrorReadPropertyMultiple
         ]
@@ -340,11 +485,67 @@
     ]
 ]
 
-[type 'Address'
-    [array uint 8 'address' count '4']
+[type 'BACnetAddress'
+    [array  uint 8 'address' count '4']
     [simple uint 16 'port']
 ]
 
+[type 'BACnetTagWithContent'
+    [simple        uint 4 'typeOrTagNumber']
+    [simple        uint 1 'contextSpecificTag']
+    [simple        uint 3 'lengthValueType']
+    [optional      uint 8 'extTagNumber' 'typeOrTagNumber == 15']
+    [optional      uint 8 'extLength' 'lengthValueType == 5']
+    [array         uint 8 'propertyIdentifier' length '(lengthValueType == 5) ? extLength : lengthValueType']
+    [const         uint 8 'openTag' '0x2e']
+    [simple        BACnetTag 'val']
+    [const         uint 8 'closingTag' '0x2f']
+]
+
+[discriminatedType 'BACnetTag'
+    [simple        uint 4 'typeOrTagNumber']
+    [discriminator uint 1 'contextSpecificTag']
+    [simple        uint 3 'lengthValueType']
+    [optional      uint 8 'extTagNumber' 'typeOrTagNumber == 15']
+    [optional      uint 8 'extLength' 'lengthValueType == 5']
+    [typeSwitch 'contextSpecificTag','typeOrTagNumber'
+        ['0','0x0' BACnetTagApplicationNull
+        ]
+        ['0','0x1' BACnetTagApplicationBoolean
+        ]
+        ['0','0x2' BACnetTagApplicationUnsignedInteger [uint 3 'lengthValueType', uint 8 'extLength']
+            [array uint 8 'data' length '(lengthValueType == 5) ? extLength : lengthValueType']
+        ]
+        ['0','0x3' BACnetTagApplicationSignedInteger [uint 3 'lengthValueType', uint 8 'extLength']
+            [array uint 8 'data' length '(lengthValueType == 5) ? extLength : lengthValueType']
+        ]
+        ['0','0x4' BACnetTagApplicationReal [uint 3 'lengthValueType', uint 8 'extLength']
+            [array uint 8 'data' length '(lengthValueType == 5) ? extLength : lengthValueType']
+        ]
+        ['0','0x5' BACnetTagApplicationDouble
+        ]
+        ['0','0x6' BACnetTagApplicationOctetString
+        ]
+        ['0','0x7' BACnetTagApplicationCharacterString
+        ]
+        ['0','0x8' BACnetTagApplicationBitString [uint 3 'lengthValueType', uint 8 'extLength']
+            [array uint 8 'data' length '(lengthValueType == 5) ? extLength : lengthValueType']
+        ]
+        ['0','0x9' BACnetTagApplicationEnumerated [uint 3 'lengthValueType', uint 8 'extLength']
+            [array uint 8 'data' length '(lengthValueType == 5) ? extLength : lengthValueType']
+        ]
+        ['0','0xA' BACnetTagApplicationDate
+        ]
+        ['0','0xB' BACnetTagApplicationTime
+        ]
+        ['0','0xC' BACnetTagApplicationObjectIdentifier
+        ]
+        ['1' BACnetTagContext [uint 4 'typeOrTagNumber', uint 8 'extTagNumber', uint 3 'lengthValueType', uint 8 'extLength']
+            [array uint 8 'data' length '(lengthValueType == 5) ? extLength : lengthValueType']
+        ]
+    ]
+]
+
 [enum uint 4 'ApplicationTags'
     ['0x0' NULL]
     ['0x1' BOOLEAN]
@@ -360,3 +561,115 @@
     ['0xB' TIME]
     ['0xC' BACNET_OBJECT_IDENTIFIER]
 ]
+
+[enum uint 4 'BACnetNetworkType'
+    ['0x0' ETHERNET]
+    ['0x1' ARCNET]
+    ['0x2' MSTP]
+    ['0x3' PTP]
+    ['0x4' LONTALK]
+    ['0x5' IPV4]
+    ['0x6' ZIGBEE]
+    ['0x7' VIRTUAL]
+    ['0x8' REMOVED_NON_BACNET]
+    ['0x9' IPV6]
+    ['0xA' SERIAL]
+]
+
+[enum uint 8 'BACnetNodeType'
+    ['0x00' UNKNOWN]
+    ['0x01' SYSTEM]
+    ['0x02' NETWORK]
+    ['0x03' DEVICE]
+    ['0x04' ORGANIZATIONAL]
+    ['0x05' AREA]
+    ['0x06' EQUIPMENT]
+    ['0x07' POINT]
+    ['0x08' COLLECTION]
+    ['0x09' PROPERTY]
+    ['0x0A' FUNCTIONAL]
+    ['0x0B' OTHER]
+    ['0x0C' SUBSYSTEM]
+    ['0x0D' BUILDING]
+    ['0x0E' FLOOR]
+    ['0x0F' SECTION]
+    ['0x10' MODULE]
+    ['0x11' TREE]
+    ['0x12' MEMBER]
+    ['0x13' PROTOCOL]
+    ['0x14' ROOM]
+    ['0x15' ZONE]
+]
+
+[enum uint 4 'BACnetNotifyType'
+    ['0x0' ALARM]
+    ['0x1' EVENT]
+    ['0x2' ACK_NOTIFICATION]
+]
+
+[enum uint 10 'BACnetObjectType'
+    ['0x000' ANALOG_INPUT]
+    ['0x001' ANALOG_OUTPUT]
+    ['0x002' ANALOG_VALUE]
+
+    ['0x003' BINARY_INPUT]
+    ['0x004' BINARY_OUTPUT]
+    ['0x005' BINARY_VALUE]
+
+    ['0x00D' MULTISTATE_INPUT]
+    ['0x00E' MULTISTATE_OUTPUT]
+    ['0x013' MULTISTATE_VALUE]
+
+    ['0x011' SCHEDULE]
+
+    ['0x008' DEVICE]
+
+    ['0x006' CALENDAR]
+    ['0x007' COMMAND]
+    ['0x009' EVENT_ENROLLMENT]
+    ['0x00A' FILE]
+    ['0x00B' GROUP]
+    ['0x00C' LOOP]
+    ['0x00F' NOTIFICATION_CLASS]
+    ['0x010' PROGRAM]
+    ['0x012' AVERAGING]
+    ['0x014' TREND_LOG]
+    ['0x015' LIFE_SAFETY_POINT]
+    ['0x016' LIFE_SAFETY_ZONE]
+    ['0x017' ACCUMULATOR]
+    ['0x018' PULSE_CONVERTER]
+    ['0x019' EVENT_LOG]
+    ['0x01A' GLOBAL_GROUP]
+    ['0x01B' TREND_LOG_MULTIPLE]
+    ['0x01C' LOAD_CONTROL]
+    ['0x01D' STRUCTURED_VIEW]
+    ['0x01E' ACCESS_DOOR]
+    ['0x01F' TIMER]
+    ['0x020' ACCESS_CREDENTIAL]
+    ['0x021' ACCESS_POINT]
+    ['0x022' ACCESS_RIGHTS]
+    ['0x023' ACCESS_USER]
+    ['0x024' ACCESS_ZONE]
+    ['0x025' CREDENTIAL_DATA_INPUT]
+    ['0x026' NETWORK_SECURITY]
+    ['0x027' BITSTRING_VALUE]
+    ['0x028' CHARACTERSTRING_VALUE]
+    ['0x029' DATEPATTERN_VALUE]
+    ['0x02A' DATE_VALUE]
+    ['0x02B' DATETIMEPATTERN_VALUE]
+    ['0x02C' DATETIME_VALUE]
+    ['0x02D' INTEGER_VALUE]
+    ['0x02E' LARGE_ANALOG_VALUE]
+    ['0x02F' OCTETSTRING_VALUE]
+    ['0x030' POSITIVE_INTEGER_VALUE]
+    ['0x031' TIMEPATTERN_VALUE]
+    ['0x032' TIME_VALUE]
+    ['0x033' NOTIFICATION_FORWARDER]
+    ['0x034' ALERT_ENROLLMENT]
+    ['0x035' CHANNEL]
+    ['0x036' LIGHTING_OUTPUT]
+    ['0x037' BINARY_LIGHTING_OUTPUT]
+    ['0x038' NETWORK_PORT]
+    ['0x039' ELEVATOR_GROUP]
+    ['0x03A' ESCALATOR]
+]
diff --git a/sandbox/test-java-bacnetip-driver/pom.xml b/sandbox/test-java-bacnetip-driver/pom.xml
index 0b8a904..793ac24 100644
--- a/sandbox/test-java-bacnetip-driver/pom.xml
+++ b/sandbox/test-java-bacnetip-driver/pom.xml
@@ -74,7 +74,7 @@
     </dependency>
     <dependency>
       <groupId>org.apache.plc4x</groupId>
-      <artifactId>plc4j-protocol-driver-base-tcp</artifactId>
+      <artifactId>plc4j-protocol-driver-base-raw-socket</artifactId>
       <version>0.5.0-SNAPSHOT</version>
     </dependency>
     <dependency>
@@ -88,6 +88,17 @@
       <version>0.5.0-SNAPSHOT</version>
       <scope>test</scope>
     </dependency>
+    <dependency>
+      <groupId>org.apache.plc4x</groupId>
+      <artifactId>plc4j-protocol-driver-base-pcap-socket</artifactId>
+      <version>0.5.0-SNAPSHOT</version>
+      <scope>test</scope>
+    </dependency>
+    <dependency>
+      <groupId>ch.qos.logback</groupId>
+      <artifactId>logback-classic</artifactId>
+      <scope>test</scope>
+    </dependency>
 
     <dependency>
       <groupId>org.apache.plc4x</groupId>
diff --git a/sandbox/test-java-bacnetip-driver/src/main/java/org/apache/plc4x/java/bacnetip/PassiveBacNetIpDriver.java b/sandbox/test-java-bacnetip-driver/src/main/java/org/apache/plc4x/java/bacnetip/PassiveBacNetIpDriver.java
new file mode 100644
index 0000000..48916f8
--- /dev/null
+++ b/sandbox/test-java-bacnetip-driver/src/main/java/org/apache/plc4x/java/bacnetip/PassiveBacNetIpDriver.java
@@ -0,0 +1,75 @@
+/*
+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.bacnetip;
+
+import org.apache.plc4x.java.api.PlcConnection;
+import org.apache.plc4x.java.api.authentication.PlcAuthentication;
+import org.apache.plc4x.java.api.exceptions.PlcConnectionException;
+import org.apache.plc4x.java.bacnetip.connection.PassiveBacNetIpPlcConnection;
+import org.apache.plc4x.java.spi.PlcDriver;
+import org.apache.plc4x.java.utils.rawsockets.netty.RawSocketIpAddress;
+
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+import static org.apache.plc4x.java.utils.rawsockets.netty.RawSocketAddress.ALL_PROTOCOLS;
+
+public class PassiveBacNetIpDriver implements PlcDriver {
+
+    public static final int BACNET_IP_PORT = 47808;
+
+    private static final Pattern PASSIVE_BACNET_IP_URI_PATTERN =
+        Pattern.compile("^bachnet-ip-passive://(?<networkDevice>.*)(?<params>\\?.*)?");
+
+    @Override
+    public String getProtocolCode() {
+        return "bacnet-ip";
+    }
+
+    @Override
+    public String getProtocolName() {
+        return "BACnet/IP";
+    }
+
+    @Override
+    public PlcConnection connect(String url) throws PlcConnectionException {
+        Matcher matcher = PASSIVE_BACNET_IP_URI_PATTERN.matcher(url);
+        if (!matcher.matches()) {
+            throw new PlcConnectionException(
+                "Connection url doesn't match the format 'bacnet-ip://{host|ip}'");
+        }
+        String networkDevice = matcher.group("networkDevice");
+
+        String params = matcher.group("params") != null ? matcher.group("params").substring(1) : null;
+
+        try {
+            RawSocketIpAddress rawSocketAddress = new RawSocketIpAddress(
+                networkDevice, ALL_PROTOCOLS, null, BACNET_IP_PORT);
+            return new PassiveBacNetIpPlcConnection(rawSocketAddress, params);
+        } catch (Exception e) {
+            throw new PlcConnectionException("Error connecting to host", e);
+        }
+    }
+
+    @Override
+    public PlcConnection connect(String url, PlcAuthentication authentication) throws PlcConnectionException {
+        throw new PlcConnectionException("BACnet/IP connections don't support authentication.");
+    }
+
+}
diff --git a/sandbox/test-java-bacnetip-driver/src/main/java/org/apache/plc4x/java/bacnetip/connection/BacNetIpFieldHandler.java b/sandbox/test-java-bacnetip-driver/src/main/java/org/apache/plc4x/java/bacnetip/connection/BacNetIpFieldHandler.java
new file mode 100644
index 0000000..d7f354d
--- /dev/null
+++ b/sandbox/test-java-bacnetip-driver/src/main/java/org/apache/plc4x/java/bacnetip/connection/BacNetIpFieldHandler.java
@@ -0,0 +1,36 @@
+/*
+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.bacnetip.connection;
+
+import org.apache.plc4x.java.api.exceptions.PlcInvalidFieldException;
+import org.apache.plc4x.java.api.model.PlcField;
+import org.apache.plc4x.java.bacnetip.model.BacNetIpField;
+import org.apache.plc4x.java.base.connection.DefaultPlcFieldHandler;
+
+public class BacNetIpFieldHandler extends DefaultPlcFieldHandler {
+
+    @Override
+    public PlcField createField(String fieldQuery) throws PlcInvalidFieldException {
+        if (BacNetIpField.matches(fieldQuery)) {
+            return BacNetIpField.of(fieldQuery);
+        }
+        throw new PlcInvalidFieldException(fieldQuery);
+    }
+
+}
diff --git a/sandbox/test-java-bacnetip-driver/src/main/java/org/apache/plc4x/java/bacnetip/connection/PassiveBacNetIpPlcConnection.java b/sandbox/test-java-bacnetip-driver/src/main/java/org/apache/plc4x/java/bacnetip/connection/PassiveBacNetIpPlcConnection.java
new file mode 100644
index 0000000..c15bac4
--- /dev/null
+++ b/sandbox/test-java-bacnetip-driver/src/main/java/org/apache/plc4x/java/bacnetip/connection/PassiveBacNetIpPlcConnection.java
@@ -0,0 +1,115 @@
+/*
+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.bacnetip.connection;
+
+import io.netty.channel.*;
+import org.apache.plc4x.java.api.exceptions.PlcInvalidFieldException;
+import org.apache.plc4x.java.api.messages.PlcReadRequest;
+import org.apache.plc4x.java.api.messages.PlcReadResponse;
+import org.apache.plc4x.java.api.model.PlcField;
+import org.apache.plc4x.java.bacnetip.model.BacNetIpField;
+import org.apache.plc4x.java.bacnetip.protocol.BacNetIpProtocol;
+import org.apache.plc4x.java.bacnetip.protocol.HelloWorldProtocol;
+import org.apache.plc4x.java.base.connection.ChannelFactory;
+import org.apache.plc4x.java.base.connection.NettyPlcConnection;
+import org.apache.plc4x.java.base.connection.RawSocketChannelFactory;
+import org.apache.plc4x.java.base.events.ConnectEvent;
+import org.apache.plc4x.java.base.events.ConnectedEvent;
+import org.apache.plc4x.java.base.messages.*;
+import org.apache.plc4x.java.utils.rawsockets.netty.RawSocketAddress;
+import org.apache.plc4x.java.utils.rawsockets.netty.RawSocketIpAddress;
+import org.apache.plc4x.java.utils.rawsockets.netty.UdpIpPacketHandler;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.util.concurrent.CompletableFuture;
+
+public class PassiveBacNetIpPlcConnection extends NettyPlcConnection implements PlcReader {
+
+    private static final Logger logger = LoggerFactory.getLogger(PassiveBacNetIpPlcConnection.class);
+
+    public PassiveBacNetIpPlcConnection(RawSocketIpAddress address, String params) {
+        this(new RawSocketChannelFactory(address.getDeviceName(), null,
+            address.getPort(), RawSocketAddress.ALL_PROTOCOLS, new UdpIpPacketHandler()), params);
+    }
+
+    public PassiveBacNetIpPlcConnection(ChannelFactory channelFactory, String params) {
+        super(channelFactory, true);
+    }
+
+    @Override
+    protected void sendChannelCreatedEvent() {
+        // Send an event to the pipeline telling the Protocol filters what's going on.
+        channel.pipeline().fireUserEventTriggered(new ConnectEvent());
+    }
+
+    @Override
+    public PlcField prepareField(String fieldQuery) throws PlcInvalidFieldException {
+        return BacNetIpField.of(fieldQuery);
+    }
+
+    @Override
+    protected ChannelHandler getChannelHandler(CompletableFuture<Void> sessionSetupCompleteFuture) {
+        return new ChannelInitializer() {
+            @Override
+            protected void initChannel(Channel channel) {
+                // Build the protocol stack for communicating with the s7 protocol.
+                ChannelPipeline pipeline = channel.pipeline();
+                pipeline.addLast(new ChannelInboundHandlerAdapter() {
+                    @Override
+                    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
+                        if (evt instanceof ConnectedEvent) {
+                            sessionSetupCompleteFuture.complete(null);
+                        } else {
+                            super.userEventTriggered(ctx, evt);
+                        }
+                    }
+                });
+                pipeline.addLast(new BacNetIpProtocol());
+                pipeline.addLast(new HelloWorldProtocol());
+            }
+        };
+    }
+
+    @Override
+    public boolean canRead() {
+        return true;
+    }
+
+    @Override
+    public PlcReadRequest.Builder readRequestBuilder() {
+        return new DefaultPlcReadRequest.Builder(this, new BacNetIpFieldHandler());
+    }
+
+    @Override
+    public CompletableFuture<PlcReadResponse> read(PlcReadRequest readRequest) {
+        InternalPlcReadRequest internalReadRequest = checkInternal(readRequest, InternalPlcReadRequest.class);
+        CompletableFuture<InternalPlcReadResponse> future = new CompletableFuture<>();
+        PlcRequestContainer<InternalPlcReadRequest, InternalPlcReadResponse> container =
+            new PlcRequestContainer<>(internalReadRequest, future);
+        channel.writeAndFlush(container).addListener(f -> {
+            if (!f.isSuccess()) {
+                future.completeExceptionally(f.cause());
+            }
+        });
+        return future
+            .thenApply(PlcReadResponse.class::cast);
+    }
+
+}
diff --git a/sandbox/test-java-bacnetip-driver/src/main/java/org/apache/plc4x/java/bacnetip/model/BacNetIpField.java b/sandbox/test-java-bacnetip-driver/src/main/java/org/apache/plc4x/java/bacnetip/model/BacNetIpField.java
new file mode 100644
index 0000000..49f51ea
--- /dev/null
+++ b/sandbox/test-java-bacnetip-driver/src/main/java/org/apache/plc4x/java/bacnetip/model/BacNetIpField.java
@@ -0,0 +1,47 @@
+/*
+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.bacnetip.model;
+
+import org.apache.plc4x.java.api.exceptions.PlcInvalidFieldException;
+import org.apache.plc4x.java.api.model.PlcField;
+
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+public class BacNetIpField implements PlcField {
+
+    private static final Pattern ADDRESS_PATTERN =
+        Pattern.compile("^N(?<fileNumber>\\d{1,7}):(?<elementNumber>\\d{1,7})(/(?<bitNumber>\\d{1,7}))?:(?<dataType>[a-zA-Z_]+)(\\[(?<size>\\d+)])?");
+
+    public BacNetIpField() {
+    }
+
+    public static boolean matches(String fieldString) {
+        return ADDRESS_PATTERN.matcher(fieldString).matches();
+    }
+
+    public static BacNetIpField of(String fieldString) {
+        Matcher matcher = ADDRESS_PATTERN.matcher(fieldString);
+        if(matcher.matches()) {
+            return new BacNetIpField();
+        }
+        throw new PlcInvalidFieldException("Unable to parse address: " + fieldString);
+    }
+
+}
diff --git a/sandbox/test-java-bacnetip-driver/src/main/java/org/apache/plc4x/java/bacnetip/protocol/BacNetIpProtocol.java b/sandbox/test-java-bacnetip-driver/src/main/java/org/apache/plc4x/java/bacnetip/protocol/BacNetIpProtocol.java
new file mode 100644
index 0000000..34489bc
--- /dev/null
+++ b/sandbox/test-java-bacnetip-driver/src/main/java/org/apache/plc4x/java/bacnetip/protocol/BacNetIpProtocol.java
@@ -0,0 +1,62 @@
+/*
+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.bacnetip.protocol;
+
+import io.netty.buffer.ByteBuf;
+import org.apache.plc4x.java.bacnetip.readwrite.BVLC;
+import org.apache.plc4x.java.bacnetip.readwrite.io.BVLCIO;
+import org.apache.plc4x.java.base.GeneratedDriverByteToMessageCodec;
+import org.apache.plc4x.java.utils.MessageIO;
+import org.apache.plc4x.java.utils.ParseException;
+import org.apache.plc4x.java.utils.ReadBuffer;
+import org.apache.plc4x.java.utils.WriteBuffer;
+
+public class BacNetIpProtocol extends GeneratedDriverByteToMessageCodec<BVLC> {
+
+    public BacNetIpProtocol() {
+        super(new MessageIO<BVLC, BVLC>() {
+            @Override
+            public BVLC parse(ReadBuffer io) throws ParseException {
+                return BVLCIO.parse(io);
+            }
+
+            @Override
+            public void serialize(WriteBuffer io, BVLC value) throws ParseException {
+                BVLCIO.serialize(io, value);
+            }
+        });
+    }
+
+    @Override
+    protected int getPacketSize(ByteBuf byteBuf) {
+        if(byteBuf.readableBytes() >= 4) {
+            return byteBuf.getUnsignedShort(byteBuf.readerIndex() + 2);
+        }
+        return -1;
+    }
+
+    @Override
+    protected void removeRestOfCorruptPackage(ByteBuf byteBuf) {
+        while (byteBuf.getUnsignedByte(0) != BVLC.BACNETTYPE) {
+            // Just consume the bytes till the next possible start position.
+            byteBuf.readByte();
+        }
+    }
+
+}
diff --git a/sandbox/test-java-bacnetip-driver/src/main/java/org/apache/plc4x/java/bacnetip/protocol/HelloWorldProtocol.java b/sandbox/test-java-bacnetip-driver/src/main/java/org/apache/plc4x/java/bacnetip/protocol/HelloWorldProtocol.java
new file mode 100644
index 0000000..c8b8e8f
--- /dev/null
+++ b/sandbox/test-java-bacnetip-driver/src/main/java/org/apache/plc4x/java/bacnetip/protocol/HelloWorldProtocol.java
@@ -0,0 +1,61 @@
+/*
+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.bacnetip.protocol;
+
+import io.netty.channel.ChannelHandlerContext;
+import org.apache.plc4x.java.bacnetip.readwrite.*;
+import org.apache.plc4x.java.base.PlcMessageToMessageCodec;
+import org.apache.plc4x.java.base.messages.PlcRequestContainer;
+
+import java.util.List;
+
+public class HelloWorldProtocol extends PlcMessageToMessageCodec<BVLC, PlcRequestContainer> {
+
+    @Override
+    protected void encode(ChannelHandlerContext channelHandlerContext, PlcRequestContainer plcRequestContainer, List<Object> list) throws Exception {
+        System.out.println(plcRequestContainer);
+    }
+
+    @Override
+    protected void decode(ChannelHandlerContext channelHandlerContext, BVLC packet, List<Object> list) throws Exception {
+        if(packet instanceof BVLCOriginalUnicastNPDU) {
+            final NPDU npdu = ((BVLCOriginalUnicastNPDU) packet).getNpdu();
+            final APDU apdu = npdu.getApdu();
+            if(apdu instanceof APDUSimpleAck) {
+                APDUSimpleAck ack = (APDUSimpleAck) apdu;
+                System.out.println("Simple-ACK(" + ack.getOriginalInvokeId() + ")");
+            } else if(apdu instanceof APDUConfirmedRequest) {
+                APDUConfirmedRequest request = (APDUConfirmedRequest) apdu;
+                final BACnetConfirmedServiceRequest serviceRequest = request.getServiceRequest();
+                if(serviceRequest instanceof BACnetConfirmedServiceRequestConfirmedCOVNotification) {
+                    BACnetConfirmedServiceRequestConfirmedCOVNotification covNotification = (BACnetConfirmedServiceRequestConfirmedCOVNotification) serviceRequest;
+                    final BACnetTagWithContent[] notifications = covNotification.getNotifications();
+                    System.out.println("Simple-ACK(" + request.getInvokeId() + "): Confirmed COV Notification [" + notifications.length + "]");
+                } else {
+                    System.out.println("Simple-ACK(" + request.getInvokeId() + "): Other");
+                }
+            } else {
+                System.out.println("Other");
+            }
+        } else {
+            System.out.println("Other");
+        }
+    }
+
+}
diff --git a/sandbox/test-java-bacnetip-driver/src/main/resources/META-INF/services/org.apache.plc4x.java.spi.PlcDriver b/sandbox/test-java-bacnetip-driver/src/main/resources/META-INF/services/org.apache.plc4x.java.spi.PlcDriver
new file mode 100644
index 0000000..9c311c9
--- /dev/null
+++ b/sandbox/test-java-bacnetip-driver/src/main/resources/META-INF/services/org.apache.plc4x.java.spi.PlcDriver
@@ -0,0 +1,19 @@
+#
+# 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.
+#
+org.apache.plc4x.java.bacnetip.PassiveBacNetIpDriver
diff --git a/sandbox/test-java-bacnetip-driver/src/test/java/org/apache/plc4x/java/bacnetip/ManualBacNetDecoder.java b/sandbox/test-java-bacnetip-driver/src/test/java/org/apache/plc4x/java/bacnetip/ManualBacNetDecoder.java
new file mode 100644
index 0000000..d7ca1c3
--- /dev/null
+++ b/sandbox/test-java-bacnetip-driver/src/test/java/org/apache/plc4x/java/bacnetip/ManualBacNetDecoder.java
@@ -0,0 +1,35 @@
+/*
+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.bacnetip;
+
+import org.apache.commons.codec.binary.Hex;
+import org.apache.plc4x.java.bacnetip.readwrite.BVLC;
+import org.apache.plc4x.java.bacnetip.readwrite.io.BVLCIO;
+import org.apache.plc4x.java.utils.ReadBuffer;
+
+public class ManualBacNetDecoder {
+
+    public static void main(String[] args) throws Exception {
+        final byte[] bytes = Hex.decodeHex("810a002b01040205790109011c020000142c000002f93a06b24e09552e44434a00002f096f2e8204002f4f");
+        ReadBuffer readBuffer = new ReadBuffer(bytes);
+        final BVLC packet = BVLCIO.parse(readBuffer);
+        System.out.println(packet);
+    }
+
+}
diff --git a/sandbox/test-java-bacnetip-driver/src/test/java/org/apache/plc4x/java/bacnetip/PassiveBacNetIpDriverManual.java b/sandbox/test-java-bacnetip-driver/src/test/java/org/apache/plc4x/java/bacnetip/PassiveBacNetIpDriverManual.java
new file mode 100644
index 0000000..5903221
--- /dev/null
+++ b/sandbox/test-java-bacnetip-driver/src/test/java/org/apache/plc4x/java/bacnetip/PassiveBacNetIpDriverManual.java
@@ -0,0 +1,39 @@
+/*
+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.bacnetip;
+
+import org.apache.plc4x.java.bacnetip.connection.PassiveBacNetIpPlcConnection;
+import org.apache.plc4x.java.base.connection.NettyPlcConnection;
+import org.apache.plc4x.java.base.connection.PcapChannelFactory;
+import org.apache.plc4x.java.utils.pcapsockets.netty.PcapSocketAddress;
+import org.apache.plc4x.java.utils.pcapsockets.netty.UdpIpPacketHandler;
+
+import java.io.File;
+
+public class PassiveBacNetIpDriverManual {
+
+    public static void main(String[] args) throws Exception {
+        NettyPlcConnection connection = new PassiveBacNetIpPlcConnection(new PcapChannelFactory(
+            //new File("/Users/christofer.dutz/Projects/Apache/PLC4X-Documents/BacNET/Captures/Merck/BACnetWhoIsRouterToNetwork.pcapng"), null,
+            new File("/Users/christofer.dutz/Downloads/20190906_udp.pcapng"), null,
+            PassiveBacNetIpDriver.BACNET_IP_PORT, PcapSocketAddress.ALL_PROTOCOLS, 1.5f, new UdpIpPacketHandler()), "");
+        connection.connect();
+    }
+
+}


[plc4x] 09/11: - Adjusted the existing dirvers to latest changes

Posted by cd...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

cdutz pushed a commit to branch develop
in repository https://gitbox.apache.org/repos/asf/plc4x.git

commit 5c8bc05b881ded89a1d7139ead6bf022f0e3909e
Author: Christofer Dutz <ch...@c-ware.de>
AuthorDate: Tue Sep 24 10:00:55 2019 +0200

    - Adjusted the existing dirvers to latest changes
---
 .../plc4x/java/abeth/protocol/AbEthProtocol.java   | 27 +++++++++++++++++++++-
 .../plc4x/java/df1/protocol/Df1Protocol.java       |  2 +-
 .../plc4x/javapassive/s7/PassiveS7PlcDriver.java   |  5 ++--
 .../s7/connection/PassiveS7PlcConnection.java      |  3 ++-
 4 files changed, 32 insertions(+), 5 deletions(-)

diff --git a/sandbox/test-java-ab-eth-driver/src/main/java/org/apache/plc4x/java/abeth/protocol/AbEthProtocol.java b/sandbox/test-java-ab-eth-driver/src/main/java/org/apache/plc4x/java/abeth/protocol/AbEthProtocol.java
index 34c6e64..24cd162 100644
--- a/sandbox/test-java-ab-eth-driver/src/main/java/org/apache/plc4x/java/abeth/protocol/AbEthProtocol.java
+++ b/sandbox/test-java-ab-eth-driver/src/main/java/org/apache/plc4x/java/abeth/protocol/AbEthProtocol.java
@@ -18,14 +18,39 @@ under the License.
 */
 package org.apache.plc4x.java.abeth.protocol;
 
+import io.netty.buffer.ByteBuf;
 import org.apache.plc4x.java.abeth.readwrite.CIPEncapsulationPacket;
 import org.apache.plc4x.java.abeth.readwrite.io.CIPEncapsulationPacketIO;
 import org.apache.plc4x.java.base.GeneratedDriverByteToMessageCodec;
+import org.apache.plc4x.java.utils.MessageIO;
+import org.apache.plc4x.java.utils.ParseException;
+import org.apache.plc4x.java.utils.ReadBuffer;
+import org.apache.plc4x.java.utils.WriteBuffer;
 
 public class AbEthProtocol extends GeneratedDriverByteToMessageCodec<CIPEncapsulationPacket> {
 
     public AbEthProtocol() {
-        super(new CIPEncapsulationPacketIO());
+        super(new MessageIO<CIPEncapsulationPacket, CIPEncapsulationPacket>() {
+            @Override
+            public CIPEncapsulationPacket parse(ReadBuffer io) throws ParseException {
+                return CIPEncapsulationPacketIO.parse(io);
+            }
+
+            @Override
+            public void serialize(WriteBuffer io, CIPEncapsulationPacket value) throws ParseException {
+                CIPEncapsulationPacketIO.serialize(io, value);
+            }
+        });
+    }
+
+    @Override
+    protected int getPacketSize(ByteBuf byteBuf) {
+        return byteBuf.readableBytes();
+    }
+
+    @Override
+    protected void removeRestOfCorruptPackage(ByteBuf byteBuf) {
+        // Nothing to do here ...
     }
 
 }
diff --git a/sandbox/test-java-df1-driver/src/main/java/org/apache/plc4x/java/df1/protocol/Df1Protocol.java b/sandbox/test-java-df1-driver/src/main/java/org/apache/plc4x/java/df1/protocol/Df1Protocol.java
index cd21883..6ce72d2 100644
--- a/sandbox/test-java-df1-driver/src/main/java/org/apache/plc4x/java/df1/protocol/Df1Protocol.java
+++ b/sandbox/test-java-df1-driver/src/main/java/org/apache/plc4x/java/df1/protocol/Df1Protocol.java
@@ -138,7 +138,7 @@ public class Df1Protocol extends PlcByteToMessageCodec<DF1Command> {
             in.readBytes(data);
             ReadBuffer readBuffer = new ReadBuffer(data, false);
 
-            resp = df1SymbolIO.parse(readBuffer, size);
+            resp = df1SymbolIO.parse(readBuffer);
 
 //        } while (readWasSucessfull);
 //        // TODO if unableto read
diff --git a/sandbox/test-java-passive-s7-driver/src/main/java/org/apache/plc4x/javapassive/s7/PassiveS7PlcDriver.java b/sandbox/test-java-passive-s7-driver/src/main/java/org/apache/plc4x/javapassive/s7/PassiveS7PlcDriver.java
index 05b0871..1c08af0 100644
--- a/sandbox/test-java-passive-s7-driver/src/main/java/org/apache/plc4x/javapassive/s7/PassiveS7PlcDriver.java
+++ b/sandbox/test-java-passive-s7-driver/src/main/java/org/apache/plc4x/javapassive/s7/PassiveS7PlcDriver.java
@@ -24,13 +24,14 @@ import org.apache.plc4x.java.api.authentication.PlcAuthentication;
 import org.apache.plc4x.java.api.exceptions.PlcConnectionException;
 import org.apache.plc4x.java.api.messages.PlcReadRequest;
 import org.apache.plc4x.java.spi.PlcDriver;
-import org.apache.plc4x.java.utils.rawsockets.netty.RawSocketAddress;
 import org.apache.plc4x.java.utils.rawsockets.netty.RawSocketIpAddress;
 import org.apache.plc4x.javapassive.s7.connection.PassiveS7PlcConnection;
 
 import java.util.regex.Matcher;
 import java.util.regex.Pattern;
 
+import static org.apache.plc4x.java.utils.rawsockets.netty.RawSocketAddress.ALL_PROTOCOLS;
+
 /**
  * Implementation of the S7 protocol, based on:
  * - S7 Protocol
@@ -67,7 +68,7 @@ public class PassiveS7PlcDriver implements PlcDriver {
 
         try {
             RawSocketIpAddress rawSocketAddress = new RawSocketIpAddress(
-                networkDevice, RawSocketIpAddress.ALL_PROTOCOLS, null, ISO_ON_TCP_PORT);
+                networkDevice, ALL_PROTOCOLS, null, ISO_ON_TCP_PORT);
             return new PassiveS7PlcConnection(rawSocketAddress, params);
         } catch (Exception e) {
             throw new PlcConnectionException("Error connecting to host", e);
diff --git a/sandbox/test-java-passive-s7-driver/src/main/java/org/apache/plc4x/javapassive/s7/connection/PassiveS7PlcConnection.java b/sandbox/test-java-passive-s7-driver/src/main/java/org/apache/plc4x/javapassive/s7/connection/PassiveS7PlcConnection.java
index 04245ec..a56b437 100644
--- a/sandbox/test-java-passive-s7-driver/src/main/java/org/apache/plc4x/javapassive/s7/connection/PassiveS7PlcConnection.java
+++ b/sandbox/test-java-passive-s7-driver/src/main/java/org/apache/plc4x/javapassive/s7/connection/PassiveS7PlcConnection.java
@@ -31,6 +31,7 @@ import org.apache.plc4x.java.base.events.ConnectedEvent;
 import org.apache.plc4x.java.base.messages.DefaultPlcReadRequest;
 import org.apache.plc4x.java.base.messages.PlcReader;
 import org.apache.plc4x.java.utils.rawsockets.netty.RawSocketIpAddress;
+import org.apache.plc4x.java.utils.rawsockets.netty.TcpIpPacketHandler;
 import org.apache.plc4x.javapassive.s7.protocol.HelloWorldProtocol;
 import org.apache.plc4x.javapassive.s7.protocol.PassiveS7Protocol;
 
@@ -40,7 +41,7 @@ public class PassiveS7PlcConnection extends NettyPlcConnection implements PlcRea
 
     public PassiveS7PlcConnection(RawSocketIpAddress address, String params) {
         this(new RawSocketChannelFactory(address.getDeviceName(), null,
-            102, -1), params);
+            address.getPort(), -1, new TcpIpPacketHandler()), params);
     }
 
     public PassiveS7PlcConnection(ChannelFactory channelFactory, String param) {


[plc4x] 01/11: - Added a new Udp driver base

Posted by cd...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

cdutz pushed a commit to branch develop
in repository https://gitbox.apache.org/repos/asf/plc4x.git

commit 05157ad4421a51e1e178bb20f04d28d183553f75
Author: Christofer Dutz <ch...@c-ware.de>
AuthorDate: Tue Sep 24 09:44:44 2019 +0200

    - Added a new Udp driver base
---
 plc4j/protocols/driver-bases/pom.xml               |   1 +
 plc4j/protocols/driver-bases/{ => udp}/pom.xml     |  47 ++++++---
 .../base/connection/UdpSocketChannelFactory.java   | 110 +++++++++++++++++++++
 3 files changed, 143 insertions(+), 15 deletions(-)

diff --git a/plc4j/protocols/driver-bases/pom.xml b/plc4j/protocols/driver-bases/pom.xml
index 0034532..2895a35 100644
--- a/plc4j/protocols/driver-bases/pom.xml
+++ b/plc4j/protocols/driver-bases/pom.xml
@@ -39,6 +39,7 @@
     <module>raw-socket</module>
     <module>serial</module>
     <module>tcp</module>
+    <module>udp</module>
     <module>test</module>
   </modules>
 
diff --git a/plc4j/protocols/driver-bases/pom.xml b/plc4j/protocols/driver-bases/udp/pom.xml
similarity index 53%
copy from plc4j/protocols/driver-bases/pom.xml
copy to plc4j/protocols/driver-bases/udp/pom.xml
index 0034532..cb1bc05 100644
--- a/plc4j/protocols/driver-bases/pom.xml
+++ b/plc4j/protocols/driver-bases/udp/pom.xml
@@ -23,23 +23,40 @@
 
   <parent>
     <groupId>org.apache.plc4x</groupId>
-    <artifactId>plc4j-protocols</artifactId>
+    <artifactId>plc4j-protocols-driver-bases</artifactId>
     <version>0.5.0-SNAPSHOT</version>
   </parent>
 
-  <artifactId>plc4j-protocols-driver-bases</artifactId>
-  <packaging>pom</packaging>
-
-  <name>PLC4J: Protocols: Driver-Bases</name>
-  <description>Collection of base-types for implementing different types of drivers.</description>
-
-  <modules>
-    <module>base</module>
-    <module>pcap-socket</module>
-    <module>raw-socket</module>
-    <module>serial</module>
-    <module>tcp</module>
-    <module>test</module>
-  </modules>
+  <artifactId>plc4j-protocol-driver-base-udp</artifactId>
+  <name>PLC4J: Protocol: Driver-Base: UDP</name>
+  <description>Base classes needed to implement plc4x drivers based on UDP connections.</description>
+
+  <dependencies>
+    <dependency>
+      <groupId>org.apache.plc4x</groupId>
+      <artifactId>plc4j-protocol-driver-base</artifactId>
+      <version>0.5.0-SNAPSHOT</version>
+    </dependency>
+    <dependency>
+      <groupId>org.apache.plc4x</groupId>
+      <artifactId>plc4j-api</artifactId>
+      <version>0.5.0-SNAPSHOT</version>
+    </dependency>
+
+    <dependency>
+      <groupId>io.netty</groupId>
+      <artifactId>netty-transport</artifactId>
+    </dependency>
+    <dependency>
+      <groupId>io.netty</groupId>
+      <artifactId>netty-common</artifactId>
+    </dependency>
+
+    <dependency>
+      <groupId>ch.qos.logback</groupId>
+      <artifactId>logback-classic</artifactId>
+      <scope>test</scope>
+    </dependency>
+  </dependencies>
 
 </project>
\ No newline at end of file
diff --git a/plc4j/protocols/driver-bases/udp/src/main/java/org/apache/plc4x/java/base/connection/UdpSocketChannelFactory.java b/plc4j/protocols/driver-bases/udp/src/main/java/org/apache/plc4x/java/base/connection/UdpSocketChannelFactory.java
new file mode 100644
index 0000000..942afc4
--- /dev/null
+++ b/plc4j/protocols/driver-bases/udp/src/main/java/org/apache/plc4x/java/base/connection/UdpSocketChannelFactory.java
@@ -0,0 +1,110 @@
+/*
+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.base.connection;
+
+import io.netty.bootstrap.Bootstrap;
+import io.netty.channel.Channel;
+import io.netty.channel.ChannelFuture;
+import io.netty.channel.ChannelHandler;
+import io.netty.channel.nio.NioEventLoopGroup;
+import io.netty.channel.socket.nio.NioDatagramChannel;
+import io.netty.util.concurrent.Future;
+import io.netty.util.concurrent.GenericFutureListener;
+import org.apache.plc4x.java.api.exceptions.PlcConnectionException;
+import org.apache.plc4x.java.api.exceptions.PlcException;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.net.InetAddress;
+import java.net.InetSocketAddress;
+import java.net.Socket;
+
+public class UdpSocketChannelFactory implements ChannelFactory {
+
+    private static final Logger logger = LoggerFactory.getLogger(UdpSocketChannelFactory.class);
+
+    private static final int PING_TIMEOUT_MS = 1_000;
+
+    private final InetAddress address;
+    private final int port;
+
+    public UdpSocketChannelFactory(InetAddress address, int port) {
+        this.address = address;
+        this.port = port;
+    }
+
+    @Override
+    public Channel createChannel(ChannelHandler channelHandler)
+        throws PlcConnectionException {
+        try {
+            final NioEventLoopGroup workerGroup = new NioEventLoopGroup();
+
+            Bootstrap bootstrap = new Bootstrap();
+            bootstrap.group(workerGroup);
+            bootstrap.channel(NioDatagramChannel.class);
+            //bootstrap.option(ChannelOption.SO_KEEPALIVE, true);
+            //bootstrap.option(ChannelOption.TCP_NODELAY, true);
+            // TODO we should use an explicit (configurable?) timeout here
+            // bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 1000);
+            bootstrap.handler(channelHandler);
+            // Start the client.
+            final ChannelFuture f = bootstrap.connect(address, port);
+            f.addListener(new GenericFutureListener<Future<? super Void>>() {
+                @Override public void operationComplete(Future<? super Void> future) throws Exception {
+                    if (!future.isSuccess()) {
+                        logger.info("Unable to connect, shutting down worker thread.");
+                        workerGroup.shutdownGracefully();
+                    }
+                }
+            });
+            // Wait for sync
+            f.sync();
+            f.awaitUninterruptibly(); // jf: unsure if we need that
+            // Wait till the session is finished initializing.
+            return f.channel();
+        } catch (InterruptedException e) {
+            Thread.currentThread().interrupt();
+            throw new PlcConnectionException("Error creating channel.", e);
+        } catch (Exception e) {
+            throw new PlcConnectionException("Error creating channel.", e);
+        }
+    }
+
+    @Override
+    public void ping() throws PlcException {
+        // TODO: Replace this check with a more accurate one ...
+        InetSocketAddress address = new InetSocketAddress(getAddress(), getPort());
+        try (Socket s = new Socket()) {
+            s.connect(address, PING_TIMEOUT_MS);
+            // TODO keep the address for a (timely) next request???
+            s.setReuseAddress(true);
+        } catch (Exception e) {
+            throw new PlcConnectionException("Unable to ping remote host");
+        }
+    }
+
+    public InetAddress getAddress() {
+        return address;
+    }
+
+    public int getPort() {
+        return port;
+    }
+
+}


[plc4x] 10/11: - Updated the version of commons-configuration to 2.6 - Updated the version of commons-text to 1.8 - Updated the version of jna to 5.3.1

Posted by cd...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

cdutz pushed a commit to branch develop
in repository https://gitbox.apache.org/repos/asf/plc4x.git

commit 333c0f96a4bace143a3d4e3377a28550e75bf128
Author: Christofer Dutz <ch...@c-ware.de>
AuthorDate: Tue Sep 24 10:02:00 2019 +0200

    - Updated the version of commons-configuration to 2.6
    - Updated the version of commons-text to 1.8
    - Updated the version of jna to 5.3.1
---
 pom.xml | 6 +++---
 1 file changed, 3 insertions(+), 3 deletions(-)

diff --git a/pom.xml b/pom.xml
index 61f8996..b9435a9 100644
--- a/pom.xml
+++ b/pom.xml
@@ -116,14 +116,14 @@
     <cmake-version>3.14.5</cmake-version>
     <commons-codec.version>1.12</commons-codec.version>
     <commons-collections4.version>4.1</commons-collections4.version>
-    <commons-configuration2.version>2.2</commons-configuration2.version>
+    <commons-configuration2.version>2.6</commons-configuration2.version>
     <commons-io.version>2.6</commons-io.version>
     <commons-lang.version>2.6</commons-lang.version>
     <commons-lang3.version>3.7</commons-lang3.version>
     <commons-logging.version>1.2</commons-logging.version>
     <commons-math3.version>3.5</commons-math3.version>
     <commons-pool2.version>2.6.0</commons-pool2.version>
-    <commons-text.version>1.6</commons-text.version>
+    <commons-text.version>1.8</commons-text.version>
     <crc.version>1.0.1</crc.version>
     <elasticsearch.version>7.2.0</elasticsearch.version>
     <equalsverifier.version>3.0.2</equalsverifier.version>
@@ -135,7 +135,7 @@
     <hamcrest.version>1.3</hamcrest.version>
     <jackson.version>2.9.9</jackson.version>
     <jmh.version>1.21</jmh.version>
-    <jna.version>4.5.1</jna.version>
+    <jna.version>5.3.1</jna.version>
     <joda-time.version>2.10</joda-time.version>
     <jopt-simple.version>5.0.2</jopt-simple.version>
     <jserialcom.version>2.5.1</jserialcom.version>


[plc4x] 03/11: - Fixed a bug in handling of ternary terms

Posted by cd...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

cdutz pushed a commit to branch develop
in repository https://gitbox.apache.org/repos/asf/plc4x.git

commit 54e898071b8da96b198f58fd13c1433070bfea36
Author: Christofer Dutz <ch...@c-ware.de>
AuthorDate: Tue Sep 24 09:47:33 2019 +0200

    - Fixed a bug in handling of ternary terms
---
 .../language/mspec/expression/ExpressionStringListener.java             | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/build-utils/protocol-base-mspec/src/main/java/org/apache/plc4x/plugins/codegenerator/language/mspec/expression/ExpressionStringListener.java b/build-utils/protocol-base-mspec/src/main/java/org/apache/plc4x/plugins/codegenerator/language/mspec/expression/ExpressionStringListener.java
index 903a5c8..b8ea9f9 100644
--- a/build-utils/protocol-base-mspec/src/main/java/org/apache/plc4x/plugins/codegenerator/language/mspec/expression/ExpressionStringListener.java
+++ b/build-utils/protocol-base-mspec/src/main/java/org/apache/plc4x/plugins/codegenerator/language/mspec/expression/ExpressionStringListener.java
@@ -260,7 +260,7 @@ public class ExpressionStringListener extends ExpressionBaseListener {
         }
         Term a = terms.get(0);
         Term b = terms.get(1);
-        Term c = terms.get(1);
+        Term c = terms.get(2);
         return new TernaryTerm(a, b, c, op);
     }
 


[plc4x] 07/11: - Changed the templates for the IO classes to no longer implement the MessageIO or MessageInput interfaces - The parse and serialize methods now take all arguments as real arguments and no longer as var args object array - No instances of IO modules are needed as now the parse and serialize methods are static (Needed to avoid stack overflows if types embed themselves) - Number of minor improvements

Posted by cd...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

cdutz pushed a commit to branch develop
in repository https://gitbox.apache.org/repos/asf/plc4x.git

commit dc22f3a0aac9cb7020d8cfbd7196dadb69a9671d
Author: Christofer Dutz <ch...@c-ware.de>
AuthorDate: Tue Sep 24 09:57:46 2019 +0200

    - Changed the templates for the IO classes to no longer implement the MessageIO or MessageInput interfaces
    - The parse and serialize methods now take all arguments as real arguments and no longer as var args object array
    - No instances of IO modules are needed as now the parse and serialize methods are static (Needed to avoid stack overflows if types embed themselves)
    - Number of minor improvements
---
 .../org/apache/plc4x/java/utils/MessageInput.java  |  2 +-
 .../org/apache/plc4x/java/utils/MessageOutput.java |  2 +-
 .../protocol/test/ProtocolTestsuiteRunner.java     | 33 ++++++++++++++++------
 3 files changed, 27 insertions(+), 10 deletions(-)

diff --git a/plc4j/utils/driver-base-java/src/main/java/org/apache/plc4x/java/utils/MessageInput.java b/plc4j/utils/driver-base-java/src/main/java/org/apache/plc4x/java/utils/MessageInput.java
index b83afa0..02ac2c8 100644
--- a/plc4j/utils/driver-base-java/src/main/java/org/apache/plc4x/java/utils/MessageInput.java
+++ b/plc4j/utils/driver-base-java/src/main/java/org/apache/plc4x/java/utils/MessageInput.java
@@ -20,6 +20,6 @@ package org.apache.plc4x.java.utils;
 
 public interface MessageInput<PARSER_TYPE> {
 
-    PARSER_TYPE parse(ReadBuffer io, Object... args) throws ParseException;
+    PARSER_TYPE parse(ReadBuffer io) throws ParseException;
 
 }
diff --git a/plc4j/utils/driver-base-java/src/main/java/org/apache/plc4x/java/utils/MessageOutput.java b/plc4j/utils/driver-base-java/src/main/java/org/apache/plc4x/java/utils/MessageOutput.java
index c76ade2..e15113c 100644
--- a/plc4j/utils/driver-base-java/src/main/java/org/apache/plc4x/java/utils/MessageOutput.java
+++ b/plc4j/utils/driver-base-java/src/main/java/org/apache/plc4x/java/utils/MessageOutput.java
@@ -20,6 +20,6 @@ package org.apache.plc4x.java.utils;
 
 public interface MessageOutput<SERIALIZER_TYPE> {
 
-    void serialize(WriteBuffer io, SERIALIZER_TYPE value, Object... args) throws ParseException;
+    void serialize(WriteBuffer io, SERIALIZER_TYPE value) throws ParseException;
 
 }
diff --git a/plc4j/utils/protocol-test-utils/src/main/java/org/apache/plc4x/protocol/test/ProtocolTestsuiteRunner.java b/plc4j/utils/protocol-test-utils/src/main/java/org/apache/plc4x/protocol/test/ProtocolTestsuiteRunner.java
index 9e8a3f1..8fbf7f7 100644
--- a/plc4j/utils/protocol-test-utils/src/main/java/org/apache/plc4x/protocol/test/ProtocolTestsuiteRunner.java
+++ b/plc4j/utils/protocol-test-utils/src/main/java/org/apache/plc4x/protocol/test/ProtocolTestsuiteRunner.java
@@ -39,6 +39,7 @@ import org.xmlunit.diff.Diff;
 
 import java.io.InputStream;
 import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Method;
 import java.util.*;
 
 public class ProtocolTestsuiteRunner {
@@ -139,18 +140,34 @@ public class ProtocolTestsuiteRunner {
 
     private MessageIO getMessageIOForTestcase(Testcase testcase) throws ProtocolTestsuiteException {
         String className = testcase.getXml().elements().get(0).attributeValue(new QName("className"));
+        String ioRootClassName = className.substring(0, className.lastIndexOf('.') + 1) + testcase.getRootType();
         String ioClassName = className.substring(0, className.lastIndexOf('.') + 1) + "io." +
             testcase.getRootType() + "IO";
         try {
+            Class<?> ioRootClass = Class.forName(ioRootClassName);
             Class<?> ioClass = Class.forName(ioClassName);
-            Object inst = ioClass.getDeclaredConstructor().newInstance();
-            if(inst instanceof MessageIO) {
-                return (MessageIO) inst;
-            } else {
-                throw new ProtocolTestsuiteException("Found IO component class is not of type MessageIO");
-            }
-        } catch (InstantiationException | InvocationTargetException | NoSuchMethodException | IllegalAccessException |
-            ClassNotFoundException e) {
+            final Method parseMethod = ioClass.getMethod("parse", ReadBuffer.class);
+            final Method serializeMethod = ioClass.getMethod("serialize", WriteBuffer.class, ioRootClass);
+            return new MessageIO() {
+                @Override
+                public Object parse(ReadBuffer io) throws ParseException {
+                    try {
+                        return parseMethod.invoke(null, io);
+                    } catch (IllegalAccessException | InvocationTargetException e) {
+                        throw new ParseException("error parsing", e);
+                    }
+                }
+
+                @Override
+                public void serialize(WriteBuffer io, Object value) throws ParseException {
+                    try {
+                        serializeMethod.invoke(null, io, value);
+                    } catch (IllegalAccessException | InvocationTargetException e) {
+                        throw new ParseException("error serializing", e);
+                    }
+                }
+            };
+        } catch (NoSuchMethodException | ClassNotFoundException e) {
             throw new ProtocolTestsuiteException("Unable to instantiate IO component", e);
         }
     }


[plc4x] 02/11: - Added filtering capabilities by ip, port and protocol id to the pcap channel

Posted by cd...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

cdutz pushed a commit to branch develop
in repository https://gitbox.apache.org/repos/asf/plc4x.git

commit d9e805cb88750b0dc265bf509d94af82d8ea9007
Author: Christofer Dutz <ch...@c-ware.de>
AuthorDate: Tue Sep 24 09:46:30 2019 +0200

    - Added filtering capabilities by ip, port and protocol id to the pcap channel
---
 .../apache/plc4x/java/base/connection/PcapChannelFactory.java | 11 +++++++++--
 1 file changed, 9 insertions(+), 2 deletions(-)

diff --git a/plc4j/protocols/driver-bases/pcap-socket/src/main/java/org/apache/plc4x/java/base/connection/PcapChannelFactory.java b/plc4j/protocols/driver-bases/pcap-socket/src/main/java/org/apache/plc4x/java/base/connection/PcapChannelFactory.java
index 7979ca7..6731a76 100644
--- a/plc4j/protocols/driver-bases/pcap-socket/src/main/java/org/apache/plc4x/java/base/connection/PcapChannelFactory.java
+++ b/plc4j/protocols/driver-bases/pcap-socket/src/main/java/org/apache/plc4x/java/base/connection/PcapChannelFactory.java
@@ -33,17 +33,24 @@ import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
 import java.io.File;
+import java.net.InetAddress;
 
 public class PcapChannelFactory implements ChannelFactory {
 
     private static final Logger logger = LoggerFactory.getLogger(PcapChannelFactory.class);
 
     private final File pcapFile;
+    private final InetAddress address;
+    private final int port;
+    private final int protocolId;
     private final float replaySpeedFactor;
     private final PacketHandler packetHandler;
 
-    public PcapChannelFactory(File pcapFile, float replaySpeedFactor, PacketHandler packetHandler) {
+    public PcapChannelFactory(File pcapFile, InetAddress address, int port, int protocolId, float replaySpeedFactor, PacketHandler packetHandler) {
         this.pcapFile = pcapFile;
+        this.address = address;
+        this.port = port;
+        this.protocolId = protocolId;
         this.replaySpeedFactor = replaySpeedFactor;
         this.packetHandler = packetHandler;
     }
@@ -62,7 +69,7 @@ public class PcapChannelFactory implements ChannelFactory {
             bootstrap.handler(channelHandler);
 
             // Start the client.
-            ChannelFuture f = bootstrap.connect(new PcapSocketAddress(pcapFile)).sync();
+            ChannelFuture f = bootstrap.connect(new PcapSocketAddress(pcapFile, address, port, protocolId)).sync();
             f.addListener(new GenericFutureListener<Future<? super Void>>() {
                 @Override public void operationComplete(Future<? super Void> future) throws Exception {
                     if (!future.isSuccess()) {


[plc4x] 08/11: - Improved and fine-tuned the GeneratedDriverByteToMessageCodec to allow checking if enough data is available and to remove the rest of faulty packages after failing to decode. - Added a protocolHandler property to the RawSocketChannelFactory - Added filter capabilities to the PcapSocket stuff - Added a speed-factor to slow down or speed up the pcap replay

Posted by cd...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

cdutz pushed a commit to branch develop
in repository https://gitbox.apache.org/repos/asf/plc4x.git

commit 2eb67c005e47ea6e4187da61fd1d87ec4e5ebd27
Author: Christofer Dutz <ch...@c-ware.de>
AuthorDate: Tue Sep 24 10:00:14 2019 +0200

    - Improved and fine-tuned the GeneratedDriverByteToMessageCodec to allow checking if enough data is available and to remove the rest of faulty packages after failing to decode.
    - Added a protocolHandler property to the RawSocketChannelFactory
    - Added filter capabilities to the PcapSocket stuff
    - Added a speed-factor to slow down or speed up the pcap replay
---
 plc4j/protocols/driver-bases/base/pom.xml          |  4 +++
 .../base/GeneratedDriverByteToMessageCodec.java    | 19 ++++++++--
 .../base/connection/RawSocketChannelFactory.java   | 11 +++---
 .../utils/pcapsockets/netty/PcapSocketAddress.java | 27 ++++++++++++--
 .../utils/pcapsockets/netty/PcapSocketChannel.java | 29 +++++++++++++--
 .../pcapsockets/netty/PcapSocketChannelConfig.java | 20 ++++++++++-
 .../utils/rawsockets/netty/RawSocketAddress.java   |  1 -
 ...wSocketAddress.java => UdpIpPacketHandler.java} | 41 ++++++++++------------
 8 files changed, 115 insertions(+), 37 deletions(-)

diff --git a/plc4j/protocols/driver-bases/base/pom.xml b/plc4j/protocols/driver-bases/base/pom.xml
index e27b060..ae89e08 100644
--- a/plc4j/protocols/driver-bases/base/pom.xml
+++ b/plc4j/protocols/driver-bases/base/pom.xml
@@ -64,6 +64,10 @@
       <groupId>io.netty</groupId>
       <artifactId>netty-transport</artifactId>
     </dependency>
+    <dependency>
+      <groupId>commons-codec</groupId>
+      <artifactId>commons-codec</artifactId>
+    </dependency>
 
     <dependency>
       <groupId>ch.qos.logback</groupId>
diff --git a/plc4j/protocols/driver-bases/base/src/main/java/org/apache/plc4x/java/base/GeneratedDriverByteToMessageCodec.java b/plc4j/protocols/driver-bases/base/src/main/java/org/apache/plc4x/java/base/GeneratedDriverByteToMessageCodec.java
index 4ac7fb6..5818622 100644
--- a/plc4j/protocols/driver-bases/base/src/main/java/org/apache/plc4x/java/base/GeneratedDriverByteToMessageCodec.java
+++ b/plc4j/protocols/driver-bases/base/src/main/java/org/apache/plc4x/java/base/GeneratedDriverByteToMessageCodec.java
@@ -20,6 +20,7 @@ package org.apache.plc4x.java.base;
 
 import io.netty.buffer.ByteBuf;
 import io.netty.channel.ChannelHandlerContext;
+import org.apache.commons.codec.binary.Hex;
 import org.apache.plc4x.java.utils.Message;
 import org.apache.plc4x.java.utils.MessageIO;
 import org.apache.plc4x.java.utils.ReadBuffer;
@@ -48,17 +49,31 @@ public abstract class GeneratedDriverByteToMessageCodec<T extends Message> exten
 
     @Override
     protected void decode(ChannelHandlerContext ctx, ByteBuf byteBuf, List<Object> out) throws Exception {
-        byte[] bytes = new byte[byteBuf.readableBytes()];
+        // Check if enough data is present to process the entire package.
+        int packetSize = getPacketSize(byteBuf);
+        if(packetSize == -1 || packetSize > byteBuf.readableBytes()) {
+            return;
+        }
+
+        byte[] bytes = new byte[packetSize];
         byteBuf.readBytes(bytes);
+
         ReadBuffer readBuffer = new ReadBuffer(bytes);
         while (readBuffer.getPos() < bytes.length) {
             try {
                 T packet = io.parse(readBuffer);
                 out.add(packet);
             } catch (Exception e) {
-                logger.warn("Error decoding package: " + e.getMessage());
+                logger.warn("Error decoding package with content [" + Hex.encodeHexString(bytes) + "]: "
+                    + e.getMessage(), e);
+                // Just remove any trailing junk ... if there is any.
+                removeRestOfCorruptPackage(byteBuf);
             }
         }
     }
 
+    abstract protected int getPacketSize(ByteBuf byteBuf);
+
+    abstract protected void removeRestOfCorruptPackage(ByteBuf byteBuf);
+
 }
diff --git a/plc4j/protocols/driver-bases/raw-socket/src/main/java/org/apache/plc4x/java/base/connection/RawSocketChannelFactory.java b/plc4j/protocols/driver-bases/raw-socket/src/main/java/org/apache/plc4x/java/base/connection/RawSocketChannelFactory.java
index 80684e6..5ba44c6 100644
--- a/plc4j/protocols/driver-bases/raw-socket/src/main/java/org/apache/plc4x/java/base/connection/RawSocketChannelFactory.java
+++ b/plc4j/protocols/driver-bases/raw-socket/src/main/java/org/apache/plc4x/java/base/connection/RawSocketChannelFactory.java
@@ -25,10 +25,7 @@ import io.netty.util.concurrent.Future;
 import io.netty.util.concurrent.GenericFutureListener;
 import org.apache.plc4x.java.api.exceptions.PlcConnectionException;
 import org.apache.plc4x.java.api.exceptions.PlcException;
-import org.apache.plc4x.java.utils.rawsockets.netty.RawSocketChannel;
-import org.apache.plc4x.java.utils.rawsockets.netty.RawSocketChannelOption;
-import org.apache.plc4x.java.utils.rawsockets.netty.RawSocketIpAddress;
-import org.apache.plc4x.java.utils.rawsockets.netty.TcpIpPacketHandler;
+import org.apache.plc4x.java.utils.rawsockets.netty.*;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
@@ -44,12 +41,14 @@ public class RawSocketChannelFactory implements ChannelFactory {
     private final InetAddress address;
     private final int port;
     private final int protocolId;
+    private final PacketHandler packetHandler;
 
-    public RawSocketChannelFactory(String deviceName, InetAddress address, int port, int protocolId) {
+    public RawSocketChannelFactory(String deviceName, InetAddress address, int port, int protocolId, PacketHandler packetHandler) {
         this.deviceName = deviceName;
         this.address = address;
         this.port = port;
         this.protocolId = protocolId;
+        this.packetHandler = packetHandler;
     }
 
     @Override
@@ -61,7 +60,7 @@ public class RawSocketChannelFactory implements ChannelFactory {
             Bootstrap bootstrap = new Bootstrap();
             bootstrap.group(workerGroup);
             bootstrap.channel(RawSocketChannel.class);
-            bootstrap.option(RawSocketChannelOption.PACKET_HANDLER, new TcpIpPacketHandler());
+            bootstrap.option(RawSocketChannelOption.PACKET_HANDLER, packetHandler);
             // TODO we should use an explicit (configurable?) timeout here
             // bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 1000);
             bootstrap.handler(channelHandler);
diff --git a/plc4j/utils/pcap-sockets/src/main/java/org/apache/plc4x/java/utils/pcapsockets/netty/PcapSocketAddress.java b/plc4j/utils/pcap-sockets/src/main/java/org/apache/plc4x/java/utils/pcapsockets/netty/PcapSocketAddress.java
index 78310e2..22cf7fa 100644
--- a/plc4j/utils/pcap-sockets/src/main/java/org/apache/plc4x/java/utils/pcapsockets/netty/PcapSocketAddress.java
+++ b/plc4j/utils/pcap-sockets/src/main/java/org/apache/plc4x/java/utils/pcapsockets/netty/PcapSocketAddress.java
@@ -19,19 +19,42 @@ under the License.
 package org.apache.plc4x.java.utils.pcapsockets.netty;
 
 import java.io.File;
+import java.net.InetAddress;
 import java.net.SocketAddress;
 
 public class PcapSocketAddress extends SocketAddress {
+
     private static final long serialVersionUID = 1L;
 
-    private File pcapFile;
+    public static final int ALL_PORTS = -1;
+    public static final int ALL_PROTOCOLS = -1;
+
+    private final File pcapFile;
+    private final InetAddress address;
+    private final int port;
+    private final int protocolId;
 
-    public PcapSocketAddress(File pcapFile) {
+    public PcapSocketAddress(File pcapFile, InetAddress address, int port, int protocolId) {
         this.pcapFile = pcapFile;
+        this.address = address;
+        this.port = port;
+        this.protocolId = protocolId;
     }
 
     public File getPcapFile() {
         return pcapFile;
     }
 
+    public InetAddress getAddress() {
+        return address;
+    }
+
+    public int getPort() {
+        return port;
+    }
+
+    public int getProtocolId() {
+        return protocolId;
+    }
+
 }
diff --git a/plc4j/utils/pcap-sockets/src/main/java/org/apache/plc4x/java/utils/pcapsockets/netty/PcapSocketChannel.java b/plc4j/utils/pcap-sockets/src/main/java/org/apache/plc4x/java/utils/pcapsockets/netty/PcapSocketChannel.java
index aff7ec0..dca632b 100644
--- a/plc4j/utils/pcap-sockets/src/main/java/org/apache/plc4x/java/utils/pcapsockets/netty/PcapSocketChannel.java
+++ b/plc4j/utils/pcap-sockets/src/main/java/org/apache/plc4x/java/utils/pcapsockets/netty/PcapSocketChannel.java
@@ -83,7 +83,6 @@ public class PcapSocketChannel extends OioByteStreamChannel {
         this.localAddress = localAddress;
         remoteRawSocketAddress = (PcapSocketAddress) remoteAddress;
 
-
         // Get a handle to the network-device and open it.
         File pcapFile = remoteRawSocketAddress.getPcapFile();
         if(!pcapFile.exists()) {
@@ -95,9 +94,16 @@ public class PcapSocketChannel extends OioByteStreamChannel {
         if(logger.isDebugEnabled()) {
             logger.debug(String.format("Opening PCAP capture file at: %s", pcapFile.getAbsolutePath()));
         }
+
         handle = Pcaps.openOffline(remoteRawSocketAddress.getPcapFile().getAbsolutePath(),
             PcapHandle.TimestampPrecision.NANO);
 
+        // If the address allows fine tuning which packets to process, set a filter to reduce the load.
+        String filter = getFilter(remoteRawSocketAddress);
+        if(filter.length() > 0) {
+            handle.setFilter(filter, BpfProgram.BpfCompileMode.OPTIMIZE);
+        }
+
         // Create a buffer where the raw socket worker can send data to.
         ByteBuf buffer = Unpooled.buffer();
 
@@ -114,7 +120,8 @@ public class PcapSocketChannel extends OioByteStreamChannel {
 
                         // If last-time is not null, wait for the given number of nano-seconds.
                         if(lastPacketTime != null) {
-                            int numMicrosecondsSleep = curPacketTime.getNanos() - lastPacketTime.getNanos();
+                            int numMicrosecondsSleep = (int)
+                                ((curPacketTime.getNanos() - lastPacketTime.getNanos()) / config.getSpeedFactor());
                             nanoSecondSleep(numMicrosecondsSleep);
                         }
 
@@ -208,6 +215,24 @@ public class PcapSocketChannel extends OioByteStreamChannel {
         }
     }
 
+    private String getFilter(PcapSocketAddress pcapSocketAddress) {
+        StringBuilder sb = new StringBuilder();
+        sb.append("(ether proto \\ip)");
+        // Add a filter for source or target address.
+        if(pcapSocketAddress.getAddress() != null) {
+            sb.append(" and (host ").append(pcapSocketAddress.getAddress().getHostAddress()).append(")");
+        }
+        // Add a filter for TCP or UDP port.
+        if(pcapSocketAddress.getPort() != PcapSocketAddress.ALL_PORTS) {
+            sb.append(" and (port ").append(pcapSocketAddress.getPort()).append(")");
+        }
+        if(pcapSocketAddress.getProtocolId() != PcapSocketAddress.ALL_PROTOCOLS) {
+            sb.append("(ether proto ").append(pcapSocketAddress.getProtocolId()).append(")");
+        }
+        return sb.toString();
+    }
+
+
     /**
      * This output stream simply discards anything it should send.
      */
diff --git a/plc4j/utils/pcap-sockets/src/main/java/org/apache/plc4x/java/utils/pcapsockets/netty/PcapSocketChannelConfig.java b/plc4j/utils/pcap-sockets/src/main/java/org/apache/plc4x/java/utils/pcapsockets/netty/PcapSocketChannelConfig.java
index e1ddb23..7896824 100644
--- a/plc4j/utils/pcap-sockets/src/main/java/org/apache/plc4x/java/utils/pcapsockets/netty/PcapSocketChannelConfig.java
+++ b/plc4j/utils/pcap-sockets/src/main/java/org/apache/plc4x/java/utils/pcapsockets/netty/PcapSocketChannelConfig.java
@@ -29,6 +29,7 @@ import java.util.Map;
 public class PcapSocketChannelConfig extends DefaultChannelConfig implements ChannelConfig {
 
     private PacketHandler packetHandler;
+    private float speedFactor;
 
     public PcapSocketChannelConfig(Channel channel) {
         super(channel);
@@ -42,7 +43,8 @@ public class PcapSocketChannelConfig extends DefaultChannelConfig implements Cha
 
     @Override
     public Map<ChannelOption<?>, Object> getOptions() {
-        return getOptions(super.getOptions(), PcapSocketChannelOption.PACKET_HANDLER);
+        return getOptions(super.getOptions(),
+            PcapSocketChannelOption.PACKET_HANDLER, PcapSocketChannelOption.SPEED_FACTOR);
     }
 
     @Override
@@ -53,6 +55,14 @@ public class PcapSocketChannelConfig extends DefaultChannelConfig implements Cha
                 return true;
             }
             return false;
+        } else if(option == PcapSocketChannelOption.SPEED_FACTOR) {
+            if(value instanceof Float) {
+                speedFactor = (float) value;
+                if(speedFactor > 0) {
+                    return true;
+                }
+            }
+            return false;
         } else {
             return super.setOption(option, value);
         }
@@ -66,4 +76,12 @@ public class PcapSocketChannelConfig extends DefaultChannelConfig implements Cha
         return packetHandler;
     }
 
+    public float getSpeedFactor() {
+        return speedFactor;
+    }
+
+    public void setSpeedFactor(float speedFactor) {
+        this.speedFactor = speedFactor;
+    }
+
 }
diff --git a/plc4j/utils/raw-sockets/src/main/java/org/apache/plc4x/java/utils/rawsockets/netty/RawSocketAddress.java b/plc4j/utils/raw-sockets/src/main/java/org/apache/plc4x/java/utils/rawsockets/netty/RawSocketAddress.java
index 0ef6312..ceb85f5 100644
--- a/plc4j/utils/raw-sockets/src/main/java/org/apache/plc4x/java/utils/rawsockets/netty/RawSocketAddress.java
+++ b/plc4j/utils/raw-sockets/src/main/java/org/apache/plc4x/java/utils/rawsockets/netty/RawSocketAddress.java
@@ -18,7 +18,6 @@ under the License.
 */
 package org.apache.plc4x.java.utils.rawsockets.netty;
 
-import java.net.InetAddress;
 import java.net.SocketAddress;
 
 public class RawSocketAddress extends SocketAddress {
diff --git a/plc4j/utils/raw-sockets/src/main/java/org/apache/plc4x/java/utils/rawsockets/netty/RawSocketAddress.java b/plc4j/utils/raw-sockets/src/main/java/org/apache/plc4x/java/utils/rawsockets/netty/UdpIpPacketHandler.java
similarity index 53%
copy from plc4j/utils/raw-sockets/src/main/java/org/apache/plc4x/java/utils/rawsockets/netty/RawSocketAddress.java
copy to plc4j/utils/raw-sockets/src/main/java/org/apache/plc4x/java/utils/rawsockets/netty/UdpIpPacketHandler.java
index 0ef6312..1b030df 100644
--- a/plc4j/utils/raw-sockets/src/main/java/org/apache/plc4x/java/utils/rawsockets/netty/RawSocketAddress.java
+++ b/plc4j/utils/raw-sockets/src/main/java/org/apache/plc4x/java/utils/rawsockets/netty/UdpIpPacketHandler.java
@@ -18,29 +18,24 @@ under the License.
 */
 package org.apache.plc4x.java.utils.rawsockets.netty;
 
-import java.net.InetAddress;
-import java.net.SocketAddress;
-
-public class RawSocketAddress extends SocketAddress {
-    private static final long serialVersionUID = 1L;
-
-    public static final int ALL_PROTOCOLS = -1;
-
-    private final String deviceName;
-
-    private final int protocolId;
-
-    public RawSocketAddress(String deviceName, int protocolId) {
-        this.deviceName = deviceName;
-        this.protocolId = protocolId;
-    }
-
-    public String getDeviceName() {
-        return deviceName;
-    }
-
-    public int getProtocolId() {
-        return protocolId;
+import org.pcap4j.packet.*;
+
+/**
+ * Little helper to automatically unwrap TCP packets to only
+ * pass along the payload and not the raw Ethernet packet.
+ */
+public class UdpIpPacketHandler implements PacketHandler {
+
+    @Override
+    public byte[] getData(Packet packet) {
+        EthernetPacket ethernetPacket = (EthernetPacket) packet;
+        IpV4Packet ipv4Packet = (IpV4Packet) ethernetPacket.getPayload();
+        UdpPacket udpPacket = (UdpPacket) ipv4Packet.getPayload();
+        if(udpPacket.getPayload() instanceof UnknownPacket) {
+            UnknownPacket unknownPacket = (UnknownPacket) udpPacket.getPayload();
+            return unknownPacket.getRawData();
+        }
+        return new byte[0];
     }
 
 }


[plc4x] 06/11: - Made the discriminator values in typeSwitch elements optional (resulting in a "default" case)

Posted by cd...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

cdutz pushed a commit to branch develop
in repository https://gitbox.apache.org/repos/asf/plc4x.git

commit b10bb73860f6426330c59ef25e996080c9d9fa1b
Author: Christofer Dutz <ch...@c-ware.de>
AuthorDate: Tue Sep 24 09:55:33 2019 +0200

    - Made the discriminator values in typeSwitch elements optional (resulting in a "default" case)
---
 .../plc4x/plugins/codegenerator/language/mspec/MSpec.g4     |  4 +++-
 .../language/mspec/parser/MessageFormatListener.java        | 13 +++++++++----
 2 files changed, 12 insertions(+), 5 deletions(-)

diff --git a/build-utils/protocol-base-mspec/src/main/antlr4/org/apache/plc4x/plugins/codegenerator/language/mspec/MSpec.g4 b/build-utils/protocol-base-mspec/src/main/antlr4/org/apache/plc4x/plugins/codegenerator/language/mspec/MSpec.g4
index 6b1b1d0..642afd4 100644
--- a/build-utils/protocol-base-mspec/src/main/antlr4/org/apache/plc4x/plugins/codegenerator/language/mspec/MSpec.g4
+++ b/build-utils/protocol-base-mspec/src/main/antlr4/org/apache/plc4x/plugins/codegenerator/language/mspec/MSpec.g4
@@ -117,7 +117,7 @@ typeReference
  ;
 
 caseStatement
- : LBRACKET discriminatorValues=multipleExpressions name=IDENTIFIER (LBRACKET params=argumentList RBRACKET)? fieldDefinition* RBRACKET
+ : LBRACKET (discriminatorValues=multipleExpressions)? name=IDENTIFIER (LBRACKET params=argumentList RBRACKET)? fieldDefinition* RBRACKET
  ;
 
 dataType
@@ -152,8 +152,10 @@ innerExpression
  | innerExpression '.' innerExpression // Field Reference or method call
  | innerExpression '[' + INTEGER_LITERAL + ']' // Array index
  | innerExpression BinaryOperator innerExpression  // Addition
+ | innerExpression '?' innerExpression ':' innerExpression
  | '(' innerExpression ')'
  | '"' innerExpression '"'
+ | '!' innerExpression
  ;
 
 COMMENT
diff --git a/build-utils/protocol-base-mspec/src/main/java/org/apache/plc4x/plugins/codegenerator/language/mspec/parser/MessageFormatListener.java b/build-utils/protocol-base-mspec/src/main/java/org/apache/plc4x/plugins/codegenerator/language/mspec/parser/MessageFormatListener.java
index 0f842e7..d457bc1 100644
--- a/build-utils/protocol-base-mspec/src/main/java/org/apache/plc4x/plugins/codegenerator/language/mspec/parser/MessageFormatListener.java
+++ b/build-utils/protocol-base-mspec/src/main/java/org/apache/plc4x/plugins/codegenerator/language/mspec/parser/MessageFormatListener.java
@@ -304,10 +304,15 @@ public class MessageFormatListener extends MSpecBaseListener {
             parserArguments.addAll(Arrays.asList(getParserArguments(ctx.argumentList().argument())));
         }
 
-        List<MSpecParser.ExpressionContext> expressions = ctx.discriminatorValues.expression();
-        String[] discriminatorValues = new String[expressions.size()];
-        for (int i = 0; i < expressions.size(); i++) {
-            discriminatorValues[i] = expressions.get(i).expr.getText();
+        String[] discriminatorValues;
+        if(ctx.discriminatorValues != null) {
+            List<MSpecParser.ExpressionContext> expressions = ctx.discriminatorValues.expression();
+            discriminatorValues = new String[expressions.size()];
+            for (int i = 0; i < expressions.size(); i++) {
+                discriminatorValues[i] = expressions.get(i).expr.getText();
+            }
+        } else {
+            discriminatorValues = new String[0];
         }
         DefaultDiscriminatedComplexTypeDefinition type =
             new DefaultDiscriminatedComplexTypeDefinition(typeName, parserArguments.toArray(new Argument[0]), null,


[plc4x] 05/11: - Changed the templates for the IO classes to no longer implement the MessageIO or MessageInput interfaces - The parse and serialize methods now take all arguments as real arguments and no longer as var args object array - No instances of IO modules are needed as now the parse and serialize methods are static (Needed to avoid stack overflows if types embed themselves) - Number of minor improvements

Posted by cd...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

cdutz pushed a commit to branch develop
in repository https://gitbox.apache.org/repos/asf/plc4x.git

commit 7525f2cd0fc73d4d021e62a655b079b076bee625
Author: Christofer Dutz <ch...@c-ware.de>
AuthorDate: Tue Sep 24 09:54:52 2019 +0200

    - Changed the templates for the IO classes to no longer implement the MessageIO or MessageInput interfaces
    - The parse and serialize methods now take all arguments as real arguments and no longer as var args object array
    - No instances of IO modules are needed as now the parse and serialize methods are static (Needed to avoid stack overflows if types embed themselves)
    - Number of minor improvements
---
 .../main/resources/templates/java/io-template.ftlh | 60 ++++++++--------------
 1 file changed, 20 insertions(+), 40 deletions(-)

diff --git a/build-utils/language-java/src/main/resources/templates/java/io-template.ftlh b/build-utils/language-java/src/main/resources/templates/java/io-template.ftlh
index b42dfbc..4f548a3 100644
--- a/build-utils/language-java/src/main/resources/templates/java/io-template.ftlh
+++ b/build-utils/language-java/src/main/resources/templates/java/io-template.ftlh
@@ -48,29 +48,11 @@ import java.lang.reflect.InvocationTargetException;
 import java.lang.reflect.Method;
 import java.util.*;
 
-public class ${typeName}IO implements <#if outputFlavor == "passive">MessageInput<${typeName}<#if helper.isDiscriminatedType(type)>IO.${typeName}Builder</#if>><#else>MessageIO<${typeName}<#if helper.isDiscriminatedType(type)>IO.${typeName}Builder</#if>, ${typeName}></#if> {
+public class ${typeName}IO {
 
     private static final Logger LOGGER = LoggerFactory.getLogger(${typeName}IO.class);
 
-<#if helper.getComplexTypes(type)?has_content>
-    // IO Helpers.
-<#list helper.getComplexTypes(type) as complexType>
-    private final ${complexType.name}IO ${complexType.name?uncap_first}IO;
-</#list>
-
-    public ${typeName}IO() {
-<#list helper.getComplexTypes(type) as complexType>
-        ${complexType.name?uncap_first}IO = new ${complexType.name}IO();
-</#list>
-   }
-
-</#if>
-    public ${typeName}<#if helper.isDiscriminatedType(type)>Builder</#if> parse(ReadBuffer io, Object... args) throws ParseException {
-<#if type.parserArguments?has_content>
-<#list type.parserArguments as parserArgument>
-        ${helper.getLanguageTypeNameForSpecType(parserArgument.type)} ${parserArgument.name} = (${helper.getLanguageTypeNameForSpecType(parserArgument.type)}) args[${parserArgument?index}];
-</#list>
-</#if>
+    public static ${typeName}<#if helper.isDiscriminatedType(type)>Builder</#if> parse(ReadBuffer io<#if type.parserArguments?has_content>, <#list type.parserArguments as parserArgument>${helper.getLanguageTypeName(parserArgument.type, false)} ${parserArgument.name}<#sep>, </#sep></#list></#if>) throws ParseException {
         int startPos = io.getPos();
         int curPos;
 <#list type.fields as field>
@@ -85,21 +67,21 @@ public class ${typeName}IO implements <#if outputFlavor == "passive">MessageInpu
         <#-- If this is a count array, we can directly initialize an array with the given size -->
         <#if helper.isCountArray(field)>
         // Count array
-        int _${field.name}Count = ${helper.toDeserializationExpression(field.loopExpression, type.parserArguments)};
+        int _${field.name}Count = ${helper.toDeserializationExpression(field.loopExpression, type.parserArguments)?no_esc};
         ${helper.getLanguageTypeNameForField(field)}[] ${field.name} = new ${helper.getLanguageTypeNameForField(field)}[_${field.name}Count];
         for(int i = 0; i < _${field.name}Count; i++) {
-            ${field.name}[i] = <#if helper.isSimpleType(field.type)>io.${helper.getReadBufferReadMethodCall(field.type)}<#else>${field.type.name?uncap_first}IO.parse(io<#if field.params?has_content>, <#list field.params as parserArgument>${parserArgument}<#sep>, </#sep></#list></#if>)</#if>;
+            ${field.name}[i] = <#if helper.isSimpleType(field.type)>io.${helper.getReadBufferReadMethodCall(field.type)}<#else>${field.type.name}IO.parse(io<#if field.params?has_content>, <#list field.params as parserArgument>${parserArgument}<#sep>, </#sep></#list></#if>)</#if>;
         }
         <#-- In all other cases do we have to work with a list, that is later converted to an array -->
         <#else>
             <#-- For a length array, we read data till the read position of the buffer reaches a given position -->
             <#if helper.isLengthArray(field)>
         // Length array
-        int _${field.name}Length = ${helper.toDeserializationExpression(field.loopExpression, type.parserArguments)};
+        int _${field.name}Length = ${helper.toDeserializationExpression(field.loopExpression, type.parserArguments)?no_esc};
         List<${helper.getNonPrimitiveLanguageTypeNameForField(field)}> _${field.name}List = new LinkedList<>();
         int ${field.name}EndPos = io.getPos() + _${field.name}Length;
         while(io.getPos() < ${field.name}EndPos) {
-            _${field.name}List.add(<#if helper.isSimpleType(field.type)>io.${helper.getReadBufferReadMethodCall(field.type)}<#else>${field.type.name?uncap_first}IO.parse(io<#if field.params?has_content>, <#list field.params as parserArgument>(${helper.getArgumentType(field.type, parserArgument?index)}) (${helper.toDeserializationExpression(parserArgument, type.parserArguments)})<#sep>, </#sep></#list></#if>)</#if>);
+            _${field.name}List.add(<#if helper.isSimpleType(field.type)>io.${helper.getReadBufferReadMethodCall(field.type)}<#else>${field.type.name}IO.parse(io<#if field.params?has_content>, <#list field.params as parserArgument>(${helper.getArgumentType(field.type, parserArgument?index)}) (${helper.toDeserializationExpression(parserArgument, type.parserArguments)})<#sep>, </#sep></#list></#if>)</#if>);
             <#-- After parsing, update the current position, but only if it's needed -->
             <#if field.loopExpression.contains("curPos")>
             curPos = io.getPos() - startPos;
@@ -109,8 +91,8 @@ public class ${typeName}IO implements <#if outputFlavor == "passive">MessageInpu
             <#elseif helper.isTerminatedArray(field)>
         // Terminated array
         List<${helper.getNonPrimitiveLanguageTypeNameForField(field)}> _${field.name}List = new LinkedList<>();
-        while(!((boolean) (${helper.toDeserializationExpression(field.loopExpression, type.parserArguments)}))) {
-            _${field.name}List.add(<#if helper.isSimpleType(field.type)>io.${helper.getReadBufferReadMethodCall(field.type)}<#else>${field.type.name?uncap_first}IO.parse(io<#if field.params?has_content>, <#list field.params as parserArgument>(${helper.getArgumentType(field.type, parserArgument?index)}) (${helper.toDeserializationExpression(parserArgument, type.parserArguments)})<#sep>, </#sep></#list></#if>)</#if>);
+        while(!((boolean) (${helper.toDeserializationExpression(field.loopExpression, type.parserArguments)?no_esc}))) {
+            _${field.name}List.add(<#if helper.isSimpleType(field.type)>io.${helper.getReadBufferReadMethodCall(field.type)}<#else>${field.type.name}IO.parse(io<#if field.params?has_content>, <#list field.params as parserArgument>(${helper.getArgumentType(field.type, parserArgument?index)}) (${helper.toDeserializationExpression(parserArgument, type.parserArguments)})<#sep>, </#sep></#list></#if>)</#if>);
 
             <#-- After parsing, update the current position, but only if it's needed -->
             <#if field.loopExpression.contains("curPos")>
@@ -226,9 +208,12 @@ public class ${typeName}IO implements <#if outputFlavor == "passive">MessageInpu
     <#case "optional">
 
         // Optional Field (${field.name}) (Can be skipped, if a given expression evaluates to false)
+        <#if field.conditionExpression.contains("curPos")>
+        curPos = io.getPos() - startPos;
+        </#if>
         ${helper.getLanguageTypeNameForField(field)} ${field.name} = null;
         if(${helper.toDeserializationExpression(field.conditionExpression, type.parserArguments)?no_esc}) {
-            ${field.name} = <#if helper.isSimpleType(field.type)>io.${helper.getReadBufferReadMethodCall(field.type)}<#else>${field.type.name?uncap_first}IO.parse(io);</#if>;
+            ${field.name} = <#if helper.isSimpleType(field.type)>io.${helper.getReadBufferReadMethodCall(field.type)}<#else>${field.type.name}IO.parse(io<#if field.params?has_content>, <#list field.params as parserArgument>(${helper.getArgumentType(field.type, parserArgument?index)}) (${helper.toDeserializationExpression(parserArgument, type.parserArguments)})<#sep>, </#sep></#list></#if>)</#if>;
         }
         <#break>
     <#case "padding">
@@ -253,15 +238,15 @@ public class ${typeName}IO implements <#if outputFlavor == "passive">MessageInpu
     <#case "simple">
 
         // Simple Field (${field.name})
-        ${helper.getLanguageTypeNameForField(field)} ${field.name} = <#if helper.isSimpleType(field.type)>io.${helper.getReadBufferReadMethodCall(field.type)}<#else>${field.type.name?uncap_first}IO.parse(io<#if field.params?has_content>, <#list field.params as parserArgument>(${helper.getArgumentType(field.type, parserArgument?index)}) (${helper.toDeserializationExpression(parserArgument, type.parserArguments)})<#sep>, </#sep></#list></#if>)</#if>;
+        ${helper.getLanguageTypeNameForField(field)} ${field.name} = <#if helper.isSimpleType(field.type)>io.${helper.getReadBufferReadMethodCall(field.type)}<#else>${field.type.name}IO.parse(io<#if field.params?has_content>, <#list field.params as parserArgument>(${helper.getArgumentType(field.type, parserArgument?index)}) (${helper.toDeserializationExpression(parserArgument, type.parserArguments)})<#sep>, </#sep></#list></#if>)</#if>;
         <#break>
     <#case "switch">
 
         // Switch Field (Depending on the discriminator values, passes the instantiation to a sub-type)
         ${typeName}Builder builder = null;
         <#list field.cases as case>
-        if(<#list case.discriminatorValues as discriminatorValue>EvaluationHelper.equals(${helper.toSwitchExpression(field.discriminatorNames[discriminatorValue?index])}, ${discriminatorValue})<#sep> && </#sep></#list>) {
-            builder = ${case.name?uncap_first}IO.parse(io<#if case.parserArguments?has_content>, <#list case.parserArguments as parserArgument>${parserArgument.name}<#sep>, </#sep></#list></#if>);
+        <#if case.discriminatorValues?has_content>if(<#list case.discriminatorValues as discriminatorValue>EvaluationHelper.equals(${helper.toSwitchExpression(field.discriminatorNames[discriminatorValue?index])}, ${discriminatorValue})<#sep> && </#sep></#list>) </#if>{
+            builder = ${case.name}IO.parse(io<#if case.parserArguments?has_content>, <#list case.parserArguments as parserArgument>${parserArgument.name}<#sep>, </#sep></#list></#if>);
         }<#sep> else </#sep>
         </#list>
         if (builder == null) {
@@ -282,12 +267,7 @@ public class ${typeName}IO implements <#if outputFlavor == "passive">MessageInpu
     }
 
 <#if outputFlavor != "passive">
-    public void serialize(WriteBuffer io, ${typeName} value, Object... args) throws ParseException {
-<#if type.parserArguments?has_content>
-<#list type.parserArguments as parserArgument>
-        ${helper.getLanguageTypeNameForSpecType(parserArgument.type)} ${parserArgument.name} = (${helper.getLanguageTypeNameForSpecType(parserArgument.type)}) args[${parserArgument?index}];
-</#list>
-</#if>
+    public static void serialize(WriteBuffer io, ${typeName} value) throws ParseException {
 <#list type.fields as field>
 <#switch field.typeName>
     <#case "array">
@@ -298,7 +278,7 @@ public class ${typeName}IO implements <#if outputFlavor == "passive">MessageInpu
                 <#if helper.isSimpleType(field.type)>
                 io.${helper.getWriteBufferReadMethodCall(field.type, "element")};
                 <#else>
-                ${field.type.name?uncap_first}IO.serialize(io, element);
+                ${field.type.name}IO.serialize(io, element);
                 </#if>
             }
         }
@@ -350,7 +330,7 @@ public class ${typeName}IO implements <#if outputFlavor == "passive">MessageInpu
             <#if helper.isSimpleType(field.type)>
             io.${helper.getWriteBufferReadMethodCall(field.type, "(" + field.name + ")")};
             <#else>
-            ${field.type.name?uncap_first}IO.serialize(io, ${field.name});
+            ${field.type.name}IO.serialize(io, ${field.name});
             </#if>
         }
         <#break>
@@ -375,7 +355,7 @@ public class ${typeName}IO implements <#if outputFlavor == "passive">MessageInpu
         <#if helper.isSimpleType(field.type)>
         io.${helper.getWriteBufferReadMethodCall(field.type, "(" + field.name + ")")};
         <#else>
-        ${field.type.name?uncap_first}IO.serialize(io, ${field.name}<#if field.params?has_content>, <#list field.params as term>(${helper.getArgumentType(field.type, term?index)}) (${helper.toDeserializationExpression(term, type.parserArguments)})<#sep>, </#sep></#list></#if>);
+        ${field.type.name}IO.serialize(io, ${field.name});
         </#if>
         <#break>
     <#case "switch">
@@ -383,7 +363,7 @@ public class ${typeName}IO implements <#if outputFlavor == "passive">MessageInpu
         // Switch field (Depending on the discriminator values, passes the instantiation to a sub-type)
         <#list field.cases as case>
         if(value instanceof ${case.name}) {
-            ${case.name?uncap_first}IO.serialize(io, (${case.name}) value<#if case.parserArguments?has_content>, <#list case.parserArguments as parserArgument>${parserArgument.name}<#sep>, </#sep></#list></#if>);
+            ${case.name}IO.serialize(io, (${case.name}) value);
         }<#sep> else </#sep>
         </#list>
         <#break>


[plc4x] 04/11: - Fixed some bugs in the code generation helper for non uint types (Were mostly all missing a "(")

Posted by cd...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

cdutz pushed a commit to branch develop
in repository https://gitbox.apache.org/repos/asf/plc4x.git

commit 9c203b866c8ec6b89182c1483a3807aa9bebc590
Author: Christofer Dutz <ch...@c-ware.de>
AuthorDate: Tue Sep 24 09:51:27 2019 +0200

    - Fixed some bugs in the code generation helper for non uint types (Were mostly all missing a "(")
---
 .../language/java/JavaLanguageTemplateHelper.java  | 36 +++++++++++-----------
 1 file changed, 18 insertions(+), 18 deletions(-)

diff --git a/build-utils/language-java/src/main/java/org/apache/plc4x/language/java/JavaLanguageTemplateHelper.java b/build-utils/language-java/src/main/java/org/apache/plc4x/language/java/JavaLanguageTemplateHelper.java
index ffc5258..c873e78 100644
--- a/build-utils/language-java/src/main/java/org/apache/plc4x/language/java/JavaLanguageTemplateHelper.java
+++ b/build-utils/language-java/src/main/java/org/apache/plc4x/language/java/JavaLanguageTemplateHelper.java
@@ -208,30 +208,30 @@ public class JavaLanguageTemplateHelper implements FreemarkerLanguageTemplateHel
             }
             case INT: {
                 if (simpleTypeReference.getSize() <= 8) {
-                    return "readByte" + simpleTypeReference.getSize() + ")";
+                    return "readByte(" + simpleTypeReference.getSize() + ")";
                 }
                 if (simpleTypeReference.getSize() <= 16) {
-                    return "readShort" + simpleTypeReference.getSize() + ")";
+                    return "readShort(" + simpleTypeReference.getSize() + ")";
                 }
                 if (simpleTypeReference.getSize() <= 32) {
-                    return "readInt" + simpleTypeReference.getSize() + ")";
+                    return "readInt(" + simpleTypeReference.getSize() + ")";
                 }
                 if (simpleTypeReference.getSize() <= 64) {
-                    return "readLong" + simpleTypeReference.getSize() + ")";
+                    return "readLong(" + simpleTypeReference.getSize() + ")";
                 }
-                return "readBigInteger" + simpleTypeReference.getSize() + ")";
+                return "readBigInteger(" + simpleTypeReference.getSize() + ")";
             }
             case FLOAT: {
                 if (simpleTypeReference.getSize() <= 32) {
-                    return "readFloat" + simpleTypeReference.getSize() + ")";
+                    return "readFloat(" + simpleTypeReference.getSize() + ")";
                 }
                 if (simpleTypeReference.getSize() <= 64) {
-                    return "readDouble" + simpleTypeReference.getSize() + ")";
+                    return "readDouble(" + simpleTypeReference.getSize() + ")";
                 }
-                return "readBigDecimal" + simpleTypeReference.getSize() + ")";
+                return "readBigDecimal(" + simpleTypeReference.getSize() + ")";
             }
             case STRING: {
-                return "readString" + simpleTypeReference.getSize() + ")";
+                return "readString(" + simpleTypeReference.getSize() + ")";
             }
         }
         return "Hurz";
@@ -259,30 +259,30 @@ public class JavaLanguageTemplateHelper implements FreemarkerLanguageTemplateHel
             }
             case INT: {
                 if (simpleTypeReference.getSize() <= 8) {
-                    return "writeByte" + simpleTypeReference.getSize() + ", ((Number) " + fieldName + ").byteValue())";
+                    return "writeByte(" + simpleTypeReference.getSize() + ", ((Number) " + fieldName + ").byteValue())";
                 }
                 if (simpleTypeReference.getSize() <= 16) {
-                    return "writeShort" + simpleTypeReference.getSize() + ", ((Number) " + fieldName + ").shortValue())";
+                    return "writeShort(" + simpleTypeReference.getSize() + ", ((Number) " + fieldName + ").shortValue())";
                 }
                 if (simpleTypeReference.getSize() <= 32) {
-                    return "writeInt" + simpleTypeReference.getSize() + ", ((Number) " + fieldName + ").intValue())";
+                    return "writeInt(" + simpleTypeReference.getSize() + ", ((Number) " + fieldName + ").intValue())";
                 }
                 if (simpleTypeReference.getSize() <= 64) {
-                    return "writeLong" + simpleTypeReference.getSize() + ", ((Number) " + fieldName + ").longValue())";
+                    return "writeLong(" + simpleTypeReference.getSize() + ", ((Number) " + fieldName + ").longValue())";
                 }
-                return "writeBigInteger" + simpleTypeReference.getSize() + ", (BigInteger) " + fieldName + ")";
+                return "writeBigInteger(" + simpleTypeReference.getSize() + ", (BigInteger) " + fieldName + ")";
             }
             case FLOAT: {
                 if (simpleTypeReference.getSize() <= 32) {
-                    return "writeFloat" + simpleTypeReference.getSize() + ", (float) " + fieldName + ")";
+                    return "writeFloat(" + simpleTypeReference.getSize() + ", (float) " + fieldName + ")";
                 }
                 if (simpleTypeReference.getSize() <= 64) {
-                    return "writeDouble" + simpleTypeReference.getSize() + ", (double) " + fieldName + ")";
+                    return "writeDouble(" + simpleTypeReference.getSize() + ", (double) " + fieldName + ")";
                 }
-                return "writeBigDecimal" + simpleTypeReference.getSize() + ", (BigDecimal) " + fieldName + ")";
+                return "writeBigDecimal(" + simpleTypeReference.getSize() + ", (BigDecimal) " + fieldName + ")";
             }
             case STRING: {
-                return "writeString" + simpleTypeReference.getSize() + ", (String) " + fieldName + ")";
+                return "writeString(" + simpleTypeReference.getSize() + ", (String) " + fieldName + ")";
             }
         }
         return "Hurz";