Skip to main content

Master diagnostics

Use master.diagnostics_info() to obtain MasterDiagnosticsInfo and access all diagnostics, monitoring and statistics features.​

Use alongside events

Drive exception handling from events instead of polling yourself. Reading diagnostic properties directly suits scenarios such as UI display.

Feature overview​

FeatureDescription
Communication and performance statisticsFrame counts, packet loss, jitter, PDO frame loss, port status, topology
WKC model ledger and unreachable slavesEffective WKC of the topology union, expected snapshot, unreachable slave count, validated publish
Per-slave WKC probePer-slave probe truth, expectation, sample freshness, probe switch
Link diagnostics event queueTotal event count, freshness token, incremental reads by seq
NIC health checkRead-only verdict, active probe, explicit soft-restart recovery
P1 foldback and measured ring topologyFoldback requirement mode, measurement state, end address, full WKC, ring slave count
Diagnostics snapshotConsistent snapshot for UI refresh and logging
DC synchronizationSync window threshold, DC summary readings, auto offset, DCSyncLost event
Redundancy statusRedundancy active, fault point detection (link down + CRC fault location)
Diagnostics counters carried with framesCumulative counters and switch on the calling / consuming side
Diagnostics controlStart/stop data collection, refresh snapshot, master frame statistics, reset statistics

Communication and performance statistics​

