Skip to main content

CoE (CANopen over EtherCAT)

Quick start​

The CoE object dictionary is loaded with OdList::load(); single values are read and written with the typed Slave::sdo_read_value::<T>() / sdo_write_value::<T>().

use darra_ethercat::OdList;

let slave = master.slave(1);

// Typed SDO read/write — failure returns Err, match it before parsing
let status: u16 = match slave.sdo_read_value(0x6041, 0x00) {
Ok(v) => v,
Err(e) => {
eprintln!("SDO 失败: {e:?}"); // SDO failure: {e:?}
return Ok(());
}
};
let position: i32 = match slave.sdo_read_value(0x6064, 0x00) {
Ok(v) => v,
Err(_) => return Ok(()),
};
slave.sdo_write_value(0x6040, 0x00, &0x0006u16)?;

// Load the complete OD tree (real mailbox traffic, no ESI cache read)
// An empty dictionary is not success. In OP use OdList::load_basic (main index list only); do not call a full load() in OP
let od = match OdList::load(master.index(), 1) {
Ok(list) if !list.objects.is_empty() => list,
Ok(_) => {
eprintln!("空字典不是成功"); // An empty dictionary is not success
return Ok(());
}
Err(e) => {
eprintln!("OD 加载失败: {e:?}"); // Failed to load OD: {e:?}
return Ok(());
}
};
for obj in &od.objects {
println!("0x{:04X}: {} ({} 条目)", obj.index, obj.name, obj.entries.len()); // 0x{:04X}: {} ({} entries)
}
Failure returns Err — do not parse it directly

Do not call from_le_bytes on a failed result or parse it as a u32.

The two API sets do not share abort codes: Slave::sdo_read* / Slave::sdo_write* do not update CoEInstance::last_sdo_error() (they are independent objects). When you need the abort code, use CoEInstance::sdo_read() / sdo_read_ex() on the same instance instead.

last_sdo_error() == SDOError::SDOProtocolTimeout means the mailbox did not come back (WKC=0 / timeout), not "the object does not exist". Only a real abort (ObjectDoesNotExist 0x06020000 / SubindexDoesNotExist 0x06090011 / 0x06090012) enters the NotPresent negative cache. Call reset_not_present_cache() after hot-plug or a firmware update.

reset_od_cache() clears only the OD cache and does not clear the NotPresent negative cache; the two must be called separately.

SDO direct read and write​

sdo_read_value::<T>()​

Reads an SDO value directly through the Slave handle; generic over the type (Complete Access is not supported).

pub fn sdo_read_value<T: Copy>(&self, index: u16, subindex: u8) -> Result<T>
// Read directly from the Slave (recommended)
// sdo_read_value::<T> is bounded by T: Copy, so it only works for fixed-size scalar types (integer/float)
let value: u16 = slave.sdo_read_value(0x6041, 0x00)?;

// A string (VisibleString) is not a Copy type — use sdo_read to get the raw bytes, then decode
let raw: Vec<u8> = slave.sdo_read(0x1008, 0x00, false)?;
let name: String = String::from_utf8_lossy(&raw).trim_end_matches('\0').to_string();

When the response length is smaller than size_of::<T>() (including a 0-byte response) it returns Err(DarraError::SdoReadFailed). Multi-byte values are decoded in ETG little-endian wire order, independent of host byte order.

sdo_write_value::<T>()​

pub fn sdo_write_value<T: Copy>(&self, index: u16, subindex: u8, value: &T) -> Result<()>
// Write directly from the Slave
slave.sdo_write_value(0x6040, 0x00, &0x0006u16)?;
slave.sdo_write_value(0x607A, 0x00, &100000i32)?;

sdo_read() / sdo_write()​

Both Slave and CoEInstance have these two methods with identical signatures; they return raw bytes.

pub fn sdo_read(&self, index: u16, subindex: u8, complete_access: bool) -> Result<Vec<u8>>
pub fn sdo_write(&self, index: u16, subindex: u8, complete_access: bool, data: &[u8]) -> Result<()>

Parameters:

  • index — object index (for example 0x6040)
  • subindex — subindex; when complete_access = true it may only be 0 or 1 (larger values fail immediately at the lower layer and no request is sent)
  • complete_access — true = Complete Access, reading or writing the whole object (all subindexes) in one transaction
  • data — bytes to write (&[u8])
Parameter order differs from C#

Rust puts complete_access before data: sdo_write(index, subindex, complete_access, data).

C# has SDOWrite(index, subindex, data, completeAccess = false) (data comes first). Do not copy the parameter order when porting from C#.

Failure semantics:

  • Read succeeded with a data length of 0 (such as an empty VISIBLE_STRING) → Ok(vec![]), not a failure
  • Read failed → Err(DarraError::SdoReadFailed { index, subindex, abort_code, raw_abort_code })
  • Write failed → Err(DarraError::SdoWriteFailed { index, subindex, abort_code, raw_abort_code }); raw_abort_code is filled in directly by the lower-layer SDO write interface, while abort_code is the normalized enum view
  • raw_abort_code is the 32-bit abort code returned verbatim by the device; it is 0 on transport-level failure (no device reply), in which case abort_code is Some(SDOProtocolTimeout) (0x05040000 is the normalized code — it appears there only and is never written into raw_abort_code)
  • Abort codes outside the table / vendor-private abort codes are placed into raw_abort_code as-is and are not normalized into UnknownError with the real value lost
A failed write sends exactly one transaction

When a write fails, the device's rejection code is surfaced as-is and is not normalized into a generic error; the write path sends only one transaction and does not issue an extra read probe.

Example:

// Raw byte read/write (third parameter: complete_access)
let data: Vec<u8> = match slave.sdo_read(0x1000, 0x00, false) {
Ok(bytes) => bytes,
Err(e) => {
eprintln!("SDO 失败: {e:?}"); // SDO failure: {e:?}
return Ok(());
}
};
// Take the first 4 bytes as DeviceType; short data does not panic, it follows the read-failure path
let Some(dev_type_bytes) = data.get(..4).and_then(|s| <[u8; 4]>::try_from(s).ok()) else {
eprintln!("SDO 数据长度不足 4 字节: {} 字节", data.len()); // SDO data shorter than 4 bytes: {} bytes
return Ok(());
};
let device_type = u32::from_le_bytes(dev_type_bytes);
slave.sdo_write(0x6040, 0x00, false, &0x0006u16.to_le_bytes())?;

Single-read limit is 64 KB: when the response data of an SDO read or OD enumeration exceeds 64 KB it is returned as a read failure Err; split oversized objects into multiple reads.

Complete Access result splitting​

A read with complete_access = true returns the whole object as a contiguous byte stream; split it by entry layout with parse_complete_access_data:

pub fn parse_complete_access_data(data: &[u8], entries: &[CaObjectEntry]) -> Vec<(u8, Vec<u8>)>

pub struct CaObjectEntry {
pub sub_index: u8,
pub data_type: u16,
pub bit_length: u16,
}
use darra_ethercat::slave::{CoEInstance, CaObjectEntry, parse_complete_access_data};

let coe = CoEInstance::new(master.index(), 1);

// data_type / bit_length come straight from the same-named ObjectEntry fields
let entries = vec![
CaObjectEntry { sub_index: 0, data_type: 0x0005, bit_length: 8 },
CaObjectEntry { sub_index: 1, data_type: 0x0006, bit_length: 16 },
CaObjectEntry { sub_index: 2, data_type: 0x0006, bit_length: 16 },
];
let raw = coe.sdo_read(0x1C12, 0x00, true)?;
for (sub, bytes) in parse_complete_access_data(&raw, &entries) {
println!("[{:02X}] {:02X?}", sub, bytes);
}
  • The first 2 bytes are always treated as subindex 0; entries[0] is skipped and only entries[1..] is iterated
  • Bit types (data_type in 0x0030..=0x0037) are taken at their bit width, not padded to whole bytes
  • Entries with insufficient data are simply not returned and raise no error

