Skip to main content

Rust-specific syntax sugar

This chapter lists the Rust-specific syntax sugar that the Darra EtherCAT Rust SDK provides in the crate::sugar module. These APIs are entirely optional: they introduce no breaking change and do not affect backward compatibility. Just add one line at the top of the file:

use darra_ethercat::sugar::prelude::*;

and every convenience form becomes available.

Iterators (SlaveIterExt)​

Standard API​

The main SDK already implements IntoIterator for [EtherCATMaster], so for s in &master works directly:

let m = EtherCATMaster::new()?;
for slave in &m {
println!("{}", slave.name());
}

The slaves() method also collects all slaves into a Vec<Slave>:

let all: Vec<Slave> = m.slaves();

Sugar: chained filtering​

With use darra_ethercat::sugar::prelude::*; in scope, any Iterator<Item = Slave> automatically gains eight domain-aware methods:

  • .by_state(EcState::Operational) — filter by EtherCAT state (a slave whose state cannot be read does not match)
  • .by_group(0) — filter by slave group (0..=7)
  • .by_vendor(0x00000002) — filter by vendor ID
  • .by_product(0x044C2C52) — filter by product code
  • .with_dc() — keep only slaves confirmed DC capable (has_dc() == Some(true); a capability that cannot be read does not count)
  • .online_only() — keep only slaves not judged lost
  • .with_protocol(mask) — keep only slaves whose mailbox protocol bit mask intersects mask
  • .filter_slave(|s| ...) — any custom predicate, with a clearer signature than Iterator::filter
use darra_ethercat::sugar::prelude::*;
use darra_ethercat::EcState;

// Beckhoff slaves in OP
let beckhoff_op: Vec<_> = m.iter()
.by_state(EcState::Operational)
.by_vendor(0x00000002)
.collect();

// Slaves with AL errors in group 0
let bad: Vec<_> = m.iter()
.by_group(0)
.filter_slave(|s| {
s.detailed_info()
.map(|d| d.al_status_code != 0)
.unwrap_or(false) // Not being able to read the details is a read failure; do not misjudge it as "has an error", treat it as no filtering
})
.collect();

When to use it​

  • More than 1 filtering step → use the sugar; it fits on one line
  • A single filter → plain Iterator::filter is fine too; use whichever you prefer
  • Inside a microsecond-level PDO callback → do not use iterators; write for i in 1..=count plus master.slave(i) to avoid any intermediate trait desugaring overhead

Indexing (Indexable)​

Standard API​

The main SDK gets a slave handle with slave(i):

let s1 = m.slave(1);
let s2 = m.slave(2);

Sugar: master.indexable()[i]​

Because Slave is a Copy handle (it owns no resources; it is just a (master_idx, slave_idx) pair), the SDK can offer Index-style access for it:

use darra_ethercat::sugar::prelude::*;

let view = m.indexable();
let s1 = &view[1]; // Equivalent to m.slave(1)
let s2 = &view[2u16]; // Supports both usize and u16 indices
println!("{}", view.len());

// Out of range panics; use try_slave below for safe access

Implementation notes​

Indexable<'a> caches the slave handles for 1..=N internally and shares its lifetime with the original &'a EtherCATMaster. It is not cached on the main EtherCATMaster, so that the existing calling pattern of immutable &self methods keeps working (otherwise they would all have to become &mut self).

When to use it​

  • Demos, teaching, REPL → view[i] is short and obvious
  • Production code → prefer try_slave(i)? (see §4); an out-of-range index becomes an error instead of a panic
  • Tight PDO loops → a direct m.slave(i) call is still the fastest

RAII (Drop / IomapGuard)​

Already implemented​

The main SDK provides RAII on its own; the sugar module is not needed for it. Listed here for reference:

{
let m = EtherCATMaster::new()?;
m.set_network("\\Device\\NPF_{...}", "")?;
// ... use ...
} // <- Drop here does Stop + Dispose automatically, no manual call needed