CategoryMethodTypeR/WStoppableDescription
Frame countsrt_cnt()u32read-onlyYesFrames per second (Hz), 5-second average
error_cnt()u32read-onlyYesErrors per second, 5-second average
packet_loss_rate()f32read-onlyYesPacket loss rate (0.0~1.0) — TX vs RX over a 5s sliding window; frames still in the pipeline do not count as lost
late_frame_rate()f32read-onlyYesLate frame rate (0.0~1.0) — frames whose index leaves the 8-frame window are stale and not counted as packet loss
Cycle and jittercycle_count()u64read-onlyNoCumulative PDO cycle count; reads the live value directly, without the sliding window
cycle_time_span()u32read-onlyYesActual cycle time (µs), live value. Follows the DENI/LoopCycle setting rather than a hard-coded 1ms.
avg_jitter_us()f64read-onlyYesAverage jitter over the last 5 seconds (µs). Jitter grows when isolation is not in effect; the cycle should still hold at the configured value. Minimum cycle 125 µs.
avg_cycle_time_us()f64read-onlyYesAverage cycle time (µs)
rt_cnt()u32read-onlyYesFrames per second (Hz); follows the configured cycle instead of a fixed 1000Hz. A frame rate that keeps deviating from the configured cycle, or jitter that keeps exceeding the norm, is treated as abnormal: it is logged and raised as an alarm (see Events.PDOFrameLoss / Events.DCSyncLost)
Mailbox latencymailbox_latency_us()f64read-onlyYesMailbox send/receive latency — maximum (µs), settled over the last 1 second
mailbox_latency_avg_us()f64read-onlyYesMailbox send/receive latency — average (µs), settled over the last 1 second
WKCwkc()u16read-onlyNoCurrent WKC
expected_wkc()u16read-onlyNoExpected WKC
WKC mirrorwkc_actual_mirror()u16read-onlyNoWorking counter measured on the bus (actual WKC) — reflects which slaves are really responding right now. The reported value is never altered. Live value, no refresh needed
wkc_expected_mirror()u16read-onlyNoExpected working counter (expected WKC) — a fixed value established at configuration time / on entering OP. It is never lowered dynamically to accommodate a degraded bus. Live value, no refresh needed
wc_deficit()u16read-onlyNoWKC deficit = expected − actual (>0 means a mapped slave is not contributing WKC right now — suspect slave loss / hot-plug). Returns to 0 automatically once the slave recovers. Live value, no refresh needed
mapped_slave_count()u16read-onlyNoNumber of mapped slaves (those taking part in the WKC calculation). Live value, no refresh needed
Master truthlost_slave_count()i32read-onlyNoLost-slave census count (the single authority for the bus-level lost-slave count); >0 = a slave is lost; 0 = no lost slave or the probing mechanism is not observable
no_process_data()boolread-onlyNoMaster-level "no process data / false OP" truth value: true = the cycle is running but the process data is dead; a read failure returns true (fail-safe)
no_process_data_known()boolread-onlyNoWhether no_process_data() has a measured sample; when false the return value carries no meaning and must be shown as "unknown"
probe_alive_count() / probe_unknown_count()i32read-onlyNoProbe truth summary (number of slaves that answered / number of slaves with insufficient evidence); 0 when there is no true-value sample
stale_input_count()Option<i32>read-onlyNoNumber of slaves whose input data is confirmed STALE (per slave input_data_validity()==Stale); Unknown / Degraded are not counted; None = a slave read failed / is unavailable
Cycle runcycle_state()CycleRunStateread-onlyNoMaster cycle tri-state: NotStarted / StartedNoAdvance / Advancing; 0 no longer blurs three different meanings into one value
Topology changetopology_fingerprint()u64read-onlyNoTopology fingerprint (slave count + a stable hash of each slave's VendorId/ProductId/RevId); topology_fingerprint_known() reports whether sampling succeeded
topology_change_count()u64read-onlyNoNumber of observed topology changes (the first sample is not counted; observed at read time, multiple changes between two reads are merged into one)
last_topology_change_utc()Option<SystemTime>read-onlyNoTime of the most recent observed topology change (UTC); None = no change observed yet
PDO frame losspdo().total_lost()u32read-onlyNoTotal lost frames (all groups combined)
pdo().consecutive_lost()u32read-onlyNoCurrent consecutive lost frames (the maximum across all groups)
pdo().frame_loss_stats(group)PDOFrameLossStatsread-onlyNoPDO frame loss statistics for the specified group
Slave anomaliesworst_slave_index()u16read-onlyNoIndex of the slave with the highest error rate
worst_link_quality()i16read-onlyNoWorst slave communication health (%), -1 = unknown
Port statusprimary_port_ok()boolread-onlyNoWhether the primary port is OK
secondary_port_ok()boolread-onlyNoWhether the secondary port is OK
primary_port_errors()u32read-onlyNoErrors on the primary port over the last 5 seconds
secondary_port_errors()u32read-onlyNoErrors on the secondary port over the last 5 seconds
Topologytopology_description()&strread-onlyNoTopology mode description ("线性" (SDK output, = linear) / "环形" (SDK output, = ring))
timing_mode()&strread-onlyNoTiming mode description ("硬件定时器" (SDK output, = hardware timer) / "RT就绪" (SDK output, = RT ready) / "降级" (SDK output, = degraded) / "RT错误" (SDK output, = RT error)). The real-time driver must be ready
Formula
MetricFormulaDescription
rt_cntFrames per sample period / window secondsSliding-window average frame rate
error_cntErrors per sample period / window secondsSliding-window average error rate
packet_loss_rate(TX-RX-pipeline) / TX5-second sliding window; frames still in the pipeline do not count as lost
late_frame_rateLateDrop / TXIndex leaving the 8-frame window is stale and not counted as packet loss

Requires set_enabled(true).

PDOFrameLossStats struct
FieldTypeDescription
total_lostu32Total lost frames
consecutive_lostu32Current consecutive lost frames
max_consecutive_lostu32Maximum consecutive lost frames on record

Example:

let diag = master.diagnostics_info();
diag.set_enabled(true); // enable diagnostics data collection

// frame counters
println!("帧频: {} Hz", diag.rt_cnt()); // Frame rate: {} Hz
println!("丢包率: {:.2}%", diag.packet_loss_rate() * 100.0); // Packet loss rate: {:.2}%
println!("错误数: {}", diag.error_cnt()); // Error count: {}

// cycle and jitter
println!("周期计数: {}", diag.cycle_count()); // Cycle count: {}
println!("周期时间: {} us", diag.cycle_time_span()); // Cycle time: {} us
println!("平均抖动: {:.2}us", diag.avg_jitter_us()); // Average jitter: {:.2}us

// mailbox send/receive latency
println!("邮箱延迟: 平均 {:.2}us, 最大 {:.2}us", // Mailbox latency: average {:.2}us, max {:.2}us
diag.mailbox_latency_avg_us(), diag.mailbox_latency_us());

// PDO frame loss (all groups combined)
let pdo = diag.pdo();
println!("PDO 丢帧: 累计={}, 连续={}", pdo.total_lost(), pdo.consecutive_lost()); // PDO frame loss: total={}, consecutive={}

// query frame loss by group (0-7)
let group0_stats = pdo.frame_loss_stats(0); // group 0
let group1_stats = pdo.frame_loss_stats(1); // group 1
println!("组0丢帧: {}, 组1丢帧: {}", // Group 0 frame loss: {}, group 1 frame loss: {}
group0_stats.total_lost, group1_stats.total_lost);

// slave anomalies
println!("最差从站: #{} ({}%)", diag.worst_slave_index(), diag.worst_link_quality()); // Worst slave: #{} ({}%)

// port status
println!("主端口: {}", if diag.primary_port_ok() { "正常" } else { "异常" }); // Primary port: {} — OK / abnormal
println!("副端口: {}", if diag.secondary_port_ok() { "正常" } else { "未连接" }); // Secondary port: {} — OK / not connected

// topology information
println!("拓扑: {}", diag.topology_description()); // Topology: {}
println!("定时: {}", diag.timing_mode()); // Timing: {}

cycle_count()​

pub fn cycle_count(&self) -> u64

Cumulative PDO cycle count. Reads the live cycle counter directly, without going through the diagnostics summary sliding window.

Returns:

  • u64 — cumulative cycles since the PDO loop started

Example:

let diag = master.diagnostics_info();
let n = diag.cycle_count();

Real-time performance statistics​

realtime_stats()​

// method on EtherCATMaster (not on diagnostics_info())
pub fn realtime_stats(&self) -> Option<RealtimeStats>

Retrieves the master's real-time performance metrics for the current cycle in one call (current cycle duration / jitter / lost frames / corrupted frames / bus utilization). None means the call failed (performance monitoring not started / master not ready).

Returns:

pub struct RealtimeStats {
pub current_cycle_time_us: f64, // current cycle duration (µs)
pub jitter_us: f64, // cycle jitter (µs)
pub lost_frames: u32, // cumulative lost frames
pub corrupted_frames: u32, // cumulative corrupted frames
pub bus_utilization: f64, // bus utilization (0.0 ~ 1.0)
}

Example:

if let Some(rt) = master.realtime_stats() {
println!("周期 {:.2}us, 抖动 {:.2}us, 总线利用率 {:.1}%", // Cycle {:.2}us, jitter {:.2}us, bus utilization {:.1}%
rt.current_cycle_time_us, rt.jitter_us, rt.bus_utilization * 100.0);
if rt.corrupted_frames > 0 {
println!("⚠ 破损帧 {} 个", rt.corrupted_frames); // ⚠ {} corrupted frames
}
}
Difference from diagnostics_info()

realtime_stats() is a lightweight one-shot snapshot provided directly by EtherCATMaster, complementing the sliding-window statistics of diagnostics_info() (5-second averages). realtime_stats() reflects the cycle values "right now" and does not need set_enabled(true).

WKC mirror (slave loss observable)​

wkc_actual_mirror() / wkc_expected_mirror() / wc_deficit() are methods on diagnostics_info() that return master-level WKC summaries; all of them read the current live value directly (no caching, no refresh — what you read is the real bus state at that moment). Combined with each slave's slave.wc_contributed(), they pinpoint which slave dropped out.

Observability rules (mandatory):

  • wkc_expected_mirror() = the fixed value established at configuration time / on entering OP. It is fixed as long as the topology is fixed, immutable by definition, and never lowered dynamically to accommodate a degraded bus.
  • wkc_actual_mirror() = the value measured on the bus; it faithfully reflects which slaves are really responding right now and is never altered.
  • wc_deficit() = wkc_expected_mirror() − wkc_actual_mirror(). > 0 is not a master fault; it means a mapped slave is not contributing WKC right now (possible slave loss / hot-plug recovery). It returns to 0 automatically when the slave recovers, with no reset call required.

Example:

use darra_ethercat::WcContribution;

let diag = master.diagnostics_info();

// master-level WKC summary (read live)
println!("WKC: {} / {} (映射从站 {} 个)", // WKC: {} / {} ({} mapped slaves)
diag.wkc_actual_mirror(), diag.wkc_expected_mirror(), diag.mapped_slave_count());

if diag.wc_deficit() > 0 {
println!("⚠ WKC 缺额 {} — 有从站没在响应,逐个从站定位:", diag.wc_deficit()); // ⚠ WKC deficit {} — some slave is not responding, locating it slave by slave:
for i in 1..=master.slave_count() {
let slave = master.slave(i);
if slave.wc_contributed() == WcContribution::NotContributed {
println!(" 从站 {} 未贡献 WKC", i); // Slave {} is not contributing WKC
}
}
}
Per-slave WKC contribution

Use slave.wc_contributed() (the WcContribution enum) for a single slave's contribution state. When wc_deficit() > 0, iterate the slaves to locate the missing one.

WKC model ledger and unreachable slaves​

WKC accounting entry points on EtherCATMaster (they do not go through diagnostics_info()). These readings separate the "model ledger" from "this cycle's measurement": the model ledger is computed from the topology union and can be read at any time; this cycle's measurement still comes from wkc_actual_mirror() / wkc(), and the two are not interchangeable.

CategoryMethodTypeR/WDescription
Model ledgereffective_wkc_cycle()u16read-onlyEffective WKC of the topology union (each slave counted at most once). This is the model ledger, not this cycle's measurement
Expected snapshotwkc_expected_cycle()u16read-onlyExpected WKC snapshot for this cycle
Unreachableunreachable_wkc_count()u16read-onlyNumber of slaves judged unreachable in this cycle. 0 = no unreachable slave, not "not measured"
Per-leg readingprimary_wkc()u16read-onlyPrimary-port WKC. Peak-held across cycles: it does not drop within the hold window after a slave is pulled, so it can only answer "how many were reached once" and cannot serve as this cycle's measurement
Collection hookrecord_wkc(wkc)()writeRecords one working counter sample into the diagnostics statistics; the collecting side calls it once per cycle, it reads no bus and changes no control state
Validated setset_expected_wkc_checked(expected)Result<()>writeValidates first, then publishes the expected WKC; when validation fails it returns Err and publishes nothing
pub fn effective_wkc_cycle(&self) -> u16
pub fn wkc_expected_cycle(&self) -> u16
pub fn unreachable_wkc_count(&self) -> u16
pub fn set_expected_wkc_checked(&self, expected: u16) -> Result<()>
pub fn primary_wkc(&self) -> u16
pub fn record_wkc(&self, wkc: u16)
The per-leg reading carries no master index

primary_wkc() reads a process-global value and carries no master index; in a multi-master setup, to read "right now" use wkc_actual_mirror() from diagnostics_info() (aggregated) or wkc().

Example:

let diag = master.diagnostics_info();

println!("模型账有效 WKC: {}", master.effective_wkc_cycle()); // Model-accounted effective WKC: {}
println!("期望快照: {}", master.wkc_expected_cycle()); // Expected snapshot: {}
println!("不可达站数: {}", master.unreachable_wkc_count()); // Unreachable station count: {}

// Sent after verification (nothing is sent when verification fails)
if let Err(e) = master.set_expected_wkc_checked(master.wkc_expected_cycle()) {
println!("期望 WKC 未下发: {}", e); // Expected WKC not issued: {}
}

// Branch reading (sticky peak convention, not a measurement of this tick)
println!("主口 WKC(粘峰): {},本拍聚合实测: {}", // Primary port WKC (sticky peak): {}, aggregate measured this tick: {}
master.primary_wkc(), diag.wkc_actual_mirror());

Per-slave WKC probe​

The per-slave probe sends a separate read-only probe frame to one slave and gets back "that slave's own" WKC: the WKC of that datagram counts only this slave, so it is not diluted by other slaves failing to respond. The probe is off by default; while it is off no frames are sent and the main loop behaves unchanged; it is read-only, writes no outputs and no registers, and does not enter any aggregate WKC accounting.

MethodReturnsDescription
slave_wkc_probe_actual(si)WkcProbeSampleWKC measured by that slave's most recent probe. Value(0) = an echo came back but this slave did not contribute (a valid true value); SentNoEcho = sent but no echo; NoSample = no sample (not enabled / not this slave's turn / this slave cannot be probed / out of range)
slave_wkc_probe_expected(si)WkcProbeSampleExpected WKC for that slave's probe. Value(1) = this slave has a read mapping; NoSample = cannot be probed (no read mapping / out of range)
slave_wkc_probe_sample_age_ms(si)Option<u32>Milliseconds since the most recent sample. None = never sampled, not 0 milliseconds
per_slave_wkc_probe_mode()u16Probe mode: 0 = off (default) / 1 = read-only probe. Only these two values are valid; any other value (including the unavailable level of all 1s) is treated as "unknown", never as off
set_per_slave_wkc_probe_mode(mode)boolSets the mode. true = read back and confirmed in effect; false = the invalid mode was rejected or it is not confirmed in effect
pub fn slave_wkc_probe_actual(&self, si: u16) -> WkcProbeSample
pub fn slave_wkc_probe_expected(&self, si: u16) -> WkcProbeSample
pub fn slave_wkc_probe_sample_age_ms(&self, si: u16) -> Option<u32>
pub fn per_slave_wkc_probe_mode(&self) -> u16
pub fn set_per_slave_wkc_probe_mode(&self, mode: u16) -> bool

si is the slave index (1-based). WkcProbeSample also has Unrecognized(i32) for raw values outside the table.

A negative sentinel is not 0

SentNoEcho / NoSample both mean "cannot be read", not 「WKC = 0」; only Value(0) is a valid true value. The display layer must not fold a negative sentinel into 0, nor treat NoSample as "this slave does not contribute".

Example:

use darra_ethercat::WkcProbeSample;

let diag = master.diagnostics_info();

// Enable the read-only probe (off by default); the return value is a read-back confirmation, not "the command was accepted"
if !diag.set_per_slave_wkc_probe_mode(1) {
println!("探针模式未确认生效,当前模式 {}", diag.per_slave_wkc_probe_mode()); // Probe mode not confirmed active, current mode {}
}