split_complete_access()​

The free function above needs the caller to supply the entry layout; CoEInstance::split_complete_access() instead splits by the real layout of that object in the ESI already loaded for this slave, so the caller does not have to work out bit widths and alignment (the ETG.1020 §14.2 bit-packing rules are applied for you). Make sure the slave's ESI is loaded first (for example through bind_esi_file()); otherwise there is no layout and the call returns Err.

pub fn split_complete_access(&self, index: u16, start_subindex: u8, blob: &[u8])
-> Result<Vec<(u8, Vec<u8>)>>

Parameters:

  • index — object index (such as 0x1C12)
  • start_subindex — 0 = the blob starts with subindex 0 (2 bytes); 1 = the blob starts at subindex 1
  • blob — the contiguous byte stream read back by Complete Access (you can also use it to check the segmentation before writing)

Returns:

  • Ok(Vec<(u8, Vec<u8>)>) — each item is (the actual subindex number, the whole-byte data of that subindex)
  • Ok(vec![]) — blob is empty, or the layout holds no entry to hand back
  • Err(DarraError::Other) — the ESI has no layout for that object / the blob length does not match the layout / the split result runs past the bounds
let coe = CoEInstance::new(master.index(), 1);
let raw = coe.sdo_read(0x1C12, 0x00, true)?;
for (sub, bytes) in coe.split_complete_access(0x1C12, 0, &raw)? {
println!("[{:02X}] {:02X?}", sub, bytes);
}

The difference from parse_complete_access_data() is where the layout comes from: the entry layout is taken from the ESI, so moving the same index to another slave does not mean writing the type table out by hand again.

Batch reads​

read_multiple()​

pub fn read_multiple(&self, entries: &[(u16, u8)]) -> HashMap<(u16, u8), Option<Vec<u8>>>

Batch SDO reads. Entries are read one after another, serially, in entries order (plain reads only, Complete Access is not supported); successful entries return Some(Vec<u8>), failed entries return None and do not interrupt the remaining reads.

This method does not return a Result; to get the first error message, loop over sdo_read() yourself.

Parameters:

  • entries (&[(u16, u8)]) -- list of (index, subindex) pairs to read

Returns:

  • HashMap<(u16, u8), Option<Vec<u8>>> -- read result for each entry

Example:

use darra_ethercat::slave::CoEInstance;

let coe = CoEInstance::new(master.index(), 1);
let entries = [(0x1000, 0x00), (0x1008, 0x00), (0x1018, 0x01)];
let results = coe.read_multiple(&entries);
for ((idx, sub), data) in &results {
match data {
Some(bytes) => println!("0x{:04X}:{:02X} = {} 字节", idx, sub, bytes.len()), // 0x{:04X}:{:02X} = {} bytes
None => println!("0x{:04X}:{:02X} 读取失败", idx, sub), // 0x{:04X}:{:02X} read failed
}
}

SDO extended interface (abort code + WKC)​

A failed sdo_read / sdo_write only returns Err; the abort code has to be fetched separately with last_sdo_error(). The extended variants sdo_read_ex / sdo_write_ex do not return a Result — the result struct carries abort_code + wkc directly, so a specific abort code such as "object does not exist (0x06020000)", "data type mismatch (0x06070010)" or "value out of range (0x06090030)" can be distinguished in one step.

sdo_read_ex / sdo_write_ex both refresh CoEInstance::last_sdo_error().

sdo_read_ex()​

pub fn sdo_read_ex(&self, index: u16, subindex: u8, complete_access: bool) -> SdoReadResultEx

Extended SDO read. Returns SdoReadResultEx (containing data / abort_code / wkc).

Single-read limit is 64 KB: when the response data exceeds 64 KB it is returned as a read failure (data=None); split oversized objects into multiple reads.

Related structures:

pub struct SdoReadResultEx {
pub data: Option<Vec<u8>>, // Data read (None on failure)
pub abort_code: u32, // SDO abort code (0 = no abort)
pub wkc: i32, // Working Counter
}

impl SdoReadResultEx {
pub fn is_ok(&self) -> bool; // data.is_some()
}

A NotPresent negative-cache hit short-circuits the call: data = None, wkc = 0, abort_code = the cached abort code (no SDO is actually sent).

Example:

use darra_ethercat::slave::CoEInstance;

let coe = CoEInstance::new(master.index(), 1);
let r = coe.sdo_read_ex(0x6041, 0x00, false);
match r.data.as_deref() {
Some([lo, hi, ..]) => {
let status = u16::from_le_bytes([*lo, *hi]);
println!("状态字: 0x{:04X}", status); // Status word: 0x{:04X}
}
_ => println!("读失败 abort=0x{:08X} wkc={}", r.abort_code, r.wkc), // Read failed abort=0x{:08X} wkc={}
}

sdo_write_ex()​

pub fn sdo_write_ex(&self, index: u16, subindex: u8, complete_access: bool, data: &[u8]) -> SdoWriteResultEx

Extended SDO write. Returns SdoWriteResultEx (containing ok / abort_code / wkc).

Related structures:

pub struct SdoWriteResultEx {
pub ok: bool, // Whether the write succeeded
pub abort_code: u32, // SDO abort code (0 = no abort)
pub wkc: i32, // Working Counter
}

Example:

use darra_ethercat::slave::CoEInstance;

let coe = CoEInstance::new(master.index(), 1);
let r = coe.sdo_write_ex(0x6040, 0x00, false, &0x000Fu16.to_le_bytes());
if !r.ok {
println!("写失败 abort=0x{:08X}", r.abort_code); // Write failed abort=0x{:08X}
}

Async and background-thread SDO​

The async versions do not block the current async task; their failure semantics match the synchronous versions.

The async-tokio feature gates the async methods:

[dependencies]
darra_ethercat = { version = "...", features = ["async-tokio"] }

CoEInstance::sdo_read_async / sdo_write_async​

pub async fn sdo_read_async(
&self,
index: u16,
subindex: u8,
complete_access: bool,
) -> Result<Vec<u8>>

pub async fn sdo_write_async(
&self,
index: u16,
subindex: u8,
complete_access: bool,
data: Vec<u8>,
) -> Result<()>
  • data is an owned Vec<u8> (the synchronous version takes &[u8])
  • No cancellation parameter is provided
  • Internally a new CoEInstance performs the SDO, so the caller instance's last_sdo_error() is not updated
  • Failure → Err(DarraError::SdoReadFailed / SdoWriteFailed); background task panic → Err(DarraError::Other("tokio join error: ..."))

Slave::sdo_read_isolated / sdo_write_isolated​

pub async fn sdo_read_isolated(
&self,
index: u16,
subindex: u8,
complete_access: bool,
cancel: Option<CancelToken>,
) -> Result<Vec<u8>>

pub async fn sdo_write_isolated(
&self,
index: u16,
subindex: u8,
complete_access: bool,
data: Vec<u8>,
cancel: Option<CancelToken>,
) -> Result<()>

They share a single serialization gate with build_async / set_state_async_isolated on the same master, so the mailbox is never hit concurrently. When cancel is Some(token):

  • Cancelled while queued or before entering the call → Err(DarraError::Cancelled(...))
  • Cancelled only after entering the lower layer → the running SDO is interrupted and returned as the post-interruption SDO error (usually Err(DarraError::SdoReadFailed))

The interruption state is cleaned up automatically by the isolation layer; no manual reset is needed.

Example​

use darra_ethercat::slave::CoEInstance;
use darra_ethercat::CancelToken;

let coe = CoEInstance::new(master.index(), 1);

// No cancellation
let status: Vec<u8> = coe.sdo_read_async(0x6041, 0x00, false).await?;
coe.sdo_write_async(0x6040, 0x00, false, 0x0006u16.to_le_bytes().to_vec()).await?;