IomapGuard is also an RAII wrapper:

{
if let Some(_guard) = m.iomap_guard() { // None = the lock was not acquired this time
// ... safe IO read/write ...
} // <- unlocks automatically when the guard is dropped
}

Cautions​

  • Do not call mem::forget(master) — it leaks runtime resources
  • The BuildResult returned by MasterBuilder::build() implements Deref<Target = EtherCATMaster>, so it gets RAII as well

What the sugar module does not touch​

Drop is guaranteed by the main types; the sugar module does not reimplement it. The same applies to IomapGuard.

Error propagation (?-friendly)​

Standard API​

let s = m.slave(1);   // Never fails (out of range returns a dangling handle)
let count = m.slave_count();
if 1 > count {
return Err(/* Assemble the error yourself*/);
}

Sugar: try_slave / slave_opt​

use darra_ethercat::sugar::prelude::*;
use darra_ethercat::Result;

fn use_first(m: &EtherCATMaster) -> Result<()> {
let s = m.try_slave(1)?; // Returns Err on out of range
println!("vendor: 0x{:08X}", s.vendor_id());
Ok(())
}

// Or take the Option path
if let Some(s) = m.slave_opt(1) {
println!("{}", s);
}

A Result wrapper for state transitions​

The main set_state API requires &mut self, which makes a direct ? awkward in shared contexts:

// Standard API (needs &mut)
master.set_state(EcState::Operational)?;

The sugar version calls the SDK through &self and works with ?:

use darra_ethercat::sugar::prelude::*;

fn ramp_up(m: &EtherCATMaster) -> Result<()> {
m.try_set_state(EcState::PreOp, 5000)?;
m.try_set_state(EcState::SafeOp, 5000)?;
m.try_set_state(EcState::Operational, 5000)?;
Ok(())
}

Cautions​

try_set_state follows the same state transition sequence as the main API: intermediate transitions and the automatic Start are handled by the underlying layer.

There is only one difference on the Rust side: try_set_state borrows &self and does not write back the started flag of the master object. So a later call to master.stop() still considers the master "not started" and does not really run the stop sequence. For scenarios that need stop() or lifecycle cleanup after reaching OP, use the main API instead:

master.set_state(EcState::Operational)?;   // Automatically calls Start()

State change channel (mpsc::channel)​

Standard API: callbacks​

use std::sync::Arc;

let m = EtherCATMaster::new()?;
let events = m.events();
events.on_slave_state_changed(Arc::new(|master, slave, old, new| {
println!("slave {}: {} -> {}", slave, old, new);
}));

Limitations of the callback approach:

  • Multi-threaded consumption needs your own Arc<Mutex<...>>
  • Replaying event history or asserting in tests needs your own buffer
  • Crossing await boundaries (async code) is awkward

Sugar: state_stream() returns a Receiver​

use darra_ethercat::sugar::prelude::*;

let m = EtherCATMaster::new()?;
let rx = m.state_stream(); // mpsc::Receiver, capacity 1024

std::thread::spawn(move || {
for ev in rx {
println!("从站 {}: {} -> {}", ev.slave, ev.old_state, ev.new_state); // Slave {}: {} -> {}
}
});

Design notes​

  • The underlying subscription uses the asynchronous delivery channel on_slave_state_changed_async (not the synchronous on_slave_state_changed); the two channels do not compete with each other
  • Default capacity is 1024; for a custom size use state_stream_with_capacity(cap) (cap == 0 returns Err instead of silently degrading to a rendezvous channel)
  • When full, the newest event is dropped (try_send), so the real-time thread is never blocked
  • MasterStateStream implements IntoIterator, so for ev in rx works directly
  • Blocking rx.recv() and non-blocking rx.try_recv() are both available
  • Each call to state_stream() returns an independent channel, and each receives its own copy of the events
Deregistering a stream (pending)

