FSoE functional safety
FSoE (Functional Safety over EtherCAT) is the FSoE state machine and protocol interface inside the ETH master; it layers a safety protocol on top of the standard PDO channel. The cyclic path is fail-closed. This is not a certified safety product, nor a PLC capability; the minimum cycle is 125 µs (flexible).
Connections are managed through SafetyManager (single/multi-connection management) and SafeMdp (MDP multi-module connections).
FSoE devices are detected automatically when the slave is initialized. The detection sequence:
- CoE prerequisite — the slave must support the CoE mailbox protocol
- 0xF980:01 check — attempt an SDO read of the device-level FSoE safety address; success confirms support
- 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 (such as ordinary servo drives) also support CoE. An FSoE device must implement the specific safety object indices to be recognized correctly.
The SDK provides FSoE support at three levels:
SafetyManager— multi-slave, multi-connection coordinator; provides one-step initialization throughbind_safe_ioSafeMdp— MDP multi-connection manager; supports multiple FSoE connections on a single slaveFsoeCrc16— CRC16 check utility
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
bind_safe_io initializes the connection and starts data exchange in one call; the SDK advances the intermediate states (Session -> Connection -> Parameter) automatically.
Minimal example (digital safety IO)
use darra_ethercat::{EtherCATMaster, EcState, SafetyManager, FsoeConfig};
// safety data structures
#[repr(C, packed)]
#[derive(Clone, Copy, Default)]
struct SafeDigitalInput {
input_bits: u8, // safety input status bits (one bit per channel)
diag_bits: u8, // input diagnostics status
}
#[repr(C, packed)]
#[derive(Clone, Copy, Default)]
struct SafeDigitalOutput {
output_bits: u8, // safety output control bits
}
// build() returns BuildResult (implements Deref only, no DerefMut);
// set_state needs &mut self, so take .master and bind it with let mut
let mut master = EtherCATMaster::builder()
.set_eni("config.deni")
.build()?
.master;
master.set_state(EcState::Operational)?;
// bind safety IO in one step
let mut fsoe_mgr = SafetyManager::new(master.index());
fsoe_mgr.bind_safe_io(
1, // slave_index
0, 2, // safe_input_offset, safe_input_size
0, 1, // safe_output_offset, safe_output_size
0x0100, // safety_address
100, // watchdog_ms
)?;
// handle it in the PDO cycle
let events = master.events();
events.on_pdo_cyclic_sync(move |_| {
fsoe_mgr.process_cycle();
// read the safety inputs
let inputs = fsoe_mgr.all_in_data();
if let Some(data) = inputs.get(&1) {
let safe_input = data[0];
let safe_output = if (safe_input & 0x01) != 0 { 0x01u8 } else { 0x00u8 };
let _ = fsoe_mgr.write_safe_output(1, &[safe_output]);
}
});
How FSoE differs from ordinary PDO
FSoE safety data cannot be mapped directly the way ordinary PDO data is. The reason lies in the protocol layer:
Ordinary PDO
The data in the IOmap is the user data; memory can be read and written directly.
FSoE PDO
The IOmap holds FSoE protocol frames; the user's safety data is wrapped inside the frame and has to be checked.
The SDK FSoE protocol engine is responsible for:
- CRC check — verifies input frame integrity and computes the output frame CRC
- State machine management — advances Session -> Connection -> Parameter -> Data automatically
- Watchdog — monitors communication timeouts and enters Failsafe on timeout
- Sequence number — detects lost and duplicate frames
Reading or writing the IOmap directly, bypassing the SDK, breaks safety protocol integrity, so FSoE must be accessed through a separate buffer.
Safety data structures
Safety data is a fixed-length payload that the application defines from the device manual, aligned byte for byte with the device layout using #[repr(C, packed)] (the structures below are defined by your own project, not exported by the SDK):
// EL19xx digital safety input (2 bytes of safety data)
#[repr(C, packed)]
#[derive(Clone, Copy, Default)]
pub struct SafeDigitalInput {
pub input_bits: u8, // safety input status bits (one bit per channel)
pub diag_bits: u8, // input diagnostics status
}
// EL29xx digital safety output (1 byte of safety data)
#[repr(C, packed)]
#[derive(Clone, Copy, Default)]
pub struct SafeDigitalOutput {
pub output_bits: u8, // safety output control bits
}
// ETG.6100 safety drive input (10 bytes of safety data)
#[repr(C, packed)]
#[derive(Clone, Copy, Default)]
pub struct SafeDriveInput {
pub safety_status_word: u16, // safety status word
pub safe_actual_position: i32, // safe actual position
pub safe_actual_velocity: i32, // safe actual velocity
}
// ETG.6100 safety drive output (2 bytes of safety data)
#[repr(C, packed)]
#[derive(Clone, Copy, Default)]
pub struct SafeDriveOutput {
pub safety_control_word: u16, // safety control word
}
// safety encoder input (6 bytes of safety data)
#[repr(C, packed)]
#[derive(Clone, Copy, Default)]
pub struct SafeEncoderInput {
pub safe_position: u32, // safe position value
pub status_word: u16, // status word
}
safe_input_size / safe_output_size must match std::mem::size_of::<T>() for the structure; otherwise reads and writes fail.
SafetyManager — multi-slave connection manager
Create the manager
pub fn new(master_index: u16) -> Self
Creates a new FSoE multi-connection manager that manages every FSoE connection on one master.
let mut fsoe_mgr = SafetyManager::new(master.index());
bind_safe_io()
pub fn bind_safe_io(&mut self, slave_index: u16,
safe_input_offset: u32, safe_input_size: u16,
safe_output_offset: u32, safe_output_size: u16,
safety_address: u16, watchdog_ms: u32) -> Result<()>
Binds safety IO in one step. It completes connection initialization and advances the state to DATA automatically.
Parameters:
slave_index— slave index (1-based)safe_input_offset— byte offset of the safety data in the input PDOsafe_input_size— safety input data size (bytes)safe_output_offset— byte offset of the safety data in the output PDOsafe_output_size— safety output data size (bytes)safety_address— safety address (hardware DIP switch)watchdog_ms— watchdog timeout (ms)
Example:
fsoe_mgr.bind_safe_io(
1, // slave_index
0, std::mem::size_of::<SafeDigitalInput>() as u16,
0, std::mem::size_of::<SafeDigitalOutput>() as u16,
0x0100, 100,
)?;
bind_safe_input() / bind_safe_output()
pub fn bind_safe_input(&mut self, slave_index: u16, safety_address: u16,
input_size: u16, watchdog_ms: u32) -> Result<()>
pub fn bind_safe_output(&mut self, slave_index: u16, safety_address: u16,
output_size: u16, watchdog_ms: u32) -> Result<()>
Binds safety inputs only / safety outputs only, for devices that have only safety inputs (such as the EL1904) or only safety outputs (such as the EL2904).
bind_mdp_drive_axis()
pub fn bind_mdp_drive_axis(&mut self, slave_index: u16, axis_index: u16,
safety_address: u16, watchdog_ms: u32) -> Result<()>
Binds the safety connection of an MDP drive axis. Each axis gets its own FSoE connection; the safety data size is discovered automatically from the MDP module information.
Parameters:
slave_index— slave index (1-based)axis_index— MDP axis/module indexsafety_address— safety addresswatchdog_ms— watchdog timeout (ms)
Example:
// dual-axis safety drive
fsoe_mgr.bind_mdp_drive_axis(1, 0, 0x0100, 100)?; // axis 0
fsoe_mgr.bind_mdp_drive_axis(1, 1, 0x0200, 100)?; // axis 1
On the Rust side, MDP module binding offers only the most complete form, bind_mdp_drive_axis: it goes through SafeMdp::init_connection with module_profile=790 FSoE Drive Connection.
If you need an input-only or output-only binding, the options are:
- use
bind_safe_input/bind_safe_outputto specify the PDO offset and size explicitly, without relying on MDP discovery; - or call
init_connectionyourself on theSafeMdpchild object and fill onlysafe_input_sizeor onlysafe_output_sizeinSafeMdpConfig.
add_connection()
pub fn add_connection(&mut self, slave_index: u16, config: FsoeConfig) -> Result<()>
Initializes the FSoE connection of the given slave and adds it to management (low-level API).
Parameters:
slave_index— slave index (1-based)config— FSoE connection configuration
Related structures:
pub struct FsoeConfig {
pub connection_id: u16, // connection ID (0 = allocated automatically)
pub safety_address: u16, // safety address (hardware DIP switch)
pub watchdog_time_ms: u32, // watchdog timeout (ms)
pub safe_input_size: u16, // safety input data size (bytes)
pub safe_output_size: u16, // safety output data size (bytes)
pub pdo_input_offset: u32, // PDO input offset
pub pdo_output_offset: u32, // PDO output offset
}
Example:
let config = FsoeConfig {
connection_id: 1,
safety_address: 0x0100,
watchdog_time_ms: 100,
safe_input_size: 2,
safe_output_size: 1,
pdo_input_offset: 0,
pdo_output_offset: 0,
};
fsoe_mgr.add_connection(1, config)?;
remove_connection()
pub fn remove_connection(&mut self, slave_index: u16) -> Result<()>
Closes and removes the FSoE connection of the given slave.
refresh_all_status()
pub fn refresh_all_status(&mut self) -> HashMap<u16, FsoeStatus>
Refreshes and returns a status snapshot of every connection.
Returns:
HashMap<u16, FsoeStatus>— map from slave index to status
write_safe_output() / write_output_frame()
pub fn write_safe_output(&self, slave_index: u16, data: &[u8]) -> Result<()>
pub fn write_output_frame(&self, slave_index: u16, frame_data: &[u8]) -> bool
Writes safety output data / a raw FSoE output frame to the given slave.
all_in_data() / read_input_frame()
pub fn all_in_data(&self) -> HashMap<u16, Vec<u8>>
pub fn read_input_frame(&self, slave_index: u16, buffer_size: usize) -> Option<Vec<u8>>
Reads the safety input data of every connection / the raw input frame of the given slave.
any_in_failsafe()
pub fn any_in_failsafe(&mut self) -> bool
Checks whether any connection is in the failsafe state.
enter_all_failsafe()
pub fn enter_all_failsafe(&self) -> Vec<(u16, Result<()>)>
Forces every connection into failsafe mode.
Returns:
Vec<(u16, Result<()>)>— result of the operation for each connection
process_cycle()
pub fn process_cycle(&self)
Runs one FSoE frame processing cycle (called from the PDO cyclic callback).
download_parameters()
pub fn download_parameters(&self, slave_index: u16, params: &[u8]) -> Result<u32>
Downloads safety parameters to the given slave and returns the SRA CRC32 check value. Call it only in the PARAMETER state.
Parameters:
slave_index— slave index (1-based)params— safety parameter data
Returns:
Result<u32>— SRA CRC32 check value
reset_connection() / clear_error()
pub fn reset_connection(&self, slave_index: u16) -> Result<()>
pub fn clear_error(&self, slave_index: u16)
Resets the FSoE connection / clears the error.
find_by_address() / find_by_connection_id()
pub fn find_by_address(&self, safety_address: u16) -> Option<u16>
pub fn find_by_connection_id(&self, connection_id: u16) -> Option<u16>
Finds the slave index by safety address / connection ID.
state()
pub fn state(&self, slave_index: u16) -> Option<FsoeState>
Reads the current FSoE state of the given slave.
Whether a valid connection exists (the Rust form of IsConnected)
The Rust side has no separate is_connected() entry point; the Option returned by state() is that fact:
let connected: bool = mgr.state(1).is_some();
Some(_)= a valid FSoE connection exists; the status is trustworthy.None= no connection / the read failed / the runtime is not ready. In that case the default values returned by convenience entry points such ascheck_watchdog()andlast_error()are not trustworthy. A safety diagnostics UI must show "unknown / read failed" and must not treat the default value as "safety OK".
The call triggers one status refresh. On the C++ side the same thing is called IsConnected() / StatusValid(); on the C side it is the return value of dx_fsoe_get_status(). Same fact, different names per language.
request_state() / check_watchdog() / last_error()
pub fn request_state(&self, slave_index: u16, target_state: FsoeState) -> Result<()>
pub fn check_watchdog(&self, slave_index: u16) -> bool
pub fn last_error(&self, slave_index: u16) -> Option<FsoeError>
request_state() requests a state transition on the given slave and returns Err on failure; check_watchdog() checks the watchdog (true = OK); last_error() returns the last FSoE error code, where None = no connection or the value cannot be read (not "no error" — do not read it as safety OK), while Some(FsoeError::None) really means there is no error.
connection_count() / is_slave_capable()
pub fn connection_count(&self) -> usize
pub fn is_slave_capable(&self, slave_index: u16) -> bool
Returns the number of connections currently managed / checks whether the given slave supports FSoE.
status_summary()
pub fn status_summary(&self) -> String
Returns a status summary string for all connections (for diagnostics).
SafeMdp — MDP multi-module connections
An MDP device can carry multiple independent FSoE connections (modules) on a single slave, typically safety I/O modules and safety drives.
- Single connection (
bind_safe_io) — simple devices, single-axis drives - Multiple connections (
SafeMdp/bind_mdp_drive_axis) — when modules need independent monitoring/recovery (for example, each axis of a multi-axis drive has its own safety connection)
Create an instance
pub fn new(master_index: u16, slave_index: u16) -> Self
Example:
let mdp = SafeMdp::new(master.index(), 1);
You can also take it directly from the slave handle (Slave::safe_mdp(), the same shape as slave.voe() / slave.aoe() / slave.soe()):
pub fn safe_mdp(&self) -> SafeMdp // Slave::safe_mdp()
let mdp = slave.safe_mdp(); // equivalent to SafeMdp::new(master.index(), current slave index)
detect_connections() / slave_connection_count() / device_address()
pub fn detect_connections(&self) -> u16
pub fn slave_connection_count(&self) -> u16
pub fn device_address(&self) -> Result<u16>
detect_connections() probes how many FSoE MDP connections the slave supports;
slave_connection_count() returns the number of MDP connections configured on the slave;
device_address() reads the device-level FSoE safety address of the slave.
init_connection() / close_connection()
pub fn init_connection(&self, connection_index: u16, config: SafeMdpConfig) -> Result<()>
pub fn close_connection(&self, connection_index: u16) -> Result<()>
Initializes / closes the FSoE MDP connection of the given module.
Parameters:
connection_index— connection index (starting at 0)config— MDP connection configuration
Related structures:
pub struct SafeMdpConfig {
pub connection_id: u16, // unique connection identifier
pub safety_address: u16, // FSoE slave safety address
pub watchdog_time_ms: u32, // watchdog timeout (ms)
pub safe_input_size: u16, // safety input data size (bytes)
pub safe_output_size: u16, // safety output data size (bytes)
pub pdo_input_offset: u32, // input offset in the IOmap
pub pdo_output_offset: u32, // output offset in the IOmap
pub module_number: u16, // module number (slot number)
pub module_profile: u16, // module profile (190, 195, 290, 790, 6900)
pub axis_number: u16, // axis number (Drive Connection only)
pub connection_type: u16, // connection type: 0=Master, 1=Slave
}
status() / check_watchdog() / last_error() / clear_error()
pub fn status(&self, connection_index: u16) -> Result<FsoeStatus>
pub fn check_watchdog(&self, connection_index: u16) -> bool
pub fn last_error(&self, connection_index: u16) -> i32
pub fn clear_error(&self, connection_index: u16)
status() returns the full runtime status of the connection; check_watchdog() checks the watchdog (true = OK);
last_error() / clear_error() get and clear the error of the connection.
Related structures:
pub struct FsoeStatus {
pub state: FsoeState, // current FSoE state
pub last_error: FsoeError, // last error code
pub error_count: u32, // total error count
pub frames_sent: u32, // frames sent
pub frames_received: u32, // valid frames received
pub crc_errors: u32, // CRC error count
pub watchdog_errors: u32, // watchdog timeout count
pub watchdog_expired: u8, // current watchdog state
pub in_failsafe: u8, // whether the connection is in failsafe mode
pub toggle_bit: u8, // current toggle bit value
pub initialized: u8, // whether the connection is initialized
}
request_state() / state() / reset()
pub fn request_state(&self, connection_index: u16, target_state: FsoeState) -> Result<()>
pub fn state(&self, connection_index: u16) -> Option<FsoeState>
pub fn reset(&self, connection_index: u16) -> Result<()>
request_state() requests a state transition on the connection; state() returns the current state;
reset() resets the connection (clears the error counters and returns to the Reset state).
write_safe_output() / read_safe_input()
pub fn write_safe_output(&self, connection_index: u16, data: &[u8]) -> Result<()>
pub fn read_safe_input(&self, connection_index: u16, max_size: usize) -> Result<Vec<u8>>
Writes / reads the safety output / input data of the given connection.
download_parameters() / set_failsafe_output()
pub fn download_parameters(&self, connection_index: u16, params: &[u8]) -> Result<u32>
pub fn set_failsafe_output(&self, connection_index: u16, data: &[u8]) -> Result<()>
download_parameters() downloads safety parameters to the connection and returns the SRA CRC;
set_failsafe_output() sets the failsafe output value of the connection.
module_comm_param() / module_diagnosis()
pub fn module_comm_param(&self, module_number: u16) -> Result<Vec<u8>>
pub fn module_diagnosis(&self, module_number: u16) -> Result<(u16, u16)>
module_comm_param() reads the FSoE communication parameters of the given module;
module_diagnosis() returns (连接状态,连接诊断).
FsoeCrc16 — CRC16 check
The FSoE safety frame CRC-16 uses the safety polynomial 0x139B7 from ETG.5100 §8.1.3.2 (low 16 bits 0x39B7, with x^16 implicit), an initial value of 0xFFFF, bit7→bit0 per byte, no reflection, and no final XOR.
Do not implement your own CRC over this polynomial to compute safety checks — always use the FsoeCrc16 entry points the SDK provides. The FsoeConstants::CRC16_POLY / FsoeConstants::CRC16_INITIAL constants exist only for comparison against the specification and for documentation checks; a hand-written implementation cannot be guaranteed to produce the same safety CRC as the SDK.
use darra_ethercat::FsoeCrc16;
// compute CRC16
let crc = FsoeCrc16::compute(&[0x01, 0x02, 0x03]);
// verify the CRC16 appended at the end of the data (little-endian)
let valid = FsoeCrc16::verify(&data_with_crc);
// append CRC16 at the end of the data
let data_with_crc = FsoeCrc16::append(&data);
// incremental update
let crc = FsoeCrc16::update(0xFFFF, &chunk1);
let crc = FsoeCrc16::update(crc, &chunk2);
FSoE states and errors
FsoeState
#[repr(i32)]
pub enum FsoeState {
Reset = 0x100, // initial / reset state
Session = 0x101, // session establishment
Connection = 0x102, // connection establishment
Parameter = 0x103, // parameter download
Data = 0x104, // data exchange (normal operation)
Failsafe = 0x105, // failsafe (the slave outputs safe values)
}
FsoeError
#[repr(i32)]
pub enum FsoeError {
None = 0x0000, // no error
WrongCommand = 0x0001, // wrong command
UnknownCommand = 0x0002, // unknown command
WrongConnId = 0x0003, // connection ID mismatch
Crc = 0x0004, // CRC check failed
Watchdog = 0x0005, // watchdog timeout
WrongAddress = 0x0006, // wrong safety address
WrongData = 0x0007, // wrong data
CommParamLength = 0x0008, // communication parameter length error
CommParam = 0x0009, // communication parameter error
AppParamLength = 0x000A, // application parameter length error
AppParam = 0x000B, // application parameter error
UnexpectedSession = 0x000C, // unexpected session command
FailsafeData = 0x000D, // failsafe data received
NotInitialized = 0x0100, // FSoE not initialized (internal error)
MaxConnections = 0x0101, // maximum number of connections reached (internal error)
InvalidState = 0x0102, // invalid state transition (internal error)
}
FsoeCommand
#[repr(u8)]
pub enum FsoeCommand {
Reset = 0x2A, // reset command
Session = 0x4E, // session request/response
Connection = 0x64, // connection request/response
Parameter = 0x52, // parameter download
Failsafe = 0x08, // failsafe mode
Data = 0x36, // normal data exchange
}
SafeModuleProfile
pub enum SafeModuleProfile {
DigitalInput = 190, // FSoE digital input
DigitalInOut = 195, // FSoE digital input/output
DigitalOutput = 290, // FSoE digital output
DriveConnection = 790, // FSoE drive connection (CiA402)
Master = 6900, // FSoE master module
}
FsoeConnectionInfo
pub struct FsoeConnectionInfo {
pub slave_index: u16, // slave index
pub config: FsoeConfig, // connection configuration (copy)
pub last_status: Option<FsoeStatus>, // most recent status snapshot
}
Events
FSoE safety data exchange callbacks are registered through SafetyManager (add_data_exchanged_callback / remove_data_exchanged_callback; the callback types live in darra_ethercat::slave::fsoe). Each time process_cycle() advances the safety cycle by one step, it dispatches the safety inputs read this cycle, the most recently issued safety outputs and the current FSoE state of each slave to the callbacks, if any subscribers exist. This is the single safety data exchange callback surface, not a multi-kind event bus. Connection management also uses SafetyManager.
add_data_exchanged_callback() / remove_data_exchanged_callback()
pub fn add_data_exchanged_callback(&self, cb: FsoeDataExchangeCallback)
pub fn remove_data_exchanged_callback(&self, cb: &FsoeDataExchangeCallback)
self is the SafetyManager. The callback type alias:
pub type FsoeDataExchangeCallback =
Arc<dyn Fn(&FsoeDataExchangeEventArgs) + Send + Sync>;
Registration / unregistration semantics: add_data_exchanged_callback takes the callback by value and appends it to the subscription list; remove_data_exchanged_callback removes by matching the Arc pointer (Arc::ptr_eq). To unregister you must keep the same Arc handle you registered with (Arc::clone a copy before calling add).
Example:
use std::sync::Arc;
use darra_ethercat::slave::fsoe::{FsoeDataExchangeCallback, FsoeDataExchangeEventArgs};
let cb: FsoeDataExchangeCallback = Arc::new(|args: &FsoeDataExchangeEventArgs| {
println!("从站{} 安全数据交换: 状态={:?}, 输入={}字节, 输出={}字节, 失效安全={}", // Slave {} safe data exchange: state={:?}, input={} bytes, output={} bytes, failsafe={}
args.slave_index, args.current_state,
args.safe_inputs.len(), args.safe_outputs.len(), args.in_failsafe);
});
fsoe_mgr.add_data_exchanged_callback(Arc::clone(&cb));
// unregister with the same Arc pointer when it is no longer needed
fsoe_mgr.remove_data_exchanged_callback(&cb);
Parameter structure:
pub struct FsoeDataExchangeEventArgs {
pub slave_index: u16, // slave index
pub current_state: FsoeState, // current FSoE state
pub safe_inputs: Vec<u8>, // safety inputs read back this cycle
pub safe_outputs: Vec<u8>, // most recently issued safety outputs through this instance (issued values, not device readback)
pub in_failsafe: bool, // whether in failsafe
pub cycle_count: u32, // cycle count
pub timestamp: SystemTime, // timestamp
}
When it fires: once per cycle from SafetyManager::process_cycle(); the safety data is read and the event dispatched only when subscribers exist.
Complete example
Single-connection safety IO (one-step initialization with bind_safe_io)
use darra_ethercat::{EtherCATMaster, EcState, SafetyManager};
// build() returns BuildResult (implements Deref only, no DerefMut);
// set_state needs &mut self, so take .master and bind it with let mut
let mut master = EtherCATMaster::builder()
.set_eni("config.deni")
.build()?
.master;
master.set_state(EcState::Operational)?;
let mut fsoe_mgr = SafetyManager::new(master.index());
// one-step binding (Session -> Connection -> Parameter -> Data automatic)
fsoe_mgr.bind_safe_io(
1, // slave_index: EL1904+EL2904
0, 2, // safe_input_offset=0, safe_input_size=2
0, 1, // safe_output_offset=0, safe_output_size=1
0x0100, // safety_address
100, // watchdog_ms
)?;
// handle it in the PDO cycle
let events = master.events();
events.on_pdo_cyclic_sync(move |_| {
fsoe_mgr.process_cycle();
// read the safety inputs
let inputs = fsoe_mgr.all_in_data();
if let Some(data) = inputs.get(&1) {
let safe_input = data[0];
// decide the safety output from the safety input
let safe_output = if (safe_input & 0x01) != 0 { 0x01u8 } else { 0x00u8 };
let _ = fsoe_mgr.write_safe_output(1, &[safe_output]);
}
});
Safety drive
use darra_ethercat::{SafetyManager, FsoeConfig};
let mut fsoe_mgr = SafetyManager::new(master.index());
// bind the safety drive IO (10 bytes of input + 2 bytes of output)
let config = FsoeConfig {
connection_id: 1,
safety_address: 0x0100,
watchdog_time_ms: 100,
safe_input_size: 10, // SafeDriveInput: u16 + i32 + i32
safe_output_size: 2, // SafeDriveOutput: u16
pdo_input_offset: 0,
pdo_output_offset: 0,
};
fsoe_mgr.add_connection(1, config)?;
// event monitoring: safety data exchange callback (fires once per cycle; in_failsafe flags failsafe)
// note: register before the move closure below, which captures fsoe_mgr by value
fsoe_mgr.add_data_exchanged_callback(std::sync::Arc::new(|args| {
if args.in_failsafe {
println!("驱动器安全停止! 从站{} 处于失效安全", args.slave_index); // Drive safe stop! Slave {} is in failsafe
}
}));
// handle the safety drive in the PDO cycle
let events = master.events();
events.on_pdo_cyclic_sync(move |_| {
fsoe_mgr.process_cycle();
if let Some(data) = fsoe_mgr.read_input_frame(1, 10) {
// parse the safety status word (first 2 bytes, little-endian)
let safety_status = u16::from_le_bytes([data[0], data[1]]);
let mut ctrl_word: u16 = 0;
if (safety_status & 0x0100) != 0 {
// Bit8: safety fault -> acknowledge the fault
ctrl_word |= 0x0080;
println!("安全故障: STO, 位置={}", i32::from_le_bytes([ // Safety fault: STO, position={}
data[2], data[3], data[4], data[5]
]));
} else {
// normal operation: clear the STO request
ctrl_word &= !0x0001;
}
let _ = fsoe_mgr.write_safe_output(1, &ctrl_word.to_le_bytes());
}
});
MDP multi-module safety device
use darra_ethercat::{SafeMdp, SafeMdpConfig};
let mdp = SafeMdp::new(master.index(), 1);
// probe the number of supported connections
let conn_count = mdp.detect_connections();
println!("从站 1 支持 {} 个 FSoE 连接", conn_count); // Slave 1 supports {} FSoE connections
// get the device safety address
if let Ok(addr) = mdp.device_address() {
println!("设备安全地址: 0x{:04X}", addr); // Device safety address: 0x{:04X}
}
// initialize the connection of each module
for i in 0..conn_count {
let config = SafeMdpConfig {
connection_id: i + 1,
safety_address: 0x0100 + i,
watchdog_time_ms: 100,
safe_input_size: 2,
safe_output_size: 1,
pdo_input_offset: 0,
pdo_output_offset: 0,
module_number: i,
module_profile: 195, // DigitalInOut
axis_number: 0,
connection_type: 0,
};
mdp.init_connection(i, config)?;
}
// read the safety inputs of each module
for i in 0..conn_count {
let input = mdp.read_safe_input(i, 16)?;
println!("模块 {} 安全输入: {:02X?}", i, input); // Module {} safety input: {:02X?}
}
// query the status of each connection
for i in 0..conn_count {
if let Ok(status) = mdp.status(i) {
println!("连接 {}: 状态={:?}, 失效安全={}, CRC错误={}", // Connection {}: state={:?}, failsafe={}, CRC errors={}
i, status.state, status.in_failsafe != 0, status.crc_errors);
}
}
// module diagnostics
for i in 0..conn_count {
if let Ok((state, diagnosis)) = mdp.module_diagnosis(i) {
println!("连接 {}: 诊断码=0x{:04X}", i, diagnosis); // Connection {}: diagnosis code=0x{:04X}
}
}
// close all connections
for i in 0..conn_count {
let _ = mdp.close_connection(i);
}
Multi-axis safety drive (MDP mode)
use darra_ethercat::SafetyManager;
let mut fsoe_mgr = SafetyManager::new(master.index());
// bind the safety connections of 2 axes
fsoe_mgr.bind_mdp_drive_axis(1, 0, 0x0100, 100)?; // axis 0
fsoe_mgr.bind_mdp_drive_axis(1, 1, 0x0200, 100)?; // axis 1
// safety data exchange monitoring (dispatched per slave each cycle; in_failsafe flags failsafe)
// note: register before the move closure below, which captures fsoe_mgr by value
fsoe_mgr.add_data_exchanged_callback(std::sync::Arc::new(|args| {
if args.in_failsafe {
println!("从站{} 失效安全: 状态={:?}", args.slave_index, args.current_state); // Slave {} failsafe: state={:?}
}
}));
// handle it in the PDO cycle
let events = master.events();
events.on_pdo_cyclic_sync(move |_| {
fsoe_mgr.process_cycle();
// each axis reads and writes safety data independently
});
Status monitoring
// refresh the status of all connections
let status_map = fsoe_mgr.refresh_all_status();
for (slave_idx, status) in &status_map {
println!("从站 {}: 状态={:?}, 错误计数={}, CRC错误={}, 帧发送={}, 帧接收={}", // Slave {}: state={:?}, error count={}, CRC errors={}, frames sent={}, frames received={}
slave_idx, status.state,
status.error_count, status.crc_errors,
status.frames_sent, status.frames_received);
if status.in_failsafe != 0 {
println!(" 从站 {} 处于失效安全模式", slave_idx); // Slave {} is in failsafe mode
}
}
// status summary
println!("{}", fsoe_mgr.status_summary());
// check whether any connection is in failsafe
if fsoe_mgr.any_in_failsafe() {
println!("警告: 存在失效安全连接"); // Warning: failsafe connections present
}
// emergency: put every connection into failsafe
let results = fsoe_mgr.enter_all_failsafe();
for (idx, result) in results {
match result {
Ok(()) => println!("从站 {} 已进入失效安全", idx), // Slave {} has entered failsafe
Err(e) => println!("从站 {} 失效安全失败: {:?}", idx, e), // Slave {} failsafe failed: {:?}
}
}
SafetyManager implements the Drop trait and closes all connections automatically when it is destroyed.
ConnID validation (validate_conn_id)
Before establishing a new FSoE connection, the chosen connection_id must be unique among all active connections on this master (ETG.5120 §5.2.3).
The SDK provides two equivalent functions, validate_conn_id / is_connection_id_available, at module level
(crate::slave::fsoe); the runtime performs the ConnID validation.
is_connection_id_available()
pub fn is_connection_id_available(conn_id: u16) -> bool
pub fn validate_conn_id(conn_id: u16) -> bool // equivalent alias
Checks that the given ConnID is not in use. conn_id == 0 is always invalid; a value other than 0 not held by any active connection returns
true. The two functions are semantically identical; the different names suit different code styles.
Bulk allocation example
use darra_ethercat::slave::fsoe::{validate_conn_id, is_connection_id_available};
// start at 1 and increment to find the first available ID
let mut conn_id = 1u16;
while !validate_conn_id(conn_id) {
let Some(next) = conn_id.checked_add(1) else {
// 1..=u16::MAX all in use: return the error honestly, do not panic
return Err(darra_ethercat::DarraError::InvalidParameter("ConnID 耗尽".into())); // ConnID exhausted
};
conn_id = next;
}
println!("分配 ConnID = {}", conn_id); // Allocated ConnID = {}
// alias form (same semantics)
assert!(is_connection_id_available(conn_id));
// apply it to FsoeConfig
let config = FsoeConfig {
connection_id: conn_id,
safety_address: 0x0100,
watchdog_time_ms: 100,
safe_input_size: 2,
safe_output_size: 1,
pdo_input_offset: 0,
pdo_output_offset: 0,
};
fsoe_mgr.add_connection(1, config)?;
- ETG.5120 §5.2.3 FSoE Connection Identifier uniqueness requirement