// With cancellation, serialized with other async operations on the same master
let token = CancelToken::new();
let data = master
.slave(1)
.sdo_read_isolated(0x6041, 0x00, false, Some(token.clone()))
.await?;
master
.slave(1)
.sdo_write_isolated(0x6040, 0x00, false, vec![0x06, 0x00], Some(token))
.await?;

Synchronous thread version​

These two associated functions are not feature-gated; they also work without async-tokio:

pub fn sdo_read_blocking(
master_index: u16,
slave_index: u16,
index: u16,
subindex: u8,
complete_access: bool,
) -> std::thread::JoinHandle<Result<Vec<u8>>>

pub fn sdo_write_blocking(
master_index: u16,
slave_index: u16,
index: u16,
subindex: u8,
complete_access: bool,
data: Vec<u8>,
) -> std::thread::JoinHandle<Result<()>>
use darra_ethercat::slave::CoEInstance;

let handle = CoEInstance::sdo_read_blocking(master.index(), 1, 0x6041, 0x00, false);
// An Err from join means the background thread panicked; surfaced as an error, never swallowed silently
let status: Vec<u8> = match handle.join() {
Ok(r) => r?,
Err(p) => return Err(darra_ethercat::DarraError::Other(format!("SDO 线程异常退出: {p}"))), // SDO thread exited abnormally: {p}
};

sdo_read_task() / sdo_write_task()​

pub fn sdo_read_task(&self, index: u16, subindex: u8, complete_access: bool)
-> SdoTask<Vec<u8>>

pub fn sdo_write_task(&self, index: u16, subindex: u8, complete_access: bool, data: Vec<u8>)
-> SdoTask<()>

Asynchronous SDO that is not gated by the async-tokio feature, returning a cancellable one-shot task SdoTask<T>.

Completion semantics: SdoTask::join() consumes self; a task yields its completion exactly once (exactly-once completion is guaranteed by the type system). The task body issues exactly one lower-layer SDO call for the request (the SDK layer does not silently retry on timeout).

Cancellation semantics stated honestly: the lower-layer SDO call itself cannot be interrupted, so cancellation only takes effect before the request is sent. A request that was already sent and returned is delivered with its real result (success is success, failure carries the real abort code); a "late cancellation" never disguises the real result as Cancelled.

Related structures:

pub struct SdoTask<T> { /* holds a JoinHandle + cancel flag internally */ }

impl<T> SdoTask<T> {
pub fn master_index(&self) -> u16; // Master index this task belongs to
pub fn cancel(&self); // Affects this task only
pub fn is_cancelled(&self) -> bool;
pub fn is_finished(&self) -> bool; // Whether the background thread has finished (does not consume, does not block)
pub fn join(self) -> Result<T>; // Wait for and take the single result
pub fn try_join(self) -> Option<Result<T>>; // Non-blocking; returns None if not finished (detaches the thread)
}

pub struct SdoCancelToken { /* master_index + cancel flag */ }

impl SdoCancelToken {
pub fn new(master_index: u16) -> Self;
pub fn master_index(&self) -> u16;
pub fn cancel(&self);
pub fn is_cancelled(&self) -> bool;
pub fn check(&self, operation: &str) -> Result<()>; // Already cancelled → Err(DarraError::Cancelled)
pub fn cancel_master(master_index: u16) -> usize; // Cancels only tokens registered under that master
}

SdoCancelToken::cancel_master() only sets tokens registered under the given master; it never calls the global AbortNetwork (which would affect every master), and it does not touch in-flight operations of other masters.

use darra_ethercat::{SdoCancelToken, SdoTask};

let task: SdoTask<Vec<u8>> = coe.sdo_read_task(0x6041, 0x00, false);
if !task.is_finished() {
task.cancel(); // Cancelled before send → join yields Err(Cancelled); no SDO was sent
}
let result = task.join(); // A task can only be joined once
match result {
Err(darra_ethercat::DarraError::Cancelled(msg)) => println!("已取消: {msg}"), // Cancelled: {msg}
other => println!("{:?}", other),
}

sdo_read_cancellable() / sdo_write_cancellable()​

pub fn sdo_read_cancellable(&self, index: u16, subindex: u8, complete_access: bool,
cancel: &SdoCancelToken) -> Result<Vec<u8>>

pub fn sdo_write_cancellable(&self, index: u16, subindex: u8, complete_access: bool,
data: &[u8], cancel: &SdoCancelToken) -> Result<()>

Cancellable variants of synchronous SDO: the token is checked before sending, so an already-cancelled request is not sent and returns Err(DarraError::Cancelled(...)); cancelling after sending does not disguise the real result as a cancellation (success / failure and the real abort code are returned as they are).

Properties​

PropertyTypeCategoryRead/writeDescription
last_sdo_error()SDOErrorDiagnosticsread-onlyError code of the last SDO operation
coe_support()Option<bool>Diagnosticsread-onlyCoE capability tri-state: Some(true)=supported / Some(false)=SII read confirms it is not declared / None=unknown
is_support_known()boolDiagnosticsread-onlyWhether the capability conclusion is known (false = unknown, which does not mean unsupported)
is_supported()boolDiagnosticsread-onlybool view of the CoE capability (true only for known supported; unknown folds to false)
master_index()u16Identityread-onlyMaster index bound to this instance
slave_index()u16Identityread-onlySlave index bound to this instance
od_count()usizeDiagnosticsread-onlyNumber of cached OD objects (0 when not loaded)

coe_support() / is_support_known() / is_supported()​

pub fn coe_support(&self) -> Option<bool>
pub fn is_support_known(&self) -> bool
pub fn is_supported(&self) -> bool

The authority chain for CoE capability: the lower-layer CoE detail query returns a value other than 0 (any capability bit set in SII General's CoE details) → when the lower-layer SII general information read really succeeds, coe_details != 0 is the authoritative conclusion → mbx_proto bit2 (0x04) counts only as positive evidence (the ESI exact-match fast path hard-codes the protocol bit to CoE).

  • Some(true) — supported
  • Some(false) — the SII read confirms CoE is not declared (unsupported can be concluded safely)
  • None — unknown (no authoritative reading, and the protocol bit gives no positive evidence either). It must not be folded to false, otherwise the "unsupported" evidence would be fake.

is_supported() is the bool view of the tri-state conclusion: only Some(true) yields true; unknown also returns false. To distinguish "unknown" from "unsupported", use is_support_known() first or read coe_support() directly.

last_sdo_error()​

pub fn last_sdo_error(&self) -> SDOError

Error code of the last SDO operation on CoEInstance. When CoEInstance::sdo_read() / sdo_write() fails, this method returns the SDO abort code. It is reset automatically to SDOError::NoError after a successful operation.

GeneralError / SDOProtocolTimeout are not "object does not exist"
  • SDOError::SDOProtocolTimeout (0x05040000) — WKC=0 / mailbox timeout / no communication response (the device sent no abort code), retryable; it does not mean the object does not exist and does not write NotPresent.
  • SDOError::GeneralError (0x08000000) — the device really returned a general error without a reason; investigate. It also does not write NotPresent.
  • Only a real abort enters NotPresent: ObjectDoesNotExist (0x06020000), SubindexDoesNotExist (0x06090011), 0x06090012.

Example:

use darra_ethercat::slave::CoEInstance;
use darra_ethercat::SDOError;

let coe = CoEInstance::new(master.index(), 1);
let data = coe.sdo_read(0x6041, 0x00, false);
if data.is_err() {
let error = coe.last_sdo_error();
println!("SDO 读取失败: {:?} (0x{:08X})", error, error as u32); // SDO read failed: {:?} (0x{:08X})
if error == SDOError::SDOProtocolTimeout {
println!("WKC=0 / 超时,不是对象不存在"); // WKC=0 / timeout, this does not mean the object does not exist
}
}

reset_not_present_cache() / clear_sdo_caches()​

pub fn reset_not_present_cache(&self)
pub fn clear_sdo_caches(&self) // Equivalent to reset_not_present_cache()

Clears the NotPresent negative cache of this slave. Call it before hot-plug, a firmware update, a topology change or a mapping rescan; otherwise previously latched "object does not exist" results keep short-circuiting reads.

Mailbox protocol common interface (MailboxProtocol)​

CoEInstance implements darra_ethercat::abstractions::MailboxProtocol, so it can be traversed with the same set of methods as SoE / FoE / EoE / AoE / VoE. These three methods come from the trait, not from the instance itself, so bring the trait into scope before calling them:

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
MethodReturnsDescription
protocol_type()u8Mailbox frame header protocol code; CoE = 0x03
protocol_name()&'static strProtocol name "CoE"
last_error_code()u32The most recent SDO result code as a number (the raw SDOError code); NoError = 0

last_error_code() shares its source with last_sdo_error() and returns the numeric form of the same SDOError: a communication-level failure is SDOProtocolTimeout (0x05040000), a real abort such as the device rejecting a write is the corresponding abort code, an abort code outside the table is UnknownError (0xFFFFFFFF), and before any SDO has run it is 0.

use darra_ethercat::abstractions::MailboxProtocol;

let coe = CoEInstance::new(master.index(), 1);
println!("协议: {:#04X} {}", coe.protocol_type(), coe.protocol_name()); // Protocol: {:#04X} {}
let code = coe.last_error_code();
if code != 0 {
println!("最近 SDO 结果码: 0x{:08X}", code); // Most recent SDO result code: 0x{:08X}
}

SDO request statistics​

MethodTypeCategoryRead/writeDescription
sdo_stats()Result<SdoStats, CoeError>Statisticsread-onlyPer-slave snapshot of accumulated SDO requests / retries / timeouts

sdo_stats()​

#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct SdoStats {
pub requests: u32, // Total SDO requests (increments by 1 per independent transaction)
pub retries: u32, // Total retries
pub timeouts: u32, // Total timeouts
}

