Skip to main content

Rust SDK overview

The Rust SDK is for developing EtherCAT master applications. The crate ships a complete high-level API: EtherCATMaster manages the master lifetime and the network, Slave accesses slaves and the object dictionary, SlavePdo reads and writes process data, and CiA402Instance / CiA401 handle the drive profiles.

Current version

This documentation covers Rust SDK v2.13.16.

Installation​

cargo add darra-ethercat-master

Or declare it in Cargo.toml:

[dependencies]
darra-ethercat-master = "2.13.16"
Crate name and import name
  • Dependency name (cargo add / Cargo.toml): darra-ethercat-master
  • Import name in code: darra_ethercat, for example use darra_ethercat::EtherCATMaster;

Requirements​

ItemRequirement
Operating systemWindows 10/11 (primary delivery); the Linux edition is planned
Rust1.70+ (stable)
PrivilegesAdministrator (Windows) / root (Linux)
Real-time driverProvided with the official installer

High-level API​

Type / functionPurpose
EtherCATMaster / MasterBuilderMaster initialization, NIC binding, state transitions, PDO cycle and diagnostics
Slave / SlavePdoSlave identity, object dictionary, process data read and write
SlaveDC / MasterDCDistributed clock configuration and diagnostics
CiA402Instance / CiA401CiA 402 / CiA 401 drive state machines and PDO mapping
CoEInstance / OdListCoE object dictionary and typed SDO
SoEInstance / FoEInstance / EoEInstance / AoEInstance / VoEInstanceThe remaining mailbox protocols
SafetyManager / SafeMdpFSoE functional safety
enumerate_network_info() / scan_slaves()NIC enumeration and slave scanning
DarraError / EcState / LinkStateUnified error type and state enums
soft_realtime moduleSoft real-time scheduling of the PDO thread: reserved core binding, thread base priority, process priority class

Soft real-time scheduling​

The darra_ethercat::soft_realtime module handles user-mode soft real-time scheduling of the PDO thread: it binds the PDO thread to a reserved core and raises the thread base priority. By default it touches only the PDO thread itself — it does not change the process priority class or the process CPU affinity. When the capability is not available, the policy is off, or the cycle is already carried by the real-time driver thread, every entry is a no-op and returns a reason text in Chinese; no entry panics or affects PDO frame exchange.

The PDO thread applies soft real-time itself at startup and re-applies it automatically after the thread exits and is recreated, so most applications only need query() to observe the status. Calling apply_for(master_number) explicitly suits scenarios that "must confirm it has taken effect early during startup". Repeated calls are idempotent and do not stack effects.

Module-level entries​

EntryReturnsDescription
query()SoftRealtimeStatusQueries the master of the most recent build / apply; when no master has ever been registered, queries at process level (master_number = 0). Read-only, no side effects
query_for(master_number)SoftRealtimeStatusQueries the specified master; master_number = 0 means process level
apply_for(master_number)SoftRealtimeStatusThread-level default: bind a reserved core + raise the thread base priority, without changing the process priority class. 0 means process level; a non-0 value is also registered as the default query target of query()
ensure_for(master_number)SoftRealtimeStatusEquivalent alias of apply_for
enable()SoftRealtimeStatusProcess-level strict: sets the whole process to REALTIME_PRIORITY_CLASS
ensure()SoftRealtimeStatusEquivalent alias of enable() (compatibility entry)
disable()SoftRealtimeStatusClears all master registrations; restores the pre-enable priority class only when the process real-time class was set by this SDK
try_set_thread_base_priority(thread_id, base_priority)boolSets the base priority of the specified thread to base_priority (the 16..31 real-time range); returns true only when the effective priority read back is >= 16
// darra_ethercat::soft_realtime
pub fn query() -> SoftRealtimeStatus
pub fn query_for(master_number: u16) -> SoftRealtimeStatus
pub fn apply_for(master_number: u16) -> SoftRealtimeStatus
pub fn ensure_for(master_number: u16) -> SoftRealtimeStatus
pub fn enable() -> SoftRealtimeStatus
pub fn ensure() -> SoftRealtimeStatus
pub fn disable() -> SoftRealtimeStatus
pub fn try_set_thread_base_priority(thread_id: u32, base_priority: i32) -> bool

