Skip to main content

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().​

SoE vs CoE

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​

CategoryMethodTypeRead/writeDescription
Basic read/writeread(short idn)byte[]read-onlyReads the IDN data value element (0x40) with a 500 ms timeout; returns null on failure
Basic read/writeread(short idn, byte elementFlags, int timeoutMs)byte[]read-onlyReads any element by element flags; returns null on failure
Basic read/writewrite(short idn, byte[] data)booleanwrite-onlyWrites the IDN data value element (0x40); empty data returns false immediately
Basic read/writewrite(short idn, byte[] data, byte elementFlags, int timeoutMs)booleanwrite-onlyWrites by element flags; returns false on failure
AsynchronousreadAsync(short idn) / readAsync(short idn, byte elementFlags, int timeoutMs)CompletableFuture<byte[]>read-onlyAsynchronous read; completes with SoEProtocolException on failure
AsynchronouswriteAsync(short idn, byte[] data) / writeAsync(short idn, byte[] data, byte elementFlags, int timeoutMs)CompletableFuture<Boolean>write-onlyAsynchronous write; completes with SoEProtocolException on failure
Typed readsreadInt16(short idn) / readInt16(short idn, byte elementFlags, int timeoutMs)Shortread-only16-bit signed integer; returns null when the data is too short
Typed readsreadInt32(short idn) / readInt32(short idn, byte elementFlags, int timeoutMs)Integerread-only32-bit signed integer; returns null when the data is too short
Typed readsreadUInt16(short idn)Integerread-only16-bit unsigned integer (0..65535)
Typed readsreadUInt32(short idn)Longread-only32-bit unsigned integer (0..4294967295)
Typed readsreadFloat(short idn)Floatread-onlySingle-precision float (requires 4 bytes)
Typed readsreadDouble(short idn)Doubleread-onlyDouble-precision float (requires 8 bytes)
Typed readsreadString(short idn)Stringread-onlyString, truncated at 0x00
Typed writeswriteInt16(short idn, short value)booleanwrite-onlyWrites a 16-bit signed integer
Typed writeswriteInt32(short idn, int value)booleanwrite-onlyWrites a 32-bit signed integer
Typed writeswriteUInt16(short idn, int value)booleanwrite-onlyWrites a 16-bit unsigned integer; out of range throws IllegalArgumentException
Typed writeswriteUInt32(short idn, long value)booleanwrite-onlyWrites a 32-bit unsigned integer; out of range throws IllegalArgumentException
MetadatareadName(short idn) / readName(short idn, int timeoutMs)Stringread-onlyParameter name (element 0x02); returns null on failure
MetadatareadUnit(short idn) / readUnit(short idn, int timeoutMs)Stringread-onlyParameter unit (element 0x08); returns null on failure
MetadatareadMinValue(short idn)byte[]read-onlyMinimum value (element 0x10)
MetadatareadMaxValue(short idn)byte[]read-onlyMaximum value (element 0x20)
MetadatareadDefaultValue(short idn)byte[]read-onlyDefault value (element 0x80)
MetadatareadDataState(short idn) / readDataState(short idn, int timeoutMs)Integerread-onlyData state (element 0x01)
Parameter informationgetAvailableIDNs() / getAvailableIDNs(int timeoutMs)List<Short>read-onlyList of IDN supported by the slave; throws SoEProtocolException if the read fails
Parameter informationgetParameterInfo(short idn) / getParameterInfo(short idn, int timeoutMs)SoEParameterread-onlySummary of name, unit, value and minimum / maximum / default value
Parameter informationreadParameter(short idn) / readParameter(short idn, int timeoutMs)SoEParameterread-onlyEquivalent to getParameterInfo
Parameter informationwriteParameter(short idn, byte[] value) / writeParameter(short idn, byte[] value, int timeoutMs)booleanwrite-onlyWrites the data value element; empty data throws IllegalArgumentException
BatchreadAllParameters() / readAllParameters(int timeoutMs)List<SoEParameter>read-onlyBatch-reads a fixed set of 18 common IDN and returns only the ones actually read
BatchlastBatchReadSummary()SoEBatchReadSummaryread-onlySuccess and failure breakdown of the most recent batch read (null if no batch read has run)
Procedure commandsexecuteCommand(short idn) / executeCommand(short idn, int timeoutMs, int pollIntervalMs)booleanwrite-onlyTriggers a procedure command and polls until it completes
AT/MDT mappinggetIDNMapping() / getIDNMapping(int timeoutMs)ServoMappingInforead-onlyReads the AT/MDT mapping; throws SoEProtocolException on failure
AT/MDT mappinggetAllDriveMappings() / getAllDriveMappings(int timeoutMs)Map<Byte, ServoMappingInfo>read-onlyScans the mapping of drives 0–7 one by one
Change notificationsaddNotificationListener(listener)voidwrite-onlyRegisters a parameter change callback (no unregister entry point)
Change notificationsenableNotification(short idn) / enableNotification(short idn, int timeoutMs)booleanwrite-onlyRequests a hardware notification and registers monitoring; returns whether the request succeeded
Change notificationsdisableNotification(short idn)voidwrite-onlyStops monitoring a single IDN
Change notificationsdisableAllNotifications()voidwrite-onlyStops all monitoring
Change notificationsgetMonitoredIDNs()List<Short>read-onlySnapshot of the IDN currently monitored
Change notificationspollNotifications() / pollNotifications(int timeoutMs)intread-onlyPolls for changes and fires the callbacks; returns the number of changes
EmergencyaddEmergencyListener(listener)voidwrite-onlyRegisters an Emergency callback
EmergencyremoveEmergencyListener(listener)voidwrite-onlyRemoves the specified Emergency callback
StatusgetLastStatus()MailboxStatusread-onlyStatus of the most recent mailbox transaction
StatusgetLastErrorCode()longread-onlyMost recent SoE error code (0 = no error)
StatusgetLastSoEError()SoEErrorread-onlyMost recent error enum (null when there is no error)
StatisticsgetStatistics()MailboxStatisticsread-onlyMailbox statistics snapshot
StatisticsresetStatistics()voidwrite-onlyResets the statistics and clears the most recent status
Protocol capabilitygetProtocolType()byteread-onlyProtocol type constant 0x05
Protocol capabilitygetProtocolName()Stringread-onlyProtocol name "SoE"
Protocol capabilityisSupported()booleanread-onlyWhether SoE is supported; an unknown capability is treated as unsupported
Protocol capabilitysupportState()Booleanread-onlyTri-state: TRUE supported / FALSE confirmed unsupported / null unknown
Protocol capabilityisSupportKnown()booleanread-onlyWhether the capability verdict is known
IDN helpersencodeIdn(boolean isStandard, byte parameterSet, short dataBlock)short—Encodes a triple into a 16-bit IDN
IDN helpersdecodeIdn(short idn)IdnTriple—Decodes a 16-bit IDN into a triple
IDN helperstryParseSercosIdn(String text)Short—Parses the S-0-0040 form; invalid input returns null
FormattingformatByteArray(byte[] data)String—Formats bytes as hexadecimal text
FormattingformatByteArray(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:

BitMeaning
bit150 = standard parameter (S-x-xxxx), 1 = product / vendor parameter (P-x-xxxx)
bit14 – bit12Parameter set (ParameterSet, 0 – 7)
bit11 – bit0Data 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:

PrefixRangecategory()Description
S-x-xxxx0x0000 – 0x7FFFStandardSERCOS standard parameters (common to all vendors)
P-x-xxxx0x8000 – 0xBFFFProductProduct-specific parameters
P-x-xxxx0xC000 – 0xFFFFVendorVendor-defined parameters

IDN constants provided by the SDK (SoE.StandardIDN) and the IDN used in this page's examples:

IDNConstantValueDescriptionData type
S-0-0000StandardIDN.IDN_LIST0x0000IDN list placeholder number—
S-0-0001StandardIDN.CYCLE_TIME0x0001Communication cycle timeuint, us
S-0-0016StandardIDN.AT_CONFIG0x0010AT (slave → master) mapping configuration list; getIDNMapping() reads itlist
S-0-0024StandardIDN.MDT_CONFIG0x0018MDT (master → slave) mapping configuration list; getIDNMapping() reads itlist
S-0-0127StandardIDN.NOTIFICATION_REQUEST0x007FNotification request; enableNotification() writes itushort
S-0-0047—0x002FPosition command valueint, inc
S-0-0148—0x0094Homing procedure commandcommand

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:

FlagMeaning
0x01Data state
0x02Parameter name (string)
0x04Attributes (data type / length / permission bitfield)
0x08Unit (string)
0x10Minimum value
0x20Maximum value
0x40Data value (default, most common)
0x80Default 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 number
  • elementFlags (byte) — element flags (default 0x40 = data value)
  • timeoutMs (int) — timeout in milliseconds (default 500)

Returns:

  • byte[] — the data read (little-endian, low byte first); returns null on 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 number
  • data (byte[]) — the data to write
  • elementFlags (byte) — element flags (default 0x40 = data value)
  • timeoutMs (int) — timeout in milliseconds (default 500)

Returns:

  • boolean — true when the write succeeds, false on 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:

MethodReturn typeDescription
readInt16(short idn) / readInt16(short idn, byte elementFlags, int timeoutMs)ShortReads a 16-bit signed integer
readInt32(short idn) / readInt32(short idn, byte elementFlags, int timeoutMs)IntegerReads a 32-bit signed integer
readUInt16(short idn)IntegerReads a 16-bit unsigned integer (0..65535)
readUInt32(short idn)LongReads a 32-bit unsigned integer (0..4294967295)
readFloat(short idn)FloatReads a single-precision float (requires 4 bytes)
readDouble(short idn)DoubleReads a double-precision float (requires 8 bytes)
readString(short idn)StringReads 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:

MethodParameter typeDescription
writeInt16(short idn, short value)shortWrites a 16-bit signed integer
writeInt32(short idn, int value)intWrites a 32-bit signed integer
writeUInt16(short idn, int value)intWrites a 16-bit unsigned integer
writeUInt32(short idn, long value)longWrites 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:

MethodExceptionTrigger condition
writeUInt16IllegalArgumentExceptionvalue is outside 0..65535
writeUInt32IllegalArgumentExceptionvalue 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 case getLastStatus() is SUCCESS.

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 / Unit are "", the four byte arrays are byte[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"
}
FieldTypeDescription
IDNshortIDN number
NameStringParameter name ("" when it cannot be read)
UnitStringUnit ("" when it cannot be read)
AttributesSoEAttributesAttributes; getParameterInfo does not fill them in, always null
Valuebyte[]Current value (byte[0] when it cannot be read)
DefaultValuebyte[]Default value (byte[0] when it cannot be read)
MinValuebyte[]Minimum value (byte[0] when it cannot be read)
MaxValuebyte[]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*"
}
FieldTypeDescription
EvaluationFactorshortEvaluation factor
LengthbyteData length (bytes)
IsListbooleanWhether it is a list parameter
IsCommandbooleanWhether it is a procedure command
DataTypebyteSERCOS data type number
DecimalsbyteNumber of decimal places
WriteProtectedPreOp / WriteProtectedSafeOp / WriteProtectedOpbooleanWhether 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 execute
  • timeoutMs (int) — timeout for waiting for the command to complete in milliseconds (default 5000); also used as the timeout of each status read
  • pollIntervalMs (int) — polling interval in milliseconds (default 50)