pub fn sdo_stats(&self) -> Result<SdoStats, CoeError>

Reads a snapshot of the SDO transaction statistics for this slave.

Returns:

  • Ok(SdoStats) — snapshot available
  • Err(CoeError::DllFailed { abort_code: 0 }) — read failed; the statistics entry point has no abort-code channel, so abort_code is always 0

Failure semantics:

  • The success criterion follows the lower-layer interface contract: 0 = success, a negative value = failure (master index out of range / context not initialized / slave index out of range / slave outside the current topology all return -1). This differs from the rc == 1 convention of the sibling diagnostic interfaces; do not apply that one here
  • A failure never returns partial or fabricated counters; treating Err as "0 requests" would make the "sent exactly once" check pass incorrectly
  • Counters accumulate per slave and are not reset automatically; measure the cost of a single operation by diffing two snapshots

Typical usage:

let before = coe.sdo_stats()?;
// ... run one sdo_read_task / sdo_write_task and join it ...
let after = coe.sdo_stats()?;
let sent_once = after.requests - before.requests == 1
&& after.retries - before.retries == 0;

SDOError enum​

SDO operation error codes (CANopen standard / ETG.1020). #[repr(u32)].

NameValueDescription
NoError0x00000000No error
ToggleBitNotChanged0x05030000Toggle bit not changed
SDOProtocolTimeout0x05040000SDO protocol timeout
InvalidCommandSpecifier0x05040001Invalid command specifier
OutOfMemory0x05040005Out of memory
UnsupportedAccess0x06010000Unsupported access
ReadWriteOnlyError0x06010001Attempt to read a write-only object
WriteReadOnlyError0x06010002Attempt to write a read-only object
SubindexWriteError0x06010003Subindex cannot be written
CompleteAccessNotSupported0x06010004Complete Access is not supported
ObjectLengthExceeded0x06010005Object length exceeded
ObjectMappedToRxPDO0x06010006Object is already mapped to an RxPDO
ObjectDoesNotExist0x06020000Object does not exist
CannotBeMappedToPDO0x06040041Cannot be mapped to a PDO
ExceedsPDOLength0x06040042Exceeds the PDO length
ParameterIncompatibility0x06040043Parameter incompatibility
InternalIncompatibility0x06040047Internal incompatibility
HardwareAccessError0x06060000Hardware access error
DataTypeMismatch0x06070010Data type mismatch
DataTypeTooHigh0x06070012Data type length too high
DataTypeTooLow0x06070013Data type length too low
SubindexDoesNotExist0x06090011Subindex does not exist
SubindexDoesNotExistForObject0x06090012Subindex does not exist for the object
ValueRangeExceeded0x06090030Value out of range
ValueTooHigh0x06090031Value too high
ValueTooLow0x06090032Value too low
ModuleIdentListMismatch0x06090033Module list mismatch
MaxLessThanMin0x06090036Maximum is less than minimum
GeneralError0x08000000General error
DataTransferError0x08000020Data cannot be transferred or stored to the application (reported by the device)
LocalControlError0x08000021Data cannot be transferred or stored because of local control (reported by the device)
DeviceStateError0x08000022Data cannot be transferred or stored because of the present device state (reported by the device)
DictionaryError0x08000023Dictionary error
LocalRequestNotSent0x0D000001Request not sent (local reject): no frame went on the bus; not an abort code reported by the device
UnknownError0xFFFFFFFFUnknown error
0x0D0000xx are master-side codes

Except for LocalRequestNotSent, these codes are not reported by a device. They only appear when the request did not complete and the device returned no abort frame. Seeing one means there is nothing to look up in the object dictionary.

CodeMeaningWhat to do
0x0D000002Frame transmitted, but no device counted itCheck whether that slave's mailbox is rejecting or full, and check the receive path
0x0D000003Mailbox layer error (the peer returned a mailbox Error frame)Check the mailbox SM configuration and the request length
0x0D000004Transport layer failure (cancelled / protocol mismatch / local resource shortage / link down / peer not consuming)No retry for a cancel; restore the link first when it is down; for a protocol mismatch check the mailbox type and SM configuration

The codes a device reports — 0x08000020 / 0x08000021 / 0x08000022 — differ from these in both value and meaning.

SDO description text is Chinese only

statics::sdo_error_description() returns Chinese text; English SDO abort descriptions are not currently provided.

OD tree traversal (OdList)​

OdList loads the complete object dictionary structure from a slave and supports lookup by index and iteration.

OdList::load()​

pub fn load(master_index: u16, slave_index: u16) -> Result<Self>

Loads the complete OD of the given slave (main index + the subentry descriptions of every object). Real mailbox traffic, no ESI cache read.

  • Success → Ok(OdList), with objects holding both objects and entries
  • Failure → Err(DarraError::SdoReadFailed { index: 0, subindex: 0, abort_code: None, raw_abort_code: 0 }) (slave has no CoE / state below PreOp / read failed)

An empty dictionary is not success: Ok with objects empty ≠ loaded. In OP / SafeOp use OdList::load_basic instead.

Example:

use darra_ethercat::OdList;

let od = match OdList::load(master.index(), 1) {
Ok(list) if !list.objects.is_empty() => list,
Ok(_) => {
eprintln!("空字典不是成功"); // An empty dictionary is not success
return Ok(());
}
Err(e) => {
eprintln!("OD 加载失败: {e:?}"); // Failed to load OD: {e:?}
return Ok(());
}
};
println!("从站 1 对象字典: {} 个对象", od.len()); // Slave 1 object dictionary: {} objects

// Look up by index
if let Some(obj) = od.find(0x6040) {
println!("0x{:04X}: {} ({} 条目)", obj.index, obj.name, obj.entries.len()); // 0x{:04X}: {} ({} entries)
for entry in &obj.entries {
println!(" [{:02X}] {} {} {}bit",
entry.sub_index, entry.name, entry.data_type, entry.bit_length);
}
}

