Skip to main content

FSoE functional safety

FSoE (Functional Safety over EtherCAT) is the FSoE state machine and protocol interface inside the ETH master, layering a safety protocol on top of the standard PDO channel. The cycle path is fail-closed. This is not a certified safety product and is not a PLC capability; the minimum cycle is 125 µs (flexible).

Accessed through slave.fsoe. Whether FSoE is supported is queried with is_capable.​

FSoE device detection

The SDK performs FSoE device detection automatically; the result is queried through slave.fsoe.is_capable. The detection sequence:

  1. CoE prerequisite — the slave must support the CoE mailbox protocol
  2. 0xF980:01 check — attempt an SDO read of the device-level FSoE safety address; success confirms support
  3. 0x9001:02 check — if the previous step fails, attempt to read the MDP connection parameters (applies to multi-module safety devices)

Checking CoE support alone is not enough, because many non-safety devices also support CoE. An FSoE device must implement the specific safety object indices to be recognized correctly.

The SDK provides three levels of FSoE support:

  • slave.fsoe — basic interface, accessed through the slave, providing single-connection FSoE operations
  • SafeMdp — MDP multi-connection manager, supporting multiple FSoE connections on one slave
  • SafetyManager — multi-slave multi-connection coordinator, providing one-step initialization with bind_safe_io

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
Automatic state advance

SafetyManager.bind_safe_io() performs initialization + starts the data exchange in one line; the intermediate states (Session → Connection → Parameter) are advanced automatically by the SDK.

Quick start​

Recommended approach

Use SafetyManager.bind_safe_io() for one-step initialization; no manual state machine handling is needed.

SafetyManager / SafeMdp are advanced APIs

SafetyManager / SafeMdp are advanced APIs; use them only when multi-slave multi-connection coordination or MDP multi-module scenarios are required. For ordinary single-slave safety data read/write, slave.fsoe (basic interface) is enough. The construction form of the advanced APIs may change later; do not hard-code it in production code for the long term.

from darra_ethercat import EtherCATMaster, EcState, SafetyManager

master = EtherCATMaster()
master.set_eni("config.deni")
master.build()
master.set_state(EcState.OP)

# bind safety IO in one step
mgr = SafetyManager(...) # create the multi-slave safety connection coordinator
mgr.bind_safe_io(
slave_index=1,
safe_input_offset=0,
safe_input_size=2,
safe_output_offset=0,
safe_output_size=1,
safety_address=0x0100,
watchdog_ms=100
)

# read/write safety data in the PDO callback (bind_safe_io uses connection_id = slave_index + 1)
def on_pdo(mi):
data = mgr.read_input_frame(1, 2)
if data:
mgr.write_output_frame(1, 2, bytes([0x01]))

master.on_pdo_cycle(on_pdo)

FSoE versus regular PDO​

FSoE safety data cannot be mapped directly the way regular PDOs are. The reason is a difference at the protocol layer:

Comparison in use

Despite the different underlying mechanism, bind_safe_io + the data exchange callback are already very close to regular PDO in use.

Regular PDO​

The data in IOmap is the user data; the mapped structure is read and written directly

FSoE PDO​

The process data frame 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 handles:

  • CRC checking — verifies input frame integrity, computes the output frame CRC
  • State machine management — advances Session -> Connection -> Parameter -> Data automatically
  • Watchdog — monitors communication timeouts and enters Failsafe automatically on timeout
  • Sequence numbers — detects lost and duplicate frames

Modifying PDO frames directly, bypassing the protocol engine, breaks the integrity of the safety protocol, so FSoE must be accessed through a separate buffer.

Basic interface properties​

The basic FSoE (slave.fsoe) exposes the following read-only properties:

CategoryPropertyTypeRead/writeDescription
Connectionconnection_idintread-onlyConnection ID actually used by the most recent init_connection (when 0 is passed, the underlying library allocates one and writes it back)
Connectionis_connectedboolread-onlyWhether a valid FSoE connection exists (equivalent to IsConnected / StatusValid in C# / C++ / Java); reading triggers a status refresh
Statusstateint (FSoEState value)read-onlyCurrent FSoE state
Capabilityis_capableboolread-onlyWhether the slave supports FSoE
Capabilityis_supportedOptional[bool]read-onlyMailbox capability: FSoE is carried over CoE, judged by the CoE bit (0x04) of SII mbx_proto. True / False are definite conclusions; a read failure returns None (unknown)
Connectionconnection_countintread-onlyNumber of FSoE connections on the master
Semantics of is_connected

is_connected is the Python counterpart of IsConnected (StatusValid) in C# / C++ / Java (Python provides a single name). Semantics = get_status() is not None: reading triggers a status refresh; False = no valid connection / read failed (the status cannot be trusted), True = this read is valid. For status details (state / failsafe / counters), read the dict returned by get_status().

Connection-level status query

Connection-level fields are not properties; read them from the dict returned by get_status(). Dict keys: state, last_error, error_count, frames_sent, frames_received, crc_errors, watchdog_errors, watchdog_expired, in_failsafe, toggle_bit, initialized (note: the FSoEConnectionStatus data class below names the same field is_initialized; the dict key is initialized). The watchdog and last error also have dedicated check_watchdog() / get_last_error() methods.

Basic interface (slave.fsoe)​

Accessed through slave.fsoe.​

Connection management​

slave = master[1]
fsoe = slave.fsoe

# initialize the FSoE connection
fsoe.init_connection(
connection_id=0,
safety_address=0x0100,
watchdog_time_ms=100,
safe_input_size=2,
safe_output_size=1
)

# get the connection status
status = fsoe.get_status()
if status:
print(f"FSoE 状态: {status['state']}") # FSoE state: {status['state']}
print(f"失效安全: {status['in_failsafe']}") # Failsafe: {status['in_failsafe']}

# request a state transition
fsoe.request_state(FSoEState.DATA) # DATA state

# reset the connection
fsoe.reset()

# close the connection
fsoe.close_connection()

Safety data read and write​

# write the safety outputs
fsoe.write_safe_output(bytes([0x01]))

# read the safety inputs
data = fsoe.read_safe_input()
if data:
print(f"安全输入: {data.hex()}") # Safety input: {data.hex()}

Parameter download​

# download the safety parameters, return the SRA CRC
sra_crc = fsoe.download_parameters(param_data)
if sra_crc is not None:
print(f"SRA CRC: 0x{sra_crc:08X}")

# set the failsafe output
fsoe.set_failsafe_output(bytes([0x00]))

Watchdog and errors​

# check the watchdog state (True = healthy)
if not fsoe.check_watchdog():
print("FSoE 看门狗超时!") # FSoE watchdog timeout!

# get the last error code
error = fsoe.get_last_error()
if error != FSoEError.NONE:
desc = FSoEHelper.get_error_description(FSoEError(error))
print(f"FSoE 错误: {desc}") # FSoE error: {desc}

# clear the error
fsoe.clear_error()

State control​

request_state()​

def request_state(self, target_state: int) -> bool

Requests an FSoE state transition. The validity of the transition is verified automatically.

Parameters:

  • target_state (int) — target state (FSoEState enum value)

Returns:

  • bool — True on success

reset()​

def reset(self) -> bool

Resets the FSoE connection to the initial state and restarts the state machine.

close_connection()​

def close_connection(self) -> bool

Closes the FSoE connection and releases resources.

clear_error()​

def clear_error(self) -> None

Clears the FSoE error. After clearing, a connection can be re-established.

Parameters and configuration​

download_parameters()​

def download_parameters(self, param_data: bytes) -> Optional[int]

Downloads the safety parameters.

note

Callable only in the Parameter state. The parameter contents are generated by the safety configuration tool.

Parameters:

  • param_data (bytes) — parameter data

Returns:

  • int | None — SRA CRC check value on success, None on failure

set_failsafe_output()​

def set_failsafe_output(self, data: bytes) -> bool

Presets the output value used in failsafe. When FSoE enters the Failsafe state, the slave switches to this value automatically.

Example:

# all outputs off in failsafe
fsoe.set_failsafe_output(bytes([0x00]))

# use a ctypes structure
safe_out = SafeDriveOutput()
safe_out.safety_control_word = 0x0001 # request STO (Safe Torque Off)
fsoe.set_failsafe_output(bytes(safe_out))

SafetyManager (multi-slave coordinator)​

SafetyManager manages FSoE connections across multiple slaves, providing one-step binding and bulk operations.

from darra_ethercat import SafetyManager
mgr = SafetyManager(...) # create the multi-slave safety connection coordinator

bind_safe_io()​

def bind_safe_io(self, slave_index, safe_input_offset, safe_input_size,
safe_output_offset, safe_output_size,
safety_address=0, watchdog_ms=100) -> bool

Binds safety IO in one step. The connection initialization is performed automatically; the state machine (Session → Connection → Parameter → Data) is then advanced automatically by the protocol engine on each cycle.

connection_id value

bind_safe_io registers the connection with connection_id = slave_index + 1 (bind_mdp_safe_input / bind_mdp_safe_output use module_number + 1, and bind_mdp_drive_axis uses axis_index + 1). Subsequent read_input_frame / write_output_frame calls must pass the same connection_id. When an explicit ID is needed, use bind_safe_input / bind_safe_output.

bind_mdp_safe_input() / bind_mdp_safe_output()​

def bind_mdp_safe_input(self, slave_index, safety_address, input_size,
module_number=0, watchdog_ms=100) -> bool
def bind_mdp_safe_output(self, slave_index, safety_address, output_size,
module_number=0, watchdog_ms=100) -> bool

Binds safety inputs/outputs for MDP modules.

bind_mdp_drive_axis()​

def bind_mdp_drive_axis(self, slave_index, axis_index,
safety_address=0, watchdog_ms=100) -> bool

Binds the safety axis connection of an MDP servo drive.

Bulk operations​

# check whether all connections are in the DATA state
if mgr.all_in_data_state():
print("所有安全连接正常") # All safety connections are OK

# check whether any connection entered failsafe (tri-state return)
failsafe = mgr.any_in_failsafe()
if failsafe is None:
print("有连接状态读失败, 按未知处理") # Failed to read some connection states; treated as unknown
elif failsafe:
print("有连接进入失效安全!") # A connection has entered failsafe!

# all connections enter failsafe
mgr.enter_all_failsafe()

# reset all connections
mgr.reset_all()

# close all connections
mgr.close_all()

# get the status summary
print(mgr.get_status_summary())

# connection count
print(f"连接数: {mgr.connection_count}") # Connection count: {mgr.connection_count}

Find a connection​

# find by safety address
mdp = mgr.find_by_address(0x0100)

# find by connection ID
mdp = mgr.find_by_connection_id(1)

Safety frame read and write​

# write safety output data (connection_id is the ID used at bind time; with bind_safe_io it is slave_index + 1)
mgr.write_output_frame(slave_index=1, connection_id=2, frame_data=bytes([0x01]))

# read safety input data
data = mgr.read_input_frame(slave_index=1, connection_id=2)

DataExchange callback​

Slave-level safety data exchange callback, registered on a SafeMdp instance (in the SafetyManager case, obtain the corresponding instance with mgr.get_mdp(slave_index, connection_id)). The callback parameter is a FSoEDataExchangeEvent snapshot.

Related structures:

from typing import Callable
from darra_ethercat.slave.fsoe import FSoEDataExchangeEvent

FSoEDataExchangeCallback = Callable[[FSoEDataExchangeEvent], None]

FSoEDataExchangeCallback is the type of the cb passed to add_data_exchanged_callback(cb) / remove_data_exchanged_callback(cb): it receives one FSoEDataExchangeEvent and returns nothing. It fires once per PDO cycle processing, and every trigger creates a new event object; safe_inputs / safe_outputs are independent bytes copies of that moment in the cycle — holding the object after the callback returns does not change it with later cycles; to keep it across cycles, copy it yourself first.

Example:

def on_safe_exchange(ev):
print(f"状态={ev.current_state}, 输入={ev.safe_inputs.hex()}, 周期={ev.cycle_count}") # state={ev.current_state}, inputs={ev.safe_inputs.hex()}, cycle={ev.cycle_count}

mdp.add_data_exchanged_callback(on_safe_exchange)
mdp.remove_data_exchanged_callback(on_safe_exchange)

The callback is fired by FSoE cycle processing after the safety inputs are refreshed and before the safety outputs are committed.

Callback constraints
  • An empty bytes for safe_inputs means no safety input was read in this cycle (the read failed, or the connection has no inputs); it does not mean "all input bytes are 0". When the connection status cannot be read (get_status() returns None), no callback fires in that cycle.
  • safe_outputs is the last snapshot written by this SDK (there is no output read-back entry point); it is not the actual slave output.
  • Passing None neither registers nor raises; registering the same callable twice keeps only one copy.
  • Unregistering must pass the same object that was registered; when using a lambda, assign it to a variable first, then register and unregister with that variable.
  • Exceptions thrown inside a callback are caught and ignored by the SDK; they do not affect the remaining callbacks or the PDO cycle.

Timing:

PDO cycle callback
+-- FSoE pre-processing
| +-- for each FSoE slave:
| +-- refresh the safety input buffer <- inputs refreshed
| +-- check state changes and error events
| +-- DataExchange callback <- read/write safety data here
+-- on_pdo_cycle callback <- regular PDO read/write (master level)
+-- FSoE post-processing
+-- commit the safety output buffer <- outputs committed automatically
PDO cycle timing

After binding, safety data can be read and written on the PDO cycle path (automatic safety data exchange on every cycle is not standard):

  1. Cycle start — refresh the safety input buffers of all FSoE slaves, check state changes and fire events
  2. DataExchange callback — slave-level callback; read the inputs (already the latest data) and modify the outputs
  3. PDO callback — master-level callback (regular PDO read/write)
  4. Cycle end — commit the safety output buffers of all FSoE slaves

MDP connections — addressed by connection_id​

SafeMdp manages multiple FSoE connections on one slave and does not return separate connection objects: every connection-level operation passes connection_id as the first argument to the SafeMdp method.

# SafeMdp: the first parameter of every method is connection_id
mdp.request_state(connection_id=1, target_state=FSoEState.DATA) # request a state transition
mdp.reset(connection_id=1) # reset the connection
mdp.clear_error(connection_id=1) # clear the error
mdp.close_connection(connection_id=1) # close the connection
mdp.download_parameters(connection_id=1, param_data=...) # download the safety parameters
mdp.set_failsafe_output(connection_id=1, data=...) # set the failsafe output
mdp.write_safe_output(connection_id=1, data=...) # write the safety outputs
data = mdp.read_safe_input(connection_id=1) # read the safety inputs
state = mdp.get_state(connection_id=1) # read the connection state (FSoEState value)

Connection-level status / errors / watchdog are read from the dict returned by mdp.get_status(connection_id).

FSoEConnectionMode​

class FSoEConnectionMode(IntEnum):
SINGLE = 0 # single-connection mode - all modules share one FSoE connection and safety address
MULTIPLE = 1 # multi-connection mode - each module has its own FSoE connection and safety address
Selection guide
  • Single connection (bind_safe_io) — simple devices, single-axis drives
  • Multiple connections (bind_mdp_safe_input / bind_mdp_safe_output / bind_mdp_drive_axis) — when modules need independent monitoring/recovery (for example, a multi-axis drive with an independent safety connection per axis)

MDP multi-connection mode (SafeMdp)​

SafeMdp manages multiple independent FSoE connections on a single slave; it applies to MDP-capable slaves such as safety I/O modules.

from darra_ethercat import SafeMdp

mdp = SafeMdp(...) # create the MDP multi-connection manager for slave 1

Connection detection and management​

# detect available connections
conn_count = mdp.detect_connections()
print(f"支持 {conn_count} 个 FSoE 连接") # Supports {conn_count} FSoE connections

# get the device safety address
addr = mdp.get_device_address()
print(f"设备安全地址: 0x{addr:04X}") # Device safety address: 0x{addr:04X}

# get the slave connection count
total = mdp.get_slave_connection_count()

Connection initialization​

# initialize the connection (supports MDP extension parameters)
# with connection_id=0 the underlying library allocates one automatically; query the actual ID back with mdp.actual_connection_id(0)
mdp.init_connection(
connection_id=1,
safety_address=0x0100,
watchdog_time_ms=100,
safe_input_size=2,
safe_output_size=1,
pdo_input_offset=0, # PDO input offset
pdo_output_offset=0, # PDO output offset
module_number=0, # MDP module number
module_profile=0, # MDP module profile
axis_number=0, # drive axis number
connection_type=0 # connection type
)

# independent operations per connection
mdp.write_safe_output(connection_id=1, data=bytes([0x01]))
data = mdp.read_safe_input(connection_id=1)
mdp.request_state(connection_id=1, target_state=FSoEState.DATA)
mdp.close_connection(connection_id=1)

Connection status​

# dict form (keys: state / last_error / error_count / frames_sent / frames_received /
# crc_errors / watchdog_errors / watchdog_expired / in_failsafe / toggle_bit / initialized)
st = mdp.get_status(connection_id=1)

# typed form: returns FSoEConnectionStatus (same name and fields as C#),
# the dict's initialized key maps to its is_initialized field
st2 = mdp.get_status_typed(connection_id=1)
if st2 is not None:
print(f"状态: {st2.state.name}, 已初始化: {st2.is_initialized}") # state: {st2.state.name}, initialized: {st2.is_initialized}

get_status_typed() has the same semantics as get_status() (each call really reads the connection state once): returns None = no valid connection / read failed (the status cannot be trusted); returns FSoEConnectionStatus = this read is valid. The typed form corresponds one-to-one with the FSoEConnectionStatus fields.

Module diagnostics​

Module communication parameter / diagnostics reads (the connection_id parameter corresponds to the MDP module number, starting from 0):

# read the module communication parameters
comm_param = mdp.get_module_comm_param(connection_id=0)

# read the module diagnostics
diag = mdp.get_module_diagnosis(connection_id=0)
if diag:
state, diagnosis = diag
print(f"连接状态: {state}, 诊断码: 0x{diagnosis:04X}") # Connection state: {state}, diagnostic code: 0x{diagnosis:04X}

Safety data read and write​

read_safe_input() / write_safe_output() read and write the raw byte buffer. The user parses or assembles the bytes according to the safety PDO layout provided by the device vendor; common approaches include:

  • int.from_bytes() / to_bytes() for scalar fields
  • struct.pack / struct.unpack for multi-field records
  • fixed-width structures for a typed layout

Example:

data = fsoe.read_safe_input()
if data:
input_bits = data[0]
ch0_safe = bool(input_bits & 0x01)

fsoe.write_safe_output(bytes([0x01])) # channel 0 output

Enums and data classes​

FSoEState​

class FSoEState(IntEnum):
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

The same value set exists under the same name in darra_ethercat.FsoEState; the state returned by get_status() uses the latter type.

FSoEError​

class FSoEError(IntEnum):
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 connections reached
INVALID_STATE_TRANSITION = 0x0102 # invalid state transition
Underlying enum with the same values

darra_ethercat.FsoEError (the type of last_error in get_status()) has the same values as this enum, but three members are named WRONG_CONN_ID / CRC / INVALID_STATE for 0x0003 / 0x0004 / 0x0102. FSoEHelper.get_error_description() uses the FSoEError from this section.

FSoEFailsafeReason​

class FSoEFailsafeReason(IntEnum):
WATCHDOG_TIMEOUT = 0 # watchdog timeout
CRC_ERROR = 1 # CRC check 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 exchange

SafeModuleProfile​

class SafeModuleProfile(IntEnum):
DIGITAL_INPUT = 190 # digital input module
DIGITAL_IN_OUT = 195 # digital input/output module
DIGITAL_OUTPUT = 290 # digital output module
DRIVE_CONNECTION = 790 # servo drive connection
MASTER = 6900 # master module

FSoEConnectionConfig​

@dataclass
class FSoEConnectionConfig:
connection_id: int = 0 # connection ID
safety_address: int = 0 # safety address
watchdog_time_ms: int = 100 # watchdog timeout (ms)
safe_input_size: int = 0 # safety input size (bytes)
safe_output_size: int = 0 # safety output size (bytes)
pdo_input_offset: int = 0 # PDO input offset
pdo_output_offset: int = 0 # PDO output offset

FSoEConnectionStatus​

@dataclass
class FSoEConnectionStatus:
state: FSoEState = FSoEState.RESET # current state
last_error: FSoEError = FSoEError.NONE # last error
error_count: int = 0 # error count
frames_sent: int = 0 # frames sent
frames_received: int = 0 # frames received
crc_errors: int = 0 # CRC errors
watchdog_errors: int = 0 # watchdog errors
watchdog_expired: bool = False # whether the watchdog expired
in_failsafe: bool = False # whether in failsafe
toggle_bit: int = 0 # current toggle bit value
is_initialized: bool = False # whether initialized

SafeMdp.get_status_typed(connection_id) returns this type (None = no valid connection / read failed); state / last_error take the FSoEState / FSoEError enums, the rest are raw int / bool values.

Event arguments​

@dataclass
class FSoEStateChangedEventArgs:
slave_index: int # slave index
connection_index: int # connection index
old_state: FSoEState # state before the change
new_state: FSoEState # state after the change

@dataclass
class FSoEErrorEventArgs:
slave_index: int # slave index
connection_index: int # connection index
error: FSoEError # error code
current_state: FSoEState # current state
@property
def description(self) -> str # error description text

@dataclass
class FSoEDataExchangeEvent:
slave_index: int # slave index
current_state: FSoEState # current FSoE state for this cycle
safe_inputs: bytes # safety input snapshot for this cycle (copy)
safe_outputs: bytes # safety output snapshot for this cycle (copy)
in_failsafe: bool # whether in failsafe mode
cycle_count: int # cumulative PDO cycle count
timestamp: Optional[datetime] # event trigger timestamp (UTC)

Slave events​

Slave-level FSoE events are registered through slave.events:

The FSoE safety data updated event does not exist in the Python SDK

Older documentation listed the add_fsoe_safe_data_updated() subscription entry and the FSoEDataUpdatedEventArgs argument type; the current Python SDK does not have these two members, so such a subscription cannot compile. Use add_fsoe_data_exchange() for safety data exchange.

The FSoE failsafe event argument does not exist in the Python SDK

The FSoEFailsafeEventArgs argument class has been removed (same family-wide ruling as C# / C++). The callback of add_fsoe_failsafe_triggered takes no arguments (no reason / no entering_failsafe); for the trigger reason use the query interfaces (last_error from get_status() / get_last_error()), and for the per-cycle failsafe state use FSoEDataExchangeEvent.in_failsafe.

slave = master[1]

# FSoE state change
slave.events.add_fsoe_state_changed(lambda old, new:
print(f"FSoE 状态: {old} -> {new}")) # FSoE state: {old} -> {new}

# FSoE error
slave.events.add_fsoe_error(lambda code:
print(f"FSoE 错误: 0x{code:04X}")) # FSoE error: 0x{code:04X}

# FSoE enters failsafe (the callback takes no arguments and carries no reason)
slave.events.add_fsoe_failsafe_triggered(lambda:
print("进入失效安全模式!")) # Entering failsafe mode!

# FSoE data exchange
slave.events.add_fsoe_data_exchange(lambda inp, out:
print(f"输入: {inp.hex()}, 输出: {out.hex()}")) # Inputs: {inp.hex()}, outputs: {out.hex()}

Unregistering: each add_fsoe_* has a matching remove_fsoe_state_changed / remove_fsoe_error / remove_fsoe_failsafe_triggered / remove_fsoe_data_exchange; slave.events.clear_all() clears everything in one call (including the FSoE subscription table). The 4 slave.events.add_fsoe_* entries above are currently not wired (registering them does not fire, pending); for cyclic safety data use SafeMdp.add_data_exchanged_callback(cb) / remove_data_exchanged_callback(cb) (see "DataExchange callback" above).

Utility classes​

FSoEHelper​

from darra_ethercat.slave.fsoe import FSoEHelper

# check whether a state transition is legal
valid = FSoEHelper.is_valid_state_transition(FSoEState.RESET, FSoEState.SESSION)

# get the error description
desc = FSoEHelper.get_error_description(FSoEError.WATCHDOG)

# parse the command byte (Command is the full-byte value from Table 5)
cmd = FSoEHelper.get_command_type(0x36) # FSoECommand.PROCESS_DATA

Deprecated FSoEHelper methods​

The following 4 static methods exist only to keep the calling form of older code compiling; do not use them in new code. In ETG.5100 V1.2.0 the Command is a whole-byte value defined by Table 5 (0x36 / 0x2A / 0x4E / 0x64 / 0x52 / 0x08); there is no toggle bit, Master Reset bit or Slave Reset bit field, so the old bit-assembly model does not hold at all.

FSoEHelper.build_command()​

from darra_ethercat.slave.fsoe import FSoEHelper

def build_command(cmd_type: FSoECommand, toggle_bit: bool,
master_reset: bool = False, slave_reset: bool = False) -> int

Deprecated: the Command has no toggle bit, master reset bit or slave reset bit to assemble, so the method performs no assembly and returns the low 8 bits of cmd_type as an integer; the last three parameters are ignored and kept only for signature compatibility.

Parameters:

  • cmd_type (FSoECommand) — command type; its whole-byte value is used
  • toggle_bit (bool) — deprecated parameter; the value is ignored
  • master_reset (bool) — deprecated parameter; the value is ignored, defaults to False
  • slave_reset (bool) — deprecated parameter; the value is ignored, defaults to False

Returns:

  • int — the whole-byte value of cmd_type

Replacement:

from darra_ethercat.slave.fsoe import FSoECommand

command = FSoECommand.PROCESS_DATA.value # 0x36

FSoEHelper.get_toggle_bit()​

from darra_ethercat.slave.fsoe import FSoEHelper

def get_toggle_bit(command: int) -> bool

Deprecated: the Command byte in ETG.5100 V1.2.0 has no toggle bit position, so the old 0x80 bit model does not hold; sequence dependency is carried by the 16-bit Sequence Number. The method ignores its argument and always returns False — that False does not mean "the toggle bit of this frame is 0", only that the information does not exist.

Parameters:

  • command (int) — command byte; the value is ignored

Returns:

  • bool — always False, kept only for signature compatibility

Replacement:

# No need to extract the toggle bit; frame loss / duplication is decided by the protocol engine's 16-bit Sequence Number

FSoEHelper.is_master_reset_request()​

from darra_ethercat.slave.fsoe import FSoEHelper

def is_master_reset_request(command: int) -> bool

Deprecated: the Command byte in ETG.5100 V1.2.0 has no Master Reset modifier bit, so the old 0x40 bit model does not hold. The method is still callable, but its meaning has narrowed to "whether the whole byte is the Reset command": it compares the low 8 bits against FSoECommand.RESET (0x2A) as a whole and returns True only when the command equals Reset; it no longer recognizes any "master reset bit".

Parameters:

  • command (int) — command byte

Returns:

  • bool — True when the whole byte equals the Reset command, otherwise False

Replacement:

from darra_ethercat.slave.fsoe import FSoECommand

if (command & 0xFF) == FSoECommand.RESET:
...

FSoEHelper.is_slave_reset_request()​

from darra_ethercat.slave.fsoe import FSoEHelper

def is_slave_reset_request(command: int) -> bool

Deprecated: the Command byte in ETG.5100 V1.2.0 has no Slave Reset modifier bit, so the old 0x20 bit model does not hold. The behaviour matches is_master_reset_request() — it returns True only when the whole byte equals the Reset command, and no longer distinguishes master reset from slave reset.

Parameters:

  • command (int) — command byte

Returns:

  • bool — True when the whole byte equals the Reset command, otherwise False

Replacement:

from darra_ethercat.slave.fsoe import FSoECommand

if (command & 0xFF) == FSoECommand.RESET:
...

CRC checking​

from darra_ethercat import fsoe_crc16, fsoe_crc16_fast

data = bytes([0x01, 0x02, 0x03])
crc = fsoe_crc16(data) # standard calculation
crc_fast = fsoe_crc16_fast(data) # compatibility alias, same result as fsoe_crc16

evaluate_fsoe_capability()​

from darra_ethercat.slave.fsoe import evaluate_fsoe_capability

def evaluate_fsoe_capability(dll, master_index: int, slave_index: int, *,
esi_path: Optional[str] = None,
allow_probe: bool = True
) -> Tuple[FSoECapabilityStatus, str]

Module-level capability entry point. slave.fsoe.is_supported is its three-state projection (True = support proven, None = unproven; it never produces False); call this function directly when you need the five-state conclusion that separates "the ESI does not declare it" from "the capability is not proven".

Decision chain (strongest to weakest):

  1. The ESI declares the FSoE safety marker → ESI_DECLARED; no SDO is sent
  2. The ESI reads successfully but does not declare it → ESI_UNDECLARED; no SDO is sent
  3. The ESI gives no verdict (not loaded / unreadable) and allow_probe=True → one short-budget probe: first confirm the CoE mailbox capability, then ask the device for its FSoE capability; a positive answer → PROBE_CONFIRMED, otherwise → UNPROVEN
  4. Probing is not allowed and there is no ESI verdict → UNPROVEN

Conclusions are cached per device identity (vendor:product:revision); UNPROVEN is only a short-term negative cache — at most one probe retry per 5 seconds for the same device identity, never an unconditional bus probe. allow_probe=False does not start the cooldown; the first probe is made immediately once probing is allowed later. When the device identity cannot be read (all 0s), no conclusion is cached.

Neither conclusion means "not supported"

ESI_UNDECLARED only means "the ESI does not declare the FSoE marker", and UNPROVEN only means "the capability is not proven"; neither means "the device does not support FSoE". This decision chain never produces a "confirmed unsupported" conclusion — do not treat it as unsupported in logs or on screen either.

Parameters:

  • dll — SDK runtime instance
  • master_index (int) — master index
  • slave_index (int) — slave index
  • esi_path (Optional[str]) — ESI file path (keyword only); the default None looks the device up in the loaded ESI registry by device identity
  • allow_probe (bool) — whether one short-budget probe is allowed when there is no ESI verdict (keyword only), defaults to True

Returns:

  • FSoECapabilityStatus — five-state verdict
  • str — human-readable basis for the verdict (for logs / diagnostics display)

Related structures:

class FSoECapabilityStatus(IntEnum):
NOT_EVALUATED = 0 # Not evaluated yet
ESI_DECLARED = 1 # the ESI explicitly declares FSoE (no SDO is sent)
PROBE_CONFIRMED = 2 # no ESI criterion, but a short-budget probe got a positive reply (support confirmed)
ESI_UNDECLARED = 3 # the ESI was really read and carries no FSoE flag (!= not supported)
UNPROVEN = 4 # capability not proven (!= not supported)

Example:

from darra_ethercat.slave.fsoe import FSoECapabilityStatus, evaluate_fsoe_capability

# dll is the SDK runtime instance
status, evidence = evaluate_fsoe_capability(dll, 0, 1)

if status in (FSoECapabilityStatus.ESI_DECLARED,
FSoECapabilityStatus.PROBE_CONFIRMED):
print(f"FSoE 已证实支持: {evidence}") # FSoE support confirmed: {evidence}
else:
print(f"未声明 / 未证实(都不是不支持): {evidence}") # Not declared / not confirmed (neither means unsupported): {evidence}

# Provide the ESI file explicitly and turn off bus probing: use the ESI criterion only
status, evidence = evaluate_fsoe_capability(dll, 0, 1, esi_path="device.xml",
allow_probe=False)

determine_failsafe_reason()​

from darra_ethercat.slave.fsoe import determine_failsafe_reason

def determine_failsafe_reason(last_error) -> FSoEFailsafeReason

Module-level pure function that infers the failsafe trigger reason from an FSoE error code. The mapping table is the same one used by the other language SDKs; this function only forwards and does not define its own attribution.

Mapping:

  • WATCHDOG → WATCHDOG_TIMEOUT
  • CRC_ERROR → CRC_ERROR
  • WRONG_COMMAND / UNKNOWN_COMMAND / WRONG_DATA / FAILSAFE_DATA → SLAVE_REQUEST
  • WRONG_CONNECTION_ID / WRONG_ADDRESS / COMM_PARAM / COMM_PARAM_LENGTH → COMMUNICATION_ERROR
  • APP_PARAM / APP_PARAM_LENGTH → APPLICATION_REQUEST
  • Any other error code / an argument that cannot be converted to FSoEError → COMMUNICATION_ERROR (the default tier of the mapping table)

Parameters:

  • last_error — FSoEError or an error code integer; an argument that cannot be converted to an integer is handled as a communication error

Returns:

  • FSoEFailsafeReason — the inferred reason; the function does not raise

Example:

from darra_ethercat import FSoEError
from darra_ethercat.slave.fsoe import determine_failsafe_reason

reason = determine_failsafe_reason(FSoEError.WATCHDOG) # WATCHDOG_TIMEOUT

# You can also pass the last_error from get_status() directly
status = fsoe.get_status()
if status:
reason = determine_failsafe_reason(status["last_error"])

is_connection_id_available()​

from darra_ethercat.slave.fsoe import is_connection_id_available

def is_connection_id_available(conn_id: int) -> bool

Module-level function that checks whether the specified ConnectionID is available (not occupied by another active FSoE connection).

The canonical name is validate_conn_id (this function is an alias for it; both share the same implementation):

from darra_ethercat.slave.fsoe import validate_conn_id

Parameters:

  • conn_id (int) — connection ID to check, valid range [1, 65535] (0 is reserved)

Returns:

  • bool — True if available; False if occupied / invalid / the runtime does not provide that query
ETG.5120 §5.2.3

ConnectionID = 0 is a reserved value (not assignable); the valid range is [1, 65535]. Every FSoE connection in the same slave network must use a unique ConnID; a duplicate causes WRONG_CONNECTION_ID (FSoEError 0x0003).

Example — occupancy check before initialization:

from darra_ethercat.slave.fsoe import is_connection_id_available
from darra_ethercat import SafetyManager

conn_id = 0x1234
if not is_connection_id_available(conn_id):
print(f"ConnID 0x{conn_id:04X} 不可用(已占用或非法),请选择其他 ID") # ConnID 0x{conn_id:04X} is unavailable (already in use or invalid); choose another ID
else:
mgr = SafetyManager(...) # create the multi-slave safety connection coordinator
# binding entry points with an explicit connection_id
mgr.bind_safe_input(slave_index=1, connection_id=conn_id,
safety_address=0x0100, input_size=2, watchdog_ms=100)
mgr.bind_safe_output(slave_index=1, connection_id=conn_id,
safety_address=0x0100, output_size=1, watchdog_ms=100)

Example — dynamically allocate an available ID:

def allocate_conn_id(start: int = 1) -> int:
"""从 start 开始扫描首个可用 ConnID""" # Scan for the first available ConnID starting from start
for cid in range(start, 0x10000):
if is_connection_id_available(cid):
return cid
raise RuntimeError("无可用 FSoE ConnectionID") # No FSoE ConnectionID available

my_id = allocate_conn_id(0x1000)

Complete examples​

Single-connection safety IO​

from darra_ethercat import EtherCATMaster, EcState
from darra_ethercat.slave.fsoe import FSoEState

with EtherCATMaster() as master:
master.set_eni("config.deni")
master.build()
master.set_state(EcState.OP)

slave = master[1]
fsoe = slave.fsoe

if fsoe.is_capable:
# initialize the connection
fsoe.init_connection(
connection_id=0,
safety_address=0x0100,
watchdog_time_ms=100,
safe_input_size=2,
safe_output_size=1
)

# set the failsafe output
fsoe.set_failsafe_output(bytes([0x00]))

# request the data exchange state
fsoe.request_state(FSoEState.DATA)

# register events
slave.events.add_fsoe_error(lambda code:
print(f"FSoE 错误: 0x{code:04X}")) # FSoE error: 0x{code:04X}

# read/write safety data in the PDO callback
def on_pdo(mi):
data = fsoe.read_safe_input()
if data:
ch0 = (data[0] & 0x01) != 0
fsoe.write_safe_output(bytes([0x01 if ch0 else 0x00]))

master.on_pdo_cycle(on_pdo)

import time
time.sleep(10)
fsoe.close_connection()

SafetyManager one-step binding​

from darra_ethercat import EtherCATMaster, EcState, SafetyManager

master = EtherCATMaster()
master.set_eni("config.deni")
master.build()
master.set_state(EcState.OP)

mgr = SafetyManager(...) # create the multi-slave safety connection coordinator

# one-step binding (the protocol engine advances the state machine automatically Session→Connection→Parameter→Data)
mgr.bind_safe_io(
slave_index=1,
safe_input_offset=0, safe_input_size=2,
safe_output_offset=0, safe_output_size=1,
safety_address=0x0100, watchdog_ms=100
)

# MDP servo drive safety axis binding
mgr.bind_mdp_drive_axis(slave_index=2, axis_index=0,
safety_address=0x0200, watchdog_ms=100)

# check the status of all connections
print(mgr.get_status_summary())
if mgr.all_in_data_state():
print("所有安全连接已进入数据交换状态") # All safety connections have entered data exchange

# PDO callback (bind_safe_io uses connection_id = slave_index + 1 = 2)
def on_pdo(mi):
data = mgr.read_input_frame(1, 2)
if data:
mgr.write_output_frame(1, 2, bytes([0x01]))

master.on_pdo_cycle(on_pdo)

import time
time.sleep(30)
mgr.close_all()
master.close()

Safety drive (with typed read/write)​

import ctypes
from darra_ethercat import EtherCATMaster, EcState, SafetyManager

class SafeDriveInput(ctypes.Structure):
_pack_ = 1
_fields_ = [
("safety_status_word", ctypes.c_uint16),
("safe_actual_position", ctypes.c_int32),
("safe_actual_velocity", ctypes.c_int32),
]

class SafeDriveOutput(ctypes.Structure):
_pack_ = 1
_fields_ = [
("safety_control_word", ctypes.c_uint16),
]

master = EtherCATMaster()
master.set_eni("config.deni")
master.build()
master.set_state(EcState.OP)

mgr = SafetyManager(...) # create the multi-slave safety connection coordinator

# bind the safety drive in one step (10-byte input + 2-byte output)
mgr.bind_safe_io(
slave_index=1,
safe_input_offset=0,
safe_input_size=ctypes.sizeof(SafeDriveInput), # 10
safe_output_offset=0,
safe_output_size=ctypes.sizeof(SafeDriveOutput), # 2
safety_address=0x0100,
watchdog_ms=100
)

# safety drive control in the PDO callback (bind_safe_io uses connection_id = slave_index + 1 = 2)
def on_pdo(mi):
data = mgr.read_input_frame(1, 2)
if data and len(data) >= ctypes.sizeof(SafeDriveInput):
drive_in = SafeDriveInput.from_buffer_copy(data)

drive_out = SafeDriveOutput()
if drive_in.safety_status_word & 0x0100: # Bit8: safety fault
drive_out.safety_control_word = 0x0080 # acknowledge the fault
print(f"安全故障: 位置={drive_in.safe_actual_position}") # Safety fault: position={drive_in.safe_actual_position}
else:
drive_out.safety_control_word = 0x0000 # clear STO

mgr.write_output_frame(1, 2, bytes(drive_out))

# failsafe event
slave = master[1]
slave.events.add_fsoe_failsafe_triggered(lambda:
print("驱动器安全停止!")) # Drive safe stop!

master.on_pdo_cycle(on_pdo)

import time
time.sleep(30)
mgr.close_all()
master.close()

MDP multiple connections​

from darra_ethercat import SafeMdp

mdp = SafeMdp(...) # create the MDP multi-connection manager for slave 1

# detect and initialize all connections
conn_count = mdp.detect_connections()
print(f"支持 {conn_count} 个 FSoE 连接") # Supports {conn_count} FSoE connections

# get the device safety address
addr = mdp.get_device_address()
print(f"设备安全地址: 0x{addr:04X}") # Device safety address: 0x{addr:04X}

for i in range(conn_count):
mdp.init_connection(
connection_id=i + 1,
safety_address=0x0100 + i,
watchdog_time_ms=100,
safe_input_size=2,
safe_output_size=1
)

# query the status of each connection
for i in range(conn_count):
status = mdp.get_status(i + 1)
if status:
print(f"连接 {i + 1}: 状态={status['state']}, 失效安全={status['in_failsafe']}") # Connection {i + 1}: state={status['state']}, failsafe={status['in_failsafe']}

# module diagnostics (the parameter is the module number)
for i in range(conn_count):
diag = mdp.get_module_diagnosis(i)
if diag:
state, diagnosis = diag
print(f"模块 {i}: 诊断码=0x{diagnosis:04X}") # Module {i}: diagnostic code=0x{diagnosis:04X}

# close
for i in range(conn_count):
mdp.close_connection(i + 1)

MDP multi-axis safety drive​

from darra_ethercat import EtherCATMaster, EcState, SafetyManager

master = EtherCATMaster()
master.set_eni("config.deni")
master.build()
master.set_state(EcState.OP)

mgr = SafetyManager(...) # create the multi-slave safety connection coordinator

# bind 2 axes (each axis has an independent FSoE connection)
mgr.bind_mdp_drive_axis(slave_index=1, axis_index=0,
safety_address=0x0100, watchdog_ms=100)
mgr.bind_mdp_drive_axis(slave_index=1, axis_index=1,
safety_address=0x0200, watchdog_ms=100)

# check the status of all connections
print(mgr.get_status_summary())
if mgr.all_in_data_state():
print("所有安全连接已进入数据交换状态") # All safety connections have entered data exchange

# PDO callback (bind_mdp_drive_axis uses connection_id = axis_index + 1)
def on_pdo(mi):
# independent safety data read/write per axis
for axis in range(2):
data = mgr.read_input_frame(1, axis + 1)
if data:
# process the safety data...
pass

master.on_pdo_cycle(on_pdo)

# event monitoring: independent per axis
slave = master[1]
slave.events.add_fsoe_failsafe_triggered(lambda:
print("轴失效安全!")) # Axis in failsafe!

import time
time.sleep(30)
mgr.close_all()
master.close()