SoE (Servo over EtherCAT)
The SoE protocol carries the SERCOS servo communication protocol inside the EtherCAT mailbox; it applies to SERCOS-compatible servo drives.
Accessed through slave.soe().
Most EtherCAT servo drives use the CoE + CiA 402 protocol stack. SoE is used only with SERCOS-compatible drives (such as the Bosch Rexroth IndraDrive series). The two cannot be mixed — which one a slave supports depends on the hardware.
Method overview
| Category | Method | Type | Read/write | Description |
|---|---|---|---|---|
| Basic read/write | read(short idn) | byte[] | read-only | Reads the IDN data value element (0x40) with a 500 ms timeout; returns null on failure |
| Basic read/write | read(short idn, byte elementFlags, int timeoutMs) | byte[] | read-only | Reads any element by element flags; returns null on failure |
| Basic read/write | write(short idn, byte[] data) | boolean | write-only | Writes the IDN data value element (0x40); empty data returns false immediately |
| Basic read/write | write(short idn, byte[] data, byte elementFlags, int timeoutMs) | boolean | write-only | Writes by element flags; returns false on failure |
| Asynchronous | readAsync(short idn) / readAsync(short idn, byte elementFlags, int timeoutMs) | CompletableFuture<byte[]> | read-only | Asynchronous read; completes with SoEProtocolException on failure |
| Asynchronous | writeAsync(short idn, byte[] data) / writeAsync(short idn, byte[] data, byte elementFlags, int timeoutMs) | CompletableFuture<Boolean> | write-only | Asynchronous write; completes with SoEProtocolException on failure |
| Typed reads | readInt16(short idn) / readInt16(short idn, byte elementFlags, int timeoutMs) | Short | read-only | 16-bit signed integer; returns null when the data is too short |
| Typed reads | readInt32(short idn) / readInt32(short idn, byte elementFlags, int timeoutMs) | Integer | read-only | 32-bit signed integer; returns null when the data is too short |
| Typed reads | readUInt16(short idn) | Integer | read-only | 16-bit unsigned integer (0..65535) |
| Typed reads | readUInt32(short idn) | Long | read-only | 32-bit unsigned integer (0..4294967295) |
| Typed reads | readFloat(short idn) | Float | read-only | Single-precision float (requires 4 bytes) |
| Typed reads | readDouble(short idn) | Double | read-only | Double-precision float (requires 8 bytes) |
| Typed reads | readString(short idn) | String | read-only | String, truncated at 0x00 |
| Typed writes | writeInt16(short idn, short value) | boolean | write-only | Writes a 16-bit signed integer |
| Typed writes | writeInt32(short idn, int value) | boolean | write-only | Writes a 32-bit signed integer |
| Typed writes | writeUInt16(short idn, int value) | boolean | write-only | Writes a 16-bit unsigned integer; out of range throws IllegalArgumentException |
| Typed writes | writeUInt32(short idn, long value) | boolean | write-only | Writes a 32-bit unsigned integer; out of range throws IllegalArgumentException |
| Metadata | readName(short idn) / readName(short idn, int timeoutMs) | String | read-only | Parameter name (element 0x02); returns null on failure |
| Metadata | readUnit(short idn) / readUnit(short idn, int timeoutMs) | String | read-only | Parameter unit (element 0x08); returns null on failure |
| Metadata | readMinValue(short idn) | byte[] | read-only | Minimum value (element 0x10) |
| Metadata | readMaxValue(short idn) | byte[] | read-only | Maximum value (element 0x20) |
| Metadata | readDefaultValue(short idn) | byte[] | read-only | Default value (element 0x80) |
| Metadata | readDataState(short idn) / readDataState(short idn, int timeoutMs) | Integer | read-only | Data state (element 0x01) |
| Parameter information | getAvailableIDNs() / getAvailableIDNs(int timeoutMs) | List<Short> | read-only | List of IDN supported by the slave; throws SoEProtocolException if the read fails |
| Parameter information | getParameterInfo(short idn) / getParameterInfo(short idn, int timeoutMs) | SoEParameter | read-only | Summary of name, unit, value and minimum / maximum / default value |
| Parameter information | readParameter(short idn) / readParameter(short idn, int timeoutMs) | SoEParameter | read-only | Equivalent to getParameterInfo |
| Parameter information | writeParameter(short idn, byte[] value) / writeParameter(short idn, byte[] value, int timeoutMs) | boolean | write-only | Writes the data value element; empty data throws IllegalArgumentException |
| Batch | readAllParameters() / readAllParameters(int timeoutMs) | List<SoEParameter> | read-only | Batch-reads a fixed set of 18 common IDN and returns only the ones actually read |
| Batch | lastBatchReadSummary() | SoEBatchReadSummary | read-only | Success and failure breakdown of the most recent batch read (null if no batch read has run) |
| Procedure commands | executeCommand(short idn) / executeCommand(short idn, int timeoutMs, int pollIntervalMs) | boolean | write-only | Triggers a procedure command and polls until it completes |
| AT/MDT mapping | getIDNMapping() / getIDNMapping(int timeoutMs) | ServoMappingInfo | read-only | Reads the AT/MDT mapping; throws SoEProtocolException on failure |
| AT/MDT mapping | getAllDriveMappings() / getAllDriveMappings(int timeoutMs) | Map<Byte, ServoMappingInfo> | read-only | Scans the mapping of drives 0–7 one by one |
| Change notifications | addNotificationListener(listener) | void | write-only | Registers a parameter change callback (no unregister entry point) |
| Change notifications | enableNotification(short idn) / enableNotification(short idn, int timeoutMs) | boolean | write-only | Requests a hardware notification and registers monitoring; returns whether the request succeeded |
| Change notifications | disableNotification(short idn) | void | write-only | Stops monitoring a single IDN |
| Change notifications | disableAllNotifications() | void | write-only | Stops all monitoring |
| Change notifications | getMonitoredIDNs() | List<Short> | read-only | Snapshot of the IDN currently monitored |
| Change notifications | pollNotifications() / pollNotifications(int timeoutMs) | int | read-only | Polls for changes and fires the callbacks; returns the number of changes |
| Emergency | addEmergencyListener(listener) | void | write-only | Registers an Emergency callback |
| Emergency | removeEmergencyListener(listener) | void | write-only | Removes the specified Emergency callback |
| Status | getLastStatus() | MailboxStatus | read-only | Status of the most recent mailbox transaction |
| Status | getLastErrorCode() | long | read-only | Most recent SoE error code (0 = no error) |
| Status | getLastSoEError() | SoEError | read-only | Most recent error enum (null when there is no error) |
| Statistics | getStatistics() | MailboxStatistics | read-only | Mailbox statistics snapshot |
| Statistics | resetStatistics() | void | write-only | Resets the statistics and clears the most recent status |
| Protocol capability | getProtocolType() | byte | read-only | Protocol type constant 0x05 |
| Protocol capability | getProtocolName() | String | read-only | Protocol name "SoE" |
| Protocol capability | isSupported() | boolean | read-only | Whether SoE is supported; an unknown capability is treated as unsupported |
| Protocol capability | supportState() | Boolean | read-only | Tri-state: TRUE supported / FALSE confirmed unsupported / null unknown |
| Protocol capability | isSupportKnown() | boolean | read-only | Whether the capability verdict is known |
| IDN helpers | encodeIdn(boolean isStandard, byte parameterSet, short dataBlock) | short | — | Encodes a triple into a 16-bit IDN |
| IDN helpers | decodeIdn(short idn) | IdnTriple | — | Decodes a 16-bit IDN into a triple |
| IDN helpers | tryParseSercosIdn(String text) | Short | — | Parses the S-0-0040 form; invalid input returns null |
| Formatting | formatByteArray(byte[] data) | String | — | Formats bytes as hexadecimal text |
| Formatting | formatByteArray(byte[] data, int dataType) | String | — | Formats according to the data type |
By default read / write access the data value element and wait 500 ms; to read other elements such as the name or unit, use the overload that takes elementFlags and timeoutMs. Every read and write updates getLastStatus() / getLastErrorCode() / getLastSoEError(); use them to tell "the parameter does not exist" apart from "no response".
Obtaining an instance
public SoE(short masterIndex, short slaveIndex)
public SoE(short masterIndex, short slaveIndex, byte driveNumber)
slave.soe() returns the SoE instance of that slave (repeated calls on the same slave return the same instance) and corresponds to driveNumber = 0. When a single slave hosts several SERCOS drives, use the three-argument constructor to select drive 0 – 7; the remaining methods behave the same.
import com.darra.ethercat.master.EtherCATMaster;
import com.darra.ethercat.slave.Slave;
import com.darra.ethercat.slave.SoE;
EtherCATMaster.BuildResult r = EtherCATMaster.create()
.setENI("C:/EtherCAT/MyProject.deni")
.build();
if (!r.success) { // Judge success by success only: with 0 slaves success is also false, but master still points to the current instance; when configuration or file reading fails, master is null
System.out.println("构建失败: " + r.message); // (SDK output, = Build failed: )
return;
}
EtherCATMaster master = r.master;
// The DENI path does not populate the slave list: construct the slave object directly from the master index + station number
Slave servo = new Slave(master.MasterIndex, (short) 1, master);
SoE soe = servo.soe();
SoE is one of the mailbox protocols; the protocol type constant is 0x05 and the protocol name is "SoE".
The SERCOS IDN scheme
SoE addresses drive parameters through the IDN (Identification Number). Each IDN is a 16-bit number that stands for one parameter (position, velocity, control word, and so on). The bit layout is fixed:
| Bit | Meaning |
|---|---|
| bit15 | 0 = standard parameter (S-x-xxxx), 1 = product / vendor parameter (P-x-xxxx) |
| bit14 – bit12 | Parameter set (ParameterSet, 0 – 7) |
| bit11 – bit0 | Data block (DataBlock, 0 – 4095) |
encodeIdn(...) / decodeIdn(...) are the encode and decode entry points for these 16 bits; SoEParameter.sercosIDN() prints the IDN as S-x-xxxx / P-x-xxxx, and SoEParameter.category() gives the category.
IDN naming rules:
| Prefix | Range | category() | Description |
|---|---|---|---|
| S-x-xxxx | 0x0000 – 0x7FFF | Standard | SERCOS standard parameters (common to all vendors) |
| P-x-xxxx | 0x8000 – 0xBFFF | Product | Product-specific parameters |
| P-x-xxxx | 0xC000 – 0xFFFF | Vendor | Vendor-defined parameters |
IDN constants provided by the SDK (SoE.StandardIDN) and the IDN used in this page's examples:
| IDN | Constant | Value | Description | Data type |
|---|---|---|---|---|
| S-0-0000 | StandardIDN.IDN_LIST | 0x0000 | IDN list placeholder number | — |
| S-0-0001 | StandardIDN.CYCLE_TIME | 0x0001 | Communication cycle time | uint, us |
| S-0-0016 | StandardIDN.AT_CONFIG | 0x0010 | AT (slave → master) mapping configuration list; getIDNMapping() reads it | list |
| S-0-0024 | StandardIDN.MDT_CONFIG | 0x0018 | MDT (master → slave) mapping configuration list; getIDNMapping() reads it | list |
| S-0-0127 | StandardIDN.NOTIFICATION_REQUEST | 0x007F | Notification request; enableNotification() writes it | ushort |
| S-0-0047 | — | 0x002F | Position command value | int, inc |
| S-0-0148 | — | 0x0094 | Homing procedure command | command |
The meaning and data type of a specific IDN are defined by the servo device manual (parameter number spaces are not fully identical between vendors).
Element flags — reading different "layers" of an IDN:
| Flag | Meaning |
|---|---|
| 0x01 | Data state |
| 0x02 | Parameter name (string) |
| 0x04 | Attributes (data type / length / permission bitfield) |
| 0x08 | Unit (string) |
| 0x10 | Minimum value |
| 0x20 | Maximum value |
| 0x40 | Data value (default, most common) |
| 0x80 | Default value |
Basic read and write
read(short idn, byte elementFlags, int timeoutMs)
public byte[] read(short idn)
public byte[] read(short idn, byte elementFlags, int timeoutMs)
Reads the raw bytes of an IDN parameter.
Parameters:
idn(short) — IDN numberelementFlags(byte) — element flags (default 0x40 = data value)timeoutMs(int) — timeout in milliseconds (default 500)
Returns:
byte[]— the data read (little-endian, low byte first); returnsnullon failure
When the call returns null, use getLastStatus() / getLastErrorCode() to tell the causes apart: TIMEOUT means the slave did not answer within the timeout, MAILBOX_ERROR means an error response was received. Do not treat every null as "the parameter does not exist". Runtime exceptions thrown by the underlying call propagate unchanged (the failure status has already been recorded before they propagate) and are not folded into null.
Example:
// Read the communication cycle time (S-0-0001)
byte[] data = slave.soe().read((short) 0x0001);
if (data != null) {
int cycleTime = (data[0] & 0xFF) | ((data[1] & 0xFF) << 8)
| ((data[2] & 0xFF) << 16) | ((data[3] & 0xFF) << 24);
System.out.printf("周期时间: %d us%n", cycleTime); // Cycle time: %d us%n
}
write(short idn, byte[] data, byte elementFlags, int timeoutMs)
public boolean write(short idn, byte[] data)
public boolean write(short idn, byte[] data, byte elementFlags, int timeoutMs)
Writes an IDN parameter.
Parameters:
idn(short) — IDN numberdata(byte[]) — the data to writeelementFlags(byte) — element flags (default 0x40 = data value)timeoutMs(int) — timeout in milliseconds (default 500)
Returns:
boolean—truewhen the write succeeds,falseon failure
When data is null or has length 0, the method returns false directly and getLastStatus() is INVALID_ARG (this is a call error, not a write failure). Runtime exceptions thrown by the underlying call propagate unchanged and are not folded into false.
Asynchronous read and write
public CompletableFuture<byte[]> readAsync(short idn)
public CompletableFuture<byte[]> readAsync(short idn, byte elementFlags, int timeoutMs)
public CompletableFuture<Boolean> writeAsync(short idn, byte[] data)
public CompletableFuture<Boolean> writeAsync(short idn, byte[] data, byte elementFlags, int timeoutMs)
Asynchronous IDN read and write, running on the SDK's background executor; on failure the returned CompletableFuture completes exceptionally with SoEProtocolException (carrying the SoEError error code). The parameters match the synchronous versions: the exception path applies exactly when the synchronous version would return null / false, and runtime exceptions thrown directly by the underlying call propagate outward as well. When receiving them through exceptionally / handle, the exception is wrapped in a CompletionException; use getCause() to inspect it.
Example:
slave.soe().readAsync((short) 0x0001)
.thenAccept(data -> System.out.printf("周期: %d us%n", // Cycle: %d us%n
(data[0] & 0xFF) | ((data[1] & 0xFF) << 8)
| ((data[2] & 0xFF) << 16) | ((data[3] & 0xFF) << 24)))
.exceptionally(ex -> {
if (ex.getCause() instanceof SoE.SoEProtocolException) {
SoE.SoEProtocolException se = (SoE.SoEProtocolException) ex.getCause();
System.err.println("SoE 读取失败: " + se.errorCode); // SoE read failed:
}
return null;
});
Typed reads
Typed reads decode the raw bytes as little-endian, saving hand-written byte shifts:
| Method | Return type | Description |
|---|---|---|
readInt16(short idn) / readInt16(short idn, byte elementFlags, int timeoutMs) | Short | Reads a 16-bit signed integer |
readInt32(short idn) / readInt32(short idn, byte elementFlags, int timeoutMs) | Integer | Reads a 32-bit signed integer |
readUInt16(short idn) | Integer | Reads a 16-bit unsigned integer (0..65535) |
readUInt32(short idn) | Long | Reads a 32-bit unsigned integer (0..4294967295) |
readFloat(short idn) | Float | Reads a single-precision float (requires 4 bytes) |
readDouble(short idn) | Double | Reads a double-precision float (requires 8 bytes) |
readString(short idn) | String | Reads a string |
Only readInt16 / readInt32 have elementFlags / timeoutMs overloads; the rest always read the data value element (0x40) with a 500 ms timeout.
Returns: null when the read fails; also null when the bytes read are too few to decode (fewer than 2 / 4 / 8 bytes), with no exception thrown. readString truncates at the first 0x00 and decodes with the JVM default charset — when the encoding must be deterministic, use read(idn) to get the raw bytes and decode them yourself; for parameter names and units use readName / readUnit.
Example:
SoE soe = slave.soe();
// S-0-0047 position command value (32-bit signed)
Integer pos = soe.readInt32((short) 0x002F);
// Read the same IDN as a 16-bit unsigned value
Integer word = soe.readUInt16((short) 0x002F);
// Overload with custom element flags and timeout
Short raw = soe.readInt16((short) 0x002F, SoE.SoEElementFlags.MIN, 1000);
Typed writes
Typed writes encode the scalar as little-endian and write it to the data value element (0x40) with a 500 ms timeout; the return value means the same as in write:
| Method | Parameter type | Description |
|---|---|---|
writeInt16(short idn, short value) | short | Writes a 16-bit signed integer |
writeInt32(short idn, int value) | int | Writes a 32-bit signed integer |
writeUInt16(short idn, int value) | int | Writes a 16-bit unsigned integer |
writeUInt32(short idn, long value) | long | Writes a 32-bit unsigned integer |
Typed writes have no elementFlags / timeoutMs overloads; to write a different element, use write(short idn, byte[] data, byte elementFlags, int timeoutMs).
Throws:
| Method | Exception | Trigger condition |
|---|---|---|
writeUInt16 | IllegalArgumentException | value is outside 0..65535 |
writeUInt32 | IllegalArgumentException | value is outside 0..4294967295 |
Unsigned writes never truncate silently; out-of-range values are rejected outright.
Example:
SoE soe = slave.soe();
// S-0-0047 position command value
if (!soe.writeInt32((short) 0x002F, 50000)) {
System.err.println("写入失败: " + soe.getLastStatus()); // Write failed:
}
// Out-of-range unsigned values are rejected outright and never truncated
try {
soe.writeUInt16((short) 0x0001, 70000);
} catch (IllegalArgumentException ex) {
System.err.println("取值超出 uint16: " + ex.getMessage()); // Value exceeds uint16: {ex.getMessage()}
}
Metadata reads
readName(short idn)
public String readName(short idn)
public String readName(short idn, int timeoutMs)
Reads the IDN parameter name (using ElementFlag 0x02).
Returns: String — the parameter name; returns null on failure. The string is decoded by trying strict UTF-8 → ASCII → Latin-1 in that order and is truncated at 0x00. The default timeout is 500 ms.
readUnit(short idn)
public String readUnit(short idn)
public String readUnit(short idn, int timeoutMs)
Reads the IDN parameter unit (using ElementFlag 0x08). The return value and decoding rules are the same as readName.
readMinValue / readMaxValue / readDefaultValue
public byte[] readMinValue(short idn)
public byte[] readMaxValue(short idn)
public byte[] readDefaultValue(short idn)
Reads the minimum value (0x10), maximum value (0x20) and default value (0x80) of an IDN parameter. Returns the raw bytes, and null on failure; these three methods have no timeout overload and always use 500 ms.
readDataState(short idn)
public Integer readDataState(short idn)
public Integer readDataState(short idn, int timeoutMs)
Reads the Data State element of an IDN (ElementFlag 0x01) and decodes it as an unsigned 16-bit value. Returns null when the read fails or fewer than 2 bytes are returned. The default timeout is 500 ms.
Example:
SoE soe = slave.soe();
String name = soe.readName((short) 0x002F);
String unit = soe.readUnit((short) 0x002F);
byte[] min = soe.readMinValue((short) 0x002F);
byte[] max = soe.readMaxValue((short) 0x002F);
Integer state = soe.readDataState((short) 0x002F);
System.out.printf("参数: %s (%s)%n", name, unit); // Parameter: %s (%s)%n
Parameter information
getAvailableIDNs()
public List<Short> getAvailableIDNs()
public List<Short> getAvailableIDNs(int timeoutMs)
Gets the list of all IDN the slave supports.
Parameters: timeoutMs (int) — timeout in milliseconds; default 5000.
Returns:
List<Short>— list of IDN numbers; an empty list when the slave really returns 0 entries, in which casegetLastStatus()isSUCCESS.
Throws: SoEProtocolException — the read failed. A failure is never folded into an empty list; "no IDN" and "not read" must be judged separately.
getParameterInfo(short idn)
public SoEParameter getParameterInfo(short idn)
public SoEParameter getParameterInfo(short idn, int timeoutMs)
Gets the complete information of an IDN parameter (name, unit, current value, minimum / maximum value and so on); internally it reads six elements in sequence.
Parameters: idn (short) — IDN number; timeoutMs (int) — read timeout for each element in milliseconds; default 5000.
Returns:
SoEParameter— the complete parameter information. Elements that could not be read are filled with defaults:Name/Unitare"", the four byte arrays arebyte[0]; the method itself does not throw.
Related structures:
SoEParameter
public static class SoEParameter {
public short IDN; // IDN number
public String Name; // parameter name
public String Unit; // unit
public SoEAttributes Attributes; // attributes (data type / length / permission bitfield)
public byte[] Value; // current value
public byte[] DefaultValue; // default value
public byte[] MinValue; // minimum value
public byte[] MaxValue; // maximum value
public String category(); // category ("Standard"/"Product"/"Vendor")
public String sercosIDN(); // SERCOS IDN format (S-x-xxxx / P-x-xxxx)
public String toString(); // "S-x-xxxx name"
}
| Field | Type | Description |
|---|---|---|
| IDN | short | IDN number |
| Name | String | Parameter name ("" when it cannot be read) |
| Unit | String | Unit ("" when it cannot be read) |
| Attributes | SoEAttributes | Attributes; getParameterInfo does not fill them in, always null |
| Value | byte[] | Current value (byte[0] when it cannot be read) |
| DefaultValue | byte[] | Default value (byte[0] when it cannot be read) |
| MinValue | byte[] | Minimum value (byte[0] when it cannot be read) |
| MaxValue | byte[] | Maximum value (byte[0] when it cannot be read) |
To obtain the attributes, use read(idn, SoE.SoEElementFlags.ATTRIBUTE, timeoutMs) to get the raw bytes, or decode them with the structure below:
SoEAttributes
public static class SoEAttributes {
public short EvaluationFactor;
public byte Length;
public boolean IsList;
public boolean IsCommand;
public byte DataType;
public byte Decimals;
public boolean WriteProtectedPreOp;
public boolean WriteProtectedSafeOp;
public boolean WriteProtectedOp;
public String accessMode(); // "RO" / "RW" / "RW*"
}
| Field | Type | Description |
|---|---|---|
| EvaluationFactor | short | Evaluation factor |
| Length | byte | Data length (bytes) |
| IsList | boolean | Whether it is a list parameter |
| IsCommand | boolean | Whether it is a procedure command |
| DataType | byte | SERCOS data type number |
| Decimals | byte | Number of decimal places |
| WriteProtectedPreOp / WriteProtectedSafeOp / WriteProtectedOp | boolean | Whether the parameter is write-protected in the PREOP / SAFEOP / OP phases |
accessMode(): returns "RO" when all three phases are write-protected, "RW" when none is, and "RW*" otherwise (writable in some phases).
Example:
SoE soe = slave.soe();
SoE.SoEParameter param = soe.getParameterInfo((short) 0x002F);
System.out.printf("IDN: %s - %s%n", param.sercosIDN(), param.Name);
System.out.printf("单位: %s%n", param.Unit); // Unit: %s%n
Procedure commands
executeCommand(short idn, int timeoutMs, int pollIntervalMs)
public boolean executeCommand(short idn)
public boolean executeCommand(short idn, int timeoutMs, int pollIntervalMs)
Executes a SoE procedure command (SERCOS Procedure Command). The command is triggered by setting bit0 of the DataState element (0x01) and writing it back, after which the method polls until the command completes.
Parameters:
idn(short) — IDN number of the command to executetimeoutMs(int) — timeout for waiting for the command to complete in milliseconds (default 5000); also used as the timeout of each status readpollIntervalMs(int) — polling interval in milliseconds (default 50)
Returns:
boolean—truewhen the command executes successfully,falseon timeout or failure
Behavior contract:
- Reads the data state element (0x01, 2 bytes little-endian) of the command IDN, sets bit0 and writes it back to trigger the command;
- Reads the status once every
pollIntervalMs: bit1 set = the slave reports a command error and the method returnsfalseimmediately; bit0 cleared = the command is complete and the method returnstrue; - If neither happens within the polling window, the call has timed out and returns
falsewithgetLastStatus()set toTIMEOUT.
A failed initial status read (or fewer than 2 bytes) and a failed trigger write both return false. When the thread is interrupted, the method returns false, sets getLastStatus() to CANCELLED and restores the interrupt flag. The method itself does not throw.
Example:
// Execute the homing command (S-0-0148)
boolean success = slave.soe().executeCommand((short) 0x0094);
if (success)
System.out.println("回零完成"); // Homing complete
else
System.out.println("回零超时或失败"); // Homing timed out or failed
// Custom timeout (long-running command)
boolean ok = slave.soe().executeCommand((short) 0x0094, 30000, 100);
AT/MDT mapping
SERCOS transfers cyclic data with AT (Acknowledge Telegram) and MDT (Master Data Telegram):
- AT = cyclic inputs from slave to master (actual position, actual velocity, status word, ...)
- MDT = cyclic outputs from master to slave (target position, target velocity, control word, ...)
The mapping configuration determines which IDN parameters are included in the cyclic data frames.
getIDNMapping()
public ServoMappingInfo getIDNMapping()
public ServoMappingInfo getIDNMapping(int timeoutMs)
Reads the AT/MDT mapping configuration of the current drive (S-0-0016 / S-0-0024).
Parameters: timeoutMs (int) — timeout in milliseconds; default 5000.
Returns:
ServoMappingInfo— the mapping information object. The lists are empty when there are no mapping entries, in which casegetLastStatus()isSUCCESS.
Throws: SoEProtocolException — the configuration cannot be read, or the configuration read is shorter than 4 bytes. A read failure is not folded into "no mapping".
Note: the BitLength of an entry is currently not populated by this method (always 0, and byteLength() is also 0), and ATBitSize / MDTBitSize are fixed at 16 — do not use them as the real bit width / byte width.
Related structures:
ServoMappingInfo
public static class ServoMappingInfo {
public List<ServoMappingEntry> ATMapping; // AT (input) mapping list
public List<ServoMappingEntry> MDTMapping; // MDT (output) mapping list
public int ATBitSize; // total AT bit size (currently fixed at 16, not accumulated from the entries)
public int MDTBitSize; // total MDT bit size (currently fixed at 16, not accumulated from the entries)
public int atByteSize(); // total AT byte size (rounded up from ATBitSize)
public int mDTByteSize(); // total MDT byte size (rounded up from MDTBitSize)
}
public static class ServoMappingEntry {
public short IDN; // IDN number
public String Name; // parameter name (placeholder "IDN 0xXXXX" when it cannot be read)
public int BitLength; // data length in bits; currently not populated, always 0
public int byteLength(); // data length in bytes (rounded up from BitLength)
}
getAllDriveMappings()
public Map<Byte, ServoMappingInfo> getAllDriveMappings()
public Map<Byte, ServoMappingInfo> getAllDriveMappings(int timeoutMs)
Gets the mapping information of all drives (scans drives 0 – 7, reading each drive through its own separate instance).
Parameters: timeoutMs (int) — read timeout per drive in milliseconds; default 5000.
Returns:
Map<Byte, ServoMappingInfo>— dictionary from drive number to mapping information, containing only drives with at least one AT or MDT mapping. A drive that does not exist or fails to read is skipped; the method does not throw.
Example:
SoE soe = slave.soe();
SoE.ServoMappingInfo mapping = soe.getIDNMapping();
System.out.println("AT 映射条目: " + mapping.ATMapping.size()); // AT mapping entries: {mapping.ATMapping.size()}
System.out.println("MDT 映射条目: " + mapping.MDTMapping.size()); // MDT mapping entries: {mapping.MDTMapping.size()}
for (SoE.ServoMappingEntry entry : mapping.ATMapping) {
System.out.printf(" IDN 0x%04X: %s%n", entry.IDN, entry.Name);
}
// Mappings of all drives
Map<Byte, SoE.ServoMappingInfo> allMappings = soe.getAllDriveMappings();
Parameter change notifications
The SoE Notification feature monitors changes of IDN parameters on a SERCOS slave. When a parameter value changes, the application is notified through a listener.
How it works:
- Hardware notification:
enableNotification(idn)writes the IDN into the notification request command (S-0-0127); a supporting slave pushes changes on its own - Polling fallback: whether or not the hardware notification request succeeds, the IDN is registered for monitoring and
pollNotifications()compares the values periodically
Notification API
addNotificationListener(listener)(void) — registers a notification callback listenerenableNotification(idn)(boolean) — enables change notification for an IDN parameterenableNotification(idn, timeoutMs)(boolean) — enables notification (custom timeout, default 500 ms)disableNotification(idn)(void) — disables notification for the specified IDNdisableAllNotifications()(void) — disables all notificationspollNotifications()(int) — polls for changes (default timeout 200 ms per IDN)pollNotifications(timeoutMs)(int) — polls for changes (custom timeout)getMonitoredIDNs()(List<Short>) — gets a snapshot of the IDN currently monitored
The return value of enableNotification says whether the hardware notification request was written successfully; false means the slave does not support it or the write was rejected, in which case the polling fallback still applies and monitoring remains active. pollNotifications returns the number of IDN whose change it detected in this call, and returns 0 immediately when nothing is monitored; a failed read of one IDN does not affect the other IDN, and a change of that IDN in this cycle is not counted.
SoE only provides addNotificationListener(listener) and has no removeNotificationListener, so a notification listener cannot be unregistered on its own and is released together with the SoE instance (the slave object); this page does not invent a removeNotificationListener call. To temporarily stop receiving notifications use disableAllNotifications() (it stops IDN monitoring, not the listener).
Emergency listeners on the same SoE do have a paired entry point: addEmergencyListener / removeEmergencyListener.
NotificationListener interface
public interface NotificationListener {
void onNotification(SoENotificationEventArgs args);
}
// Semantic naming alias (extends NotificationListener)
public interface SoENotificationListener extends NotificationListener { }
SoENotificationEventArgs
public static class SoENotificationEventArgs {
public short SlaveIndex; // slave index
public byte DriveNumber; // drive number
public short IDN; // the IDN number that changed
public byte ElementFlags; // SoE ElementFlags (bit0=Data bit1=Name ...)
public byte[] NewValue; // new value
public byte[] OldValue; // old value
public String sercosIDN(); // formatted SERCOS IDN name (such as "S-0-0127")
}
| Field | Type | Description |
|---|---|---|
| SlaveIndex | short | Slave index |
| DriveNumber | byte | Drive number |
| IDN | short | IDN number that changed |
| ElementFlags | byte | Element flag bitmask; hardware notifications carry the bits reported by the slave, events triggered by polling are 0x00 |
| NewValue | byte[] | New value |
| OldValue | byte[] | Previous value (may be null on the first notification) |
An exception thrown by one listener does not affect the other listeners.
Example:
SoE soe = slave.soe();
// Register the notification listener
soe.addNotificationListener((args) -> {
System.out.printf("参数变化: %s (IDN 0x%04X)%n", args.sercosIDN(), args.IDN); // Parameter change: %s (IDN 0x%04X)%n
});
// Enable monitoring of the position command (S-0-0047)
boolean hwSupported = soe.enableNotification((short) 0x002F);
System.out.println("硬件通知: " + (hwSupported ? "支持" : "回退到轮询")); // Hardware notification: supported / falling back to polling
// Enable monitoring of the communication cycle (S-0-0001)
soe.enableNotification((short) 0x0001);
// Poll for changes periodically
int changed = soe.pollNotifications();
if (changed > 0)
System.out.printf("检测到 %d 个参数变化%n", changed); // Detected %d parameter changes%n
// Inspect the monitored IDNs
List<Short> monitored = soe.getMonitoredIDNs();
// Stop monitoring
soe.disableAllNotifications();
dispatchHardwareNotification(idn, elementFlags, newValue) and dispatchHardwareEmergency(errorCode) are event routing entry points called by the SDK when a hardware notification frame arrives; the application side must not call them manually.
Emergency events
A SoE Emergency corresponds to the hardware emergency frame with OpCode=6 in the underlying callback, as defined by ETG.1020. The slave pushes it proactively on internal faults, hardware warnings and similar conditions; ErrorCode is the IEC 61491 Sercos error code.
Emergency API
addEmergencyListener(listener)(void) — registers an Emergency callback listenerremoveEmergencyListener(listener)(void) — removes the specified Emergency listener
The two entry points exist as a pair; passing null is ignored (unlike notification listeners, an Emergency listener can be unregistered individually).
SoEEmergencyListener interface
public interface SoEEmergencyListener {
void onEmergency(SoEEmergencyEventArgs args);
}
SoEEmergencyEventArgs
public static class SoEEmergencyEventArgs {
public short SlaveIndex; // slave index
public byte DriveNumber; // drive number
public int ErrorCode; // IEC 61491 Sercos error code
public long TimestampUtcMs; // event timestamp (UTC epoch milliseconds)
}
| Field | Type | Description |
|---|---|---|
| SlaveIndex | short | Slave index |
| DriveNumber | byte | Drive number |
| ErrorCode | int | IEC 61491 Sercos error code (16-bit) |
| TimestampUtcMs | long | Event time (Unix milliseconds) |
Example:
SoE soe = slave.soe();
// Register the Emergency listener (triggered by OpCode=6 hardware frames)
soe.addEmergencyListener(args -> {
System.out.printf("SoE Emergency: slave=%d drive=%d code=0x%04X at %s%n",
args.SlaveIndex, args.DriveNumber & 0xFF, args.ErrorCode,
java.time.Instant.ofEpochMilli(args.TimestampUtcMs));
});
// Also listen for parameter change Notifications (OpCode=5)
soe.addNotificationListener(args -> {
System.out.printf("参数变化: %s (IDN 0x%04X, flags=0x%02X)%n", // Parameter change: %s (IDN 0x%04X, flags=0x%02X)%n
args.sercosIDN(), args.IDN, args.ElementFlags & 0xFF);
});
SoENotificationEventArgs has an ElementFlags field that exposes the ElementFlags bitmask reported by the slave; SoEEmergencyEventArgs does not have that field and carries only the error code and the timestamp.
IDN encoding helpers
SoEElementFlags
elementFlags bitmask constants.
Related structures:
public static final class SoEElementFlags {
public static final byte NONE = (byte) 0x00; // none
public static final byte DATA_STATUS = (byte) 0x01; // data status word
public static final byte NAME = (byte) 0x02; // IDN name
public static final byte ATTRIBUTE = (byte) 0x04; // attributes (data type / length and so on)
public static final byte UNIT = (byte) 0x08; // unit string
public static final byte MIN = (byte) 0x10; // minimum value
public static final byte MAX = (byte) 0x20; // maximum value
public static final byte VALUE = (byte) 0x40; // operating data value
public static final byte DEFAULT = (byte) 0x80; // default value
}
byte[] name = soe.read((short) 0x002F, SoE.SoEElementFlags.NAME, 500);
byte[] unit = soe.read((short) 0x002F, SoE.SoEElementFlags.UNIT, 500);
encodeIdn(boolean isStandard, byte parameterSet, short dataBlock)
public static short encodeIdn(boolean isStandard, byte parameterSet, short dataBlock)
Encodes a SERCOS IDN triple into a 16-bit IDN (flag bit + ParameterSet 3 bits + DataBlock 12 bits).
Parameters:
| Parameter | Type | Description |
|---|---|---|
| isStandard | boolean | true = S-x-xxxx standard parameter, false = P-x-xxxx product / vendor parameter |
| parameterSet | byte | Parameter set, the low 3 bits are used (0 – 7) |
| dataBlock | short | Data block number, the low 12 bits are used (0 – 4095) |
Returns: short — the 16-bit IDN.
decodeIdn(short idn)
public static IdnTriple decodeIdn(short idn)
Decodes a 16-bit IDN into an IdnTriple, the inverse entry point of encodeIdn.
IdnTriple
public static class IdnTriple {
public final boolean isStandard; // true = S standard / false = P product
public final byte parameterSet; // ParameterSet (0..7)
public final short dataBlock; // DataBlock (0..4095)
}
All IdnTriple fields are final (immutable), and toString() is overridden to output the S-x-xxxx / P-x-xxxx format.
tryParseSercosIdn(String text)
public static Short tryParseSercosIdn(String text)
Parses a SERCOS IDN string ("S-0-0040" / "P-1-0123") into a 16-bit IDN. Another inverse entry point of encodeIdn. The string must have three segments (separated by -); the S / P prefix is case-insensitive.
Returns:
Short— the 16-bit IDN on success;nullmeans an invalid format or an out-of-range parameter (segment count not equal to 3, prefix not S/P, parameter set outside 0 – 7, data block outside 0 – 4095, or number parsing failed).
Example:
// S-0-0047 (position command value) = standard, set=0, block=47
short idn = SoE.encodeIdn(true, (byte) 0, (short) 47);
SoE.IdnTriple t = SoE.decodeIdn(idn);
System.out.printf("%s-%d-%04d%n",
t.isStandard ? "S" : "P", t.parameterSet, t.dataBlock);
// Parse from a string
Short parsed = SoE.tryParseSercosIdn("S-0-0047"); // position command value IDN
if (parsed != null) {
byte[] data = slave.soe().read(parsed);
}
Batch operations
readAllParameters()
public List<SoEParameter> readAllParameters()
public List<SoEParameter> readAllParameters(int timeoutMs)
Batch-reads common parameters: a fixed set of 18 IDN (0x0000 – 0x0004, 0x0010 – 0x0016, 0x0021, 0x0024, 0x0032, 0x0033, 0x0040, 0x0047). A single IDN failure does not abort the whole batch.
Parameters: timeoutMs (int) — read timeout per IDN in milliseconds; default 5000.
Returns:
List<SoEParameter>— the parameters whose data was actually read; IDN that were not read are absent from the list, seelastBatchReadSummary()for details.
Failure details: use lastBatchReadSummary() to obtain the summary of the most recent batch read (null if no batch read has run). The criterion is that an IDN counts as not read when all six items — name, unit, value, minimum / maximum / default — are empty; an IDN whose read threw an exception is also counted as failed.
Related structures:
SoEBatchReadSummary
public static final class SoEBatchReadSummary {
public final int Total; // number of IDNs attempted
public final int Succeeded; // number of IDNs whose data was actually read
public final int Failed; // number of IDNs not read
public final List<Short> FailedIDNs; // list of IDNs not read (immutable)
public boolean isComplete(); // Failed == 0
}
| Field | Type | Description |
|---|---|---|
| Total | int | Total number of IDN attempted |
| Succeeded | int | Number of IDN whose data was actually read |
| Failed | int | Number of IDN whose data was not read (or whose read threw) |
| FailedIDNs | List<Short> | List of IDN not read (immutable) |
readParameter(short idn)
public SoEParameter readParameter(short idn)
public SoEParameter readParameter(short idn, int timeoutMs)
Reads the metadata and current value of a single parameter; equivalent to getParameterInfo (one implementation, two entry points). The default timeout is 5000 ms.
writeParameter(short idn, byte[] data)
public boolean writeParameter(short idn, byte[] value)
public boolean writeParameter(short idn, byte[] value, int timeoutMs)
Writes parameter data (as the data value element 0x40); the return value means the same as in write. The default timeout is 500 ms.
Throws: IllegalArgumentException — value is null or has length 0 (note the difference from write: write returns false, this method throws).
Example:
SoE soe = slave.soe();
// Batch-read common parameters
List<SoE.SoEParameter> params = soe.readAllParameters();
SoE.SoEBatchReadSummary summary = soe.lastBatchReadSummary();
System.out.printf("读到 %d/%d,未读到 %s%n", // Read %d/%d, could not read %s%n
summary.Succeeded, summary.Total, summary.FailedIDNs);
for (SoE.SoEParameter p : params) {
System.out.println(p.sercosIDN() + " " + p.Name);
}
// Write the position command value (S-0-0047)
if (!soe.writeParameter((short) 0x002F, new byte[] { (byte) 0xE8, 0x03, 0x00, 0x00 })) {
System.err.println("写入失败: " + soe.getLastStatus()); // Write failed:
}
Exception types
SoEProtocolException
public static class SoEProtocolException extends RuntimeException {
public final SoEError errorCode; // SoE error code
}
The SoE protocol exception, carrying the last SoEError error code; the message text ends with [error=错误码名]. Thrown by:
| Thrown by | Trigger condition |
|---|---|
readAsync / writeAsync | When the synchronous read/write fails (returns null / false), the asynchronous future completes with this exception; obtain it with ex.getCause() |
getAvailableIDNs | The IDN list read fails (not folded into an empty list) |
getIDNMapping | The AT / MDT configuration cannot be read, or the data read is shorter than 4 bytes |
The other methods (read / write / typed reads and writes / getParameterInfo / executeCommand / notifications / getAllDriveMappings) do not throw protocol exceptions; failures surface as null / false / empty values plus getLastStatus().
Other exceptions
| Method | Exception | Trigger condition |
|---|---|---|
writeUInt16 | IllegalArgumentException | value is outside 0..65535 |
writeUInt32 | IllegalArgumentException | value is outside 0..4294967295 |
writeParameter | IllegalArgumentException | value is null or has length 0 |
SoEError error codes
SoEError (com.darra.ethercat.data.EtherCATTypes) is the error code enum of the SoE protocol; both SoEProtocolException.errorCode and getLastSoEError() return it, and fromValue(int) returns UNKNOWN for unknown values.
| Value | Enum | Meaning |
|---|---|---|
| 0x0000 | NO_ERROR | No error |
| 0x1001 | NO_IDN | No IDN |
| 0x1009 | INVALID_ACCESS_TO_ELEMENT | Invalid access to element |
| 0x2001 | NO_NAME | No name |
| 0x2002 | NAME_TRANSMISSION_TOO_SHORT | Name transmission too short |
| 0x2003 | NAME_TRANSMISSION_TOO_LONG | Name transmission too long |
| 0x2004 | NAME_CANNOT_BE_CHANGED | Name cannot be changed |
| 0x2005 | NAME_WRITE_PROTECTED | Name write-protected |
| 0x3002 | ATTRIBUTE_TRANSMISSION_TOO_SHORT | Attribute transmission too short |
| 0x3003 | ATTRIBUTE_TRANSMISSION_TOO_LONG | Attribute transmission too long |
| 0x3004 | ATTRIBUTE_CANNOT_BE_CHANGED | Attribute cannot be changed |
| 0x3005 | ATTRIBUTE_WRITE_PROTECTED | Attribute write-protected |
| 0x4001 | NO_UNITS | No units |
| 0x4002 | UNIT_TRANSMISSION_TOO_SHORT | Unit transmission too short |
| 0x4003 | UNIT_TRANSMISSION_TOO_LONG | Unit transmission too long |
| 0x4004 | UNIT_CANNOT_BE_CHANGED | Unit cannot be changed |
| 0x4005 | UNIT_WRITE_PROTECTED | Unit write-protected |
| 0x5001 | NO_MINIMUM_INPUT_VALUE | No minimum input value |
| 0x5002 | MIN_VALUE_TOO_SHORT | Minimum value too short |
| 0x5003 | MIN_VALUE_TOO_LONG | Minimum value too long |
| 0x5004 | MIN_VALUE_CANNOT_BE_CHANGED | Minimum value cannot be changed |
| 0x5005 | MIN_VALUE_WRITE_PROTECTED | Minimum value write-protected |
| 0x6001 | NO_MAXIMUM_INPUT_VALUE | No maximum input value |
| 0x6002 | MAX_VALUE_TOO_SHORT | Maximum value too short |
| 0x6003 | MAX_VALUE_TOO_LONG | Maximum value too long |
| 0x6004 | MAX_VALUE_CANNOT_BE_CHANGED | Maximum value cannot be changed |
| 0x6005 | MAX_VALUE_WRITE_PROTECTED | Maximum value write-protected |
| 0x7001 | NO_OPERATION_DATA | No operating data |
| 0x7002 | OP_DATA_TOO_SHORT | Operating data too short |
| 0x7003 | OP_DATA_TOO_LONG | Operating data too long |
| 0x7004 | OP_DATA_CANNOT_BE_CHANGED | Operating data cannot be changed |
| 0x7005 | OP_DATA_WRITE_PROTECTED_BY_STATE | Operating data write-protected by state |
| 0x7006 | OP_DATA_SMALLER_THAN_MIN | Operating data smaller than the minimum |
| 0x7007 | OP_DATA_GREATER_THAN_MAX | Operating data greater than the maximum |
| 0x7008 | INVALID_OP_DATA_CONFIG | Invalid operating data configuration |
| 0x7009 | OP_DATA_WRITE_PROTECTED_BY_PASSWORD | Operating data write-protected by password |
| 0x700A | OP_DATA_CYCLICALLY_WRITE_PROTECTED | Operating data cyclically write-protected |
| 0x700B | INVALID_INDIRECT_ADDRESSING | Invalid indirect addressing |
| 0x700C | OP_DATA_WRITE_PROTECTED_BY_SETTINGS | Operating data write-protected by settings |
| 0x700D | RESERVED_700D | Reserved |
| 0x7010 | PROCEDURE_COMMAND_ALREADY_ACTIVE | Procedure command already active |
| 0x7011 | PROCEDURE_COMMAND_NOT_INTERRUPTIBLE | Procedure command not interruptible |
| 0x7012 | PROCEDURE_COMMAND_NOT_EXECUTABLE_STATE | Procedure command not executable in the current state |
| 0x7013 | PROCEDURE_COMMAND_INVALID_PARAMS | Procedure command parameters invalid |
| 0x7014 | NO_DATA_STATE | No data state |
| 0x8001 | NO_DEFAULT_VALUE | No default value |
| 0x8002 | DEFAULT_VALUE_TOO_LONG | Default value too long |
| 0x8003 | DEFAULT_VALUE_TOO_SHORT | Default value too short |
| 0x8004 | DEFAULT_VALUE_CANNOT_BE_CHANGED | Default value cannot be changed |
| 0x8005 | DEFAULT_VALUE_WRITE_PROTECTED | Default value write-protected |
| 0x800A | INVALID_DRIVE_NUMBER | Invalid drive number |
| 0x800B | GENERAL_ERROR | General error |
| 0x800C | NO_ELEMENT_ADDRESSED | No element addressed |
| 0xFFFF | UNKNOWN | Unknown error |
When a read or write fails and no specific error code can be determined, UNKNOWN(0xFFFF) is used as the fallback so that getLastErrorCode() is never 0 on a failure path.
Mailbox statistics
SoE implements the unified IMailboxProtocol interface. Since 2.5.x, getStatistics() / resetStatistics() return real statistics (earlier versions returned a placeholder empty snapshot).
| Category | Method | Type | Read/write | Description |
|---|---|---|---|---|
| Protocol identification | getProtocolType() | byte | read-only | Protocol type constant (SoE=0x05) |
| getProtocolName() | String | read-only | Protocol name ("SoE") | |
| isSupported() | boolean | read-only | Whether the slave supports this protocol; returns false when the capability is unknown (fail-closed) | |
| supportState() | Boolean | read-only | Tri-state capability: TRUE = supported, FALSE = confirmed unsupported, null = unknown | |
| isSupportKnown() | boolean | read-only | Whether the capability verdict is known (supportState() != null) | |
| Transaction status | getLastStatus() | MailboxStatus | read-only | Unified status of the most recent mailbox transaction |
| getLastErrorCode() | long | read-only | Most recent protocol-layer error code (0 = no error) | |
| getLastSoEError() | SoEError | read-only | Most recent error enum (null on success or when nothing has been started) | |
| Statistics | getStatistics() | MailboxStatistics | read-only | Mailbox statistics snapshot |
| resetStatistics() | void | write-only | Resets the mailbox statistics counters and clears the most recent status and error code |
MailboxStatus values:
| Enum | Value | Description |
|---|---|---|
| PENDING | 0 | Transaction not yet started or in progress |
| SUCCESS | 1 | Success |
| TIMEOUT | -1 | Timeout |
| CANCELLED | -2 | Cancelled |
| MAILBOX_ERROR | -3 | Mailbox error frame / protocol-layer abort |
| PROTO_MISMATCH | -4 | Response protocol type mismatch |
| WKC_FAIL | -6 | Working counter did not match the expectation |
| NO_MEMORY | -7 | Out of memory |
| INVALID_ARG | -8 | Invalid argument |
| NOT_IMPLEMENTED | -9 | Not supported |
| LINK_DOWN | -10 | Link down (frames fail immediately instead of timing out one by one); check the cable / NIC link status |
| NOT_SENT | -11 | Request never left the local host (frame never reached the wire: aborted / backoff / pool exhausted / channel closed / held by the kernel); not a slave timeout and not a slave rejection — carries no bus evidence, must not be used for slave-drop or health verdicts; callers treat it as retryable |
MailboxStatistics (com.darra.ethercat.abstractions) is an immutable snapshot:
| Field | Type | Description |
|---|---|---|
| totalSent | long | Total transactions sent |
| totalReceived | long | Total responses received (including error frames) |
| totalTimeout | long | Total timeouts |
| totalMailboxError | long | Total mailbox error frames |
| totalProtocolError | long | Total protocol errors (protocol type / WKC mismatch) |
| totalCancelled | long | Total cancelled transactions |
| lastErrorCode | long | Most recent error code (0 = none) |
| lastErrorTime | Instant | Time of the most recent error (UTC, null when there is no error) |
| averageLatencyUs | double | Average transaction latency (microseconds) |
Example:
SoE soe = slave.soe();
byte[] raw = soe.read((short) 0x0001);
if (raw == null) {
System.out.printf("读失败: status=%s code=0x%04X%n", // Read failed: status=%s code=0x%04X%n
soe.getLastStatus(), soe.getLastErrorCode());
}
MailboxStatistics stats = soe.getStatistics();
System.out.printf("SoE 邮箱: 发送=%d, 接收=%d, 超时=%d, 平均延迟=%.1fus%n", // SoE mailbox: sent=%d, received=%d, timeouts=%d, average latency=%.1fus%n
stats.totalSent, stats.totalReceived, stats.totalTimeout, stats.averageLatencyUs);
soe.resetStatistics();
Full example
Parameter scan
SoE soe = slave.soe();
List<Short> idns = soe.getAvailableIDNs();
System.out.printf("从站支持 %d 个 IDN 参数%n%n", idns.size()); // Slave supports %d IDN parameters%n%n
for (int i = 0; i < Math.min(10, idns.size()); i++) {
SoE.SoEParameter info = soe.getParameterInfo(idns.get(i));
System.out.printf("%s: %s (%s)%n", info.sercosIDN(), info.Name, info.Unit);
}
Servo drive control
SoE soe = slave.soe();
// 1. Read the communication cycle (S-0-0001)
Integer cycle = soe.readUInt32((short) 0x0001);
System.out.printf("通信周期: %s%n", cycle); // Communication cycle: %s%n
// 2. Inspect the AT/MDT mapping (to learn which parameters the cyclic data carries)
SoE.ServoMappingInfo mapping = soe.getIDNMapping();
System.out.printf("%nAT 映射(%d 条):%n", mapping.ATMapping.size()); // %nAT mapping (%d entries):%n
for (SoE.ServoMappingEntry entry : mapping.ATMapping)
System.out.printf(" IDN 0x%04X: %s%n", entry.IDN, entry.Name);
System.out.printf("%nMDT 映射(%d 条):%n", mapping.MDTMapping.size()); // %nMDT mapping (%d entries):%n
for (SoE.ServoMappingEntry entry : mapping.MDTMapping)
System.out.printf(" IDN 0x%04X: %s%n", entry.IDN, entry.Name);
// 3. Set the position command value (S-0-0047)
if (!soe.writeInt32((short) 0x002F, 50000)) {
System.err.println("位置指令写入失败: " + soe.getLastStatus()); // Position command write failed:
}
// 4. Read the position command value back
Integer pos = soe.readInt32((short) 0x002F);
System.out.printf("%n位置指令值: %d%n", pos); // %nPosition command value: %d%n
// 5. Execute the homing procedure command (S-0-0148)
boolean homed = soe.executeCommand((short) 0x0094, 30000, 100);
System.out.println(homed ? "回零完成" : "回零未完成: " + soe.getLastStatus()); // Homing complete / homing not complete:
Formatting helpers
Use these two static methods to display the raw bytes you have read:
public static String formatByteArray(byte[] data)
public static String formatByteArray(byte[] data, int dataType)
| Method | Description |
|---|---|
formatByteArray(byte[] data) | Hexadecimal text with bytes separated by spaces (such as "E8 03 00 00"); null or an empty array returns "" |
formatByteArray(byte[] data, int dataType) | Formats according to the data type |
dataType values: 0 = binary (falls back to hexadecimal), 1 = unsigned integer, 2 = signed integer, 3 = hexadecimal (with a 0x prefix), 4 = UTF-8 string (trailing 0x00 removed), 6 = float. 1 / 2 support only 1, 2 and 4 bytes, and 6 supports only 4 / 8 bytes; on a length mismatch or when dataType is outside the values above, the hexadecimal format is used.
byte[] raw = soe.read((short) 0x002F);
System.out.println(SoE.formatByteArray(raw)); // E8 03 00 00
System.out.println(SoE.formatByteArray(raw, 2)); // 1000
System.out.println(SoE.formatByteArray(raw, 3)); // 0xE8030000
Failures and handling
| Symptom | Cause | Handling |
|---|---|---|
| read / readName / readUnit return null | The IDN number does not exist, or the device does not support that parameter | Check the IDN number in the device manual; use readName first to confirm the parameter exists |
| read returns null and getLastStatus() is TIMEOUT | The slave did not answer within the timeout | Retry with a larger timeoutMs; make sure the slave is in a communicable state |
| read returns null and getLastStatus() is MAILBOX_ERROR | An error response was received | Interpret it with getLastErrorCode() / getLastSoEError() |
| write returns false | The parameter is read-only or write-protected | Check the access rights in the device manual; enable or switch state as the device requires, then write again |
| write returns false and getLastStatus() is INVALID_ARG | data is null or an empty array | Provide at least 1 byte of data |
| Read or write times out | The slave does not respond, or the mailbox channel is busy | Retry with a larger timeoutMs; make sure the slave is in a communicable state |
| The write is rejected with an abnormal status | The current operating state does not allow changing that parameter | Switch to a state that allows parameter changes first, then switch back to the operating state |
| getAvailableIDNs / getIDNMapping throw SoEProtocolException | The read failed or the response length is invalid (this is not "no parameters / no mapping") | Interpret it with errorCode; only an empty list / empty mapping means the slave really has none |
| executeCommand returns false | The command reported an error, the trigger failed, or it did not complete within the polling window | Check getLastStatus(): on TIMEOUT increase timeoutMs, on ERROR check the current state of the command |
| enableNotification returns false | The slave does not support hardware notification, or the write was rejected | The pollNotifications() polling fallback is still available |
| writeUInt16 / writeUInt32 / writeParameter throw IllegalArgumentException | The value exceeds the unsigned bit width, or the data is empty | Correct the value / supply the data |
FSoE data exchange events (read-only view)
The cyclic data event of slave.fsoe() produces a FSoE.FSoEDataExchangeEvent snapshot after every safe data exchange. The event object exposes the snapshot of that cycle through read-only accessors, so it can be read directly inside the addDataExchangedListener callback.
public FSoEState getCurrentState()
public byte[] getSafeInputs()
public byte[] getSafeOutputs()
public boolean isInFailsafe()
public boolean isStatusValid()
public long getTimestampMillis()
| Category | Property | Type | Read/write | Description |
|---|---|---|---|---|
| State | getCurrentState | FSoEState | read-only | Current FSoE state of this cycle; trustworthy only while isStatusValid() is true |
| Safety data | getSafeInputs | byte[] | read-only | Safe input snapshot of this cycle (the source data was already copied when the event fired); not trustworthy while isStatusValid() is false |
| Safety data | getSafeOutputs | byte[] | read-only | Safe output snapshot of this cycle, reflecting the current values before the outputs are committed |
| Safety state | isInFailsafe | boolean | read-only | Whether it is in failsafe mode; trustworthy only while isStatusValid() is true |
| Safety state | isStatusValid | boolean | read-only | Whether the snapshot of this cycle is trustworthy; false = at least one of the state or the safe inputs failed to read |
| Event information | getTimestampMillis | long | read-only | Time the event fired (Unix milliseconds) |
Returns:
getCurrentState()— the FSoE state enum of this cyclegetSafeInputs()/getSafeOutputs()— the snapshot arrays; length 0 when there is no dataisInFailsafe()—truemeans this cycle is in failsafe modeisStatusValid()—truemeans every snapshot field came from a successful read in this cyclegetTimestampMillis()— the time the event fired (Unix milliseconds)
When isStatusValid() is false, getCurrentState() / isInFailsafe() / getSafeInputs() hold default values rather than real readings: do not read the default false as "not in failsafe / safety OK", and do not read an empty array as "no safe inputs".
Example:
FSoE fsoe = slave.fsoe();
fsoe.addDataExchangedListener(ev -> {
if (!ev.isStatusValid()) {
System.out.println("本周期快照不可信, 时间戳=" + ev.getTimestampMillis()); // This cycle's snapshot is not trustworthy, timestamp={ev.getTimestampMillis()}
return;
}
System.out.printf("状态=%s 失效安全=%s 安全输入=%d 字节%n", // state=%s failsafe=%s safety input=%d bytes%n
ev.getCurrentState(), ev.isInFailsafe(), ev.getSafeInputs().length);
});