Master diagnostics
Access advanced diagnostics through master.diagnostics_info (frame counts, jitter, packet loss rate and other MasterDiagnosticsInfo objects).
Access the ETG.1510 basic diagnostic data through master.diagnostics (returns a dict containing cyclic_lost_frames, acyclic_lost_frames, cyclic_fps, acyclic_fps, state; returns None on failure).
Drive exception handling from events instead of polling on your own. Reading diagnostic properties directly suits UI display and similar scenarios.
Feature overview
| Feature | Description |
|---|---|
| Communication and performance statistics | Frame counts, packet loss, jitter, PDO frame loss, port status, piggybacked counters, window statistics, topology |
| DC synchronization | Sync window threshold, DC diagnostics 2-second snapshot, dc_sync_lost event |
| Redundancy status | Redundancy active, fault point detection |
| Recovery ladder observation | Per-slave / master recovery ladder status bits, incremental read of ladder events |
| Diagnostics control | Start and stop data collection, reset statistics |
Communication and performance statistics
| Category | Property | Type | R/W | Description |
|---|---|---|---|---|
| Performance statistics | rt_cnt | int | Read-only | Frames per second (Hz); real-time driver mode reads the bus frequency directly, Npcap mode uses a 5-second window average |
| error_cnt | int | Read-only | Errors per second, 5-second average | |
| packet_loss_rate | float | Read-only | Packet loss rate (0.0~1.0) = merged bus WKC deficit / expected WKC (instantaneous value); 0 = no frame is really lost (including uninterrupted redundancy takeover); only on a cold start before OP does it fall back to the TX/RX count difference | |
| late_frame_rate | float | Read-only | Late frame rate (0.0~1.0) — an index that leaves the 8-frame window goes stale and is not counted as packet loss | |
| Cycle and jitter | cycle_time_span | int | Read-only | Actual cycle time (µs). Compare it against the DENI / LoopCycle setting; it is not hard-coded to 1 ms. When the reading is 0 it falls back to the frame rate |
| avg_jitter_us | float | Read-only | Average jitter (µs): for Npcap the last 5-second sliding window, for real-time driver mode the bus jitter over roughly a 1-second window. Jitter grows when isolation is not in effect, and the cycle should still hold at the configured value. A sustained deviation of ±20% from the configured value, or a maximum jitter > 25% of the cycle time, must be logged and alarmed (on_pdo_frame_loss() / set_dc_sync_lost_callback()). The cycle time has no product lower limit (a non-negative configured value is issued as is, with no minimum cycle threshold); do not hard-code 1000 Hz | |
| bus_clean_max_jitter_us | float | Read-only | Maximum disturbance-free bus jitter (µs): SMI interruptions are already removed, so it reflects the pure frame transmission timing deviation. Comparing it with bus_max_jitter_us shows whether the jitter mainly comes from SMI. Returns 0.0 when the summary cannot be read (this field has no unknown state) | |
| mailbox_latency_us | float | Read-only | Mailbox round-trip latency — maximum (µs); see the notes below | |
| mailbox_latency_avg_us | float | Read-only | Mailbox round-trip latency — average (µs); see the notes below | |
| Frame loss statistics | pdo.total_lost | int | Read-only | Total lost frames (sum of all groups) |
| pdo.consecutive_lost | int | Read-only | Current consecutive lost frames | |
| pdo_lost_frames | int | Read-only | Total PDO lost frames (sum of all groups) — the property form of the same underlying statistic as pdo.total_lost | |
| pdo_consecutive_lost | int | Read-only | Current consecutive lost frames (the maximum across all groups) — same source as pdo.consecutive_lost | |
| pdo_max_consecutive_lost | int | Read-only | Maximum consecutive lost frames on record (the maximum across all groups); use it to judge "sporadic or persistent" | |
| pdo.get_frame_loss_stats(group) | PDOFrameLossStats | Read-only | Frame loss statistics of the specified group (group=0-7; omit it or pass 255 to return the summary of all groups) | |
| Slave health | worst_slave_index | int | Read-only | Index of the slave with the worst link quality |
| worst_link_quality | int | Read-only | Communication health of the worst slave (%), -1 = unknown | |
| WKC mirror | wkc_actual_mirror | Optional<int> | Read-only | Mirror of the measured bus working counter (actual WKC) — reflects which slaves really respond right now; the measured value is never altered; returns None when the read fails |
| wkc_expected_mirror | Optional<int> | Read-only | Mirror of the expected working counter (expected WKC) — the fixed true value determined at configuration time / when entering OP; it is fixed once the topology is fixed and is never lowered dynamically to accommodate a degraded bus; returns None when the read fails | |
| wc_deficit | Optional<int> | Read-only | WKC deficit = expected − actual (>0 means a mapped slave is not contributing WKC at this moment, suspected slave loss / hot-plug); it returns to 0 automatically after the slave recovers; returns None when the read fails | |
| mapped_slave_count | Optional<int> | Read-only | Number of mapped slaves (participating in the WKC calculation), usable as a valid upper bound when iterating the per-slave WcState; 0 = the mapping contract is not ready (the master has not entered OP / the mapping has not been issued; in that state the per-slave WcState mirror is not trustworthy and UNKNOWN 0xFF is returned honestly); returns None when the read fails (unknown, not folded to 0) | |
| Master truth | lost_slave_count | Optional<int> | Read-only | Lost-slave census count (the single authority for the bus-level lost-slave count); >0 = a slave is lost; None = read failed / unavailable (unknown, not folded into 0) |
| no_process_data | bool | Read-only | Master-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; missing evidence is never passed off as healthy) | |
| no_process_data_known | bool | Read-only | Whether 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 | Optional<int> | Read-only | Probe truth summary (number of slaves that answered / number of slaves with insufficient evidence); None = the probing mechanism is not observable (no true-value sample) | |
| stale_input_count | Optional<int> | Read-only | Number 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 run | cycle_state | CycleRunState | Read-only | Master cycle tri-state: NOT_STARTED / STARTED_NO_ADVANCE / ADVANCING; 0 no longer blurs three different meanings into one value |
| Topology change | topology_fingerprint | int | Read-only | Topology fingerprint (slave count + a stable hash of each slave's VendorId/ProductId/RevId); topology_fingerprint_known reports whether sampling succeeded |
| topology_change_count | int | Read-only | Number 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 | Optional[datetime] | Read-only | Time of the most recent observed topology change (UTC); None = no change observed yet | |
| Primary-port WKC | primary_wkc | Optional<int> | Read-only | Primary-port WKC — a single-port scale that does not include the secondary port (for the aggregate scale see wkc). It holds the peak across cycles, so it can only prove that the primary port received frames within this window; it is not a real-time value; returns None when the read fails |
| primary_wkc_rt | Optional<int> | Read-only | Filtered real-time WKC of the primary port — measured from the frames and filtered every cycle, so it drops in the same cycle a slave is unplugged or the link breaks. A reading of 0 is legal when the primary port is physically disconnected (failover is immediately visible); returns None when the read fails | |
| Redundancy ports | primary_port_ok | bool | Read-only | Whether the primary port is healthy |
| secondary_port_ok | bool | Read-only | Whether the secondary port is healthy | |
| primary_port_errors | int | Read-only | Primary-port errors in the last 5 seconds | |
| secondary_port_errors | int | Read-only | Secondary-port errors in the last 5 seconds | |
| Topology and timing | topology_description | str | Read-only | Topology mode description |
| timing_mode | str | Read-only | Timing mode (returned as text): real-time driver / Npcap PDO thread / not started / unknown | |
| Hardware counters | hardware_smi_counter_available | Optional<bool> | Read-only | Whether the hardware SMI counter is available (commonly available on Intel, False on AMD / virtual machines). Returns None when the read fails — False is the true value of "genuinely unavailable"; the two cannot substitute for each other |
| Real-time runtime | wdk_rt_cpu_core | int | Read-only | CPU core the real-time thread is currently bound to; returns -1 when not yet enabled or the runtime does not support it |
PDOFrameLossStats:
@dataclass
class PDOFrameLossStats:
total_lost: int # total lost frames
consecutive_lost: int # current consecutive lost frames
max_consecutive_lost: int # maximum consecutive lost frames on record
mailbox_latency_us / mailbox_latency_avg_us are the time a mailbox transaction (CoE / SoE / FoE / EoE / AoE / VoE request-response and similar) takes from the request being issued to the response returning: the maximum and the average over the last 1-second window.
For real-time jitter see bus_max_jitter_us / bus_avg_jitter_us.
get_piggyback_consume_counters()
def get_piggyback_consume_counters(self) -> Optional[dict]
Reads the consumer-side 5 process-global cumulative counters: after a cyclic frame carries the slave AL status back, they record the hits and skips while that status is consumed segment by segment. They are not the same counter group as the 4 initiator-side counters; do not add them together.
Return value:
Optional[dict]— fixed keys, values are 32-bit unsigned cumulative counts:calls(int) — consumer-side call countskip_ado(int) — times the segment was skipped because its target is not the AL status registerskip_len(int) — times the segment was skipped because its length is not 2 bytesskip_active(int) — times the segment was skipped because the previous round had not finished consumingwrites(int) — times the master state was written successfully
A failed read returns None (it does not return all 0s to fake "the counters are zero").
Example:
diag = master.diagnostics_info
c = diag.get_piggyback_consume_counters()
if c is None:
print("消费侧计数读取失败") # Failed to read the consumer-side counter
else:
print(f"消费 {c['calls']} 次, 跳过(目标/长度/未完成)=" # consumed {c['calls']} times, skipped (target/length/incomplete)=
f"{c['skip_ado']}/{c['skip_len']}/{c['skip_active']}, 写入 {c['writes']}") # {c['skip_ado']}/{c['skip_len']}/{c['skip_active']}, writes {c['writes']}
get_piggyback_call_counters()
def get_piggyback_call_counters(self) -> Optional[dict]
Reads the initiator-side 4 process-global cumulative counters: calls of the aggregate status read, times the running-state fast path was taken, times the channel slot was occupied, and successful enqueues.
Return value:
Optional[dict]— fixed keys:call_total(int) — total calls of the aggregate status readop_branch(int) — times the running-state fast path was takenop_inactive(int) — times the channel slot was already occupied and nothing was appended this roundop_queued(int) — times the entry was successfully placed in the channel slot
A failed read returns None (distinguishable from the case where the counters on both sides really are 0).
Example:
c = master.diagnostics_info.get_piggyback_call_counters()
if c is not None:
print(f"总调用 {c['call_total']}, 快速路径 {c['op_branch']}, " # total calls {c['call_total']}, fast path {c['op_branch']},
f"槽位占用 {c['op_inactive']}, 已排队 {c['op_queued']}") # slot busy {c['op_inactive']}, queued {c['op_queued']}
The runtime keeps the counters per process; several master instances share the same group, so this is not a per-master scale; diagnostics_info.reset() does not reset them.
diag_cs_window_stats()
def diag_cs_window_stats(self) -> CsWindowStats
Reads the CS 5-second sliding window statistics. The values are computed once by the runtime; the SDK only passes them through and does no second-stage calculation.
Return value:
CsWindowStats— frozen dataclass:available(bool) —False= no statistics (the runtime returned a failure or the call raised); the remaining numeric fields are then always 0 and must not be interpretederror_per_sec(float) — errors per second within the window; 0 when the accumulated window duration is less than 1 millisecondcycle_hz(float) — cycle frequency within the window; 0 when the accumulated window duration is less than 1 millisecondavg_jitter_us(float) — average jitter within the window (µs); 0 when there are no samplesfilled(int) — number of samples in the window
When available=False the fields are all 0; when available=True a 0 is a measured 0 (the samples really had no error, or the window really has no samples). Judge "is there statistics" only by available; do not infer it from whether the numbers are 0.
Example:
diag = master.diagnostics_info
st = diag.diag_cs_window_stats()
if not st.available:
print("窗口统计不可用") # Window statistics unavailable
else:
print(f"{st.filled} 个样本: {st.cycle_hz:.1f} Hz, " # {st.filled} samples: {st.cycle_hz:.1f} Hz,
f"抖动 {st.avg_jitter_us:.2f} us, 错误 {st.error_per_sec:.2f}/s") # jitter {st.avg_jitter_us:.2f} us, errors {st.error_per_sec:.2f}/s
WKC mirror (slave loss observable)
wkc_actual_mirror / wkc_expected_mirror / wc_deficit are the master-level aggregate mirror of the per-slave WC diagnostics; all of them are properties on master.diagnostics_info and are read in real time (no refresh needed). Together with slave.diagnostics.wc_contributed on each slave they locate exactly which slave dropped.
Observability contract (must not be violated):
wkc_expected_mirror= the fixed true value determined at configuration time / when entering OP; it is fixed once the topology is fixed, conceptually immutable, and never lowered dynamically to accommodate a degraded bus.wkc_actual_mirror= the measured bus value that reports as measured which slaves really respond right now, never altered.wc_deficit = wkc_expected_mirror − wkc_actual_mirror.wc_deficit > 0is not a master fault: a mapped slave is not contributing WKC right now (suspected slave loss / hot-plug in recovery). Once the slave recovers,wc_deficitreturns to 0 automatically, with no reset call needed.
Example:
diag = master.diagnostics_info
# Master-level WKC mirror (thin read, zero frames, real time)
print(f"WKC: {diag.wkc_actual_mirror} / {diag.wkc_expected_mirror} "
f"(映射从站 {diag.mapped_slave_count} 个)") # ({diag.mapped_slave_count} slaves mapped)
if diag.wc_deficit is not None and diag.wc_deficit > 0:
print(f"⚠️ WKC 缺额 {diag.wc_deficit} — 有从站没在响应,逐个从站定位:") # ⚠️ WKC deficit {diag.wc_deficit} — some slaves are not responding, locating them one by one:
from darra_ethercat.data.types import WcContribution
for slave in master.slaves:
if slave.diagnostics.wc_contributed == WcContribution.NOT_CONTRIBUTED:
print(f" 从站 {slave.slave_num} 未贡献 WKC") # Slave {slave.slave_num} is not contributing WKC
Use slave.diagnostics.wc_contributed (WcContribution enum) for the contribution state of an individual slave. When wc_deficit > 0, iterate the slaves to locate the dropped one.
Read the global expected value with master.get_expected_wkc() and the group-level value with master.get_group_expected_wkc(group) (see slave grouping). set_expected_wkc() is only used for lower-level debugging: the expected value is the fixed true value from configuration time, and normal application code must not lower it to accommodate a degraded bus; for devices whose absence is genuinely allowed, mark them with slave.is_optional = True.
Secondary-port WKC "unknown" state
secondary_wkc is the measured in this cycle secondary-port working counter: if a fresh value is sampled in this cycle you get the measured value, otherwise you get "unknown". It never returns a stale full count and never returns a peak-held value from an earlier cycle.
| Category | Member | Type | R/W | Description |
|---|---|---|---|---|
| Redundancy WKC | diagnostics_info.secondary_wkc | Optional[int] | Read-only | Secondary-port WKC measured in this cycle. Returns WKC_UNKNOWN when this cycle has no fresh measurement; returns None when the read fails |
| Redundancy WKC | WKC_UNKNOWN | int (0xFFFF) | Read-only | The "no measurement" sentinel; can be imported from the darra_ethercat top level |
| Redundancy WKC | diagnostics_info.secondary_wkc_known | bool | Read-only | Whether this cycle has a measurement. False only means secondary_wkc is WKC_UNKNOWN or the read failed |
| Redundancy WKC | diagnostics_info.secondary_wkc_rt | Optional[int] | Read-only | Filtered real-time value of the secondary port (drops in the same cycle a slave is unplugged or the link breaks); use this to look at "right now" |
On a single NIC (no secondary leg configured) a return of 0 is a valid reading and counts as "known". So deciding "unknown" must go through secondary_wkc_known; neither "is the value 0" nor treating 0xFFFF as a full count works.
None / 0 / 0xFFFF tri-state0 = a valid reading (single NIC / the secondary port makes no contribution in this cycle); 0xFFFF = no measurement in this cycle (unknown); None = the read failed. The three have different semantics; do not mix them. To look at the filtered real-time value use secondary_wkc_rt.
Example:
diag = master.diagnostics_info
if not diag.secondary_wkc_known:
print("副口 WKC: 未知(本拍无实测)") # Secondary-port WKC: unknown (no measurement this cycle)
elif diag.secondary_wkc == 0:
print("副口 WKC: 0(单网口 / 副口本拍无贡献)") # Secondary-port WKC: 0 (single port / secondary port contributed nothing this cycle)
else:
print(f"副口 WKC: {diag.secondary_wkc}, 实时值 {diag.secondary_wkc_rt}") # Secondary-port WKC: {diag.secondary_wkc}, real-time value {diag.secondary_wkc_rt}
Real OP verdict (RealOp)
"Reading OP from the AL status word" is not the same as "this cycle really exchanges process data". The status word can lag: after a slave drops out the AL may still report OP, and with the merged WKC down to 6/12 the user interface still shows "all OP". The per-slave "real OP" is given by the SDK's per-slave verdict.
- A verdict that holds is what makes a clean OP: the AL state is OP (
0x08), the Error bit (0x10) = 0, and the slave has not dropped out; - The WKC contribution is display evidence only and cannot be used to overturn the verdict.
Master-level "real OP" is a separate layer of conclusion: every required slave (not optional and with process data) passes the per-slave verdict, and the merged measured WKC is not below the fixed expectation from configuration time. Per-slave verdicts holding on their own does not mean the whole machine is in 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.
This API group only decides and displays: it does not trigger recovery, stop PDO, leave OP, change expectations, or modify any existing control criterion. Evidence that cannot be read is always judged RealOpReason.UNKNOWN, and a cached or old value is never passed off as real OP; the expected WKC is never lowered.
Entry points
| Category | Member | Returns | R/W | Description |
|---|---|---|---|---|
| Diagnostics | diagnostics_info.real_op_truth | MasterRealOpTruth | Read-only | Captures one cycle; equivalent to capture_real_op_truth() |
| Diagnostics | diagnostics_info.capture_real_op_truth() | MasterRealOpTruth | Read-only | Captures one cycle of real OP truth (master level + per slave) |
| Diagnostics | diagnostics_info.evaluate_slave_real_op(slave) | Optional[SlaveRealOpState] | Read-only | Single-slave verdict; None = cannot evaluate, reported honestly as unknown |
| Diagnostics | diagnostics_info.evaluate_real_op(evidence, wkc_actual, wkc_expected) | MasterRealOpTruth | Read-only | Evaluates from same-cycle evidence (no re-read when a snapshot already exists) |
The application layer can use the entry points above directly; it does not need to, and should not, write its own "is this real OP" judgement.
Reason enumeration
RealOpReason (IntEnum; the values map one-to-one to the other language SDKs)
| Value | Name | Meaning |
|---|---|---|
| 0 | OK | Real OP: the per-slave verdict holds |
| 1 | AL_NOT_CLEAN | The per-slave verdict does not hold (not in the OP base state / the Error bit is set / the slave has dropped out) |
| 2 | NO_CONTRIBUTION | Reserved value (not produced currently) |
| 3 | UNSTABLE | Reserved value (not produced currently) |
| 4 | WKC_DEFICIT | Master level: all required slaves pass the verdict, but the merged measured WKC is below the fixed expectation |
| 5 | UNKNOWN | Insufficient evidence (the data needed for the verdict cannot be read / no required slaves) |
Result structure
MasterRealOpTruth (dataclass; category: diagnostics; access: read-only)
| Field | Type | Description |
|---|---|---|
| sequence | int | Evaluation sequence number, monotonically increasing per master |
| real_op | bool | Master-level real OP |
| reason | RealOpReason | Main reason the master-level verdict does not hold |
| required_count | int | Number of required slaves |
| real_op_count | int | Number of required slaves in per-slave real OP |
| failed_count | int | Number of required slaves that have not reached real OP |
| wkc_actual | int | Merged measured WKC (as measured) |
| wkc_expected | int | Fixed expected WKC from configuration time (never lowered) |
| wkc_deficit | int | Deficit = expected − actual (≤0 means no deficit) |
| slaves | List[SlaveRealOpState] | Per-slave results |
| detail_text | str | Readable detail (master conclusion + list of slaves that fell short + WKC comparison) |
SlaveRealOpState (dataclass; category: diagnostics; access: read-only)
| Field | Type | Description |
|---|---|---|
| slave_index | int | Slave index (1-based) |
| required | bool | Whether it participates in the master-level verdict (not optional and has PDO) |
| al_clean_op | bool | Per-slave verdict (AL is OP ∧ Error bit = 0 ∧ not dropped out; the AL status code is not included) |
| contributed | bool | This cycle has a WKC contribution — display evidence only, not part of the verdict |
| real_op | bool | The slave is in real OP |
| reason | RealOpReason | Reason it does not hold (OK when it is in real OP) |
| detail | str | Readable reason detail (not part of the verdict) |
Example:
truth = master.diagnostics_info.real_op_truth
if truth.real_op:
print(f"真 OP: 必需站 {truth.real_op_count}/{truth.required_count}, " # Real OP: required slaves {truth.real_op_count}/{truth.required_count},
f"WKC {truth.wkc_actual}/{truth.wkc_expected}")
else:
print(f"非真 OP [{truth.reason.name}] {truth.detail_text}") # Not real OP [{truth.reason.name}] {truth.detail_text}
for s in truth.slaves:
if s.required and not s.real_op:
print(f" 从站 {s.slave_index}: {s.reason.name} — {s.detail}") # Slave {s.slave_index}: {s.reason.name} — {s.detail}
Diagnostics snapshot
get_snapshot()
def get_snapshot(self) -> DiagnosticsSnapshot
Fetch a consistent snapshot of the diagnostic data. Returns a frozen snapshot (immutable dataclass) of all diagnostic metrics at the current instant; suitable for logging, UI refresh, passing across threads and similar scenarios.
DiagnosticsSnapshot data class:
@dataclass(frozen=True)
class DiagnosticsSnapshot:
frequency: int # frames per second (Hz)
error_count: int # errors per second
packet_loss_rate: float # packet loss rate (0.0-1.0) = merged bus WKC deficit / expected WKC (instantaneous)
late_frame_rate: float # late frame rate (0.0-1.0) — an index leaving the 8-frame window goes stale, not counted as lost
avg_jitter_us: float # average jitter (µs)
mailbox_latency_us: float # mailbox round-trip latency - maximum (µs)
mailbox_latency_avg_us: float # mailbox round-trip latency - average (µs)
cycle_time_us: int # actual cycle time (µs)
wkc_actual: int # current WKC
wkc_expected: int # expected WKC
bus_cycle_hz: int # bus frequency (Hz)
bus_max_jitter_us: float # maximum bus jitter (µs)
bus_avg_jitter_us: float # average bus jitter (µs)
bus_roundtrip_us: float # bus round-trip latency (µs)
bus_load_percent: float # communication load (%) (derived value)
smi_count: int # SMI count
smi_peak_us: float # SMI peak (µs)
primary_port_ok: bool # primary port healthy
secondary_port_ok: bool # secondary port healthy
redundancy_active: bool # redundancy protection is running (RingMode>=1 and both ports carry frames; always false for line / end foldback)
Example:
diag = master.diagnostics_info
snap = diag.get_snapshot()
print(f"频率: {snap.frequency} Hz, 丢包率: {snap.packet_loss_rate:.2%}") # Frequency: {snap.frequency} Hz, packet loss: {snap.packet_loss_rate:.2%}
print(f"WKC: {snap.wkc_actual}/{snap.wkc_expected}")
print(f"总线抖动: 平均 {snap.bus_avg_jitter_us:.2f} us, 最大 {snap.bus_max_jitter_us:.2f} us") # Bus jitter: average {snap.bus_avg_jitter_us:.2f} us, max {snap.bus_max_jitter_us:.2f} us
print(f"邮箱延迟: 平均 {snap.mailbox_latency_avg_us:.2f} us, 最大 {snap.mailbox_latency_us:.2f} us") # Mailbox latency: average {snap.mailbox_latency_avg_us:.2f} us, max {snap.mailbox_latency_us:.2f} us
print(f"冗余: {'激活' if snap.redundancy_active else '未激活'}") # Redundancy: {'active' if snap.redundancy_active else 'inactive'}
Definitions:
rt_cnt/error_cnt: in Npcap mode these are per-second averages over the last 5-second window; in real-time driver modert_cntreads the bus frequency directly (not a sliding window), whileerror_cntstill uses the 5-second sliding window.packet_loss_rate= merged bus WKC deficit / expected WKC (instantaneous value); 0 = no frame is really lost (including uninterrupted redundancy takeover); only on a cold start before OP does it fall back to the TX/RX count difference.late_frame_rate= the share of late frames that go stale within the 8-frame window, not counted as packet loss.wkc_actual/wkc_expectedareintin the snapshot (no tri-state): the snapshot gives 0 when the value cannot be read. To distinguish "cannot read", readwkc_actual_mirror/wkc_expected_mirrordirectly (Optional,Noneon failure).
enabled is not the master switch for collection: WKC / packet loss / DC / port diagnostics are always collected; it only controls the SDK-side sliding-window sampling timer.
Per-item read example:
diag = master.diagnostics_info
print(f"帧频: {diag.rt_cnt} Hz") # Frame rate: {diag.rt_cnt} Hz
print(f"丢包率: {diag.packet_loss_rate:.2%}") # Packet loss: {diag.packet_loss_rate:.2%}
print(f"错误数: {diag.error_cnt}") # Error count: {diag.error_cnt}
print(f"周期时间: {diag.cycle_time_span} us") # Cycle time: {diag.cycle_time_span} us
print(f"总线抖动: 平均 {diag.bus_avg_jitter_us:.2f} us, 最大 {diag.bus_max_jitter_us:.2f} us") # Bus jitter: average {diag.bus_avg_jitter_us:.2f} us, max {diag.bus_max_jitter_us:.2f} us
print(f"邮箱延迟: 平均 {diag.mailbox_latency_avg_us:.2f} us, 最大 {diag.mailbox_latency_us:.2f} us") # Mailbox latency: average {diag.mailbox_latency_avg_us:.2f} us, max {diag.mailbox_latency_us:.2f} us
# PDO frame loss
pdo = diag.pdo
print(f"PDO 丢帧: 累计={pdo.total_lost}, 连续={pdo.consecutive_lost}") # PDO frame loss: total={pdo.total_lost}, consecutive={pdo.consecutive_lost}
# Query by group
stats0 = pdo.get_frame_loss_stats(0)
stats1 = pdo.get_frame_loss_stats(1)
print(f"组0丢帧: {stats0.total_lost}, 组1丢帧: {stats1.total_lost}") # Group 0 frame loss: {stats0.total_lost}, group 1 frame loss: {stats1.total_lost}
# Slave anomalies
print(f"最差从站: #{diag.worst_slave_index} ({diag.worst_link_quality}%)") # Worst slave: #{diag.worst_slave_index} ({diag.worst_link_quality}%)
# Port status
print(f"主端口: {'正常' if diag.primary_port_ok else '异常'}") # Primary port: {'OK' if diag.primary_port_ok else 'abnormal'}
print(f"副端口: {'正常' if diag.secondary_port_ok else '未连接'}") # Secondary port: {'OK' if diag.secondary_port_ok else 'not connected'}
# Topology information
print(f"拓扑: {diag.topology_description}") # Topology: {diag.topology_description}
print(f"定时: {diag.timing_mode}") # Timing: {diag.timing_mode}
Read the ESC port errors of each slave through slave.diagnostics.read_port_errors().
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
hot_swap_rescan_count: Optional[int] # completed rounds
last_hot_swap_rescan_result: Optional[int] # last result code
last_hot_swap_rescan_time_ms: Optional[int] # last completion time (Unix ms UTC)
The three attributes read the kernel accounting (zero-frame thin reads; a read failure returns None, distinct from 0). There is no manual rebuild method to call. Result codes: 0 succeeded, -20 BUSY, -21 RESCAN_0 (R0: do not blame the link), -23 NO_OP, -25 IDX_FULL; gates -1 / -6.
Example:
diag = master.diagnostics_info
print(f"自动重建 {diag.hot_swap_rescan_count} 轮," # {diag.hot_swap_rescan_count} auto-rebuild rounds,
f"上次结果 {diag.last_hot_swap_rescan_result}," # last result {diag.last_hot_swap_rescan_result},
f"时刻 {diag.last_hot_swap_rescan_time_ms}") # timestamp {diag.last_hot_swap_rescan_time_ms}
Recovery ladder observation
After a slave drops out, recovery advances along a fixed ladder: first classify (a class-A disconnection is left alone, everything else recovers level by level), then replay the configuration step by step and return to OP. The entry points below are read-only observation; they do not trigger recovery and do not affect the cycle. When a value cannot be read, each entry returns its own "unavailable" form honestly (available=False / 0 / an empty list) and raises no exception into the application.
| Category | Property | Type | R/W | Description |
|---|---|---|---|---|
| Recovery ladder status | SlaveRecoveryStatus.paused_a | bool | Read-only | Status bit bit0: class-A disconnection left alone (paused) |
| SlaveRecoveryStatus.needs_reconfig | bool | Read-only | Status bit bit1: the configuration has not been replayed yet | |
| SlaveRecoveryStatus.ladder_exhausted | bool | Read-only | Status bit bit2: suspended after repeated failures (already raised to L2) | |
| SlaveRecoveryStatus.epilogue | bool | Read-only | Status bit bit3: finishing up in OP |
The four status bits are decoded bit by bit from the raw flags byte of the returned object and are independent of each other. When available=False the flags value is always 0 and all four bits are False — that only means observation is unavailable, and must not be read as "no pause / no suspension".
slave_recovery()
def slave_recovery(self, slave_index: int) -> SlaveRecoveryStatus
Reads the recovery ladder status snapshot of one slave. Read-only observation; it does not trigger recovery.
Parameters:
slave_index(int) — slave index (1-based)
Return value:
SlaveRecoveryStatus— frozen dataclass, neverNone:available(bool) —False= observation unavailable (the runtime lacks this capability / no mirror yet / invalid index / the call failed); not "this slave is not recovering"; the remaining fields are meaningless thenlevel/step(int) — current level / current step (raw codes passed through; unrecognised codes keep their raw value and are not folded into invented enums)last_step(int) — previous substep, used to trace the transitionfail_reason/fail_alsc(int) — failure reason of the previous step / measured AL status code at the failure (0 = none or not read)retry_count(int) — attempts in this roundbackoff_remain_ms(int) — remaining milliseconds of the slave-level cool-down (0 = can act at any time)step_elapsed_ms(int) — milliseconds already spent in the current stepskip_frames(int) — cumulative recovery frames skippedseq(int) — state transition count, used to judge whether this mirror is freshflags(int) — raw status-bit byte; the four status bits are listed in the table abovelast_result_ok(int) — 1 = success, 0 = failure, 2 = not executed (suppressed)classify(int) — raw recovery classification code (0 = not classified)
Example:
diag = master.diagnostics_info
st = diag.slave_recovery(3)
if not st.available:
print("从站 3 恢复观测不可用") # does not mean "this slave did not recover"
elif st.ladder_exhausted:
print(f"从站 3 连败挂起: 已尝试 {st.retry_count} 次, " # Slave 3 suspended after consecutive failures: {st.retry_count} attempts made,
f"冷静期剩 {st.backoff_remain_ms} ms") # {st.backoff_remain_ms} ms of cooldown left
elif st.paused_a:
print("从站 3 因 A 类断线暂停处理") # Slave 3 processing suspended due to a class-A cable break
else:
print(f"从站 3: 级 {st.level} / 步 {st.step}, 已耗时 {st.step_elapsed_ms} ms") # Slave 3: level {st.level} / step {st.step}, {st.step_elapsed_ms} ms elapsed
master_recovery_ladder()
def master_recovery_ladder(self) # returns a read-only observation object
Master-level recovery escalation observation snapshot. Read-only; it does not trigger recovery.
Return value:
- Recovery observation object (frozen dataclass, never
None):available(bool) —False= observation unavailable (the runtime does not support it / the call failed)trigger_blocked_total(int) — cumulative count of "trigger matched but not executed in this round"; the only field that currently carries a real collected value. Always 0 whenavailable=False, and must then not be interpreted- The remaining extension fields (
rebuild_req_pending/rebuild_active/rebuild_fail/alarm_only/handoff_busy/a_suppressed/bad_persistent/ladder_exhausted/backoff_remain_ms/bad_since_ms/rebuild_total/seq) are currently alwaysNone= not collected, not 0
Example:
ladder = master.diagnostics_info.master_recovery_ladder()
if not ladder.available:
print("主站级恢复观测不可用") # Master-level recovery observation unavailable
elif ladder.trigger_blocked_total > 0:
print(f"恢复触发被压制累计 {ladder.trigger_blocked_total} 次") # Recovery triggers suppressed {ladder.trigger_blocked_total} times in total
recovery_ladder_seq()
def recovery_ladder_seq(self) -> int
Freshness token of the recovery ladder (monotonically increasing). A token that stops increasing means the observation is producing no new content; do not treat old observations as the current state.
Return value:
int— token value;0= unavailable or no transition yet (an honest value, not a guess). A failed read also returns0.
Example:
seq = master.diagnostics_info.recovery_ladder_seq()
print("尚无转移记录或观测不可用" if seq == 0 else f"当前令牌 {seq}") # No transition record yet or observation unavailable / current token {seq}
recovery_events()
def recovery_events(self, since_seq: int, max_count: int = 256) -> List[RecoveryEvent]
Incrementally reads recovery ladder events: returns the events whose seq is strictly greater than since_seq, at most max_count of them.
Parameters:
since_seq(int) — cursor;0= start from the oldest available event in the event ringmax_count(int) — maximum number of entries, default256; a value of 0 or less returns an empty list directly, anything above256is truncated to256
Return value:
-
List[RecoveryEvent]— list of events. No new events, a failed read and a runtime that lacks the capability all return an empty list (the failure is only logged, no exception is raised). This differs fromget_link_diag_events(): link events useNoneto distinguish "read failed", recovery events do not distinguish.Each event object is read through its properties:
seq(int) — global monotonic sequence number, used as the next cursorslave(int) — slave index;0= master-level eventkind(int) — event kind: 0 = step transition, 1 = level transition, 2 = L1 result, 3 = L2 suspension / escalation, ..., 11 = penalty clearedfrom_level/to_level(int) — level before / after the transitionfrom_step/to_step(int) — step before / after the transitionreason(int) — raw reason codeok(int) — 1 = success, 0 = failure, 2 = not executed (suppressed)alsc(int) — raw measured AL status codetick_ms(int) — event time (milliseconds)
The event ring has a fixed capacity; when writes outpace reads the old events are overwritten. seq stays monotonic, but sequence gaps can appear between two reads — de-duplicate by seq and accept the gaps; do not assume they are consecutive.
Example:
diag = master.diagnostics_info
cursor = 0
while True:
events = diag.recovery_events(cursor, 64)
if not events:
break
for e in events:
print(f"[{e.seq}] 从站 {e.slave}: {e.from_level}/{e.from_step} → " # [{e.seq}] Slave {e.slave}: {e.from_level}/{e.from_step} →
f"{e.to_level}/{e.to_step} ok={e.ok}")
cursor = events[-1].seq
Link observation
| Category | Property | Type | R/W | Description |
|---|---|---|---|---|
| Link observation | primary_phy_link_state / secondary_phy_link_state | PhyLinkState | Read-only | Physical link of the primary / secondary port: UP=1, DOWN=0, UNKNOWN=-1; a failed read returns UNKNOWN |
| master.secondary_frame_link_state | PhyLinkState | Read-only | Frame-level link tri-state of the secondary port; use it separately from the physical link reading | |
| phy_link_bitmask | Optional<int> | Read-only | Bitmap of both ports: bit0 = primary Up, bit1 = secondary Up; 0xFFFF = not observable; phy_link_state is a compatibility alias | |
| diagnostics_info.link_diag_event_count | Optional<int> | Read-only | Total number of line-interruption diagnostic events (including the history before the event ring overwrote it); returns None when the read fails and is not disguised as 0 | |
| diagnostics_info.link_diag_seq | Optional<int> | Read-only | Event ring freshness token: monotonically increasing = events are being written; stopped increasing = no new events are produced. Returns None when the read fails |
UNKNOWN only means the value cannot be read or has not been decided yet (the version does not support it, the frame-level link has no result yet); it does not equal DOWN: do not report a broken link, a slave loss or fault handling from it. Only an explicit DOWN is a broken link.
diag = master.diagnostics_info
if diag.primary_phy_link_state == PhyLinkState.DOWN:
print("主口明确 Down") # Primary port is definitively Down
elif diag.primary_phy_link_state == PhyLinkState.UNKNOWN:
print("主口状态未知") # Primary port state unknown
master.secondary_link_ok is a compatibility boolean health check: it is True only for an explicit Up, and False for both Down and unknown. To tell the latter two apart, read master.secondary_frame_link_state.
get_link_diag_events()
def get_link_diag_events(self, since_seq: int = 0) -> Optional[list]
Reads line-interruption diagnostic events incrementally by cursor. Pass the seq of the last event you read to keep consuming continuously.
Parameters:
since_seq(int) — cursor; take theseqof the last event in the previous result; the default0= start from the oldest available event in the event ring
Return value:
-
Optional[list]— a list ofLinkDiagEvent. No new events returns an empty list; a failed read returnsNone. The two are distinguishable, and a failure is not disguised as "no new events".Each event object is read through its properties:
t_us(int) — event time (µs)seq(int) — monotonic sequence number within the master, used as the next cursorkind(int) — event type: 1 = port A link break, 2 = port B link break, 3 = mid-segment break, 4 = healthy again, 5 = whole network lost, 6 = PHY A, 7 = PHY B, 8 = redundancy switchover, 9 = recovery, 10 = fast flapping, 11 = WKC tupleport(int) — port 0–3 (for PHY-type events);0xFFfor the other eventsfrom_state/to_state(int) — redundancy state before / after the transitiona_peer/a_self/b_peer/b_self(int) — raw snapshot of the four-port tuple in the cycle that triggered the event (not debounced)ring_intact(int) — 1 = ring closed, 0 = ring brokenis_up(int) — 1 = rising edge of recovery, 0 = falling edge of disconnectioneffective_wkc(int) — topology union WKC, comparable with the expected value on the same scaleexpected_wkc(int) — expected WKC fixed at configuration time
Example:
diag = master.diagnostics_info
cursor = 0
while True:
events = diag.get_link_diag_events(cursor)
if events is None:
print("事件读取失败") # Failed to read events
break
if not events:
break
for ev in events:
print(f"[{ev.t_us}] kind={ev.kind} 端口={ev.port} 环闭合={ev.ring_intact}") # [{ev.t_us}] kind={ev.kind} port={ev.port} ring intact={ev.ring_intact}
cursor = events[-1].seq
Static port topology model (ring / branch / chain forms)
The static port model is used to decide the ring / branch / chain form. The caller supplies the per-slave port topology set (slave index, physical port mask, entry port, parent slave, parent port), and the result is returned directly with no second-stage derivation.
This encoding is not the same set as the "runtime form topology_mode": the latter has one extra value 3 (ring degraded to line), and the two must never be compared raw. When the model is unknown (model_known=False) it must not be treated as linear.
| Category | Property | Type | R/W | Description |
|---|---|---|---|---|
| Static model | master.slave_topology.compute_ring_branch() | RingBranchInfo | Read-only | Read-only query that changes no state; computed uniformly by the SDK |
| P1 ring + branch | diagnostics_info.topo_p1_foldback_mode | int | Read-only | P1 foldback requirement mode: 0=NONE, 1=SINGLE_NIC, 2=DUAL_RING_BRANCH; -1 = unavailable |
| diagnostics_info.topo_p1_mode | int | Read-only | Compatibility alias of topo_p1_foldback_mode, with exactly the same value meanings | |
| diagnostics_info.topo_p1_ring_end_adp | int | Read-only | Slave index that owns the P1 ring end exit port; 0 or greater = measured value, -1 = unavailable | |
| diagnostics_info.topo_p1_full_wkc | int | Read-only | Complete P1 WKC (ring members + branches combined); 0 or greater = measured value, -1 = unavailable | |
| diagnostics_info.topo_measured_ring_count | int | Read-only | Number of slaves inside the P1 ring; branch slave count = topo_p1_full_wkc − topo_measured_ring_count; 0 or greater = measured value, -1 = unavailable | |
| diagnostics_info.topo_p1_measured | int | Read-only | Whether a real on-site topology measurement ran in this round: 1 = measured, 0 = not measured; -1 = unavailable |
For this group of fields -1 always means unavailable (not calibrated / not a dual-NIC ring + branch topology / invalid index / the runtime lacks the capability), not "genuinely none". A 0 in these fields is a valid value (foldback mode NONE / 0 slaves inside the ring / not measured this round) — folding -1 into 0 disguises "cannot read" as "genuinely none".
Result fields (RingBranchInfo, dataclass):
| Field | Type | Description |
|---|---|---|
| total_count | int | Total slave count reported by the SDK; with model_known=False it is the number of slaves supplied in this call |
| ring_count | int | Number of ring members (available only when model_known=True) |
| branch_count | int | Number of branches = total_count − ring_count (available only when model_known=True) |
| closure_slave_num | int | Slave index of the closure point; -1 = no closure point. It is also -1 when the model is unknown, but that means "not known" |
| mode | int | Raw value returned by the SDK: 0 = line / 1 = ring / 2 = ring + branch; -1 = not obtained |
| chain_form | Optional[int] | 0 = linear / 1 = chain (foldback at the end); only has a value when mode == 0, otherwise None |
| ring_slave_nums | List[int] | List of ring member slave indices (length = ring_count; available only when model_known=True) |
| model_known | bool | Whether the SDK really computed this model (return code 0) |
| unavailable_reason | Optional[str] | Reason the model is unavailable (non-empty when model_known=False) |
chain_form values:
| Value | Meaning |
|---|---|
None | Not applicable (ring / ring + branch / unknown model) |
0 | Linear |
1 | Chain (foldback at end) |
chain_formonly has a value whenmode == 0. Under ring / ring + branch / unknown model the field is a placeholder0that does not mean linear, so this layer does not expose it (it returnsNone). Whenmode == 0and a value other than0/1comes back, it is exposed as is, without guessing.- With
model_known=False,ring_count/branch_count/closure_slave_num/ring_slave_nums/chain_formare all unavailable — that means "not computed", not "linear / no ring / no closure point". The caller must look atmodel_knownfirst. - Linear and chain (foldback at end) both have no ring. Linear = the end is a single active port and all slaves are in series; chain (foldback at end) = the end folds back inside a single port (the primary port sends and the secondary port receives, the whole chain is traversed twice), with no redundancy protection. Do not call
chain_form"the only criterion for whether redundancy exists".
Return codes and failure semantics:
| Return code | Meaning |
|---|---|
0 | Success; every slave has a definite assignment and the conclusion is supported by this cycle's measurements |
-1 | Parameter error |
-2 | No / missing measured port evidence (any slave with phys_ap == 0) |
-3 | The topology input is degenerate and cannot prove the form (invalid / duplicate slave indices, too many closure candidates, broken closure chain) |
-4 | Conclusion undecided (there are UNKNOWN slaves / candidate closure points are mutually exclusive / insufficient link evidence) |
A negative value always means "no reliable answer"; in that case the underlying library writes no result, and this layer sets model_known=False and fills unavailable_reason — it never disguises "not computed" as "linear / no ring".
When the underlying library is too old to support this query, the call raises NotImplementedError; the SDK likewise reports model_known=False and writes unavailable_reason without returning a false "linear" conclusion. The newer underlying implementation only returns one extra field, chain_form; every other field equals the older implementation field by field, with unchanged meaning.
Example:
info = master.slave_topology.compute_ring_branch()
if not info.model_known:
print("拓扑模型不可用:", info.unavailable_reason) # not computed != linear
elif info.mode == 0:
print("无环形态:", info.chain_form_text) # linear / chain (foldback at end)
print("总站数:", info.total_count) # Total slave count:
elif info.mode == 1:
print("环形:", info.ring_slave_nums) # Ring:
elif info.mode == 2:
print("环+分支: 环", info.ring_count, "分支", info.branch_count, # Ring + branch: ring N, branch M
"闭合点", info.closure_slave_num) # closure point: N
else:
print("未知 mode:", info.mode) # Unknown mode:
New code should use compute_ring_branch() uniformly.
Per-slave reachable leg / liveness reason / clean OP / SYNC0 armed
The per-slave conclusions are read through the public high-level interfaces:
| Conclusion | Public API | Returns | R/W | Description |
|---|---|---|---|---|
| Slave loss reason | master.events.try_get_slave_offline_reason(slave_index) | Optional[SlaveOfflineReason] | Read-only | Read-only cache / existing conclusion; sends no frames; for the classification see Events |
| Clean OP / real OP | master.diagnostics_info.evaluate_slave_real_op(slave) | Optional[SlaveRealOpState] | Read-only | Per-slave real OP verdict; AlCleanOp is the clean OP |
| SYNC0 armed | slave.dc_config.get_sync_window_status() | Optional[SyncWindowStatus] | Read-only | None = the underlying layer cannot answer; it must not be collapsed to False |
Reachable legs / evidence bits currently have no public read entry point; for the public redundancy conclusions see Redundancy status.
"Cannot answer" (model not ready / insufficient evidence / criterion unavailable) is not the same as "not armed / no ring / not clean": treat it uniformly as "conclusion unavailable", and never collapse it to False or 0.
DC synchronization
Automatic monitoring (ETG.1500 5.13.3) checks the time deviation of each slave every second. Exceeding the sync_window_threshold threshold triggers the dc_sync_lost event.
For the synchronization state of an individual slave use slave.diagnostics.dc.is_in_sync and slave.diagnostics.dc.sync_time_difference.
| Category | Property | Type | R/W | Description |
|---|---|---|---|---|
| DC summary | diagnostics_info.dc_has_dc | bool | Read-only | Whether the network contains slaves with DC capability; returns False when the summary cannot be read (this bit has no unknown state) |
| diagnostics_info.dc_all_in_sync | Optional<bool> | Read-only | Whether all DC slaves are inside the synchronization window. True = all inside; False = some slave is outside, or the failure conclusion "zero DC-active participants"; None = the summary cannot be read (unknown; True / False is not substituted). Note that older runtimes return True when there is no DC slave (that means "nothing can lose sync", not "synchronized"); for the tri-state participant semantics read dc_diagnostics.all_in_sync | |
| diagnostics_info.dc_max_drift_ns | int | Read-only | Current maximum absolute system time difference across all DC slaves (nanoseconds). 0 is the default of the summary surface; it does not distinguish between having no DC slave, not being armed, and a measurement of exactly 0 ns; for the tri-state read dc_diagnostics.max_drift_ns | |
| diagnostics_info.dc_reference_clock_slave | int | Read-only | Reference clock slave index (1-based); 0 = no DC slave in the network, or the summary cannot be read | |
| DC cycle | master.dc_auto_shift | bool | Read/write | DC auto-shift switch: when enabled, the master computes the optimal shift during DC configuration and issues it; this property has no None tri-state |
| Propagation delay | master.dc_propagation_delay_resolve_count | int | Read-only | Number of propagation delay resolutions actively triggered by the SDK and successful within this process; 0 is a valid count (= no such resolution observed) |
| master.dc_propagation_delay_resolved_at_utc | Optional<datetime> | Read-only | Time of the most recent successful resolution of this kind (UTC); None = not observed by this process. That time is not the physical measurement time (the same session may reuse an existing baseline) |
The trigger entry points are configure_dc() / update_propagation_delays() / auto_calculate_dc_shift(): one entry is recorded only when the SDK actively initiates the resolution and it succeeds. The same-named fields on the master.dc_diagnostics 2-second snapshot are taken directly from these two master properties — it is the same accounting entry, not two independent statistics.
sync_window_threshold
@property
def sync_window_threshold(self) -> int
@sync_window_threshold.setter
def sync_window_threshold(self, value: int) -> None
Synchronization window threshold (ns), default 1000 ns. Exceeding the threshold triggers the dc_sync_lost event.
set_dc_cycle_time()
def set_dc_cycle_time(self, time_ns: int)
Sets the master DC cycle time (nanoseconds). The DC cycle and the PDO cycle are independent of each other: changing only the DC cycle does not change the PDO cycle, and vice versa.
Parameters:
time_ns(int) — DC cycle time (nanoseconds)
Return value:
- None. The method does not report success / failure; to confirm the value actually in effect, read the slave-side DC configuration mirror (for example
slave.dc_config.sync0_cycle_ns).
Example:
# DC cycle 1 ms, configured separately from the PDO loop cycle
master.set_dc_cycle_time(1_000_000)
DC diagnostics 2-second snapshot
master.dc_diagnostics and master.diagnostics_info.dc_diagnostics return the same object (DcDiagnosticsSnapshot): the per-slave and master-level DC conclusions are assembled in one go, and every consumer within the same 2-second window shares the same copy, avoiding the split in readings caused by each column reading its own set.
Everything the snapshot reads is a local cache (the underlying slave cache / synchronization state cache / armed mask); it sends no bus frames and can be read on the UI thread or a diagnostics thread. The cache TTL is 2 seconds: after it expires the next read reassembles. The sampling history window holds 25 samples (about 50 seconds) and is used for frozen-reading decisions and steady-state jitter.
| Category | Field | Type | R/W | Description |
|---|---|---|---|---|
| DC diagnostics | captured_at_utc | datetime | Read-only | Assembly time of this cycle (UTC) |
| DC diagnostics | has_dc | bool | Read-only | Whether the network has slaves with DC capability (capability bit scale) |
| DC diagnostics | all_in_sync | Optional[bool] | Read-only | Whether all SYNC0 participants are inside the synchronization window. No confirmed participants → None (not True); participants not sampled / not readable / not in the window → False; any DC slave with an unknown armed state → conservatively False |
| DC diagnostics | max_drift_ns | Optional[int] | Read-only | Maximum absolute synchronization difference among all usable windows (ns). No usable window at all → None (not 0) |
| DC diagnostics | sync_window_threshold_ns | Optional[int] | Read-only | Synchronization window threshold (ns); None = cannot read |
| DC diagnostics | reference_clock | DcReferenceClockInfo | Read-only | Reference clock facts: slave_index (0 = none), tier, tier_text, is_chain_head_fallback, known. When there is no reference clock an explicit DcReferenceClockInfo.none() instance is given; no empty reference is left |
| DC diagnostics | armed_slave_count | int | Read-only | Number of slaves with SYNC0 armed (of the DC-capable slaves, those with sync0_armed is True); 0 is a valid count |
| DC diagnostics | active_slave_count | int | Read-only | Number of DC-active slaves (0x0980 effective value not 0); 0 is a valid count |
| DC diagnostics | armed_unknown_count | int | Read-only | Number of slaves whose armed verdict is unknown (the underlying layer cannot answer); 0 is a valid count |
| DC diagnostics | armed_sync_participant_count | int | Read-only | Number of SYNC0 synchronization participants (armed + not the reference clock); 0 = no slave for which synchronization can be discussed |
| DC diagnostics | applicable_window_count | int | Read-only | Number of slaves with a measured window; when it is 0, max_drift_ns is necessarily None |
| DC diagnostics | active_without_process_data_count | int | Read-only | Number of DC-active slaves without process data bytes; 0 is a valid count |
| DC diagnostics | expected_wkc | int | Read-only | Expected master WKC (fixed true value from configuration time, never lowered) |
| DC diagnostics | propagation_delay_resolved_at_utc | Optional[datetime] | Read-only | Time of the most recent successful propagation delay resolution actively triggered by the SDK (UTC); None = not observed by this process. That time is not the physical measurement time (the underlying library may reuse the in-session baseline) |
| DC diagnostics | propagation_delay_resolve_count | int | Read-only | Number of successful propagation delay resolutions actively triggered by the SDK; 0 is still a valid count |
| DC diagnostics | slaves | Tuple[DcSlaveSnapshot, ...] | Read-only | Per-slave snapshots (ascending by slave index) |
| DC diagnostics | find(slave_index) | Optional[DcSlaveSnapshot] | Read-only | Single-slave snapshot by slave index; out of range / not sampled returns None |
| DC diagnostics | any_read_failure | bool | Read-only | At least one slave / the reference clock failed to read in this cycle (failed items already land as Unknown / None) |
Main fields of the per-slave snapshot DcSlaveSnapshot:
| Category | Field | Type | R/W | Description |
|---|---|---|---|---|
| DC diagnostics | slave_index / name | int / str | Read-only | Slave index (1-based) and display name |
| DC diagnostics | has_dc | bool | Read-only | ESC capability bit (a hardware fact; does not mean it is enabled) |
| DC diagnostics | capability | DcCapability | Read-only | Capability tier (ESC + ESI) |
| DC diagnostics | arm_outcome | Optional[DcArmResult] | Read-only | Final armed outcome — always None in this SDK (unavailable); arm_outcome_available is always False; for the unavailable reason see arm_outcome_unavailable_reason |
| DC diagnostics | assign_activate / sync0_cycle_ns / sync1_cycle_ns / shift_ns | Optional[int] | Read-only | Effective mirror of 0x0980 / 0x09A0 / 0x09A4 / phase shift |
| DC diagnostics | propagation_delay_ns / propagation_delay_origin | Optional[int] / DcPropagationDelayOrigin | Read-only | Effective 0x0928 value and origin tier (the 0 ns ambiguity is not guessed away) |
| DC diagnostics | sync0_armed | Optional[bool] | Read-only | SYNC0 armed tri-state; None = cannot decide, not collapsed to False |
| DC diagnostics | sync_window | DcSyncWindowInfo | Read-only | Synchronization window (including the N/A reason and the frozen proxy bit) |
| DC diagnostics | jitter / convergence_ms / convergence_measured_at_utc | Optional[DcJitterStats] / Optional[int] / Optional[datetime] | Read-only | Steady-state jitter and convergence time (from the 2-second sampling history); insufficient samples / no complete transition observed → None |
| DC diagnostics | output_bytes / input_bytes | int | Read-only | Process image byte counts (to decide "has PDO") |
| DC diagnostics | is_dc_active / is_reference_clock | bool | Read-only | Effective 0x0980 value not 0 / whether this slave is the reference clock |
The master level also has direct entry points: master.dc_armed_slave_count / master.dc_active_slave_count (equivalent to the same-named fields of the snapshot).
0 / True for a tri-stateall_in_sync, max_drift_ns and the per-slave sync0_armed are all tri-state. "No confirmed participants", "no usable window" and "the underlying layer cannot answer" always give None and are never written as True / 0 / False. The synchronization window of the reference clock itself is always not applicable and likewise never produces 0 ns.
Example:
snap = master.dc_diagnostics # the same object as master.diagnostics_info.dc_diagnostics
print(f"DC 站: 武装 {snap.armed_slave_count}, DC-active {snap.active_slave_count}, " # DC slaves: armed {snap.armed_slave_count}, DC-active {snap.active_slave_count},
f"武装未知 {snap.armed_unknown_count}") # arm state unknown {snap.armed_unknown_count}
print(f"全部在窗: {snap.all_in_sync}") # None = no confirmed participants
print(f"最大同步差: {snap.max_drift_ns}") # None = no usable window
ref = snap.reference_clock
if ref.known:
print(f"参考钟: 从站 {ref.slave_index} ({ref.tier_text})") # Reference clock: slave {ref.slave_index} ({ref.tier_text})
entry = snap.find(1)
if entry is not None and entry.sync_window.applicable:
print(f"从站 1 同步差 {entry.sync_window.diff_ns} ns, " # Slave 1 sync diff {entry.sync_window.diff_ns} ns,
f"冻结 {entry.sync_window.reading_unchanged}") # frozen {entry.sync_window.reading_unchanged}
The same-named per-slave properties (slave.dc_config.capability / sync0_armed / sync_window and so on) can be read directly, but they do not include the historical conclusions (frozen reading / jitter / convergence exist only on the 2-second sampling surface).
Redundancy status
| Category | Property | Type | R/W | Description |
|---|---|---|---|---|
| Redundancy status | redundancy_active | bool | Read-only | Redundancy protection is running = master.redundancy_ring_mode >= RingMode.DUAL and both ports carry frame traffic in this window; always false for line / end foldback topologies |
| break_point | Optional[dict] | Read-only | Current fault point (count, slave_index, port, type); None means both "genuinely no fault" and "query failed" — to tell them apart use master.get_break_points() (None = failure, an empty list = succeeded and no fault) |
RingMode enum:
class RingMode(IntEnum):
UNKNOWN = -1 # unknown: cannot be read / value out of range (must not be folded to INACTIVE)
INACTIVE = 0 # not active
DUAL = 1 # bidirectional redundancy
DEGRADED = 2 # degraded mode
redundancy_active means "redundancy protection is running", not "both ports carry frames"redundancy_active = master.redundancy_ring_mode >= RingMode.DUAL and the primary / secondary port both carry frame traffic in this window. In a chain (end foldback) topology the primary port sends and the secondary port receives, the whole chain is traversed twice and both ports carry frames, but physically there is no second independent path — this property is False, consistent with redundancy_ring_mode == INACTIVE.
To see "whether both ports carry frames", read primary_port_ok / secondary_port_ok and the primary / secondary port TX/RX counts; do not infer it from this property. slave.diagnostics.redundancy_activated is the same master-level criterion (RingMode >= 1), not an independent per-slave conclusion.
break_point returns a dict containing the following fields:
{
'count': int, # number of fault points
'slave_index': int, # faulty slave index (1-based)
'port': int, # faulty port number (0-3)
'type': int, # fault type: 0=link break, 1=CRC fault
}
break_point detects two kinds of physical fault in one place:
| Type | fault_type | Detection | Typical scenario |
|---|---|---|---|
| Link break | 0 | Port physical link lost in DL Status | Cable unplugged, cable broken |
| CRC fault | 1 | Port-level RxError + InvalidFrame keep rising | Poor contact, aged cable, oxidized connector |
None break_point does not mean "no fault"break_point returning None means both "genuinely no fault" and "query failed" (this return type has no third state). To tell them apart use master.get_break_points(): None = query failed, an empty list = query succeeded and there is no fault. An empty list must not be taken as "query failed", and None must not be taken as "no fault".
Locating a faulty cable segment: when the facing ports of adjacent slaves (for example P1 of slave N and P0 of slave N+1) report a fault at the same time, the cable connecting them is the problem. A fault reported on one side only points to the connector of that port.
Example:
diag = master.diagnostics_info
print(f"冗余模式: {master.redundancy_ring_mode.name}") # Redundancy mode: {master.redundancy_ring_mode.name}
if master.redundancy_ring_mode == RingMode.DEGRADED:
print("警告: secondary链路不可用") # Warning: secondary link unavailable
if diag.redundancy_active:
print("冗余已激活") # Redundancy activated
bp = diag.break_point
if bp is not None:
print(f"故障: 从站{bp['slave_index']} P{bp['port']} " # Fault: slave{bp['slave_index']} P{bp['port']}
f"{'断线' if bp['type'] == 0 else 'CRC故障'}") # {'cable break' if bp['type'] == 0 else 'CRC fault'}
if bp['type'] == 1:
print("建议检查线缆/连接器") # Check the cable / connector
Diagnostics control
| Category | Property | Type | R/W | Description |
|---|---|---|---|---|
| Diagnostics control | master.diagnostics_enabled | bool | Read/write | Master-level collection switch: only the switch itself is issued, and it does not start or stop the SDK-side sliding-window sampling timer; when it cannot be read it returns False (this property has no unknown state) |
| diagnostics_info.enabled | bool | Read/write | Diagnostics-object-level collection switch: writing True also starts the SDK-side sliding-window sampling timer, writing False stops it |
Both read and write the same collection switch; the only difference is the side effect on the sampling timer: master.diagnostics_enabled = True only turns the switch on and does not start SDK-side sliding-window sampling; to get the statistics of the last 5-second sliding window (frame rate, packet loss rate and so on) use master.diagnostics_info.enabled = True.
Reset (diagnostic counters)
@property
def enabled(self) -> bool # SDK-side sliding-window sampling timer switch
def reset(self) -> None # reset all diagnostic statistics at once
enabled only controls the SDK-side sliding-window sampling timer (statistics over the last 5-second window); it is not the master switch for diagnostic collection: WKC / packet loss / DC / port diagnostics are always collected and the criteria are unaffected. reset() resets the basic statistics, the PDO frame loss statistics of groups 0–7 and the SDK-side sliding window; the DC synchronization window statistics and the slave port counters have their own reset entry points (see DC synchronization and slave diagnostics).
AL error classification
Classifies the AL Status Code to help judge the nature of an error and the handling strategy quickly.
classify_al_error()
def classify_al_error(al_status_code: int) -> 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 single authority for the classification is the underlying library; the Python-side classify_al_error() only maps the enum 0=None / 1=TRANSIENT / 2=CONFIGURATION / 3=HARDWARE / 4=UNKNOWN and holds no local classification table. It returns UNKNOWN when the underlying layer is unavailable.
Parameters:
al_status_code(int) — AL Status Code, obtained fromslave.error_code(EcALStateenum, an IntEnum that can be passed directly) or when a state transition fails
Return value:
ALErrorCategory— error category enum
ALErrorCategory enum:
class ALErrorCategory(IntEnum):
NONE = 0 # no error
TRANSIENT = 1 # transient error; retry the state transition, it 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, cable and power supply
UNKNOWN = 4 # unknown error; consult ETG.1000 or the slave manual
Example:
from darra_ethercat import classify_al_error, ALErrorCategory, EcALState
slave = master[1]
if slave.error_code != EcALState.NO_ERROR:
category = classify_al_error(slave.error_code)
print(f"从站 {slave.slave_num} 错误 0x{slave.error_code.value:04X}: {category.name}") # Slave {slave.slave_num} error 0x{slave.error_code.value:04X}: {category.name}
if category == ALErrorCategory.TRANSIENT:
print("瞬态错误,尝试重新切换状态...") # Transient error, retrying the state transition...
elif category == ALErrorCategory.CONFIGURATION:
print("配置错误,请检查 PDO/SM 配置") # Configuration error, check the PDO/SM configuration
elif category == ALErrorCategory.HARDWARE:
print("硬件错误,请检查从站设备") # Hardware error, check the slave device
classify_al_error actually returns is in parentheses)0x0011invalid state change (EcALState.INVALID_STATE_CHANGE) — TRANSIENT0x0015invalid mailbox configuration in BOOT state (EcALState.INVALID_MAILBOX_CONFIG) — CONFIGURATION0x001Einvalid input configuration (EcALState.INVALID_INPUT_CONFIG) — CONFIGURATION0x002Dsync not received (EcALState.NO_SYNC_ERROR) — TRANSIENT0x0034DC synchronization timeout (EcALState.DC_SYNC_TIMEOUT) — TRANSIENT0x0050EEPROM no access permission (EcALState.EEPROM_NO_ACCESS) — HARDWARE0x0051EEPROM error (EcALState.EEPROM_ERROR) — HARDWARE
Values not in the built-in code table return UNKNOWN (for example 0x002F, which neither standard table defines); the defined codes 0x0041-0x0045, 0x004F and 0x0050-0x0052 map to HARDWARE — undefined codes are not inferred from their high-order segment. For per-code meaning, use the native AL status table (status_codes.c).
Slave error counters
| Category | Property | Type | R/W | Description |
|---|---|---|---|---|
| Slave error count | SlaveErrorCounters.total_crc_errors | int | Read-only | Total CRC errors = the sum of the CRC errors of the four ports port0~port3; derived from the port fields and not stored separately |
Related structure:
class SlaveErrorCounters:
# Construct: SlaveErrorCounters(slave_index=0)
slave_index: int # slave index
port0_crc_errors: int # CRC / RX error counter for P0
port1_crc_errors: int # CRC / RX error counter for P1
port2_crc_errors: int # CRC / RX error counter for P2
port3_crc_errors: int # CRC / RX error counter for P3
frame_errors: int # total invalid frames across the four ports
lost_frames: int # total lost links across the four ports
master.diagnostics_info.read_slave_error_counters(i) returns a dict (three per-port lists under rx_error / invalid_frame / lost_link), not an instance of this class. SlaveErrorCounters is an aggregate view of the per-port CRC and frame errors / link loss; import it from the darra_ethercat top level; the caller fills in the fields, and total_crc_errors is always summed in real time from the four port fields.
read_slave_error_counters()
def read_slave_error_counters(self, slave_index: int) -> Optional[dict]
Reads the error counters of the specified slave (ESC registers 0x0300-0x0307).
Parameters:
slave_index(int) — slave index (1-based)
Return value:
Optional[dict]— error counter dict; a failed read returns None (it does not return all 0s to fake "no errors"). The dict contains the following fields:
{
'slave_index': int, # slave index
'rx_error': List[int], # per-port RX error count [Port0-3]
'invalid_frame': List[int], # per-port invalid frame count [Port0-3]
'lost_link': List[int], # per-port link loss count [Port0-3]
}
Example:
counters = master.diagnostics_info.read_slave_error_counters(1)
if counters and any(v > 0 for v in counters['rx_error']):
print(f"从站 1 错误计数:") # Slave 1 error counters:
print(f" RX 错误: {counters['rx_error']}") # RX errors: {counters['rx_error']}
print(f" 无效帧: {counters['invalid_frame']}") # Invalid frames: {counters['invalid_frame']}
print(f" 链路丢失: {counters['lost_link']}") # Link lost: {counters['lost_link']}
Diagnostic messages
read_diagnostic_messages()
from darra_ethercat.slave.coe import read_diagnostic_messages
def read_diagnostic_messages(coe: CoE) -> List[DiagnosticMessage]
Reads the diagnostic messages in slave object 0x10F3 (diagnostic history object, ETG.1510) over CoE. Returns the list of diagnostic events recorded by the slave; each entry contains sub_index / diag_code (diagnostic code) / flags / text_index / raw_data.
Parameters:
coe(CoE) — the slave's CoE interface (slave.coe)
Return value:
List[DiagnosticMessage]— list of diagnostic messages; an empty list when there are none (at most 20 entries)
Example:
from darra_ethercat.slave.coe import read_diagnostic_messages
for slave in master.slaves:
if slave.coe is None:
continue
messages = read_diagnostic_messages(slave.coe)
for msg in messages:
print(f"[从站 {slave.slave_num}] 代码=0x{msg.diag_code:08X}, {msg}") # [Slave {slave.slave_num}] code=0x{msg.diag_code:08X}, {msg}
Not every slave supports the 0x10F3 diagnostic history object. Calling it on an unsupported slave returns an empty list. This method reads over SDO, so calling it frequently on the real-time path is not recommended.
Diagnostics field guide by problem
This chapter is organised by on-site symptom to help you locate the problem. Note the difference in data sources:
get_slave_diagnostics()only populateslink_quality_percent, and the remaining fields ofSlaveDiagnosticsDatakeep their default 0; for real-time statistics useMasterDiagnosticsInfo, events or the port error count API.
Site problem → field mapping
Object each field belongs to:
D=SlaveDiagnosticsData(viaget_slave_diagnostics());M=master.diagnostics_info(MasterDiagnosticsInfo).
- Packet loss? —
packet_loss_rate(M); for frame loss counts seepdo.total_lost(M) and Events.PDOFrameLoss - Sporadic or persistent? —
pdo.consecutive_lost/pdo.get_frame_loss_stats().max_consecutive_lost(M) - Which slave has poor link quality? —
link_quality_percent[i](D) /worst_slave_index(M) - Unstable cable contact? —
read_slave_error_counters(i)['lost_link']orslave.diagnostics.read_port_errors().lost_link - Which cable is broken? —
break_point(M) - Primary or secondary port errors? —
primary_port_errors/secondary_port_errors(M) - Is redundancy really protecting? —
redundancy_active(M) (already includesredundancy_ring_mode >= DUALand frames on both ports; to check only whether both ports carry frames, read the primary / secondary port TX/RX counts) - Is the bus load high? —
bus_load_percent(M)
Frame error fields (present on SlaveDiagnosticsData, currently not populated)
SlaveDiagnosticsData declares the following fields, but get_slave_diagnostics() does not populate them (they are always the default 0). For real-time frame error statistics use error_cnt / pdo.* of MasterDiagnosticsInfo and events (Events.PDOFrameLoss and so on):
lost_frames— the frame never came backtimeout_frames— no response received within the PDO cycleworking_counter_errors— WKC mismatchconsecutive_wkc_errors— consecutive WKC errorsframe_errors— derived totalchecksum_errors— physical-layer CRC
Port error counts
primary_port_errors / secondary_port_errors— primary / secondary NIC errors over the 5-second sliding window. OnMasterDiagnosticsInfothese are real-time values; the same-named fields onSlaveDiagnosticsDataare not populated.- For per-slave ESC port errors use
master.diagnostics_info.read_slave_error_counters(i)orslave.diagnostics.read_port_errors().
Per-slave physical layer (ESC registers)
SlaveDiagnosticsData is obtained through the module-level function get_slave_diagnostics(dll, master_index, slave_count) (located in darra_ethercat.master.other); EtherCATMaster has no get_diagnostics() method. The data class provides the following per-slave list fields (index = slave index, 1-based):
link_quality_percent[i]— link quality percentage of slave i (0-100, -1 = unknown), actually populated byget_slave_diagnostics()port_error_count[i]— total port errors of slave i (not populated, always 0; useread_slave_error_counters(i))lost_link_count[i]— link loss count of slave i (not populated, always 0; useread_slave_error_counters(i)['lost_link'])
SlaveDiagnosticsData global statistics fields
The scalar fields of SlaveDiagnosticsData (designed for the 5-second sliding window scale; all of them come back as the default 0 through get_slave_diagnostics()):
frame_errors— global frame error totallost_frames— global lost frame totalchecksum_errors— physical-layer CRC errorstimeout_frames— number of timed-out framesworking_counter_errors— total WKC errorsconsecutive_wkc_errors— consecutive WKC errorsprimary_port_errors / secondary_port_errors— primary / secondary port errors over the 5-second window
RT performance + runtime stability
The following fields are properties of master.diagnostics_info (MasterDiagnosticsInfo) and are not on SlaveDiagnosticsData:
bus_cycle_hz— RT frame frequencybus_max_jitter_us / bus_avg_jitter_us— bus jitterbus_roundtrip_us— RTTbus_load_percent— communication load (>70% requires reducing the frequency)
Complete diagnostics flow example
from darra_ethercat.master.other import get_slave_diagnostics
# MasterDiagnosticsInfo object (frame rate / jitter / packet loss / fault point / bus load)
diag = master.diagnostics_info
# SlaveDiagnosticsData snapshot — per-slave link quality
# dll is the SDK runtime instance; master_index / slave_count come from the master object
slave_diag = get_slave_diagnostics(dll, master.master_index,
master.slave_count)
# 1. Persistent vs sporadic (consecutive PDO frame loss)
if diag.pdo.consecutive_lost >= 5:
print(f"⚠️ 持续 PDO 丢帧 (连续 {diag.pdo.consecutive_lost})") # ⚠️ Persistent PDO frame loss (consecutive {diag.pdo.consecutive_lost})
elif diag.pdo.consecutive_lost > 0:
print("偶发 PDO 丢帧") # Occasional PDO frame loss
# 2. Packet loss rate (MasterDiagnosticsInfo)
if diag.packet_loss_rate > 0.01:
print(f"⚠️ 丢包率 {diag.packet_loss_rate:.2%} 严重") # ⚠️ Packet loss {diag.packet_loss_rate:.2%} is severe
# 3. Fault location (break_point returns a dict)
bp = diag.break_point
if bp is not None:
print(f"故障点: 从站 {bp['slave_index']} P{bp['port']}") # Fault location: slave {bp['slave_index']} P{bp['port']}
# 4. Slave with the worst link quality (link_quality_percent list, 1-based index)
if slave_diag and slave_diag.link_quality_percent:
lq = slave_diag.link_quality_percent
worst = min((i for i in range(1, len(lq)) if lq[i] >= 0), key=lambda i: lq[i], default=None)
if worst is not None and lq[worst] < 100:
print(f"链路质量最差从站: #{worst} ({lq[worst]}%)") # Slave with the worst link quality: #{worst} ({lq[worst]}%)
# 5. Cable contact diagnostics (per-slave ESC link loss counts)
for slave in master.slaves:
counters = diag.read_slave_error_counters(slave.slave_num)
if counters and any(n > 0 for n in counters['lost_link']):
print(f"从站 {slave.slave_num} 链路丢失: {counters['lost_link']}") # Slave {slave.slave_num} link lost: {counters['lost_link']}
# 6. Bus load (MasterDiagnosticsInfo)
if diag.bus_load_percent > 70:
print(f"⚠️ 总线负载 {diag.bus_load_percent:.1f}%, 必须降频") # ⚠️ Bus load {diag.bus_load_percent:.1f}%, the rate must be reduced
diagnose_nic_health / verify_nic_health are meaningful only in real-time driver mode; outside it they return -1. auto_recover_nic() returns 1 = recovery succeeded, 0 = failed (non-real-time driver mode also returns 0, which does not mean recovery succeeded), and has no -1 semantics. The first two are read-only diagnostics; only auto_recover_nic() performs one explicit RT soft restart, and the SDK never calls it on its own, nor does it restart RT, disable or enable a NIC during diagnostics. For NIC binding repair use the official installer.