Master diagnostics
Call master.GetDiagnostics() to get a Diagnostics& reference, then construct MasterDiagnosticsInfo from it to reach the higher-level statistics.
C++ SDK diagnostics have two layers:
Diagnostics— the lower-level class returned directly bymaster.GetDiagnostics(). It providesEnabled()/ExpectedWKC()/SlaveLinkQuality()/GetBreakPoints()/RingMode()/GetPDOFrameLossStats()/PrimaryWKC()/SecondaryWKC()/BusRoundtripUs()/BusLoadPercent()/BusCycleHz()/PacketLossRate()/LateFrameRate()/BusMaxJitterUs()/Summary()/ZeroWkcCount()and so on.MasterDiagnosticsInfo— the higher-level wrapper class, constructed fromDiagnostics&; it providesRTcnt()/ErrorCnt()/CycleTimeSpan()/AvgJitterUs()/MailboxLatencyUs()/MailboxLatencyAvgUs()/WorstSlaveIndex()/WorstLinkQuality()/PrimaryPortOk()/TopologyDescription()/GetSnapshot()/Reset()/SyncWindowThreshold()/ReadSlaveErrorCounters()/RtPreemptCount()/CycleCount()/HardwareSmiCounterAvailable()and other properties and real-time diagnostics.
In the examples below, any object named diag that uses properties such as RTcnt() / CycleTimeSpan() / GetSnapshot() /
WorstSlaveIndex() / Reset() should be a MasterDiagnosticsInfo instance:
auto& base = master.GetDiagnostics(); // Diagnostics&
MasterDiagnosticsInfo diag(base, master.MasterNumber()); // High-level wrapper
Drive exception handling from events instead of polling on your own. Reading diagnostic properties directly suits scenarios such as UI display.
Get the diagnostics object
// Underlying Diagnostics
auto& base = master.GetDiagnostics();
// High-level MasterDiagnosticsInfo (the properties on this page all live at this level)
MasterDiagnosticsInfo diag(base, master.MasterNumber());
The Diagnostics object is created lazily and allocated automatically on the first call to GetDiagnostics().
MasterDiagnosticsInfo is a lightweight wrapper that holds Diagnostics&; construct it whenever you need it.
Feature overview
| Feature | Description |
|---|---|
| Communication and performance statistics | Frame counts, packet loss, jitter, mailbox latency, PDO frame loss, WKC, ports |
| WKC mirror (lost slaves are observable) | expected / actual / deficit and per-slave location |
| Real OP verdict | Per-slave and master-level real OP conclusions |
| Hot-plug rebuild / P1 foldback topology | Hot-plug rebuild at runtime; foldback calibration results and slave reachability |
| DC synchronization | Sync window threshold, DCSyncLost event, DC diagnostics 2-second snapshot |
| Redundancy status / Physical link tri-state | Redundancy mode, fault point location; single-port link tri-state |
| Diagnostics snapshot / Recovery ladder observation | Everything in one read; recovery level / step, backoff and event cursor |
| AL error classification | Error code to action |
| Sliding window statistics (DiagCsWindow) | 5s × 0.2s error rate / frequency / jitter aggregation |
| Link diagnostic events | Link-down / recovery events, incremental reads by cursor |
| Diagnostics control / Hard real-time | Sampling switch and statistics reset; honest RT counters and jitter / wake path |
| Transmit and receive path counters | Primary / secondary port frame-level transmit and receive, receive drops and transmit fallback totals |
Communication and performance statistics
All properties are accessed through C++ property-style methods (methods with no parameters that return a value).
| Category | Property | Type | Read/write | Description |
|---|---|---|---|---|
| Frame counts | RTcnt() | uint32_t | Read-only | Frames per second (Hz), 5-second average. The frame rate follows the PDO cycle (see Configuration § LoopCycle); do not hard-code 1000 Hz |
| ErrorCnt() | uint32_t | Read-only | Errors per second | |
| PacketLossRate() | float | Read-only | Packet loss rate (0.0~1.0) = merged bus WKC deficit / expected WKC (instantaneous value); 0 = no frame was really lost (a seamless redundancy takeover counts as no loss); only a cold start that has not reached OP falls back to the TX/RX counter difference | |
| LateFrameRate() | float | Read-only | Late frame rate (0.0~1.0): the frame is still missing after the 8-frame window and is not counted as packet loss | |
| Cycle and jitter | CycleTimeSpan() | double | Read-only | Actual cycle time (microseconds); compare it against the configured cycle, it is not hard-coded to 1 ms |
| AvgJitterUs() | double | Read-only | Average jitter over the last 5 seconds (microseconds). Jitter grows when isolation is not in effect; the cycle should still hold at the configured value | |
| BusCleanMaxJitterUs() | double | Read-only | Maximum bus jitter with a clean bus (microseconds, SMI interference excluded). Read it together with BusMaxJitterUs(); the difference is the effect of SMI on transmit timing. Returns 0.0 when the snapshot is unavailable | |
| Mailbox latency | MailboxLatencyUs() | double | Read-only | Maximum mailbox transaction round-trip time (microseconds, settled over the last 1 second). A mailbox transaction (CoE/SoE/FoE/EoE/AoE/VoE and other acyclic request-response traffic), from request sent to response received |
| MailboxLatencyAvgUs() | double | Read-only | Average mailbox transaction round-trip time (microseconds, settled over the last 1 second, same definition as above) | |
| PDO frame loss | GetPDOFrameLossStats(group) | PDOFrameLossStats | Read-only | PDO frame loss statistics for the given group (0-7), called on the lower-level Diagnostics; an out-of-range group returns all 0s without an error. For group-level criteria and actions see Group diagnostics |
| Slave anomalies | WorstSlaveIndex() | int | Read-only | Index of the slave with the highest error rate |
| WorstLinkQuality() | float | Read-only | Worst slave communication health (%, lower is worse); -1 = unknown | |
| WKC | PrimaryWKC() | uint16_t | Read-only | Primary-port WKC — a peak latch that persists across cycles and does not drop when a slave is unplugged; for the live value use base.PrimaryWkcRt() |
| SecondaryWKC() | uint16_t | Read-only | Secondary-port WKC (measured in this cycle); returns WkcUnknown (0xFFFF) when this cycle has no measurement, never a stale full reading | |
| base.SecondaryWkcKnown() | bool | Read-only | Whether the secondary port has a measurement in this cycle; false only means the value is WkcUnknown, while 0 on a single-port setup still counts as known (this entry point is on the lower-level Diagnostics) | |
| base.PrimaryWkcRt() / base.SecondaryWkcRt() | uint16_t | Read-only | Real-time filtered values for the primary / secondary port; they drop in the same cycle a slave is unplugged; 0 is a valid reading (these entry points are on the lower-level Diagnostics) | |
| Master truth | LostSlaveCount() | int | Read-only | Lost-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 |
| NoProcessData() | bool | Read-only | Master-level "no process data / false OP" truth value: true = the cycle is running but the process data is dead; returns true on a read failure (fail-safe; missing evidence is never passed off as healthy) | |
| NoProcessDataKnown() | bool | Read-only | Whether NoProcessData() has a measured sample; when false the return value carries no meaning and must be shown as "unknown" | |
| ProbeAliveCount() / ProbeUnknownCount() | int | Read-only | Probe truth summary (number of slaves that answered / number of slaves with insufficient evidence); 0 when there is no true-value sample | |
| StaleInputCount() | int | Read-only | Number of slaves whose input data is confirmed STALE (per slave InputDataValidity()==Stale); Unknown / Degraded are not counted; -1 = a slave read failed / is unavailable | |
| Cycle run | CycleState() | CycleRunState | Read-only | Master cycle tri-state: NotStarted / StartedNoAdvance / Advancing; 0 no longer blurs three different meanings into one value |
| Topology change | TopologyFingerprint() | uint64_t | Read-only | Topology fingerprint (slave count + a stable hash of each slave's VendorId/ProductId/RevId); TopologyFingerprintKnown() reports whether sampling succeeded |
| TopologyChangeCount() | uint64_t | 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) | |
| LastTopologyChangeUtc() | std::optional<std::chrono::system_clock::time_point> | Read-only | Time of the most recent observed topology change (UTC); nullopt = no change observed yet | |
| Port status | PrimaryPortOk() / SecondaryPortOk() | bool | Read-only | Whether the port is healthy (traffic present and no error within 5 seconds); the secondary port is always false without redundancy |
| PrimaryPortErrors() / SecondaryPortErrors() | uint32_t | Read-only | Port error count over the last 5 seconds | |
| Topology | TopologyDescription() | std::string | Read-only | Topology mode, four values ("line" / "ring" / "ring + branch" / "ring degraded to line"); an unknown raw value shows "unknown (raw value: N)" |
| master.TimingMode() | uint32_t | Read-only | Raw timing mode code; convert it to text with ethercat::protocol_codes::diag_timing_mode() ("hardware timer" / "RT ready" / "degraded" / "RT error"). The text member of the same name inside MasterDiagnosticsInfo is a private implementation and cannot be called | |
| DC synchronization | SyncWindowThreshold() / SyncWindowThreshold(ns) | int | Read/write | Sync window threshold (nanoseconds), read without parameters / written with one; exceeding the threshold raises DCSyncLost. For read/write details see Sync window monitoring |
| Redundancy status | RedundancyActive() | bool | Read-only | Redundancy protection is running (criteria in Redundancy status) |
| RingMode() | darra::RingMode | Read-only | Ring topology redundancy run mode (-1 Unknown / 0 Inactive / 1 Dual / 2 Degraded) | |
| GetBreakPoints(max) | std::vector<BreakPoint> | Read-only | Current fault points (link break + CRC), cleared automatically after recovery | |
| Hard real-time | CycleCount() | uint64_t | Read-only | Accumulated PDO cycle count |
| HardwareSmiCounterAvailable() | bool | Read-only | Whether a hardware SMI counter exists |
PDOFrameLossStats structure
struct PDOFrameLossStats {
uint32_t total_lost; // Accumulated frame loss
uint32_t consecutive_lost; // Current consecutive frame loss
uint32_t max_consecutive_lost; // Highest consecutive frame loss in history
};
Example:
auto& base = master.GetDiagnostics();
MasterDiagnosticsInfo diag(base, master.MasterNumber());
diag.Enabled(true); // Turn on the optional user-tier statistics (the baseline tier is always on, see "diagnostics control")
// Frame count
printf("帧频: %u Hz\n", diag.RTcnt()); // Frame rate: %u Hz
printf("丢包率: %.2f%%\n", diag.PacketLossRate() * 100.0); // Packet loss rate: %.2f%%
printf("错误数: %u\n", diag.ErrorCnt()); // Error count: %u
// Cycle time and jitter
printf("周期时间: %.1f us\n", diag.CycleTimeSpan()); // Cycle time: %.1f us
printf("总线抖动: 平均 %.2f us\n", diag.AvgJitterUs()); // Bus jitter: average %.2f us
printf("邮箱延迟: 平均 %.2f us, 最大 %.2f us\n", // Mailbox latency: average %.2f us, max %.2f us
diag.MailboxLatencyAvgUs(), diag.MailboxLatencyUs());
// PDO frame loss - query by group on the underlying Diagnostics
auto group0Stats = base.GetPDOFrameLossStats(0);
auto group1Stats = base.GetPDOFrameLossStats(1);
printf("组0丢帧: 累计=%u 连续=%u, 组1丢帧: 累计=%u\n", // Group 0 frame loss: total=%u consecutive=%u, group 1 frame loss: total=%u
group0Stats.total_lost, group0Stats.consecutive_lost, group1Stats.total_lost);
if (group0Stats.consecutive_lost > 10)
printf("警告: 组0 PDO 连续丢帧!\n"); // Warning: group 0 PDO consecutive frame loss!
// Slave fault
printf("最差从站: #%d (%.0f%%)\n", diag.WorstSlaveIndex(), diag.WorstLinkQuality()); // -1 = unknown
// NIC link status
printf("主端口: %s\n", diag.PrimaryPortOk() ? "正常" : "异常"); // Primary port: %s (OK / abnormal)
printf("副端口: %s\n", diag.SecondaryPortOk() ? "正常" : "未连接"); // Secondary port: %s (OK / not connected)
// Topology information
printf("拓扑: %s\n", diag.TopologyDescription().c_str()); // Topology: %s
printf("定时: %s\n", // Timing: %s
ethercat::protocol_codes::diag_timing_mode(master.TimingMode()).c_str());
Each slave's ESC port errors are read through the free function slave_stats::read_port_errors(dll, mi, si) in the slave_stats namespace
(the Slave class has no GetDiagnostics() member).
WKC mirror (lost slaves are observable)
The WKC mirror is provided by the darra::ethercat::diag_mirror namespace in the header slave/diag_mirror.hpp (not on the Diagnostics / MasterDiagnosticsInfo classes); these are read-only free functions defined in that header. Together with each slave's dm::slave_wc_contributed(mi, si) they pinpoint which slave actually dropped out.
namespace dm = darra::ethercat::diag_mirror;
| Category | Property | Type | Read/write | Description |
|---|---|---|---|---|
| WKC mirror | dm::wkc_actual_mirror(mi) | uint16_t | Read-only | Measured bus WKC (actual). The measured value is never altered; returns 0 when the runtime is not ready (then the reading is not a bus measurement) |
| dm::wkc_expected_mirror(mi) | uint16_t | Read-only | Expected WKC (expected): the fixed true value determined at configuration time / when entering OP, never lowered | |
| dm::wc_deficit(mi) | uint16_t | Read-only | Deficit = expected − actual. >0 means a mapped slave is not contributing right now (suspected lost slave / Hot-plug); returns to 0 automatically after recovery | |
| dm::mapped_slave_count(mi) | uint16_t | Read-only | Number of mapped slaves that have received the contract and participate in the WKC calculation; 0 = the contract is not ready | |
| dm::wkc_complete(mi) | bool | Read-only | actual == expected and expected > 0; false does not mean a master fault |
The parameter
mi= master index (master.MasterNumber()).
Master-level aggregated measurement entry points (MasterDiagnosticsInfo members):
| Category | Property | Type | Read/write | Description |
|---|---|---|---|---|
| WKC | LiveWkcActual() | uint16_t | Read-only | Live source of the aggregated measured WKC: prefers the merged mirror (redundancy primary + secondary, including the secondary port through the ring), falls back to the primary-port single-port value when the mirror is 0; returns 0 honestly when all of them are 0 and never papers over a lost slave with a cached value. Same definition as GetSnapshot().WkcActual; for single-port values use PrimaryWKC() / SecondaryWKC() |
Criteria (not negotiable):
- expected is a fixed true value and is never lowered dynamically to accommodate a degraded bus; actual honestly reflects who is responding right now and is never altered.
wc_deficit > 0is not a master fault: a mapped slave is not contributing WKC right now (lost slave / recovering from Hot-plug); it returns to 0 automatically once that slave recovers, with no reset call needed.
Example:
#include "slave/diag_mirror.hpp"
namespace dm = darra::ethercat::diag_mirror;
uint16_t mi = master.MasterNumber();
printf("WKC: %u / %u (映射从站 %u 个)\n", // WKC: %u / %u (%u mapped slaves)
dm::wkc_actual_mirror(mi), dm::wkc_expected_mirror(mi), dm::mapped_slave_count(mi));
if (dm::wc_deficit(mi) > 0)
for (int si = 1; si <= master.SlaveCount(); ++si)
if (dm::slave_wc_contributed(mi, si) == dm::WcContribution::NotContributed)
printf("从站 %d 未贡献 WKC\n", si); // Slave %d contributes no WKC
The "unknown" state of the secondary-port WKC
SecondaryWKC() is a measurement of the current cycle: if a fresh value is sampled in this cycle it returns the measured value, and if not it returns WkcUnknown, never a stale full reading. These members all live on the lower-level Diagnostics and are accessed as diag.Base().… (MasterDiagnosticsInfo forwards only PrimaryWKC() / SecondaryWKC() directly):
| Category | Property | Type | Read/write | Description |
|---|---|---|---|---|
| Redundancy WKC | diag.Base().SecondaryWKC() | uint16_t | Read-only | Secondary-port WKC measured in this cycle; returns WkcUnknown when this cycle has no fresh measurement |
| Diagnostics::WkcUnknown | static constexpr uint16_t | Read-only | The "no measurement" sentinel, value 0xFFFF | |
| diag.Base().SecondaryWkcKnown() | bool | Read-only | Whether this cycle has a measurement; false only means SecondaryWKC() == WkcUnknown | |
| diag.Base().SecondaryWkcRt() | uint16_t | Read-only | Real-time filtered value of the secondary port (drops in the same cycle a slave is unplugged or the link breaks); 0 is a valid reading |
On a single-port setup (no secondary leg configured), returning 0 is a valid reading and counts as "known". Deciding "unknown" always requires SecondaryWkcKnown(): neither "is the value 0" nor treating 0xFFFF as a full reading works. Apart from "the runtime is not loaded", 0 is always a real reading; to decide whether the SDK is usable, check darra::ethercat::shell_ready().
Example:
auto& base = master.GetDiagnostics();
if (!base.SecondaryWkcKnown())
printf("副口 WKC: 未知(本拍无实测)\n"); // Secondary port WKC: unknown (no measurement this cycle)
else if (base.SecondaryWKC() == 0)
printf("副口 WKC: 0(单网口 / 副口本拍无贡献)\n"); // Secondary port WKC: 0 (single NIC / secondary port contributed nothing this cycle)
else
printf("副口 WKC: %u,实时值 %u\n", base.SecondaryWKC(), base.SecondaryWkcRt()); // Secondary port WKC: %u, real-time value %u
Real OP verdict
"Reading OP in the AL status word" is not the same as "process data is really being exchanged in this cycle": after a slave drops out the AL status can still report OP, and the UI keeps showing "all in OP" when the merged WKC is down to 6/12. The per-slave real OP verdict is decided by the public entry points from the evidence of the current cycle; a single status bit is not used in its place.
- The verdict holds when the low 4 bits of the AL status = OP (
0x08) and the Error bit (0x10) = 0, and the slave has not been judged lost. - The AL Status Code is not consulted, and the WKC contribution bit is not required: contribution is display evidence only and cannot overturn the verdict.
- No run of consecutive cycles is required: there is no "consecutive clean cycle" threshold;
StableStreakis a display-layer streak count only and takes no part in the verdict.
Master-level real OP is a second threshold: every required slave (not optional and carrying process data) holds per-slave, and the merged measured WKC is not lower than the fixed expectation from configuration time. Per-slave success does not mean the whole machine is in real OP. The application layer does not need to — and should not — write its own "is this real OP" check.
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.
It triggers no recovery, stops no PDO, does not leave OP and does not change the expected value. Evidence that cannot be read is always judged Unknown; a cached or outdated value is never passed off as real OP.
Entry points
All are MasterDiagnosticsInfo members.
| Category | Property | Type | Read/write | Description |
|---|---|---|---|---|
| Diagnostics | RealOpTruth() | MasterRealOpTruth | Read-only | Capture one cycle of real OP truth (equivalent to CaptureRealOpTruth()) |
| CaptureRealOpTruth() | MasterRealOpTruth | Read-only | Capture one cycle of real OP truth (master level + per slave) | |
| EvaluateSlaveRealOp(slaveIndex) | std::optional<SlaveRealOpState> | Read-only | Single-slave verdict; nullopt = cannot be evaluated (illegal index / empty slave), reported honestly as unknown | |
| EvaluateRealOp(evidence, wkcActual, wkcExpected) | MasterRealOpTruth | Read-only | Evaluate from evidence of the same cycle (no re-read when a snapshot exists); evidence is std::vector<SlaveRealOpEvidence> |
Reason enumeration
RealOpReason (values match the other language SDKs)
| Value | Name | Meaning |
|---|---|---|
| 0 | Ok | Real OP: the per-slave verdict holds |
| 1 | AlNotClean | The per-slave verdict does not hold (not in the OP base state / Error bit set / judged lost) |
| 2 | NoContribution | Historical compatibility value; per-slave verdicts no longer produce it |
| 3 | Unstable | Historical compatibility value; per-slave verdicts no longer produce it |
| 4 | WkcDeficit | Master level: every required slave holds, but the merged measured WKC is lower than the fixed expectation |
| 5 | Unknown | Insufficient evidence (lower-level criteria unavailable / no master context / no required slaves) |
Result structures
MasterRealOpTruth (read-only):
| Field | Type | Description |
|---|---|---|
| Sequence | long long | Evaluation sequence number, monotonically increasing per master |
| RealOp | bool | Master-level real OP |
| Reason | RealOpReason | Primary reason the master-level verdict does not hold |
| RequiredCount | int | Number of required slaves |
| RealOpCount | int | Number of required slaves in real OP |
| FailedCount | int | Number of required slaves not in real OP |
| WkcActual | int | Merged measured WKC (as measured) |
| WkcExpected | int | Fixed expected WKC from configuration time (never lowered) |
| WkcDeficit | int | Deficit = expected − actual (≤0 means no deficit) |
| Slaves | std::vector<SlaveRealOpState> | Per-slave results |
| DetailText | std::string | Human-readable detail (master conclusion + list of slaves that did not pass + WKC comparison) |
SlaveRealOpState (read-only):
| Field | Type | Description |
|---|---|---|
| SlaveIndex | int | Slave index (1-based) |
| Required | bool | Whether it takes part in the master-level verdict (not optional and has PDO) |
| AlCleanOp | bool | This slave's "clean OP" verdict (a compatibility field from the same source as RealOp) |
| Contributed | bool | This cycle has a WKC contribution — display evidence only, not part of the verdict |
| StableStreak | int | Display-layer streak count, not part of the verdict |
| RealOp | bool | This slave is in real OP |
| Reason | RealOpReason | Reason it does not hold (Ok when it is in real OP) |
| Detail | std::string | Human-readable reason detail (not part of the verdict) |
Example:
MasterDiagnosticsInfo diag(master.GetDiagnostics(), master.MasterNumber());
MasterRealOpTruth truth = diag.RealOpTruth();
if (truth.RealOp) {
printf("真 OP: 必需站 %d/%d, WKC %d/%d\n", // Real OP: required slaves %d/%d, WKC %d/%d
truth.RealOpCount, truth.RequiredCount, truth.WkcActual, truth.WkcExpected);
} else {
printf("非真 OP [%d] %s\n", static_cast<int>(truth.Reason), truth.DetailText.c_str()); // Not real OP [%d] %s
for (const auto& s : truth.Slaves)
if (s.Required && !s.RealOp)
printf(" 从站 %d: reason=%d — %s\n", // Slave %d: reason=%d — %s
s.SlaveIndex, static_cast<int>(s.Reason), s.Detail.c_str());
}
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 accounting
namespace dm = darra::ethercat::diag_mirror;
uint32_t dm::GetHotSwapRescanCount(uint16_t mi);
int dm::GetHotSwapRescanLastResult(uint16_t mi);
int64_t dm::GetHotSwapRescanLastTimeMs(uint16_t mi);
The three entry points read the kernel accounting (zero frames): completed rounds / last result code / last completion time. There is no manual rebuild function 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:
#include "slave/diag_mirror.hpp"
namespace dm = darra::ethercat::diag_mirror;
uint32_t rounds = dm::GetHotSwapRescanCount(master.MasterNumber());
int last = dm::GetHotSwapRescanLastResult(master.MasterNumber());
int64_t when = dm::GetHotSwapRescanLastTimeMs(master.MasterNumber());
printf("自动重建 %u 轮,上次结果 %d,时刻 %lld\n", // Automatic rebuild %u rounds, last result %d, at %lld
rounds, last, (long long)when);
P1 foldback topology
Read-only queries of the P1 foldback topology calibration results and slave reachability. In the table below, p1 is a MasterDiagnosticsInfo instance.
| Member | Returns | Description |
|---|---|---|
| p1.TopoP1Mode() | int | Foldback mode: 0=NONE (no foldback needed or not calibrated in this run), 1=SINGLE_NIC (single NIC, no foldback window), 2=DUAL_RING_BRANCH (dual NIC ring + branch, foldback required); -1=invalid master index |
| p1.TopoP1Measured() | int | Whether the on-site topology measurement completed in this run: 1=measured; 0=not measured; -1=invalid master index |
| p1.TopoP1FullWkc() | int | Full working counter measured at that foldback position; -1=unavailable |
| p1.TopoMeasuredRingCount() | int | Measured number of slaves on the ring; -1=unavailable |
| master.GetSlave(1).P1FoldbackOnly() | int | Slave-level foldback reachability: 1=this slave is reachable only through the foldback window, and while it is set any positional addressing of that slave must open the foldback window first. 0=not a branch slave / property not calibrated; -1=invalid master index or slave index |
Ring-side boundary of the foldback window (supplementary member, also read-only):
| Category | Property | Type | Read/write | Description |
|---|---|---|---|---|
| Topology | p1.TopoP1RingEndAdp() | int | Read-only | Adapter number at the ring end (= 1 − K), that is, the ring-side boundary of the foldback window; -1 = unavailable (not calibrated / not a dual NIC ring + branch / invalid master index). 0 is a valid adapter number and does not mean failure |
Use TopoP1RingEndAdp() together with TopoMeasuredRingCount(): slaves whose index is greater than the number of slaves on the ring belong to the branch, and the branch count = TopoP1FullWkc() − TopoMeasuredRingCount().
All members are read-only queries and change no state. -1 only means unavailable / not calibrated / illegal parameter (master index or slave index out of range, master already released) and is treated as "not readable". 0 is a real value, not a failure: TopoP1Mode() returning 0 means NONE, TopoP1Measured() returning 0 means not measured in this run, and TopoMeasuredRingCount() returning 0 means 0 were measured; do not treat 0 as an error.
Example:
auto& base = master.GetDiagnostics();
MasterDiagnosticsInfo p1(base, master.MasterNumber());
// Foldback mode: 0=NONE, 1=SINGLE_NIC, 2=DUAL_RING_BRANCH; -1=invalid master index
int mode = p1.TopoP1Mode();
if (mode < 0) {
printf("P1 折返拓扑不可用 (主站索引非法)\n"); // P1 loopback topology unavailable (invalid master index)
} else {
printf("P1 模式: %d\n", mode); // P1 mode: %d
printf("已实测: %d\n", p1.TopoP1Measured()); // 1=measured this round, 0=not measured, -1=invalid index
}
// Foldback calibration result: every item returns -1 when uncalibrated / not a dual-NIC ring+branch / the index is invalid
int fullWkc = p1.TopoP1FullWkc();
int ringCount = p1.TopoMeasuredRingCount();
if (fullWkc < 0 || ringCount < 0) {
printf("折返标定结果不可用 (-1)\n"); // Loopback calibration result unavailable (-1)
} else {
printf("满 WKC=%d, 环上 %d 站\n", fullWkc, ringCount); // Full WKC=%d, %d slaves on the ring
}
// Slave level: 1=reachable only through the foldback window, 0=not a branch station / not calibrated, -1=invalid master index or station number
for (int si = 1; si <= master.SlaveCount(); ++si) {
int foldbackOnly = master.GetSlave(si).P1FoldbackOnly();
if (foldbackOnly < 0) continue; // -1 is treated as "could not be read", not as "not a branch station"
if (foldbackOnly == 1)
printf("从站 %d 只能经折返窗口可达,寻址前需先打开折返窗口\n", si); // Slave %d is reachable only through the loopback window; open the loopback window before addressing
}
Physical link tri-state
The master method returns a bitmap and the diagnostics object returns a per-port tri-state. Both exist; do not substitute one for the other.
| Category | Property | Type | Read/write | Description |
|---|---|---|---|---|
| Network and link | EtherCATMaster::GetPhyLinkState() | uint32_t | Read-only | Bitmap: bit0 = primary port up, bit1 = secondary port up; 0xFFFF = not observable (the real-time process image is unavailable / the master is not built) |
| Network and link | MasterDiagnosticsInfo::PrimaryPhyLinkState() | PhyLinkState | Read-only | Primary-port physical link tri-state |
| MasterDiagnosticsInfo::SecondaryPhyLinkState() | PhyLinkState | Read-only | Secondary-port physical link tri-state | |
| MasterDiagnosticsInfo::SecondaryFrameLinkState() | PhyLinkState | Read-only | Secondary-port frame-level link: whether frames really come back through the redundancy ring; when the peer does not forward, the link is physically up but down at frame level | |
| MasterDiagnosticsInfo::PrimaryPhyLinkUp() / SecondaryPhyLinkUp() | bool | Read-only | Boolean projections: true only when the state equals Up; to tell "down / unknown" apart use the tri-state methods above |
Related structure:
enum class PhyLinkState : int {
Up = 1, // Connected
Down = 0, // Disconnect
Unknown = -1 // Not observable (the driver is not installed / the real-time process image is not ready / the master is not built)
};
PhyLinkState::Unknown (-1) means not observable: it is neither Down nor Up. To decide "it really is disconnected" you must compare explicitly against PhyLinkState::Down; do not use a truthiness test — both Unknown and Up are true, which would read "unknown" as "connected".
DC synchronization
Automatic monitoring (ETG.1500 5.13.3): the time deviation of every slave is checked once per second. When it exceeds the SyncWindowThreshold() threshold the DCSyncLost event is raised; for reading and writing the threshold see Sync window monitoring.
For an individual slave's synchronization state use the Slave member methods slave.IsInSync() / slave.SyncTimeDifference() /
slave.GetSyncWindowStatus() (the Slave class has no GetDiagnostics() member).
DC diagnostics 2-second snapshot
DcDiagnostics() takes every DC conclusion in one call (per slave + master level); within the same 2-second window every consumer shares the same data, so a UI cannot end up with split definitions by reading each column on its own. Everything read comes from local caches; no bus frame is sent.
There is no background sampling on the C++ side: DcDiagnostics() only re-samples once at least 2 seconds have passed since the last assembly. The sample density of history-type fields (σ / convergence time and so on) depends on the caller's polling rate — when you need a steady 2-second cadence, read this method about every 200 ms.
DcDiagnostics() returns a copy. The pointer returned by Find(...) points inside that copy and must not be kept beyond the expression (the value returned by info.DcDiagnostics().Find(1) becomes invalid once the full expression ends); when you need to keep it, copy a DcSlaveSnapshot. FindDcSample() returns a std::optional<DcSlaveSnapshot> value copy, which is safe to store.
| Category | Property | Type | Read/write | Description |
|---|---|---|---|---|
| DC diagnostics | DcDiagnostics() | DcDiagnosticsSnapshot | Read-only | Snapshot object. When the master is not built / the read fails it returns the empty-snapshot representation (everything Unknown / nullopt, AnyReadFailure = true) instead of fabricated healthy values |
| CapturedAtUtc | std::chrono::system_clock::time_point | Read-only | Time this snapshot was assembled (UTC) | |
| HasDc | bool | Read-only | Whether the network contains slaves with DC capability (capability-bit definition) | |
| AllInSync | std::optional<bool> | Read-only | Whether every SYNC0 participant is inside the window; nullopt when there is no confirmed participant (not true); false when a participant exists but was not sampled / cannot be read / any slave's arming conclusion is unknown | |
| MaxDriftNs | std::optional<int> | Read-only | Largest absolute synchronization difference among the usable windows (ns); nullopt when no window is usable (not 0) | |
| SyncWindowThresholdNs | std::optional<int> | Read-only | Sync window threshold (ns); nullopt = cannot be read | |
| ReferenceClock | DcReferenceClockInfo | Read-only | Reference clock facts (slave index / tier / reason); an explicit None() instance when there is no DC slave | |
| ArmedSlaveCount / ActiveSlaveCount | int | Read-only | Number of SYNC0-armed slaves / number of DC-active slaves; 0 is a valid count | |
| ArmedUnknownCount | int | Read-only | Number of slaves whose arming conclusion is unknown (the lower layer cannot decide); 0 is a valid count | |
| ArmedSyncParticipantCount | int | Read-only | Number of SYNC0 synchronization participants (armed and not the reference clock, excluding unarmed / non-DC slaves); 0 = no slave about which synchronization can be discussed | |
| ApplicableWindowCount | int | Read-only | Number of slaves with a usable measured window; 0 means MaxDriftNs is nullopt | |
| ActiveWithoutProcessDataCount | int | Read-only | Number of slaves that are DC-active but have no process data bytes; 0 is a valid count | |
| ExpectedWkc | uint16_t | Read-only | Expected WKC (fixed value from configuration time) | |
| PropagationDelayResolvedAtUtc | std::optional<std::chrono::system_clock::time_point> | Read-only | Time of the most recent propagation-delay resolution the SDK triggered successfully (UTC); nullopt = not observed in this process. Not the same as the physical measurement time | |
| PropagationDelayResolveCount | int | Read-only | Number of successes under the same accounting definition; 0 = not observed | |
| Slaves | std::vector<DcSlaveSnapshot> | Read-only | Per-slave DC snapshots (ascending by slave index, no placeholder rows) | |
| Find(index) | const DcSlaveSnapshot* | Read-only | Single-slave snapshot by slave index; returns nullptr when out of range / not sampled. The pointer belongs to the snapshot copy and must not be kept beyond the expression | |
| AnyReadFailure | bool | Read-only | At least one slave / the reference clock failed to read in this cycle (failed items are filled as Unknown / nullopt) |
Master-level direct entry points (the same 2-second snapshot):
| Category | Property | Type | Read/write | Description |
|---|---|---|---|---|
| DC diagnostics | DcArmedSlaveCount() | int | Read-only | Same as the snapshot's ArmedSlaveCount |
| DcActiveSlaveCount() | int | Read-only | Same as the snapshot's ActiveSlaveCount | |
| DcReferenceClock() | DcReferenceClockInfo | Read-only | Reference clock facts (slave index + tier projection) | |
| FindDcSample(slaveIndex) | std::optional<DcSlaveSnapshot> | Read-only | Single-slave snapshot from the most recent completed sampling, without triggering sampling; returns nullopt when not sampled | |
| DcConvergenceMs(slaveIndex) | std::optional<int> | Read-only | Convergence time (ms); nullopt when no complete transition has been observed | |
| DcJitter(slaveIndex) | std::optional<DcJitterStats> | Read-only | Steady-state quality; nullopt when there are fewer than 2 samples |
The fields inside the per-slave snapshot DcSlaveSnapshot (capability tier / 0x0980 / SYNC0 / SYNC1 / propagation delay / arming / sync window / jitter / convergence) come from the same source and use the same definitions as Slave DC diagnostics, and additionally carry ShiftNs (phase offset), OutputBytes / InputBytes, IsDcActive, IsReferenceClock and ConvergenceMeasuredAtUtc.
Example:
MasterDiagnosticsInfo diag(master.GetDiagnostics(), master.MasterNumber());
// Polled by the caller roughly every 200 ms; the snapshot advances internally on a 2 s TTL
DcDiagnosticsSnapshot dc = diag.DcDiagnostics();
if (!dc.AllInSync.has_value()) {
// No confirmed participants: unknown, not "all in sync"
} else if (!*dc.AllInSync) {
printf("有参与者未在窗, 站数=%d\n", dc.ArmedSyncParticipantCount); // Some participants are not in the window, slave count=%d
}
if (dc.MaxDriftNs) {
printf("最大同步差 %d ns (实测窗口 %d 个)\n", // Max sync difference %d ns (%d measured windows)
*dc.MaxDriftNs, dc.ApplicableWindowCount);
}
if (const DcSlaveSnapshot* s1 = dc.Find(1)) {
// Use it immediately; do not keep s1 beyond dc
printf("站 1 武装=%d, DC-active=%d\n", (int)s1->Sync0Armed.value_or(false), // Slave 1 armed=%d, DC-active=%d
(int)s1->IsDcActive);
}
Redundancy status
RingMode() reports the run state of ring-topology redundancy: -1 Unknown (cannot be read / out-of-domain value), 0 Inactive (redundancy not initialized), 1 Dual (bidirectional redundancy healthy), 2 Degraded (the secondary link is unavailable and only the primary link is working).
Text projection of the same mode:
| Category | Property | Type | Read/write | Description |
|---|---|---|---|---|
| Redundancy status | RingModeStr() | std::string | Read-only | Redundancy mode text: "inactive" / "bidirectional redundancy" / "degraded"; an unknown raw value returns "unknown (raw value: N)" instead of guessing. For numeric decisions still use RingMode() |
RedundancyActive() means "redundancy protection is running", not "both ports carry frames"RedundancyActive() = RingMode() >= 1 and both the primary and the secondary port carry frame traffic within this window. In a chain (end foldback) topology the primary port transmits and the secondary port receives, so both ports carry frames, but physically there is no second independent path — this method returns false, consistent with RingMode() == Inactive. To ask "do both ports carry frames" read PrimaryPortOk() / SecondaryPortOk(); do not infer it from this method. slave.RedundancyActivated() is the same master-level criterion (RingMode >= 1), not an independent per-slave conclusion.
GetBreakPoints() returns the current fault points and detects two kinds of physical fault:
| Type | type value | Detection | Typical scenario |
|---|---|---|---|
| Link break | 0 | Physical link loss on a DL Status port | Cable unplugged, cable cut |
| CRC fault | 1 | Sustained growth of port-level RxError + InvalidFrame | Poor contact, aged cable, oxidized connector |
An empty list from GetBreakPoints() must be read together with LastBreakPointsQueryOk(): true = the query succeeded and there really is no break point; false = not ready / rejected by the lower layer, nothing was queried. The free function of the redundancy module, master_redundancy::GetBreakPoints(master, max, &queryOk), has the same semantics: queryOk = true means the query succeeded, false means not ready / illegal parameter / rejected by the lower layer.
Locating the faulty cable segment: facing ports on adjacent slaves (for example P1 on slave N and P0 on slave N+1) reporting a fault at the same time = the cable between them is the problem; a fault on one side only = the connector on that port is the problem.
BreakPoint structure
enum class FaultType : uint8_t {
LinkDown = 0, // Broken link
CrcFault = 1, // CRC failure (degraded cable/connector)
Unknown = 255 // Unknown fault
};
struct Diagnostics::BreakPoint {
uint16_t slave; // Faulted slave index (1-based)
uint8_t port; // Faulted port number (0-3, corresponding to P0-P3)
FaultType fault_type; // Fault type enum
bool is_link_down() const; // Whether it is a broken-link fault
bool is_crc_fault() const; // Whether it is a CRC fault
};
Example:
if (diag.RingMode() == darra::RingMode::Degraded)
printf("警告: 副链路不可用,仅主链工作\n"); // Warning: the secondary link is unavailable, only the primary link is working
auto bps = base.GetBreakPoints();
if (bps.empty() && !base.LastBreakPointsQueryOk())
printf("故障点没查到(未就绪)——不是「无故障」\n"); // The fault point was not found (not ready) — this is not "no fault"
for (auto& bp : bps)
printf("故障: 从站 %d P%d %s\n", bp.slave, bp.port, // Fault: slave %d P%d %s
bp.is_crc_fault() ? "CRC 劣化,查线缆/连接器" : "断线,查线缆"); // CRC degradation, check the cable/connector / cable break, check the cable
Diagnostics snapshot
UpdateSnapshot()
void UpdateSnapshot();
Refresh the diagnostics snapshot (a forward of the same-named entry point on the lower-level Diagnostics). Cyclic statistics such as frame rate / cycle time / jitter are settled as a snapshot; call it when subsequent readings must immediately reflect the latest settlement.
Parameters:
- None
Return value:
- None (void)
It only refreshes the snapshot and resets no counter; for resetting see Diagnostics control.
GetSnapshot()
DiagnosticsSnapshot GetSnapshot() const;
Get a consistent snapshot of all common diagnostic values in one call, avoiding cross-field inconsistency and the overhead of many separate property reads.
Parameters:
- None
Return value:
MasterDiagnosticsInfo::DiagnosticsSnapshot— a consistent snapshot copy:
struct MasterDiagnosticsInfo::DiagnosticsSnapshot {
int Frequency; // Frames per second (Hz)
uint32_t ErrorCount; // Errors per second
float PacketLossRate; // Packet loss rate (0.0-1.0) = combined bus WKC deficit / expected WKC (instantaneous)
float LateFrameRate; // Too-slow frame rate (0.0-1.0) - a frame that has left the 8-frame window and still has not arrived is not counted as lost
double AvgJitterUs; // Average bus jitter (microseconds)
double MailboxLatencyUs; // Maximum mailbox transaction round trip (microseconds)
double MailboxLatencyAvgUs;// Average mailbox transaction round trip (microseconds)
double CycleTimeUs; // Actual cycle time (microseconds)
uint16_t WkcActual; // Combined measured WKC (primary+secondary, including the secondary port traversing the ring), directly comparable with WkcExpected
uint16_t WkcExpected; // Expected WKC fixed at configuration time (never lowered)
uint32_t BusCycleHz; // Bus rate (Hz)
double BusMaxJitterUs; // Maximum bus jitter (microseconds)
double BusAvgJitterUs; // Average bus jitter (microseconds)
double BusRoundtripUs; // Bus round trip latency (microseconds)
double BusLoadPercent; // Communication load (%) - round trip / cycle x 100
uint32_t SmiCount; // SMI count
double SmiPeakUs; // SMI peak jitter (microseconds)
bool PrimaryPortOk; // Primary port normal
bool SecondaryPortOk; // Secondary port normal
bool RedundancyActive; // Redundancy protection is running (RingMode >= 1 and both ports have frame traffic)
};
The live source of the WkcExpected field is the master-level GetExpectedWKC (the C++ entry point is ExpectedWKC()): the fixed true value from configuration time, never lowered, not a separately stored stale mirror copy; WkcActual takes the aggregated measured value from LiveWkcActual(). Both use the same definition and can be subtracted directly to get the deficit. The snapshot structure itself defines no separate GetExpectedWKC method.
Example:
auto snap = diag.GetSnapshot();
printf("频率 %d Hz, 丢包 %.2f%%, WKC %u/%u\n", // Frequency %d Hz, packet loss %.2f%%, WKC %u/%u
snap.Frequency, snap.PacketLossRate * 100.0, snap.WkcActual, snap.WkcExpected);
printf("总线抖动: 平均 %.2f us, 邮箱延迟: 平均/最大 %.2f/%.2f us\n", // Bus jitter: average %.2f us, mailbox latency: average/max %.2f/%.2f us
snap.AvgJitterUs, snap.MailboxLatencyAvgUs, snap.MailboxLatencyUs);
When several diagnostic metrics must be read at the same time (a UI panel refresh, for example), GetSnapshot() is more efficient than reading the properties one by one and gives consistent data.
Recovery ladder observation
Read-only observation surface of the recovery ladder: the current level / step of a single slave, the failure reason and measured ALSC, slave-level backoff, the master-level rebuild / handoff / suppressed-trigger counters, and an event ring that can be read incrementally. All of it is snapshot reading: it triggers no recovery action and blocks no write.
| Category | Property | Type | Read/write | Description |
|---|---|---|---|---|
| Recovery ladder | SlaveRecoveryLadder(slaveIndex) | std::optional<dx_ladder_status_t> | Read-only | Single-slave ladder state snapshot; nullopt = a true value cannot be given (runtime not ready / slave out of range / nothing written for this slave yet), which is not the same as Idle / normal |
| MasterRecoveryLadder() | std::optional<dx_master_ladder_t> | Read-only | Master-level ladder observation (rebuild / handoff / backoff / suppressed-trigger counters); nullopt semantics as above | |
| RecoveryLadderSeq() | uint64_t | Read-only | Master-level freshness token = the sum of the transition counts of all slaves; 0 = unavailable or no transition yet. A token that stops increasing means the record is not advancing | |
| RecoveryEvents(sinceSeq, maxEvents) | std::vector<dx_recovery_event_t> | Read-only | Copies at most maxEvents events starting at sinceSeq (default 64, single-call limit 256); empty = no new events, nothing is invented. seq is monotonic and can serve as an incremental cursor |
Related structures:
struct dx_ladder_status_t {
uint8_t level; // Current level
uint8_t step; // Current step
uint8_t last_step; // Previous step (so transitions are traceable)
uint8_t fail_reason; // Reason the previous step failed (0 = none)
uint16_t fail_alsc; // The ALSC measured on failure (0 = not read)
uint16_t retry_count; // Consecutive failures / attempt count for this episode
uint32_t backoff_remain_ms; // Station-level backoff remaining (0 = ready to move)
uint32_t step_elapsed_ms; // Time elapsed in the current step
uint32_t skip_frames; // Class A skipped recovery frame count
uint64_t seq; // State transition counter (snapshot freshness token)
uint8_t flags; // bit0=paused_a bit1=needs_reconfig bit2=ladder_exhausted bit3=epilogue
uint8_t last_result_ok; // Previous step result: 1=succeeded 0=failed 2=not executed (suppressed)
uint8_t reserved[2]; // reserved[0]=classify, reserved[1] reserved
};
struct dx_master_ladder_t {
uint8_t rebuild_req_pending; // Rebuild request pending
uint8_t rebuild_active; // Rebuild in progress
uint8_t rebuild_fail; // Rebuild failed
uint8_t alarm_only; // Alarm-only mode
uint8_t handoff_busy; // Handover in progress
uint8_t a_suppressed; // Class A suppression in progress
uint8_t bad_persistent; // Sustained anomaly
uint8_t ladder_exhausted; // The ladder is exhausted
uint32_t backoff_remain_ms; // Master-level backoff remaining
uint32_t trigger_blocked_total; // Suppressed trigger count (a suppressed trigger must be visible)
uint32_t bad_since_ms; // Start time of the sustained anomaly
uint32_t rebuild_total; // Accumulated rebuild count
uint64_t seq; // Master-level freshness token
};
struct dx_recovery_event_t {
uint32_t seq; // Event sequence number (monotonic, incremental cursor)
uint16_t slave; // Slave index (0 = master-level event)
uint8_t kind; // Event kind
uint8_t from_level; // Transition source level
uint8_t to_level; // Transition target level
uint8_t from_step; // Transition source step
uint8_t to_step; // Transition target step
uint8_t reason; // Reason
uint8_t ok; // 1=success 0=failure 2=not executed
uint16_t alsc; // Measured ALSC
uint32_t tick_ms; // Event time (milliseconds)
};
A nullopt from SlaveRecoveryLadder() / MasterRecoveryLadder() means a true value cannot be given (no instance / parameter out of range / nothing written yet / runtime not ready); it must not be taken as "Idle / normal / not recovering". To decide "there really is no recovery action in progress" you have to read an actual state value first.
Example:
MasterDiagnosticsInfo diag(master.GetDiagnostics(), master.MasterNumber());
if (auto ladder = diag.SlaveRecoveryLadder(1)) {
printf("站 1: 级=%u 步=%u 退避剩余=%u ms\n", // Slave 1: level=%u step=%u backoff remaining=%u ms
(unsigned)ladder->level, (unsigned)ladder->step, ladder->backoff_remain_ms);
} else {
printf("站 1 阶梯状态未知(不是 Idle)\n"); // Slave 1 ladder state unknown (not Idle)
}
if (auto m = diag.MasterRecoveryLadder())
printf("重建 %u 次,触发被压制 %u 次\n", m->rebuild_total, m->trigger_blocked_total); // %u rebuilds, %u triggers suppressed
uint32_t since = 0; // Event cursor: starts at the earliest entry
for (const auto& ev : diag.RecoveryEvents(since, 64)) {
printf("seq=%u 站=%u kind=%u %u->%u\n",
ev.seq, (unsigned)ev.slave, (unsigned)ev.kind,
(unsigned)ev.from_level, (unsigned)ev.to_level);
since = ev.seq; // Next read starts from here
}
Diagnostics control
Enabled() / Enabled(val) pass straight through to the lower-level switch: it controls only the user-tier optional statistics (turning it off really does turn them off), while the baseline tier (WKC / cycle / lost-slave accounting) is always on and unaffected by that switch. So after turning Enabled off the WKC and packet-loss criteria are still valid, while statistics that depend on the user tier may stop updating; do not treat it as a master switch.
Enabled() / Enabled(val)
bool Enabled() const;
void Enabled(bool enable);
Diagnostic data collection switch (read without a parameter / write with one).
Parameters:
enable(bool) — true turns on the user-tier optional statistics; false turns them off (the baseline tier is unaffected)
Return value:
- The no-argument version returns bool — whether the user-tier optional statistics are currently enabled
Reset()
void Reset();
Reset the base statistics, the PDO frame loss statistics (groups 0-7) and the WKC classification counters (Zero / Low / High) in one call.
Parameters:
- None
Return value:
- None (void)
DC sync window statistics are reset with SlaveDC::ResetAllSyncWindowStats(dll, mi) and a single slave's port error counters with ResetSlavePortErrorCounters(si); neither is covered by Reset().
ResetWkcClassification()
void ResetWkcClassification();
Clears only the WKC classification counters (Zero / Low / High) and leaves the base statistics and the PDO frame loss statistics untouched; equivalent to the WKC part of Reset().
Parameters:
- None
Return value:
- None (void)
The classification counters only grow if UpdateWkcClassification(wkc, expected_wkc) is called every cycle; when expected_wkc is 0 the call is skipped and produces no count.
Hard real-time
Honest RT counters on MasterDiagnosticsInfo; reading them adds no bus traffic.
| Category | Property | Type | Read/write | Description |
|---|---|---|---|---|
| Hard real-time | SmiCount() / SmiPeakUs() | uint32_t / double | Read-only | SMI count / peak jitter; SMI jitter is direct evidence of BIOS interference |
| SmiMsrAvailable() | uint32_t | Read-only | Raw availability value of the SMI MSR hardware counter: 0 = unavailable, a value other than 0 = available; HardwareSmiCounterAvailable() is its Boolean projection | |
| RtPreemptCount() / RtPreemptPeakNs() | uint64_t / uint32_t | Read-only | Number of times the RT thread was preempted / the peak; a value other than 0 means the real-time thread was interrupted | |
| BigGapUnknownCount() | uint64_t | Read-only | Count of large gaps of unknown cause | |
| JitterHistogramBins() | std::vector<uint32_t> | Read-only | 7-bucket jitter histogram (below 1 µs / 1-2 / 2-5 / 5-10 / 10-50 / 50-100 / above 100 µs) |
Jitter and wake-path counters
Wake-up quality and branch path of the real-time transmit thread. All read-only, and reading them does not load the bus; when an integer entry point is unavailable it returns 0, a floating-point entry point returns 0.0, and a CPU core number returns -1 — these are "cannot read" defaults, not a measured 0.
| Category | Property | Type | Read/write | Description |
|---|---|---|---|---|
| Jitter instrument | JitterInstrumentVersion() | uint32_t | Read-only | Jitter instrument version; 0 = instrument unavailable / runtime not ready |
| JitterTotalSamples() | uint64_t | Read-only | Total number of jitter samples | |
| JitterMinNs() | uint32_t | Read-only | Minimum jitter (nanoseconds) | |
| JitterLastWakeDeltaNs() | int | Read-only | Most recent wake-up deviation (nanoseconds, signed); the sign says whether the wake-up was early or late relative to the target wake time | |
| Path branches | PathCountFast() | uint32_t | Read-only | Cumulative count of the real-time fast path branch |
| PathCountMed() | uint32_t | Read-only | Cumulative count of the real-time medium path branch | |
| PathCountSlow() | uint32_t | Read-only | Cumulative count of the real-time slow path branch | |
| Wake-up | KtimerWakeNormalCount() | uint32_t | Read-only | Cumulative normal wake-ups of the real-time timer |
| KtimerWakeOverrunCount() | uint32_t | Read-only | Cumulative overrun wake-ups of the real-time timer | |
| Cycle jitter | DispatchCycleMaxJitterUs() | double | Read-only | Maximum cycle jitter of the dispatch phase (microseconds); returns 0.0 when the entry point is unavailable |
| DrainCycleMaxJitterUs() | double | Read-only | Maximum cycle jitter of the drain phase (microseconds); returns 0.0 when the entry point is unavailable |
The three path-branch counters are cumulative; to read a trend take differences over a time window instead of using the absolute value to judge "the slow branch is happening more often".
CycleCount()
uint64_t CycleCount() const;
Accumulated PDO cycle count.
Parameters:
- None
Return value:
- (uint64_t) Accumulated PDO cycle count; returns 0 when the entry point is unavailable
Example:
printf("周期计数: %llu\n", // Cycle count: %llu
static_cast<unsigned long long>(diag.CycleCount()));
HardwareSmiCounterAvailable()
bool HardwareSmiCounterAvailable() const;
Whether a hardware SMI counter exists.
Parameters:
- None
Return value:
- (bool) true = a hardware SMI counter exists
Example:
if (diag.HardwareSmiCounterAvailable())
printf("SMI 硬件计数器可用\n"); // SMI hardware counter available
Transmit and receive path counters
These members report frame counts on the primary / secondary port transmit and receive paths, receive-drop / transmit-fallback counters and thread binding information. All are read-only and take local counters. The named members that carry an id are fixed projections of WdkDiagCounter(counterId) with identical definitions; frame counts and late drops go through separate frame-level / window counters.
| Category | Property | Type | Read/write | Description |
|---|---|---|---|---|
| Diagnostic counters | WdkDiagCounter(counterId) | uint32_t | Read-only | Read a raw diagnostic counter by numeric id (zero-frame read); returns 0 when the entry point is unavailable. Only the ids listed in the table below are promised; other ids belong to the internal diagnostics surface and their value definitions are not promised |
| Frame counts | WdkPrimaryFrameTx() / WdkPrimaryFrameRx() | uint32_t | Read-only | Cumulative frames transmitted / received on the primary port |
| WdkSecondaryFrameTx() / WdkSecondaryFrameRx() | uint32_t | Read-only | Cumulative frames transmitted / received on the secondary port | |
| Late drops | WdkPdoIdxDropCount() | uint32_t | Read-only | Cumulative late-frame drops: the frame arrived but its index was already outside the 8-frame window. Not counted as packet loss |
| WKC | WdkWkcMismatchCount() | uint32_t | Read-only | Cumulative number of WKC mismatches (id 1) |
| Receive ring | WdkPrimaryRingFullDrop() / WdkSecondaryRingFullDrop() | uint32_t | Read-only | Drops caused by a full receive ring on the primary / secondary port (id 2 / 3) |
| Transmit early return | WdkPrimaryTxBailBusy() / WdkSecondaryTxBailBusy() | uint32_t | Read-only | Primary / secondary port transmit early return: resource busy (id 7 / 13) |
| WdkPrimaryTxBailPreallocMiss() / WdkSecondaryTxBailPreallocMiss() | uint32_t | Read-only | Primary / secondary port transmit early return: preallocation miss (id 8 / 14) | |
| Transmit fallback | WdkPrimaryTxFallbackSent() / WdkSecondaryTxFallbackSent() | uint32_t | Read-only | Number of times the primary / secondary port switched to the fallback transmit path (id 9 / 15) |
| Receive calls | WdkPrimaryNdisCall() / WdkSecondaryNdisCall() | uint32_t | Read-only | Number of NIC receive calls on the primary / secondary port (id 20 / 22) |
| WdkPrimaryEcatMatch() / WdkSecondaryEcatMatch() | uint32_t | Read-only | Number of frames recognized as EtherCAT frames on the primary / secondary port (id 21 / 23) | |
| Scheduling | WdkPollCallbackTxTicks() | uint32_t | Read-only | Number of entries into the cyclic transmit callback (id 16) |
| WdkPollCallbackRxTicks() | uint32_t | Read-only | Number of wake-ups in which the receive-drain wait was satisfied by the deadline timer (id 17) | |
| Thread binding | WdkRtCpuCore() | int | Read-only | CPU core the real-time thread is currently bound to; -1 = not set / not readable |
| WdkRxCpuCore() | int | Read-only | CPU core the receive-drain thread is currently bound to; -1 = not enabled / not readable |
- A named diagnostic counter (id projection) returning 0: the count really is 0, or the entry point is unavailable; only when the frame-level totals are a value other than 0 or WdkRtCpuCore() is not -1 is the path really running.
- A frame-level total (WdkPrimaryFrameTx and so on) returning 0: the port has no real-time transmit/receive path enabled or the counter cannot be read, not "0 frames measured".
- WdkPdoIdxDropCount() being 0: not enabled, or no drops; it is not part of packet loss itself — packet loss and lost-slave criteria still go through PacketLossRate and the WKC mirror.
Example:
// Primary port frame-level send/receive and PDO window drops (0 = that port's real-time path is not enabled, not a measured 0 frames)
printf("主口 TX=%u RX=%u, PDO 窗口丢弃=%u\n", // Primary port TX=%u RX=%u, PDO window drops=%u
diag.WdkPrimaryFrameTx(), diag.WdkPrimaryFrameRx(), diag.WdkPdoIdxDropCount());
AL error classification
Classifies the AL Status Code to help judge the nature of an error and the handling strategy quickly.
High-frequency codes and actions:
| Code | Meaning | Action |
|---|---|---|
| 0x0011 | Requested state transition is illegal | Switch in ETG state machine order (Init → PreOp → SafeOp → OP) |
| 0x0015 / 0x0016 | Bootstrap / PreOp mailbox configuration is illegal | Check the mailbox / SM configuration |
| 0x001D | Invalid output configuration | Check the SM configuration and length of the output process data (a mapping mismatch is 0x0025) |
| 0x001E | Invalid input configuration | Check the SM configuration and length of the input process data (a mapping mismatch is 0x0024) |
| 0x002D | Sync not received (ETG.1000.6 literal name "No sync error" does not mean error-free) | SAFEOP waits for the first Sync0/Sync1 and times out, so the slave refuses OP; check whether DC/SYNC0 is enabled, 0x1C32:01 SyncType and SystemTimeOffset |
| 0x0032 | PLL error | Check the DC reference clock and the synchronization configuration |
| 0x0034 | DC synchronization timeout | Check the DC configuration and the SYNC0 cycle |
| 0x0050 | EEPROM cannot be accessed | Slave hardware / EEPROM connection |
| 0x0051 | EEPROM error | Slave hardware / EEPROM recovery |
Error classification follows the lower-level implementation; the table lists only the frequent entries — for the complete meanings use the SDK's AL status table (status_codes.c), with the original definitions in ETG.1000 / ETG.1020 or the slave manual.
ALErrorClassifier::Classify()
static ALErrorCategory ALErrorClassifier::Classify(uint16_t alStatusCode);
static ALErrorCategory ALErrorClassifier::Classify(EcALState alState);
Classifies an AL Status Code (the error code returned by a slave). Both uint16_t and EcALState parameter types are supported.
Parameters:
alStatusCode(uint16_t) — AL Status Code, obtained fromslave.ErrorCode()or from a failed state transitionalState(EcALState) — the enum form of the same code
Return value:
ALErrorCategory— 5 categories; the per-code result is exactly the same as in C / C# / Java / Python / Rust:
enum class ALErrorCategory {
None, // 0 = no error
Transient, // 1 transient error, the state transition can be retried, 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 supply
Unknown // 4 unknown error; see ETG.1000 or the slave manual
};
The mapping from return code to category is fixed at 0 = None / 1 = Transient / 2 = Configuration / 3 = Hardware / 4 = Unknown; out-of-range codes (or categories added in the future) always fall back to Unknown instead of guessing.
Example:
auto ec = master.GetSlave(1).ErrorCode();
if (ec != EcALState::NoError) {
auto category = ALErrorClassifier::Classify(ec);
printf("从站 1 错误 0x%04X: ", static_cast<uint16_t>(ec)); // Slave 1 error 0x%04X:
switch (category) {
case ALErrorCategory::Transient:
printf("瞬态错误,尝试重新切换状态\n"); break; // Transient error, retrying the state switch
case ALErrorCategory::Configuration:
printf("配置错误,请检查 PDO/SM 配置\n"); break; // Configuration error, check the PDO/SM configuration
case ALErrorCategory::Hardware:
printf("硬件错误,请检查从站设备\n"); break; // Hardware error, check the slave device
default:
printf("未知错误\n"); break; // Unknown error
}
}
Slave error counters
The only authoritative way to read slave port errors is slave_stats::read_port_errors(). The master-side MasterDiagnosticsInfo::ReadSlaveErrorCounters(slaveIndex) is kept for compatibility only and its readings are incomplete (the forwarded RX error item is missing, and FrameErrors / LostFrames are totals over the 4 ports); new code should use the former. When a read fails, zero counters together with LastSlaveErrorCountersReadOk() == false mean "nothing was read", not "0 errors". For a single slave's link quality use SlaveLinkQuality(slaveIndex).
ReadSlaveErrorCounters()
SlaveErrorCounters ReadSlaveErrorCounters(int slaveIndex);
Read the error counter summary of the given slave (registers 0x0300-0x030B: CRC(RX) errors, invalid frames and lost-link counts for ports 0-3).
Parameters:
slaveIndex(int) — slave index (1-based)
Return value:
SlaveErrorCounters— filled in as measured when the lower-level data can be read; when it cannot (runtime not ready / illegal index / slave unreachable / rejected) it returns all 0 counters andLastSlaveErrorCountersReadOk()== false:
struct SlaveErrorCounters {
int SlaveIndex; // Slave index
uint32_t Port0CrcErrors; // Port 0 CRC errors
uint32_t Port1CrcErrors; // Port 1 CRC errors
uint32_t Port2CrcErrors; // Port 2 CRC errors
uint32_t Port3CrcErrors; // Port 3 CRC errors
uint32_t FrameErrors; // Invalid frame count (sum over the 4 ports)
uint32_t LostFrames; // Lost link count (sum over the 4 ports)
};
Companion methods:
bool LastSlaveErrorCountersReadOk()— whether the lastReadSlaveErrorCounters()really read the lower-level data; when false, zero counters mean "nothing was read", not "0 errors"int16_t SlaveLinkQuality(uint16_t slave)— slave link quality- On the lower-level
Diagnostics:int ReadAllPortErrors()reads the port errors of all slaves in one batch;bool ResetSlavePortErrorCounters(uint16_t slave)resets the port error counters of the given slave
Example:
auto counters = diag.ReadSlaveErrorCounters(1);
if (!diag.LastSlaveErrorCountersReadOk()) {
printf("从站 1 错误计数没查到\n"); // Slave 1 error count could not be read
} else if (counters.Port0CrcErrors + counters.FrameErrors + counters.LostFrames > 0) {
printf("从站 1 错误计数: CRC P0=%u P1=%u P2=%u P3=%u, 帧=%u, 丢=%u\n", // Slave 1 error counts: CRC P0=%u P1=%u P2=%u P3=%u, frames=%u, lost=%u
counters.Port0CrcErrors, counters.Port1CrcErrors,
counters.Port2CrcErrors, counters.Port3CrcErrors,
counters.FrameErrors, counters.LostFrames);
}
Diagnostic messages
For reading and acknowledging the 0x10F3 diagnostic history see CoE - Diagnostic messages.
ReadDiagnosticMessages()
std::vector<DiagnosticMessage> slave.GetCoE().ReadDiagnosticMessages();
Reads the list of diagnostic messages from slave object 0x10F3 (the diagnostic history object, ETG.1020) over CoE, including the diagnostic code, flags and text index.
Parameters:
- None
Return value:
std::vector<DiagnosticMessage>— the list of diagnostic messages; an empty list when there are no messages (or the slave does not support 0x10F3):
struct DiagnosticMessage {
uint8_t sub_index; // Subindex
uint32_t diag_code; // Diagnostic code
uint16_t flags; // Flag bits
uint16_t text_index; // Text index
std::vector<uint8_t> raw_data; // Raw data
};
Example:
// GetSlaves() returns std::vector<uint16_t> (slave indices, 1-based),
// Only a direct range-based for over master gives you Slave objects.
for (auto& slave : master) {
auto messages = slave.GetCoE().ReadDiagnosticMessages();
if (messages.empty()) continue;
for (auto& msg : messages) {
printf("[从站 %d] 代码=0x%08X, Flags=0x%04X\n", // [Slave %d] code=0x%08X, Flags=0x%04X
slave.SlaveNum(), msg.diag_code, msg.flags);
}
}
Not every slave supports the 0x10F3 diagnostic history object. An unsupported slave returns an empty list. This method reads over SDO and should not be called at high frequency on a real-time path.
Sliding window statistics (DiagCsWindow)
Error rate / cycle frequency / average jitter aggregation over a 5s × 0.2s sliding window. Window advancement and throttling happen inside the runtime; the SDK only passes them through and does not recompute the definitions at the SDK layer.
namespace darra::ethercat {
bool DiagCsWindow_GetStats(uint16_t master_index, DiagCsWindowStats* out);
}
| Category | Property | Type | Read/write | Description |
|---|---|---|---|---|
| Sliding window statistics | darra::ethercat::DiagCsWindow_GetStats(mi, out) | bool | Read-only | Take the window statistics: true = statistics exist and out was filled; false = no statistics (illegal master index / out is null / SDK not ready), in which case out is not cleared — the caller must clear out first and then judge the return value |
| DiagCsWindow_Sample(mi, now_ts, ts_freq) | void | Write-only | Advance the window by one sampling tick. Throttling and window boundaries are handled in the lower layer; do not compute them in the application layer | |
| DiagCsWindow_Reset(mi) | void | Write-only | Clear the window statistics of that master |
DiagCsWindow_GetStats lives in the darra::ethercat namespace (typed out-parameter DiagCsWindowStats*); DiagCsWindow_Sample / DiagCsWindow_Reset are same-named functions in the global scope (declared in the C SDK header master/diagnostics_info.h) — call them directly from C++ and do not wrap another function with the same signature inside darra::ethercat.
Related structure:
struct DiagCsWindowStats {
double error_per_sec; // Errors per second (ErrorCnt convention)
double cycle_hz; // Cycle rate in Hz (RTcnt fallback convention)
double avg_jitter_us; // Average jitter (microseconds)
int32_t filled; // Ticks accounted for within the window
int32_t reserved; // Reserved, always 0
};
DiagCsWindowStats has a naturally aligned 32-byte layout; filled == 0 means the window has no samples yet, so the three metrics are 0, which does not mean "0 errors / 0 Hz measured".
DiagCsWindow_GetStats() returning false only means "no statistics"; it does not write 0 into out. Use DiagCsWindowStats stats{}; first, then call it, and judge by the return value; do not take the leftover value from the previous call as this call's result.
Example:
#include "ethercat.hpp"
using namespace darra::ethercat;
DiagCsWindowStats stats{}; // Clear it first: out is not written when the value cannot be obtained
if (DiagCsWindow_GetStats(master.MasterNumber(), &stats)) {
if (stats.filled == 0)
printf("窗口还没采样\n"); // The window has not been sampled yet
else
printf("错误/秒=%.2f 周期=%.1f Hz 抖动=%.1f us (采样 %d 拍)\n", // Errors/sec=%.2f cycle=%.1f Hz jitter=%.1f us (%d sampled cycles)
stats.error_per_sec, stats.cycle_hz,
stats.avg_jitter_us, stats.filled);
} else {
printf("取不到窗口统计 (主站索引非法 / SDK 未就绪)\n"); // Window statistics unavailable (invalid master index / SDK not ready)
}
Link diagnostic events
The master stores link-down / recovery diagnostic events by sequence number; the caller reads them incrementally using the sequence number as a cursor and does not need to de-duplicate on its own. Link-down / recovery / redundancy switch-over can also be obtained through the events callbacks.
| Category | Property | Type | Read/write | Description |
|---|---|---|---|---|
| Link events | EtherCATMaster::GetLinkDiagEventCount() | uint32_t | Read-only | Total number of link diagnostic events (including history before wrap-around overwrite), used to judge whether there are new events |
| EtherCATMaster::GetLinkDiagEvents(sinceSeq, out, max) | uint32_t | Read-only | Copies at most max events starting at sinceSeq and returns the actual count; 0 = no new events. out must be a LinkDiagEvent array | |
| EtherCATMaster::GetLinkDiagSeq() | uint32_t | Read-only | Freshness token: monotonically increasing = the event record is advancing; not increasing = the record has stalled. It is neither the event count nor the sequence number of the last event |
Related structure:
struct LinkDiagEvent {
uint64_t t_us; // Event time (microseconds)
uint32_t seq; // Monotonically increasing sequence per master (the reader's cursor)
uint8_t kind; // Event type: 1=A_LINK_DOWN 2=B_LINK_DOWN 3=MIDDLE_BROKEN
// 4=HEALTHY 5=TOTAL_LOST 6=PHY_A 7=PHY_B 8=FAILOVER
// 9=RECOVER 10=QUICK_FLAP 11=WKC_TUPLE
uint8_t port; // Ports 0-3 (used for PHY_* events; 0xFF otherwise)
uint8_t from_state; // Old redundancy state value
uint8_t to_state; // New redundancy state value
uint16_t a_peer, a_self, b_peer, b_self; // Raw snapshot of the trigger tick quartet (not debounced)
uint8_t ring_intact; // 1=ring closed 0=ring open
uint8_t is_up; // 1=reconnect edge 0=disconnect edge
uint16_t effective_wkc; // Topology union WKC (comparable with expected on the same basis, no double counting)
uint16_t expected_wkc; // The fixed expected WKC truth established at configuration time
};
kind / is_up record "what happened"; effective_wkc and expected_wkc are given side by side as the comparison for that cycle. Health is still judged from the relation between the merged WKC and the expected WKC; do not characterize a slave from a single event alone.
Example:
#include "ethercat.hpp"
using namespace darra;
uint32_t since = 0; // Cursor: starts at the earliest entry
LinkDiagEvent events[32];
uint32_t n = master.GetLinkDiagEvents(since, events, 32);
for (uint32_t i = 0; i < n; ++i) {
printf("[%llu us] seq=%u kind=%u port=%u WKC=%u/%u\n",
static_cast<unsigned long long>(events[i].t_us), events[i].seq,
events[i].kind, events[i].port,
events[i].effective_wkc, events[i].expected_wkc);
since = events[i].seq; // Next read starts from here
}
// Freshness: if the token read twice does not change, the event log is not advancing
uint32_t seq = master.GetLinkDiagSeq();
printf("累计事件 %u 条, 新鲜度令牌 %u\n", master.GetLinkDiagEventCount(), seq); // %u events so far, freshness token %u
Slave-loss attribution
Slave-loss attribution is not wrapped separately: take data from three places — the real OP verdict, the WKC mirror and the event stream:
- Real OP verdict —
RealOpTruth()/CaptureRealOpTruth()/EvaluateSlaveRealOp(int)(per-slave verdict): evidence that cannot be read is honestly judgedRealOpReason::Unknown(see Real OP verdict above). - WKC mirror —
dm::wc_deficit(mi)/dm::slave_wc_contributed(mi, si)(per-slave WKC deficit): a lost slave is a persistent state, which is a different definition from the single-cycle WKC deficit; do not mix them (see WKC mirror above). - Events — take data from event streams such as
SlaveProbeStateand read incrementally with the event sequence number as a cursor.
When you build a slave-loss attribution report, take data from the real OP result and the event stream; there is no need to fetch the raw verdict separately. Any evidence that cannot be obtained is treated as "unknown"; do not read it as "not recovered" or "process data is dead".
Complete example
#include "ethercat.hpp"
#include <cstdio>
#include <thread>
#include <chrono>
using namespace darra;
int main() {
try {
dll_t dll;
EtherCATMaster master(dll);
if (!master.SetNetwork("\\Device\\NPF_{...}").SetENI("C:/config.deni").Build()) {
printf("建链失败: %ld (21=瞬态可重试, 1168=网卡未绑定)\n", master.LastError()); // Link-up failed: %ld (21=transient, retryable; 1168=NIC not bound)
return 1;
}
if (!master.SetState(EcState::OP)) {
printf("进入 OP 失败, 诊断读数无意义\n"); // Entering OP failed, the diagnostic readings are meaningless
return 1;
}
master.Start();
auto& base = master.GetDiagnostics();
MasterDiagnosticsInfo diag(base, master.MasterNumber());
diag.Enabled(true); // Turn on the optional user-tier statistics (the baseline tier is always on, see "diagnostics control")
// Register the exception callback (PDO frame loss events go through OnPDOFrameLoss, not a field assignment)
master.Events().OnPDOFrameLoss([](uint16_t mi, uint8_t grp,
uint32_t c, uint32_t t) {
printf("组 %d 丢帧: 连续=%u, 累计=%u\n", grp, c, t); // Group %d frame loss: consecutive=%u, total=%u
});
// Print diagnostic information periodically
for (int i = 0; i < 60; ++i) {
std::this_thread::sleep_for(std::chrono::seconds(1));
// Frame count
printf("[%02d] 帧频=%u Hz, 丢包率=%.2f%%, CycleCount=%llu\n", // [%02d] frame rate=%u Hz, packet loss rate=%.2f%%, CycleCount=%llu
i, diag.RTcnt(), diag.PacketLossRate() * 100.0,
static_cast<unsigned long long>(diag.CycleCount()));
// Cycle time and jitter + mailbox latency
printf(" 周期=%.1f us, 总线抖动 平均=%.2f us, 邮箱延迟 平均/最大=%.2f/%.2f us\n", // Cycle=%.1f us, bus jitter average=%.2f us, mailbox latency average/max=%.2f/%.2f us
diag.CycleTimeSpan(), diag.AvgJitterUs(),
diag.MailboxLatencyAvgUs(), diag.MailboxLatencyUs());
// PDO frame loss (GetPDOFrameLossStats is on the underlying Diagnostics)
auto pdo_stats = base.GetPDOFrameLossStats(0);
if (pdo_stats.total_lost > 0)
printf(" PDO 丢帧: 累计=%u, 连续=%u\n", // PDO frame loss: total=%u, consecutive=%u
pdo_stats.total_lost, pdo_stats.consecutive_lost);
// Slave fault
if (diag.WorstLinkQuality() >= 0 && diag.WorstLinkQuality() < 80)
printf(" 最差从站: #%d (%.0f%%)\n", // Worst slave: #%d (%.0f%%)
diag.WorstSlaveIndex(), diag.WorstLinkQuality());
// NIC link status
printf(" 主端口: %s, 副端口: %s\n", // Primary port: %s, secondary port: %s
diag.PrimaryPortOk() ? "正常" : "异常", // OK / abnormal
diag.SecondaryPortOk() ? "正常" : "未连接"); // OK / not connected
// Redundancy state
if (diag.RingMode() == darra::RingMode::Degraded) {
printf(" 警告: 冗余降级!\n"); // Warning: redundancy degraded!
auto bps = base.GetBreakPoints();
for (auto& bp : bps) {
printf(" 故障: 从站 %d P%d %s\n", bp.slave, bp.port, // Fault: slave %d P%d %s
bp.is_crc_fault() ? "CRC故障" : "断线"); // CRC fault / cable break
}
}
// AL error classification
for (int si = 1; si <= master.SlaveCount(); ++si) {
auto& slave = master.GetSlave(si);
auto ec = slave.ErrorCode();
if (ec != EcALState::NoError) {
auto category = ALErrorClassifier::Classify(ec);
printf(" 从站%d 错误 0x%04X: %s\n", si, // Slave %d error 0x%04X: %s
static_cast<uint16_t>(ec),
category == ALErrorCategory::Transient ? "瞬态" : // Transient
category == ALErrorCategory::Configuration ? "配置" : // Configuration
category == ALErrorCategory::Hardware ? "硬件" : "未知"); // Hardware / unknown
}
}
}
} catch (const ethercat::DarraException& e) {
printf("错误: %s\n", e.what()); // Error: %s
return -1;
}
return 0;
}
Diagnostic field guide by symptom
Every API in the table is a real interface: members of MasterDiagnosticsInfo (the higher-level wrapper, diag in the table) and of the lower-level Diagnostics (base in the table).
| Field symptom | C++ API |
|---|---|
| Is it packet loss? | diag.PacketLossRate() + diag.LateFrameRate() |
| WKC deficit / locating the lost slave? | dm::wc_deficit(mi) + dm::slave_wc_contributed(mi, si) |
| Is the WKC problem sporadic or persistent? | base.ZeroWkcCount() / base.LowWkcCount() / base.HighWkcCount() |
| Which slave has the worst link? | diag.WorstSlaveIndex() + diag.WorstLinkQuality() |
| Link quality of a single slave? | base.SlaveLinkQuality(slaveIndex) |
| ESC port errors (CRC and so on)? | slave_stats::read_port_errors(dll, mi, si) (Slave diagnostics) |
| Which cable is broken? | base.GetBreakPoints() + base.LastBreakPointsQueryOk() |
| RT stability? | diag.RtPreemptCount() / diag.BigGapUnknownCount() / diag.SmiCount() / diag.SmiPeakUs() |
Packet loss and frame timing
PacketLossRate() (estimated packet loss ratio, definition in Communication and performance statistics) / LateFrameRate() (late frames) / RTcnt() (frame rate in Hz) / ErrorCnt() (errors per second).
WKC classification counters
base.ZeroWkcCount() (WKC = 0, complete loss) / base.LowWkcCount() (below expectation, some slaves did not respond) / base.HighWkcCount() (above expectation, abnormal). They only accumulate when base.UpdateWkcClassification(wkc, expected) is called every cycle.
WKC and lost slaves: for expected / actual / deficit see WKC mirror; for the per-slave real OP see Real OP verdict. Use the deficit directly as the criterion; do not compute a second one in the application layer.
Port status
PrimaryPortOk() / SecondaryPortOk() (traffic present and no error within 5 seconds); PrimaryPortErrors() / SecondaryPortErrors() (error count over 5 seconds).
Per-slave physical layer (ESC registers)
ESC port error counters (RX / invalid frames / link loss / forwarding errors) are read through the slave_stats free functions, see Slave diagnostics - Communication diagnostics. Link quality can also be queried for a single slave through base.SlaveLinkQuality(si).
RT performance and stability
BusCycleHz() / BusMaxJitterUs() / BusRoundtripUs() / BusLoadPercent() (derived values); RtPreemptCount() (number of RT thread preemptions) with a value other than 0 means the RT thread was interrupted; BigGapUnknownCount() (count of large gaps of unknown cause) / SmiCount() (SMI count) / SmiPeakUs() (SMI peak jitter); for the jitter distribution use JitterHistogramBins() (7-bucket histogram).
Complete diagnostic flow example
auto& base = master.GetDiagnostics();
MasterDiagnosticsInfo diag(base, master.MasterNumber());
// 1. Packet loss rate
if (diag.PacketLossRate() > 0.01)
std::cout << "[警告] 丢包率 " << (diag.PacketLossRate() * 100) << "% 严重\n"; // [Warning] packet loss rate <value>% — severe
// 2. WKC classification (requires UpdateWkcClassification to accumulate every cycle)
if (base.LowWkcCount() > 0 || base.ZeroWkcCount() > 0)
std::cout << "[警告] WKC 异常: 完全丢失 " << base.ZeroWkcCount() // [Warning] WKC abnormal: total loss
<< " 次, 低于预期 " << base.LowWkcCount() << " 次\n"; // times, below expected
// 3. Fault localisation (GetBreakPoints returns a vector, not a single value)
for (auto& bp : base.GetBreakPoints())
std::cout << "故障点: 从站 " << bp.slave << " P" << (int)bp.port // Fault point: slave
<< (bp.is_crc_fault() ? " CRC 劣化" : " 断线") << "\n"; // CRC degradation / cable break
// 4. Worst-link slave
if (diag.WorstLinkQuality() >= 0 && diag.WorstLinkQuality() < 80)
std::cout << "最差从站: #" << diag.WorstSlaveIndex() // Worst slave: #
<< " (" << diag.WorstLinkQuality() << "%)\n";
// 5. RT stability (honest hard real-time counters)
if (diag.RtPreemptCount() > 0)
std::cout << "[警告] RT 线程被抢占 " << diag.RtPreemptCount() // [Warning] RT thread preempted
<< " 次, 峰值 " << diag.RtPreemptPeakNs() << " ns\n"; // times, peak