Returns:

  • boolean — true when the command executes successfully, false on timeout or failure

Behavior contract:

  1. Reads the data state element (0x01, 2 bytes little-endian) of the command IDN, sets bit0 and writes it back to trigger the command;
  2. Reads the status once every pollIntervalMs: bit1 set = the slave reports a command error and the method returns false immediately; bit0 cleared = the command is complete and the method returns true;
  3. If neither happens within the polling window, the call has timed out and returns false with getLastStatus() set to TIMEOUT.

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 case getLastStatus() is SUCCESS.

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:

  1. Hardware notification: enableNotification(idn) writes the IDN into the notification request command (S-0-0127); a supporting slave pushes changes on its own
  2. 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 listener
  • enableNotification(idn) (boolean) — enables change notification for an IDN parameter
  • enableNotification(idn, timeoutMs) (boolean) — enables notification (custom timeout, default 500 ms)
  • disableNotification(idn) (void) — disables notification for the specified IDN
  • disableAllNotifications() (void) — disables all notifications
  • pollNotifications() (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.

Notification listeners have no unregister entry point

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")
}
FieldTypeDescription
SlaveIndexshortSlave index
DriveNumberbyteDrive number
IDNshortIDN number that changed
ElementFlagsbyteElement flag bitmask; hardware notifications carry the bits reported by the slave, events triggered by polling are 0x00
NewValuebyte[]New value
OldValuebyte[]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();
Event routing entry points

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 listener
  • removeEmergencyListener(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)
}
FieldTypeDescription
SlaveIndexshortSlave index
DriveNumberbyteDrive number
ErrorCodeintIEC 61491 Sercos error code (16-bit)
TimestampUtcMslongEvent 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);
});
Event arguments

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:

ParameterTypeDescription
isStandardbooleantrue = S-x-xxxx standard parameter, false = P-x-xxxx product / vendor parameter
parameterSetbyteParameter set, the low 3 bits are used (0 – 7)
dataBlockshortData 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; null means 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, see lastBatchReadSummary() 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
}
FieldTypeDescription
TotalintTotal number of IDN attempted
SucceededintNumber of IDN whose data was actually read
FailedintNumber of IDN whose data was not read (or whose read threw)
FailedIDNsList<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 byTrigger condition
readAsync / writeAsyncWhen the synchronous read/write fails (returns null / false), the asynchronous future completes with this exception; obtain it with ex.getCause()
getAvailableIDNsThe IDN list read fails (not folded into an empty list)
getIDNMappingThe 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​

MethodExceptionTrigger condition
writeUInt16IllegalArgumentExceptionvalue is outside 0..65535
writeUInt32IllegalArgumentExceptionvalue is outside 0..4294967295
writeParameterIllegalArgumentExceptionvalue 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.

ValueEnumMeaning
0x0000NO_ERRORNo error
0x1001NO_IDNNo IDN
0x1009INVALID_ACCESS_TO_ELEMENTInvalid access to element
0x2001NO_NAMENo name
0x2002NAME_TRANSMISSION_TOO_SHORTName transmission too short
0x2003NAME_TRANSMISSION_TOO_LONGName transmission too long
0x2004NAME_CANNOT_BE_CHANGEDName cannot be changed
0x2005NAME_WRITE_PROTECTEDName write-protected
0x3002ATTRIBUTE_TRANSMISSION_TOO_SHORTAttribute transmission too short
0x3003ATTRIBUTE_TRANSMISSION_TOO_LONGAttribute transmission too long
0x3004ATTRIBUTE_CANNOT_BE_CHANGEDAttribute cannot be changed
0x3005ATTRIBUTE_WRITE_PROTECTEDAttribute write-protected
0x4001NO_UNITSNo units
0x4002UNIT_TRANSMISSION_TOO_SHORTUnit transmission too short
0x4003UNIT_TRANSMISSION_TOO_LONGUnit transmission too long
0x4004UNIT_CANNOT_BE_CHANGEDUnit cannot be changed
0x4005UNIT_WRITE_PROTECTEDUnit write-protected
0x5001NO_MINIMUM_INPUT_VALUENo minimum input value
0x5002MIN_VALUE_TOO_SHORTMinimum value too short
0x5003MIN_VALUE_TOO_LONGMinimum value too long
0x5004MIN_VALUE_CANNOT_BE_CHANGEDMinimum value cannot be changed
0x5005MIN_VALUE_WRITE_PROTECTEDMinimum value write-protected
0x6001NO_MAXIMUM_INPUT_VALUENo maximum input value
0x6002MAX_VALUE_TOO_SHORTMaximum value too short
0x6003MAX_VALUE_TOO_LONGMaximum value too long
0x6004MAX_VALUE_CANNOT_BE_CHANGEDMaximum value cannot be changed
0x6005MAX_VALUE_WRITE_PROTECTEDMaximum value write-protected
0x7001NO_OPERATION_DATANo operating data
0x7002OP_DATA_TOO_SHORTOperating data too short
0x7003OP_DATA_TOO_LONGOperating data too long
0x7004OP_DATA_CANNOT_BE_CHANGEDOperating data cannot be changed
0x7005OP_DATA_WRITE_PROTECTED_BY_STATEOperating data write-protected by state
0x7006OP_DATA_SMALLER_THAN_MINOperating data smaller than the minimum
0x7007OP_DATA_GREATER_THAN_MAXOperating data greater than the maximum
0x7008INVALID_OP_DATA_CONFIGInvalid operating data configuration
0x7009OP_DATA_WRITE_PROTECTED_BY_PASSWORDOperating data write-protected by password
0x700AOP_DATA_CYCLICALLY_WRITE_PROTECTEDOperating data cyclically write-protected
0x700BINVALID_INDIRECT_ADDRESSINGInvalid indirect addressing
0x700COP_DATA_WRITE_PROTECTED_BY_SETTINGSOperating data write-protected by settings
0x700DRESERVED_700DReserved
0x7010PROCEDURE_COMMAND_ALREADY_ACTIVEProcedure command already active
0x7011PROCEDURE_COMMAND_NOT_INTERRUPTIBLEProcedure command not interruptible
0x7012PROCEDURE_COMMAND_NOT_EXECUTABLE_STATEProcedure command not executable in the current state
0x7013PROCEDURE_COMMAND_INVALID_PARAMSProcedure command parameters invalid
0x7014NO_DATA_STATENo data state
0x8001NO_DEFAULT_VALUENo default value
0x8002DEFAULT_VALUE_TOO_LONGDefault value too long
0x8003DEFAULT_VALUE_TOO_SHORTDefault value too short
0x8004DEFAULT_VALUE_CANNOT_BE_CHANGEDDefault value cannot be changed
0x8005DEFAULT_VALUE_WRITE_PROTECTEDDefault value write-protected
0x800AINVALID_DRIVE_NUMBERInvalid drive number
0x800BGENERAL_ERRORGeneral error
0x800CNO_ELEMENT_ADDRESSEDNo element addressed
0xFFFFUNKNOWNUnknown 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).