for i in 1..=master.slave_count() {
match diag.slave_wkc_probe_actual(i) {
WkcProbeSample::Value(wkc) => println!("从站 {}: 探针 WKC {}", i, wkc), // Slave {}: probe WKC {}
WkcProbeSample::SentNoEcho => println!("从站 {}: 已发无回声", i), // Slave {}: sent but no echo
WkcProbeSample::NoSample => println!("从站 {}: 无样本", i), // Slave {}: no sample
WkcProbeSample::Unrecognized(code) => println!("从站 {}: 表外值 {}", i, code), // Slave {}: out-of-table value {}
}
if let Some(age) = diag.slave_wkc_probe_sample_age_ms(i) {
if age > 1000 {
println!(" 样本已过期 {} ms", age); // Sample is {} ms stale
}
}
}

"Unknown" state of the secondary-port WKC​

RedundancyManager::secondary_wkc() is the current-sample measurement of the secondary-port working counter: if a fresh value was sampled this cycle it returns the measured value, otherwise it returns "unknown", never a stale full value and never a peak value carried across cycles.

CategoryMemberTypeR/WDescription
Redundancy WKCRedundancyManager::secondary_wkc()u16read-onlySecondary-port WKC measured in this cycle. Returns WKC_UNKNOWN when there is no fresh measurement this cycle
Redundancy WKCWKC_UNKNOWNu16 (0xFFFF)read-onlySentinel for "no measurement"; importable from the crate root
Redundancy WKCRedundancyManager::secondary_wkc_known()boolread-onlyWhether this cycle has a measurement. false means only that secondary_wkc() is WKC_UNKNOWN
Redundancy WKCRedundancyManager::secondary_wkc_rt()u16read-onlyFiltered live secondary-port value (drops in the same cycle when a slave is pulled / the link breaks); use this for "right now"

With a single NIC (no secondary leg configured), a return of 0 is a valid reading and counts as "known". Judging "unknown" therefore requires secondary_wkc_known(); neither "is the value 0" nor treating 0xFFFF as a full value works.

Do not use the wrong entry point

EtherCATMaster::secondary_wkc() reads a peak value held across cycles (it does not drop within the hold window after a slave is pulled) and is only good for historical reference, not as this cycle's measurement. To judge "unknown" or see "right now", use secondary_wkc() / secondary_wkc_known() / secondary_wkc_rt() on RedundancyManager.

Example:

use darra_ethercat::RedundancyManager;

let red = RedundancyManager::new(master.master_number());

if !red.secondary_wkc_known() {
println!("副口 WKC: 未知(本拍无实测)"); // Secondary port WKC: unknown (no measurement this tick)
} else if red.secondary_wkc() == 0 {
println!("副口 WKC: 0(单网口 / 副口本拍无贡献)"); // Secondary port WKC: 0 (single NIC / secondary port contributed nothing this tick)
} else {
println!("副口 WKC: {},实时值 {}", red.secondary_wkc(), red.secondary_wkc_rt()); // Secondary port WKC: {}, real-time value {}
}

Real OP determination (RealOp)​

"The AL status word reads OP" is not the same as "process data is really being exchanged this cycle". The status word sticks: after a slave drops out the AL status may still report OP, and the UI still shows "all OP" while the merged WKC is only 6/12. The per-slave "real OP" is given only by the SDK's per-slave decision.

  • Real OP criteria: the low 4 bits of the AL status = OP (0x08), the Error bit (0x10) = 0, and the slave is currently not lost;
  • AL status code is not checked: the AL Status Code does not take part in the real OP decision;
  • WKC contribution is display evidence only: whether a slave contributes WKC this cycle cannot be used to overturn the per-slave real OP conclusion;
  • No consecutive-cycle threshold: per-slave real OP does not require N consecutive cycles.

Master-level "real OP" is a separate gate (layered with the per-slave conclusion — neither replaces the other): every required slave (not optional and has process data) must be real OP, and the merged measured WKC must not fall below the fixed configuration-time expectation. Per-slave real OP on its own does not mean the whole machine is real OP.

This language does not expose GetMasterAlstatRefresh: the master AL-status refresh timestamp is only available on the C# (master.Diagnostics.TryGetMasterAlstatRefresh) and C (DarraEcat_GetMasterAlstatRefresh) public surfaces, and in the current version it always returns failure. There is no equivalent entry point in this language; do not call those two names. To detect a false OP, use the real-OP verdict on this page together with the group-level WKC.

Read-only decision; does not take part in control

This API group only decides and displays: it does not trigger recovery, stop PDO, drop out of OP, change expected values, or alter any existing control criterion. Missing evidence always yields RealOpReason::Unknown; cached or stale values are never passed off as real OP, and the expected WKC is never lowered.

Entry points​

CategoryMemberReturnsR/WDescription
Diagnosticsdiagnostics_info().real_op_truth()MasterRealOpTruthread-onlyCaptures one cycle; equivalent to capture_real_op_truth()
Diagnosticsdiagnostics_info().capture_real_op_truth()MasterRealOpTruthread-onlyCaptures the real OP truth for one cycle (master level + per slave)
Diagnosticsdiagnostics_info().evaluate_slave_real_op(i32)Option<SlaveRealOpState>read-onlySingle-slave decision; None = cannot evaluate, reported as unknown
Diagnosticsdiagnostics_info().evaluate_real_op(&[SlaveRealOpEvidence], i32, i32)MasterRealOpTruthread-onlyEvaluate from same-cycle evidence (no re-read when a snapshot already exists)

The only per-slave criterion is the per-slave decision result; the only master-level criterion is the counts and flags of the master-level decision. The master_index in the evidence must be filled in (if missing, Unknown is returned as-is). The application layer does not need to — and should not — write its own "is this real OP" check.

Reason enum​

RealOpReason (repr(u8); the values map one-to-one to the other language SDKs)

ValueNameMeaning
0OkReal OP: the per-slave decision is real OP
1AlNotCleanThe slave is not in clean OP (not in the OP base state / Error bit set / dropped out)
2NoContributionLegacy reason code: no longer produced by the per-slave decision (value kept for compatibility)
3UnstableLegacy reason code: no longer produced by the per-slave decision (value kept for compatibility)
4WkcDeficitMaster level: all required slaves are real OP, but the merged measured WKC is below the fixed expectation
5UnknownInsufficient evidence (criterion unavailable / no master context / no required slaves)

Result structs​

MasterRealOpTruth (Category: diagnostics; R/W: read-only)

FieldTypeDescription
sequencei64Evaluation sequence number, monotonically increasing per master
real_opboolMaster-level real OP
reasonRealOpReasonPrimary reason the master-level result does not hold
required_counti32Number of required slaves
real_op_counti32Number of required slaves that are real OP
failed_counti32Number of required slaves that are not real OP
wkc_actuali32Merged measured WKC (as measured)
wkc_expectedi32Fixed configuration-time expected WKC (never lowered)
wkc_deficiti32Deficit = expected − actual (≤0 means no deficit)
slavesVec<SlaveRealOpState>Per-slave results
detail_textStringHuman-readable detail (master conclusion + list of failing slaves + WKC comparison)

SlaveRealOpState (Category: diagnostics; R/W: read-only)

FieldTypeDescription
slave_indexi32Slave index (1-based)
requiredboolWhether the slave takes part in the master-level decision (not optional and has PDO)
al_clean_opboolWhether the slave is in clean OP this cycle (low 4 bits = OP and Error bit = 0 and not lost; AL status code excluded)
contributedboolContributes WKC this cycle — display evidence only, not part of the decision
real_opboolReal OP for this slave
reasonRealOpReasonReason it does not hold (Ok when real OP)
detailStringHuman-readable reason detail (not part of the decision)

Example:

let truth = master.diagnostics_info().real_op_truth();

if truth.real_op {
println!("真 OP: 必需站 {}/{}, WKC {}/{}", // Real OP: required slaves {}/{}, WKC {}/{}
truth.real_op_count, truth.required_count, truth.wkc_actual, truth.wkc_expected);
} else {
println!("非真 OP [{:?}] {}", truth.reason, truth.detail_text); // Not real OP [{:?}] {}
for s in &truth.slaves {
if s.required && !s.real_op {
println!(" 从站 {}: {:?} — {}", s.slave_index, s.reason, s.detail); // Slave {}: {:?} — {}
}
}
}

Hot-plug (automatic)​

When slaves are plugged or unplugged on site while the system runs, the master handles it itself: a declared module whose identity verifies is discovered, configured and promoted to OP automatically by the StateGuard in the OP steady state (within about 1 second). No state-change command is sent to healthy OP slaves and the PDO cycle keeps running. There is no public rebuild trigger.

Cases that are not handled automatically are reported truthfully and the operator re-scans after fixing them: a mid-chain insertion that shifts physical positions (re-scan requested, no address stealing), an extra device not declared in DENI, an identity mismatch, or ambiguous ownership with several identical modules.

Automatic rebuild observation​

pub fn hot_swap_rescan_count(&self) -> u32
pub fn last_hot_swap_rescan_result(&self) -> HotSwapCode
pub fn last_hot_swap_rescan_time_ms(&self) -> i64
Automatic rebuilds have no public trigger

The only trigger lives in the kernel StateGuard. User space has no rebuild function, no switch and no period setting; these three methods only read the kernel accounting, with zero frames.

Example:

let diag = master.diagnostics_info();
println!("自动重建 {} 轮,上次结果 {},时刻 {}", // Auto-rebuild {} rounds, last result {}, at {}
diag.hot_swap_rescan_count(),
diag.last_hot_swap_rescan_result().description(),
diag.last_hot_swap_rescan_time_ms());

Rescan accounting​

hot_swap_rescan_count() / last_hot_swap_rescan_result() / last_hot_swap_rescan_time_ms() are the read-only observation surface of automatic rebuilds.