// Fuzzy lookup by name
let results = od.find_by_name("control");
for obj in results {
println!("找到: 0x{:04X} {}", obj.index, obj.name); // Found: 0x{:04X} {}
}

OdList::load_basic()​

pub fn load_basic(master_index: u16, slave_index: u16) -> Result<Self>

Reads only the main index list and does not read back subentry descriptions (OdObject.entries is empty for every object), saving one mailbox round trip compared with load(). Use this in OP / SafeOp to avoid saturating the mailbox.

An empty dictionary is likewise not success; the failure return value is the same as for load().

OdObject structure​

Represents one object dictionary object (such as 0x6040 control word) containing a number of subobjects.

pub struct OdObject {
pub index: u16, // Object index
pub name: String, // Object name
pub object_code: u8, // Object code: 0x07=VAR, 0x08=ARRAY, 0x09=RECORD
pub data_type: EcDataType, // Data type identifier
pub max_sub: u8, // Maximum subindex count
pub entries: Vec<ObjectEntry>, // Subentry list
}

ObjectEntry structure​

Represents one subobject (such as 0x6040:00) and is the final data read/write node.

pub struct ObjectEntry {
pub od_index: u16, // Parent object index
pub sub_index: u8, // Subindex
pub name: String, // Name
pub data_type: EcDataType, // Data type (determines the automatic conversion target on read)
pub bit_length: u16, // Bit length
pub access: ObjAccess, // Access permission flags
pub value_info: u8, // ValueInfo flags
}

ObjectEntry carries per-entry read/write methods: the first parameter is the master index and the second is the slave index (decoupled from OdList, so a cached OD can also be used to read other slaves).

let Some(entry) = od.find(0x6040).and_then(|o| o.entry(0x00)) else {
return Err(darra_ethercat::DarraError::Other("OD 里找不到 0x6040:00".into())); // 0x6040:00 not found in the OD
};

// Raw bytes
let raw: Vec<u8> = entry.bytes(master.index(), 1)?;

// Typed read/write
let val: u16 = entry.read_u16(master.index(), 1)?;
entry.write_u16(master.index(), 1, 0x0006)?;

// Decode automatically by data_type
use darra_ethercat::slave::coe::CoEValue;
if let CoEValue::U16(v) = entry.get_value(master.index(), 1)? {
println!("0x6040 = {}", v);
}
MethodReturnsDescription
bytes(master_index, slave_index)Result<Vec<u8>>Raw bytes
read_u8 / read_u16 / read_u32 / read_u64Result<uN>Unsigned integer
read_i32 / read_i64Result<iN>Signed integer
read_f32 / read_f64Result<fN>Floating point
read_stringResult<String>Decoded with the entry's own OD data type (VISIBLE_STRING / OCTET_STRING = single-byte ISO-8859-1, UNICODE_STRING = UTF-16LE); returns Err(SdoReadFailed) when the type is not a CoE string
get_valueResult<CoEValue>Decodes automatically by data_type; types outside the table fall back to CoEValue::Raw
write_u8 / write_u16 / write_u32 / write_u64 / write_i32 / write_i64 / write_f32 / write_f64Result<()>Write

Failure semantics:

  • Without permission it returns Err immediately without bus traffic: reads check can_read(), writes check can_write()
  • The error payload of bytes() and the write_*() methods matches CoEInstance::sdo_read() / sdo_write(): an abort code really returned by the device is passed through verbatim in abort_code / raw_abort_code; on transport-level failure (no device reply) abort_code is Some(SDOProtocolTimeout) and raw_abort_code is 0. For finer diagnostics use CoEInstance::sdo_read_ex() / sdo_write_ex()
  • bytes() treats a 0-byte response as a failure (Err), which differs from CoEInstance::sdo_read() returning Ok(vec![])

Check access permissions:

if entry.can_read() { /* ... */ }
if entry.can_write() { /* ... */ }
if entry.can_write_op() { /* ... */ }
println!("{}", entry.access_description()); // read-only / read/write (writable in OP) ...

EcDataType enum​

#[repr(u16)]
pub enum EcDataType {
None = 0x0000, // Empty
Boolean = 0x0001, // bool — boolean
Integer8 = 0x0002, // i8 — int8
Integer16 = 0x0003, // i16 — int16
Integer32 = 0x0004, // i32 — int32
Unsigned8 = 0x0005, // u8 — uint8
Unsigned16 = 0x0006, // u16 — uint16
Unsigned32 = 0x0007, // u32 — uint32
Real32 = 0x0008, // f32 — single-precision float
VisibleString = 0x0009, // String — ASCII string
OctetString = 0x000A, // Vec<u8> — byte string
UnicodeString = 0x000B, // String — Unicode string
TimeOfDay = 0x000C, // Vec<u8> — time of day (raw bytes)
TimeDifference = 0x000D, // Vec<u8> — time difference (raw bytes)
Domain = 0x000F, // Vec<u8> — raw data
Real64 = 0x0011, // f64 — double-precision float
Integer24 = 0x0010, // 24-bit integer
Integer40 = 0x0012,
Integer48 = 0x0013,
Integer56 = 0x0014,
Integer64 = 0x0015, // i64 — int64
Unsigned24 = 0x0016,
Unsigned40 = 0x0018,
Unsigned48 = 0x0019,
Unsigned56 = 0x001A,
Unsigned64 = 0x001B, // u64 — uint64
Guid = 0x001D,
Byte = 0x001E,
Word = 0x001F,
DWord = 0x0020,
PdoMapping = 0x0021,
SmComType = 0x0022,
Identity = 0x0023,
Bit1 = 0x0030,
Bit2 = 0x0031,
Bit3 = 0x0032,
Bit4 = 0x0033,
Bit5 = 0x0034,
Bit6 = 0x0035,
Bit7 = 0x0036,
Bit8 = 0x0037,
Unknown = 0xFFFF,
}

Protocol names and display aliases:

  • The authoritative protocol names come from the lower layer and are canonical uppercase names such as INT8 / UINT16 / REAL32 / VISIBLE_STRING / BIT1 / UNKNOWN. The Rust entry point is statics::print::data_type_name().
  • The int8 / float / string values returned by statics::print::data_type_short_name() are display-layer aliases for the UI only; they take no part in protocol decisions, bit-width computation, PDO encoding/decoding or cross-language semantic comparison. The local Integer8 / Real32 / VisibleString name table has been removed.
  • The Integer8 / Real32 / VisibleString in the table above are Rust enum member names, not the strings returned by the lower layer.

ObjAccess access permissions​

pub struct ObjAccess(pub u16);

impl ObjAccess {
// Base bit constants, type is u16
pub const NONE: u16 = 0x0000;
pub const READ_PREOP: u16 = 0x0001; // Readable in PreOp
pub const READ_SAFEOP: u16 = 0x0002; // Readable in SafeOp
pub const READ_OP: u16 = 0x0004; // Readable in OP
pub const WRITE_PREOP: u16 = 0x0008; // Writable in PreOp
pub const WRITE_SAFEOP: u16 = 0x0010; // Writable in SafeOp
pub const WRITE_OP: u16 = 0x0020; // Writable in OP
pub const MAP_RXPDO: u16 = 0x0040; // Mappable to RxPDO
pub const MAP_TXPDO: u16 = 0x0080; // Mappable to TxPDO
pub const SETTINGS: u16 = 0x0100; // Settings parameter

// Same-value aliases, type is Self
pub const READ_PRE_OP: Self = Self(Self::READ_PREOP);
pub const READ_SAFE_OP: Self = Self(Self::READ_SAFEOP);
pub const WRITE_PRE_OP: Self = Self(Self::WRITE_PREOP);
pub const WRITE_SAFE_OP: Self = Self(Self::WRITE_SAFEOP);

// Aggregate constants
pub const READ_ANY: u16 = Self::READ_PREOP | Self::READ_SAFEOP | Self::READ_OP;
pub const WRITE_ANY: u16 = Self::WRITE_PREOP | Self::WRITE_SAFEOP | Self::WRITE_OP;
pub const READ_WRITE_ALL: Self = Self(Self::READ_ANY | Self::WRITE_ANY);

pub fn can_read(self) -> bool; // Readable in any state
pub fn can_write(self) -> bool; // Writable in any state
pub fn is_read_only(self) -> bool; // Readable and not writable
pub fn can_write_preop(self) -> bool; // Writable in PreOp
pub fn can_write_safeop(self) -> bool; // Writable in PreOp/SafeOp
pub fn can_write_op(self) -> bool; // Writable in any state
pub fn rxpdo_mappable(self) -> bool; // Mappable to RxPDO
pub fn txpdo_mappable(self) -> bool; // Mappable to TxPDO
pub fn contains(self, other: Self) -> bool; // Every bit of other is present in self
pub fn union(self, other: Self) -> Self; // Bitwise OR merge
pub fn access_description(self) -> String; // e.g. "read-only" / "read/write (writable in OP)"

// Legacy names equivalent to can_read / can_write
pub fn readable(self) -> bool;
pub fn writable(self) -> bool;
}