Except for try_set_thread_base_priority, every entry returns the real status snapshot after the action: mode says which state it is currently in, and reason says what was done, or why it was not.

Thread level vs process level​

DimensionThread level (default)Process level (strict)
Entryapply_for(n) / ensure_for(n)enable() / ensure()
Applies toThe PDO thread of that masterEvery thread of the whole process
Process priority classNot modifiedSet to REALTIME_PRIORITY_CLASS
IntrusivenessSmall: the host UI, GC and other threads are unaffectedLarge: ordinary effective priorities are raised into the real-time range, and every host thread is affected
CPU affinityBinds only the PDO threadLikewise does not change process CPU affinity

Use the process-level entries only when "the whole host is allowed to be scheduled in the real-time range"; ordinary applications keep the thread level. disable() rolls back only what this SDK set: it clears all master registrations, and restores the pre-enable process priority class only when applied_by_sdk is true; the affinity and priority of an already bound PDO thread follow the thread lifetime and are not part of the rollback.

SoftRealtimeMode​

ValueDescription
UnsupportedThe platform does not support it / this machine has no valid reserved core / the current process lacks the privilege
InactiveThe capability exists but is not in effect yet (including policy off and the PDO thread not yet created)
ActiveThe PDO thread is already in the real-time range (reserved core bound + thread base priority), or the process is in REALTIME_PRIORITY_CLASS
KernelOffloadThe cycle is carried by the real-time driver thread, and the SDK does not change any process state

SoftRealtimePolicy​

Determined by the environment variable ENV_SOFT_REALTIME (DARRA_ECAT_SRT):

ValueDescription
AutoDefault: takes effect only when the cycle is not yet carried by the real-time driver thread, the reserved core is valid, and the privilege to raise priority is available; used when the variable is unset / empty / unrecognized
OffHard off: not applied even when explicitly requested
OnForced attempt

SoftRealtimeStatus fields​

FieldTypeDescription
modeSoftRealtimeModeCurrent mode
supportedboolWhether this machine meets the user-mode soft real-time conditions (Windows, valid reserved core, privilege to raise priority); unrelated to whether this attempt succeeded
process_realtimeboolWhether the process is currently in REALTIME_PRIORITY_CLASS; reported truthfully, regardless of who set it
applied_by_sdkboolWhether the process real-time class was set by this SDK; decides whether disable() rolls back
reserved_core_countu32Number of valid reserved cores; 0 when invalid / unreadable
reserved_maskStringReserved core mask, hexadecimal, LSB-first (bit0 = core 0), e.g. 0x00000000C0000000; (无) when not configured
pdo_corei32Core index the PDO thread is bound to; -1 (that is, PDO_CORE_UNASSIGNED) means unbound / unknown. For a process-level query it gives the core of the most recent successful bind
pdo_thread_idu32ID of the PDO thread whose priority was raised; 0 means unknown / not raised
pdo_priorityi32Effective priority of the PDO thread; 0 means unknown
thread_priority_appliedboolWhether the PDO thread priority was raised and passed the read-back check (>= 16)
policySoftRealtimePolicyScheduling policy currently in effect
reasonStringReason text in Chinese, always non-empty, ready to be displayed directly

Constants​

ConstantTypeValueDescription
ENV_SOFT_REALTIME&str"DARRA_ECAT_SRT"Name of the environment variable that controls the automatic soft real-time policy
PDO_CORE_UNASSIGNEDi32-1Sentinel value of SoftRealtimeStatus::pdo_core meaning unbound

Behavior contract​

  • Every failure is a no-op: no panic and no half-applied state; the reason of the returned snapshot is always non-empty and says what was done / why it was not. Troubleshoot by reason, not by guessing from return codes.
  • master_number = 0 means process level: query_for(0) looks only at process-level state; apply_for(0) is a process-level request. The no-argument form of query() queries the master of the most recent build / apply, and falls back to a process-level query when there is none.
  • Non-Windows platforms: every entry returns mode = SoftRealtimeMode::Unsupported and supported = false, and touches no system state.
  • Roll back only what it set itself: disable() uses applied_by_sdk as the criterion; a process real-time class set by someone else is left alone.
  • Trust mode for the state: KernelOffload means the cycle is already carried by the real-time driver thread, in which case the SDK does not change process state — and it does not mean soft real-time failed to take effect.

