SoE (Servo over EtherCAT)
The SoE protocol carries the SERCOS servo communication protocol inside the EtherCAT mailbox; it applies to SERCOS-compatible servo drives.
Get an SoEInstance through slave.soe() — the method returns SoEInstance directly (not an Option); use soe.soe_support() to tell whether SoE is really supported. When a drive number is needed, use slave.soe_drive(drive_number).
Protocol capability detection
pub fn soe_support(&self) -> Option<bool>
pub fn is_support_known(&self) -> bool
pub fn is_supported(&self) -> bool
Authority chain:
- the low-level SoE details query, bit0 = SoE supported → positive evidence
- the low-level SII general information was really read →
soe_detailsbit0 counts as positive evidence only; that byte is reserved, so 0 / bit not set means unknown and must not be read as false mbx_protobit4 (0x10) is positive evidence only — the ESI fast path hardwires the protocol bits as CoE, so bit4 = 0 does not prove SoE is unsupported
Some(true)— supportedSome(false)— the current implementation never returns this value; SoE has no reverse authority, so anything unknown isNoneNone— unknown (must not be folded into false)
is_supported() is the bool view: true only for Some(true).
Most EtherCAT servo drives use the CoE + CiA 402 stack. SoE applies only to SERCOS-compatible drives (such as the Bosch Rexroth IndraDrive series). The two cannot be mixed — which one a slave supports depends on the hardware.
Status and errors
last_soe_error()
pub fn last_soe_error(&self) -> Option<SoEErrorCode>
Returns the most recent SoE error code recorded by this instance, or None when nothing has been recorded. SoEErrorCode is a #[repr(u16)] enum whose values are the protocol error codes (for example 0x1001 = IDN does not exist, 0x800B = general error).
This record is not updated by the read and write methods, so in normal operation what you get is always None: to tell whether one particular read or write failed, rely on the Result that method returns, and do not read None as "the previous call succeeded".
Mailbox protocol common interface (MailboxProtocol)
SoEInstance implements darra_ethercat::abstractions::MailboxProtocol, so it can be walked with the same set of methods as CoE / FoE / EoE / AoE / VoE. These three methods come from the trait, not from the instance itself, so the trait has to be imported first:
use darra_ethercat::abstractions::MailboxProtocol;
// trait method signatures (excerpt)
fn protocol_type(&self) -> u8
fn protocol_name(&self) -> &'static str
fn last_error_code(&self) -> u32
| Method | Returns | Description |
|---|---|---|
| protocol_type() | u8 | mailbox frame header protocol code, SoE = 0x05 |
| protocol_name() | &'static str | protocol name "SoE" |
| last_error_code() | u32 | numeric form of last_soe_error() (the raw SoEErrorCode); 0 when nothing is recorded |
use darra_ethercat::abstractions::MailboxProtocol;
let soe = slave.soe();
println!("协议: {:#04X} {}", soe.protocol_type(), soe.protocol_name()); // Protocol: {:#04X} {}
if soe.last_error_code() != 0 {
println!("最近错误码: 0x{:04X}", soe.last_error_code()); // Most recent error code: 0x{:04X}
}
SERCOS IDN system
SoE addresses drive parameters through the IDN (Identification Number). Each IDN is a 16-bit number that stands for one parameter (position, velocity, control word, and so on).
IDN naming rules:
| Prefix | Range | Description |
|---|---|---|
| S-x-xxxx | 0x0000 - 0x7FFF | SERCOS standard parameters (common to all vendors) |
| P-x-xxxx | 0x8000 - 0xBFFF | Product-specific parameters |
| P-x-xxxx | 0xC000 - 0xFFFF | Vendor-defined parameters |
Common standard IDNs (servo control):
| IDN | SERCOS name | Description | Data type |
|---|---|---|---|
| S-0-0001 (0x0001) | Cycle Time | communication cycle time | u32, us |
| S-0-0011 (0x000B) | Position Feedback 1 | actual position | i32, inc |
| S-0-0012 (0x000C) | Position Command | target position | i32, inc |
| S-0-0013 (0x000D) | Velocity Feedback | actual velocity | i32, rpm |
| S-0-0014 (0x000E) | Velocity Command | target velocity | i32, rpm |
| S-0-0016 (0x0010) | AT Config | input mapping configuration list | list |
| S-0-0019 (0x0013) | Drive Status | drive status word | u16 |
| S-0-0024 (0x0018) | MDT Config | output mapping configuration list | list |
| S-0-0036 (0x0024) | Max Velocity | maximum velocity limit | u32, rpm |
| S-0-0040 (0x0028) | Homing Velocity | homing velocity | u32, rpm |
| S-0-0064 (0x0040) | Drive Control Word | drive control word | u16 |
| S-0-0071 (0x0047) | Drive Status Word | drive status word | u16 |
SoEElementFlags element flags: select which "layer" (element) of an IDN to read; a bitflags-style
wrapper around u8.
#[repr(transparent)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct SoEElementFlags(pub u8);
impl SoEElementFlags {
pub const NONE: Self = Self(0x00); // no flags
pub const DATA_STATUS: Self = Self(0x01); // data state word (valid/invalid/busy)
pub const NAME: Self = Self(0x02); // parameter name (string)
pub const ATTRIBUTE: Self = Self(0x04); // attributes (data type/length/access bitfield)
pub const UNIT: Self = Self(0x08); // unit (string)
pub const MIN: Self = Self(0x10); // minimum value
pub const MAX: Self = Self(0x20); // maximum value
pub const VALUE: Self = Self(0x40); // operating data value (default, most common)
pub const DEFAULT: Self = Self(0x80); // default value
pub const fn contains(self, other: Self) -> bool;
pub const fn bits(self) -> u8;
}
SERCOS IDN encoding and decoding (module-level associated functions): convert between the SERCOS string form (such as "S-0-0001") and the 16-bit
IDN number without an instance.
// (is_standard, parameter_set 0..7, data_block 0..0x0FFF) -> 16-bit IDN
pub fn encode_idn(is_standard: bool, parameter_set: u8, data_block: u16) -> u16
// 16-bit IDN -> (is_standard, parameter_set, data_block)
pub fn decode_idn(idn: u16) -> (bool, u8, u16)
// parse "S-0-0011" / "P-1-0123" -> 16-bit IDN; None on failure
pub fn try_parse_sercos_idn(text: &str) -> Option<u16>
// 16-bit IDN -> "S-x-xxxx" / "P-x-xxxx" string
pub fn format_sercos_idn(idn: u16) -> String
Convention (bitfields): bit15 = P/S flag (set when is_standard=false: 0 = standard S-, 1 = vendor P-); bit14..12 = parameter_set; bit11..0 = data_block.
use darra_ethercat::slave::soe::{
encode_idn, decode_idn, try_parse_sercos_idn, format_sercos_idn, SoEElementFlags,
};
// string -> IDN (a parse failure is raised as an invalid-parameter error, no unwrap)
let idn = try_parse_sercos_idn("S-0-0011")
.ok_or(darra_ethercat::DarraError::InvalidParameter("IDN 字符串非法".into()))?; // 0x000B
let val = soe.read_i32(idn, 500)?;
// assemble directly / decode in reverse
let idn = encode_idn(true, 0, 11); // 0x000B (standard, set 0, block 11)
let (is_std, set, block) = decode_idn(0x000B); // (true, 0, 11)
// format back (debug / logging)
println!("{}", format_sercos_idn(idn)); // "S-0-0011"
// vendor IDN example
let p_idn = encode_idn(false, 1, 123); // 0x907B (0x8000 | 1<<12 | 123)
assert_eq!(format_sercos_idn(p_idn), "P-1-0123");
// element flags select different layers
let data = soe.read(0x000B, SoEElementFlags::VALUE.bits(), 500)?;
let name = soe.read(0x000B, SoEElementFlags::NAME.bits(), 500)?;
Basic read and write
read()
pub fn read(&self, idn: u16, element_flags: u8, timeout_ms: i32)
-> Result<Vec<u8>, DarraError>
Reads the raw bytes of the IDN parameter. Automatically switches out of a non-operational state.
Parameters:
idn(u16) — IDN numberelement_flags(u8) — element flags (default 0x40 = data value)timeout_ms(i32) — timeout (ms)
Returns:
Result<Vec<u8>, DarraError>— the data read
Example:
let soe = slave.soe();
if soe.soe_support() != Some(true) {
println!("从站未确认支持 SoE(未知或 SII 确认未声明)"); // Slave support for SoE is not confirmed (unknown, or not declared in the SII confirmation)
return Ok(());
}
// read the communication cycle time (S-0-0001)
let data = soe.read(0x0001, 0x40, 500)?;
// turn data[0..4] into [u8;4]: no panic when the length is short; return early with a data error
let Some(cycle_bytes) = data.get(0..4).and_then(|s| <[u8; 4]>::try_from(s).ok()) else {
eprintln!("S-0-0001 数据不足 4 字节: {} 字节", data.len()); // S-0-0001 data shorter than 4 bytes: {} bytes
return Ok(());
};
let cycle_time = u32::from_le_bytes(cycle_bytes);
println!("周期时间: {} us", cycle_time); // Cycle time: {} us
write()
pub fn write(&self, idn: u16, data: &[u8], element_flags: u8, timeout_ms: i32)
-> Result<(), DarraError>
Writes the IDN parameter. Automatically switches out of a non-operational state.
Parameters:
idn(u16) — IDN numberdata(&[u8]) — the data to writeelement_flags(u8) — element flags (0x40= data value, the most common case)timeout_ms(i32) — timeout (ms)
Returns:
Result<(), DarraError>— success or error
Example:
// set the target position (S-0-0012); element_flags 0x40 = data value
soe.write(0x000C, &100000i32.to_le_bytes(), 0x40, 500)?;
write_parameter()
pub fn write_parameter(&self, idn: u16, data: &[u8], timeout_ms: i32) -> Result<()>
Writes the IDN parameter through the data value element (ElementFlag 0x40); it is equivalent to write(idn, data, 0x40, timeout_ms), with one extra empty-data check first: when data is empty it returns Err(DarraError::InvalidParameter) directly and sends no mailbox frame.
Returns:
Ok(())— the slave accepted the writeErr(DarraError::InvalidParameter)—datais emptyErr(DarraError::SoeFailed(idn))— the write failed / timed out
// Write control word S-0-0064 = 0x0006
soe.write_parameter(0x0040, &0x0006u16.to_le_bytes(), 500)?;
Typed reads
pub fn read_i16(&self, idn: u16, timeout_ms: i32) -> Result<i16>
pub fn read_i32(&self, idn: u16, timeout_ms: i32) -> Result<i32>
pub fn read_u16(&self, idn: u16, timeout_ms: i32) -> Result<u16>
pub fn read_u32(&self, idn: u16, timeout_ms: i32) -> Result<u32>
pub fn read_f32(&self, idn: u16, timeout_ms: i32) -> Result<f32>
pub fn read_f64(&self, idn: u16, timeout_ms: i32) -> Result<f64>
pub fn read_string(&self, idn: u16, timeout_ms: i32) -> Result<String>
Example:
// read the actual position (S-0-0011)
let pos = soe.read_i32(0x000B, 500)?;
println!("实际位置: {} inc", pos); // Actual position: {} inc
// read the drive status word (S-0-0071)
let status = soe.read_u16(0x0047, 500)?;
println!("状态字: 0x{:04X}", status); // Status word: 0x{:04X}
// read the parameter name
let name = soe.read_string(0x000B, 500)?;
println!("参数名: {}", name); // Parameter name: {}
Typed writes
pub fn write_i16(&self, idn: u16, value: i16, timeout_ms: i32) -> Result<()>
pub fn write_i32(&self, idn: u16, value: i32, timeout_ms: i32) -> Result<()>
pub fn write_u16(&self, idn: u16, value: u16, timeout_ms: i32) -> Result<()>
pub fn write_u32(&self, idn: u16, value: u32, timeout_ms: i32) -> Result<()>
Example:
// set the target position (S-0-0012); the 3rd argument is the timeout (ms)
soe.write_i32(0x000C, 50000, 500)?;
// write the control word (S-0-0064)
soe.write_u16(0x0040, 0x0006, 500)?;
Metadata reads
read_name()
pub fn read_name(&self, idn: u16, timeout_ms: i32) -> Result<String>
Reads the IDN parameter name (the ElementFlag 0x02 read).
read_unit()
pub fn read_unit(&self, idn: u16, timeout_ms: i32) -> Result<String>
Reads the IDN parameter unit (the ElementFlag 0x08 read).
Example:
let name = soe.read_name(0x000B, 500)?;
println!("参数名: {}", name); // Parameter name: {}
let unit = soe.read_unit(0x000B, 500)?;
println!("单位: {}", unit); // Unit: {}
read_attributes()
pub fn read_attributes(&self, idn: u16, timeout_ms: i32) -> Result<SoEAttributes>
Reads the attribute element of an IDN (ElementFlag 0x04) and decodes it into SoEAttributes: evaluation factor, length step, whether it is a list / a command, data type, number of decimal places, and the write-protection bits for the PreOp / SafeOp / Op states. The decoded struct tells the access rights directly through is_read_only() / access_mode().
A failed read returns Err(DarraError::SoeFailed(idn)); it does not return an all-zero attribute struct pretending the read succeeded.
let attrs = soe.read_attributes(0x000B, 500)?;
println!(
"类型: {:?}, 长度档位: {}, 访问: {}", // Type: {:?}, length tier: {}, access: {}
attrs.data_type, attrs.length, attrs.access_mode(),
);
read_min_value() / read_max_value() / read_default_value()
pub fn read_min_value(&self, idn: u16, timeout_ms: i32) -> Result<Vec<u8>>
pub fn read_max_value(&self, idn: u16, timeout_ms: i32) -> Result<Vec<u8>>
pub fn read_default_value(&self, idn: u16, timeout_ms: i32) -> Result<Vec<u8>>
Reads the minimum (0x10), maximum (0x20) and default (0x80) value of the IDN parameter.
Example:
let name = soe.read_name(0x000B, 500)?;
let unit = soe.read_unit(0x000B, 500)?;
let min = soe.read_min_value(0x000B, 500)?;
let max = soe.read_max_value(0x000B, 500)?;
println!("参数: {} ({})", name, unit); // Parameter: {} ({})
if min.len() >= 4 && max.len() >= 4 {
// the guard already guarantees 4 bytes; a failed conversion does not panic in place but returns early with a data error
let (Ok(min_arr), Ok(max_arr)) = (min[0..4].try_into(), max[0..4].try_into()) else {
eprintln!("min/max 数据不足 4 字节"); // min/max data shorter than 4 bytes
return Ok(());
};
let min_val = i32::from_le_bytes(min_arr);
let max_val = i32::from_le_bytes(max_arr);
println!("范围: {} - {}", min_val, max_val); // Range: {} - {}
}
Parameter information
get_available_idns() / available_idns()
pub fn get_available_idns(&self, timeout_ms: i32) -> Result<Vec<u16>>
pub fn available_idns(&self, timeout_ms: i32) -> Result<Vec<u16>>
Lists every IDN the slave supports. The two names are two entry points to the same read: get_available_idns() forwards directly to available_idns() (the Rust-style entry point), with identical data and identical failure semantics.
A failed read or an empty list returns Err(DarraError::SoeFailed(0)); "there is no IDN" and "the read failed" are not folded into an empty list.
get_parameter_info() / parameter_info() / read_parameter()
pub fn get_parameter_info(&self, idn: u16, timeout_ms: i32) -> Result<SoEParameter>
pub fn parameter_info(&self, idn: u16, timeout_ms: i32) -> Result<SoEParameter>
pub fn read_parameter(&self, idn: u16, timeout_ms: i32) -> Result<SoEParameter>
Reads the full information of the IDN parameter (name, unit, attributes, current value, minimum/maximum value and so on). The three names point at one implementation: parameter_info() is the Rust-style entry point, and both get_parameter_info() and read_parameter() forward directly to it, with identical return values and identical failure semantics.
Name / unit / attributes / value / minimum value / maximum value / default value are read one by one, and a failure on any one of them makes the whole call return Err (DarraError::SoeFailed(idn)) — "the device does not have this parameter" and "the read failed" are not folded into the same empty value. When Err comes back, an invalid parameter / a timeout / a failed read are all possible.
pub struct SoEParameter {
pub idn: u16,
pub name: String,
pub unit: String,
pub attributes: SoEAttributes,
pub value: Vec<u8>,
pub default_value: Vec<u8>,
pub min_value: Vec<u8>,
pub max_value: Vec<u8>,
}
impl SoEParameter {
pub fn sercos_idn(&self) -> String // SERCOS IDN form (such as "S-0-0001")
pub fn category(&self) -> &'static str // category ("Standard" / "Product" / "Vendor")
pub fn is_read_only(&self) -> bool // whether the parameter is read-only
pub fn access_mode(&self) -> &'static str // access mode ("RO" / "RW" / "RW*")
}
pub struct SoEAttributes {
pub evaluation_factor: u16, // evaluation factor
pub length: u8, // data length
pub is_list: bool, // whether it is a list
pub is_command: bool, // whether it is a command
pub data_type: SoEDataType, // data type
pub decimals: u8, // number of decimal places
pub write_protected_preop: bool, // write protection in the PreOp state
pub write_protected_safeop: bool, // write protection in the SafeOp state
pub write_protected_op: bool, // write protection in the Op state
}
#[repr(u8)]
pub enum SoEDataType {
Binary = 0, // binary
UInt = 1, // unsigned integer
Int = 2, // signed integer
Hexadecimal = 3, // hexadecimal
String = 4, // string
IDN = 5, // IDN reference
Float = 6, // floating point
Parameter = 7, // parameter
}
Example:
let param = soe.get_parameter_info(0x000B, 500)?;
println!("IDN: {} - {}", param.sercos_idn(), param.name);
println!("类别: {}, 单位: {}, 访问: {}", // Category: {}, unit: {}, access: {}
param.category(), param.unit, param.access_mode());
read_all_parameters()
pub fn read_all_parameters(&self, timeout_ms: i32) -> Result<Vec<SoEParameter>>
Reads parameters in bulk from a fixed list of standard IDNs (0x0000 / 0x0001 / 0x0002 / 0x0003 / 0x0004 / 0x0010 / 0x0011 / 0x0012 / 0x0013 / 0x0014 / 0x0015 / 0x0016 / 0x0021 / 0x0024 / 0x0032 / 0x0033 / 0x0040 / 0x0047, 18 in total), calling parameter_info() for each of them.
- an IDN whose name and value are both empty does not enter the result; the list keeps only parameters that have content
- a failure on any IDN makes the whole call return
Err; failed items are not skipped to assemble a list anyway. If the device lacks any IDN in the list, the whole batch fails — when you need fault tolerance, walkavailable_idns()yourself and callparameter_info()for each IDN timeout_msis the timeout for each IDN (and for each element read inside it), not a total budget for the whole batch
let params = soe.read_all_parameters(500)?;
for p in ¶ms {
println!("{} = {:02X?} {}", p.sercos_idn(), p.value, p.unit);
}
AT/MDT mapping
SERCOS uses AT (Acknowledge Telegram) and MDT (Master Data Telegram) to transfer cyclic data:
- AT = cyclic inputs from the slave to the master (actual position, actual velocity, status word, ...)
- MDT = cyclic outputs from the master to the slave (target position, target velocity, control word, ...)
The mapping configuration determines which IDN parameters are included in the cyclic data frame.
get_idn_mapping()
pub fn get_idn_mapping(&self, timeout_ms: i32) -> Result<ServoMappingInfo>
Reads the current AT/MDT mapping configuration of the drive. Returns Result<ServoMappingInfo>: Err means a timeout / a failed read.
pub struct ServoMappingInfo {
pub at_mapping: Vec<ServoMappingEntry>, // AT (input) mapping list
pub mdt_mapping: Vec<ServoMappingEntry>, // MDT (output) mapping list
pub at_bit_size: i32, // total AT bits
pub mdt_bit_size: i32, // total MDT bits
}
impl ServoMappingInfo {
pub fn at_byte_size(&self) -> i32 // total AT bytes
pub fn mdt_byte_size(&self) -> i32 // total MDT bytes
}
pub struct ServoMappingEntry {
pub idn: u16, // IDN number
pub name: String, // parameter name
pub bit_length: i32, // data length (bits)
}
impl ServoMappingEntry {
pub fn byte_length(&self) -> i32 // data length (bytes)
}
idn_mapping()
pub fn idn_mapping(&self, timeout_ms: i32) -> Result<ServoMappingInfo>
Reads the AT/MDT mapping of this drive; it is the Rust-style entry point of get_idn_mapping() — get_idn_mapping() forwards directly to it and both return the same result.
- a failure on either AT (
S-0-0016) or MDT (S-0-0024) makes the whole call returnErr(DarraError::SoeFailed(idn)); "there is no mapping" and "the read failed" are not folded into the same empty mapping at_bit_size/mdt_bit_sizestart from a 16-bit baseline and then add the attribute length step of every mapping entry (8 / 16 / 32 / 64 bits)- if reading a mapping entry's name fails, only that entry's
nameis affected (it falls back to the formIDN 0xNNNN) and the read as a whole still succeeds; if reading a mapping entry's attributes fails, the entry is still listed, but itsbit_lengthis0and it does not count towards the total number of bits
get_all_drive_mappings()
pub fn get_all_drive_mappings(&self, timeout_ms: i32) -> Result<HashMap<u8, ServoMappingInfo>>
Reads the mapping information of all drives (up to 8 drives are scanned). Returns Result<HashMap<u8, ServoMappingInfo>>: Err means a timeout / a failed read.
Parameter change notification
The SoE Notification feature lets you monitor changes of SERCOS slave IDN parameters. Parameter value changes are detected by polling.
Mechanism:
- Hardware notification: try to enable the slave's own notification by writing S-0-0127 (the notification request IDN)
- Polling detection: if the slave does not support hardware notification, fall back to polling automatically
enable_notification()
pub fn enable_notification(&self, idn: u16, timeout_ms: i32) -> bool
Enables parameter change notification for the given IDN. It first tries to enable hardware notification through S-0-0127; whether or not that succeeds, the IDN is added to the polling monitor list.
Returns:
bool—true= the slave confirmed hardware notification is supported;false= fell back to polling mode
disable_notification()
pub fn disable_notification(&self, idn: u16)
Disables parameter change notification for the given IDN.
disable_all_notifications()
pub fn disable_all_notifications(&self)
Disables every enabled notification and clears the monitor list.
poll_notifications()
pub fn poll_notifications(&self, timeout_ms: i32) -> Vec<SoENotificationEventArgs>
pub fn monitored_idns(&self) -> Vec<u16>
pub fn get_monitored_idns(&self) -> Vec<u16> // alias of monitored_idns
poll_notifications() polls every monitored IDN for parameter changes and returns the list of change events it detected;
monitored_idns() / get_monitored_idns() return the list of IDNs currently monitored.
SoENotificationEventArgs
#[derive(Debug, Clone)]
pub struct SoENotificationEventArgs {
pub slave_index: u16, // slave index
pub drive_number: u8, // drive number
pub idn: u16, // the IDN number that changed
pub new_value: Option<Vec<u8>>, // new value
pub old_value: Option<Vec<u8>>, // old value
}
impl SoENotificationEventArgs {
pub fn sercos_idn(&self) -> String // formatted SERCOS IDN name (such as "S-0-0127")
}
Example:
let soe = slave.soe();
// enable monitoring of the actual position (S-0-0011)
let hw_supported = soe.enable_notification(0x000B, 500);
println!("硬件通知: {}", if hw_supported { "支持" } else { "回退到轮询" }); // Hardware notification: {} — supported / falls back to polling
// enable monitoring of the drive status word (S-0-0071)
soe.enable_notification(0x0047, 500);
// poll for changes
let changes = soe.poll_notifications(200);
for args in &changes {
println!("参数变化: {} (IDN 0x{:04X})", args.sercos_idn(), args.idn); // Parameter changed: {} (IDN 0x{:04X})
if let Some(ref new_val) = args.new_value {
println!(" 新值: {:?}", new_val); // New value: {:?}
}
}
// list the monitored IDNs
let monitored = soe.monitored_idns();
println!("监控列表: {:?}", monitored); // Monitoring list: {:?}
// stop monitoring
soe.disable_all_notifications();
Standard IDN constants
pub mod standard_idn {
pub const IDN_LIST: u16 = 0x0000; // IDN list (S-0-0000)
pub const CYCLE_TIME: u16 = 0x0001; // communication cycle time (S-0-0001)
pub const AT_CONFIG: u16 = 0x0010; // AT configuration - input mapping (S-0-0016)
pub const MDT_CONFIG: u16 = 0x0018; // MDT configuration - output mapping (S-0-0024)
pub const NOTIFICATION_REQUEST: u16 = 0x007F; // notification request (S-0-0127)
}
Procedure commands
execute_command()
pub fn execute_command(&self, idn: u16, timeout_ms: i32, poll_interval_ms: i32) -> Result<()>
Executes an SoE procedure command (SERCOS Procedure Command). It triggers execution by writing bit0 of the DataState element, then polls until the command completes.
Parameters:
idn(u16) — IDN number of the command to executetimeout_ms(i32) — timeout for the command to complete (ms)poll_interval_ms(i32) — polling interval (ms)
Returns:
Result<()>—Ok(())on success;Err(DarraError::Timeout)on timeout
Example:
// execute the homing command (S-0-0148). execute_command returns Result<()>:
// Ok(()) = command complete, Err(DarraError::Timeout) = timeout/failure
match soe.execute_command(0x0094, 5000, 50) {
Ok(()) => println!("回零完成"), // Homing complete
Err(e) => println!("回零超时或失败: {}", e), // Homing timed out or failed: {}
}
// custom timeout (long-running command); use ? to propagate the error
soe.execute_command(0x0094, 30000, 100)?;
read_data_state()
pub fn read_data_state(&self, idn: u16, timeout_ms: i32) -> Result<u16>
Reads the Data State element of an IDN (ElementFlag 0x01), which carries the command state, data validity and similar information, and returns a u16
value. It is often used with execute_command() to poll the current state during a long-running procedure command.
let state = soe.read_data_state(0x0094, 500)?;
let command_active = (state & 0x0001) != 0;
let command_error = (state & 0x0002) != 0;
println!("命令激活: {}, 命令错误: {}", command_active, command_error); // Command active: {}, command error: {}
Complete example
Parameter scanning
let soe = slave.soe();
if soe.soe_support() != Some(true) {
return Ok(());
}
let idns = soe.get_available_idns(5000)?;
println!("从站支持 {} 个 IDN 参数\n", idns.len()); // Slave supports {} IDN parameters\n
for idn in idns.iter().take(10) {
// get_parameter_info returns Result<SoEParameter> and needs the timeout
let info = soe.get_parameter_info(*idn, 500)?;
println!("{}: {} = {:02X?} {} [{}]",
info.sercos_idn(), info.name, info.value,
info.unit, info.access_mode());
}
Servo drive control
let soe = slave.soe();
if soe.soe_support() != Some(true) {
return Ok(());
}
// 1. Read the drive status (read_u16 returns Result<u16> and needs the timeout)
let status = soe.read_u16(0x0047, 500)?;
println!("状态字: 0x{:04X}", status); // Status word: 0x{:04X}
// 2. Inspect the AT/MDT mapping (to learn the cyclic data layout)
// get_idn_mapping returns Result<ServoMappingInfo> and needs the timeout
let mapping = soe.get_idn_mapping(5000)?;
println!("\nAT 映射(输入 {} 字节):", mapping.at_byte_size()); // \nAT mapping (input {} bytes):
for entry in &mapping.at_mapping {
println!(" IDN 0x{:04X}: {} ({}B)", entry.idn, entry.name, entry.byte_length());
}
println!("\nMDT 映射(输出 {} 字节):", mapping.mdt_byte_size()); // \nMDT mapping (output {} bytes):
for entry in &mapping.mdt_mapping {
println!(" IDN 0x{:04X}: {} ({}B)", entry.idn, entry.name, entry.byte_length());
}
// 3. Write the control word to enable the drive (S-0-0064)
soe.write_u16(0x0040, 0x0006, 500)?;
// 4. Set the target position (S-0-0012)
soe.write_i32(0x000C, 50000, 500)?;
// 5. Read the actual position (S-0-0011)
let pos = soe.read_i32(0x000B, 500)?;
println!("\n实际位置: {} inc", pos); // \nActual position: {} inc
Metadata queries
let soe = slave.soe();
if soe.soe_support() != Some(true) {
return Ok(());
}
// read the parameter name and unit (read_name/read_unit return Result<String>)
let name = soe.read_name(0x000B, 500)?;
let unit = soe.read_unit(0x000B, 500)?;
println!("参数: {} ({})", name, unit); // Parameter: {} ({})
// read the minimum and maximum value (return Result<Vec<u8>>)
let min = soe.read_min_value(0x000B, 500)?;
let max = soe.read_max_value(0x000B, 500)?;
if min.len() >= 4 && max.len() >= 4 {
// the guard already guarantees 4 bytes; a failed conversion does not panic in place but returns early with a data error
let (Ok(min_arr), Ok(max_arr)) = (min[0..4].try_into(), max[0..4].try_into()) else {
eprintln!("min/max 数据不足 4 字节"); // min/max data shorter than 4 bytes
return Ok(());
};
let min_val = i32::from_le_bytes(min_arr);
let max_val = i32::from_le_bytes(max_arr);
println!("范围: {} - {} {}", min_val, max_val, unit); // Range: {} - {} {}
}
Runtime asynchronous notification (Notification / Emergency)
Polling with poll_notifications() suits low-frequency monitoring; for high real-time scenarios (millisecond response) use the callback dispatch model instead:
register once, and the underlying layer calls your closure directly. SoE supports two kinds of events — Notification (an IDN value changed)
and Emergency (an SoE error frame, ETG.5003).
The SDK exposes callbacks as the Arc<dyn Fn(...) + Send + Sync> type, so multiple subscribers can share them and they are thread-safe.
When registering a callback (add_notification_callback / register_native_emergency_callback) you must keep a clone of the Arc you passed in; later removal (remove_notification_callback / unregister_native_emergency_callback) matches by Arc::ptr_eq.
Without a kept clone you cannot remove it precisely: you can clear all monitored IDNs with disable_all_notifications() (which does not clear the callback list), or clear every callback registered on this slave through register_native_* with clear_native_callbacks().
SoENotificationEvent
use std::time::SystemTime;
#[derive(Debug, Clone)]
pub struct SoENotificationEvent {
pub master_index: u16, // master index
pub slave_index: u16, // slave index
pub drive_number: u8, // drive number
pub idn: u16, // the IDN that changed
pub new_value: Option<Vec<u8>>, // new value (Element Value)
pub old_value: Option<Vec<u8>>, // old value (as read by the previous poll)
pub timestamp: SystemTime, // trigger time
}
impl SoENotificationEvent {
/// SERCOS IDN form "S-0-0016" / "P-1-0100"
pub fn sercos_idn(&self) -> String;
}
SoEEmergencyEvent
#[derive(Debug, Clone)]
pub struct SoEEmergencyEvent {
pub master_index: u16, // master index
pub slave_index: u16, // slave index
pub drive_number: u8, // drive number
pub idn: u16, // associated IDN
pub error_code: SoEErrorCode, // SoE error code (ETG.5003)
pub data: Vec<u8>, // Emergency payload (raw bytes)
pub timestamp: SystemTime, // trigger time
}
add_notification_callback() / remove_notification_callback()
use std::sync::Arc;
pub type SoENotificationCallback = Arc<dyn Fn(&SoENotificationEvent) + Send + Sync>;
pub type SoEEmergencyCallback = Arc<dyn Fn(&SoEEmergencyEvent) + Send + Sync>;
pub fn add_notification_callback(&self, cb: SoENotificationCallback)
pub fn remove_notification_callback(&self, cb: &SoENotificationCallback)
Registers / removes an SoE Notification callback.
Registering the same Arc several times makes it fire several times. The callback runs while events are dispatched, so do not block or perform long computations.
fire_notification()
pub fn fire_notification(&self, ev: &SoENotificationEvent)
Manually dispatches one event to the Notification callbacks of this instance (for example to reuse the same set of callbacks from your own polling loop or an external trigger source). It delivers only to callbacks registered on the same instance through add_notification_callback(): every call to slave.soe() creates a new instance, and callback lists are not shared across instances; it does not trigger notification on the slave side either, and it does not deliver to callbacks registered through register_native_*.
Before dispatching, it clones a snapshot of the callback list and then invokes the entries one by one; a panic in a single callback is caught in place and ignored, without affecting the other callbacks of the same dispatch. The method runs synchronously on the calling thread.
use std::sync::Arc;
use darra_ethercat::slave::soe::{SoENotificationEvent, SoENotificationCallback};
let soe = slave.soe();
let cb: SoENotificationCallback = Arc::new(|e: &SoENotificationEvent| {
println!("IDN {} -> {:?}", e.sercos_idn(), e.new_value);
});
soe.add_notification_callback(Arc::clone(&cb));
// Self-built trigger source: construct the event and hand it to the same set of callbacks
soe.fire_notification(&SoENotificationEvent {
master_index: 0,
slave_index: 1,
drive_number: 0,
idn: 0x000B,
new_value: Some(1234i32.to_le_bytes().to_vec()),
old_value: None,
timestamp: std::time::SystemTime::now(),
});
register_native_emergency_callback() / unregister_native_emergency_callback()
pub fn register_native_emergency_callback(&self, cb: SoEEmergencyCallback)
pub fn unregister_native_emergency_callback(&self, cb: &SoEEmergencyCallback)
Registers / removes an SoE Emergency callback (fires when an SoE Error Frame is received). Removal matches the same Arc with Arc::ptr_eq, so you must keep the original Arc handle to remove it. The execution constraints are the same as for Notification (it runs while events are dispatched; do not block or perform long computations).
Unlike add_notification_callback (which attaches to an instance-local list), Emergency callbacks have no instance-local list and this is the only registration path: the callbacks are shared per master / slave, multiple SoEInstance objects of the same slave register into the same callback set, and any instance calling clear_native_callbacks() clears every callback that the slave registered through register_native_*.
Example: register and keep the Arc for removal
use std::sync::Arc;
use darra_ethercat::slave::soe::{
SoENotificationEvent, SoENotificationCallback,
SoEEmergencyEvent, SoEEmergencyCallback,
};
let soe = slave.soe();
// 1. Notification callback
let cb: SoENotificationCallback = Arc::new(|e: &SoENotificationEvent| {
println!(
"[{}] Slave {} IDN {} (0x{:04X}) 变化", // [{}] Slave {} IDN {} (0x{:04X}) changed
format!("{:?}", e.timestamp),
e.slave_index,
e.sercos_idn(),
e.idn,
);
if let Some(v) = &e.new_value {
println!(" 新值 ({} 字节): {:02X?}", v.len(), v); // New value ({} bytes): {:02X?}
}
});
soe.add_notification_callback(Arc::clone(&cb));
// enable polled monitoring (falls back automatically when hardware notification is unsupported)
soe.enable_notification(0x000B, 500); // S-0-0011 actual position
// 2. Emergency callback — raise an alarm immediately when an SoE Error Frame arrives (keep the Arc handle for removal)
let emcy: SoEEmergencyCallback = Arc::new(|e: &SoEEmergencyEvent| {
eprintln!(
"SoE Emergency: Slave {}, IDN 0x{:04X}, 错误码 {:?}, data={:02X?}", // SoE Emergency: Slave {}, IDN 0x{:04X}, error code {:?}, data={:02X?}
e.slave_index, e.idn, e.error_code, e.data,
);
});
soe.register_native_emergency_callback(Arc::clone(&emcy));
// 3. Remove before exit (both callbacks match the original Arc handle through Arc::ptr_eq)
soe.remove_notification_callback(&cb);
soe.unregister_native_emergency_callback(&emcy);
- IEC 61800-7-204 — SERCOS over EtherCAT (SoE)
- ETG.5003 — Emergency frame format