After a MasterStateStream / EmergencyStream is dropped, the event callback registered underneath is not removed from the event table automatically (there is no deregistration entry point at present), and later events are dropped silently. To clear everything, use MasterEvents::clear_all() (it clears all event subscriptions of that master). A per-stream deregistration API is pending; do not assume that Drop unsubscribes.

The same for emergency events (EMCY)​

let emcy = m.emergency_stream();
for ev in emcy {
println!("EMCY {}: code=0x{:04X} reg=0x{:02X}",
ev.slave, ev.error_code, ev.error_register);
}

EMCY streams are unbounded by default — events of this kind are low in volume, so they do not put pressure on the real-time thread.

Async streams (tokio, async-tokio feature only)​

Enabling it​

Cargo.toml:

[dependencies]
darra-ethercat-master = { path = "../darra-ethercat-master-2.13.16", features = ["async-tokio"] }
tokio = { version = "1", features = ["rt-multi-thread", "macros", "sync"] }

Note that tokio must have the sync feature enabled (async-tokio uses tokio::sync::mpsc internally; the crate already declares sync on its tokio dependency, so no extra feature has to be configured on the crate side).

Usage​

use darra_ethercat::sugar::prelude::*;
use darra_ethercat::EtherCATMaster;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let m = EtherCATMaster::new()?;
let mut stream = m.state_stream_async();

while let Some(ev) = stream.recv().await {
println!("从站 {}: {} -> {}", ev.slave, ev.old_state, ev.new_state); // Slave {}: {} -> {}
}
Ok(())
}

Relation to the synchronous version​

  • state_stream() (synchronous) and state_stream_async() (asynchronous) do not affect each other and can be used at the same time
  • The asynchronous version is built on tokio::sync::mpsc::unbounded_channel; it never drops events when full (but it does use memory)
  • To adapt it to the futures::Stream trait, call into_inner() to get the UnboundedReceiver, then tokio_stream::wrappers::UnboundedReceiverStream::new(rx)

When to use it​

  • The whole program already runs on a tokio runtime → use the asynchronous version and do not start a new thread
  • Only event consumption needs to be async → a synchronous state_stream() plus tokio spawn_blocking will do, though it is not elegant
  • You do not use tokio → use the synchronous version only and leave the async-tokio feature off, to keep dependencies down

derive / type conversion​

Existing derives​

The main SDK derives Clone, Debug, Copy, PartialEq, Eq, Default on almost every data structure. For example, SlaveIdentity / EsmTimeouts / RedundancyStatus / CommunicationStats are all #[derive(Debug, Clone, Copy)].

From conversions added by the sugar module​

  • &Slave → SlaveIdentity — let id: SlaveIdentity = (&slave).into(); extracts the identity in one line
  • Slave → SlaveIdentity — same as above, owned version
  • u8 → EcState — get the enum straight from a raw byte
  • EcState → u8 / i32 — write back through SDK interfaces
  • u8 → LinkState — get the enum straight from a raw byte
  • i32 → RedundancyState — get the enum straight from a runtime return value
  • i32 → CiA402State — same as above
  • EcState / LinkState / RedundancyState → &'static str — logging and formatting
use darra_ethercat::sugar::prelude::*;

let s = m.slave(1);

// Extract the identity in one line, for configuration comparison
let id: SlaveIdentity = (&s).into();
println!("{}", id); // Vendor=0x00000002 Product=0x044C2C52 Rev=...

// raw -> enum (for example to parse PDO frame bytes)
let st: EcState = 0x08u8.into();
assert_eq!(st, EcState::Operational);

// enum -> static string (no heap allocation)
let label: &'static str = EcState::PreOp.into();
assert_eq!(label, "PreOp");

When to use it​

  • Log messages and metrics labels → the &'static str conversion is zero-cost, better than format!
  • Conversions at call boundaries → EcState::from(raw_byte) is shorter than EcState::from_raw(raw_byte).unwrap_or(...)

Display support​