Example​

use darra_ethercat::soft_realtime::{self, SoftRealtimeMode};

// 1) Read-only observation: query() shows the master of the last build / apply
let st = soft_realtime::query();
println!(
"模式={:?} 支持={} 预留核={} 掩码={} PDO核={} 原因={}", // Mode={:?} supported={} reserved cores={} mask={} PDO core={} reason={}
st.mode, st.supported, st.reserved_core_count, st.reserved_mask, st.pdo_core, st.reason
);

// 2) Thread-level default: only bind the PDO thread of master 1 and raise its base priority; do not change the process priority class
let st = soft_realtime::apply_for(1);
if matches!(st.mode, SoftRealtimeMode::Active | SoftRealtimeMode::KernelOffload) {
println!("已生效,PDO 线程绑定核 = {}", st.pdo_core); // In effect; PDO thread bound to core = {}
} else {
println!("未生效:{:?},{}", st.policy, st.reason); // Not in effect: {:?}, {}
}

// 3) Process-level strict: the whole process enters the real-time priority class and every host thread is affected; call it only when explicitly needed
let st = soft_realtime::enable();
println!("进程实时类={} 由本 SDK 设置={}", st.process_realtime, st.applied_by_sdk); // Process real-time class={} set by this SDK={}

// 4) Wrap up: roll back only the process real-time class this SDK set
let st = soft_realtime::disable();
println!("已关闭,当前模式={:?},{}", st.mode, st.reason); // Turned off, current mode={:?}, {}

// 5) Raise the base priority of the host / diagnostics threads separately (16..31 real-time band); thread_id is registered when the application creates the thread
let thread_id: u32 = 1234; // Example value, replace with the real target thread ID
let ok = soft_realtime::try_set_thread_base_priority(thread_id, 20);
if !ok {
println!("未达成:权限不足或线程已退出"); // Not achieved: insufficient privileges or the thread has exited
}

// 6) Sentinel value: pdo_core equal to PDO_CORE_UNASSIGNED means the reserved core is not bound yet
if soft_realtime::query_for(1).pdo_core == soft_realtime::PDO_CORE_UNASSIGNED {
println!("主站 1 的 PDO 线程尚未绑定预留核"); // Master 1's PDO thread is not yet bound to a reserved core
}

Runtime dependencies​

The crate is a source package and does not contain the runtime libraries. The process must be able to find DarraEtherCAT.dll and the core runtime libraries; both are deployed by the official installer. Put them in the same directory as the exe, or add that directory to PATH. The installer default location is C:\DARRA\EtherCAT_Master\SDK\SDK_Rust\bin\.

If a runtime library is missing or the version does not match, EtherCATMaster::new() / MasterBuilder::build() return a DarraError carrying the reason. Handle it as an error and do not ignore the initialization result and keep calling.

Quick start​

Use the Darra configuration tool
  1. Open the Darra configuration tool and scan the EtherCAT network
  2. Configure the slave parameters (PDO mapping, DC settings and so on)
  3. Export the DENI configuration file
  4. Load the DENI file in your code to initialize the master
use darra_ethercat::{EcState, EtherCATMaster};

fn main() -> darra_ethercat::Result<()> {
// Recommended: load the DENI file exported by the configuration tool
// build() returns BuildResult (it implements Deref only, not DerefMut),
// and set_state needs &mut self, so take out .master and declare it mut.
let mut master = EtherCATMaster::builder()
.set_eni(r"C:\EtherCAT\MyProject.deni")
.build()?
.master;

master.set_state(EcState::Operational)?;
master.start();

let slave = master.slave(1);
let status_word: u16 = slave.sdo_read_value(0x6041, 0x00)?;
println!("Statusword=0x{status_word:04X}");

master.stop();
Ok(()) // Drop also stops the cycle and releases the master automatically
}

Alternative: automatic NIC discovery (without DENI)​

Without DENI, use enumerate_network_info() to scan the NICs and take the one that has slaves:

use darra_ethercat::{enumerate_network_info, EcState, EtherCATMaster, NicScanStatus};