MethodReturnsDescription
hot_swap_rescan_count()u32Completed automatic rebuild rounds (rejected before execution do not count). 0 = never
last_hot_swap_rescan_result()HotSwapCodeLast result code. Ok means both "last succeeded" and "never happened"; disambiguate with rounds / time. Other variants: Busy / RescanZero (R0: do not blame the link) / NotInOp / IndexFull / BadIndex / NotInitialized
last_hot_swap_rescan_time_ms()i64Last completion time (Unix ms UTC). 0 = never

An advancing round count means the kernel really ran an automatic rebuild; a steady count means none happened.

pub fn hot_swap_rescan_count(&self) -> u32
pub fn last_hot_swap_rescan_result(&self) -> HotSwapCode
pub fn last_hot_swap_rescan_time_ms(&self) -> i64

Example:

let diag = master.diagnostics_info();

let done = diag.hot_swap_rescan_count();
let last = diag.last_hot_swap_rescan_result();
let at = diag.last_hot_swap_rescan_time_ms();

if done == 0 || at == 0 {
println!("还没有发生过自动重建"); // No auto-rebuild has happened yet
} else {
println!("已自动重建 {} 轮,末次 {},结果 {}", done, at, last.description()); // Auto-rebuilt {} rounds, last one {}, result {}
}
MethodReturnsDescription
primary_phy_link_state() / secondary_phy_link_state()PhyLinkStatePrimary/secondary port physical link: Up=1, Down=0, Unknown=-1
master.secondary_frame_link_state()PhyLinkStateFrame-level secondary-port link tri-state; use separately from the physical-layer reading
phy_link_bitmask()u32Dual-port bitmask: bit0 = primary port Up, bit1 = secondary port Up; 0xFFFF = not observable

Unknown only means the value cannot be read or has not been decided yet (older runtime, frame-level link not yet resolved); it does not mean Down. Do not report a link break, slave loss or fault handling based on it. Only an explicit Down means the link is down.

let diag = master.diagnostics_info();
if diag.primary_phy_link_state() == PhyLinkState::Down {
println!("主口明确 Down"); // Primary port definitively down
} else if diag.primary_phy_link_state() == PhyLinkState::Unknown {
println!("主口状态未知"); // Primary port state unknown
}

master.secondary_link_status() is a compatibility boolean health check: true only for an explicit Up; both Down and unknown give false. To tell the latter two apart, call secondary_frame_link_state().

Link-break events are written by the collection path into a fixed-capacity ring queue, and reads go through a seq cursor: note the current token first, then use it as since_seq to pull incrementally, so no event is processed twice.

MethodReturnsDescription
link_diag_event_count()u32Total event count (including history from before the ring overwrote it)
link_diag_seq()u32Freshness token of the event ring. Monotonically increasing = the event ring is being written; no longer increasing = the recording side is not running
link_diag_events(since_seq)Vec<LinkDiagEvent>New events read from since_seq onwards; an empty Vec when there are none. At most 256 per call; when there are more, continue with the seq of the last returned event

LinkDiagEvent (darra_ethercat::utils::LinkDiagEvent):

FieldTypeDescription
t_usu64Event time (µs)
sequ32Event sequence number, used as the next since_seq cursor
kindu8Event type, see the table below
port / from_state / to_stateu8Port number and the state before / after the change
a_peer / a_self / b_peer / b_selfu16Peer and local slave-number evidence for each of the two ports
ring_intact / is_upu8Whether the ring is intact and whether the link is Up
effective_wkc / expected_wkcu16Effective WKC and expected WKC for this cycle
kindMeaning
1A-port link down
2B-port link down
3Link down in the middle segment
4Healthy
5Total loss of contact
6A-port physical layer
7B-port physical layer
8Primary / secondary switchover
9Recovery
10Rapid flapping
11WKC combination

Example:

let diag = master.diagnostics_info();
let mut cursor = 0u32;

loop {
let events = diag.link_diag_events(cursor);
if events.is_empty() {
println!("无新事件;令牌 {},累计 {}", // No new events; token {}, cumulative {}
diag.link_diag_seq(), diag.link_diag_event_count());
break;
}
for ev in &events {
println!("[{}] kind={} port={} WKC {}/{}",
ev.t_us, ev.kind, ev.port, ev.effective_wkc, ev.expected_wkc);
cursor = ev.seq;
}
if events.len() < 256 {
break; // This batch is not full, which means everything has been read
}
}

NIC health check​

All three entry points live on diagnostics_info() and only judge whether the NIC data plane is healthy: the first two are read-only diagnostics, and the SDK never restarts, disables or enables a NIC by itself; only auto_recover_nic() performs one explicit soft restart.

MethodReturnsDescription
diagnose_nic_health()Result<NicHealth>Read-only health verdict: Ok / PrimaryBad / SecondaryBad / BothBad; raw values outside the table land in Unrecognized(i32); -1 → Err, never folded into Ok
verify_nic_health(num_probes, timeout_ms)Result<NicProbeVerdict>Active probe: sends probe packets the given number of times and waits for returned frames, returning synchronously. Healthy / PrimaryTx / PrimaryRx / SubmitPathDead / Secondary; values outside the table land in Unrecognized(i32); -1 → Err
auto_recover_nic()Result<()>The only entry point that performs one explicit soft restart. Ok only when the underlying layer explicitly reports success; everything else is Err(DiagnosticsFailed)
pub fn diagnose_nic_health(&self) -> Result<NicHealth>
pub fn verify_nic_health(&self, num_probes: i32, timeout_ms: i32) -> Result<NicProbeVerdict>
pub fn auto_recover_nic(&self) -> Result<()>
Scope and calling discipline

Both read-only entry points are meaningful only in real-time operation mode; in non-real-time operation mode no conclusion is available (the underlying layer returns -1), which appears as Err on the Rust side, not Ok, and does not mean the NIC is healthy. auto_recover_nic() is a synchronous call and the SDK never triggers it on its own; for NIC binding problems use the official installer, and do not call the recovery entry point repeatedly in business code.

Example:

use darra_ethercat::{NicHealth, NicProbeVerdict};

let diag = master.diagnostics_info();

match diag.diagnose_nic_health() {
Ok(NicHealth::Ok) => println!("双口健康"), // Both ports healthy
Ok(NicHealth::PrimaryBad) => println!("主口异常"), // Primary port abnormal
Ok(NicHealth::SecondaryBad) => println!("副口异常"), // Secondary port abnormal
Ok(NicHealth::BothBad) => println!("双口异常"), // Both ports abnormal
Ok(NicHealth::Unrecognized(code)) => println!("表外判决 {}", code), // Out-of-table verdict {}
Err(e) => println!("读不到结论: {}", e), // Could not read a verdict: {}
}

match diag.verify_nic_health(5, 200) {
Ok(NicProbeVerdict::Healthy) => println!("主动探测通过"), // Active probe passed
Ok(NicProbeVerdict::PrimaryTx) => println!("主口发送路径异常"), // Primary port transmit path abnormal
Ok(NicProbeVerdict::PrimaryRx) => println!("主口接收路径异常"), // Primary port receive path abnormal
Ok(NicProbeVerdict::SubmitPathDead) => println!("提交路径不通"), // Submit path dead
Ok(NicProbeVerdict::Secondary) => println!("副口路径异常"), // Secondary port path abnormal
Ok(NicProbeVerdict::Unrecognized(code)) => println!("表外结论 {}", code), // Out-of-table conclusion {}
Err(e) => println!("探测被拒: {}", e), // Probe rejected: {}
}

// Explicit recovery: call only when really needed; the SDK does not call it itself
if diag.auto_recover_nic().is_ok() {
println!("软重启已完成"); // Soft restart complete
}

Port topology static model (ring / branch / chain forms)​

The static port topology model is computed by the SDK; callers only assemble the input from this cycle's readings and always read the output fields through RingBranchInfo, without any second-guessing. It is not the same encoding as the runtime form topology_mode: the static model has only three levels — 0 = no ring / 1 = ring / 2 = ring + branch — while the runtime form has an extra 3 = ring degraded to a line; never cast between them directly. When the model is unknown (mode is None) it must not be treated as linear.

Entry points​

MethodReturnsDescription
master.slave_topology().compute_ring_branch_ex()Result<RingBranchInfo, c_int>Assembles the input from the already-built topology nodes; read-only, changes no state
slave::topology::compute_ring_branch_ex(&[TopoRingSlaveIn])Result<RingBranchInfo, c_int>Free function; pass each slave's port input directly; read-only, changes no state

Both call paths (method form / free-function form) have the same semantics and produce the same output structure. Always read the output fields through RingBranchInfo.

Input fields (TopoRingSlaveIn)​

