Skip to main content

Master control

EtherCATMaster handles master initialization, NIC binding, the EtherCAT state machine, the PDO cycle and diagnostics. Every entry point that can fail returns Result<T> (DarraError); the instance implements Drop, which stops the cycle and releases it when it goes out of scope.

Lifecycle​

StepEntry pointReturnsDescription
CreateEtherCATMaster::new()Result<EtherCATMaster>Allocates a master instance automatically
Specific instanceEtherCATMaster::with_index(i)Result<EtherCATMaster>For multi-instance setups; indexes start at 1
Configuration fileEtherCATMaster::from_json_file(path) / from_json(json)Result<EtherCATMaster>Binds, configures, enters OP and starts in one step
BuilderEtherCATMaster::builder().set_eni(path).build()Result<BuildResult>Loads a DENI/ENI file; recommended for production
Bind a NICmaster.set_network(primary, redundant)Result<()>Pass an empty string for redundant when there is a single NIC
Bind and countmaster.set_network_with_count(primary, redundant)Result<i32>Returns the number of slaves found by the scan
State transitionmaster.set_state(EcState)Result<()>Runs the full INIT → PRE_OP → SAFE_OP → OP chain automatically
Async transitionmaster.set_state_async(EcState)JoinHandle<Result<()>>Runs the same state chain on a background thread
Start the cyclemaster.start()()Starts the PDO cycle after entering OP; a failure is logged at ERROR level and can be retried
Stop the cyclemaster.stop()()Stops the PDO cycle
Release manuallymaster.dispose()()Stops the cycle and releases the instance; normally left to Drop
use darra_ethercat::{EcState, EtherCATMaster};

fn main() -> darra_ethercat::Result<()> {
let mut master = EtherCATMaster::new()?;

// the NIC name comes from the NIC list in the Darra configuration tool (of the form \Device\NPF_{GUID}).
let found = master.set_network_with_count(r"\Device\NPF_{GUID}", "")?;
println!("扫描到 {found} 个从站"); // Scan found {found} slaves

// runs the full INIT → PRE_OP → SAFE_OP → OP chain.
master.set_state(EcState::Operational)?;
master.start();

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

master.stop();
Ok(()) // Drop performs the remaining cleanup automatically
}
Empty bus and binding failures

set_network / set_network_with_count return Err(DarraError::NetworkFailedWithLastError) when binding fails or there are no slaves on the bus. If you only want to tell whether the bus is empty, use EtherCATMaster::scan_slaves() first: an empty list means the scan completed and there really are no slaves, Err means the scan failed.

Entry pointReturnsDescription
master.state()EcStateCurrent master state; EcState::None when it cannot be read
master.link_state() / master.link_status()LinkStateConnected / Disconnected / PrimaryOnly / SecondaryOnly / Unknown
master.slave_count()u16Number of slaves
master.slave(n)Slave<'_>Handle to slave n (1-based)
master.slaves()Vec<Slave<'_>>Handles to all slaves
master.has_dc()Option<bool>None = cannot be read, which is not the same as having no DC
master.loop_cycle() / master.set_loop_cycle(ns)u32 / ()PDO cycle (nanoseconds)
master.master_dc_time()u64DC master clock time (nanoseconds)
master.diagnostics_info().dc_diagnostics()DcDiagnosticsSnapshotDC snapshot with a 2-second TTL
master.diagnostics_info().dc_armed_slave_count() / dc_active_slave_count()i32Number of slaves with SYNC0 armed / DC-active
use darra_ethercat::LinkState;

match master.link_state() {
LinkState::Connected => println!("链路正常"), // Link OK
LinkState::Disconnected => println!("两个已配置端口都断开"), // Both configured ports are down
LinkState::PrimaryOnly => println!("仅主口有链路"), // Only the primary port has a link
LinkState::SecondaryOnly => println!("仅副口有链路"), // Only the secondary port has a link
LinkState::Unknown => println!("链路状态未知 (不是断开)"), // Link state unknown (not disconnected)
}

println!("状态: {:?}, 从站: {}", master.state(), master.slave_count()); // State: {:?}, slaves: {}
for slave in master.slaves() {
println!(
"#{} {} vendor=0x{:08X} product=0x{:08X} state={:?}",
slave.index(), slave.name(), slave.vendor_id(), slave.product_id(), slave.state_live()
);
}