ObjectEntry has a set of forwarding methods with the same names: can_read() / can_write() / is_read_only() / can_write_preop() / can_write_safeop() / can_write_op() / access_description().

let Some(entry) = od.find(0x1C12).and_then(|o| o.entry(0x00)) else {
return Err(darra_ethercat::DarraError::Other("OD 里找不到 0x1C12:00".into())); // 0x1C12:00 not found in the OD
};
if entry.access.txpdo_mappable() {
println!("{}", entry.access); // Display: [R(PreOp)|R(SafeOp)|R(Op)|TxPDO]
}

OD cache entry points (CoEInstance)​

CoEInstance caches the OD inside the instance (Arc-shared; instances produced by clone() share one cache):

MethodReturnsDescription
load_od(prefer_esi: bool)Result<OdList>Loads and caches; in PreOp it also reads subentries, other states read only the main index list
get_sdo_list(prefer_esi: bool)Result<OdList>Public alias of load_od (aligned with the C#/Python naming); entry count via OdList::count()
load_od_list(prefer_esi: bool)Result<bool>Same as above, returns whether it is non-empty; returns Ok(false) while loading
load_od_async(prefer_esi)JoinHandle<Result<OdList>>Standard thread version
load_od_list_async(prefer_esi)JoinHandle<Result<bool>>Standard thread version
od_list()Option<OdList>Cached copy; None when not loaded
od_count()usizeNumber of cached objects
reset_od_cache()()Clears the OD cache (does not clear the NotPresent negative cache)
is_od_list_loading()boolWhether a load is in progress
bind_esi_file(path: &str)Result<()>Hands an ESI file to the lower layer to load and parse (the path is stored as the "bound ESI" marker)
bind_esi_xml(xml: impl Into<String>)()Only marks ESI as bound; the passed text is no longer parsed (the OD is queried at the lower layer by this slave's SII identity), so to let the lower layer find data you must first load an ESI file with bind_esi_file

When prefer_esi = true and an ESI is bound, the object dictionary is looked up first by this slave's SII identity (VendorId / ProductCode / RevisionNo) in the ESI already loaded by the lower layer (no mailbox traffic), falling back to SDO Information when there is no hit. In files with multiple <Device> entries the device is located by identity; it never silently takes the first one.

get_sdo_list()​

pub fn get_sdo_list(&self, prefer_esi: bool) -> Result<OdList>

The Rust public surface for the object dictionary list, equivalent to load_od(prefer_esi). With prefer_esi = true the OD from the ESI is preferred, otherwise the mailbox SDO Info upload is used. Entry count = OdList::count().

use darra_ethercat::slave::CoEInstance;

let coe = CoEInstance::new(master.index(), 1);
let od = coe.get_sdo_list(true)?;
println!("OD 对象数: {}", od.count()); // OD object count: {}

get_object_description() / get_entry_description()​

pub fn get_object_description(master_index: u16, slave_index: u16, index: u16)
-> Result<OdObject>

pub fn get_entry_description(master_index: u16, slave_index: u16, index: u16, subindex: u8)
-> Result<ObjectEntry>

Reads a single object description / subentry description and hits the mailbox in real time every time. On failure it returns Err(DarraError::CoEInfoFailed { index, subindex, abort_code, wkc }):

  • abort_code is the 16-bit SDO Info ErrorCode returned by the device (ETG.1000.6 Table 48); None = the device returned no abort code (transfer-level failure, the device response was never reached)
  • wkc is the result of the innermost mailbox transaction (false = transfer-level failure or the transaction never ran)
Not the same code table as SdoReadFailed

The 16-bit Info ErrorCode of CoEInfoFailed and the 32-bit SDO Abort Code of SdoReadFailed cannot be interpreted as each other's code.

load_via_coe_h2() / load_via_coe_h2_basic()​

pub fn load_via_coe_h2(master_index: u16, slave_index: u16) -> Result<Self>
pub fn load_via_coe_h2_basic(master_index: u16, slave_index: u16) -> Result<Self>

Reads the OD list straight from SDO Information (lower-layer OD list interface + per-subindex entry description queries), without reading the description cache. A lower-layer list read failure → Err(DarraError::CoEInfoFailed) (carrying the device Info abort code and the innermost wkc). A failure while reading an entry for one subindex still skips that entry without aborting the whole table load (use get_entry_description() when you need per-entry abort codes).

load_via_coe_h2_basic is the fallback for a slave that carries the Error bit after a Boot round trip: the standard SDO list path refuses it, while the basic path only checks the AL base state < PreOp and can still read the list.

EMCY emergency history​

CoE supports CiA 301 emergency (Emergency) records. The Rust SDK provides read / clear / count operations as free functions in the darra_ethercat::slave::coe_emcy module and re-exports them under the darra_ethercat::slave module:

use darra_ethercat::slave::{emcy_get_history, emcy_get_count, emcy_clear_history};
FunctionCategoryRead/writeDescription
emcy_get_history()Diagnosticsread-onlyFetches up to max_records EMCY history records
emcy_get_count()Diagnosticsread-onlyCurrent number of EMCY records
emcy_clear_history()Diagnosticswrite-onlyClears the EMCY history of that slave

emcy_get_history()​

pub fn emcy_get_history(
master_index: u16,
slave_index: u16,
max_records: usize,
) -> std::result::Result<Vec<EmcyRecord>, CoeError>

Fetches the EMCY emergency history of that slave: the most recent max_records records of the ring, returned in time order (oldest → newest). The ring capacity is at most 256 records; max_records decides how many are taken at most this call, so a smaller value is fine; passing 0 reports InvalidParameter.

The return value strictly separates "no records" from "read failure" (the CoeError definition is in CoeError enum below):

ReturnsMeaning
Ok(records)Read succeeded; an empty Vec = the slave confirmed there are no EMCY records
Err(CoeError::InvalidParameter)max_records == 0 (caller parameter error)
Err(CoeError::DllFailed)Lower-layer entry point unavailable / call failed

Failures always go through Err and are never folded into an empty history: an empty Vec only means "confirmed no records" and never mixes in a read failure.

emcy_get_count()​

pub fn emcy_get_count(master_index: u16, slave_index: u16) -> std::result::Result<usize, CoeError>

Returns the current number of EMCY history records for that slave. Ok(0) = confirmed no records; a read failure goes through Err(CoeError::DllFailed) and is not folded into 0 records, so "no records" and "cannot read" stay distinguishable.

emcy_clear_history()​

pub fn emcy_clear_history(master_index: u16, slave_index: u16)

Clears the EMCY history records of that slave.

EmcyRecord structure​

emcy_get_history() returns EmcyRecord (#[repr(C, packed)], also available from darra_ethercat::EmcyRecord).

#[repr(C, packed)]
pub struct EmcyRecord {
pub error_code: u16, // Emergency error code (CiA 301 Table 24)
pub error_register: u8, // Error register (object 0x1001)
pub data: [u8; 5], // Vendor-specific data (fixed 5 bytes)
pub slave_index: u16, // Source slave index
pub timestamp_ms: u32, // Receive time (millisecond timestamp)
}
About EmergencyMessage

darra_ethercat::slave::coe_emcy also contains a higher-level EmergencyMessage (data: [u8; 5] / timestamp_ms: u64), obtained via the From<&EmcyRecord> conversion. emcy_get_history() returns EmcyRecord directly; if you need the higher-level structure, call EmergencyMessage::from(&record) yourself.

Example:

use darra_ethercat::slave::{emcy_get_history, emcy_get_count, emcy_clear_history};

// The example lives inside a function returning Result; errors propagate via ? (otherwise handle Ok/Err with match explicitly)

// Get the slave's EMCY message count (Ok(0) = confirmed no records)
let count = emcy_get_count(master.index(), 1)?;

// Get the history (at most 64 records; ring capacity is 256, max_records can be smaller)
let history = emcy_get_history(master.index(), 1, 64)?;
for msg in &history {
// packed fields must be copied to a local variable before formatting
let code = msg.error_code;
let reg = msg.error_register;
println!("EMCY 0x{:04X} 寄存器=0x{:02X}", code, reg); // EMCY 0x{:04X} register=0x{:02X}
}

// Clear the history
emcy_clear_history(master.index(), 1);

Complete example​

Traverse the object dictionary​

use darra_ethercat::OdList;

let od = match OdList::load(master.index(), 1) {
Ok(list) if !list.objects.is_empty() => list,
Ok(_) => {
eprintln!("空字典不是成功"); // An empty dictionary is not success
return Ok(());
}
Err(e) => {
eprintln!("OD 加载失败: {e:?}"); // Failed to load OD: {e:?}
return Ok(());
}
};
println!("从站 1 对象字典: {} 个对象", od.len()); // Slave 1 object dictionary: {} objects

for obj in &od.objects {
println!("0x{:04X}: {} (代码=0x{:02X}, {} 条目)", // 0x{:04X}: {} (code=0x{:02X}, {} entries)
obj.index, obj.name, obj.object_code, obj.entries.len());
for entry in &obj.entries {
let rw = if entry.access.writable() { "RW" } else { "RO" };
println!(" [{:02X}] {}: {} {}bit [{}]",
entry.sub_index, entry.name, entry.data_type,
entry.bit_length, rw);
}
}

// Look up by index
if let Some(obj) = od.find(0x6040) {
println!("0x{:04X}: {} ({} 条目)", obj.index, obj.name, obj.entries.len()); // 0x{:04X}: {} ({} entries)
}

// Fuzzy lookup by name
let results = od.find_by_name("control");
for obj in results {
println!("找到: 0x{:04X} {}", obj.index, obj.name); // Found: 0x{:04X} {}
}

Batch SDO reads​

let slave = master.slave(1);

// Read device information — failures / WKC=0 must be matched; do not call from_le_bytes directly
let device_type: u32 = match slave.sdo_read_value(0x1000, 0x00) {
Ok(v) => v,
Err(e) => {
eprintln!("SDO 失败: {e:?}"); // SDO failure: {e:?}
return Ok(());
}
};
let vendor_id: u32 = match slave.sdo_read_value(0x1018, 0x01) {
Ok(v) => v,
Err(_) => return Ok(()),
};
let product_code: u32 = match slave.sdo_read_value(0x1018, 0x02) {
Ok(v) => v,
Err(_) => return Ok(()),
};

// 0x1008 is a VisibleString, a non-Copy type; use sdo_read to get the raw bytes and decode
let name_raw: Vec<u8> = match slave.sdo_read(0x1008, 0x00, false) {
Ok(bytes) => bytes,
Err(_) => return Ok(()),
};
let device_name = String::from_utf8_lossy(&name_raw).trim_end_matches('\0').to_string();

println!("设备类型: 0x{:08X}", device_type); // Device type: 0x{:08X}
println!("设备: {} (VID=0x{:08X}, PID=0x{:08X})", device_name, vendor_id, product_code); // Device: {} (VID=0x{:08X}, PID=0x{:08X})

Diagnostic history (Diagnosis History, 0x10F3)​

ETG.1020 §16 defines the standard interface through which a slave reports diagnostic messages via object 0x10F3, letting the master query "are there new messages / metadata / a single message / acknowledge processed" as four kinds of operation. The Darra SDK wraps this flow under CoEInstance: poll_has_new_diagnostic() returns the three-state DiagnosticPollResult enum (no new messages / new messages / communication failure), and the other three return Result<T, CoeError> so they can be chained with ?.

Typical usage scenarios
  • Use poll_has_new_diagnostic() for high-frequency polling to avoid reading the whole dictionary each time
  • After new messages are detected, call read_diagnostic_meta() to get the latest subindex range
  • Fetch the raw bytes in subindex order with read_diagnostic_message(msg_idx, 512)
  • After processing, call acknowledge_diagnostic(msg_idx) (in Acknowledge mode the slave cleans up messages <= msg_idx; in Overwrite mode this write carries no decision weight)
Concurrent consumption in Rust

The diagnostic history has only a synchronous polling API (poll_has_new_diagnostic() / read_diagnostic_meta() / read_diagnostic_message() / acknowledge_diagnostic()). The Rust SDK has no async Stream for diagnostic messages: under async-tokio, state_stream_async() / emergency_stream_async() are master state change / EMCY streams unrelated to 0x10F3 diagnostic messages and cannot be used as a diagnostic stream. In tokio scenarios, put the synchronous calls above into spawn_blocking, or forward the polling results yourself with tokio::sync::mpsc.

CoeError enum​

The dedicated error type shared by the diagnostic history and EMCY reads; generic SDO read/write still uses DarraError::SdoReadFailed / SdoWriteFailed.

#[derive(Debug, Clone)]
pub enum CoeError {
/// Runtime library call failed (carries the SDO Abort Code, 0 = no abort code)
DllFailed { abort_code: u32 },
/// Parameter out of range
InvalidParameter(String),
/// Unexpected data length returned by the lower layer
InvalidResponse(String),
}

impl From<CoeError> for DarraError { /* converts to DarraError::Other */ }

Error categories:

  • DllFailed — the runtime library returned a failure, carrying the SDO Abort Code (slave does not support 0x10F3 / Abort 0x06020000)
  • InvalidParameter — Rust-layer parameter validation failed (msg_idx outside 6..=255 / buf_size out of range / max_records == 0)
  • InvalidResponse — the runtime library returned an unexpected length (out_len > buf_size and so on)

DiagMeta structure​

Aligned with 0x10F3 subindexes 01/02/03/05, corresponding to ETG.1020 Table 48/49.

#[derive(Debug, Clone, Copy, Default)]
pub struct DiagMeta {
/// 0x10F3:01 MaxMessages — maximum number of messages supported (usually <= 250)
pub max_messages: u8,
/// 0x10F3:02 NewestMessage — subindex holding the newest message; 0 = no message
pub newest_message: u8,
/// 0x10F3:03 NewestAcknowledged — newest acknowledged subindex
/// (in Overwrite mode the slave keeps 0 by specification; that 0 is normal)
pub newest_acknowledged: u8,
/// 0x10F3:05 Flags — bit4 = 0 Overwrite / 1 Acknowledge, bit5 = Overrun
pub flags: u16,
}

impl DiagMeta {
/// Whether Acknowledge mode is active (bit4=1); false = Overwrite mode
pub fn is_acknowledge_mode(&self) -> bool { self.flags & 0x0010 != 0 }
/// Whether messages were ever lost due to Overrun (bit5=1, unread messages overwritten)
pub fn has_overrun(&self) -> bool { self.flags & 0x0020 != 0 }
}
Meaning of the Flags bits

Per ETG.1020 v1.5.0 Table 49, flags (0x10F3:05) is defined as:

  • bit4 = diagnostic buffer mode: 0 = Overwrite / 1 = Acknowledge
  • bit5 = 1 means Overrun occurred (the ring buffer has overwritten unread messages)

How to read it: in Overwrite mode the slave keeps newest_acknowledged = 0 by specification; that 0 is a normal value and must not be read as "there are unacknowledged messages", nor may it be inferred from newest_message != newest_acknowledged. In that mode, whether an unread message exists can only be answered by 0x10F3:04 NewAvailable (poll_has_new_diagnostic()). Only in Acknowledge mode does newest_message != newest_acknowledged indicate unacknowledged messages.

Accessor: this language provides DiagMeta::is_acknowledge_mode() (equivalent to flags & 0x0010 != 0; 0 = Overwrite, 1 = Acknowledge) and DiagMeta::has_overrun() (flags & 0x0020 != 0), so no manual bit mask is needed.

poll_has_new_diagnostic()​

pub enum DiagnosticPollResult {
None, // No new messages (lower layer returned 0)
HasNew, // New messages present; continue fetching 0x10F3 history (lower layer returned 1)
Failed, // Communication failure: lower layer returned -1, or an unexpected value other than 1/0/-1
}

pub fn poll_has_new_diagnostic(&self) -> DiagnosticPollResult

Quickly polls the 0x10F3:04 "NewAvailable" flag (ETG.1020 §16.2). No new messages means the full history is not read, which suits high-frequency polling.

Returns:

  • DiagnosticPollResult::HasNew — new messages present; continue fetching the 0x10F3 history
  • DiagnosticPollResult::None — no new messages
  • DiagnosticPollResult::Failed — communication failure (lower layer returned -1 or an unexpected value). The SDK writes a log entry with the original value and abort code for root-cause analysis; "cannot ask the slave" and "no new messages" are two different things, so on Failed retry or report — do not treat it as no messages

read_diagnostic_meta()​

pub fn read_diagnostic_meta(&self) -> Result<DiagMeta, CoeError>

Reads the 0x10F3 metadata (MaxMessages / NewestMessage / NewestAcknowledged / Flags).

read_diagnostic_message()​

pub fn read_diagnostic_message(
&self,
msg_idx: u16,
buf_size: usize,
) -> Result<Vec<u8>, CoeError>

Reads the raw bytes of the diagnostic message at the given subindex (6..=255) (Octet String). The length of the returned Vec<u8> is the actual message length.

Parameters:

  • msg_idx — message subindex, must be in 6..=255
  • buf_size — receive buffer capacity, 512 bytes recommended (ETG Table 49 upper bound), must be in 1..=65536

acknowledge_diagnostic()​

pub fn acknowledge_diagnostic(&self, msg_idx: u16) -> Result<(), CoeError>

Acknowledges that the given subindex (6..=255) has been processed by writing 0x10F3:03 NewestAcknowledged. In Acknowledge mode (DiagMeta::is_acknowledge_mode() = true) the slave advances its acknowledged position accordingly and cleans up messages <= msg_idx; in Overwrite mode this write carries no decision weight (the slave keeps newest_acknowledged = 0 by specification).

Example: diagnostic history polling​

use darra_ethercat::slave::{CoEInstance, CoeError};
use darra_ethercat::slave::coe::DiagnosticPollResult;

let coe = CoEInstance::new(master.index(), slave.index());

// 1. Poll the "NewAvailable" flag frequently
match coe.poll_has_new_diagnostic() {
DiagnosticPollResult::HasNew => {} // New messages; keep fetching the history below
DiagnosticPollResult::None => return Ok(()), // No new messages
DiagnosticPollResult::Failed => return Ok(()), // Communication failure: retry or report; do not treat as "no messages"
}

// 2. Read the metadata
let meta = coe.read_diagnostic_meta()?;
println!(
"最大={} 最新={} 已确认={} AckMode={} Overrun={}", // Max={} Latest={} Acknowledged={} AckMode={} Overrun={}
meta.max_messages,
meta.newest_message,
meta.newest_acknowledged,
meta.is_acknowledge_mode(),
meta.has_overrun(),
);

// 3. Fetch new messages in subindex order
// In Overwrite mode newest_acknowledged stays 0 by specification and is not a read cursor;
// only Acknowledge mode starts from acked+1
let mut idx = if meta.is_acknowledge_mode() {
meta.newest_acknowledged.saturating_add(1).max(6) as u16
} else {
6u16
};
while idx <= meta.newest_message as u16 {
match coe.read_diagnostic_message(idx, 512) {
Ok(bytes) => {
println!("消息 [{:02X}] {} 字节: {:02X?}", idx, bytes.len(), &bytes[..bytes.len().min(16)]); // Message [{:02X}] {} bytes: {:02X?}
coe.acknowledge_diagnostic(idx)?;
}
Err(CoeError::DllFailed { abort_code }) => {
eprintln!("读 [{:02X}] 失败, Abort=0x{:08X}", idx, abort_code); // Read [{:02X}] failed, Abort=0x{:08X}
break;
}
Err(e) => {
eprintln!("读 [{:02X}] 失败: {}", idx, e); // Read [{:02X}] failed: {}
break;
}
}
idx += 1;
}
References
  • ETG.1020 §16 Diagnosis History Object
  • ETG.1020 Table 48/49 — 0x10F3 subindex definitions and Flags bit fields

Batch diagnostic message reads (module-level functions)​

read_diagnostic_messages​

pub fn read_diagnostic_messages(master_index: u16, slave_index: u16) -> Vec<DiagnosticMessage>

Reads the slave's 0x10F3 diagnostic messages in one go (up to 20) and returns a list of DiagnosticMessage.

  • Subindexes that fail to read are skipped automatically and no error is returned; an empty Vec does not mean the slave has no diagnostics
  • At most 20 are returned; anything beyond that is not read
  • Complementary to the "on-demand single message + metadata" mode of CoEInstance::read_diagnostic_message; this function suits a one-shot export of the whole history

Return structure:

#[derive(Debug, Clone)]
pub struct DiagnosticMessage {
/// Subindex (1-based)
pub sub_index: u8,
/// ETG diagnostic code (32-bit)
pub diag_code: u32,
/// Flags (Type/Severity)
pub flags: u16,
/// Text index (references the ESI string table)
pub text_index: u16,
/// Whole raw byte block (8-byte header + optional appended data)
pub raw_data: Vec<u8>,
}

Example:

use darra_ethercat::slave::coe::read_diagnostic_messages;

let msgs = read_diagnostic_messages(master.index(), slave.index());
println!("总共 {} 条诊断消息", msgs.len()); // {} diagnostic messages in total
for m in msgs {
println!("{} → Code 0x{:08X}, Flags 0x{:04X}, TextIdx 0x{:04X}",
m.sub_index, m.diag_code, m.flags, m.text_index);
}
Combine with 0x10F3:04 NewAvailable

In high-frequency polling scenarios still prefer CoEInstance::poll_has_new_diagnostic and call this function only when it returns DiagnosticPollResult::HasNew, avoiding the mailbox pressure of walking every subindex each cycle.

get_device_profile​

pub fn get_device_profile(master_index: u16, slave_index: u16) -> u16

Reads the lower 16 bits of 0x1000 Device Type, that is the CiA device profile number (for example 402=drive, 401=generic IO). Returns 0 on failure. Useful for classifying devices quickly without loading the full OD.

use darra_ethercat::slave::coe::get_device_profile;

let profile = get_device_profile(master.index(), slave.index());
match profile {
402 => println!("CiA 402 驱动"), // CiA 402 drive
401 => println!("CiA 401 通用 IO"), // CiA 401 general-purpose IO
_ => println!("其它/未知 profile = {}", profile), // Other/unknown profile = {}
}