CategoryMethodTypeRead/writeDescription
Protocol identificationgetProtocolType()byteread-onlyProtocol type constant (SoE=0x05)
getProtocolName()Stringread-onlyProtocol name ("SoE")
isSupported()booleanread-onlyWhether the slave supports this protocol; returns false when the capability is unknown (fail-closed)
supportState()Booleanread-onlyTri-state capability: TRUE = supported, FALSE = confirmed unsupported, null = unknown
isSupportKnown()booleanread-onlyWhether the capability verdict is known (supportState() != null)
Transaction statusgetLastStatus()MailboxStatusread-onlyUnified status of the most recent mailbox transaction
getLastErrorCode()longread-onlyMost recent protocol-layer error code (0 = no error)
getLastSoEError()SoEErrorread-onlyMost recent error enum (null on success or when nothing has been started)
StatisticsgetStatistics()MailboxStatisticsread-onlyMailbox statistics snapshot
resetStatistics()voidwrite-onlyResets the mailbox statistics counters and clears the most recent status and error code

MailboxStatus values:

EnumValueDescription
PENDING0Transaction not yet started or in progress
SUCCESS1Success
TIMEOUT-1Timeout
CANCELLED-2Cancelled
MAILBOX_ERROR-3Mailbox error frame / protocol-layer abort
PROTO_MISMATCH-4Response protocol type mismatch
WKC_FAIL-6Working counter did not match the expectation
NO_MEMORY-7Out of memory
INVALID_ARG-8Invalid argument
NOT_IMPLEMENTED-9Not supported
LINK_DOWN-10Link down (frames fail immediately instead of timing out one by one); check the cable / NIC link status
NOT_SENT-11Request 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:

