diff --git a/plc4j/drivers/canopen/src/main/java/org/apache/plc4x/java/canopen/api/conversation/canopen/SDODownloadConversation.java b/plc4j/drivers/canopen/src/main/java/org/apache/plc4x/java/canopen/api/conversation/canopen/SDODownloadConversation.java index 1960b4345c2..3883b83f76e 100644 --- a/plc4j/drivers/canopen/src/main/java/org/apache/plc4x/java/canopen/api/conversation/canopen/SDODownloadConversation.java +++ b/plc4j/drivers/canopen/src/main/java/org/apache/plc4x/java/canopen/api/conversation/canopen/SDODownloadConversation.java @@ -32,13 +32,11 @@ public class SDODownloadConversation extends CANOpenConversationBase { - private final CANConversation delegate; private final IndexAddress indexAddress; private final byte[] data; public SDODownloadConversation(CANConversation delegate, int nodeId, int answerNodeId, IndexAddress indexAddress, PlcValue value, CANOpenDataType type) { super(delegate, nodeId, answerNodeId); - this.delegate = delegate; this.indexAddress = indexAddress; try { diff --git a/plc4j/drivers/eip/src/main/java/org/apache/plc4x/java/eip/base/protocol/EipProtocolLogic.java b/plc4j/drivers/eip/src/main/java/org/apache/plc4x/java/eip/base/protocol/EipProtocolLogic.java index e6c72a17ba7..74d2b7c427a 100644 --- a/plc4j/drivers/eip/src/main/java/org/apache/plc4x/java/eip/base/protocol/EipProtocolLogic.java +++ b/plc4j/drivers/eip/src/main/java/org/apache/plc4x/java/eip/base/protocol/EipProtocolLogic.java @@ -819,7 +819,7 @@ private PlcValue parsePlcValue(EipTag tag, ByteBuf data, CIPDataTypeCode type) { // TODO: return as type STRUCT with structuredType to let user // apps/progs handle it. } - // TODO: This will fall-though to "default" + return null; } default: return null; @@ -852,7 +852,7 @@ private PlcValue parsePlcValue(EipTag tag, ByteBuf data, CIPDataTypeCode type) { else { // This is a different type of STRUCTURED data } - // TODO: This will fall-though to "default" + return null; } default: return null; diff --git a/plc4j/drivers/eip/src/main/java/org/apache/plc4x/java/eip/base/tag/EipTag.java b/plc4j/drivers/eip/src/main/java/org/apache/plc4x/java/eip/base/tag/EipTag.java index d8ac9898e8d..fcaf501f47a 100644 --- a/plc4j/drivers/eip/src/main/java/org/apache/plc4x/java/eip/base/tag/EipTag.java +++ b/plc4j/drivers/eip/src/main/java/org/apache/plc4x/java/eip/base/tag/EipTag.java @@ -39,10 +39,9 @@ public class EipTag implements PlcTag, Serializable { private static final Pattern ADDRESS_PATTERN = Pattern.compile("^(?[%a-zA-Z_.0-9]+\\[?[0-9]*]?):?(?[A-Z]*):?(?[0-9]*)"); - private static final String TAG = "tag"; - private static final String ELEMENTS = "elementNb"; - private static final String TYPE = "dataType"; - + private static final String GROUP_NAME_TAG = "tag"; + private static final String GROUP_NAME_GROUP_NAME_ELEMENTS = "elementNb"; + private static final String GROUP_NAME_TYPE = "dataType"; private final String tag; private CIPDataTypeCode type; @@ -111,14 +110,14 @@ public static boolean matches(String tagQuery) { public static EipTag of(String tagString) { Matcher matcher = ADDRESS_PATTERN.matcher(tagString); if (matcher.matches()) { - String tag = matcher.group(TAG); + String tag = matcher.group(GROUP_NAME_TAG); int nb = 1; CIPDataTypeCode type; - if (!matcher.group(ELEMENTS).isEmpty()) { - nb = Integer.parseInt(matcher.group(ELEMENTS)); + if (!matcher.group(GROUP_NAME_GROUP_NAME_ELEMENTS).isEmpty()) { + nb = Integer.parseInt(matcher.group(GROUP_NAME_GROUP_NAME_ELEMENTS)); } - if (!matcher.group(TYPE).isEmpty()) { - type = CIPDataTypeCode.valueOf(matcher.group(TYPE)); + if (!matcher.group(GROUP_NAME_TYPE).isEmpty()) { + type = CIPDataTypeCode.valueOf(matcher.group(GROUP_NAME_TYPE)); } else { type = CIPDataTypeCode.DINT; } diff --git a/plc4j/drivers/knxnetip/src/main/java/org/apache/plc4x/java/knxnetip/ets/EtsParser.java b/plc4j/drivers/knxnetip/src/main/java/org/apache/plc4x/java/knxnetip/ets/EtsParser.java index 5cc69f76f60..1cc4b502480 100644 --- a/plc4j/drivers/knxnetip/src/main/java/org/apache/plc4x/java/knxnetip/ets/EtsParser.java +++ b/plc4j/drivers/knxnetip/src/main/java/org/apache/plc4x/java/knxnetip/ets/EtsParser.java @@ -74,14 +74,15 @@ public EtsModel parse(File knxprojFile, String password) { File knxMasterFile = new File(tempDir.toFile(), "knx_master.xml"); // If the file contains: it's an ETS6 file // In all other cases, we'll treat it as ETS5 - Scanner scanner = new Scanner(knxMasterFile); String etsSchemaVersion = null; - while (scanner.hasNextLine()) { - final String curLine = scanner.nextLine(); - if(curLine.contains("http://knx.org/xml/project/")) { - etsSchemaVersion = curLine.substring(curLine.indexOf("http://knx.org/xml/project/") + "http://knx.org/xml/project/".length()); - etsSchemaVersion = etsSchemaVersion.substring(0, etsSchemaVersion.indexOf("\"")); - break; + try(Scanner scanner = new Scanner(knxMasterFile)) { + while (scanner.hasNextLine()) { + final String curLine = scanner.nextLine(); + if(curLine.contains("http://knx.org/xml/project/")) { + etsSchemaVersion = curLine.substring(curLine.indexOf("http://knx.org/xml/project/") + "http://knx.org/xml/project/".length()); + etsSchemaVersion = etsSchemaVersion.substring(0, etsSchemaVersion.indexOf("\"")); + break; + } } } EtsFileHandler fileHandler = ("21".equals(etsSchemaVersion)) ? new Ets6FileHandler() : new Ets5FileHandler(); diff --git a/plc4j/drivers/knxnetip/src/main/java/org/apache/plc4x/java/knxnetip/tag/KnxNetIpTag.java b/plc4j/drivers/knxnetip/src/main/java/org/apache/plc4x/java/knxnetip/tag/KnxNetIpTag.java index 56138d3fe59..debc323badd 100644 --- a/plc4j/drivers/knxnetip/src/main/java/org/apache/plc4x/java/knxnetip/tag/KnxNetIpTag.java +++ b/plc4j/drivers/knxnetip/src/main/java/org/apache/plc4x/java/knxnetip/tag/KnxNetIpTag.java @@ -120,20 +120,17 @@ public boolean matchesGroupAddress(GroupAddress groupAddress) { return false; } // NOTE: This case fallthrough is intentional :-) - switch (getLevels()) { - case 3: - if(!WILDCARD.equals(getMiddleGroup()) && !getMiddleGroup().equals(otherAddress.getMiddleGroup())) { - return false; - } - case 2: - if(!WILDCARD.equals(getSubGroup()) && !getSubGroup().equals(otherAddress.getSubGroup())) { - return false; - } - case 1: - return WILDCARD.equals(getMainGroup()) || getMainGroup().equals(otherAddress.getMainGroup()); - default: + if(getLevels() == 3) { + if (!WILDCARD.equals(getMiddleGroup()) && !getMiddleGroup().equals(otherAddress.getMiddleGroup())) { return false; + } } + if(getLevels() >= 2) { + if (!WILDCARD.equals(getSubGroup()) && !getSubGroup().equals(otherAddress.getSubGroup())) { + return false; + } + } + return WILDCARD.equals(getMainGroup()) || getMainGroup().equals(otherAddress.getMainGroup()); } } diff --git a/plc4j/drivers/profinet-ng/src/main/java/org/apache/plc4x/java/profinet/protocol/ProfinetProtocolLogic.java b/plc4j/drivers/profinet-ng/src/main/java/org/apache/plc4x/java/profinet/protocol/ProfinetProtocolLogic.java index 42cc71a7d49..d35607ace6c 100644 --- a/plc4j/drivers/profinet-ng/src/main/java/org/apache/plc4x/java/profinet/protocol/ProfinetProtocolLogic.java +++ b/plc4j/drivers/profinet-ng/src/main/java/org/apache/plc4x/java/profinet/protocol/ProfinetProtocolLogic.java @@ -50,7 +50,7 @@ public class ProfinetProtocolLogic extends Plc4xProtocolBase implements HasConfiguration { - private ProfinetDriverContext driverContext; + private ProfinetDriverContext profinetDriverContext; private ProfinetConfiguration configuration; private final Logger logger = LoggerFactory.getLogger(ProfinetProtocolLogic.class); @@ -62,7 +62,7 @@ public void setDriverContext(DriverContext driverContext) { throw new PlcRuntimeException( "Expecting a driverContext of type ProfinetDriverContext, but got " + driverContext.getClass().getName()); } - this.driverContext = (ProfinetDriverContext) driverContext; + this.profinetDriverContext = (ProfinetDriverContext) driverContext; } @Override @@ -95,7 +95,7 @@ public void onConnect(ConversationContext context) { // Check if we actually got the vendor-id and product-id ... // without these, we don't know what to do with the device. - if ((driverContext.getVendorId() == 0) || (driverContext.getDeviceId() == 0)) { + if ((profinetDriverContext.getVendorId() == 0) || (profinetDriverContext.getDeviceId() == 0)) { logger.error("Unable to determine vendor-id or product-id, closing channel..."); context.getChannel().close(); return; @@ -103,10 +103,10 @@ public void onConnect(ConversationContext context) { // Look up the GSD file for this device ... ProfinetISO15745Profile deviceProfile = - configuration.getGsdProfile(driverContext.getVendorId(), driverContext.getDeviceId()); + configuration.getGsdProfile(profinetDriverContext.getVendorId(), profinetDriverContext.getDeviceId()); if (deviceProfile == null) { logger.error("Unable to find GSD profile for device with vendor-id {} and device-id {}", - driverContext.getVendorId(), driverContext.getDeviceId()); + profinetDriverContext.getVendorId(), profinetDriverContext.getDeviceId()); context.getChannel().close(); return; } @@ -115,11 +115,11 @@ public void onConnect(ConversationContext context) { if (configuration.dapId != null) { for (ProfinetDeviceAccessPointItem profinetDeviceAccessPointItem : deviceProfile.getProfileBody().getApplicationProcess().getDeviceAccessPointList()) { if(profinetDeviceAccessPointItem.getId().equalsIgnoreCase(configuration.dapId)) { - driverContext.setDapId(profinetDeviceAccessPointItem.getId()); + profinetDriverContext.setDapId(profinetDeviceAccessPointItem.getId()); break; } } - if(driverContext.getDapId() == null) { + if(profinetDriverContext.getDapId() == null) { logger.error("Couldn't find requested device access points (DAP): {}", configuration.dapId); context.getChannel().close(); } @@ -151,7 +151,7 @@ else if(deviceProfile.getProfileBody().getApplicationProcess().getDeviceAccessPo // Try to read the RealIdentificationData ... RawSocketChannel pnChannel = ((RawSocketChannel) context.getChannel()); CompletableFuture future1 = - PnDcpPacketFactory.sendRealIdentificationDataRequest(context, pnChannel, driverContext); + PnDcpPacketFactory.sendRealIdentificationDataRequest(context, pnChannel, profinetDriverContext); future1.whenComplete((realIdentificationData, throwable1) -> { if(throwable1 != null) { logger.error("Unable to detect device access point, closing channel...", throwable1); @@ -190,12 +190,12 @@ else if(deviceProfile.getProfileBody().getApplicationProcess().getDeviceAccessPo } long moduleIdentNumber = Long.parseLong(moduleIdentNumberStr, 16); if(moduleIdentNumber == dapModuleIdentificationNumber) { - driverContext.setDap(curDap); + profinetDriverContext.setDap(curDap); break; } } // Abort, if we weren't able to detect a DAP. - if(driverContext.getDap() == null) { + if(profinetDriverContext.getDap() == null) { logger.error("Unable to auto-detect the device access point, closing channel..."); context.getChannel().close(); return; @@ -259,8 +259,8 @@ else if(deviceProfile.getProfileBody().getApplicationProcess().getDeviceAccessPo } } } - driverContext.setModuleIndex(moduleIndex); - driverContext.setSubmoduleIndex(submoduleIndex); + profinetDriverContext.setModuleIndex(moduleIndex); + profinetDriverContext.setSubmoduleIndex(submoduleIndex); context.fireConnected(); }); @@ -320,7 +320,7 @@ public CompletableFuture browse(PlcBrowseRequest browseReques Map> values = new HashMap<>(); for (String queryName : browseRequest.getQueryNames()) { List items = new ArrayList<>(); - for(Map.Entry> slotEntry : driverContext.getSubmoduleIndex().entrySet()) { + for(Map.Entry> slotEntry : profinetDriverContext.getSubmoduleIndex().entrySet()) { int slot = slotEntry.getKey(); for(Map.Entry subslotEntry: slotEntry.getValue().entrySet()) { int subslot = subslotEntry.getKey(); @@ -369,7 +369,7 @@ public CompletableFuture browse(PlcBrowseRequest browseReques @Override public CompletableFuture subscribe(PlcSubscriptionRequest subscriptionRequest) { // When subscribing, we actually set up the PN IO Application Relation and make the remote device start sending data. - if (driverContext.getDap() == null) { + if (profinetDriverContext.getDap() == null) { return CompletableFuture.failedFuture(new PlcConnectionException("DAP not set")); } @@ -420,12 +420,12 @@ public CompletableFuture subscribe(PlcSubscriptionReque int subslotNumber = subslotEntry.getKey(); Map> direction = subslotEntry.getValue(); - int iocsLength = driverContext.getSubmoduleIndex().get(slotNumber).get(subslotNumber).getIoData().getIocsLength(); + int iocsLength = profinetDriverContext.getSubmoduleIndex().get(slotNumber).get(subslotNumber).getIoData().getIocsLength(); // The default is 1 if(iocsLength == 0) { iocsLength = 1; } - int iopsLength = driverContext.getSubmoduleIndex().get(slotNumber).get(subslotNumber).getIoData().getIopsLength(); + int iopsLength = profinetDriverContext.getSubmoduleIndex().get(slotNumber).get(subslotNumber).getIoData().getIopsLength(); // The default is 1 if(iopsLength == 0) { iopsLength = 1; @@ -478,12 +478,12 @@ public CompletableFuture subscribe(PlcSubscriptionReque blocks.add(new PnIoCm_Block_ArReq( ProfinetDriverContext.BLOCK_VERSION_HIGH, ProfinetDriverContext.BLOCK_VERSION_LOW, PnIoCm_ArType.IO_CONTROLLER, - driverContext.generateUuid(), - driverContext.getSessionKey(), + profinetDriverContext.generateUuid(), + profinetDriverContext.getSessionKey(), localMacAddress, - driverContext.getCmInitiatorObjectUuid(), + profinetDriverContext.getCmInitiatorObjectUuid(), false, - driverContext.isNonLegacyStartupMode(), + profinetDriverContext.isNonLegacyStartupMode(), false, false, PnIoCm_CompanionArType.SINGLE_AR, @@ -506,14 +506,14 @@ public CompletableFuture subscribe(PlcSubscriptionReque false, PnIoCm_RtClass.RT_CLASS_2, ProfinetDriverContext.DEFAULT_IO_DATA_SIZE, - driverContext.getAndIncrementIdentification(), - driverContext.getSendClockFactor(), - driverContext.getReductionRatio(), + profinetDriverContext.getAndIncrementIdentification(), + profinetDriverContext.getSendClockFactor(), + profinetDriverContext.getReductionRatio(), 1, 0, 0xffffffffL, - driverContext.getWatchdogFactor(), - driverContext.getDataHoldFactor(), + profinetDriverContext.getWatchdogFactor(), + profinetDriverContext.getDataHoldFactor(), 0xC000, ProfinetDriverContext.DEFAULT_EMPTY_MAC_ADDRESS, Collections.singletonList( @@ -533,14 +533,14 @@ public CompletableFuture subscribe(PlcSubscriptionReque false, PnIoCm_RtClass.RT_CLASS_2, ProfinetDriverContext.DEFAULT_IO_DATA_SIZE, - driverContext.getAndIncrementIdentification(), - driverContext.getSendClockFactor(), - driverContext.getReductionRatio(), + profinetDriverContext.getAndIncrementIdentification(), + profinetDriverContext.getSendClockFactor(), + profinetDriverContext.getReductionRatio(), 1, 0, 0xffffffffL, - driverContext.getWatchdogFactor(), - driverContext.getDataHoldFactor(), + profinetDriverContext.getWatchdogFactor(), + profinetDriverContext.getDataHoldFactor(), 0xC000, ProfinetDriverContext.DEFAULT_EMPTY_MAC_ADDRESS, Collections.singletonList( @@ -567,9 +567,9 @@ public CompletableFuture subscribe(PlcSubscriptionReque DceRpc_PacketType.WORKING, false, false, false, IntegerEncoding.BIG_ENDIAN, CharacterEncoding.ASCII, FloatingPointEncoding.IEEE, - new DceRpc_ObjectUuid((byte) 0x00, (short) 0x0001, Integer.decode("0x" + driverContext.getDeviceId()), Integer.decode("0x" + driverContext.getVendorId())), + new DceRpc_ObjectUuid((byte) 0x00, (short) 0x0001, Integer.decode("0x" + profinetDriverContext.getDeviceId()), Integer.decode("0x" + profinetDriverContext.getVendorId())), new DceRpc_InterfaceUuid_DeviceInterface(), - driverContext.getActivityUuid(), + profinetDriverContext.getActivityUuid(), 0L, 0L, DceRpc_Operation.CONNECT, (short) 0, @@ -584,8 +584,8 @@ public CompletableFuture subscribe(PlcSubscriptionReque (short) 64, new IpAddress(localAddress.getAddress().getAddress()), new IpAddress(remoteAddress.getAddress().getAddress()), - driverContext.getLocalPort(), - driverContext.getRemotePortImplicitCommunication(), + profinetDriverContext.getLocalPort(), + profinetDriverContext.getRemotePortImplicitCommunication(), packet ); Ethernet_Frame ethernetFrame = new Ethernet_Frame( @@ -607,13 +607,13 @@ protected void extractBlockInfo(List blocks) { if (blockMap.containsKey(ProfinetDiscoverer.DEVICE_TYPE_NAME)) { PnDcp_Block_DevicePropertiesDeviceVendor block = (PnDcp_Block_DevicePropertiesDeviceVendor) blockMap.get(ProfinetDiscoverer.DEVICE_TYPE_NAME); - driverContext.setDeviceType(new String(block.getDeviceVendorValue())); + profinetDriverContext.setDeviceType(new String(block.getDeviceVendorValue())); } if (blockMap.containsKey(ProfinetDiscoverer.DEVICE_NAME_OF_STATION)) { PnDcp_Block_DevicePropertiesNameOfStation block = (PnDcp_Block_DevicePropertiesNameOfStation) blockMap.get(ProfinetDiscoverer.DEVICE_NAME_OF_STATION); - driverContext.setDeviceName(new String(block.getNameOfStation())); + profinetDriverContext.setDeviceName(new String(block.getNameOfStation())); } if (blockMap.containsKey(ProfinetDiscoverer.DEVICE_ROLE)) { @@ -632,14 +632,14 @@ protected void extractBlockInfo(List blocks) { if (block.getPnioDevice()) { roles.add("DEVICE"); } - driverContext.setRoles(roles); + profinetDriverContext.setRoles(roles); } if (blockMap.containsKey(ProfinetDiscoverer.DEVICE_ID)) { PnDcp_Block_DevicePropertiesDeviceId block = (PnDcp_Block_DevicePropertiesDeviceId) blockMap.get(ProfinetDiscoverer.DEVICE_ID); - driverContext.setVendorId(block.getVendorId()); - driverContext.setDeviceId(block.getDeviceId()); + profinetDriverContext.setVendorId(block.getVendorId()); + profinetDriverContext.setDeviceId(block.getDeviceId()); } } diff --git a/plc4j/drivers/profinet/src/main/java/org/apache/plc4x/java/profinet/protocol/ProfinetProtocolLogic.java b/plc4j/drivers/profinet/src/main/java/org/apache/plc4x/java/profinet/protocol/ProfinetProtocolLogic.java index 2ebcbee4534..95beb4f774e 100644 --- a/plc4j/drivers/profinet/src/main/java/org/apache/plc4x/java/profinet/protocol/ProfinetProtocolLogic.java +++ b/plc4j/drivers/profinet/src/main/java/org/apache/plc4x/java/profinet/protocol/ProfinetProtocolLogic.java @@ -53,7 +53,7 @@ public class ProfinetProtocolLogic extends Plc4xProtocolBase imp private final Logger LOGGER = LoggerFactory.getLogger(ProfinetProtocolLogic.class); - private ProfinetDriverContext driverContext; + private ProfinetDriverContext profinetDriverContext; private Map devices = new HashMap<>(); public ProfinetProtocolLogic() { @@ -63,12 +63,12 @@ public ProfinetProtocolLogic() { public void setDriverContext(ProfinetDriverContext driverContext) { super.setDriverContext(driverContext); - this.driverContext = driverContext; + this.profinetDriverContext = driverContext; } @Override public void setConfiguration(ProfinetConfiguration configuration) { - driverContext.setConfiguration(configuration); + profinetDriverContext.setConfiguration(configuration); Map configuredDevices = configuration.getDevices().getConfiguredDevices(); @@ -85,7 +85,7 @@ public void setConfiguration(ProfinetConfiguration configuration) { devices.get(entry.getValue().getDevicename()).setIpAddress(entry.getValue().getIpaddress()); } - driverContext.setHandler(new ProfinetDeviceMessageHandler(devices)); + profinetDriverContext.setHandler(new ProfinetDeviceMessageHandler(devices)); for (Map.Entry device : devices.entrySet()) { device.getValue().getDeviceContext().setConfiguration(configuration); } @@ -97,15 +97,15 @@ public void setContext(ConversationContext context) { // Open the receiving UDP port and keep it open. try { - driverContext.setSocket(new DatagramSocket(ProfinetDriverContext.DEFAULT_UDP_PORT)); + profinetDriverContext.setSocket(new DatagramSocket(ProfinetDriverContext.DEFAULT_UDP_PORT)); } catch (SocketException e) { throw new RuntimeException(e); } - driverContext.getHandler().setConfiguredDevices(devices); + profinetDriverContext.getHandler().setConfiguredDevices(devices); for (Map.Entry device : devices.entrySet()) { - device.getValue().setContext(context, this.driverContext.getChannel()); + device.getValue().setContext(context, this.profinetDriverContext.getChannel()); } } @@ -118,10 +118,10 @@ public void setContext(ConversationContext context) { * @throws PlcConnectionException */ private void onDeviceDiscovery() throws InterruptedException, PlcConnectionException { - ProfinetPlcDiscoverer discoverer = new ProfinetPlcDiscoverer(driverContext.getChannel()); - driverContext.getChannel().setDiscoverer(discoverer); + ProfinetPlcDiscoverer discoverer = new ProfinetPlcDiscoverer(profinetDriverContext.getChannel()); + profinetDriverContext.getChannel().setDiscoverer(discoverer); DefaultPlcDiscoveryRequest request = new DefaultPlcDiscoveryRequest(discoverer, new LinkedHashMap<>()); - discoverer.ongoingDiscoverWithHandler(request, driverContext.getHandler(), 5000L, 30000L); + discoverer.ongoingDiscoverWithHandler(request, profinetDriverContext.getHandler(), 5000L, 30000L); waitForDeviceDiscovery(); } @@ -186,13 +186,13 @@ public void onConnect(ConversationContext context) { String localAddress = channel.getLocalAddress().toString().substring(1).split(":")[0]; localIpAddress = InetAddress.getByName(localAddress); PcapNetworkInterface devByAddress = Pcaps.getDevByAddress(localIpAddress); - driverContext.setChannel(new ProfinetChannel(Collections.singletonList(devByAddress), devices)); - driverContext.getChannel().setConfiguredDevices(devices); + profinetDriverContext.setChannel(new ProfinetChannel(Collections.singletonList(devByAddress), devices)); + profinetDriverContext.getChannel().setConfiguredDevices(devices); // Set both the network-interface and the channel for this device // TODO: Find out what they are needed for ... for (Map.Entry entry : devices.entrySet()) { entry.getValue().getDeviceContext().setNetworkInterface(new ProfinetNetworkInterface(devByAddress)); - entry.getValue().getDeviceContext().setChannel(driverContext.getChannel()); + entry.getValue().getDeviceContext().setChannel(profinetDriverContext.getChannel()); } } catch (PcapNativeException | UnknownHostException e) { throw new RuntimeException(e); diff --git a/plc4j/drivers/s7/src/main/java/org/apache/plc4x/java/s7/readwrite/protocol/S7ProtocolEventLogic.java b/plc4j/drivers/s7/src/main/java/org/apache/plc4x/java/s7/readwrite/protocol/S7ProtocolEventLogic.java index ac36d0651c4..eb6939432ed 100644 --- a/plc4j/drivers/s7/src/main/java/org/apache/plc4x/java/s7/readwrite/protocol/S7ProtocolEventLogic.java +++ b/plc4j/drivers/s7/src/main/java/org/apache/plc4x/java/s7/readwrite/protocol/S7ProtocolEventLogic.java @@ -42,7 +42,6 @@ public class S7ProtocolEventLogic implements PlcSubscriber { private final org.slf4j.Logger logger = LoggerFactory.getLogger(S7ProtocolEventLogic.class); - private final BlockingQueue eventQueue; private final BlockingQueue dispachQueue = new ArrayBlockingQueue<>(1024); @@ -133,7 +132,7 @@ public void run() { dispatchQueue.add(modeEvent); } else if (obj instanceof S7PayloadDiagnosticMessage) { S7PayloadDiagnosticMessage msg = (S7PayloadDiagnosticMessage) obj; - if ((msg.getEventId() >= 0x0A000) & (msg.getEventId() <= 0x0BFFF)) { + if ((msg.getEventId() >= 0x0A000) && (msg.getEventId() <= 0x0BFFF)) { S7UserEvent userEvent = new S7UserEvent(msg); dispatchQueue.add(userEvent); } else { diff --git a/plc4j/drivers/s7/src/main/java/org/apache/plc4x/java/s7/readwrite/tag/S7SzlTag.java b/plc4j/drivers/s7/src/main/java/org/apache/plc4x/java/s7/readwrite/tag/S7SzlTag.java index 26a9ffd3a00..002b9ad574e 100644 --- a/plc4j/drivers/s7/src/main/java/org/apache/plc4x/java/s7/readwrite/tag/S7SzlTag.java +++ b/plc4j/drivers/s7/src/main/java/org/apache/plc4x/java/s7/readwrite/tag/S7SzlTag.java @@ -33,8 +33,8 @@ public class S7SzlTag implements PlcTag { private static final Pattern SSL_ADDRESS_PATTERN = Pattern.compile("^SZL_ID=(?16#[0-9a-fA-F]{4});INDEX=(?16#[0-9a-fA-F]{4})"); - private static final String SZL_ID = "szlId"; - private static final String INDEX = "index"; + private static final String GROUP_NAME_SZL_ID = "szlId"; + private static final String GROUP_NAME_INDEX = "index"; private final int szlId; private final int index; @@ -74,8 +74,8 @@ public static boolean matches(String tagString) { public static S7SzlTag of(String tagString) { Matcher matcher = SSL_ADDRESS_PATTERN.matcher(tagString); if (matcher.matches()){ - String strSxlId = matcher.group(SZL_ID); - String strIndex = matcher.group(INDEX); + String strSxlId = matcher.group(GROUP_NAME_SZL_ID); + String strIndex = matcher.group(GROUP_NAME_INDEX); strSxlId = strSxlId.replaceAll("16#", ""); strIndex = strIndex.replaceAll("16#", ""); return new S7SzlTag(Integer.parseInt(strSxlId, 16),Integer.parseInt(strIndex, 16)); diff --git a/plc4j/integrations/apache-kafka/src/main/java/org/apache/plc4x/kafka/Plc4xSinkTask.java b/plc4j/integrations/apache-kafka/src/main/java/org/apache/plc4x/kafka/Plc4xSinkTask.java index 728913606d4..55da47c41b6 100644 --- a/plc4j/integrations/apache-kafka/src/main/java/org/apache/plc4x/kafka/Plc4xSinkTask.java +++ b/plc4j/integrations/apache-kafka/src/main/java/org/apache/plc4x/kafka/Plc4xSinkTask.java @@ -206,7 +206,7 @@ public void put(Collection records) { log.debug("Ignoring write request received on wrong topic"); } else if (!tags.containsKey(tagName)) { log.warn("Unable to find address for tag " + tagName); - } else if ((System.currentTimeMillis() > expires) & !(expires == 0)) { + } else if ((System.currentTimeMillis() > expires) && !(expires == 0)) { log.warn("Write request has expired {} - {}, discarding {}", expires, System.currentTimeMillis(), tagName); } else { String address = tags.get(tagName); diff --git a/plc4j/integrations/apache-nifi/nifi-plc4x-processors/src/main/java/org/apache/plc4x/nifi/record/RecordPlc4xWriter.java b/plc4j/integrations/apache-nifi/nifi-plc4x-processors/src/main/java/org/apache/plc4x/nifi/record/RecordPlc4xWriter.java index c8948ae2394..ca8f0267cd1 100644 --- a/plc4j/integrations/apache-nifi/nifi-plc4x-processors/src/main/java/org/apache/plc4x/nifi/record/RecordPlc4xWriter.java +++ b/plc4j/integrations/apache-nifi/nifi-plc4x-processors/src/main/java/org/apache/plc4x/nifi/record/RecordPlc4xWriter.java @@ -39,28 +39,28 @@ public class RecordPlc4xWriter implements Plc4xWriter { - private final RecordSetWriterFactory recordSetWriterFactory; - private final AtomicReference writeResultRef; - private final Map originalAttributes; + private final RecordSetWriterFactory recordSetWriterFactory; + private final AtomicReference writeResultRef; + private final Map originalAttributes; private String mimeType; - - private RecordSet fullRecordSet; - private RecordSchema writeSchema; - - - public RecordPlc4xWriter(RecordSetWriterFactory recordSetWriterFactory, Map originalAttributes) { - this.recordSetWriterFactory = recordSetWriterFactory; + + private RecordSet fullRecordSet; + private RecordSchema writeSchema; + + + public RecordPlc4xWriter(RecordSetWriterFactory recordSetWriterFactory, Map originalAttributes) { + this.recordSetWriterFactory = recordSetWriterFactory; this.writeResultRef = new AtomicReference<>(); this.originalAttributes = originalAttributes; - } + } - @Override - public long writePlcReadResponse(PlcReadResponse response, OutputStream outputStream, ComponentLog logger, Plc4xReadResponseRowCallback callback, RecordSchema recordSchema) throws Exception { - if (fullRecordSet == null) { + @Override + public long writePlcReadResponse(PlcReadResponse response, OutputStream outputStream, ComponentLog logger, Plc4xReadResponseRowCallback callback, RecordSchema recordSchema) throws Exception { + if (fullRecordSet == null) { fullRecordSet = new Plc4xReadResponseRecordSetWithCallback(response, callback, recordSchema); writeSchema = recordSetWriterFactory.getSchema(originalAttributes, fullRecordSet.getSchema()); } - Map empty = new HashMap<>(); + Map empty = new HashMap<>(); try (final RecordSetWriter resultSetWriter = recordSetWriterFactory.createWriter(logger, writeSchema, outputStream, empty)) { writeResultRef.set(resultSetWriter.write(fullRecordSet)); if (mimeType == null) { @@ -70,64 +70,69 @@ public long writePlcReadResponse(PlcReadResponse response, OutputStream outputSt } catch (final Exception e) { throw new IOException(e); } - } - - @Override - public long writePlcReadResponse(PlcReadResponse response, OutputStream outputStream, ComponentLog logger, Plc4xReadResponseRowCallback callback, RecordSchema recordSchema, FlowFile originalFlowFile) throws Exception { - if (fullRecordSet == null) { + } + + @Override + public long writePlcReadResponse(PlcReadResponse response, OutputStream outputStream, ComponentLog logger, Plc4xReadResponseRowCallback callback, RecordSchema recordSchema, FlowFile originalFlowFile) throws Exception { + if (fullRecordSet == null) { fullRecordSet = new Plc4xReadResponseRecordSetWithCallback(response, callback, recordSchema); writeSchema = recordSetWriterFactory.getSchema(originalAttributes, fullRecordSet.getSchema()); } - final RecordSetWriter resultSetWriter; - if (originalFlowFile != null){ - try { - resultSetWriter = recordSetWriterFactory.createWriter(logger, writeSchema, outputStream, originalFlowFile); - } catch (final Exception e) { - throw new IOException(e); + RecordSetWriter resultSetWriter = null; + try { + if (originalFlowFile != null) { + try { + resultSetWriter = recordSetWriterFactory.createWriter(logger, writeSchema, outputStream, originalFlowFile); + } catch (final Exception e) { + throw new IOException(e); + } + } else { + resultSetWriter = recordSetWriterFactory.createWriter(logger, writeSchema, outputStream, Collections.emptyMap()); + } + + writeResultRef.set(resultSetWriter.write(fullRecordSet)); + if (mimeType == null) { + mimeType = resultSetWriter.getMimeType(); + } + return writeResultRef.get().getRecordCount(); + } finally { + if (resultSetWriter != null) { + resultSetWriter.close(); } - } else { - resultSetWriter = recordSetWriterFactory.createWriter(logger, writeSchema, outputStream, Collections.emptyMap()); - } - - - writeResultRef.set(resultSetWriter.write(fullRecordSet)); - if (mimeType == null) { - mimeType = resultSetWriter.getMimeType(); } - return writeResultRef.get().getRecordCount(); - } - - - @Override - public void writeEmptyPlcReadResponse(OutputStream outputStream, ComponentLog logger) throws IOException { - Map empty = new HashMap<>(); - try (final RecordSetWriter resultSetWriter = recordSetWriterFactory.createWriter(logger, writeSchema, outputStream, empty)) { + } + + + @Override + public void writeEmptyPlcReadResponse(OutputStream outputStream, ComponentLog logger) throws IOException { + Map empty = new HashMap<>(); + try (final RecordSetWriter resultSetWriter = recordSetWriterFactory.createWriter(logger, writeSchema, outputStream, empty)) { mimeType = resultSetWriter.getMimeType(); resultSetWriter.beginRecordSet(); resultSetWriter.finishRecordSet(); } catch (final Exception e) { throw new IOException(e); } - } - - @Override - public void writeEmptyPlcReadResponse(OutputStream outputStream, ComponentLog logger, FlowFile originalFlowFile) throws IOException { - try (final RecordSetWriter resultSetWriter = recordSetWriterFactory.createWriter(logger, writeSchema, outputStream, originalFlowFile)) { + } + + @Override + public void writeEmptyPlcReadResponse(OutputStream outputStream, ComponentLog logger, FlowFile originalFlowFile) throws IOException { + try (final RecordSetWriter resultSetWriter = recordSetWriterFactory.createWriter(logger, writeSchema, outputStream, originalFlowFile)) { mimeType = resultSetWriter.getMimeType(); resultSetWriter.beginRecordSet(); resultSetWriter.finishRecordSet(); } catch (final Exception e) { throw new IOException(e); } - } - - @Override - public String getMimeType() { - return mimeType; - } - - @Override + } + + @Override + public String getMimeType() { + return mimeType; + } + + @Override public Map getAttributesToAdd() { Map attributesToAdd = new HashMap<>(); attributesToAdd.put(CoreAttributes.MIME_TYPE.key(), mimeType); @@ -142,40 +147,42 @@ public Map getAttributesToAdd() { return attributesToAdd; } - @Override + @Override public void updateCounters(ProcessSession session) { final WriteResult result = writeResultRef.get(); if (result != null) { session.adjustCounter("Records Written", result.getRecordCount(), false); } } - - private static class Plc4xReadResponseRecordSetWithCallback extends Plc4xReadResponseRecordSet { + + private static class Plc4xReadResponseRecordSetWithCallback extends Plc4xReadResponseRecordSet { private final Plc4xReadResponseRowCallback callback; + public Plc4xReadResponseRecordSetWithCallback(final PlcReadResponse readResponse, Plc4xReadResponseRowCallback callback, RecordSchema recordSchema) throws IOException { super(readResponse, recordSchema); this.callback = callback; } + @Override public Record next() throws IOException { - if (hasMoreRows()) { - PlcReadResponse response = getReadResponse(); - final Record record = createRecord(response); - setMoreRows(false); - if (callback != null) { - callback.processRow(response); - } - return record; - } else { - return null; + if (hasMoreRows()) { + PlcReadResponse response = getReadResponse(); + final Record record = createRecord(response); + setMoreRows(false); + if (callback != null) { + callback.processRow(response); } + return record; + } else { + return null; + } } - } + } - public RecordSchema getRecordSchema(){ + public RecordSchema getRecordSchema() { try { return this.fullRecordSet.getSchema(); - } catch (IOException e){ + } catch (IOException e) { return null; } } diff --git a/plc4j/spi/src/main/java/org/apache/plc4x/java/spi/values/PlcBINT.java b/plc4j/spi/src/main/java/org/apache/plc4x/java/spi/values/PlcBINT.java index 7592fb9521e..d4aba0d3719 100644 --- a/plc4j/spi/src/main/java/org/apache/plc4x/java/spi/values/PlcBINT.java +++ b/plc4j/spi/src/main/java/org/apache/plc4x/java/spi/values/PlcBINT.java @@ -57,22 +57,22 @@ public PlcBINT(Boolean value) { } public PlcBINT(Byte value) { - this.value = BigInteger.valueOf(value);; + this.value = BigInteger.valueOf(value); this.isNullable = false; } public PlcBINT(Short value) { - this.value = BigInteger.valueOf(value);; + this.value = BigInteger.valueOf(value); this.isNullable = false; } public PlcBINT(Integer value) { - this.value = BigInteger.valueOf(value);; + this.value = BigInteger.valueOf(value); this.isNullable = false; } public PlcBINT(Long value) { - this.value = BigInteger.valueOf(value);; + this.value = BigInteger.valueOf(value); this.isNullable = false; } @@ -97,7 +97,7 @@ public PlcBINT(BigDecimal value) { } public PlcBINT(String value) { - this.value = new BigInteger(value.trim());; + this.value = new BigInteger(value.trim()); this.isNullable = false; } diff --git a/plc4j/spi/src/main/java/org/apache/plc4x/java/spi/values/PlcBREAL.java b/plc4j/spi/src/main/java/org/apache/plc4x/java/spi/values/PlcBREAL.java index 8fd5aac9886..74b7e3d0928 100644 --- a/plc4j/spi/src/main/java/org/apache/plc4x/java/spi/values/PlcBREAL.java +++ b/plc4j/spi/src/main/java/org/apache/plc4x/java/spi/values/PlcBREAL.java @@ -57,22 +57,22 @@ public PlcBREAL(Boolean value) { } public PlcBREAL(Byte value) { - this.value = BigDecimal.valueOf(value);; + this.value = BigDecimal.valueOf(value); this.isNullable = false; } public PlcBREAL(Short value) { - this.value = BigDecimal.valueOf(value);; + this.value = BigDecimal.valueOf(value); this.isNullable = false; } public PlcBREAL(Integer value) { - this.value = BigDecimal.valueOf(value);; + this.value = BigDecimal.valueOf(value); this.isNullable = false; } public PlcBREAL(Long value) { - this.value = BigDecimal.valueOf(value);; + this.value = BigDecimal.valueOf(value); this.isNullable = false; } @@ -97,7 +97,7 @@ public PlcBREAL(BigDecimal value) { } public PlcBREAL(String value) { - this.value = new BigDecimal(value.trim());; + this.value = new BigDecimal(value.trim()); this.isNullable = false; } diff --git a/plc4j/transports/serial/src/main/java/org/apache/plc4x/java/transport/serial/SerialChannel.java b/plc4j/transports/serial/src/main/java/org/apache/plc4x/java/transport/serial/SerialChannel.java index e29e28a2805..51586ba3143 100644 --- a/plc4j/transports/serial/src/main/java/org/apache/plc4x/java/transport/serial/SerialChannel.java +++ b/plc4j/transports/serial/src/main/java/org/apache/plc4x/java/transport/serial/SerialChannel.java @@ -47,10 +47,10 @@ public class SerialChannel extends AbstractNioByteChannel implements DuplexChann private final SerialChannelConfig config; private final VoidChannelPromise unsafeVoidPromise = new VoidChannelPromise(this, false); - private boolean readPending = false; // Did we receive an EOF? + private boolean serialReadPending = false; // Did we receive an EOF? private SocketAddress remoteAddress; private boolean active = false; - private SerialSelectionKey selectionKey; + private SerialSelectionKey serialSelectionKey; private SerialChannelHandler comPort; private final DefaultChannelPipeline pipeline; // Copied from AbstractChannel @@ -165,7 +165,7 @@ protected boolean doConnect(SocketAddress remoteAddress, SocketAddress localAddr logger.debug("Using Com Port {}, trying to open port", comPort.getIdentifier()); if (comPort.open()) { logger.debug("Opened port successful to {}", comPort.getIdentifier()); - comPort.registerSelectionKey(selectionKey); + comPort.registerSelectionKey(serialSelectionKey); this.active = true; return true; @@ -275,13 +275,13 @@ public void read() { close = allocHandle.lastBytesRead() < 0; if (close) { // There is nothing left to read as we received an EOF. - readPending = false; + serialReadPending = false; } break; } allocHandle.incMessagesRead(1); - readPending = false; + serialReadPending = false; pipeline.fireChannelRead(byteBuf); } while (allocHandle.continueReading()); @@ -297,13 +297,13 @@ public void read() { // handleReadException(pipeline, byteBuf, t, close, allocHandle); t.printStackTrace(); } finally { - // Check if there is a readPending which was not processed yet. + // Check if there is a serialReadPending which was not processed yet. // This could be for two reasons: // * The user called Channel.read() or ChannelHandlerContext.read() in channelRead(...) method // * The user called Channel.read() or ChannelHandlerContext.read() in channelReadComplete(...) method // // See https://github.com/netty/netty/issues/2254 - if (!readPending && !config.isAutoRead()) { + if (!serialReadPending && !config.isAutoRead()) { // TODO } } @@ -349,12 +349,12 @@ public void register(EventLoop eventLoop, ChannelPromise promise) { SerialPollingSelector selector = (SerialPollingSelector) method.invoke(eventLoop); // Register the channel - selectionKey = (SerialSelectionKey) ((SerialChannel) promise.channel()).javaChannel().register(selector, 0, SerialChannel.this); + serialSelectionKey = (SerialSelectionKey) ((SerialChannel) promise.channel()).javaChannel().register(selector, 0, SerialChannel.this); // Set selection key final Field selectionKeyField = AbstractNioChannel.class.getDeclaredField("selectionKey"); selectionKeyField.setAccessible(true); - selectionKeyField.set(SerialChannel.this, selectionKey); + selectionKeyField.set(SerialChannel.this, serialSelectionKey); // Set event loop (again, via reflection) final Field loop = AbstractChannel.class.getDeclaredField("eventLoop"); diff --git a/plc4j/utils/raw-sockets/src/main/java/org/apache/plc4x/java/utils/rawsockets/netty/utils/ArpUtils.java b/plc4j/utils/raw-sockets/src/main/java/org/apache/plc4x/java/utils/rawsockets/netty/utils/ArpUtils.java index 9c01d0cb76a..c19d56e0a87 100644 --- a/plc4j/utils/raw-sockets/src/main/java/org/apache/plc4x/java/utils/rawsockets/netty/utils/ArpUtils.java +++ b/plc4j/utils/raw-sockets/src/main/java/org/apache/plc4x/java/utils/rawsockets/netty/utils/ArpUtils.java @@ -103,15 +103,18 @@ public static Set scanNetworkDevice(PcapNetworkInterface nif) { } final MacAddress localMacAddress = first.get(); - // This handle will be used for receiving response packets. - PcapHandle receivingHandle = nif.openLive( - 65535, PcapNetworkInterface.PromiscuousMode.PROMISCUOUS, 100); - // This handle will be used for sending the request packet. - PcapHandle sendingHandle = nif.openLive( - 65535, PcapNetworkInterface.PromiscuousMode.PROMISCUOUS, 100); - // The executor, that handles processing the incoming packets. - ExecutorService arpExecutor = Executors.newSingleThreadExecutor(); + PcapHandle receivingHandle = null; + PcapHandle sendingHandle = null; + ExecutorService arpExecutor = null; try { + // This handle will be used for receiving response packets. + receivingHandle = nif.openLive( + 65535, PcapNetworkInterface.PromiscuousMode.PROMISCUOUS, 100); + // This handle will be used for sending the request packet. + sendingHandle = nif.openLive( + 65535, PcapNetworkInterface.PromiscuousMode.PROMISCUOUS, 100); + // The executor, that handles processing the incoming packets. + arpExecutor = Executors.newSingleThreadExecutor(); StringBuilder sb = new StringBuilder("arp"); sb.append(" and ether dst ").append(Pcaps.toBpfString(localMacAddress)).append(" and ("); boolean firstAddress = true; @@ -140,10 +143,11 @@ public static Set scanNetworkDevice(PcapNetworkInterface nif) { // The resolution task actually runs in one of the // arpExecutor pools threads and just makes sure the // incoming packet is passed to the listener. + final PcapHandle finalReceivingHandle = receivingHandle; Runnable resolutionTask = () -> { try { - while (receivingHandle.isOpen()) { - final Packet nextPacket = receivingHandle.getNextPacket(); + while (finalReceivingHandle.isOpen()) { + final Packet nextPacket = finalReceivingHandle.getNextPacket(); if (nextPacket != null) { listener.gotPacket(nextPacket); } @@ -193,13 +197,13 @@ public static Set scanNetworkDevice(PcapNetworkInterface nif) { logger.error("error", e); } finally { // Gracefully shut down. - if (receivingHandle.isOpen()) { + if ((receivingHandle != null) && receivingHandle.isOpen()) { receivingHandle.close(); } - if (sendingHandle.isOpen()) { + if ((sendingHandle != null) && sendingHandle.isOpen()) { sendingHandle.close(); } - if (!arpExecutor.isShutdown()) { + if ((arpExecutor != null) && !arpExecutor.isShutdown()) { arpExecutor.shutdown(); } } @@ -214,103 +218,106 @@ public static Set scanNetworkDevice(PcapNetworkInterface nif) { /** * Used to get the mac address for a given IP address. * - * @param nif network device - * @param remoteAddress remote ip address that we want to get the mac address for - * @param localAddress local ip address of the device asking the question + * @param nif network device + * @param remoteAddress remote ip address that we want to get the mac address for + * @param localAddress local ip address of the device asking the question * @param localMacAddress local mac address of the device asking the question * @return optional that possibly contains the mac address we were looking for. */ public static Optional resolveMacAddress(PcapNetworkInterface nif, InetSocketAddress remoteAddress, InetSocketAddress localAddress, MacAddress localMacAddress) { + PcapHandle receivingHandle = null; + PcapHandle sendingHandle = null; + ExecutorService arpExecutor = null; try { // This handle will be used for receiving response packets. - PcapHandle receivingHandle = nif.openLive( + receivingHandle = nif.openLive( 65535, PcapNetworkInterface.PromiscuousMode.PROMISCUOUS, 100); // This handle will be used for sending the request packet. - PcapHandle sendingHandle = nif.openLive( + sendingHandle = nif.openLive( 65535, PcapNetworkInterface.PromiscuousMode.PROMISCUOUS, 100); // The executor, that handles processing the incoming packets. - ExecutorService arpExecutor = Executors.newSingleThreadExecutor(); + arpExecutor = Executors.newSingleThreadExecutor(); CompletableFuture remoteMacAddressFuture = new CompletableFuture<>(); - try { - // Try to limit the number of processed incoming packets to the minimum. - // So far we know the source host ip as well as the target ip and mac address. - receivingHandle.setFilter( - String.format("arp and src host %s and dst host %s and ether dst %s", - Pcaps.toBpfString(remoteAddress.getAddress()), Pcaps.toBpfString(localAddress.getAddress()), - Pcaps.toBpfString(localMacAddress)), - BpfProgram.BpfCompileMode.OPTIMIZE); - // Register the listener, which will be processing all packets that pass - // the filter (Should actually only be one) - PacketListener listener = - packet -> { - if (packet.contains(ArpPacket.class)) { - ArpPacket arp = packet.get(ArpPacket.class); - if (arp.getHeader().getOperation().equals(ArpOperation.REPLY)) { - remoteMacAddressFuture.complete(arp.getHeader().getSrcHardwareAddr()); - } - } - }; + // Try to limit the number of processed incoming packets to the minimum. + // So far we know the source host ip as well as the target ip and mac address. + receivingHandle.setFilter( + String.format("arp and src host %s and dst host %s and ether dst %s", + Pcaps.toBpfString(remoteAddress.getAddress()), Pcaps.toBpfString(localAddress.getAddress()), + Pcaps.toBpfString(localMacAddress)), + BpfProgram.BpfCompileMode.OPTIMIZE); - // The resolution task actually runs in one of the - // arpExecutor pools threads and just makes sure the - // incoming packet is passed to the listener. - Runnable resolutionTask = () -> { - try { - receivingHandle.loop(1, listener); - } catch (InterruptedException e) { - Thread.currentThread().interrupt(); - } catch (PcapNativeException | NotOpenException e) { - remoteMacAddressFuture.completeExceptionally(e); + // Register the listener, which will be processing all packets that pass + // the filter (Should actually only be one) + PacketListener listener = + packet -> { + if (packet.contains(ArpPacket.class)) { + ArpPacket arp = packet.get(ArpPacket.class); + if (arp.getHeader().getOperation().equals(ArpOperation.REPLY)) { + remoteMacAddressFuture.complete(arp.getHeader().getSrcHardwareAddr()); + } } }; - arpExecutor.execute(resolutionTask); - - // Actually assemble the ARP packet. - ArpPacket.Builder arpBuilder = new ArpPacket.Builder(); - arpBuilder.hardwareType(ArpHardwareType.ETHERNET) - .protocolType(EtherType.IPV4) - .hardwareAddrLength((byte) MacAddress.SIZE_IN_BYTES) - .protocolAddrLength((byte) ByteArrays.INET4_ADDRESS_SIZE_IN_BYTES) - .operation(ArpOperation.REQUEST) - .srcHardwareAddr(localMacAddress) - .srcProtocolAddr(localAddress.getAddress()) - .dstHardwareAddr(MacAddress.ETHER_BROADCAST_ADDRESS) - .dstProtocolAddr(remoteAddress.getAddress()); - EthernetPacket.Builder etherBuilder = new EthernetPacket.Builder(); - etherBuilder - .dstAddr(MacAddress.ETHER_BROADCAST_ADDRESS) - .srcAddr(localMacAddress) - .type(EtherType.ARP) - .payloadBuilder(arpBuilder) - .paddingAtBuild(true); - Packet arpRequestPacket = etherBuilder.build(); - // Send the arp lookup packet. - sendingHandle.sendPacket(arpRequestPacket); - - // Wait for the future to complete (It's completed in the packet listener). + // The resolution task actually runs in one of the + // arpExecutor pools threads and just makes sure the + // incoming packet is passed to the listener. + final PcapHandle finalReceivingHandle = receivingHandle; + Runnable resolutionTask = () -> { try { - return Optional.of(remoteMacAddressFuture.get(1000, TimeUnit.MILLISECONDS)); + finalReceivingHandle.loop(1, listener); } catch (InterruptedException e) { Thread.currentThread().interrupt(); - } catch (ExecutionException | TimeoutException e) { - return Optional.empty(); - } - } finally { - // Gracefully shut down. - if (receivingHandle.isOpen()) { - receivingHandle.close(); - } - if (sendingHandle.isOpen()) { - sendingHandle.close(); - } - if (!arpExecutor.isShutdown()) { - arpExecutor.shutdown(); + } catch (PcapNativeException | NotOpenException e) { + remoteMacAddressFuture.completeExceptionally(e); } + }; + arpExecutor.execute(resolutionTask); + + // Actually assemble the ARP packet. + ArpPacket.Builder arpBuilder = new ArpPacket.Builder(); + arpBuilder.hardwareType(ArpHardwareType.ETHERNET) + .protocolType(EtherType.IPV4) + .hardwareAddrLength((byte) MacAddress.SIZE_IN_BYTES) + .protocolAddrLength((byte) ByteArrays.INET4_ADDRESS_SIZE_IN_BYTES) + .operation(ArpOperation.REQUEST) + .srcHardwareAddr(localMacAddress) + .srcProtocolAddr(localAddress.getAddress()) + .dstHardwareAddr(MacAddress.ETHER_BROADCAST_ADDRESS) + .dstProtocolAddr(remoteAddress.getAddress()); + EthernetPacket.Builder etherBuilder = new EthernetPacket.Builder(); + etherBuilder + .dstAddr(MacAddress.ETHER_BROADCAST_ADDRESS) + .srcAddr(localMacAddress) + .type(EtherType.ARP) + .payloadBuilder(arpBuilder) + .paddingAtBuild(true); + Packet arpRequestPacket = etherBuilder.build(); + + // Send the arp lookup packet. + sendingHandle.sendPacket(arpRequestPacket); + + // Wait for the future to complete (It's completed in the packet listener). + try { + return Optional.of(remoteMacAddressFuture.get(1000, TimeUnit.MILLISECONDS)); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } catch (ExecutionException | TimeoutException e) { + return Optional.empty(); } } catch (NotOpenException | PcapNativeException e) { return Optional.empty(); + } finally { + // Gracefully shut down. + if ((receivingHandle != null) && receivingHandle.isOpen()) { + receivingHandle.close(); + } + if ((sendingHandle != null) && sendingHandle.isOpen()) { + sendingHandle.close(); + } + if ((arpExecutor != null) && !arpExecutor.isShutdown()) { + arpExecutor.shutdown(); + } } return Optional.empty(); } diff --git a/plc4j/utils/test-utils/src/main/java/org/apache/plc4x/test/driver/internal/handlers/ApiRequestHandler.java b/plc4j/utils/test-utils/src/main/java/org/apache/plc4x/test/driver/internal/handlers/ApiRequestHandler.java index 29c95038a49..b3616289fae 100644 --- a/plc4j/utils/test-utils/src/main/java/org/apache/plc4x/test/driver/internal/handlers/ApiRequestHandler.java +++ b/plc4j/utils/test-utils/src/main/java/org/apache/plc4x/test/driver/internal/handlers/ApiRequestHandler.java @@ -18,6 +18,7 @@ */ package org.apache.plc4x.test.driver.internal.handlers; +import org.apache.commons.lang3.NotImplementedException; import org.apache.plc4x.java.api.PlcConnection; import org.apache.plc4x.java.api.exceptions.PlcRuntimeException; import org.apache.plc4x.java.api.messages.PlcReadRequest; @@ -86,6 +87,7 @@ public void executeApiRequest(PlcConnection plcConnection) { } case "TestSubscriptionRequest":{ // TODO: chris add your stuff here... + throw new NotImplementedException(); } default: throw new PlcRuntimeException("Unknown class name" + typeName);