fn main() -> darra_ethercat::Result<()> {
// scan all NICs and probe the slave count (takes about 0.5–1.5 s)
let nic = enumerate_network_info(false, true)?
.into_iter()
.find(|n| n.scan_status == NicScanStatus::Found)
.ok_or(darra_ethercat::DarraError::NoSlaves)?;

println!("使用 {} ({}), 从站 {} 台", nic.name, nic.description, nic.slave_num); // Using {} ({}), {} slave(s)

let mut master = EtherCATMaster::new()?;
let found = master.set_network_with_count(&nic.name, "")?; // the second argument is the redundant NIC; pass an empty string for a single NIC
println!("扫描到 {found} 个从站"); // Scan found {found} slaves

master.set_state(EcState::Operational)?;
master.start();

// ... read and write process data / mailbox ...

master.stop();
Ok(())
}

The second parameter of enumerate_network_info(is_redundant, need_slaves_num) is "whether to count the slaves": with false, scan_status is always NicScanStatus::NotMeasured (not requested ≠ measured 0 slaves), and slave_num is only the raw native value; only with true do you get IdleNoSlave / Found / OccupiedByMaster.

Which one to use
  • DENI — production; one line loads the complete ESI/PDO/DC parameter set. Recommended.
  • Automatic discovery — demos, tool-type applications, and cases where you do not need preconfigured startup parameters.

PDO and CoE example​

After entering OP the SDK runs the bus cycle, so the application layer does not need a real-time loop of its own. Process data is read and written as whole-frame snapshots:

let slave = master.slave(1);
let pdo = slave.pdo();

// Input (TxPDO, slave -> master): take a whole-frame snapshot and decode it as little-endian.
let inputs = pdo.try_inputs()?;
if inputs.len() >= 2 {
let status_word = u16::from_le_bytes([inputs[0], inputs[1]]);
println!("Statusword=0x{status_word:04X}");
}

// Output (RxPDO, master -> slave): the write length must match the mapping.
let mut outputs = pdo.try_outputs()?;
if outputs.len() >= 2 {
outputs[0..2].copy_from_slice(&0x000Fu16.to_le_bytes());
pdo.try_write_outputs(&outputs)?;
}

CoE mailbox access reads and writes object dictionary entries by index / subindex; failures return Err and never use 0 to fake success:

let slave = master.slave(1);

let status_word: u16 = slave.sdo_read_value(0x6041, 0x00)?; // Statusword
let position: i32 = slave.sdo_read_value(0x6064, 0x00)?; // Position actual

slave.sdo_write_value(0x6040, 0x00, &0x0006u16)?; // Controlword
slave.sdo_write_value(0x607A, 0x00, &100_000i32)?; // Target position

println!("SW=0x{status_word:04X} pos={position}");

Error handling​

Every entry point that can fail returns Result<T> (DarraError); none uses 0 or a null pointer to fake success:

SituationError
NIC binding failed / no slaves on the busDarraError::NetworkFailedWithLastError { .. }
State transition did not reach the targetDarraError::StateChangeFailed { target, actual_master_state, al_status_code, unreached_slaves }
SDO read or write failedDarraError::SdoReadFailed / DarraError::SdoWriteFailed (carrying the abort code)
PDO read or write failedDarraError::PdoFailed
Configuration load failedDarraError::ConfigLoadFailed

Match on the enum when you need to handle cases differently; the error text is only for logs and UI display.

Handles and lifetimes​

  • EtherCATMaster implements Drop: leaving scope stops the PDO cycle and releases the instance automatically; you can also call master.dispose() explicitly.
  • The Slave<'_> values returned by master.slave(n) / master.slaves(), and the SlavePdo<'_> returned by slave.pdo(), borrow the master. The master cannot be moved or destroyed while a handle is alive; using a handle after drop(master) is a compile error.
  • EtherCATMaster is not Sync; do not share &EtherCATMaster across threads. Move the instance into a thread, or create a new instance on the target thread.
  • Process data is sent and received automatically by the SDK's PDO cycle; the application layer does not need a real-time loop of its own.

Next steps​

Version compatibility​

The current SDK version is 2.13.16 (after cargo add darra-ethercat-master it matches what is declared in Cargo.toml). PATCH upgrades are compatible; MINOR / MAJOR upgrades require reinstalling the matching driver.