FieldTypeDescription
slave_numu16Slave index
phys_apu8Physical port mask, bit0..3 = P0..P3; 0 = no physical link on that port. Must be the port mask read from DL status this cycle, never a cached historical value
entry_portu8Entry port 0..3; 0xFF = unknown / not filled in
parentu16Parent slave index; 0 = root (hangs directly on the master's primary port)
parent_portu8Port 0..3 on which this slave connects to its parent; 0xFF = unknown / not filled in

Output fields (RingBranchInfo)​

FieldTypeDescription
total_counti32Total slaves
ring_counti32Number of ring members; available only when the model computed it
branch_counti32Branch count = total_count − ring_count
closure_slave_numi32Closure point slave index; -1 = no closure point. Not readable when the model is unknown
mode_rawi32Raw mode value for reconciliation; no remapping is applied
modeOption<TopoRingMode>The strictly mapped form; None = raw value out of range or not obtained (not folded into linear)
chain_formOption<TopoChainForm>Sub-form when there is no ring; interpreted only when mode == Some(TopoRingMode::Linear)
ring_slave_numsVec<u16>Ring member slave indices (in walking order from the closure point → root)

chain_form values​

ValueEnumMeaning
None—Not applicable: mode is not Some(TopoRingMode::Linear), or the raw value is out of range (not applicable, no guessing)
0TopoChainForm::LinearLinear: the end is a single active port and all slaves are chained
1TopoChainForm::FoldbackChain (foldback at end): the end port folds back internally; frames are sent on the primary port and received on the secondary port, so the whole chain is traversed twice

Must read:

  • chain_form is interpreted only when mode == Some(TopoRingMode::Linear); under ring / ring + branch the SDK writes 0, which is a placeholder and does not mean linear.
  • Both linear and chain (foldback at end) have no ring.
  • Chain (foldback at end) has only one physical path end to end and no redundancy protection; do not treat it as the sole criterion for whether redundancy exists.
  • When it returns Err(_) the SDK writes no output fields, and no field may be used as a conclusion.

Return codes​

ReturnsMeaning
Ok(RingBranchInfo)Returns 0: every slave has a definite membership and the conclusion is backed by this cycle's measurements
Err(-1)Parameter error (including SDK not ready)
Err(-2)Missing measured port evidence (any slave has phys_ap == 0)
Err(-3)Degenerate topology input that cannot be proven (invalid / duplicate slave indices, too many closure candidates, broken closure chain)
Err(-4)Reachability undetermined overall (UNKNOWN slaves / mutually exclusive closure candidates / insufficient link evidence)

Both call paths return the same set of codes. When slaves is empty a default empty model is returned directly (no query is made): total_count / ring_count / branch_count are 0, closure_slave_num and mode_raw are -1, and mode / chain_form are None.

Example:

use darra_ethercat::slave::topology::{TopoChainForm, TopoRingMode};

let info = master.slave_topology().compute_ring_branch_ex()?;

match info.mode {
Some(TopoRingMode::Linear) => match info.chain_form {
Some(TopoChainForm::Linear) => println!("线性:全站串联,末端为活动口"), // Linear: all stations in series, the end is an active port
Some(TopoChainForm::Foldback) => println!("链式(末端折返):无冗余保护"), // Chain (foldback at the end): no redundancy protection
None => println!("不适用:非线形态下 chain_form 无意义"), // Not applicable: chain_form is meaningless outside a linear form
},
Some(TopoRingMode::Ring) => println!("环形:环上 {} 站", info.ring_count), // Ring: {} stations on the ring
Some(TopoRingMode::RingBranch) => println!(
"环+分支:环上 {} 站,分支 {} 站", // Ring + branches: {} stations on the ring, {} on branches
info.ring_count, info.branch_count
),
None => println!("静态模型未知(mode_raw = {})", info.mode_raw), // Static model unknown (mode_raw = {})
}

New code should use compute_ring_branch_ex throughout.

P1 foldback and measured ring topology​

topo_p1_* are read-only properties of the "foldback at the end" requirement in a dual-port ring + branch topology. They are unavailable whenever this round has not been calibrated or the topology is not dual-port ring + branch; do not treat unavailable as a measured value.

MethodReturnsDescription
topo_p1_foldback_mode()Result<TopoP1Mode>Foldback requirement mode: None = no foldback requirement or not calibrated this round; SingleNic = single port; DualRingBranch = dual-port ring + branch. Invalid master index → Err (not mode None); value outside the table → Err
topo_p1_measured()Option<bool>Whether the on-site port auto-increment measurement really ran this round. Some(false) = definitely did not run; None = invalid index (not "not measured")
topo_p1_ring_end_adp()Option<i32>Foldback end address. None = unavailable (not calibrated / not dual-port ring + branch / invalid index), not the measured value -1
topo_p1_full_wkc()Option<i32>Full WKC measured at the foldback position. None = unavailable
topo_measured_ring_count()Option<i32>Number of slaves on the measured ring. 0 is a valid measured value; None = unavailable. Branch count = topo_p1_full_wkc() − this value
pub fn topo_p1_foldback_mode(&self) -> Result<TopoP1Mode>
pub fn topo_p1_measured(&self) -> Option<bool>
pub fn topo_p1_ring_end_adp(&self) -> Option<i32>
pub fn topo_p1_full_wkc(&self) -> Option<i32>
pub fn topo_measured_ring_count(&self) -> Option<i32>

Example:

use darra_ethercat::TopoP1Mode;

let diag = master.diagnostics_info();

match diag.topo_p1_foldback_mode() {
Ok(TopoP1Mode::None) => println!("无折返需求(或本轮未标定)"), // No foldback needed (or not calibrated this round)
Ok(TopoP1Mode::SingleNic) => println!("单口折返"), // Single-NIC foldback
Ok(TopoP1Mode::DualRingBranch) => println!("双口环+分支折返"), // Dual-NIC ring + branch foldback
Err(e) => println!("读不到折返模式: {}", e), // Could not read the foldback mode: {}
}

if diag.topo_p1_measured() == Some(true) {
println!("末端地址 {:?},满 WKC {:?},环上站数 {:?}", // End address {:?}, full WKC {:?}, stations on the ring {:?}
diag.topo_p1_ring_end_adp(), diag.topo_p1_full_wkc(), diag.topo_measured_ring_count());
} else {
println!("本轮未做现场实测"); // No on-site measurement was done this round
}

Per-slave liveness reason / clean OP / SYNC0 armed​

The SDK decides per-slave liveness reason, clean OP and SYNC0 armed status, exposed through public APIs:

CapabilityPublic entry pointDescription
Clean OPdiagnostics_info().real_op_truth() / evaluate_slave_real_op(i)Per-slave real OP conclusion; see "Real OP determination" above
SYNC0 armedslave.diagnostics().dc().dc_sync0_armed()Tri-state: Some(true) SYNC0 is committed; Some(false) known not armed; None = cannot determine
Liveness / offline reasonslave.events().try_get_slave_offline_reason()Returns SlaveOfflineReason
Common rules
  • On query failure, no output is written; the public API returns None / Unknown and callers must not treat stale values as this cycle's conclusion.
  • "Unknown" never equals false: with insufficient evidence the conclusion is "unknown", not "neither leg is reachable / not armed / not clean". Conservative handling means no re-routing and no duplicate sending.

Liveness reason​

SlaveOfflineReason has only three values, and the events and the query API share the same conclusion:

ReasonMeaningConclusion
UnknownInsufficient evidence, cannot confirmNot judged as really offline
RealOfflineConfirmed offlineOffline
UnreachableNot confirmed, but process data is still being contributedNot judged as really offline

The query API is read-only: it sends no frames and changes no state. A failed query is treated as "unknown".

SYNC0 armed semantics​

  • Some(true) means only that the slave commits to producing SYNC0 (the configuration is in place); it does not mean the whole network clock has converged (check the sync window status for that).
  • A slave with DC disabled counts as not armed; that is a normal conclusion, not an error.
  • Read-only: changes no state. When it cannot be determined the public API gives None (unknown conclusion) and does not fold it into Some(false).

Example:

// clean OP conclusion (see above)
let truth = master.diagnostics_info().real_op_truth();
for s in &truth.slaves {
println!("从站 {}: real_op={}", s.slave_index, s.real_op); // Slave {}: real_op={}
}

// SYNC0 armed tri-state
let slave = master.slave(1);
match slave.diagnostics().dc().dc_sync0_armed() {
Some(true) => println!("SYNC0 已武装(承诺产生 SYNC0,不代表整网收敛)"), // SYNC0 armed (this promises SYNC0 output; it does not mean the whole network has converged)
Some(false) => println!("确知未武装"), // Definitively unarmed
None => println!("无法判定,结论未知"), // Cannot be determined, verdict unknown
}

// offline / liveness reason
if let Some(reason) = slave.events().try_get_slave_offline_reason() {
println!("离线原因: {:?}", reason); // Offline reason: {:?}
}

Diagnostics snapshot​

get_snapshot()​

pub fn get_snapshot(&self) -> DiagnosticsSnapshot

Takes a consistent snapshot of the diagnostics data. All current diagnostic metrics are copied into a separate struct so that repeated reads of the live process image do not disagree. Suited to UI refresh, logging and similar scenarios.

Returns:

pub struct DiagnosticsSnapshot {
pub frequency: i32, // application-level frame rate (Hz)
pub error_count: u32, // cumulative error count
pub packet_loss_rate: f32, // packet loss rate (0.0 ~ 1.0) — TX vs RX 5s sliding window
pub late_frame_rate: f32, // late frame rate (0.0 ~ 1.0) — index leaving the 8-frame window is stale, not counted as loss
pub avg_jitter_us: f64, // average jitter (µs)
pub mailbox_latency_us: f64, // mailbox send/receive latency — maximum (µs, settled over 1 second)
pub mailbox_latency_avg_us: f64, // mailbox send/receive latency — average (µs, settled over 1 second)
pub cycle_time_us: i32, // actual cycle time (µs)
pub wkc_actual: u16, // current working counter
pub wkc_expected: u16, // expected working counter
pub bus_cycle_hz: u32, // bus frame send rate (Hz, RT layer)
pub bus_max_jitter_us: f64, // maximum bus jitter (µs, RT layer)
pub bus_avg_jitter_us: f64, // average bus jitter (µs, RT layer)
pub bus_roundtrip_us: f64, // frame round-trip latency (µs)
pub bus_load_percent: f64, // communication load (%) — RTT / cycle × 100
pub smi_count: u32, // cumulative SMI count
pub smi_peak_us: f64, // SMI peak jitter (µs)
pub primary_port_ok: bool, // whether the primary port is OK
pub secondary_port_ok: bool, // whether the secondary port is OK
pub redundancy_active: bool, // redundancy protection running (RingMode >= 1 and frames on both ports; always false for linear / foldback at end)
}

Example:

let diag = master.diagnostics_info();
diag.set_enabled(true);

// take a consistent snapshot for UI refresh
let snapshot = diag.get_snapshot();
println!("频率: {} Hz, 丢包: {:.2}%, 抖动: {:.2}us", // Frequency: {} Hz, packet loss: {:.2}%, jitter: {:.2}us
snapshot.frequency,
snapshot.packet_loss_rate * 100.0,
snapshot.avg_jitter_us);

if snapshot.wkc_actual != snapshot.wkc_expected {
println!("WKC 不匹配: {}/{}", snapshot.wkc_actual, snapshot.wkc_expected); // WKC mismatch: {}/{}
}

DC synchronization​

Automatic monitoring (ETG.1500 5.13.3) checks each slave's time deviation once per second. When it exceeds the sync_window_threshold() threshold, the on_dc_sync_lost event fires.

sync_window_threshold() / set_sync_window_threshold()​

pub fn sync_window_threshold(&self) -> i32
pub fn set_sync_window_threshold(&self, ns: i32)

Sync window threshold in nanoseconds; default 1000ns. Exceeding the threshold fires the DCSyncLost event.

Single slave

For a single slave's sync state use slave.diagnostics().dc().is_in_sync() and slave.diagnostics().dc().sync_time_difference().

DC diagnostics 2-second snapshot​

pub fn dc_diagnostics(&self) -> DcDiagnosticsSnapshot

Assembles the per-slave and master-level DC conclusions in one go: a 2-second TTL, with all callers sharing the same snapshot within the same 2 seconds, so each UI column does not read its own set and split the numbers. The snapshot is assembled from diagnostics data already available locally (slave structure / sync window status / 2-second sampling history), sends no bus frames, and can be read directly on the UI thread. History-style fields (frozen readings / jitter / convergence) accumulate from the 2-second sampling; reading a single slave's property surface directly does not include these historical conclusions.

CategoryFieldTypeR/WDescription
DC diagnosticscaptured_at_utcSystemTimeread-onlyTime this snapshot was assembled
DC diagnosticsall_in_syncOption<bool>read-onlyWhether all SYNC0 participants are inside the window. No confirmed participants = None, not true; participants exist but were not sampled / cannot be read → false; any DC slave with unknown armed state → conservatively false
DC diagnosticsmax_drift_nsOption<i32>read-onlyLargest absolute sync difference across all usable windows. No usable window at all = None, not 0
DC diagnosticssync_window_threshold_nsOption<i32>read-onlySync window threshold (ns); None = cannot read
DC diagnosticsreference_clockDcReferenceClockInforead-onlyReference clock facts: slave_index / tier / tier_text / is_chain_head_fallback; when there is no reference clock this is an explicit none() instance
DC diagnosticsarmed_slave_counti32read-onlyNumber of slaves with SYNC0 armed (sync0_armed == Some(true)); 0 is a valid count
DC diagnosticsactive_slave_counti32read-onlyNumber of DC-active slaves (0x0980 value in effect is not 0); 0 is a valid count
DC diagnosticsarmed_unknown_counti32read-onlyNumber of slaves whose armed conclusion is unknown (cannot be determined)
DC diagnosticsarmed_sync_participant_counti32read-onlyNumber of sync participants (armed and not the reference clock); 0 = no slave on this network can carry a "sync conclusion"
DC diagnosticsapplicable_window_counti32read-onlyNumber of slaves with a usable measured window; 0 = max_drift_ns is None
DC diagnosticsactive_without_process_data_counti32read-onlyNumber of slaves that are DC-active but have no process data bytes (risk of hard DC failure)
DC diagnosticsexpected_wkcu16read-onlyMaster expected WKC (the fixed configuration-time value); compare with armed_slave_count to see WKC coverage of the DC slaves
DC diagnosticspropagation_delay_resolved_at_utc / propagation_delay_resolve_countOption<SystemTime> / i32read-onlyPropagation delay resolution accounting. This language does not implement that accounting: always None / 0; the reason is in DC_PROPAGATION_DELAY_TRACKING_UNAVAILABLE_REASON; 0 does not mean it was never measured
DC diagnosticsslavesVec<DcSlaveSnapshot>read-onlyPer-slave snapshots (ascending by slave index, no placeholder rows). Per-slave fields: slave_index / name / has_dc / capability / arm_outcome (always None) / assign_activate / sync0_cycle_ns / sync1_cycle_ns / shift_ns / propagation_delay_ns / propagation_delay_origin / sync0_armed / sync_window / jitter / convergence_ms / convergence_measured_at_utc / output_bytes / input_bytes / is_dc_active / is_reference_clock
DC diagnosticsfind(index)Option<&DcSlaveSnapshot>read-onlyFetch one slave's snapshot by slave index; out of range / not sampled returns None
DC diagnosticsany_read_failureboolread-onlyAt least one slave / the reference clock failed to read this cycle (failures are recorded as Unknown / None)
DC diagnosticshas_dcboolread-onlyA slave with DC capability exists on the network (capability-bit basis); does not mean it is enabled

The master level has direct entry points too (all from the same 2-second snapshot): master.diagnostics_info().dc_armed_slave_count() / master.diagnostics_info().dc_active_slave_count(); the reference clock and threshold come from MasterDC::new(master.index()).reference_clock_info() / MasterDC::new(master.index()).dc_sync_window_threshold_ns().

Tri-state convention

all_in_sync / max_drift_ns / per-slave sync0_armed are all tri-state; None means "no conclusion" and must not be folded into false / 0. The older summary surface (which defaults to 0 / true when there is no DC) cannot be used as a tri-state.

DC summary readings (1-second settlement)​

These three readings come from the diagnostics summary, settled once per second by the collection thread (lagging by up to about 1 second); to get the latest value immediately, call master.update_diagnostics_snapshot() first.

MethodReturnsDescription
dc_has_dc()boolWhether DC slaves exist on the network (capability-bit basis); does not mean they are enabled. Unreadable summary = false
dc_max_drift_ns()i32Current largest absolute system-time difference across all DC slaves (ns). 0 is the summary default and does not distinguish 「no DC slave / not armed / measured exactly 0」; for the tri-state use max_drift_ns from dc_diagnostics()
dc_reference_clock_slave()u16Reference clock slave index (1-based). 0 = no DC slave or the summary cannot be read

The reference clock itself is not counted in the measurement — by definition it has no synchronization error.

Auto offset and sync-loss callback​

MethodReturnsDescription
auto_calculate_dc_shift()Result<i32>Computes and applies the offset for all DC slaves immediately; Ok(已计算的站数); a negative value → Err
set_dc_auto_shift_enabled(enable)()Switch: run the offset calculation automatically once on the PreOp → SafeOp transition
dc_auto_shift_enabled()boolQueries the current state of that switch
set_dc_sync_lost_callback(callback)()Sets a process-level DC sync-loss callback (an associated function, with no master instance). It shares one callback slot with the events().on_dc_sync_lost() subscription; do not stack the two
pub fn auto_calculate_dc_shift(&self) -> Result<i32>
pub fn set_dc_auto_shift_enabled(&self, enable: bool)
pub fn dc_auto_shift_enabled(&self) -> bool
pub fn set_dc_sync_lost_callback(callback: DCSyncLostCallback)

The DCSyncLostCallback callback type takes (master_index: u16, slave_index: u16, diff_ns: i32). For long-term monitoring, use the event subscription directly; it manages the subscription lifetime per master.

Example:

use darra_ethercat::DCSyncLostCallback;

extern "C" fn on_dc_sync_lost(master_index: u16, slave_index: u16, diff_ns: i32) {
println!("主站 {} 从站 {} 失步 {} ns", master_index, slave_index, diff_ns); // Master {} slave {} out of sync {} ns
}

let diag = master.diagnostics_info();

println!("有无 DC 从站: {},参考钟: {},最大偏差: {} ns", // DC slaves present: {}, reference clock: {}, max deviation: {} ns
diag.dc_has_dc(), diag.dc_reference_clock_slave(), diag.dc_max_drift_ns());

// Compute the offset once manually; with the auto switch on it runs automatically on the PreOp → SafeOp transition
let _ = diag.auto_calculate_dc_shift();
diag.set_dc_auto_shift_enabled(true);
println!("自动偏移: {}", diag.dc_auto_shift_enabled()); // Auto shift: {}

EtherCATMaster::set_dc_sync_lost_callback(on_dc_sync_lost);

Redundancy status​

redundancy_active()​

pub fn redundancy_active(&self) -> bool

Redundancy protection running = redundancy_ring_mode() is Dual or Degraded and both the primary and secondary ports carried frame traffic within this window. In a chain (foldback at end) topology frames are sent on the primary port and received on the secondary port, the whole chain is traversed twice and both ports carry frames, but physically there is no second independent path — this method returns false, matching the redundancy_ring_mode() == Inactive convention.

To see "whether both ports carry frames", read primary_port_ok / secondary_port_ok and the primary / secondary port TX/RX counters directly; do not infer it from this method. slave.diagnostics().redundancy_activated() is the same master-level criterion (RingMode >= 1), not an independent per-slave conclusion.

redundancy_ring_mode()​

// entry point on EtherCATMaster, returns the raw i32 value
pub fn redundancy_ring_mode(&self) -> i32

Ring-topology redundancy operating mode. The strongly typed RingMode enum is available through master.diagnostics_info().redundancy_ring_mode().

Related structs:

#[repr(i32)]
pub enum RingMode {
Inactive = 0, // not active: redundancy monitoring not initialized
Dual = 1, // bidirectional redundancy: sending on both ports, normal operation
Degraded = 2, // degraded mode: the secondary link is unavailable, only the primary works
}

break_point()​

pub fn break_point(&self) -> Option<BreakPointInfo>

The current fault point (only the first fault is returned when there are several). Both link-down and CRC faults are supported; it clears automatically after recovery, and returns None when there is no fault.

None does not mean "no fault"

break_point() returning None means both "definitely no fault" and "query failed" (the return type has no third state). Use all_break_points() to tell them apart: None = query failed, Some(vec![]) = query succeeded and there is no fault.

Related structs:

pub struct BreakPointInfo {
pub slave_index: u16, // faulting slave index (1-based)
pub port: u8, // faulting port number (0-3, corresponding to P0-P3)
pub fault_type: u8, // fault type: 0 = link down, 1 = CRC fault
}

impl BreakPointInfo {
pub fn is_link_down(&self) -> bool; // whether this is a link-down fault (fault_type == 0)
pub fn is_crc_fault(&self) -> bool; // whether this is a CRC fault (fault_type == 1)
}

is_link_down() / is_crc_fault() must be called with parentheses.

Fault type notes:

  • Link down (fault_type=0) — the port's physical link is lost in DL Status; typical cases: cable unplugged, cable broken
  • CRC fault (fault_type=1) — port-level RxError + InvalidFrame keep growing; typical cases: poor contact, aging cable

Locating a faulty cable segment: when the facing ports of adjacent slaves report faults at the same time, the cable between them is suspect. A fault on one side only points to the connector on that port.

Example:

let diag = master.diagnostics_info();

// ring-topology redundancy mode
println!("冗余模式: {:?}", diag.redundancy_ring_mode()); // Redundancy mode: {:?}

if diag.redundancy_active() {
println!("冗余已激活"); // Redundancy active
}

if let Some(bp) = diag.break_point() {
println!("故障: {}", bp); // "slave 3 P1 link down" or "slave 3 P1 CRC fault"
if bp.is_crc_fault() { // method call, with parentheses
println!("建议检查线缆/连接器"); // Check the cable/connectors
}
}

Diagnostics counters carried with frames​

The redundant send path carries diagnostics along with frames, with two sets of process-level cumulative counters (independent of any particular master). The counters are always-on readings; the switch only controls whether per-cycle detail is accumulated in addition.

MethodReturnsDescription
piggyback_consume_counters()PiggybackConsumeCounters5 cumulative counters on the consuming side, see below
piggyback_call_counters()PiggybackCallCounters4 cumulative counters on the calling side, a different set from the consuming side
EtherCATMaster::set_piggyback_diag(enabled)()Process-level switch (no master instance) that decides whether per-cycle detail is accumulated in addition
EtherCATMaster::piggyback_diag_enabled()boolQueries the current state of that switch
pub fn piggyback_consume_counters(&self) -> PiggybackConsumeCounters
pub fn piggyback_call_counters(&self) -> PiggybackCallCounters

pub fn set_piggyback_diag(enabled: bool)
pub fn piggyback_diag_enabled() -> bool
pub struct PiggybackConsumeCounters {
pub calls: u32,
pub skip_ado: u32,
pub skip_len: u32,
pub skip_active: u32,
pub writes: u32,
}

pub struct PiggybackCallCounters {
pub call_total: u32,
pub op_branch: u32,
pub op_inactive: u32,
pub op_queued: u32,
}

Example:

let diag = master.diagnostics_info();

// Turn on per-cycle detail accumulation (process-wide, one setting takes effect globally)
EtherCATMaster::set_piggyback_diag(true);
println!("明细累计开关: {}", EtherCATMaster::piggyback_diag_enabled()); // Detailed accumulation switch: {}

let consume = diag.piggyback_consume_counters();
println!("消费侧: calls={} skip_ado={} skip_len={} skip_active={} writes={}", // Consumer side: calls={} skip_ado={} skip_len={} skip_active={} writes={}
consume.calls, consume.skip_ado, consume.skip_len, consume.skip_active, consume.writes);

let call = diag.piggyback_call_counters();
println!("调用侧: call_total={} op_branch={} op_inactive={} op_queued={}", // Caller side: call_total={} op_branch={} op_inactive={} op_queued={}
call.call_total, call.op_branch, call.op_inactive, call.op_queued);

Diagnostics control​

Properties marked "Yes" require set_enabled(true) to start periodic sampling; features marked "cannot stop" are always active.

enabled() / set_enabled()​

pub fn enabled(&self) -> bool
pub fn set_enabled(&self, enabled: bool)

Diagnostics data collection switch (off by default).

reset()​

pub fn reset(&self)

Resets all diagnostics statistics in one call (base statistics / PDO frame loss / DC sync window / port error counters of every slave).

When you need a narrower scope, use the two entry points on the master:

MethodReturnsUse
master.reset_diagnostics()()Reset only the master diagnostics counters
master.reset_slave_port_error_counters(slave_index)boolReset only the specified slave's port error counters
slave.diagnostics().reset_port_errors()()Slave-level reset of that slave's port errors

Collection switch, snapshot refresh and master frame statistics​

enabled() / set_enabled() on diagnostics_info() also have equivalent entry points on the master object; there are also two refresh entry points and one frame-statistics snapshot.

MethodReturnsDescription
master.diagnostics_enabled()boolCurrent state of the collection switch
master.set_diagnostics_enabled(enable)()Starts/stops diagnostics data collection (off by default); equivalent to diagnostics_info().set_enabled()
master.update_diagnostics_snapshot()()Settles the diagnostics summary once immediately. Summary-style readings are normally settled once per second by the collection thread; call this first when you need to "see it right now"
master.update_diagnostics_with_esc_errors()()Refreshes the diagnostics data and includes the ESC port error counters in this update
master.master_diag_data()Result<MasterDiagData>Master frame-statistics snapshot; on read failure → Err (DiagnosticsFailed)
pub fn diagnostics_enabled(&self) -> bool
pub fn set_diagnostics_enabled(&self, enable: bool)
pub fn update_diagnostics_snapshot(&self)
pub fn update_diagnostics_with_esc_errors(&self)
pub fn master_diag_data(&self) -> Result<MasterDiagData>

update_diagnostics_with_esc_errors() is the ESC error summary entry point: it refreshes the diagnostics data and settles each slave's port error counters into the same update, which suits calls before and after bulk port-error reads; when you only need an ordinary snapshot, update_diagnostics_snapshot() is enough.

pub struct MasterDiagData {
pub cyclic_lost_frames: u32, // Number of lost cyclic frames
pub acyclic_lost_frames: u32, // Number of lost acyclic frames
pub cyclic_frames_per_sec: u32, // Cyclic frames per second
pub acyclic_frames_per_sec: u32, // Acyclic frames per second
pub master_state: u16, // Current master state
}

Example:

// Acquisition switch
master.set_diagnostics_enabled(true);
println!("采集开关: {}", master.diagnostics_enabled()); // Collection switch: {}

// Settle once immediately; use the other entry point when you need the ESC port errors too
master.update_diagnostics_snapshot();
master.update_diagnostics_with_esc_errors();

// Master frame statistics
match master.master_diag_data() {
Ok(d) => println!("周期帧 {}/s,非周期帧 {}/s,丢失 {}/{},状态 {}", // Cyclic frames {}/s, acyclic frames {}/s, lost {}/{} (cyclic/total), state {}
d.cyclic_frames_per_sec, d.acyclic_frames_per_sec,
d.cyclic_lost_frames, d.acyclic_lost_frames, d.master_state),
Err(e) => println!("读不到主站帧统计: {}", e), // Could not read master frame statistics: {}
}

AL error classification​

Classifies the AL Status Code to help judge the nature of an error and the handling strategy quickly.

classify_al_error()​

pub fn classify_al_error(code: u16) -> ALErrorCategory

Classifies the AL Status Code (the error code returned by a slave) to help judge the nature of an error and the handling strategy quickly.

The return value is the ALErrorCategory enum: 0=None / 1=Transient / 2=Configuration / 3=Hardware / 4=Unknown.

Parameters:

  • code (u16) -- raw AL Status Code; obtain it with slave.al_status_mirror().al_status_code (slave.error_code() returns the EcALState enum)

Returns:

#[repr(u8)]
pub enum ALErrorCategory {
None = 0, // no error
Transient = 1, // transient error; the state transition may be retried and usually recovers automatically
Configuration = 2, // configuration error; check the PDO mapping, SM configuration, startup parameters and so on
Hardware = 3, // hardware error; check the slave hardware, cabling and power
Unknown = 4, // unknown error; consult ETG.1000 or the slave manual
}

Example:

use darra_ethercat::{classify_al_error, ALErrorCategory};

let slave = master.slave(1);
let error_code = slave.al_status_mirror().al_status_code; // raw u16 AL Status Code
if error_code != 0 {
let category = classify_al_error(error_code);
println!("从站 {} 错误 0x{:04X}: {:?}", slave.index(), error_code, category); // Slave {} error 0x{:04X}: {:?}

match category {
ALErrorCategory::Transient => {
println!("瞬态错误,尝试重新切换状态..."); // Transient error, retrying the state switch...
}
ALErrorCategory::Configuration => {
println!("配置错误,请检查 PDO/SM 配置"); // Configuration error, check the PDO/SM configuration
}
ALErrorCategory::Hardware => {
println!("硬件错误,请检查从站设备"); // Hardware error, check the slave device
}
_ => {}
}
}
Common AL Status Codes
  • 0x0011 invalid requested state change — Transient
  • 0x001D invalid output configuration — Configuration
  • 0x001E invalid input configuration — Configuration
  • 0x002D sync not received (the ETG.1000.6 literal name "No sync error" does not mean error-free) — Transient
  • 0x0032 PLL error — Transient
  • 0x0050 EEPROM no access — Hardware

The category column is the actual value returned by classify_al_error(); for per-code meaning and handling advice, use the native AL status table (status_codes.c).

Rust-specific sugar

Rust sugar implements Display for EcALState, so format!("ALSC: {}", EcALState::SyncError) directly produces a friendly string (falling back to AL(0x00XX)); logs and UI no longer need their own match function.

Slave error counters​

read_slave_error_counters()​

pub fn read_slave_error_counters(&self, slave_index: i32) -> SlaveErrorCounters

Reads the error counter summary for the specified slave (CRC errors, frame errors, lost frame statistics).

Parameters:

  • slave_index (i32) — slave index (1-based)

Returns:

pub struct SlaveErrorCounters {
pub slave_index: i32, // slave index
pub port0_crc_errors: u32, // port 0 CRC errors
pub port1_crc_errors: u32, // port 1 CRC errors
pub port2_crc_errors: u32, // port 2 CRC errors
pub port3_crc_errors: u32, // port 3 CRC errors
pub frame_errors: u32, // frame error count
pub lost_frames: u32, // lost frame count
}

Example:

let counters = diag.read_slave_error_counters(1);
if counters.port0_crc_errors + counters.frame_errors + counters.lost_frames > 0 {
println!("从站 1 错误计数:"); // Slave 1 error counters:
println!(" CRC 错误: P0={}, P1={}, P2={}, P3={}", // CRC errors: P0={}, P1={}, P2={}, P3={}
counters.port0_crc_errors, counters.port1_crc_errors,
counters.port2_crc_errors, counters.port3_crc_errors);
println!(" 帧错误: {}", counters.frame_errors); // Frame errors: {}
println!(" 丢帧: {}", counters.lost_frames); // Lost frames: {}
}

Diagnostic messages​

read_diagnostic_messages()​

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

Reads diagnostic messages from slave object 0x10F3 (the diagnostics history object, ETG.1020) over CoE. Returns the list of diagnostic events recorded by the slave.

Returns:

pub struct DiagnosticMessage {
pub sub_index: u8, // subindex
pub diag_code: u32, // diagnostic code
pub flags: u16, // flags
pub text_index: u16, // text index
pub raw_data: Vec<u8>, // raw data
}

Example:

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

let messages = read_diagnostic_messages(master.index(), 1);
for msg in &messages {
println!("[从站 1] Code=0x{:08X}, Flags=0x{:04X}", // [Slave 1] Code=0x{:08X}, Flags=0x{:04X}
msg.diag_code, msg.flags);
}
note

Not every slave supports the 0x10F3 diagnostics history object. Slaves that do not support it return an empty list.

Full example​

let diag = master.diagnostics_info();
diag.set_enabled(true);

// communication and performance
println!("帧频: {} Hz", diag.rt_cnt()); // Frame rate: {} Hz
println!("丢包率: {:.2}%", diag.packet_loss_rate() * 100.0); // Packet loss rate: {:.2}%
println!("平均抖动: {:.2}us", diag.avg_jitter_us()); // Average jitter: {:.2}us
println!("邮箱延迟: 平均 {:.2}us, 最大 {:.2}us", // Mailbox latency: average {:.2}us, max {:.2}us
diag.mailbox_latency_avg_us(), diag.mailbox_latency_us());

// PDO frame loss
let pdo = diag.pdo();
println!("PDO 丢帧: 累计={}, 连续={}", pdo.total_lost(), pdo.consecutive_lost()); // PDO frame loss: total={}, consecutive={}

// slave anomalies
println!("最差从站: #{} ({}%)", diag.worst_slave_index(), diag.worst_link_quality()); // Worst slave: #{} ({}%)

// redundancy status
if diag.redundancy_active() {
println!("冗余模式: {:?}", diag.redundancy_ring_mode()); // Redundancy mode: {:?}
}
if let Some(bp) = diag.break_point() {
println!("故障: {}", bp); // Fault: {}
}

// slave error counters
// slave_count() returns u16 and read_slave_error_counters takes i32, so an explicit cast is needed
for i in 1..=master.slave_count() {
let c = diag.read_slave_error_counters(i as i32);
if c.frame_errors > 0 || c.lost_frames > 0 {
println!("从站 {}: 帧错误={}, 丢帧={}", i, c.frame_errors, c.lost_frames); // Slave {}: frame errors={}, lost frames={}
}
}

// AL error classification
for i in 1..=master.slave_count() {
let slave = master.slave(i);
let error_code = slave.al_status_mirror().al_status_code; // raw u16 code
if error_code != 0 {
let category = classify_al_error(error_code);
println!("从站 {} AL错误 0x{:04X}: {:?}", i, error_code, category); // Slave {} AL error 0x{:04X}: {:?}
}
}

// diagnostic messages (ETG.1020 0x10F3)
for i in 1..=master.slave_count() {
let messages = read_diagnostic_messages(master.index(), i);
for msg in &messages {
println!("[从站 {}] Code=0x{:08X}, Flags=0x{:04X}", // [Slave {}] Code=0x{:08X}, Flags=0x{:04X}
i, msg.diag_code, msg.flags);
}
}

Diagnostics field guide by problem​

On-site symptomWhich API to use
Is it packet loss?diagnostics_info().packet_loss_rate() + pdo().total_lost()
Is the cycle stable?diagnostics_info().avg_jitter_us() / cycle_time_span() / bus_max_jitter_us()
Mailbox transactions slow?diagnostics_info().mailbox_latency_us() / mailbox_latency_avg_us()
Which slave is unstable?diagnostics_info().worst_slave_index() / worst_link_quality()
Cable contact / CRC problems?diagnostics_info().read_slave_error_counters(i) or port_error_count[] of get_diagnostics()
Which cable is broken?diagnostics_info().break_point()
Primary / secondary port errors?diagnostics_info().primary_port_errors() / secondary_port_errors()
Whole-network diagnostics snapshot?darra_ethercat::master::other::get_diagnostics(mi, slave_count)

Whole-network slave diagnostics snapshot (get_diagnostics)​

get_diagnostics() is a free function in darra_ethercat::master::other that pulls link quality / port errors / link loss for all slaves in one call.

pub struct SlaveDiagnosticsData {
pub link_quality_percent: Vec<i16>, // link quality per slave (0-100, -1 = unknown), 1-based indexing
pub port_error_count: Vec<u32>, // total port errors per slave (Rx + invalid frames)
pub lost_link_count: Vec<u32>, // link loss count per slave
pub frame_errors: u32, // frame errors
pub lost_frames: u32, // lost frames
pub checksum_errors: u32, // checksum errors
pub timeout_frames: u32, // timed-out frames
pub primary_port_errors: u32, // primary port error count
pub secondary_port_errors: u32, // secondary port error count
}

Full diagnostics workflow example​

use darra_ethercat::master::other::get_diagnostics;

let diag = master.diagnostics_info();
diag.set_enabled(true);

// 1. packet loss rate
if diag.packet_loss_rate() > 0.01 {
println!("丢包率 {:.2}% 严重", diag.packet_loss_rate() * 100.0); // Packet loss rate {:.2}% is severe
}

// 2. mailbox send/receive latency
if diag.mailbox_latency_us() > 1000.0 {
println!("邮箱事务延迟偏大: {:.2}us", diag.mailbox_latency_us()); // Mailbox transaction latency is high: {:.2}us
}

// 3. fault location
if let Some(bp) = diag.break_point() {
println!("故障点: 从站 {} P{}", bp.slave_index, bp.port); // Fault point: slave {} P{}
}

// 4. worst slave
println!("最差从站: #{} ({}%)", // Worst slave: #{} ({}%)
diag.worst_slave_index(), diag.worst_link_quality());

// 5. whole-network slave snapshot
if let Some(snap) = get_diagnostics(master.index(), master.slave_count()) {
for i in 1..=master.slave_count() as usize {
let q = snap.link_quality_percent[i];
let err = snap.port_error_count[i];
if (q >= 0 && q < 100) || err > 0 {
println!("从站 {}: 链路质量 {}%, 端口错误 {}", i, q, err); // Slave {}: link quality {}%, port errors {}
}
}
}