LinkState::Unknown only means the physical link cannot be read; it does not mean disconnected. The UI should show it as "unknown".

NIC enumeration and scanning​

Entry pointReturnsDescription
enumerate_network_info(is_redundant, need_slaves_num)Result<Vec<EnumeratedNetworkInfo>>Enumerate NICs; with need_slaves_num = true it also probes the slave count (about 0.5–1.5 s)
EtherCATMaster::abort_scan()()Aborts a scan that is blocking

EnumeratedNetworkInfo::scan_status distinguishes "not measured" from "measured zero slaves": Found = has slaves, IdleNoSlave = the scan completed and the bus really is empty, NotMeasured = not measured this time, OccupiedByMaster = skipped because a master on this machine already uses it.

use darra_ethercat::{enumerate_network_info, NicScanStatus};

match enumerate_network_info(false, true) {
Ok(nics) => {
for nic in nics {
match nic.scan_status {
NicScanStatus::Found => println!("{}: {} 台从站", nic.description, nic.slave_num), // {}: {} slave(s)
NicScanStatus::IdleNoSlave => println!("{}: 总线上没有从站", nic.description), // {}: no slaves on the bus
NicScanStatus::NotMeasured => println!("{}: 本次未测量", nic.description), // {}: not measured this time
NicScanStatus::OccupiedByMaster => println!("{}: 已被主站占用, 跳过", nic.description), // {}: already in use by a master, skipped
}
}
}
Err(err) => eprintln!("枚举网卡失败: {}", err), // Failed to enumerate NICs: {}
}

Process data (PDO)​

After entering OP the SDK runs the bus cycle. slave.pdo() returns a SlavePdo that borrows the master; read and write with whole-frame snapshots, decoding multi-byte values in EtherCAT wire order (little-endian):

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

// Input (TxPDO): take a whole-frame snapshot and decode it.
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): 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)?;
}

try_write_outputs() writes the whole frame; a length mismatch returns DarraError::PdoFailed and nothing is partially written. To change only a few bytes, use the element view pdo.out_items().get(offset)?.set_*(), or slave::pdo::batch_write(...) to commit several blocks in one transaction; a failure there must likewise not be treated as "0 bytes written".

Mailbox CoE (SDO)​

Read and write object dictionary entries by index / subindex. The typed interfaces return Err on failure 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}");

When you need raw bytes, use slave.sdo_read(index, subindex, complete_access) / slave.sdo_write(...), which return Result<Vec<u8>> / Result<()>. The error code of a deterministic abort is preserved as-is in DarraError::SdoReadFailed / SdoWriteFailed.

Diagnostics​

master.diagnostics_info() returns a read-only diagnostic snapshot, suitable for UI refresh and logging:

Entry pointReturnsDescription
diagnostics_info().wkc() / expected_wkc() / wc_deficit()u16Current WKC / expected WKC fixed at configuration time / deficit
diagnostics_info().packet_loss_rate() / late_frame_rate()f32Packet loss rate / late frame rate
diagnostics_info().avg_cycle_time_us() / avg_jitter_us()f64Average cycle time and jitter
diagnostics_info().mailbox_latency_us() / mailbox_latency_avg_us()f64Mailbox latency
diagnostics_info().worst_slave_index() / worst_link_quality()u16 / i16Slave with the highest error rate / worst link quality
diagnostics_info().redundancy_active()boolWhether redundancy carries current traffic
diagnostics_info().dc_all_in_sync()Option<bool>None = no confirmed participants, not true
master.diagnostics_info().dc_diagnostics().max_drift_nsOption<i32>Maximum synchronization difference; None = no usable window, not 0
master.realtime_stats()Option<RealtimeStats>Current cycle / jitter / frame loss / bus utilization
let diag = master.diagnostics_info();
println!(
"WKC {}/{} 缺额 {} 丢包 {:.4} 周期 {:.1}us 抖动 {:.2}us", // WKC {}/{} deficit {} packet loss {:.4} cycle {:.1}us jitter {:.2}us
diag.wkc(),
diag.expected_wkc(),
diag.wc_deficit(),
diag.packet_loss_rate(),
diag.avg_cycle_time_us(),
diag.avg_jitter_us(),
);

Version compatibility​

The current SDK version is 2.13.16. PATCH upgrades do not require updating the matching driver; MINOR / MAJOR upgrades do.