Display implementations added by the sugar module​

The main SDK already implements Display for EcState / DarraError / EcPortType and others. The sugar module adds:

  • LinkState — Connected / Redundancy
  • RedundancyState — PrimaryOnly / Both
  • CiA402State — OperationEnabled / Fault
  • CiA402Mode — CSP / PP
  • EcALState — NoError / InvalidStateChange / AL(0x00XX) as a fallback
  • SlaveIdentity — Vendor=0x... Product=0x... Rev=0x... Serial=0x...

Usage​

use darra_ethercat::sugar::prelude::*;

use darra_ethercat::data::error::CiA402State;
use darra_ethercat::data::types::EcALState;

println!("链路: {}", m.link_status()); // Link: Connected
println!("驱动: {}", CiA402State::OperationEnabled); // Drive: OperationEnabled
println!("ALSC: {}", EcALState::SyncError); // ALSC: SyncError

Difference from Debug​

  • Debug ({:?}) — output style: complete fields, suited to troubleshooting; used in unit test assertions and when printing a whole structure
  • Display ({}) — output style: short and readable, suited to end users; used in logs, the GUI and alarm messages

Builder pattern​

Existing builder​

The main SDK already ships MasterBuilder; the sugar module does not build another one:

let result = EtherCATMaster::builder()
.set_eni("config.deni")
.enable_auto_startup()
.build()?;

println!("从站数量: {}", result.slave_count()); // Slave count: {}

BuildResult implements Deref<Target = EtherCATMaster>, so read-only methods can be used as they are; but it does not implement DerefMut — methods that need &mut self (set_state / start / stop / dispose) must first take the owned EtherCATMaster out through .master and bind it with let mut. See the full example below.

What the sugar module does not touch​

We consider the existing builder to cover most scenarios, so there is no need to build a sugar version. If the builder chain has to grow (for example with_redundancy(...) / with_callback(...)), add the methods to the main master module rather than to sugar.

Full example​

use darra_ethercat::sugar::prelude::*;
use darra_ethercat::{EtherCATMaster, EcState, Result};

fn main() -> Result<()> {
let mut m = EtherCATMaster::builder()
.set_eni("config.deni")
.enable_auto_startup()
.build()?
.master;

// Start the state stream (consumed by a background thread)
let rx = m.state_stream();
std::thread::spawn(move || {
for ev in rx {
log::info!("[state] slave {} {} -> {}", ev.slave, ev.old_state, ev.new_state);
}
});

// Enter OP
m.set_state(EcState::Operational)?;

// Index + error propagation
let s = m.try_slave(1)?;
println!("{}", s);

// Chained filtering: list all Beckhoff slaves in OP
let beckhoff_op: Vec<_> = m.iter()
.by_state(EcState::Operational)
.by_vendor(0x00000002)
.collect();
println!("Beckhoff OP 从站数: {}", beckhoff_op.len()); // Beckhoff OP slave count: {}

// RAII does Stop + Dispose automatically
Ok(())
}

Appendix: module index​

ModuleResponsibility
sugarModule entry point; re-exports all submodules
sugar::preludeA single use line brings in all the sugar
sugar::indexIndexable + MasterIndexExt
sugar::conversionsCross-type From / Into
sugar::displayDisplay implementations for LinkState / RedundancyState / CiA402State and others
sugar::state_streammpsc state stream and emergency stream
sugar::iter_extSlaveIterExt (by_state / by_group / by_vendor / by_product / with_dc / online_only / with_protocol / filter_slave)
sugar::try_slavetry_slave / slave_opt / try_set_state
sugar::async_streamtokio async stream (async-tokio feature)

Appendix: difference from hand-written loops​

The sugar module in this chapter is built on Iterator + adapters, Drop and mpsc::channel.

Rust's syntax sugar rests on zero-cost abstractions — every adapter above is inlined at compile time, so the runtime cost equals that of a hand-written loop and no extra instructions are introduced.