FieldTypeDescription
totalSentlongTotal transactions sent
totalReceivedlongTotal responses received (including error frames)
totalTimeoutlongTotal timeouts
totalMailboxErrorlongTotal mailbox error frames
totalProtocolErrorlongTotal protocol errors (protocol type / WKC mismatch)
totalCancelledlongTotal cancelled transactions
lastErrorCodelongMost recent error code (0 = none)
lastErrorTimeInstantTime of the most recent error (UTC, null when there is no error)
averageLatencyUsdoubleAverage 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)
MethodDescription
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​

SymptomCauseHandling
read / readName / readUnit return nullThe IDN number does not exist, or the device does not support that parameterCheck the IDN number in the device manual; use readName first to confirm the parameter exists
read returns null and getLastStatus() is TIMEOUTThe slave did not answer within the timeoutRetry with a larger timeoutMs; make sure the slave is in a communicable state
read returns null and getLastStatus() is MAILBOX_ERRORAn error response was receivedInterpret it with getLastErrorCode() / getLastSoEError()
write returns falseThe parameter is read-only or write-protectedCheck 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_ARGdata is null or an empty arrayProvide at least 1 byte of data
Read or write times outThe slave does not respond, or the mailbox channel is busyRetry with a larger timeoutMs; make sure the slave is in a communicable state
The write is rejected with an abnormal statusThe current operating state does not allow changing that parameterSwitch to a state that allows parameter changes first, then switch back to the operating state
getAvailableIDNs / getIDNMapping throw SoEProtocolExceptionThe 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 falseThe command reported an error, the trigger failed, or it did not complete within the polling windowCheck getLastStatus(): on TIMEOUT increase timeoutMs, on ERROR check the current state of the command
enableNotification returns falseThe slave does not support hardware notification, or the write was rejectedThe pollNotifications() polling fallback is still available
writeUInt16 / writeUInt32 / writeParameter throw IllegalArgumentExceptionThe value exceeds the unsigned bit width, or the data is emptyCorrect 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()
CategoryPropertyTypeRead/writeDescription
StategetCurrentStateFSoEStateread-onlyCurrent FSoE state of this cycle; trustworthy only while isStatusValid() is true
Safety datagetSafeInputsbyte[]read-onlySafe input snapshot of this cycle (the source data was already copied when the event fired); not trustworthy while isStatusValid() is false
Safety datagetSafeOutputsbyte[]read-onlySafe output snapshot of this cycle, reflecting the current values before the outputs are committed
Safety stateisInFailsafebooleanread-onlyWhether it is in failsafe mode; trustworthy only while isStatusValid() is true
Safety stateisStatusValidbooleanread-onlyWhether the snapshot of this cycle is trustworthy; false = at least one of the state or the safe inputs failed to read
Event informationgetTimestampMillislongread-onlyTime the event fired (Unix milliseconds)

Returns:

  • getCurrentState() — the FSoE state enum of this cycle
  • getSafeInputs() / getSafeOutputs() — the snapshot arrays; length 0 when there is no data
  • isInFailsafe() — true means this cycle is in failsafe mode
  • isStatusValid() — true means every snapshot field came from a successful read in this cycle
  • getTimestampMillis() — 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);
});