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 2026/08/21 07:19:38 UTC
(plc4x) 02/02: feat(plc4j/s7): Add a ManualS7Inventory that uses SZL requests to find all installed S7 devices as well as their serial numbers and firmware versions.
This is an automated email from the ASF dual-hosted git repository.
chrisdutz pushed a commit to branch develop
in repository https://gitbox.apache.org/repos/asf/plc4x.git
commit 0a028e28674d87c99edcb5963cec53ed984ec70b
Author: Christofer Dutz <ch...@c-ware.de>
AuthorDate: Fri Aug 21 09:19:27 2026 +0200
feat(plc4j/s7): Add a ManualS7Inventory that uses SZL requests to find all installed S7 devices as well as their serial numbers and firmware versions.
---
.../org/apache/plc4x/java/s7/S7CotpConnection.java | 111 ++++++-
.../apache/plc4x/java/s7/S7HCotpConnection.java | 10 +
.../plc4x/java/s7/userdata/S7SzlService.java | 358 +++++++++++++++++++--
.../plc4x/java/s7/S7DeviceIdentificationTest.java | 303 +++++++++++++++++
.../plc4x/java/s7/S7HCotpConnectionTest.java | 42 +++
.../plc4x/java/s7/S7ScriptedConnectionHarness.java | 86 +++++
.../plc4x/java/s7/manual/ManualS7Inventory.java | 301 +++++++++++++++++
.../plc4x/java/s7/userdata/S7SzlServiceTest.java | 339 ++++++++++++++++++-
8 files changed, 1496 insertions(+), 54 deletions(-)
diff --git a/plc4j/drivers/s7/src/main/java/org/apache/plc4x/java/s7/S7CotpConnection.java b/plc4j/drivers/s7/src/main/java/org/apache/plc4x/java/s7/S7CotpConnection.java
index 0c8feecc69..2d99275698 100644
--- a/plc4j/drivers/s7/src/main/java/org/apache/plc4x/java/s7/S7CotpConnection.java
+++ b/plc4j/drivers/s7/src/main/java/org/apache/plc4x/java/s7/S7CotpConnection.java
@@ -46,6 +46,7 @@ import org.apache.plc4x.java.s7.userdata.S7BrowseService;
import org.apache.plc4x.java.s7.userdata.S7CyclicSubscriptionHandle;
import org.apache.plc4x.java.s7.userdata.S7CyclicSubscriptionService;
import org.apache.plc4x.java.s7.userdata.S7SzlService;
+import org.apache.plc4x.java.s7.userdata.S7SzlService.S7DeviceIdentification;
import org.apache.plc4x.java.s7.userdata.S7UserDataPushDispatcher;
import org.apache.plc4x.java.api.messages.PlcBrowseItem;
import org.apache.plc4x.java.api.messages.PlcBrowseRequestInterceptor;
@@ -97,6 +98,7 @@ import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Consumer;
+import java.util.function.Function;
import java.util.stream.IntStream;
/**
@@ -110,6 +112,9 @@ import java.util.stream.IntStream;
*/
public class S7CotpConnection extends ConnectionBase<S7Configuration> {
+ /** Safety net so a device that always claims "more data" cannot loop forever. */
+ private static final int MAX_SZL_CONTINUATIONS = 16;
+
private static final Logger LOGGER = LoggerFactory.getLogger(S7CotpConnection.class);
private final AtomicInteger tpduGenerator = new AtomicInteger(10);
@@ -263,15 +268,115 @@ public class S7CotpConnection extends ConnectionBase<S7Configuration> {
private S7SzlService.ProbeResult trySzlProbe(SzlId szlId, int szlIndex) {
try {
- S7Message request = S7SzlService.buildRequest(getTpduId(), szlId, szlIndex);
- S7Message response = sendInternal(request).get(driverContext.getReadTimeout(), TimeUnit.MILLISECONDS);
- return S7SzlService.parseProbeResponse(response);
+ // Draining matters even for the probe: a chained response the driver walks away
+ // from leaves the sequence open, and the CPU then refuses every later SZL read on
+ // this connection with 0xD406.
+ byte[] szlData = readSzlData(szlId, szlIndex, this::sendInternal)
+ .get(driverContext.getReadTimeout() * (MAX_SZL_CONTINUATIONS + 1L),
+ TimeUnit.MILLISECONDS);
+ return S7SzlService.parseProbeResponse(szlData);
} catch (Exception e) {
LOGGER.debug("SZL {}/{} probe failed: {}", szlId.getSublistList(), szlIndex, e.getMessage());
return null;
}
}
+ /**
+ * Read one SZL list, following the chain if the PLC splits it across several PDUs.
+ *
+ * <p>A response with {@code lastDataUnit} set means the CPU is holding the rest of the
+ * list. Continuation chunks carry no header of their own - they simply continue the byte
+ * stream, possibly starting mid-record - so the chunks are concatenated and parsed as one.
+ *
+ * @param sender how to dispatch each request; the connect-time probe sends directly,
+ * while normal operation goes through the request throttle.
+ */
+ private CompletableFuture<byte[]> readSzlData(SzlId szlId, int szlIndex,
+ Function<S7Message, CompletableFuture<S7Message>> sender) {
+ S7Message request = S7SzlService.buildRequest(getTpduId(), szlId, szlIndex);
+ return sender.apply(request).thenCompose(response ->
+ appendSzlChunks(szlId, szlIndex, response, S7SzlService.szlDataOf(response), 0, sender));
+ }
+
+ private CompletableFuture<byte[]> appendSzlChunks(SzlId szlId, int szlIndex, S7Message response,
+ byte[] soFar, int continuations,
+ Function<S7Message, CompletableFuture<S7Message>> sender) {
+ if (!S7SzlService.moreDataFollows(response)) {
+ return CompletableFuture.completedFuture(soFar);
+ }
+ if (continuations >= MAX_SZL_CONTINUATIONS) {
+ // Give up rather than loop forever. The sequence stays open, so later SZL reads on
+ // this connection will fail - worth a warning rather than silent truncation.
+ LOGGER.warn("SZL {}/{} still reports more data after {} continuations; giving up "
+ + "with {} bytes. Further SZL reads on this connection may be refused.",
+ szlId.getSublistList(), szlIndex, continuations, soFar.length);
+ return CompletableFuture.completedFuture(soFar);
+ }
+ S7Message next = S7SzlService.buildContinuationRequest(getTpduId(), szlId, szlIndex,
+ S7SzlService.sequenceNumberOf(response));
+ return sender.apply(next).thenCompose(chunk ->
+ appendSzlChunks(szlId, szlIndex, chunk, concat(soFar, S7SzlService.szlDataOf(chunk)),
+ continuations + 1, sender));
+ }
+
+ private static byte[] concat(byte[] first, byte[] second) {
+ byte[] combined = new byte[first.length + second.length];
+ System.arraycopy(first, 0, combined, 0, first.length);
+ System.arraycopy(second, 0, combined, first.length, second.length);
+ return combined;
+ }
+
+ /**
+ * Read everything the CPU is willing to tell us about itself: order code, hardware and
+ * firmware version, the configured names, the serial number and — where the device
+ * implements it — the protection level currently in force.
+ *
+ * <p>The connect-time probe deliberately keeps only what the driver itself needs; this is
+ * the on-demand version for callers building a device inventory. Three SZL lists are read
+ * one after the other and merged. Each one is best-effort: devices implement different
+ * subsets (S7-1200/1500 typically reject the protection-status list), so a rejected or
+ * unanswered list leaves its fields {@code null} instead of failing the whole call.
+ *
+ * @return the merged identification, never {@code null}; {@link S7DeviceIdentification#EMPTY}
+ * if the device answered none of the lists.
+ */
+ public CompletableFuture<S7DeviceIdentification> readDeviceIdentification() {
+ return readSzl(S7SzlService.MODULE_IDENTIFICATION, 0x0000,
+ S7SzlService::parseModuleIdentification)
+ .thenCompose(module -> readSzl(S7SzlService.COMPONENT_IDENTIFICATION, 0x0000,
+ S7SzlService::parseComponentIdentification)
+ .thenApply(module::mergedWith))
+ .thenCompose(identification -> readSzl(S7SzlService.PROTECTION_STATUS, 0x0004,
+ S7SzlService::parseProtectionStatus)
+ .thenApply(identification::mergedWith));
+ }
+
+ /**
+ * Issue one SZL read and parse it, collapsing every failure mode — transport error, PLC
+ * rejection, unparsable payload, no answer at all — into an empty identification. The
+ * timeout matters: a device that simply ignores an SZL it doesn't implement would
+ * otherwise leave the caller waiting forever.
+ */
+ private CompletableFuture<S7DeviceIdentification> readSzl(
+ SzlId szlId, int szlIndex, Function<byte[], S7DeviceIdentification> parser) {
+ return readSzlData(szlId, szlIndex, request -> executeThrottled(() -> sendInternal(request))
+ .orTimeout(driverContext.getReadTimeout(), TimeUnit.MILLISECONDS))
+ .handle((szlData, error) -> {
+ if (error != null) {
+ LOGGER.debug("SZL {}/{} read failed: {}",
+ szlId.getSublistList(), szlIndex, error.getMessage());
+ return S7DeviceIdentification.EMPTY;
+ }
+ try {
+ return parser.apply(szlData);
+ } catch (Exception e) {
+ LOGGER.debug("SZL {}/{} response could not be parsed: {}",
+ szlId.getSublistList(), szlIndex, e.getMessage());
+ return S7DeviceIdentification.EMPTY;
+ }
+ });
+ }
+
private CompletableFuture<Void> doSetupCommunication() {
S7ParameterSetupCommunication setup = new S7ParameterSetupCommunication(
driverContext.getMaxAmqCaller(), driverContext.getMaxAmqCallee(), driverContext.getPduSize());
diff --git a/plc4j/drivers/s7/src/main/java/org/apache/plc4x/java/s7/S7HCotpConnection.java b/plc4j/drivers/s7/src/main/java/org/apache/plc4x/java/s7/S7HCotpConnection.java
index c65bada521..daf04a41fb 100644
--- a/plc4j/drivers/s7/src/main/java/org/apache/plc4x/java/s7/S7HCotpConnection.java
+++ b/plc4j/drivers/s7/src/main/java/org/apache/plc4x/java/s7/S7HCotpConnection.java
@@ -35,6 +35,7 @@ import org.apache.plc4x.java.api.messages.PlcUnsubscriptionResponse;
import org.apache.plc4x.java.api.messages.PlcWriteRequest;
import org.apache.plc4x.java.api.messages.PlcWriteResponse;
import org.apache.plc4x.java.api.metadata.PlcConnectionMetadata;
+import org.apache.plc4x.java.s7.userdata.S7SzlService;
import org.apache.plc4x.java.api.model.PlcConsumerRegistration;
import org.apache.plc4x.java.api.model.PlcSubscriptionHandle;
import org.apache.plc4x.java.s7.configuration.S7Configuration;
@@ -186,6 +187,15 @@ public class S7HCotpConnection extends ConnectionBase<S7Configuration> {
};
}
+ /**
+ * Read the device identification from whichever inner connection is currently healthy.
+ * Unlike subscriptions, identification is stateless — both endpoints of an S7-H pair
+ * answer for the same CPU — so this can simply ride the normal failover path.
+ */
+ public CompletableFuture<S7SzlService.S7DeviceIdentification> readDeviceIdentification() {
+ return withFailover(S7CotpConnection::readDeviceIdentification);
+ }
+
@Override
protected void onConnect() throws PlcConnectionException {
// Connect both inners in parallel; succeed if at least one comes up. Failure of a
diff --git a/plc4j/drivers/s7/src/main/java/org/apache/plc4x/java/s7/userdata/S7SzlService.java b/plc4j/drivers/s7/src/main/java/org/apache/plc4x/java/s7/userdata/S7SzlService.java
index 43fab875b0..7776260199 100644
--- a/plc4j/drivers/s7/src/main/java/org/apache/plc4x/java/s7/userdata/S7SzlService.java
+++ b/plc4j/drivers/s7/src/main/java/org/apache/plc4x/java/s7/userdata/S7SzlService.java
@@ -35,7 +35,10 @@ import org.apache.plc4x.java.s7.readwrite.SzlModuleTypeClass;
import org.apache.plc4x.java.s7.readwrite.SzlSublist;
import java.nio.charset.StandardCharsets;
+import java.util.ArrayList;
+import java.util.Arrays;
import java.util.Collections;
+import java.util.List;
/**
* S7Comm UserData "CPU functions / Read SZL" service.
@@ -58,6 +61,15 @@ public final class S7SzlService {
public static final SzlId COMPONENT_IDENTIFICATION =
new SzlId(SzlModuleTypeClass.CPU, (byte) 0x00, SzlSublist.COMPONENT_IDENTIFICATION);
+ /**
+ * Protection level and mode-selector status — SZL-ID {@code 0x0232}, index {@code 0x0004}.
+ * The ID is composed of type class {@code CPU}, partial-list extension {@code 0x02} and
+ * partial list {@code 0x32}. Documented for S7-300/400; S7-1200/1500 frequently reject it,
+ * so callers must treat a failure here as "not reported" rather than an error.
+ */
+ public static final SzlId PROTECTION_STATUS =
+ new SzlId(SzlModuleTypeClass.CPU, (byte) 0x02, SzlSublist.COMMUNICATION_STATUS_DATA);
+
private S7SzlService() {
}
@@ -91,6 +103,62 @@ public final class S7SzlService {
new S7PayloadUserData(Collections.singletonList(payload)));
}
+ /**
+ * Build the follow-up request for a chained SZL response.
+ *
+ * <p>When a list doesn't fit in one PDU the CPU answers with {@code lastDataUnit} set and
+ * keeps the sequence open. Until it is drained, every new SZL request on that connection
+ * is refused with {@code 0xD406} — which is why this has to be sent rather than ignored.
+ *
+ * <p>The follow-up is the same ReadSZL request with the sequence number the PLC assigned
+ * echoed back; verified against a CPU 315-2 PN/DP, which answers it with the next chunk.
+ */
+ public static S7Message buildContinuationRequest(int tpduRef, SzlId szlId, int szlIndex,
+ int sequenceNumber) {
+ S7ParameterUserDataItem parameter = new S7ParameterUserDataItemCPUFunctions(
+ (short) 0x11, // method
+ (byte) 0x04, // cpuFunctionType: request
+ (byte) 0x04, // cpuFunctionGroup: CPU
+ (short) 0x01, // cpuSubfunction: ReadSZL
+ (short) sequenceNumber, // the sequence the PLC opened
+ null, null, null);
+ S7PayloadUserDataItem payload = new S7PayloadUserDataItemCpuFunctionReadSzlRequest(
+ DataTransportErrorCode.OK, DataTransportSize.OCTET_STRING, 4, szlId, szlIndex);
+ return new S7MessageUserData(tpduRef,
+ new S7ParameterUserData(Collections.singletonList(parameter)),
+ new S7PayloadUserData(Collections.singletonList(payload)));
+ }
+
+ /**
+ * Whether the PLC still has data pending for this SZL read, i.e. whether a continuation
+ * request is needed before anything else can be asked of this connection.
+ */
+ public static boolean moreDataFollows(S7Message response) {
+ Short lastDataUnit = cpuFunctionsOf(response, S7ParameterUserDataItemCPUFunctions::getLastDataUnit);
+ return lastDataUnit != null && lastDataUnit != 0;
+ }
+
+ /** The sequence number the PLC assigned to a chained read, to be echoed back. */
+ public static int sequenceNumberOf(S7Message response) {
+ Short sequenceNumber = cpuFunctionsOf(response,
+ S7ParameterUserDataItemCPUFunctions::getSequenceNumber);
+ return sequenceNumber == null ? 0 : sequenceNumber;
+ }
+
+ private static Short cpuFunctionsOf(S7Message response,
+ java.util.function.Function<S7ParameterUserDataItemCPUFunctions, Short> field) {
+ if (!(response instanceof S7MessageUserData)
+ || !(response.getParameter() instanceof S7ParameterUserData param)) {
+ return null;
+ }
+ for (S7ParameterUserDataItem item : param.getItems()) {
+ if (item instanceof S7ParameterUserDataItemCPUFunctions cpu) {
+ return field.apply(cpu);
+ }
+ }
+ return null;
+ }
+
/** Probe result: identifying information and derived capability flags. */
public record ProbeResult(String articleNumber, ControllerType controllerType) {
}
@@ -146,42 +214,20 @@ public final class S7SzlService {
* looking for the first chunk that decodes as printable ASCII starting with {@code "6ES7"}
* — robust across families without needing a separate parser per SZL ID.
*/
- public static ProbeResult parseProbeResponse(S7Message response) {
- if (!(response instanceof S7MessageUserData)) {
- throw new IllegalArgumentException("Expected S7MessageUserData, got "
- + response.getClass().getSimpleName());
+ public static ProbeResult parseProbeResponse(byte[] bytes) {
+ if (bytes == null || bytes.length < 4) {
+ throw new IllegalStateException("SZL response too short: "
+ + (bytes == null ? -1 : bytes.length) + " bytes");
}
- // The PLC reports unsupported SZL-ID/index combinations via the parameter's errorCode.
- // Treat any non-zero error as "this SZL didn't work" and let the caller try the next one.
- S7ParameterUserData param = (S7ParameterUserData) response.getParameter();
- for (S7ParameterUserDataItem pItem : param.getItems()) {
- if (pItem instanceof S7ParameterUserDataItemCPUFunctions cpu
- && cpu.getErrorCode() != null && cpu.getErrorCode() != 0) {
- throw new IllegalStateException("SZL request rejected by PLC, errorCode=0x"
- + Integer.toHexString(cpu.getErrorCode()));
- }
- }
- S7PayloadUserData payload = (S7PayloadUserData) response.getPayload();
- for (S7PayloadUserDataItem item : payload.getItems()) {
- if (!(item instanceof S7PayloadUserDataItemCpuFunctionReadSzlResponse szl)) {
- continue;
- }
- byte[] bytes = szl.getItems();
- if (bytes == null || bytes.length < 4) {
- throw new IllegalStateException("SZL response too short: "
- + (bytes == null ? -1 : bytes.length) + " bytes");
- }
- // Best-effort identification: try the order-number prefix first, then the
- // model-name pattern (e.g. "CPU 315-2 PN/DP" on S7-300). If neither hits we
- // still return an empty-string article — the response was structurally valid,
- // which is enough to say UserData services work on this device.
- String article = findArticleNumber(bytes);
- String descriptor = article != null ? article : findCpuModelName(bytes);
- return new ProbeResult(
- descriptor != null ? descriptor : "",
- decodeControllerType(descriptor));
- }
- throw new IllegalStateException("No SZL response item in payload");
+ // Best-effort identification: try the order-number prefix first, then the
+ // model-name pattern (e.g. "CPU 315-2 PN/DP" on S7-300). If neither hits we
+ // still return an empty-string article — the response was structurally valid,
+ // which is enough to say UserData services work on this device.
+ String article = findArticleNumber(bytes);
+ String descriptor = article != null ? article : findCpuModelName(bytes);
+ return new ProbeResult(
+ descriptor != null ? descriptor : "",
+ decodeControllerType(descriptor));
}
/**
@@ -288,4 +334,246 @@ public final class S7SzlService {
}
return ControllerType.ANY;
}
+
+ // ------------------------------------------------------------------------
+ // Full device identification
+ // ------------------------------------------------------------------------
+
+ /**
+ * Everything we can learn about a device from the identification SZLs. Every field is
+ * nullable: devices answer different subsets depending on family and firmware, and a
+ * field stays {@code null} when the owning SZL was not answered or did not carry it.
+ */
+ public record S7DeviceIdentification(String orderCode,
+ String hardwareVersion,
+ String firmwareVersion,
+ String moduleName,
+ String moduleTypeName,
+ String systemName,
+ String plantDesignation,
+ String serialNumber,
+ Integer protectionLevel,
+ String keySwitchPosition,
+ Boolean passwordProtected) {
+
+ public static final S7DeviceIdentification EMPTY = new S7DeviceIdentification(
+ null, null, null, null, null, null, null, null, null, null, null);
+
+ /**
+ * Combine two partial identifications. Fields set on {@code this} win; {@code null}
+ * fields are filled in from {@code other}. Used to fold the three SZL responses
+ * (module, component, protection) into a single result.
+ */
+ public S7DeviceIdentification mergedWith(S7DeviceIdentification other) {
+ if (other == null) {
+ return this;
+ }
+ return new S7DeviceIdentification(
+ orderCode != null ? orderCode : other.orderCode,
+ hardwareVersion != null ? hardwareVersion : other.hardwareVersion,
+ firmwareVersion != null ? firmwareVersion : other.firmwareVersion,
+ moduleName != null ? moduleName : other.moduleName,
+ moduleTypeName != null ? moduleTypeName : other.moduleTypeName,
+ systemName != null ? systemName : other.systemName,
+ plantDesignation != null ? plantDesignation : other.plantDesignation,
+ serialNumber != null ? serialNumber : other.serialNumber,
+ protectionLevel != null ? protectionLevel : other.protectionLevel,
+ keySwitchPosition != null ? keySwitchPosition : other.keySwitchPosition,
+ passwordProtected != null ? passwordProtected : other.passwordProtected);
+ }
+ }
+
+ /** An SZL response split into its header and fixed-length records. */
+ record SzlList(int szlId, int szlIndex, int recordLength, List<byte[]> records) {
+ }
+
+ /**
+ * Split an SZL response into records. The data section is an 8-byte header
+ * ({@code szl-id}, {@code szl-index}, {@code record-length}, {@code record-count})
+ * followed by {@code record-count} records of {@code record-length} bytes each.
+ *
+ * <p>Records the PLC announced but did not actually send are skipped rather than causing
+ * a failure — some devices cut the response short at the PDU boundary.
+ */
+ static SzlList parseRecords(byte[] data) {
+ if (data.length < 8) {
+ throw new IllegalStateException("SZL response too short for a data header: "
+ + data.length + " bytes");
+ }
+ int szlId = readWord(data, 0);
+ int szlIndex = readWord(data, 2);
+ int recordLength = readWord(data, 4);
+ int recordCount = readWord(data, 6);
+ if (recordLength <= 0) {
+ throw new IllegalStateException("SZL response declares record length " + recordLength);
+ }
+ List<byte[]> records = new ArrayList<>();
+ for (int i = 0; i < recordCount; i++) {
+ int offset = 8 + (i * recordLength);
+ if (offset + recordLength > data.length) {
+ break;
+ }
+ records.add(Arrays.copyOfRange(data, offset, offset + recordLength));
+ }
+ return new SzlList(szlId, szlIndex, recordLength, records);
+ }
+
+ /**
+ * Parse a module-identification response (SZL {@code 0x0011}, read with index
+ * {@code 0x0000} so the PLC returns every record).
+ *
+ * <p>Each record is {@code index(2) + MLFB(20) + BGTyp(2) + Ausbg(2) + Ausbe(2)}. Record
+ * index 1 identifies the module itself, 6 the basic hardware and 7 the basic firmware.
+ * The version is the record's trailing three bytes — the reading Snap7 and nmap's
+ * {@code s7-info} both use, and the one that matches what TIA Portal displays.
+ */
+ public static S7DeviceIdentification parseModuleIdentification(byte[] szlData) {
+ String orderCode = null;
+ String hardwareVersion = null;
+ String firmwareVersion = null;
+ for (byte[] record : parseRecords(szlData).records()) {
+ switch (readWord(record, 0)) {
+ case 0x0001 -> orderCode = emptyToNull(readAscii(record, 2, 20));
+ case 0x0006 -> hardwareVersion = readVersion(record);
+ case 0x0007 -> firmwareVersion = readVersion(record);
+ default -> { /* other records identify submodules — not part of the inventory */ }
+ }
+ }
+ return new S7DeviceIdentification(orderCode, hardwareVersion, firmwareVersion,
+ null, null, null, null, null, null, null, null);
+ }
+
+ /**
+ * Parse a component-identification response (SZL {@code 0x001C}, read with index
+ * {@code 0x0000}). Each record is {@code index(2)} followed by an ASCII value; the record
+ * indices we care about are 1 (system/station name), 2 (module name), 3 (plant
+ * designation), 5 (serial number) and 7 (module type name, e.g. {@code "CPU 1511-1 PN"}).
+ */
+ public static S7DeviceIdentification parseComponentIdentification(byte[] szlData) {
+ String systemName = null;
+ String moduleName = null;
+ String plantDesignation = null;
+ String serialNumber = null;
+ String moduleTypeName = null;
+ for (byte[] record : parseRecords(szlData).records()) {
+ String value = emptyToNull(readAscii(record, 2, record.length - 2));
+ switch (readWord(record, 0)) {
+ case 0x0001 -> systemName = value;
+ case 0x0002 -> moduleName = value;
+ case 0x0003 -> plantDesignation = value;
+ case 0x0005 -> serialNumber = value;
+ case 0x0007 -> moduleTypeName = value;
+ default -> { /* copyright, OEM id, location designation — not inventoried */ }
+ }
+ }
+ return new S7DeviceIdentification(null, null, null, moduleName, moduleTypeName,
+ systemName, plantDesignation, serialNumber, null, null, null);
+ }
+
+ /**
+ * Parse a protection-status response (SZL {@code 0x0232} index {@code 0x0004}). The record
+ * is {@code index, sch_schal, sch_par, sch_rel, bart_sch, anl_sch} as 16-bit words.
+ *
+ * <p>{@code sch_rel} is the protection level actually in force (1 = read and write,
+ * 2 = read-only without password, 3 = no access without password) and {@code sch_par} is
+ * non-zero exactly when a protection level was configured, i.e. when a password is set.
+ */
+ public static S7DeviceIdentification parseProtectionStatus(byte[] szlData) {
+ List<byte[]> records = parseRecords(szlData).records();
+ if (records.isEmpty()) {
+ throw new IllegalStateException("Protection-status SZL carried no records");
+ }
+ byte[] record = records.get(0);
+ if (record.length < 10) {
+ throw new IllegalStateException("Protection-status record too short: "
+ + record.length + " bytes");
+ }
+ int parameterisedLevel = readWord(record, 4); // sch_par
+ int effectiveLevel = readWord(record, 6); // sch_rel
+ int keySwitch = readWord(record, 8); // bart_sch
+ return new S7DeviceIdentification(null, null, null, null, null, null, null, null,
+ effectiveLevel, decodeKeySwitchPosition(keySwitch), parameterisedLevel != 0);
+ }
+
+ /**
+ * Pull the raw SZL data section out of a response, after checking that the PLC didn't
+ * reject the request. For a chained response this is one chunk; callers append the
+ * chunks and hand the result to the parsers.
+ */
+ public static byte[] szlDataOf(S7Message response) {
+ if (!(response instanceof S7MessageUserData)) {
+ throw new IllegalArgumentException("Expected S7MessageUserData, got "
+ + (response == null ? "null" : response.getClass().getSimpleName()));
+ }
+ checkErrorCode(response);
+ S7PayloadUserData payload = (S7PayloadUserData) response.getPayload();
+ for (S7PayloadUserDataItem item : payload.getItems()) {
+ if (item instanceof S7PayloadUserDataItemCpuFunctionReadSzlResponse szl
+ && szl.getItems() != null) {
+ return szl.getItems();
+ }
+ }
+ throw new IllegalStateException("No SZL response item in payload");
+ }
+
+ /**
+ * The PLC reports unsupported SZL-ID/index combinations via the parameter's errorCode.
+ * Treat any non-zero error as "this SZL didn't work" and let the caller try the next one.
+ */
+ private static void checkErrorCode(S7Message response) {
+ S7ParameterUserData param = (S7ParameterUserData) response.getParameter();
+ for (S7ParameterUserDataItem pItem : param.getItems()) {
+ if (pItem instanceof S7ParameterUserDataItemCPUFunctions cpu
+ && cpu.getErrorCode() != null && cpu.getErrorCode() != 0) {
+ throw new IllegalStateException("SZL request rejected by PLC, errorCode=0x"
+ + Integer.toHexString(cpu.getErrorCode()));
+ }
+ }
+ }
+
+ private static String decodeKeySwitchPosition(int bartSch) {
+ return switch (bartSch) {
+ case 1 -> "RUN";
+ case 2 -> "RUN-P";
+ case 3 -> "STOP";
+ case 4 -> "MRES";
+ default -> "unknown";
+ };
+ }
+
+ /** Version as the record's trailing three bytes, e.g. {@code "V 2.6.0"}. */
+ private static String readVersion(byte[] record) {
+ if (record.length < 3) {
+ return null;
+ }
+ return String.format("V %d.%d.%d",
+ record[record.length - 3] & 0xFF,
+ record[record.length - 2] & 0xFF,
+ record[record.length - 1] & 0xFF);
+ }
+
+ private static String readAscii(byte[] record, int offset, int length) {
+ if (offset >= record.length || length <= 0) {
+ return "";
+ }
+ int available = Math.min(length, record.length - offset);
+ // Devices pad with either spaces or NULs; stop at the first NUL so the trailing
+ // padding doesn't end up in the string.
+ int end = offset;
+ while (end < offset + available && record[end] != 0x00) {
+ end++;
+ }
+ return new String(record, offset, end - offset, StandardCharsets.US_ASCII).trim();
+ }
+
+ private static String emptyToNull(String value) {
+ return value == null || value.isEmpty() ? null : value;
+ }
+
+ private static int readWord(byte[] data, int offset) {
+ if (offset + 1 >= data.length) {
+ return 0;
+ }
+ return ((data[offset] & 0xFF) << 8) | (data[offset + 1] & 0xFF);
+ }
}
diff --git a/plc4j/drivers/s7/src/test/java/org/apache/plc4x/java/s7/S7DeviceIdentificationTest.java b/plc4j/drivers/s7/src/test/java/org/apache/plc4x/java/s7/S7DeviceIdentificationTest.java
new file mode 100644
index 0000000000..411cb7c7ec
--- /dev/null
+++ b/plc4j/drivers/s7/src/test/java/org/apache/plc4x/java/s7/S7DeviceIdentificationTest.java
@@ -0,0 +1,303 @@
+/*
+ * 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.s7;
+
+import org.apache.plc4x.java.s7.S7ScriptedConnectionHarness.ScriptedS7Transport;
+import org.apache.plc4x.java.s7.userdata.S7SzlService.S7DeviceIdentification;
+import org.junit.jupiter.api.Test;
+
+import java.nio.charset.StandardCharsets;
+import java.util.Arrays;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.TimeUnit;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/**
+ * A device inventory needs more than the article number the connect-time probe keeps, so the
+ * connection can read the three identification SZLs on demand. Devices answer different subsets
+ * of them — notably S7-1200/1500 usually refuse the protection-status list — so whatever did
+ * come back has to survive the ones that didn't.
+ */
+class S7DeviceIdentificationTest {
+
+ @Test
+ void readsOrderCodeAndFirmwareFromTheModuleIdentificationList() throws Exception {
+ S7DeviceIdentification id = identificationFrom(new SzlScript(true, true, true));
+ assertEquals("6ES7 511-1AK02-0AB0", id.orderCode());
+ assertEquals("V 2.6.0", id.firmwareVersion());
+ }
+
+ @Test
+ void readsNamesFromTheComponentIdentificationList() throws Exception {
+ S7DeviceIdentification id = identificationFrom(new SzlScript(true, true, true));
+ assertEquals("PLC_1", id.moduleName());
+ assertEquals("S C-J2UD57132018", id.serialNumber());
+ }
+
+ @Test
+ void readsProtectionLevelFromTheProtectionStatusList() throws Exception {
+ S7DeviceIdentification id = identificationFrom(new SzlScript(true, true, true));
+ assertEquals(Integer.valueOf(2), id.protectionLevel());
+ assertEquals(Boolean.TRUE, id.passwordProtected());
+ }
+
+ @Test
+ void keepsIdentificationWhenTheProtectionListIsRefused() throws Exception {
+ // What an S7-1200/1500 does: answers 0x0011 and 0x001C, rejects 0x0232.
+ S7DeviceIdentification id = identificationFrom(new SzlScript(true, true, false));
+ assertEquals("V 2.6.0", id.firmwareVersion());
+ assertEquals("PLC_1", id.moduleName());
+ assertNull(id.protectionLevel());
+ }
+
+ @Test
+ void keepsFirmwareWhenTheComponentListIsRefused() throws Exception {
+ S7DeviceIdentification id = identificationFrom(new SzlScript(true, false, true));
+ assertEquals("V 2.6.0", id.firmwareVersion());
+ assertNull(id.moduleName());
+ }
+
+ @Test
+ void returnsAnEmptyIdentificationWhenEverySzlIsRefused() throws Exception {
+ S7DeviceIdentification id = identificationFrom(new SzlScript(false, false, false));
+ assertEquals(S7DeviceIdentification.EMPTY, id);
+ }
+
+ /**
+ * A list that doesn't fit in one PDU comes back as a chain: the first chunk sets
+ * lastDataUnit and can stop in the middle of a record, and the continuation carries no
+ * header of its own. Unless the driver echoes the sequence number and appends the chunks,
+ * the straddling record is lost - and the CPU refuses every later SZL read on the
+ * connection because the sequence was left open.
+ */
+ @Test
+ void assemblesAChainedSzlResponse() throws Exception {
+ ScriptedS7Transport transport = new ScriptedS7Transport();
+ S7CotpConnection connection = S7ScriptedConnectionHarness.newConnectedConnection(transport);
+ transport.resetCounters();
+
+ byte[] whole = moduleIdentificationData();
+ int cut = 8 + 14; // stop halfway through the first record
+ byte[] firstChunk = Arrays.copyOfRange(whole, 0, cut);
+ byte[] rest = Arrays.copyOfRange(whole, cut, whole.length);
+
+ CompletableFuture<S7DeviceIdentification> future = connection.readDeviceIdentification();
+ answerWith(transport, future, request -> {
+ int tpduReference = S7ScriptedConnectionHarness.tpduReferenceOfFrame(request);
+ if (S7ScriptedConnectionHarness.szlIdOfRequest(request) != 0x0011) {
+ return S7ScriptedConnectionHarness.szlErrorResponse(tpduReference, 0xD401);
+ }
+ // A continuation is a ReadSZL request echoing the sequence number we handed out.
+ return S7ScriptedConnectionHarness.sequenceNumberOfRequest(request) == SEQUENCE
+ ? S7ScriptedConnectionHarness.szlResponse(tpduReference, rest, SEQUENCE, 0)
+ : S7ScriptedConnectionHarness.szlResponse(tpduReference, firstChunk, SEQUENCE, 1);
+ });
+
+ S7DeviceIdentification id = future.get(20, TimeUnit.SECONDS);
+ connection.close();
+ assertEquals("V 2.6.0", id.firmwareVersion());
+ assertEquals("6ES7 511-1AK02-0AB0", id.orderCode());
+ }
+
+ /**
+ * A device that keeps claiming there is more data must not spin forever - the driver caps
+ * the chain and returns what it has.
+ */
+ @Test
+ void stopsChainingAfterTheContinuationLimit() throws Exception {
+ ScriptedS7Transport transport = new ScriptedS7Transport();
+ S7CotpConnection connection = S7ScriptedConnectionHarness.newConnectedConnection(transport);
+ transport.resetCounters();
+
+ CompletableFuture<S7DeviceIdentification> future = connection.readDeviceIdentification();
+ answerWith(transport, future, request -> {
+ int tpduReference = S7ScriptedConnectionHarness.tpduReferenceOfFrame(request);
+ if (S7ScriptedConnectionHarness.szlIdOfRequest(request) != 0x0011) {
+ return S7ScriptedConnectionHarness.szlErrorResponse(tpduReference, 0xD401);
+ }
+ // Always "more data follows".
+ return S7ScriptedConnectionHarness.szlResponse(
+ tpduReference, moduleIdentificationData(), SEQUENCE, 1);
+ });
+
+ S7DeviceIdentification id = future.get(20, TimeUnit.SECONDS);
+ connection.close();
+ // It gave up, but kept what the chunks contained rather than failing outright.
+ assertEquals("6ES7 511-1AK02-0AB0", id.orderCode());
+ assertTrue(transport.writeCount() <= 20,
+ "expected the chain to be capped, but the driver sent " + transport.writeCount()
+ + " requests");
+ }
+
+ /** Sequence number the scripted device hands out for its chained reads. */
+ private static final int SEQUENCE = 3;
+
+ /** Answers every frame the driver writes until {@code future} completes. */
+ private static void answerWith(ScriptedS7Transport transport, CompletableFuture<?> future,
+ Responder responder) {
+ Thread thread = new Thread(() -> {
+ int answered = 0;
+ while (!future.isDone()) {
+ try {
+ if (transport.writeCount() > answered) {
+ byte[] request = transport.writtenFrames().get(answered);
+ answered++;
+ transport.deliver(responder.replyTo(request));
+ transport.runDataListener();
+ }
+ Thread.sleep(5);
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ return;
+ } catch (Exception e) {
+ throw new IllegalStateException("could not answer SZL request", e);
+ }
+ }
+ }, "szl-responder");
+ thread.setDaemon(true);
+ thread.start();
+ }
+
+ private interface Responder {
+ byte[] replyTo(byte[] request) throws Exception;
+ }
+
+ /**
+ * Runs {@code readDeviceIdentification()} against the scripted transport, answering each
+ * SZL request the driver sends according to {@code script}.
+ */
+ private static S7DeviceIdentification identificationFrom(SzlScript script) throws Exception {
+ ScriptedS7Transport transport = new ScriptedS7Transport();
+ S7CotpConnection connection = S7ScriptedConnectionHarness.newConnectedConnection(transport);
+ transport.resetCounters();
+
+ CompletableFuture<S7DeviceIdentification> future = connection.readDeviceIdentification();
+
+ Thread responder = new Thread(() -> {
+ int answered = 0;
+ while (!future.isDone()) {
+ try {
+ if (transport.writeCount() > answered) {
+ byte[] request = transport.writtenFrames().get(answered);
+ answered++;
+ transport.deliver(script.replyTo(request));
+ transport.runDataListener();
+ }
+ Thread.sleep(5);
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ return;
+ } catch (Exception e) {
+ throw new IllegalStateException("could not answer SZL request", e);
+ }
+ }
+ }, "szl-responder");
+ responder.setDaemon(true);
+ responder.start();
+
+ S7DeviceIdentification id = future.get(20, TimeUnit.SECONDS);
+ connection.close();
+ return id;
+ }
+
+ /** Decides, per SZL-ID, whether the simulated device answers or rejects the request. */
+ private record SzlScript(boolean answerModule, boolean answerComponent, boolean answerProtection) {
+
+ byte[] replyTo(byte[] request) throws Exception {
+ int szlId = S7ScriptedConnectionHarness.szlIdOfRequest(request);
+ int tpduReference = S7ScriptedConnectionHarness.tpduReferenceOfFrame(request);
+ return switch (szlId) {
+ case 0x0011 -> answerModule
+ ? S7ScriptedConnectionHarness.szlResponse(tpduReference, moduleIdentificationData())
+ : S7ScriptedConnectionHarness.szlErrorResponse(tpduReference, 0xD401);
+ case 0x001C -> answerComponent
+ ? S7ScriptedConnectionHarness.szlResponse(tpduReference, componentIdentificationData())
+ : S7ScriptedConnectionHarness.szlErrorResponse(tpduReference, 0xD401);
+ case 0x0232 -> answerProtection
+ ? S7ScriptedConnectionHarness.szlResponse(tpduReference, protectionStatusData())
+ : S7ScriptedConnectionHarness.szlErrorResponse(tpduReference, 0xD401);
+ default -> throw new IllegalStateException(
+ "unexpected SZL-ID 0x" + Integer.toHexString(szlId));
+ };
+ }
+ }
+
+ private static byte[] moduleIdentificationData() {
+ return szlData(0x0011, 0x0000, 28,
+ moduleRecord(1, "6ES7 511-1AK02-0AB0", 5, 1, 2),
+ moduleRecord(6, "6ES7 511-1AK02-0AB0", 1, 0, 0),
+ moduleRecord(7, "6ES7 511-1AK02-0AB0", 2, 6, 0));
+ }
+
+ private static byte[] componentIdentificationData() {
+ return szlData(0x001C, 0x0000, 34,
+ componentRecord(1, "PLANT-LINE-3"),
+ componentRecord(2, "PLC_1"),
+ componentRecord(5, "S C-J2UD57132018"));
+ }
+
+ private static byte[] protectionStatusData() {
+ // sch_schal=0, sch_par=2 (password configured), sch_rel=2, bart_sch=2 (RUN-P), anl_sch=0
+ return szlData(0x0232, 0x0004, 12, words(0x0004, 0, 2, 2, 2, 0));
+ }
+
+ private static byte[] moduleRecord(int index, String mlfb, int v1, int v2, int v3) {
+ byte[] record = new byte[28];
+ record[0] = (byte) (index >> 8);
+ record[1] = (byte) index;
+ byte[] mlfbBytes = mlfb.getBytes(StandardCharsets.US_ASCII);
+ System.arraycopy(mlfbBytes, 0, record, 2, Math.min(mlfbBytes.length, 20));
+ record[25] = (byte) v1;
+ record[26] = (byte) v2;
+ record[27] = (byte) v3;
+ return record;
+ }
+
+ private static byte[] componentRecord(int index, String value) {
+ byte[] record = new byte[34];
+ record[0] = (byte) (index >> 8);
+ record[1] = (byte) index;
+ byte[] valueBytes = value.getBytes(StandardCharsets.US_ASCII);
+ System.arraycopy(valueBytes, 0, record, 2, Math.min(valueBytes.length, 32));
+ return record;
+ }
+
+ private static byte[] szlData(int szlId, int szlIndex, int recordLength, byte[]... records) {
+ byte[] data = new byte[8 + records.length * recordLength];
+ byte[] header = words(szlId, szlIndex, recordLength, records.length);
+ System.arraycopy(header, 0, data, 0, 8);
+ for (int i = 0; i < records.length; i++) {
+ System.arraycopy(records[i], 0, data, 8 + i * recordLength,
+ Math.min(records[i].length, recordLength));
+ }
+ return data;
+ }
+
+ private static byte[] words(int... values) {
+ byte[] out = new byte[values.length * 2];
+ for (int i = 0; i < values.length; i++) {
+ out[i * 2] = (byte) (values[i] >> 8);
+ out[i * 2 + 1] = (byte) values[i];
+ }
+ return out;
+ }
+}
diff --git a/plc4j/drivers/s7/src/test/java/org/apache/plc4x/java/s7/S7HCotpConnectionTest.java b/plc4j/drivers/s7/src/test/java/org/apache/plc4x/java/s7/S7HCotpConnectionTest.java
index a395bf750f..38f910618e 100644
--- a/plc4j/drivers/s7/src/test/java/org/apache/plc4x/java/s7/S7HCotpConnectionTest.java
+++ b/plc4j/drivers/s7/src/test/java/org/apache/plc4x/java/s7/S7HCotpConnectionTest.java
@@ -33,6 +33,8 @@ import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import static org.junit.jupiter.api.Assertions.*;
+import org.apache.plc4x.java.s7.userdata.S7SzlService;
+
import static org.mockito.Mockito.*;
/**
@@ -186,6 +188,46 @@ class S7HCotpConnectionTest {
// Test fixture helpers
// ------------------------------------------------------------------------------------
+ @Test
+ void readDeviceIdentification_readsFromTheActiveInner() throws Exception {
+ S7CotpConnection primary = mock(S7CotpConnection.class);
+ S7CotpConnection secondary = mock(S7CotpConnection.class);
+ when(primary.isConnected()).thenReturn(true);
+ when(secondary.isConnected()).thenReturn(true);
+ when(primary.readDeviceIdentification())
+ .thenReturn(CompletableFuture.completedFuture(identificationWithFirmware("V 2.6.0")));
+
+ TestableS7HCotpConnection wrapper = newWrapper(primary, secondary);
+ wrapper.markActiveAsPrimaryForTest();
+
+ assertEquals("V 2.6.0",
+ wrapper.readDeviceIdentification().get(5, TimeUnit.SECONDS).firmwareVersion());
+ verify(secondary, never()).readDeviceIdentification();
+ }
+
+ @Test
+ void readDeviceIdentification_failsOverToTheSurvivingInner() throws Exception {
+ S7CotpConnection primary = mock(S7CotpConnection.class);
+ S7CotpConnection secondary = mock(S7CotpConnection.class);
+ when(primary.isConnected()).thenReturn(false);
+ when(secondary.isConnected()).thenReturn(true);
+ when(secondary.readDeviceIdentification())
+ .thenReturn(CompletableFuture.completedFuture(identificationWithFirmware("V 4.2.1")));
+
+ TestableS7HCotpConnection wrapper = newWrapper(primary, secondary);
+ // A wrapper only reaches this call after onConnect() has picked an active slot, so
+ // the failover under test is "active inner went down", not "never connected".
+ wrapper.markActiveAsPrimaryForTest();
+
+ assertEquals("V 4.2.1",
+ wrapper.readDeviceIdentification().get(5, TimeUnit.SECONDS).firmwareVersion());
+ }
+
+ private static S7SzlService.S7DeviceIdentification identificationWithFirmware(String firmware) {
+ return new S7SzlService.S7DeviceIdentification(null, null, firmware,
+ null, null, null, null, null, null, null, null);
+ }
+
private static TestableS7HCotpConnection newWrapper(S7CotpConnection primary, S7CotpConnection secondary) {
S7Configuration config = new S7Configuration();
TransportInstance<?> transport = mock(TransportInstance.class);
diff --git a/plc4j/drivers/s7/src/test/java/org/apache/plc4x/java/s7/S7ScriptedConnectionHarness.java b/plc4j/drivers/s7/src/test/java/org/apache/plc4x/java/s7/S7ScriptedConnectionHarness.java
index eb087515aa..d473942350 100644
--- a/plc4j/drivers/s7/src/test/java/org/apache/plc4x/java/s7/S7ScriptedConnectionHarness.java
+++ b/plc4j/drivers/s7/src/test/java/org/apache/plc4x/java/s7/S7ScriptedConnectionHarness.java
@@ -22,7 +22,17 @@ import org.apache.plc4x.java.s7.configuration.S7Configuration;
import org.apache.plc4x.java.s7.readwrite.ControllerType;
import org.apache.plc4x.java.s7.readwrite.S7Message;
import org.apache.plc4x.java.s7.readwrite.S7MessageResponseData;
+import org.apache.plc4x.java.s7.readwrite.S7MessageUserData;
import org.apache.plc4x.java.s7.readwrite.S7ParameterSetupCommunication;
+import org.apache.plc4x.java.s7.readwrite.S7ParameterUserData;
+import org.apache.plc4x.java.s7.readwrite.S7ParameterUserDataItem;
+import org.apache.plc4x.java.s7.readwrite.S7ParameterUserDataItemCPUFunctions;
+import org.apache.plc4x.java.s7.readwrite.S7PayloadUserData;
+import org.apache.plc4x.java.s7.readwrite.S7PayloadUserDataItemCpuFunctionReadSzlRequest;
+import org.apache.plc4x.java.s7.readwrite.S7PayloadUserDataItemCpuFunctionReadSzlResponse;
+import org.apache.plc4x.java.s7.readwrite.DataTransportErrorCode;
+import org.apache.plc4x.java.s7.readwrite.DataTransportSize;
+import org.apache.plc4x.java.s7.readwrite.SzlId;
import org.apache.plc4x.java.spi.buffers.api.WithOption;
import org.apache.plc4x.java.spi.buffers.bytebased.ReadBufferByteBased;
import org.apache.plc4x.java.spi.buffers.bytebased.WithByteBasedOption;
@@ -154,6 +164,82 @@ public final class S7ScriptedConnectionHarness {
(short) errorClass, (short) errorCode));
}
+ /**
+ * The SZL-ID an outgoing ReadSZL request asks for, as the 16-bit value Siemens documents
+ * it by (type class, partial-list extension, partial list) — so a test can answer each
+ * request according to which list it is.
+ */
+ public static int szlIdOfRequest(byte[] frame) throws Exception {
+ S7Message message = S7Message.staticParse(readBuffer(frame));
+ S7PayloadUserData payload = (S7PayloadUserData) message.getPayload();
+ for (Object item : payload.getItems()) {
+ if (item instanceof S7PayloadUserDataItemCpuFunctionReadSzlRequest request) {
+ SzlId szlId = request.getSzlId();
+ return ((szlId.getTypeClass().getValue() & 0x0F) << 12)
+ | ((szlId.getSublistExtract() & 0x0F) << 8)
+ | (szlId.getSublistList().getValue() & 0xFF);
+ }
+ }
+ throw new IllegalStateException("frame is not a ReadSZL request");
+ }
+
+ /** A ReadSZL response carrying the given raw data section, complete in one PDU. */
+ public static byte[] szlResponse(int tpduReference, byte[] szlData) throws Exception {
+ return szlResponse(tpduReference, szlData, 0, 0);
+ }
+
+ /**
+ * A ReadSZL response chunk. {@code lastDataUnit} non-zero is how a CPU says it still holds
+ * the rest of the list; {@code sequenceNumber} is the sequence the client has to echo to
+ * fetch the next chunk.
+ */
+ public static byte[] szlResponse(int tpduReference, byte[] szlData, int sequenceNumber,
+ int lastDataUnit) throws Exception {
+ return wireBytes(new S7MessageUserData(tpduReference,
+ new S7ParameterUserData(List.of(
+ cpuFunctionsResponseParameter(0, sequenceNumber, lastDataUnit))),
+ new S7PayloadUserData(List.of(new S7PayloadUserDataItemCpuFunctionReadSzlResponse(
+ DataTransportErrorCode.OK, DataTransportSize.OCTET_STRING,
+ szlData.length, szlData)))));
+ }
+
+ /**
+ * The sequence number on an outgoing ReadSZL request. Zero on a first request; a
+ * continuation echoes the sequence the PLC assigned.
+ */
+ public static int sequenceNumberOfRequest(byte[] frame) throws Exception {
+ S7Message message = S7Message.staticParse(readBuffer(frame));
+ for (S7ParameterUserDataItem item
+ : ((S7ParameterUserData) message.getParameter()).getItems()) {
+ if (item instanceof S7ParameterUserDataItemCPUFunctions cpu) {
+ return cpu.getSequenceNumber();
+ }
+ }
+ throw new IllegalStateException("frame carries no CPU-functions parameter");
+ }
+
+ /**
+ * What a controller sends when it does not implement the requested SZL-ID: a ReadSZL
+ * response whose CPU-functions parameter carries a non-zero error code and no payload.
+ */
+ public static byte[] szlErrorResponse(int tpduReference, int errorCode) throws Exception {
+ return wireBytes(new S7MessageUserData(tpduReference,
+ new S7ParameterUserData(List.of(cpuFunctionsResponseParameter(errorCode, 0, 0))),
+ new S7PayloadUserData(List.of())));
+ }
+
+ private static S7ParameterUserDataItem cpuFunctionsResponseParameter(int errorCode,
+ int sequenceNumber,
+ int lastDataUnit) {
+ return new S7ParameterUserDataItemCPUFunctions(
+ (short) 0x12, // method
+ (byte) 0x08, // cpuFunctionType: response
+ (byte) 0x04, // cpuFunctionGroup: CPU
+ (short) 0x01, // cpuSubfunction: ReadSZL
+ (short) sequenceNumber,
+ (short) 0x00, (short) lastDataUnit, errorCode);
+ }
+
private static byte[] s7SetupCommunicationResponse(int tpduReference) throws Exception {
S7Message message = new S7MessageResponseData(tpduReference,
new S7ParameterSetupCommunication(8, 8, 240), null, (short) 0, (short) 0);
diff --git a/plc4j/drivers/s7/src/test/java/org/apache/plc4x/java/s7/manual/ManualS7Inventory.java b/plc4j/drivers/s7/src/test/java/org/apache/plc4x/java/s7/manual/ManualS7Inventory.java
new file mode 100644
index 0000000000..5a2e3d0274
--- /dev/null
+++ b/plc4j/drivers/s7/src/test/java/org/apache/plc4x/java/s7/manual/ManualS7Inventory.java
@@ -0,0 +1,301 @@
+/*
+ * 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
+ *
+ * https://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.s7.manual;
+
+import org.apache.plc4x.java.api.PlcConnection;
+import org.apache.plc4x.java.api.PlcDriverManager;
+import org.apache.plc4x.java.api.messages.PlcDiscoveryItem;
+import org.apache.plc4x.java.api.messages.PlcDiscoveryResponse;
+import org.apache.plc4x.java.api.value.PlcValue;
+import org.apache.plc4x.java.s7.S7CotpConnection;
+import org.apache.plc4x.java.s7.userdata.S7SzlService.S7DeviceIdentification;
+
+import java.io.IOException;
+import java.io.PrintWriter;
+import java.net.InetSocketAddress;
+import java.net.Socket;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.concurrent.TimeUnit;
+
+/**
+ * Manual test that builds an inventory of the Siemens S7 devices on the local network: what
+ * they are, which firmware they run and whether they are protected.
+ *
+ * <p>Two steps. First a PROFINET DCP {@code IdentifyAll} broadcast finds the S7Comm-capable
+ * devices — the same discovery {@link ManualS7Discovery} prints. DCP answers carry the station
+ * name, MAC and IP but no firmware, so the second step connects to each device over ISO-on-TCP
+ * and reads the identification system status lists (SZL {@code 0x0011}, {@code 0x001C} and
+ * {@code 0x0232}).
+ *
+ * <p><b>This actively connects to every device it finds.</b> Unlike plain discovery, which only
+ * listens for broadcast answers, this opens a TCP session to port 102 on each device. Run it
+ * only on networks you are authorised to scan. It reads nothing but identification data and
+ * changes no controller state, but it is unmistakably an active probe.
+ *
+ * <p>Requires libpcap on the host (and root/admin privileges on most platforms — pcap4j needs
+ * raw socket access). On macOS, run with {@code sudo}; on Windows, run as Administrator with
+ * Npcap installed.
+ *
+ * <p>Usage: {@code ManualS7Inventory [output.csv]} — with an argument, the inventory is also
+ * written to that file as CSV.
+ */
+public class ManualS7Inventory {
+
+ /** Rack/slot combinations to try, in order: S7-1200/1500, then S7-300, then S7-400. */
+ private static final int[] CANDIDATE_SLOTS = {0, 1, 2, 3};
+
+ /** How long to wait for port 102 before deciding a device isn't speaking ISO-on-TCP. */
+ private static final int PORT_PROBE_TIMEOUT_MS = 1_500;
+
+ private static final int READ_TIMEOUT_MS = 3_000;
+
+ public static void main(String[] args) throws Exception {
+ System.out.println("Discovering S7 devices via PROFINET DCP ...");
+ PlcDiscoveryResponse discovery = PlcDriverManager.getDefault()
+ .getDriver("s7")
+ .discoveryRequestBuilder()
+ .build()
+ .execute()
+ .get();
+
+ List<PlcDiscoveryItem> devices = discovery.getValues() == null
+ ? List.of() : discovery.getValues();
+ if (devices.isEmpty()) {
+ System.out.println("No S7-capable devices discovered.");
+ return;
+ }
+ System.out.printf("Discovered %d device(s); reading identification from each ...%n%n",
+ devices.size());
+
+ List<InventoryEntry> inventory = new ArrayList<>();
+ for (PlcDiscoveryItem device : devices) {
+ inventory.add(inventory(device));
+ }
+
+ printTable(inventory);
+ if (args.length > 0) {
+ writeCsv(inventory, Path.of(args[0]));
+ System.out.printf("%nWrote %d row(s) to %s%n", inventory.size(), args[0]);
+ }
+ }
+
+ /**
+ * Connect to one discovered device and read its identification. Never throws: a device that
+ * can't be reached still belongs in the inventory, with the reason in place of the data.
+ */
+ private static InventoryEntry inventory(PlcDiscoveryItem device) {
+ String ipAddress = attribute(device, "ipAddress");
+ String stationName = attribute(device, "deviceName");
+ String deviceType = attribute(device, "deviceTypeName");
+
+ if (ipAddress == null || ipAddress.isEmpty() || ipAddress.startsWith("0.0.0.0")) {
+ return InventoryEntry.unreachable(ipAddress, stationName, deviceType,
+ "no IP address assigned");
+ }
+ if (!isPortOpen(ipAddress)) {
+ // Devices that answer DCP but keep port 102 closed: PROFINET IO devices that
+ // aren't CPUs, or CPUs with S7 communication disabled.
+ return InventoryEntry.unreachable(ipAddress, stationName, deviceType,
+ "port 102 closed or filtered");
+ }
+ for (int slot : CANDIDATE_SLOTS) {
+ // The rack/slot parameters belong to the COTP transport, hence the prefix.
+ String url = String.format("s7://%s?cotp.remote-slot=%d&read-timeout=%d",
+ ipAddress, slot, READ_TIMEOUT_MS);
+ // getConnection() hands back an already-connected connection — connecting again
+ // would re-run the S7 handshake on a live session and fail.
+ try (PlcConnection connection = PlcDriverManager.getDefault()
+ .getConnectionFactory().getConnection(url)) {
+ if (!(connection instanceof S7CotpConnection s7Connection)) {
+ return InventoryEntry.unreachable(ipAddress, stationName, deviceType,
+ "not an S7 COTP connection");
+ }
+ S7DeviceIdentification id = s7Connection.readDeviceIdentification()
+ .get(4 * READ_TIMEOUT_MS, TimeUnit.MILLISECONDS);
+ // Connected, but every SZL was rejected — typical of LOGO and other low-end
+ // devices that don't implement the system status lists at all.
+ String note = S7DeviceIdentification.EMPTY.equals(id)
+ ? "connected on slot " + slot + " but answered no identification SZL" : null;
+ return new InventoryEntry(ipAddress, stationName, deviceType, slot, id, note);
+ } catch (Exception e) {
+ // Wrong rack/slot is the common case — the CPU refuses the COTP connection
+ // request. Try the next candidate before giving up on the device.
+ if (slot == CANDIDATE_SLOTS[CANDIDATE_SLOTS.length - 1]) {
+ return InventoryEntry.unreachable(ipAddress, stationName, deviceType,
+ "no answer on rack 0 slots 0-3 (" + rootCause(e) + ")");
+ }
+ }
+ }
+ return InventoryEntry.unreachable(ipAddress, stationName, deviceType, "not reachable");
+ }
+
+ /** Cheap pre-check so unreachable hosts don't cost four connection attempts each. */
+ private static boolean isPortOpen(String ipAddress) {
+ try (Socket socket = new Socket()) {
+ socket.connect(new InetSocketAddress(ipAddress, 102), PORT_PROBE_TIMEOUT_MS);
+ return true;
+ } catch (IOException e) {
+ return false;
+ }
+ }
+
+ private static String attribute(PlcDiscoveryItem device, String name) {
+ PlcValue value = device.getAttributes().get(name);
+ return value == null ? null : value.getString();
+ }
+
+ private static String rootCause(Throwable t) {
+ Throwable cause = t;
+ while (cause.getCause() != null && cause.getCause() != cause) {
+ cause = cause.getCause();
+ }
+ String message = cause.getMessage();
+ return message == null ? cause.getClass().getSimpleName() : message;
+ }
+
+ // ------------------------------------------------------------------------
+ // Output
+ // ------------------------------------------------------------------------
+
+ private static void printTable(List<InventoryEntry> inventory) {
+ String format = "%-15s %-20s %-22s %-10s %-10s %-18s %-12s%n";
+ System.out.printf(format,
+ "IP", "STATION", "ORDER CODE", "FIRMWARE", "HARDWARE", "SERIAL", "PROTECTION");
+ System.out.println("-".repeat(120));
+ for (InventoryEntry entry : inventory) {
+ System.out.printf(format,
+ nvl(entry.ipAddress()),
+ truncate(nvl(entry.stationName()), 20),
+ truncate(entry.orderCode(), 22),
+ entry.firmwareVersion(),
+ entry.hardwareVersion(),
+ truncate(entry.serialNumber(), 18),
+ entry.protection());
+ }
+
+ long identified = inventory.stream().filter(InventoryEntry::wasIdentified).count();
+ System.out.printf("%n%d of %d device(s) answered the identification lists.%n",
+ identified, inventory.size());
+ long unprotected = inventory.stream()
+ .filter(InventoryEntry::wasIdentified)
+ .filter(e -> Boolean.FALSE.equals(e.identification().passwordProtected()))
+ .count();
+ if (unprotected > 0) {
+ System.out.printf("%d of them report no configured protection level.%n", unprotected);
+ }
+ for (InventoryEntry entry : inventory) {
+ if (entry.failure() != null) {
+ System.out.printf(" %s: %s%n", nvl(entry.ipAddress()), entry.failure());
+ }
+ }
+ }
+
+ private static void writeCsv(List<InventoryEntry> inventory, Path path) throws IOException {
+ try (PrintWriter writer = new PrintWriter(Files.newBufferedWriter(path,
+ StandardCharsets.UTF_8))) {
+ writer.println("ip,station,device_type,slot,order_code,module_type,firmware,"
+ + "hardware,serial,plant,protection_level,password_protected,key_switch,status");
+ for (InventoryEntry entry : inventory) {
+ S7DeviceIdentification id = entry.identification();
+ writer.println(String.join(",",
+ csv(entry.ipAddress()),
+ csv(entry.stationName()),
+ csv(entry.deviceType()),
+ entry.slot() < 0 ? "" : Integer.toString(entry.slot()),
+ csv(id == null ? null : id.orderCode()),
+ csv(id == null ? null : id.moduleTypeName()),
+ csv(id == null ? null : id.firmwareVersion()),
+ csv(id == null ? null : id.hardwareVersion()),
+ csv(id == null ? null : id.serialNumber()),
+ csv(id == null ? null : id.plantDesignation()),
+ id == null || id.protectionLevel() == null
+ ? "" : Integer.toString(id.protectionLevel()),
+ id == null || id.passwordProtected() == null
+ ? "" : Boolean.toString(id.passwordProtected()),
+ csv(id == null ? null : id.keySwitchPosition()),
+ csv(entry.failure() == null ? "ok" : entry.failure())));
+ }
+ }
+ }
+
+ private static String csv(String value) {
+ if (value == null) {
+ return "";
+ }
+ return "\"" + value.replace("\"", "\"\"") + "\"";
+ }
+
+ private static String nvl(String value) {
+ return value == null || value.isEmpty() ? "-" : value;
+ }
+
+ private static String truncate(String value, int max) {
+ String text = nvl(value);
+ return text.length() <= max ? text : text.substring(0, max - 1) + "…";
+ }
+
+ /** One row of the inventory: what discovery said, plus what the device told us. */
+ private record InventoryEntry(String ipAddress, String stationName, String deviceType,
+ int slot, S7DeviceIdentification identification,
+ String failure) {
+
+ static InventoryEntry unreachable(String ipAddress, String stationName,
+ String deviceType, String reason) {
+ return new InventoryEntry(ipAddress, stationName, deviceType, -1, null, reason);
+ }
+
+ /** A device that connected but answered no SZL at all hasn't been identified. */
+ boolean wasIdentified() {
+ return identification != null && !S7DeviceIdentification.EMPTY.equals(identification);
+ }
+
+ String orderCode() {
+ return identification == null ? "-" : nvl(identification.orderCode());
+ }
+
+ String firmwareVersion() {
+ return identification == null ? "-" : nvl(identification.firmwareVersion());
+ }
+
+ String hardwareVersion() {
+ return identification == null ? "-" : nvl(identification.hardwareVersion());
+ }
+
+ String serialNumber() {
+ return identification == null ? "-" : nvl(identification.serialNumber());
+ }
+
+ /**
+ * The security-relevant summary: the protection level in force and whether a password
+ * backs it. Devices that don't implement the protection SZL report {@code "n/a"} —
+ * absence of an answer is not evidence of an unprotected CPU.
+ */
+ String protection() {
+ if (identification == null || identification.protectionLevel() == null) {
+ return "n/a";
+ }
+ return "level " + identification.protectionLevel()
+ + (Boolean.TRUE.equals(identification.passwordProtected()) ? " (pwd)" : " (no pwd)");
+ }
+ }
+}
diff --git a/plc4j/drivers/s7/src/test/java/org/apache/plc4x/java/s7/userdata/S7SzlServiceTest.java b/plc4j/drivers/s7/src/test/java/org/apache/plc4x/java/s7/userdata/S7SzlServiceTest.java
index 70d00a50fe..0a9421992f 100644
--- a/plc4j/drivers/s7/src/test/java/org/apache/plc4x/java/s7/userdata/S7SzlServiceTest.java
+++ b/plc4j/drivers/s7/src/test/java/org/apache/plc4x/java/s7/userdata/S7SzlServiceTest.java
@@ -30,6 +30,9 @@ import org.apache.plc4x.java.s7.readwrite.S7ParameterUserDataItemCPUFunctions;
import org.apache.plc4x.java.s7.readwrite.S7PayloadUserData;
import org.apache.plc4x.java.s7.readwrite.S7PayloadUserDataItem;
import org.apache.plc4x.java.s7.readwrite.S7PayloadUserDataItemCpuFunctionReadSzlResponse;
+import org.apache.plc4x.java.s7.readwrite.SzlId;
+import org.apache.plc4x.java.s7.readwrite.SzlModuleTypeClass;
+import org.apache.plc4x.java.s7.readwrite.SzlSublist;
import org.junit.jupiter.api.Test;
import java.nio.charset.StandardCharsets;
@@ -56,7 +59,7 @@ class S7SzlServiceTest {
@Test
void parseProbeResponse_decodesS71200Article() {
- S7Message response = mockSzlResponse("6ES7 212-1AE40-0XB0 ");
+ byte[] response = mockSzlResponse("6ES7 212-1AE40-0XB0 ");
S7SzlService.ProbeResult result = S7SzlService.parseProbeResponse(response);
assertEquals(ControllerType.S7_1200, result.controllerType());
assertTrue(result.articleNumber().startsWith("6ES7 2"), result.articleNumber());
@@ -85,7 +88,7 @@ class S7SzlServiceTest {
// Response payload decodes as ASCII but doesn't contain a "6ES7"/"6GK" order number
// or a "CPU NNN" model name. The response is still structurally valid — that's enough
// to mark UserData services as supported. ControllerType falls back to ANY.
- S7Message resp = mockSzlResponse("VENDORX 999 ");
+ byte[] resp = mockSzlResponse("VENDORX 999 ");
S7SzlService.ProbeResult result = S7SzlService.parseProbeResponse(resp);
assertEquals(ControllerType.ANY, result.controllerType());
assertEquals("", result.articleNumber());
@@ -93,7 +96,7 @@ class S7SzlServiceTest {
@Test
void parseProbeResponse_decodesCpuModelNameForS7300() {
- S7Message resp = mockSzlResponse("CPU 315-2 PN/DP ");
+ byte[] resp = mockSzlResponse("CPU 315-2 PN/DP ");
S7SzlService.ProbeResult result = S7SzlService.parseProbeResponse(resp);
assertEquals(ControllerType.S7_300, result.controllerType());
assertTrue(result.articleNumber().startsWith("CPU 315"), result.articleNumber());
@@ -101,14 +104,14 @@ class S7SzlServiceTest {
@Test
void parseProbeResponse_decodesCpuModelNameForS71200() {
- S7Message resp = mockSzlResponse("CPU 1212C ");
+ byte[] resp = mockSzlResponse("CPU 1212C ");
assertEquals(ControllerType.S7_1200,
S7SzlService.parseProbeResponse(resp).controllerType());
}
@Test
void parseProbeResponse_decodesCpuModelNameForS71500() {
- S7Message resp = mockSzlResponse("CPU 1511-1 PN ");
+ byte[] resp = mockSzlResponse("CPU 1511-1 PN ");
assertEquals(ControllerType.S7_1500,
S7SzlService.parseProbeResponse(resp).controllerType());
}
@@ -123,30 +126,335 @@ class S7SzlServiceTest {
void parseProbeResponse_acceptsZeroFilledItemAsAny() {
// Empty/zeroed item is structurally valid — the probe succeeds with an empty
// article and ANY controllerType. The connection treats that as "UserData works".
- S7Message resp = wrapInUserData(new S7PayloadUserDataItemCpuFunctionReadSzlResponse(
- DataTransportErrorCode.OK, DataTransportSize.OCTET_STRING, 0x10, new byte[16]));
- S7SzlService.ProbeResult result = S7SzlService.parseProbeResponse(resp);
+ S7SzlService.ProbeResult result = S7SzlService.parseProbeResponse(new byte[16]);
assertEquals(ControllerType.ANY, result.controllerType());
assertEquals("", result.articleNumber());
}
@Test
- void parseProbeResponse_rejectsMissingSzlItem() {
+ void szlDataOf_rejectsMissingSzlItem() {
S7Message resp = new S7MessageUserData(7,
new S7ParameterUserData(Collections.emptyList()),
new S7PayloadUserData(Collections.emptyList()));
- assertThrows(IllegalStateException.class, () -> S7SzlService.parseProbeResponse(resp));
+ assertThrows(IllegalStateException.class, () -> S7SzlService.szlDataOf(resp));
}
@Test
- void parseProbeResponse_rejectsNonUserDataMessage() {
+ void szlDataOf_rejectsNonUserDataMessage() {
S7Message reqMessage = new S7MessageRequest(1, null, null);
assertThrows(IllegalArgumentException.class,
- () -> S7SzlService.parseProbeResponse(reqMessage));
+ () -> S7SzlService.szlDataOf(reqMessage));
+ }
+
+ @Test
+ void szlDataOf_returnsTheRawDataSection() {
+ byte[] data = {0x00, 0x11, 0x00, 0x00, 0x00, 0x1C, 0x00, 0x01};
+ assertArrayEquals(data, S7SzlService.szlDataOf(szlMessage(data, 0, 0)));
+ }
+
+ // ------------------------------------------------------------------------
+ // Full device identification (SZL 0x0011 / 0x001C / 0x0232)
+ // ------------------------------------------------------------------------
+
+ @Test
+ void protectionStatusSzlIdEncodesTo0232() {
+ SzlId id = S7SzlService.PROTECTION_STATUS;
+ assertEquals(SzlModuleTypeClass.CPU, id.getTypeClass());
+ assertEquals(0x02, id.getSublistExtract());
+ assertEquals(SzlSublist.COMMUNICATION_STATUS_DATA, id.getSublistList());
+ }
+
+ @Test
+ void parseModuleIdentification_extractsOrderCode() {
+ byte[] resp = szlResponse(0x0011, 0x0000, 28,
+ moduleRecord(1, "6ES7 511-1AK02-0AB0", 5, 1, 2),
+ moduleRecord(6, "6ES7 511-1AK02-0AB0", 1, 0, 0),
+ moduleRecord(7, "6ES7 511-1AK02-0AB0", 2, 6, 0));
+ assertEquals("6ES7 511-1AK02-0AB0",
+ S7SzlService.parseModuleIdentification(resp).orderCode());
+ }
+
+ @Test
+ void parseModuleIdentification_extractsFirmwareVersionFromRecordSeven() {
+ byte[] resp = szlResponse(0x0011, 0x0000, 28,
+ moduleRecord(1, "6ES7 511-1AK02-0AB0", 5, 1, 2),
+ moduleRecord(7, "6ES7 511-1AK02-0AB0", 2, 6, 0));
+ assertEquals("V 2.6.0",
+ S7SzlService.parseModuleIdentification(resp).firmwareVersion());
+ }
+
+ @Test
+ void parseModuleIdentification_extractsHardwareVersionFromRecordSix() {
+ byte[] resp = szlResponse(0x0011, 0x0000, 28,
+ moduleRecord(6, "6ES7 511-1AK02-0AB0", 1, 0, 0));
+ assertEquals("V 1.0.0",
+ S7SzlService.parseModuleIdentification(resp).hardwareVersion());
+ }
+
+ @Test
+ void parseModuleIdentification_leavesFirmwareNullWhenRecordAbsent() {
+ byte[] resp = szlResponse(0x0011, 0x0000, 28,
+ moduleRecord(1, "6ES7 314-6CH04-0AB0", 3, 3, 0));
+ assertNull(S7SzlService.parseModuleIdentification(resp).firmwareVersion());
+ }
+
+ @Test
+ void parseComponentIdentification_extractsSystemAndModuleName() {
+ byte[] resp = szlResponse(0x001C, 0x0000, 34,
+ componentRecord(1, "PLANT-LINE-3"),
+ componentRecord(2, "PLC_1"));
+ S7SzlService.S7DeviceIdentification id = S7SzlService.parseComponentIdentification(resp);
+ assertEquals("PLANT-LINE-3", id.systemName());
+ assertEquals("PLC_1", id.moduleName());
+ }
+
+ @Test
+ void parseComponentIdentification_extractsSerialNumberAndPlantDesignation() {
+ byte[] resp = szlResponse(0x001C, 0x0000, 34,
+ componentRecord(3, "Wall-Mounted Demo Rig"),
+ componentRecord(5, "S C-J2UD57132018"));
+ S7SzlService.S7DeviceIdentification id = S7SzlService.parseComponentIdentification(resp);
+ assertEquals("Wall-Mounted Demo Rig", id.plantDesignation());
+ assertEquals("S C-J2UD57132018", id.serialNumber());
+ }
+
+ @Test
+ void parseComponentIdentification_extractsModuleTypeName() {
+ byte[] resp = szlResponse(0x001C, 0x0000, 34,
+ componentRecord(7, "CPU 1511-1 PN"));
+ assertEquals("CPU 1511-1 PN",
+ S7SzlService.parseComponentIdentification(resp).moduleTypeName());
+ }
+
+ @Test
+ void parseProtectionStatus_reportsConfiguredProtectionLevel() {
+ // sch_schal=0 (no selector), sch_par=2 (password parameterised), sch_rel=2 (level in
+ // force), bart_sch=2 (RUN-P), anl_sch=0.
+ byte[] resp = szlResponse(0x0232, 0x0004, 12, protectionRecord(0, 2, 2, 2, 0));
+ S7SzlService.S7DeviceIdentification id = S7SzlService.parseProtectionStatus(resp);
+ assertEquals(Integer.valueOf(2), id.protectionLevel());
+ assertEquals(Boolean.TRUE, id.passwordProtected());
+ assertEquals("RUN-P", id.keySwitchPosition());
+ }
+
+ @Test
+ void parseProtectionStatus_reportsCpuWithoutPassword() {
+ // sch_par=0 means no protection level was parameterised, i.e. no password is set.
+ byte[] resp = szlResponse(0x0232, 0x0004, 12, protectionRecord(0, 0, 1, 1, 0));
+ S7SzlService.S7DeviceIdentification id = S7SzlService.parseProtectionStatus(resp);
+ assertEquals(Integer.valueOf(1), id.protectionLevel());
+ assertEquals(Boolean.FALSE, id.passwordProtected());
+ assertEquals("RUN", id.keySwitchPosition());
+ }
+
+ @Test
+ void parseProtectionStatus_reportsUnknownKeySwitchPosition() {
+ byte[] resp = szlResponse(0x0232, 0x0004, 12, protectionRecord(0, 0, 3, 0, 0));
+ assertEquals("unknown",
+ S7SzlService.parseProtectionStatus(resp).keySwitchPosition());
+ }
+
+ @Test
+ void szlDataOf_rejectsResponseWithNonZeroErrorCode() {
+ S7Message resp = szlResponseWithErrorCode(0xD401);
+ assertThrows(IllegalStateException.class, () -> S7SzlService.szlDataOf(resp));
+ }
+
+ @Test
+ void parseIdentification_rejectsTruncatedResponse() {
+ assertThrows(IllegalStateException.class,
+ () -> S7SzlService.parseModuleIdentification(new byte[4]));
+ }
+
+ @Test
+ void parseIdentification_ignoresRecordsTruncatedByThePlc() {
+ // Declared count of 2 records but only one record's worth of bytes on the wire.
+ // The parser must use what arrived rather than reading past the end of the array.
+ byte[] header = {0x00, 0x11, 0x00, 0x00, 0x00, 28, 0x00, 0x02};
+ byte[] record = moduleRecord(7, "6ES7 511-1AK02-0AB0", 2, 6, 0);
+ byte[] data = new byte[header.length + record.length];
+ System.arraycopy(header, 0, data, 0, header.length);
+ System.arraycopy(record, 0, data, header.length, record.length);
+ assertEquals("V 2.6.0", S7SzlService.parseModuleIdentification(data).firmwareVersion());
+ }
+
+ @Test
+ void mergedWith_fillsNullFieldsFromTheOtherIdentification() {
+ S7SzlService.S7DeviceIdentification module = S7SzlService.parseModuleIdentification(
+ szlResponse(0x0011, 0x0000, 28, moduleRecord(7, "6ES7 511-1AK02-0AB0", 2, 6, 0)));
+ S7SzlService.S7DeviceIdentification component = S7SzlService.parseComponentIdentification(
+ szlResponse(0x001C, 0x0000, 34, componentRecord(2, "PLC_1")));
+
+ S7SzlService.S7DeviceIdentification merged = module.mergedWith(component);
+
+ assertEquals("V 2.6.0", merged.firmwareVersion());
+ assertEquals("PLC_1", merged.moduleName());
+ }
+
+ @Test
+ void mergedWith_keepsOwnValueWhenBothAreSet() {
+ S7SzlService.S7DeviceIdentification first = S7SzlService.parseComponentIdentification(
+ szlResponse(0x001C, 0x0000, 34, componentRecord(2, "PLC_1")));
+ S7SzlService.S7DeviceIdentification second = S7SzlService.parseComponentIdentification(
+ szlResponse(0x001C, 0x0000, 34, componentRecord(2, "PLC_2")));
+ assertEquals("PLC_1", first.mergedWith(second).moduleName());
+ }
+
+ @Test
+ void mergedWith_toleratesNullOther() {
+ S7SzlService.S7DeviceIdentification id = S7SzlService.parseComponentIdentification(
+ szlResponse(0x001C, 0x0000, 34, componentRecord(2, "PLC_1")));
+ assertEquals("PLC_1", id.mergedWith(null).moduleName());
+ }
+
+ // ------------------------------------------------------------------------
+ // Chained (multi-part) SZL responses
+ // ------------------------------------------------------------------------
+
+ @Test
+ void moreDataFollows_isTrueWhenTheResponseSetsLastDataUnit() {
+ assertTrue(S7SzlService.moreDataFollows(szlMessage(new byte[8], 1, 1)));
+ }
+
+ @Test
+ void moreDataFollows_isFalseWhenTheResponseIsComplete() {
+ assertFalse(S7SzlService.moreDataFollows(szlMessage(new byte[8], 0, 1)));
+ }
+
+ @Test
+ void moreDataFollows_isFalseWhenTheParameterOmitsTheFlag() {
+ S7ParameterUserDataItem param = new S7ParameterUserDataItemCPUFunctions(
+ (short) 0x12, (byte) 0x08, (byte) 0x04, (short) 0x01, (short) 0x00, null, null, null);
+ S7Message resp = new S7MessageUserData(1,
+ new S7ParameterUserData(Collections.singletonList(param)),
+ new S7PayloadUserData(Collections.emptyList()));
+ assertFalse(S7SzlService.moreDataFollows(resp));
+ }
+
+ @Test
+ void sequenceNumberOf_returnsTheSequenceThePlcAssigned() {
+ assertEquals(7, S7SzlService.sequenceNumberOf(szlMessage(new byte[8], 1, 7)));
+ }
+
+ @Test
+ void buildContinuationRequest_echoesTheSequenceNumber() {
+ S7Message msg = S7SzlService.buildContinuationRequest(
+ 42, S7SzlService.COMPONENT_IDENTIFICATION, 0x0000, 7);
+ S7ParameterUserDataItemCPUFunctions item = (S7ParameterUserDataItemCPUFunctions)
+ ((S7ParameterUserData) msg.getParameter()).getItems().get(0);
+ assertEquals(7, item.getSequenceNumber());
+ // Still a ReadSZL request — only the sequence number distinguishes it from the first.
+ assertEquals(0x04, item.getCpuFunctionGroup());
+ assertEquals(0x04, item.getCpuFunctionType());
+ assertEquals(0x01, item.getCpuSubfunction());
+ }
+
+ /**
+ * A chained response splits records at the PDU boundary, so the second chunk carries no
+ * header of its own and can start in the middle of a record. Parsing the concatenation has
+ * to recover the record that straddles the boundary.
+ */
+ @Test
+ void parseComponentIdentification_readsRecordSplitAcrossChunkBoundary() {
+ byte[] whole = szlResponse(0x001C, 0x0000, 34,
+ componentRecord(1, "PLANT-LINE-3"),
+ componentRecord(5, "S C-J2UD57132018"));
+ // Cut mid-way through the second record, as the PLC does at the PDU boundary.
+ int cut = 8 + 34 + 20;
+ byte[] firstChunk = Arrays.copyOfRange(whole, 0, cut);
+ byte[] secondChunk = Arrays.copyOfRange(whole, cut, whole.length);
+
+ byte[] assembled = new byte[firstChunk.length + secondChunk.length];
+ System.arraycopy(firstChunk, 0, assembled, 0, firstChunk.length);
+ System.arraycopy(secondChunk, 0, assembled, firstChunk.length, secondChunk.length);
+
+ assertEquals("S C-J2UD57132018",
+ S7SzlService.parseComponentIdentification(assembled).serialNumber());
+ }
+
+ /** A ReadSZL response carrying {@code data}, with the given lastDataUnit and sequence. */
+ private static S7Message szlMessage(byte[] data, int lastDataUnit, int sequenceNumber) {
+ S7ParameterUserDataItem param = new S7ParameterUserDataItemCPUFunctions(
+ (short) 0x12, (byte) 0x08, (byte) 0x04, (short) 0x01,
+ (short) sequenceNumber, (short) 0x00, (short) lastDataUnit, 0);
+ return new S7MessageUserData(1,
+ new S7ParameterUserData(Collections.singletonList(param)),
+ new S7PayloadUserData(Collections.singletonList(
+ new S7PayloadUserDataItemCpuFunctionReadSzlResponse(
+ DataTransportErrorCode.OK, DataTransportSize.OCTET_STRING,
+ data.length, data))));
+ }
+
+ /** SZL 0x0011 record: index(2) + MLFB(20) + BGTyp(2) + Ausbg(2) + Ausbe(2). */
+ private static byte[] moduleRecord(int index, String mlfb, int v1, int v2, int v3) {
+ byte[] record = new byte[28];
+ record[0] = (byte) (index >> 8);
+ record[1] = (byte) index;
+ byte[] mlfbBytes = mlfb.getBytes(StandardCharsets.US_ASCII);
+ System.arraycopy(mlfbBytes, 0, record, 2, Math.min(mlfbBytes.length, 20));
+ for (int i = 2 + Math.min(mlfbBytes.length, 20); i < 22; i++) {
+ record[i] = ' ';
+ }
+ // Snap7 and nmap both read the version as the record's trailing three bytes:
+ // Ausbg's low byte followed by Ausbe.
+ record[25] = (byte) v1;
+ record[26] = (byte) v2;
+ record[27] = (byte) v3;
+ return record;
+ }
+
+ /** SZL 0x001C record: index(2) + 32 ASCII bytes. */
+ private static byte[] componentRecord(int index, String value) {
+ byte[] record = new byte[34];
+ record[0] = (byte) (index >> 8);
+ record[1] = (byte) index;
+ byte[] valueBytes = value.getBytes(StandardCharsets.US_ASCII);
+ System.arraycopy(valueBytes, 0, record, 2, Math.min(valueBytes.length, 32));
+ for (int i = 2 + Math.min(valueBytes.length, 32); i < 34; i++) {
+ record[i] = ' ';
+ }
+ return record;
+ }
+
+ /** SZL 0x0232 index 4 record: index, sch_schal, sch_par, sch_rel, bart_sch, anl_sch. */
+ private static byte[] protectionRecord(int schSchal, int schPar, int schRel,
+ int bartSch, int anlSch) {
+ return words(0x0004, schSchal, schPar, schRel, bartSch, anlSch);
+ }
+
+ private static byte[] words(int... values) {
+ byte[] out = new byte[values.length * 2];
+ for (int i = 0; i < values.length; i++) {
+ out[i * 2] = (byte) (values[i] >> 8);
+ out[i * 2 + 1] = (byte) values[i];
+ }
+ return out;
+ }
+
+ /** Wrap records in the 8-byte SZL data header the PLC prefixes them with. */
+ private static byte[] szlResponse(int szlId, int szlIndex, int recordLength,
+ byte[]... records) {
+ byte[] data = new byte[8 + records.length * recordLength];
+ byte[] header = words(szlId, szlIndex, recordLength, records.length);
+ System.arraycopy(header, 0, data, 0, 8);
+ for (int i = 0; i < records.length; i++) {
+ System.arraycopy(records[i], 0, data, 8 + i * recordLength,
+ Math.min(records[i].length, recordLength));
+ }
+ return data;
+ }
+
+ private static S7Message szlResponseWithErrorCode(int errorCode) {
+ S7ParameterUserDataItem param = new S7ParameterUserDataItemCPUFunctions(
+ (short) 0x12, (byte) 0x08, (byte) 0x04, (short) 0x01,
+ (short) 0x00, null, null, errorCode);
+ return new S7MessageUserData(1,
+ new S7ParameterUserData(Collections.singletonList(param)),
+ new S7PayloadUserData(Collections.emptyList()));
}
- /** Build a 22-byte SZL item: 2 bytes header + 20-byte article-number window. */
- private static S7Message mockSzlResponse(String article) {
+ /** Build a 22-byte SZL data section: 2 bytes header + 20-byte article-number window. */
+ private static byte[] mockSzlResponse(String article) {
byte[] articleBytes = article.getBytes(StandardCharsets.US_ASCII);
byte[] szlItem = new byte[22];
// Bytes 0..1 are the 2-byte index header — opaque to us. Bytes 2..21 hold the MLFB.
@@ -156,8 +464,7 @@ class S7SzlServiceTest {
for (int i = 2 + copyLen; i < 22; i++) {
szlItem[i] = ' ';
}
- return wrapInUserData(new S7PayloadUserDataItemCpuFunctionReadSzlResponse(
- DataTransportErrorCode.OK, DataTransportSize.OCTET_STRING, szlItem.length, szlItem));
+ return szlItem;
}
private static S7Message wrapInUserData(S7PayloadUserDataItem item) {