FSoE functional safety
FSoE (Functional Safety over EtherCAT) layers a safety protocol on top of the standard PDO channel: once a safety connection is established, safety inputs and outputs are exchanged every cycle, and the SDK takes care of the state machine, CRC checking and the watchdog. This is not a certified safety product, nor is it a PLC logic capability; the cycle time has no product-level lower bound (it is flexible and determined by measurement on the target machine).
Accessed through slave.fsoe().
slave.fsoe() is created lazily and always returns an instance (it is never null). Use isCapable() to determine whether the slave supports FSoE; do not rely on the SII mailbox protocol bits (FSoE rides on top of CoE and is not necessarily marked separately in SII).
The SDK offers three levels of FSoE support:
slave.fsoe()— basic interface, accessed through the slave, provides single-connection FSoE operations- MDP — multi-connection management, supports multiple FSoE connections on a single slave
FSoE.SafetyManager— multi-slave, multi-connection coordinator, provides one-stepbindSafeIOinitialization
Quick start
FSoE workflow
FSoE establishes an independent safety connection over the EtherCAT PDO channel. The master handles protocol management; the slave handles the safety logic.
State machine flow:
- Reset — initial state, waiting for the master to start a session
- Session — session established, connection ID exchanged
- Connection — connection established, safety address verified
- Parameter — parameter download phase (SRA CRC check)
- Data — normal safety data exchange
- Failsafe — failsafe, the slave outputs safe values
SafetyManager.bindSafeIO() binds the safety input and safety output connection in one line; entering data exchange (DATA) still requires an explicit requestState(...).
Minimal example
FSoE fsoe = slave.fsoe();
// 1. Check capability
if (!fsoe.isCapable()) return;
// 2. Configure the connection
FSoE.FSoEConnectionConfig config = new FSoE.FSoEConnectionConfig();
config.ConnectionId = 0x0100;
config.SafetyAddress = 0x0100;
config.WatchdogTimeMs = 100;
config.SafeInputSize = 2;
config.SafeOutputSize = 1;
// 3. Initialize
fsoe.initialize(config);
// 4. Start data exchange
fsoe.requestData();
// 5. Read and write safety data cyclically
byte[] safeInput = fsoe.safeInputData();
fsoe.setSafeOutputData(new byte[]{0x01});
FSoE versus regular PDO
FSoE safety data cannot be mapped directly the way regular PDOs can. IOmap holds FSoE protocol frames; the user's safety data is wrapped inside the frame and must pass the checks.
The SDK's FSoE protocol engine is responsible for:
- CRC checking — verifies input frame integrity and computes the output frame CRC
- State machine management — maintains the legality of the SESSION -> CONNECTION -> PARAMETER -> DATA states and transitions; state changes are initiated by
requestState(...) - Watchdog — monitors communication timeouts and enters failsafe on timeout
- Sequence checking — the sequence number in the frame participates in the check calculation (see
FSoEPdoFrame.SequenceNumber); a mismatch with the expected value fails the check
Capability detection
isCapable()
public boolean isCapable()
Checks whether the slave supports the FSoE functional safety protocol.
Returns:
boolean—truewhen supported
Method overview
| Category | Method | Type | Read/write | Description |
|---|---|---|---|---|
| Capability detection | isCapable() | boolean | read-only | Whether the slave supports FSoE |
| Connection management | initialize(FSoEConnectionConfig) | boolean | write-only | Initializes a connection (connection ID, safety address, watchdog, safety data length) |
| Connection management | close() | boolean | write-only | Closes the connection |
| Connection management | dispose() | void | write-only | Resets and closes; used to release resources |
| State read | connectionState() | FSoEState | read-only | Current FSoE state; throws IllegalStateException when there is no valid connection |
| State read | connectionId() | int | read-only | Connection ID actually in use; returns -1 when not initialized |
| State read | isInitialized() | boolean | read-only | Whether the connection is initialized; throws IllegalStateException on read failure |
| State control | requestState(FSoEState targetState) | boolean | write-only | Requests a transition to the specified FSoE state |
| State control | requestData() | boolean | write-only | Requests entry into the data exchange state (DATA) |
| State control | requestFailsafe() | boolean | write-only | Enters the failsafe state explicitly |
| State control | resetConnection() | boolean | write-only | Resets the connection to the initial state |
| Safety data | safeInputData() | byte[] | read-only | Reads safety inputs (64-byte buffer by default); returns null on read failure |
| Safety data | safeInputData(int bufferSize) | byte[] | read-only | Reads safety inputs with the given buffer size |
| Safety data | setSafeOutputData(byte[]) | boolean | write-only | Writes safety outputs |
| Safety data | writeOutputFrame(byte[]) | boolean | write-only | Writes a raw output frame |
| Safety data | downloadParameters(byte[]) | int | write-only | Downloads safety parameters in the PARAMETER state; returns the SRA CRC32 or -1 |
| Safety data | setFailsafeOutput(byte[]) | boolean | write-only | Sets the safety output value used in the failsafe state |
| State check | checkWatchdog() | boolean | read-only | Whether the watchdog is healthy; false means a timeout or a failed call |
| State check | inFailsafe() | boolean | read-only | Whether the connection is in failsafe; throws IllegalStateException on read failure |
| State check | inFailsafeOrNull() | Boolean | read-only | Same as above; returns null on read failure |
| State check | watchdogExpired() | boolean | read-only | Whether the watchdog has expired; throws IllegalStateException on read failure |
| State check | watchdogExpiredOrNull() | Boolean | read-only | Same as above; returns null on read failure |
| State check | lastError() | FSoEError | read-only | Last error code |
| Statistics | status() | FSoEConnectionStatus | read-only | Full status snapshot (with a validity flag) |
| Statistics | crcErrorCount() | int | read-only | CRC error count; throws IllegalStateException on read failure |
| Statistics | watchdogErrorCount() | int | read-only | Watchdog timeout count; throws IllegalStateException on read failure |
| Statistics | framesSent() | int | read-only | Frames sent; throws IllegalStateException on read failure |
| Statistics | framesReceived() | int | read-only | Valid frames received; throws IllegalStateException on read failure |
| Statistics | connectionCount() | int | read-only | Number of FSoE connections on the current master |
| Statistics | clearError() | void | write-only | Clears the error code |
| Events | addDataExchangedListener(FSoEDataExchangeListener) | void | write-only | Registers a cyclic data event listener |
| Events | removeDataExchangedListener(FSoEDataExchangeListener) | void | write-only | Unregisters the cyclic data event listener |
| Events | processCycle() | boolean | write-only | Runs one cycle of processing and fires events |
| Events | fireDataExchanged(byte[], byte[]) | void | write-only | Fires the cyclic event manually |
| Events | addStateChangedListener(OnStateChanged) | void | write-only | Registers a state change listener |
| Events | removeStateChangedListener(OnStateChanged) | void | write-only | Unregisters the state change listener |
| Events | addErrorListener(OnErrorOccurred) | void | write-only | Registers an error listener |
| Events | removeErrorListener(OnErrorOccurred) | void | write-only | Unregisters the error listener |
| Events | addFailsafeListener(OnFailsafeTriggered) | void | write-only | Registers a failsafe listener |
| Events | removeFailsafeListener(OnFailsafeTriggered) | void | write-only | Unregisters the failsafe listener |
| MDP multi-connection | initializeMdp(SafeModuleConfig[]) | boolean | write-only | Initializes multiple connections in one call |
| MDP multi-connection | mdpSafeInputData(int) | byte[] | read-only | Reads the safety inputs of the specified connection (64-byte buffer by default) |
| MDP multi-connection | mdpSafeInputData(int, int) | byte[] | read-only | Reads safety inputs with the given buffer size |
| MDP multi-connection | setMdpSafeOutputData(int, byte[]) | boolean | write-only | Writes the safety outputs of the specified connection |
| MDP multi-connection | mdpConnectionState(int) | FSoEState | read-only | Current state of the specified connection |
| Mailbox protocol | getProtocolType() | byte | read-only | Protocol type 0x08 |
| Mailbox protocol | getProtocolName() | String | read-only | Protocol name "FSoE" |
| Mailbox protocol | isSupported() | boolean | read-only | Whether the slave supports this protocol (same as isCapable()) |
| Mailbox protocol | getLastStatus() | MailboxStatus | read-only | Status of the last mailbox transaction |
| Mailbox protocol | getLastErrorCode() | long | read-only | Last error code; 0 means no error |
| Mailbox protocol | getStatistics() | MailboxStatistics | read-only | Mailbox statistics snapshot |
| Mailbox protocol | resetStatistics() | void | write-only | Resets the mailbox statistics counters |
| Static utilities | isConnectionIdAvailable(int) | boolean | read-only | Whether the connection ID is available |
| Static utilities | validateConnId(int) | boolean | read-only | Whether the connection ID is available; throws UnsupportedOperationException when the query itself fails |
| Static utilities | fsoeCrc16(byte[]) | int | read-only | FSoE CRC16 |
| Static utilities | fsoeCrc16Fast(byte[]) | int | read-only | Same result as fsoeCrc16(byte[]) |
Safety IO binding (FSoE.SafetyManager instance methods) | bindSafeIO(...) | boolean | write-only | Binds safety inputs and outputs in one step (both share the same connection ID) |
Safety IO binding (FSoE.SafetyManager instance methods) | bindSafeInput(...) | boolean | write-only | Binds the safety input channel only |
Safety IO binding (FSoE.SafetyManager instance methods) | bindSafeOutput(...) | boolean | write-only | Binds the safety output channel only |
bindSafeIO / bindSafeInput / bindSafeOutput are instance methods of FSoE.SafetyManager, not of FSoE. SafetyManager needs the master context, and FSoE offers no entry point that returns a SafetyManager — so these three methods cannot be called directly from slave.fsoe(). For day-to-day safety data exchange, use initialize(...) / requestState(...) / safeInputData() / setSafeOutputData() as shown in the examples on this page.
Safety constraints
| Constraint | Description |
|---|---|
| Safety address | SafetyAddress must match the safety address on the slave side (DIP switch or configuration). On a mismatch the connection stays in SESSION / CONNECTION / PARAMETER and never reaches DATA. |
| Connection ID | Range 1..65535, unique within the same master. Passing 0 to initialize(...) lets the SDK allocate one automatically; the actual value is written back to config.ConnectionId and can also be read with connectionId(). Use isConnectionIdAvailable(int) before allocation to avoid conflicts. |
| Watchdog | WatchdogTimeMs defaults to 100 milliseconds. A timeout shows up as FSoEError.WATCHDOG and WatchdogExpired = true, and the connection enters failsafe. |
| Failsafe | In the FAILSAFE state the safety outputs take the safe values, which are set with setFailsafeOutput(byte[]); you can also enter it explicitly with requestFailsafe(). |
| Safety data length | SafeInputSize / SafeOutputSize must match what the slave declares, with a maximum of 64 bytes per direction (FSoEConstants.MAX_SAFE_DATA_SIZE). Reads and writes fail when the lengths do not match. |
| Read validity | A failed safety state read must not be treated as false or 0: inFailsafe() / watchdogExpired() / isInitialized() / crcErrorCount() and the like throw IllegalStateException when the read fails; status() marks the whole snapshot untrustworthy with StatusValid = false. When you need a form that may fail to read, use inFailsafeOrNull() / watchdogExpiredOrNull(). |
Safety data is read and written as bytes (byte[]). The meaning of each byte is defined by the protocol of the connected safety device; the SDK performs no field interpretation: if 2 bytes of safety input are declared, the data is parsed as 2 bytes and extra bytes are ignored.
Connection management
initialize(FSoEConnectionConfig config)
public boolean initialize(FSoEConnectionConfig config)
Initializes an FSoE connection: registers the connection ID, safety address, watchdog and safety data lengths. Initialization only establishes the connection parameters; it does not switch to DATA automatically — call requestState(...) to advance.
Parameters:
config(FSoEConnectionConfig) — connection configuration; returnsfalsewhennull(recorded asMailboxStatus.INVALID_ARG) without throwing
Returns:
boolean—trueon success;falseon failure, with the reason distinguished throughgetLastStatus()/getLastErrorCode()(connection ID conflict, safety address mismatch with the slave, and an unsupported slave all show up asfalse)
Related structures:
FSoEConnectionConfig
public static class FSoEConnectionConfig {
public short ConnectionId; // Unique connection identifier; 0 = allocated automatically by the SDK and written back
public short SafetyAddress; // FSoE slave safety address (set by DIP switch)
public int WatchdogTimeMs; // Watchdog timeout (milliseconds), default 100
public short SafeInputSize; // Safety input data size (bytes)
public short SafeOutputSize; // Safety output data size (bytes)
public int PdoInputOffset; // Byte offset of the input safety data in the process data area
public int PdoOutputOffset; // Byte offset of the output safety data in the process data area
}
Passing 0 for ConnectionId lets the SDK allocate one automatically; the actual value is written back to config.ConnectionId and can also be read with connectionId(). To preallocate, first check for conflicts with isConnectionIdAvailable(int).
Example:
FSoE fsoe = slave.fsoe();
FSoE.FSoEConnectionConfig config = new FSoE.FSoEConnectionConfig();
config.ConnectionId = 0x0100;
config.SafetyAddress = 0x0100;
config.WatchdogTimeMs = 100;
config.SafeInputSize = 2;
config.SafeOutputSize = 1;
boolean ok = fsoe.initialize(config);
close()
public boolean close()
Closes the FSoE connection and releases the connection ID and safety data channel it occupies.
Returns: boolean — true when the close succeeded; false when the close request was not accepted (see getLastStatus() / getLastErrorCode() for the reason).
dispose()
public void dispose()
Releases all resources: calls resetConnection() and then close(); exceptions from either step are ignored. Intended only for final cleanup; it does not throw.
connectionState()
public FSoEState connectionState()
Reads the current FSoE connection state.
Returns: FSoEState — one of RESET / SESSION / CONNECTION / PARAMETER / DATA / FAILSAFE.
Throws: IllegalStateException — none of the six valid state codes was read (no valid connection or a failed read). Unknown state codes are not folded into RESET to pose as "already reset".
connectionId()
public int connectionId()
The connection ID actually used after a successful initialize(...) (including the auto-allocated case). The value is recorded when initialization succeeds and is not refreshed by state reads.
Returns: int — the actual connection ID; -1 when not yet initialized or when initialization failed.
isInitialized()
public boolean isInitialized()
Returns: boolean — true when the connection is initialized; false when it is not (in which case the read really succeeded).
Throws: IllegalStateException — the state read failed. A failed read is not the same as "not initialized" and is not folded into false.
Safety data exchange
safeInputData(int bufferSize)
public byte[] safeInputData(int bufferSize)
public byte[] safeInputData()
Reads safety input data. The no-argument overload reads with a 64-byte buffer (FSoEConstants.MAX_SAFE_DATA_SIZE).
Parameters:
bufferSize(int) — buffer size in bytes; should be no smaller than the slave's safety input length
Returns:
byte[]— the safety inputs read this time, with the actual byte count as the length;null= the read failed or the length this time is 0 (an absent safety input is never passed off as normal empty data). The failure reason is distinguished throughgetLastStatus()/getLastErrorCode()
Throws: SDK call exceptions propagate unchanged (the failure state is recorded first); they never turn silently into null.
setSafeOutputData(byte[] data)
public boolean setSafeOutputData(byte[] data)
Sets the safety output data. After a successful write, the value also serves as the SafeOutputs snapshot in the cyclic event.
Parameters:
data(byte[]) — safety output data; returnsfalsefornullor an empty array (recorded asMailboxStatus.INVALID_ARG)
Returns:
boolean—trueon a successful write;falsewhen the write failed or the argument is invalid
Example:
FSoE fsoe = slave.fsoe();
// Read safety input
byte[] safeInput = fsoe.safeInputData();
if (safeInput != null) {
boolean ch0 = (safeInput[0] & 0x01) != 0;
System.out.println("通道0: " + (ch0 ? "安全" : "触发")); // Channel 0: safe / triggered
}
// Write safety output
fsoe.setSafeOutputData(new byte[]{0x01});
writeOutputFrame(byte[] frameData)
public boolean writeOutputFrame(byte[] frameData)
Writes FSoE output frame data directly, through the same channel as setSafeOutputData(byte[]).
Parameters: frameData (byte[]) — raw frame bytes; null or an empty array returns false.
Returns: boolean — true on a successful write; false when the write failed or the argument is invalid.
downloadParameters(byte[] paramData)
public int downloadParameters(byte[] paramData)
Downloads safety parameters in the PARAMETER state.
Parameters: paramData (byte[]) — parameter data; null or an empty array returns -1.
Returns: int — the SRA CRC32 value on success; -1 on failure (the reason is distinguished through getLastStatus() / getLastErrorCode()).
setFailsafeOutput(byte[] data)
public boolean setFailsafeOutput(byte[] data)
Sets the safety output value used in the failsafe state (after entering FAILSAFE the safety outputs take this value).
Parameters: data (byte[]) — failsafe output data; null or an empty array returns false.
Returns: boolean — true when set successfully; false when setting failed or the argument is invalid.
State control
requestState(FSoEState targetState)
public boolean requestState(FSoEState targetState)
Requests an FSoE state transition. Check whether the transition is legal first with FSoEHelper.isValidStateTransition(current, target).
Parameters:
targetState(FSoEState) — target state; must not benull
Returns:
boolean—truewhen the request was accepted;falsewhen the request failed (seegetLastStatus()/getLastErrorCode()for the reason).trueonly means the request was accepted; read the actual state back withconnectionState()
requestData()
public boolean requestData()
Requests entry into the data exchange state (DATA). Equivalent to requestState(FSoEState.DATA); the return value has the same meaning.
requestFailsafe()
public boolean requestFailsafe()
Enters failsafe mode (FAILSAFE) explicitly. Equivalent to requestState(FSoEState.FAILSAFE); the return value has the same meaning. Use it for fault handling when the watchdog times out or the safety inputs are abnormal; the failsafe output values are set with setFailsafeOutput(byte[]).
resetConnection()
public boolean resetConnection()
Resets the current connection to the initial state (RESET). After binding parameter changes or connection errors, reset first and then re-establish the connection.
Returns: boolean — true when the reset request was accepted; false when the reset request was not accepted.
checkWatchdog()
public boolean checkWatchdog()
Checks the watchdog state.
Returns: boolean — true when the watchdog is healthy; false on a timeout or a failed check. false does not distinguish "really timed out" from "the check did not happen"; both are treated as unhealthy.
inFailsafe()
public boolean inFailsafe()
public Boolean inFailsafeOrNull()
Whether the connection is in failsafe mode.
Returns:
inFailsafe()—boolean:truein failsafe;falsenot in failsafe (in which case the read really succeeded)inFailsafeOrNull()—Boolean:truein failsafe;falsenot in failsafe;nullthe read failed (untrustworthy)
Throws: inFailsafe() throws IllegalStateException when the state read fails. A failed read is not folded into false to pose as "safety OK"; to distinguish it yourself, use inFailsafeOrNull() or look at status().StatusValid.
watchdogExpired()
public boolean watchdogExpired()
public Boolean watchdogExpiredOrNull()
Whether the watchdog has expired.
Returns:
watchdogExpired()—boolean:trueexpired;falsenot expired (in which case the read really succeeded)watchdogExpiredOrNull()—Boolean:trueexpired;falsenot expired;nullthe read failed (untrustworthy)
Throws: watchdogExpired() throws IllegalStateException when the state read fails; the semantics are the same as inFailsafe().
lastError()
public FSoEError lastError()
Reads the most recent FSoE error code.
Returns: FSoEError — error code enum; unrecognized code values return FSoEError.NONE. This method only maps code values; it does not change the transaction bookkeeping of getLastStatus() / getLastErrorCode().
clearError()
public void clearError()
Clears the error state. Throws: SDK call exceptions propagate unchanged (the failure state is recorded first).
Example:
FSoE fsoe = slave.fsoe();
fsoe.requestState(FSoE.FSoEState.DATA);
fsoe.requestData();
fsoe.requestFailsafe();
fsoe.resetConnection();
Statistics
status()
public FSoEConnectionStatus status()
Gets the connection status details: reads a complete status snapshot in one call.
Returns:
FSoEConnectionStatus— connection status information. An object is returned even when the read fails, butStatusValid/IsConnectedarefalseand the remaining fields keep their defaults (State = RESET,InFailsafe = false,WatchdogExpired = false) and are untrustworthy; a safety diagnostics UI must show this as "unknown/read failure" and must not treat it as safety OK
Throws: SDK call exceptions propagate unchanged (the failure state is recorded first).
Related structures:
FSoEConnectionStatus
public static class FSoEConnectionStatus {
public FSoEState State; // Current FSoE state
public FSoEError LastError; // Last error code
public int ErrorCount; // Total error count
public int FramesSent; // Frames sent
public int FramesReceived; // Valid frames received
public int CrcErrors; // CRC error count
public int WatchdogErrors; // Watchdog timeout count
public boolean WatchdogExpired; // Whether the watchdog has expired
public boolean InFailsafe; // Whether the connection is in failsafe mode
public int ToggleBit; // Reserved field (ETG.5100 V1.2.0 has no toggle bit concept; do not rely on it)
public boolean IsInitialized; // Whether the connection is initialized
public boolean StatusValid; // Whether this status read is trustworthy
public boolean IsConnected; // Whether a valid connection exists (same semantics as StatusValid)
}
| Field | Type | Description |
|---|---|---|
| State | FSoEState | Current state; untrustworthy when StatusValid = false |
| LastError | FSoEError | Last error code |
| ErrorCount | int | Total error count |
| FramesSent | int | Frames sent |
| FramesReceived | int | Valid frames received |
| CrcErrors | int | CRC error count |
| WatchdogErrors | int | Watchdog timeout count |
| WatchdogExpired | boolean | Whether the watchdog has expired |
| InFailsafe | boolean | Whether the connection is in failsafe mode |
| ToggleBit | int | Reserved field, do not rely on it |
| IsInitialized | boolean | Whether the connection is initialized |
| StatusValid | boolean | Whether this status read is trustworthy; when false the other fields are untrustworthy |
| IsConnected | boolean | Whether a valid connection exists; same semantics as StatusValid |
Example:
FSoE.FSoEConnectionStatus status = slave.fsoe().status();
if (!status.StatusValid) {
System.out.println("状态读取失败, 按未知处理"); // Status read failed, treated as unknown
return;
}
System.out.println("状态: " + status.State); // State:
System.out.println("CRC 错误: " + status.CrcErrors); // CRC errors:
System.out.println("发送帧: " + status.FramesSent); // Frames sent:
System.out.println("接收帧: " + status.FramesReceived); // Frames received:
System.out.println("看门狗: " + (status.WatchdogExpired ? "过期" : "正常")); // Watchdog: expired / normal
crcErrorCount() / watchdogErrorCount() / framesSent() / framesReceived()
public int crcErrorCount()
public int watchdogErrorCount()
public int framesSent()
public int framesReceived()
Single-item statistics queries; the values match the same-named fields in status(), but a failed read throws IllegalStateException (never folded into 0, to avoid mistaking a failed read for "no errors").
Returns: int — the corresponding count.
connectionCount()
public int connectionCount()
Returns: int — the number of FSoE connections on the current master (a master-level statistic, not the connection count of a single slave).
Mailbox statistics
Besides the safety connection statistics from status(), FSoE also implements the unified IMailboxProtocol interface to provide mailbox-level statistics. As of 2.5.x, getStatistics() / resetStatistics() return real statistics (earlier versions returned an empty placeholder snapshot).
| Category | Method | Type | Read/write | Description |
|---|---|---|---|---|
| Protocol identification | getProtocolType() | byte | read-only | Protocol type constant (FSoE=0x08) |
| getProtocolName() | String | read-only | Protocol name ("FSoE") | |
| isSupported() | boolean | read-only | Whether the slave supports this protocol | |
| Transaction status | getLastStatus() | MailboxStatus | read-only | Unified status of the last mailbox transaction |
| getLastErrorCode() | long | read-only | Last protocol-layer error code (0=no error) | |
| Statistics | getStatistics() | MailboxStatistics | read-only | Mailbox statistics snapshot |
| resetStatistics() | void | write-only | Resets the mailbox statistics counters; also resets the transaction status to PENDING and the error code to 0 |
MailboxStatus values: PENDING (pending) / SUCCESS (success) / TIMEOUT (timeout) / CANCELLED (cancelled) / MAILBOX_ERROR (error frame) / PROTO_MISMATCH (protocol type mismatch) / WKC_FAIL (working counter mismatch) / NO_MEMORY (out of memory) / INVALID_ARG (invalid argument) / NOT_IMPLEMENTED (not supported) / LINK_DOWN (link down: frames fail immediately; check the cable / NIC link status) / NOT_SENT (request never left the local host: the 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 fields:
| Field | Type | Description |
|---|---|---|
| totalSent | long | Times sent |
| totalReceived | long | Times received |
| totalTimeout | long | Timeout count |
| totalMailboxError | long | Mailbox error count |
| totalProtocolError | long | Protocol error count |
| totalCancelled | long | Cancellation count |
| lastErrorCode | long | Last error code |
| lastErrorTime | Instant | Time of the last error |
| averageLatencyUs | double | Average transaction latency (microseconds) |
When a transaction fails without a specific protocol error code, getLastErrorCode() returns FSoE.FSOE_TRANSACTION_FAILED_CODE (0x80000001L): a failure path never yields an error code of 0, and the value does not collide with any FSoE protocol error code. The success path always yields an error code of 0.
MDP multi-connection
MDP (Modular Device Profile) allows a single slave to host multiple independent FSoE safety connections, each module with its own safety address and data channel.
initializeMdp(SafeModuleConfig[] moduleConfigs)
public boolean initializeMdp(SafeModuleConfig[] moduleConfigs)
Initializes MDP multi-connection mode: each module gets an independent connection, with its own connection ID, safety address and safety data lengths.
Parameters:
moduleConfigs(SafeModuleConfig[]) — module configuration array;nullor an empty array returnsfalse
Returns:
boolean—truewhen all modules initialized successfully;falseif any failed (connections already initialized are kept)
Throws:
IllegalArgumentException— a 16-bit protocol field (SlotIndex/AxisNumber) is outside0..65535. Such fields are never silently wrapped into a different module number
Related structures:
SafeModuleConfig
public static class SafeModuleConfig {
public int SlotIndex; // Module slot index
public int AxisNumber; // Axis number
public SafeModuleProfile Profile; // Module profile
public short SafetyAddress; // Safety address
public short ConnectionId; // Connection ID
public FSoEConnectionType ConnectionType; // Connection type
public short SafeInputSize; // Safety input data size
public short SafeOutputSize; // Safety output data size
public int PdoInputOffset; // PDO input offset
public int PdoOutputOffset; // PDO output offset
public int WatchdogTimeMs; // Watchdog timeout (milliseconds)
public FSoEConnectionConfig toConnectionConfig(); // Converts to a connection configuration
}
mdpSafeInputData(int connectionIndex)
public byte[] mdpSafeInputData(int connectionIndex)
public byte[] mdpSafeInputData(int connectionIndex, int bufferSize)
Reads the safety inputs of the specified MDP connection. The overload without a buffer argument reads 64 bytes.
Parameters:
connectionIndex(int) — connection index, range0..65535bufferSize(int) — buffer size (bytes)
Returns:
byte[]— safety input data;null= the read failed or the length this time is 0
Throws: IllegalArgumentException — connectionIndex is outside the 16-bit protocol field range.
setMdpSafeOutputData(int connectionIndex, byte[] data)
public boolean setMdpSafeOutputData(int connectionIndex, byte[] data)
Writes the safety outputs of the specified MDP connection.
Parameters:
connectionIndex(int) — connection indexdata(byte[]) — safety output data;nullor an empty array returnsfalse
Returns:
boolean—trueon a successful write;falsewhen the write failed or the argument is invalid
Throws: IllegalArgumentException — connectionIndex is outside the 16-bit protocol field range.
mdpConnectionState(int connectionIndex)
public FSoEState mdpConnectionState(int connectionIndex)
Reads the current state of the specified MDP connection.
Returns: FSoEState — current state.
Throws:
IllegalStateException— none of the six valid state codes was read (no valid connection or a failed read); never folded intoRESETIllegalArgumentException—connectionIndexis outside the 16-bit protocol field range
Example:
FSoE fsoe = slave.fsoe();
int connCount = fsoe.connectionCount();
for (int i = 0; i < connCount; i++) {
FSoE.FSoEState state = fsoe.mdpConnectionState(i);
byte[] input = fsoe.mdpSafeInputData(i);
System.out.printf("连接 %d: 状态=%s, 输入=%s%n", i, state, // Connection %d: state=%s, input=%s%n
input != null ? String.format("%d 字节", input.length) : "null"); // %d bytes
}
MDP device configuration
SafeMdpDeviceConfig
Complete configuration structure for MDP multi-connection devices. The Modules list is converted to SafeModuleConfig[] and then passed to initializeMdp(SafeModuleConfig[]).
public static class SafeMdpDeviceConfig {
public FSoEConnectionMode ConnectionMode; // Connection mode
public short DeviceSafetyAddress; // Device-level safety address
public boolean IsDrive; // Whether this is a drive device
public int AxisCount; // Axis count
public List<SafeModuleConfig> Modules; // Module list
public SafeModuleConfig addModule(SafeModuleProfile profile, short safetyAddress);
public SafeModuleConfig addDriveAxis(int axisNumber, short safetyAddress);
public int getConnectionCount();
}
| Method | Returns | Description |
|---|---|---|
| addModule(SafeModuleProfile, short) | SafeModuleConfig | Appends a module: SlotIndex takes the current list length, and ConnectionId is automatically 0x0001 + 列表长度 |
| addDriveAxis(int, short) | SafeModuleConfig | Appends a drive axis module (Profile = DRIVE_CONNECTION); AxisNumber takes the axis number passed in |
| getConnectionCount() | int | ConnectionMode = SINGLE returns 1; MULTIPLE returns Modules.size() |
Example:
FSoE.SafeMdpDeviceConfig devConfig = new FSoE.SafeMdpDeviceConfig();
devConfig.ConnectionMode = FSoE.FSoEConnectionMode.MULTIPLE;
// Add digital safety IO modules
devConfig.addModule(FSoE.SafeModuleProfile.DIGITAL_IN_OUT, (short) 0x0100);
devConfig.addModule(FSoE.SafeModuleProfile.DIGITAL_INPUT, (short) 0x0200);
// Add a drive axis
devConfig.addDriveAxis(0, (short) 0x0300);
// Convert to a module configuration array and initialize the multi-connection
FSoE.SafeModuleConfig[] modules =
devConfig.Modules.toArray(new FSoE.SafeModuleConfig[0]);
if (!slave.fsoe().initializeMdp(modules)) {
System.out.println("MDP 连接初始化失败"); // MDP connection initialization failed
}
Event listening
Cyclic data listener (DataExchanged)
The event registration entry point FSoE currently exposes is the DataExchanged cyclic event: it fires once per PDO cycle and carries the status snapshot for that cycle.
addDataExchangedListener(FSoEDataExchangeListener listener)
public void addDataExchangedListener(FSoEDataExchangeListener listener)
public void removeDataExchangedListener(FSoEDataExchangeListener listener)
@FunctionalInterface
public interface FSoEDataExchangeListener {
void onDataExchanged(FSoEDataExchangeEvent event);
}
Registers a cyclic data event listener; null is ignored. removeDataExchangedListener unregisters a previously registered listener; calling it with an object that was never registered has no effect.
processCycle()
public boolean processCycle()
Runs one cycle of processing and fires events: first reads this cycle's safety inputs, then the status, then compares the status and dispatches OnStateChanged / OnErrorOccurred / OnFailsafeTriggered, and finally fires DataExchanged. Call it once per cycle from the master's synchronous cycle or from your own cycle thread.
Returns: boolean — true when this cycle's snapshot is valid (both the status and the safety inputs were read); false when a read failed (the snapshot in the event is untrustworthy).
fireDataExchanged(byte[] safeInputs, byte[] safeOutputs)
public void fireDataExchanged(byte[] safeInputs, byte[] safeOutputs)
Fires the cyclic event manually (for use with your own cycle). Both the inputs and the outputs are copied. safeInputs being null means no safety inputs were read this cycle and the event is marked untrustworthy. An exception thrown by one listener does not affect the other listeners and does not block the cycle.
Event structure:
public static class FSoEDataExchangeEvent {
public final int SlaveIndex; // Slave index
public final FSoEState CurrentState; // Current FSoE state for this cycle
public final byte[] SafeInputs; // Safety input snapshot for this cycle
public final byte[] SafeOutputs; // Safety output snapshot for this cycle
public final boolean InFailsafe; // Whether the connection is in failsafe mode
public final boolean StatusValid; // Whether this cycle's snapshot is trustworthy (false = read failure, the previous three fields are untrustworthy)
public final long CycleCount; // Cumulative PDO cycle count
public final long TimestampMillis; // Event timestamp (milliseconds)
}
When StatusValid = false, CurrentState / InFailsafe / SafeInputs all hold untrustworthy default values: never treat the default false as "not in failsafe / safety OK", and never treat an empty SafeInputs as "genuinely no inputs".
Example:
FSoE fsoe = slave.fsoe();
fsoe.addDataExchangedListener(ev -> {
if (!ev.StatusValid) {
System.out.println("本周期安全状态读取失败, 周期=" + ev.CycleCount); // Failed to read the safe state this cycle, cycle={ev.CycleCount}
return;
}
if (ev.InFailsafe) {
System.out.println("FSoE 进入失效安全, 周期=" + ev.CycleCount); // FSoE entered failsafe, cycle={ev.CycleCount}
}
});
State / error / failsafe events
Besides the cyclic data event, FSoE provides three semantic event types: state change, error and failsafe. They are driven by the status comparison in processCycle() and are only produced when the cycle entry point is called.
// Register / unregister
public void addStateChangedListener(OnStateChanged listener)
public void removeStateChangedListener(OnStateChanged listener)
public void addErrorListener(OnErrorOccurred listener)
public void removeErrorListener(OnErrorOccurred listener)
public void addFailsafeListener(OnFailsafeTriggered listener)
public void removeFailsafeListener(OnFailsafeTriggered listener)
// State change event
@FunctionalInterface
public interface OnStateChanged {
void onStateChanged(FSoEStateChangedEventArgs args);
}
// Error event
@FunctionalInterface
public interface OnErrorOccurred {
void onErrorOccurred(FSoEErrorEventArgs args);
}
// Failsafe event
@FunctionalInterface
public interface OnFailsafeTriggered {
void onFailsafeTriggered(FSoEFailsafeEventArgs args);
}
A null registration argument is ignored; duplicate registrations are not deduplicated, so avoid them yourself. An exception thrown by one listener does not affect the other listeners and does not block the cycle.
Trigger rules (compared once per cycle):
| Event | Trigger condition |
|---|---|
OnStateChanged | The state changed relative to the last observation. The first observation only establishes a baseline; the first state after startup is not counted as a transition |
OnFailsafeTriggered | Entering FAILSAFE: EnteringFailsafe = true and Reason is inferred from the error code by FSoEHelper.determineFailsafeReason(...); returning from FAILSAFE to DATA: EnteringFailsafe = false, Reason = RECOVERY_TO_DATA |
OnErrorOccurred | The error code changed relative to the last observation and is not NONE |
When a state read fails, no event is fired and the baseline is not updated (a failed read is not a state transition).
Event argument structures:
public static class FSoEStateChangedEventArgs {
public int SlaveIndex; // Slave index
public int ConnectionIndex; // Connection index (multi-connection mode)
public FSoEState OldState; // Old state
public FSoEState NewState; // New state
}
public static class FSoEErrorEventArgs {
public int SlaveIndex; // Slave index
public int ConnectionIndex; // Connection index
public FSoEError Error; // Error code
public FSoEState CurrentState; // Current state
public String getDescription(); // Error description
}
public static class FSoEFailsafeEventArgs {
public int SlaveIndex; // Slave index
public int ConnectionIndex; // Connection index
public FSoEFailsafeReason Reason; // Trigger reason
public boolean EnteringFailsafe; // Whether entering failsafe
}
FSoE manager
SafetyManager
Multi-connection manager that manages the lifecycle of multiple FSoE connections.
public static class SafetyManager {
public SafetyManager(...);
public boolean addConnection(short slaveIndex, int connectionId,
short safetyAddress, int watchdogMs,
short safeInputSize, short safeOutputSize,
int pdoInputOffset, int pdoOutputOffset,
int moduleNumber);
public boolean removeConnection(int slaveIndex, int connectionId);
public SafeMdp getMdp(int slaveIndex, int connectionId);
public void processCycle();
public Map<String, FSoEConnectionStatus> getAllStatuses();
public void closeAll();
public int getConnectionCount();
public SafeMdp findByAddress(short safetyAddress);
public SafeMdp findByConnectionId(int connectionId);
public SafeMdp findConnectionByAddress(short safetyAddress);
public byte[] readInputFrame(int slaveIndex, int connectionId, int bufferSize);
public String getStatusSummary();
public boolean bindSafeInput(short slaveIndex, int connectionId,
short safetyAddress, short inputSize, int watchdogMs);
public boolean bindSafeOutput(short slaveIndex, int connectionId,
short safetyAddress, short outputSize, int watchdogMs);
public boolean bindSafeIO(short slaveIndex, int safeInputOffset, int safeInputSize,
int safeOutputOffset, int safeOutputSize,
short safetyAddress, int watchdogMs);
public boolean bindMdpSafeInput(short slaveIndex, short safetyAddress,
short inputSize, int moduleNumber, int watchdogMs);
public boolean bindMdpSafeOutput(short slaveIndex, short safetyAddress,
short outputSize, int moduleNumber, int watchdogMs);
public boolean bindMdpDriveAxis(short slaveIndex, int axisIndex,
short safetyAddress, int watchdogMs);
}
The connection table key is "slaveIndex:connectionId", and the getAllStatuses() map keys use that format; when a connection's status read fails, the corresponding value is null.
| Method | Returns | Description |
|---|---|---|
| addConnection(...) | boolean | Creates and initializes a connection (9 arguments: slave, connection ID, safety address, watchdog, input/output lengths, input/output offsets, module number). Registered in the connection table on success |
| removeConnection(int, int) | boolean | Closes the connection; removes it from the connection table whether or not the close succeeded, and returns false when the connection is not in the table |
| getMdp(int, int) | SafeMdp | Gets the SafeMdp instance for that connection; returns null when it is not registered |
| processCycle() | void | Runs one FSoE cycle of the master |
| getAllStatuses() | Map<String, FSoEConnectionStatus> | Status snapshot of all connections |
| closeAll() | void | Closes all connections and clears the connection table; exceptions from individual closes are ignored |
| getConnectionCount() | int | Number of connections currently managed |
| findByAddress(short) | SafeMdp | Finds by safety address; returns null when not found |
| findByConnectionId(int) | SafeMdp | Finds by connection ID; returns null when not found |
| findConnectionByAddress(short) | SafeMdp | Same as findByAddress(short) |
| readInputFrame(int, int, int) | byte[] | Reads the raw input frame of the specified connection; returns null when the connection is not registered |
| getStatusSummary() | String | Status summary text for all connections; "未初始化" (SDK output, = not initialized) when there are no connections |
bindSafeIO()
public boolean bindSafeIO(short slaveIndex, int safeInputOffset, int safeInputSize,
int safeOutputOffset, int safeOutputSize,
short safetyAddress, int watchdogMs)
One-step safety IO binding: establishes both the safety input and the safety output binding. It only sets up the connection and does not request a state change; entering data exchange still requires requestState(...).
Parameters:
slaveIndex(short) — slave indexsafeInputOffset(int) — byte offset of the input safety data (currently not used for the binding; the offset in the connection configuration is fixed at 0)safeInputSize(int) — safety input data size (bytes)safeOutputOffset(int) — byte offset of the output safety data (currently not used for the binding, same as above)safeOutputSize(int) — safety output data size (bytes)safetyAddress(short) — safety address (hardware DIP switch)watchdogMs(int) — watchdog timeout (milliseconds)
Returns: boolean — true when both the input and the output binding succeeded. Both bindings share the same connection ID (slaveIndex + 1), so getConnectionCount() is still 1.
Throws: IllegalArgumentException — a 16-bit field (safety input/output length) is outside 0..65535.
Example:
FSoE.SafetyManager mgr = ...; // Constructed from the master context
// One-step binding (then requestState to enter DATA)
boolean ok = mgr.bindSafeIO((short) 1, 0, 2, 0, 1, (short) 0x0100, 100);
System.out.println(mgr.getStatusSummary());
bindSafeInput() / bindSafeOutput()
public boolean bindSafeInput(short slaveIndex, int connectionId,
short safetyAddress, short inputSize, int watchdogMs)
public boolean bindSafeOutput(short slaveIndex, int connectionId,
short safetyAddress, short outputSize, int watchdogMs)
Binds a single connection for safety inputs only or safety outputs only; the caller specifies the connection ID.
Parameters:
slaveIndex(short) — slave indexconnectionId(int) — connection ID (0..65535, unique within the same master)safetyAddress(short) — safety addressinputSize/outputSize(short) — safety data size (bytes) for the corresponding direction; the other direction is treated as 0watchdogMs(int) — watchdog timeout (milliseconds)
Returns: boolean — true when the binding succeeded.
bindMdpSafeInput() / bindMdpSafeOutput()
public boolean bindMdpSafeInput(short slaveIndex, short safetyAddress,
short inputSize, int moduleNumber, int watchdogMs)
public boolean bindMdpSafeOutput(short slaveIndex, short safetyAddress,
short outputSize, int moduleNumber, int watchdogMs)
Binds an input-only or output-only safety module on an MDP modular device (ETG.5001) (typical examples: emergency stop button / light curtain feedback / safety relay output); the connection ID is automatically moduleNumber + 1.
Parameters:
slaveIndex(short) — slave indexsafetyAddress(short) — safety addressinputSize/outputSize(short) — safety data size (bytes) for the corresponding directionmoduleNumber(int) — MDP module number (starting at 0)watchdogMs(int) — watchdog timeout (milliseconds)
Returns: boolean — true when the binding succeeded.
bindMdpDriveAxis()
public boolean bindMdpDriveAxis(short slaveIndex, int axisIndex,
short safetyAddress, int watchdogMs)
Binds the STO/SS1/SS2 safety connection of an MDP drive axis. Each axis gets an independent FSoE connection, the connection ID is automatically axisIndex + 1, and the module profile is SafeModuleProfile.DRIVE_CONNECTION. The safety data lengths and offsets are determined by the module description and do not need to be entered manually.
Parameters:
slaveIndex(short) — slave indexaxisIndex(int) — axis/module index (starting at 0)safetyAddress(short) — safety addresswatchdogMs(int) — watchdog timeout (milliseconds)
Returns: boolean — true when the binding succeeded.
bindSafeIO/bindSafeInput/bindSafeOutput— require the safety data lengths to be entered manually; suitable for non-MDP safety slaves (bare FSoE connections)bindMdpSafeInput/bindMdpSafeOutput— bind a single-direction module by MDP module number; the connection ID ismoduleNumber + 1bindMdpDriveAxis— binds a drive safety connection by axis number; the lengths and offsets are determined by the module description
Example (dual-axis MDP safety drive plus one emergency stop input):
FSoE.SafetyManager mgr = ...; // Constructed from the master context
// Emergency stop button (input)
mgr.bindMdpSafeInput((short) 2, (short) 0x0001, (short) 2, 0, 100);
// Dual-axis drive
mgr.bindMdpDriveAxis((short) 1, 0, (short) 0x0100, 100); // Axis 0
mgr.bindMdpDriveAxis((short) 1, 1, (short) 0x0200, 100); // Axis 1
System.out.println(mgr.getStatusSummary());
mgr.closeAll();
Bulk operations
// Check whether all connections are in the DATA state
// (determined by iterating over the connection statuses)
// Get the status summary
System.out.println(mgr.getStatusSummary());
// Close all connections
mgr.closeAll();
SafeMdp
Accessor for a single MDP connection (nested class FSoE.SafeMdp). It can be used on its own without SafetyManager, and likewise requires the master context to construct.
public static class SafeMdp {
public boolean initConnection(int connectionId, short safetyAddress,
int watchdogTimeMs, short safeInputSize,
short safeOutputSize, int pdoInputOffset,
int pdoOutputOffset, int moduleNumber,
int moduleProfile, int axisNumber,
int connectionType);
public boolean closeConnection(int connectionId);
public FSoEConnectionStatus getStatus(int connectionId);
public boolean requestState(int connectionId, int targetState);
public int getState(int connectionId);
public boolean reset(int connectionId);
public boolean writeSafeOutput(int connectionId, byte[] data);
public byte[] readSafeInput(int connectionId, int bufferSize);
public int downloadParameters(int connectionId, byte[] paramData);
public boolean setFailsafeOutput(int connectionId, byte[] data);
public boolean checkWatchdog(int connectionId);
public int getLastError(int connectionId);
public void clearError(int connectionId);
public int getSlaveConnectionCount();
public int detectConnections();
public int getDeviceAddress();
public byte[] getModuleCommParam(int moduleNumber, int bufferSize);
public int[] getModuleDiagnosis(int moduleNumber);
}
| Method | Returns | Description |
|---|---|---|
| initConnection(...) | boolean | Initializes an MDP connection (11 arguments: connection ID, safety address, watchdog, input/output lengths, input/output offsets, module number, module profile number, axis number, connection type) |
| closeConnection(int) | boolean | Closes the connection |
| getStatus(int) | FSoEConnectionStatus | Connection status snapshot; returns null on a failed read (not an "untrustworthy snapshot") |
| requestState(int, int) | boolean | Requests a state transition; pass FSoEState.value() for targetState |
| getState(int) | int | Raw code value of the current state; map it with FSoEState.fromValue(int) |
| reset(int) | boolean | Resets the connection |
| writeSafeOutput(int, byte[]) | boolean | Writes safety outputs; returns false when data is null or empty |
| readSafeInput(int, int) | byte[] | Reads safety inputs; returns null on failure or when the length is 0 |
| downloadParameters(int, byte[]) | int | Downloads safety parameters; returns the SRA CRC32, or -1 on failure or with empty parameters |
| setFailsafeOutput(int, byte[]) | boolean | Sets the failsafe output value; returns false when data is null or empty |
| checkWatchdog(int) | boolean | Whether the watchdog is healthy |
| getLastError(int) | int | Raw value of the last error code |
| clearError(int) | void | Clears the connection error |
| getSlaveConnectionCount() | int | Number of MDP connections on this slave |
| detectConnections() | int | Automatically probes the number of MDP connections this slave supports |
| getDeviceAddress() | int | Device safety address; returns -1 on failure |
| getModuleCommParam(int, int) | byte[] | Module communication parameter bytes; returns null on failure or when the length is 0 |
| getModuleDiagnosis(int) | int[] | [连接状态, 连接诊断]; returns null on failure |
Throws: In every method that takes a connectionId / moduleNumber / axis number, a 16-bit field outside 0..65535 throws IllegalArgumentException; it is never silently wrapped into a different ID.
Connection ID validation
isConnectionIdAvailable(int connId) / validateConnId(int connId)
public static boolean isConnectionIdAvailable(int connId)
public static boolean validateConnId(int connId)
Checks whether the specified FSoE Connection ID is available (not occupied by the current master). This is a static method callable without instantiating FSoE; configuration tools use it to check for conflicts before allocating a new ConnID, so that initialize does not fail on a duplicate.
Parameters:
connId(int) — candidate Connection ID, valid range1..65535
Returns:
boolean—truewhen available (not occupied and not 0);falsewhen already occupied, equal to0(reserved value) or outside1..65535(never wrapped into another ID)
Throws:
validateConnId(int)— throwsUnsupportedOperationExceptionwhen the query itself fails;isConnectionIdAvailable(int)returnsfalsein the same situation
ConnIDmust be>= 1;0is a reserved valueConnIDmust be globally unique within the same master
Example:
int myConnId = 0x1234;
if (!FSoE.isConnectionIdAvailable(myConnId)) {
System.out.println("ConnID 0x" + Integer.toHexString(myConnId) + " 已被占用"); // ConnID 0x{Integer.toHexString(myConnId)} is already in use
return;
}
// Run initialize only after the conflict check passes
FSoE.FSoEConnectionConfig config = new FSoE.FSoEConnectionConfig();
config.ConnectionId = (short) myConnId;
config.SafetyAddress = 0x0100;
config.WatchdogTimeMs = 100;
config.SafeInputSize = 2;
config.SafeOutputSize = 1;
slave.fsoe().initialize(config);
CRC calculation
fsoeCrc16(byte[] data)
public static int fsoeCrc16(byte[] data)
Computes the FSoE CRC16 check value. The algorithm follows the safety polynomial in ETG.5100 §8.1.3.2 (0x139B7, low 16 bits 0x39B7, see FSoEConstants.CRC16_POLY) with an initial value of 0xFFFF (FSoEConstants.CRC16_INITIAL); each byte is processed from bit7 to bit0, with no reflection and no final XOR. The connection ID does not participate in the calculation.
Returns: int — the CRC value in 0..0xFFFF; null data is treated as an empty array.
fsoeCrc16Fast(byte[] data)
public static int fsoeCrc16Fast(byte[] data)
The result is exactly the same as fsoeCrc16(byte[]); kept only for compatibility (the algorithm is fixed and there is no local fast path).
FSoECrc16 class
CRC-16 calculator that can include a connection ID prefix.
public static class FSoECrc16 {
public FSoECrc16(); // The connection ID does not participate in the calculation
public FSoECrc16(int connectionId); // Carries a connection ID prefix
public int compute(byte[] data); // Computes CRC-16
}
| Method | Description |
|---|---|
FSoECrc16() | The connection ID does not participate in the calculation |
FSoECrc16(int connectionId) | Carries a connection ID prefix; range 1..65535; passing 0 means it does not participate |
compute(byte[]) | Returns the CRC value in 0..0xFFFF |
The old three-argument constructor (custom polynomial / initial value / XOR output) has been removed: the polynomial and initial value are fixed by the protocol and are not configurable.
PDO frame encoding and decoding
The layout of FSoE frames in the process data area and the encoding/decoding of frame contents, for scenarios that handle on-wire frames directly (configuration tools, diagnostics, protocol debugging). For day-to-day safety data exchange, safeInputData() / setSafeOutputData() are sufficient; you do not need to assemble frames yourself.
FSoEPdoLayout
public static class FSoEPdoLayout {
public int CommandOffset; // Command byte offset
public int SafeDataOffset; // Safety data start offset
public int SafeDataLength; // Total safety data length (bytes)
public int CrcSegmentCount; // Number of CRC segments
public int ConnIdOffset; // Connection ID (little-endian u16) offset
public int TotalLength; // Total frame length
public int PaddingBytes; // Padding for an odd byte in the last segment (0 or 1)
public int[] CrcOffsets; // Offset of each segment CRC (little-endian u16)
public static FSoEPdoLayout create(int safeDataLength);
public void validate();
}
Wire order per ETG.5100 §5.2.1:
[Command][D0 D1][CRC_0][D2 D3][CRC_1]...[last segment data][CRC_k][ConnID u16]
Each data segment is 2 bytes (the last segment is padded with 1 byte of 0x00 when it has an odd byte count), each segment CRC follows immediately after its segment, and the connection ID follows the last segment CRC. The number of CRC segments is the safety data length divided by 2, rounded up, with at least 1 segment (a length of 0 still yields 1 command CRC).
| Method | Description |
|---|---|
create(int safeDataLength) | Builds the layout above for the given safety data length. Throws: IllegalArgumentException — the length is outside 0..64 |
validate() | Validates that the layout is self-consistent (segment count, offsets and lengths match each other). Throws: IllegalArgumentException — the layout is inconsistent or a field is invalid |
FSoEPdoFrame
public static class FSoEPdoFrame {
public FSoECommand Command; // Command
public int ConnectionId; // Connection ID
public int SequenceNumber; // Virtual sequence number (check input, not sent on the wire)
public int LastCrc0; // CRC_0 this side sent last time (check input)
public byte[] SafeData; // Safety data; the length must equal the layout's SafeDataLength
public int[] CrcSegments; // Segment CRCs
public byte[] toBytes(FSoEPdoLayout layout, FSoECrc16 crcCalc);
public static FSoEPdoFrame fromBytes(byte[] data, FSoEPdoLayout layout, FSoECrc16 crcCalc);
public static FSoEPdoFrame fromBytes(byte[] data, FSoEPdoLayout layout,
int sequenceNumber, int lastCrc0);
public boolean validateCrc(FSoEPdoLayout layout);
}
| Method | Description |
|---|---|
toBytes(layout, crcCalc) | Serializes to on-wire frame bytes with length = layout.TotalLength, and writes the emitted segment CRCs back into CrcSegments. crcCalc is a compatibility parameter and does not participate in the calculation (passing null gives the same result as passing an instance) |
fromBytes(data, layout, crcCalc) | Parses and checks using the first-frame convention (SequenceNumber = 1, LastCrc0 = 0) |
fromBytes(data, layout, sequenceNumber, lastCrc0) | Parses and checks using the check inputs supplied by the caller; use this overload for frames on an established connection |
validateCrc(layout) | true when all segment CRCs match; false when a CRC does not match; other failures throw |
Throws:
IllegalArgumentException— an argument, the layout or the safety data length is invalid (nullframe data / layout,SafeDatalength not matching the layout, etc.)IllegalStateException— runtime failures such as an encoding failure, a CRC mismatch or an insufficient buffer
SequenceNumber / LastCrc0 only participate in the check calculation and are not written to the on-wire frame: use 1 / 0 for the first frame, and subsequent frames must match the values this side expects, otherwise the CRC is guaranteed to mismatch.
FSoEState
FSoE connection state enum (ETG.5100 §4.2.6); the values of connectionState() / status().State.
public enum FSoEState {
RESET(0x100), // Initial/reset state
SESSION(0x101), // Session established
CONNECTION(0x102), // Connection established
PARAMETER(0x103), // Parameter download
DATA(0x104), // Data exchange (normal operation)
FAILSAFE(0x105); // Failsafe
}
fromValue(int) maps a code value to the enum, and unrecognized code values return RESET; when you need to distinguish "state could not be read", use connectionState(), which throws.
FSoEError
FSoE error code enum (ETG.5001.4); the values of lastError() / status().LastError. fromValue(int) maps a code value to the enum, and unrecognized code values return NONE.
public enum FSoEError {
NONE(0x0000), // No error
WRONG_COMMAND(0x0001), // Wrong command
UNKNOWN_COMMAND(0x0002), // Unknown command
WRONG_CONNECTION_ID(0x0003), // Connection ID mismatch
CRC_ERROR(0x0004), // CRC check failed
WATCHDOG(0x0005), // Watchdog timeout
WRONG_ADDRESS(0x0006), // Wrong FSoE address
WRONG_DATA(0x0007), // Invalid data
COMM_PARAM_LENGTH(0x0008), // Communication parameter length error
COMM_PARAM(0x0009), // Communication parameter error
APP_PARAM_LENGTH(0x000A), // Application parameter length error
APP_PARAM(0x000B), // Application parameter error
UNEXPECTED_SESSION(0x000C), // Unexpected session command
FAILSAFE_DATA(0x000D), // Failsafe data received
NOT_INITIALIZED(0x0100), // FSoE not initialized
MAX_CONNECTIONS(0x0101), // Maximum number of connections reached
INVALID_STATE_TRANSITION(0x0102) // Invalid state transition
}
Other enums
FSoECommand
public enum FSoECommand {
RESET((byte) 0x2A), // Reset command (ETG.5100 Table 5)
SESSION((byte) 0x4E), // Session request/response
CONNECTION((byte) 0x64), // Connection request/response
PARAMETER((byte) 0x52), // Parameter download
FAILSAFE((byte) 0x08), // Failsafe mode
DATA((byte) 0x36); // Normal data exchange / ProcessData
}
FSoEFailsafeReason
public enum FSoEFailsafeReason {
WATCHDOG_TIMEOUT(0), // Watchdog timeout
CRC_ERROR(1), // CRC error
COMMUNICATION_ERROR(2), // Communication error
APPLICATION_REQUEST(3), // Application request
SLAVE_REQUEST(4), // Slave request
MASTER_REQUEST(5), // Master request
RECOVERY_TO_DATA(6); // Recovery to data mode
}
SafeModuleProfile
public enum SafeModuleProfile {
DIGITAL_INPUT(190), // FSoE digital input
DIGITAL_IN_OUT(195), // FSoE digital input/output
DIGITAL_OUTPUT(290), // FSoE digital output
DRIVE_CONNECTION(790), // FSoE MDP drive connection
MASTER(6900); // FSoE master
}
FSoEConnectionMode / FSoEConnectionType
| Enum | Member | Value | Meaning |
|---|---|---|---|
FSoEConnectionMode | SINGLE | 0 | Single-connection mode: all modules share one FSoE connection and safety address |
FSoEConnectionMode | MULTIPLE | 1 | Multi-connection mode: each module has its own FSoE connection and safety address |
FSoEConnectionType | MASTER | 0 | FSoE master connection (ETG.5120 SI6) |
FSoEConnectionType | SLAVE | 1 | FSoE slave connection (ETG.5120 SI6) |
FSoEDiagnosisBits
Diagnostic bit definitions (ETG.5001.4 Table 9). The low 4 bits are the error code; the high bits indicate where the error occurred and the connection state.
| Member | Value | Meaning |
|---|---|---|
| NO_ERROR | 0x0000 | No error |
| WRONG_COMMAND | 0x0001 | Wrong command |
| UNKNOWN_COMMAND | 0x0002 | Unknown command |
| WRONG_CONNECTION_ID | 0x0003 | Connection ID mismatch |
| WRONG_CRC | 0x0004 | CRC check failed |
| WATCHDOG_EXPIRED | 0x0005 | Watchdog expired |
| WRONG_FSOE_ADDRESS | 0x0006 | Wrong FSoE safety address |
| WRONG_DATA | 0x0007 | Invalid data |
| WRONG_COMM_PARAM_LENGTH | 0x0008 | Communication parameter length error |
| WRONG_COMM_PARAM | 0x0009 | Communication parameter error |
| WRONG_APPL_PARAM_LENGTH | 0x000A | Application parameter length error |
| WRONG_APPL_PARAM | 0x000B | Application parameter error |
| UNEXPECTED_SESSION_CMD | 0x000C | Unexpected session command |
| FAILSAFE_DATA_RECEIVED | 0x000D | Failsafe data received |
| ERROR_MASK | 0x000F | Error code mask |
| ERROR_IN_MASTER | 0x0000 | Error occurred in the master |
| ERROR_IN_SLAVE | 0x0010 | Error occurred in the slave |
| SLAVE_IN_FAILSAFE | 0x0020 | The slave is in failsafe |
| CONNECTION_IN_STARTUP | 0x0040 | The connection is starting up |
| MASTER_IN_FAILSAFE | 0x0080 | The master is in failsafe |
Constants and helper methods
FSoEConstants
public static final class FSoEConstants {
public static final int MAX_CONNECTIONS; // 64, maximum number of FSoE connections per master
public static final int MAX_SAFE_DATA_SIZE; // 64, maximum safety data per connection (bytes)
public static final int MAX_CRC_SEGMENTS; // 32, maximum number of CRC segments
public static final int FRAME_HEADER_SIZE; // 3, frame header size (command + connection ID)
public static final int FRAME_CRC_SIZE; // 2, frame CRC size
public static final int CRC16_POLY; // 0x39B7, CRC16 polynomial (low 16 bits)
public static final int CRC16_INITIAL; // 0xFFFF, CRC16 initial value
public static final int SRA_CRC32_POLY; // 0x814141AB, SRA CRC32 polynomial (ETG.5120 §6.3)
public static final int DEFAULT_WATCHDOG_TIME_MS; // 100, default watchdog timeout (milliseconds)
}
There are four additional mask constants — COMMAND_TYPE_MASK / TOGGLE_BIT_MASK / MASTER_RESET_MASK / SLAVE_RESET_MASK: commands in ETG.5100 V1.2.0 are whole-byte values with no toggle bit and no master/slave reset bits, so these constants are kept only for compatibility; do not rely on them.
FSoEHelper
Command parsing, state transition legality checks, and error code text.
public static final class FSoEHelper {
public static FSoECommand getCommandType(int command);
public static boolean isValidStateTransition(FSoEState current, FSoEState target);
public static FSoEFailsafeReason determineFailsafeReason(FSoEError lastError);
public static String getErrorDescription(FSoEError error);
}
| Method | Returns | Description |
|---|---|---|
getCommandType(int) | FSoECommand | Decodes the command type from the command byte (whole-byte match, no bitmask) |
isValidStateTransition(FSoEState, FSoEState) | boolean | Whether the state transition is legal; returns false when either argument is null |
determineFailsafeReason(FSoEError) | FSoEFailsafeReason | Infers the failsafe trigger reason from the error code (WATCHDOG → watchdog timeout, CRC_ERROR → CRC error, command/data errors → slave request, application parameter errors → application request, everything else falls back to communication error). Used only when entering failsafe; leaving failsafe is always RECOVERY_TO_DATA |
getErrorDescription(FSoEError) | String | Chinese description of the error code |
Legal state transitions:
| Current | Allowed targets |
|---|---|
RESET | SESSION |
SESSION | CONNECTION, RESET |
CONNECTION | PARAMETER, RESET |
PARAMETER | DATA, RESET |
DATA | FAILSAFE (a direct transition to RESET is not allowed) |
FAILSAFE | DATA, RESET |
There are also four deprecated methods whose signatures are kept but which no longer participate in the protocol: getToggleBit(int) always returns false; isMasterResetRequest(int) / isSlaveResetRequest(int) only test whether the command is RESET; buildCommand(FSoECommand, boolean, boolean, boolean) returns the command byte value directly. To test for a reset, use command == FSoECommand.RESET.value().
SafeMdpIndex
MDP object index area definitions (ETG.5001.4), for computing object indexes by area.
| Constant | Value | Meaning |
|---|---|---|
| AXIS_INDEX_OFFSET | 0x0800 | Axis index offset |
| MODULE_INDEX_OFFSET | 0x0010 | Module index offset |
| CONFIG_AREA_BASE | 0x8000 | Configuration area base address |
| DIAG_AREA_BASE | 0xA000 | Diagnostics area base address |
| INFO_AREA_BASE | 0x9000 | Information area base address |
| INPUT_AREA_BASE | 0x6000 | Input area base address |
| OUTPUT_AREA_BASE | 0x7000 | Output area base address |
| DRIVE_CONFIG_AREA_BASE | 0xE800 | Drive configuration area base address |
| DRIVE_DIAG_AREA_BASE | 0xEA00 | Drive diagnostics area base address |
| DRIVE_INFO_AREA_BASE | 0xE900 | Drive information area base address |
| DRIVE_INPUT_AREA_BASE | 0xE600 | Drive input area base address |
| DRIVE_OUTPUT_AREA_BASE | 0xE700 | Drive output area base address |
| PARAM_SET_MAPPING_BASE | 0x1E00 | Parameter set mapping base address |
| RX_PDO_MAPPING_BASE | 0x1600 | Receive PDO mapping base address |
| TX_PDO_MAPPING_BASE | 0x1A00 | Transmit PDO mapping base address |
| DEVICE_FSOE_ADDRESS | 0xF980 | Device FSoE safety address |
getAxisIndex(int baseIndex, int axisNumber) returns baseIndex + axisNumber * AXIS_INDEX_OFFSET; getModuleIndex(int baseIndex, int moduleNumber) returns baseIndex + moduleNumber * MODULE_INDEX_OFFSET.
Complete examples
Digital safety IO
FSoE fsoe = slave.fsoe();
if (fsoe.isCapable()) {
// Initialize the connection
FSoE.FSoEConnectionConfig config = new FSoE.FSoEConnectionConfig();
config.ConnectionId = 0x0100;
config.SafetyAddress = 0x0100;
config.WatchdogTimeMs = 100;
config.SafeInputSize = 2;
config.SafeOutputSize = 1;
fsoe.initialize(config);
// Request data exchange
fsoe.requestData();
// Register the cyclic data listener (DataExchanged is the only event entry point currently exposed)
fsoe.addDataExchangedListener(ev -> {
if (ev.InFailsafe) {
System.out.println("进入失效安全! 周期=" + ev.CycleCount // Entered failsafe! cycle={ev.CycleCount}
+ ", 状态=" + ev.CurrentState); // , state={ev.CurrentState}
}
});
// Cyclic data exchange
while (running) {
byte[] safeInput = fsoe.safeInputData();
if (safeInput != null) {
boolean ch0 = (safeInput[0] & 0x01) != 0;
fsoe.setSafeOutputData(new byte[]{ ch0 ? (byte) 0x01 : (byte) 0x00 });
}
// Check the state
if (fsoe.inFailsafe()) {
System.out.println("安全模式已触发!"); // Safety mode triggered!
break;
}
Thread.sleep(1);
}
// View statistics
FSoE.FSoEConnectionStatus status = fsoe.status();
System.out.printf("发送: %d, 接收: %d, CRC错误: %d%n", // Sent: %d, received: %d, CRC errors: %d%n
status.FramesSent, status.FramesReceived, status.CrcErrors);
fsoe.close();
}
SafetyManager one-step binding
FSoE.SafetyManager mgr = ...; // Constructed from the master context
// One-step binding (only establishes the connection; call requestState afterwards to enter DATA)
mgr.bindSafeIO((short) 1, 0, 2, 0, 1, (short) 0x0100, 100);
slave.fsoe().requestState(FSoE.FSoEState.DATA);
// Check the status
System.out.println(mgr.getStatusSummary());
// Read and write safety data in the PDO callback
master.events().addProcessDataCyclicSyncListener(mi -> {
mgr.processCycle();
// Read safety input
byte[] data = slave.fsoe().safeInputData();
if (data != null) {
boolean ch0 = (data[0] & 0x01) != 0;
slave.fsoe().setSafeOutputData(new byte[]{ ch0 ? (byte) 0x01 : (byte) 0x00 });
}
});
// ... close after running
mgr.closeAll();
Safety drive
FSoE fsoe = slave.fsoe();
if (fsoe.isCapable()) {
// Initialize the safety drive connection (10 bytes input + 2 bytes output)
FSoE.FSoEConnectionConfig config = new FSoE.FSoEConnectionConfig();
config.ConnectionId = 0x0100;
config.SafetyAddress = 0x0100;
config.WatchdogTimeMs = 100;
config.SafeInputSize = 10; // Safety status word u16 + actual safety position i32 + actual safety velocity i32
config.SafeOutputSize = 2; // Safety control word u16
fsoe.initialize(config);
fsoe.requestData();
// Failsafe monitoring (through the DataExchanged cyclic event)
fsoe.addDataExchangedListener(ev -> {
if (ev.InFailsafe) {
System.out.println("驱动器安全停止! 周期=" + ev.CycleCount); // Drive safe stop! cycle={ev.CycleCount}
}
});
// Cyclic safety drive control
while (running) {
byte[] safeInput = fsoe.safeInputData();
if (safeInput != null && safeInput.length >= 10) {
// Parse the safety status word (first 2 bytes, little-endian)
int safetyStatus = (safeInput[0] & 0xFF) | ((safeInput[1] & 0xFF) << 8);
byte[] output = new byte[2];
if ((safetyStatus & 0x0100) != 0) {
// Bit8: safety fault -> acknowledge the fault
output[0] = (byte) 0x80;
output[1] = 0x00;
// Read the actual safety position (bytes 2-5)
int position = (safeInput[2] & 0xFF)
| ((safeInput[3] & 0xFF) << 8)
| ((safeInput[4] & 0xFF) << 16)
| ((safeInput[5] & 0xFF) << 24);
System.out.printf("安全故障: 位置=%d%n", position); // Safety fault: position=%d%n
} else {
// Normal operation: clear the STO request
output[0] = 0x00;
output[1] = 0x00;
}
fsoe.setSafeOutputData(output);
}
Thread.sleep(1);
}
fsoe.close();
}
MDP multi-connection mode
FSoE fsoe = slave.fsoe();
if (fsoe.isCapable()) {
// Configure multiple modules
FSoE.SafeModuleConfig[] modules = new FSoE.SafeModuleConfig[2];
modules[0] = new FSoE.SafeModuleConfig();
modules[0].SafetyAddress = 0x0100;
modules[0].ConnectionId = 0x0001;
modules[0].SafeInputSize = 2;
modules[0].SafeOutputSize = 1;
modules[0].WatchdogTimeMs = 100;
modules[0].Profile = FSoE.SafeModuleProfile.DIGITAL_IN_OUT;
modules[1] = new FSoE.SafeModuleConfig();
modules[1].SafetyAddress = 0x0200;
modules[1].ConnectionId = 0x0002;
modules[1].SafeInputSize = 2;
modules[1].SafeOutputSize = 0;
modules[1].WatchdogTimeMs = 100;
modules[1].Profile = FSoE.SafeModuleProfile.DIGITAL_INPUT;
fsoe.initializeMdp(modules);
// Access data by connection index
int connCount = fsoe.connectionCount();
for (int i = 0; i < connCount; i++) {
FSoE.FSoEState state = fsoe.mdpConnectionState(i);
byte[] input = fsoe.mdpSafeInputData(i);
System.out.printf("连接 %d: %s%n", i, state); // Connection %d: %s%n
}
}
Multi-axis safety drive (MDP mode)
FSoE.SafetyManager mgr = ...; // Constructed from the master context
// Bind 2 axes (independent FSoE connection per axis; size/offsets are discovered automatically from the MDP description)
mgr.bindMdpDriveAxis((short) 1, 0, (short) 0x0100, 100); // Axis 0
mgr.bindMdpDriveAxis((short) 1, 1, (short) 0x0200, 100); // Axis 1
System.out.println(mgr.getStatusSummary());
// Handle each axis's safety data in the PDO callback
master.events().addProcessDataCyclicSyncListener(mi -> {
mgr.processCycle();
// Read and write safety data independently for each axis...
});
// Failsafe monitoring (through the DataExchanged cyclic event)
slave.fsoe().addDataExchangedListener(ev -> {
if (ev.InFailsafe) {
System.out.printf("从站%d 失效安全, 周期=%d%n", // Slave %d failsafe, cycle=%d%n
ev.SlaveIndex, ev.CycleCount);
}
});
// Close after running
mgr.closeAll();
Failures and handling
| Symptom | Cause | Handling |
|---|---|---|
Stuck in SESSION / CONNECTION / PARAMETER for a long time | The safety address or connection ID does not match the slave | Verify the slave's DIP-switch safety address against the configuration; confirm the connection ID is not occupied |
| checkWatchdog returns false | Watchdog timeout; the safety data was not refreshed on time | Call requestFailsafe() immediately; check the cycle calls and the communication state, then reconnect with resetConnection() |
| initialize returns false or the connection is not established | Connection ID conflict, or the same master already occupies that ID | Switch to an unoccupied connection ID and initialize again |
inFailsafe() returns true | The slave or the master has triggered failsafe | Investigate the safety inputs and the fault cause; after handling it, reconnect and re-enter data exchange with resetConnection() under safe conditions |
inFailsafe() / watchdogExpired() / isInitialized() throws IllegalStateException | The state read failed (no valid connection or a failed read) | Do not treat the exception as false; use inFailsafeOrNull() / watchdogExpiredOrNull() instead, or look at status().StatusValid |
connectionState() / mdpConnectionState() throws IllegalStateException | The state code is not one of the six valid values | Treat it as no valid connection; check whether initialize(...) was called and whether the safety address matches the slave |
status().StatusValid is false | This status read failed | The other fields are untrustworthy; display as "unknown/read failure" and do not treat it as safety OK |
safeInputData() returns null | Not in DATA, no safety inputs read this cycle, or the read failed | Handle it as a fault: call checkWatchdog() first, then decide between requestFailsafe() and reconnecting with resetConnection(); never pass off the previous cycle's cache as this cycle's data |
requestState(...) returns false | The target state is illegal, or the connection is not ready | Verify the transition with FSoEHelper.isValidStateTransition(current, target); confirm the current state with connectionState() |
downloadParameters(...) returns -1 | Not in the PARAMETER state, the parameters are empty, or the download failed | Call requestState(FSoEState.PARAMETER) first, then retry with non-empty parameters |
mdpSafeInputData(...) / getStatus(...) returns null | The connection is not registered, or the read failed | Use getStatusSummary() to check whether the connection is registered; a failed read is not "no safety input" |