Master diagnostics
Access all diagnostics, monitoring and statistics through master.Diagnostics.
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, topology |
| DC synchronization | Sync window threshold, DCSyncLost event |
| Redundancy status | Redundancy active, fault point detection (link break and CRC fault location) |
| Diagnostic control | Start and stop data collection, reset statistics |
Communication and performance statistics
| Category | Property | Type | Access | Enable control | Description |
|---|---|---|---|---|---|
| Frame counts | RTcnt | int | Read-only | Yes | Frames per second (Hz), 5-second average |
ErrorCnt | uint | Read-only | Yes | Errors per second, 5-second average | |
PacketLossRate | float | Read-only | Yes | Packet loss rate (0.0~1.0) — TX vs RX over a 5-second sliding window; frames still in flight on the pipeline do not count as lost | |
LateFrameRate | float | Read-only | Yes | Late frame rate (0.0~1.0) — an index that leaves the 8-frame window is stale and not counted as packet loss | |
| Cycle and jitter | CycleTimeSpan | int | Read-only | Yes | Actual cycle time (µs). Derived from the frame rate when it cannot be read; returns 0 when the frame rate is also 0. Compare it with the configured master cycle time; it is not hard-coded to 1 ms. |
CycleCount | ulong | Read-only | Always on | Cycle counter, incremented on every bus cycle. | |
AvgJitterUs | double | Read-only | Yes | Average jitter over the last 5 seconds (µs). Jitter grows when real-time isolation is not in effect; the cycle should still hold at the configured value. Minimum cycle time is 125 µs. | |
RTcnt | int | Read-only | Yes | Frames per second (Hz). A sustained deviation of ±20% from the configured value, or a maximum jitter above 25% of the cycle time, should be logged and alarmed. Use it together with Events.PDOFrameLoss / Events.DCSyncLost. Do not hard-code 1000 Hz. | |
| Mailbox latency | MailboxLatencyUs | double | Read-only | Yes | Mailbox latency — maximum (µs). Maximum round-trip time of mailbox transactions (acyclic request-response exchanges such as CoE/SoE/FoE/EoE/AoE/VoE) from request to response (settled over the last second) |
MailboxLatencyAvgUs | double | Read-only | Yes | Mailbox latency — average (µs). Average round-trip time of the same transactions (settled over the last second) | |
| PDO frame loss | PDO.TotalLost | uint | Read-only | Always on | Total lost frames (sum of all groups) |
PDO.ConsecutiveLost | uint | Read-only | Always on | Current consecutive lost frames (maximum across all groups) | |
PDO.GetFrameLossStats(byte group) | PDOFrameLossStats | Read-only | Always on | Get the PDO frame loss statistics of the specified group. 0-7 returns the corresponding group; without a parameter it returns the summary for all groups. Valid PDO groups are 1-7; group 0 is the unassigned marker and has no PDO data segment. The returned value contains TotalLost / ConsecutiveLost / MaxConsecutiveLost | |
| Slave anomalies | WorstSlaveIndex | ushort | Read-only | Always on | Slave index with the highest error rate |
WorstLinkQuality | short | Read-only | Always on | Communication health of the worst slave (%), lower is worse; -1 = unknown | |
| Master truth values / input validity | LostSlaveCount | int | Read-only | Always on | Lost-slave census count (the single authority for the bus-level lost-slave count); >0 = a slave was lost; -1 = read failed / unavailable (use together with LostSlaveCountKnown) |
LostSlaveCountKnown | bool | Read-only | Always on | Whether LostSlaveCount has a measured sample; when false the -1 carries no meaning and must be shown as "unknown" | |
NoProcessData | bool | Read-only | Always on | Master-level "no process data / false OP" truth value: true = the cycle runs but process data is dead; a read failure returns true (failsafe, never passed off as healthy) | |
NoProcessDataKnown | bool | Read-only | Always on | Whether NoProcessData has a measured sample; when false the return value carries no meaning and must be shown as "unknown" | |
ProbeAliveCount | int | Read-only | Always on | Probe truth summary — number of slaves with a real reply (0 when there is no true-value sample) | |
ProbeUnknownCount | int | Read-only | Always on | Probe truth summary — number of slaves with insufficient evidence (unknown) (0 when there is no true-value sample) | |
StaleInputCount | int | Read-only | Always on | Number of slaves whose input data is confirmed STALE; Unknown/Degraded are not counted; -1 = a slave read failed / unavailable (use together with StaleInputCountKnown) | |
StaleInputCountKnown | bool | Read-only | Always on | Whether StaleInputCount has a complete measured sample; when false the -1 carries no meaning | |
| Topology changes | TopologyFingerprint | ulong | Read-only | Always on | Topology fingerprint (stable hash of the slave count + each slave's VendorId/ProductId/RevId); a changed fingerprint = the topology changed; TopologyFingerprintKnown says whether sampling succeeded |
TopologyFingerprintKnown | bool | Read-only | Always on | Whether the topology fingerprint has been sampled successfully at least once; when false the value carries no meaning | |
TopologyChangeCount | ulong | Read-only | Always on | Number of observed topology changes (the first sampling is not counted; observed on read, several changes between two reads are merged into one) | |
LastTopologyChangeUtc | DateTime? | Read-only | Always on | Time of the most recently observed topology change (UTC); null = no change observed yet | |
| WKC | WKC | ushort | Read-only | Always on | Current working counter (actual WKC). WKC ≠ ExpectedWKC means a slave is not responding correctly |
ExpectedWKC | ushort | Read-only | Always on | Expected working counter (expected WKC). A fixed value determined at configuration time / when entering OP; it is never lowered dynamically to accommodate a degraded bus | |
PrimaryWKC | ushort | Read-only | Always on | Primary-port working counter (tracked independently in redundancy mode) | |
SecondaryWKC | ushort | Read-only | Always on | WKC measured on the secondary port in this cycle. Returns 0xFFFF (WkcUnknown) when this cycle has no fresh measurement, never a stale full count; 0 on a single-port setup is a valid reading | |
SecondaryWkcKnown | bool | Read-only | Always on | Whether this cycle has a measurement for the secondary-port WKC. false only means SecondaryWKC == 0xFFFF; 0 on a single-port setup still counts as known | |
SecondaryWkcRt | ushort | Read-only | Always on | Real-time filtered WKC of the secondary port (drops in the same cycle a slave is unplugged or the link breaks). Use this property for the current instant; do not substitute a peak-held value | |
PrimaryExpectedWKC | ushort | Read-only | Always on | **Ring share** expectation for frames sent on the primary port. Differs from SecondaryExpectedWKC under redundancy; returns 0 on a single port / when the topology is not identified, falling back to ExpectedWKC | |
SecondaryExpectedWKC | ushort | Read-only | Always on | **Branch share** expectation for frames sent on the secondary port. In chain (end foldback) form the secondary port only receives → always 0; returns 0 on a single port / when the topology is not identified | |
PrimaryWkcRt | ushort | Read-only | Always on | Real-time filtered WKC of the primary port — filtered frame by frame from the frames by the real-time runtime and dropping in the same cycle a slave is unplugged; not a peak-held value. Use this property for the current instant; for the aggregate scale see WKC | |
| WKC mirror | WkcActualMirror | int | Read-only | Always on | Mirror of the measured bus working counter (actual WKC) — reflects which slaves really respond right now. Reported as measured, never altered; a read generates no bus frames and returns the current cycle |
WkcExpectedMirror | int | Read-only | Always on | Mirror of the expected working counter (expected WKC) — the fixed 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; a read generates no bus frames | |
WcDeficit | int | Read-only | Always on | WKC deficit (>0 means a mapped slave is not contributing WKC right now, suspected lost slave / Hot-plug). Judged by the engine over the topology union (each slave counted at most once); when the engine has not produced a verdict this session it falls back to the raw kernel mirror value; 0 may be a true 0 or may be unknown. This is not a master fault but an observable of the bus reality; it returns to 0 automatically once the slave recovers. Do not compute it yourself as WkcExpectedMirror − WkcActualMirror | |
MappedSlaveCount | int | Read-only | Always on | Number of mapped slaves (participating in the WKC calculation) | |
HasWkcMirrorData | bool | Read-only | Always on | Whether the WKC mirror data is ready. false = the mirror is not usable yet (no mapped slaves / expected WKC unknown); do not draw conclusions from WkcActualMirror and WkcExpectedMirror in that state | |
| Port status | PrimaryPortOk | bool | Read-only | Always on | Whether the primary port is healthy (traffic present and no errors within 5 seconds) |
SecondaryPortOk | bool | Read-only | Always on | Whether the secondary port is healthy (traffic present and no errors within 5 seconds; always false without redundancy) | |
PrimaryPortErrors | uint | Read-only | Always on | Primary-port errors in the last 5 seconds | |
SecondaryPortErrors | uint | Read-only | Always on | Secondary-port errors in the last 5 seconds | |
| Topology | TopologyDescription | string | Read-only | Always on | Topology mode description ("line" / "ring" / "ring + branch") |
TimingModeCode | uint | Read-only | Always on | Raw value of the current timing mode | |
TimingModeDescription | string | Read-only | Always on | Text of the current timing mode ("hardware timer" / "RT ready" / "degraded" / "RT error"). The real-time runtime must be ready before operation | |
| DC synchronization | SyncWindowThreshold | int | Read/write | Always on | Synchronization window threshold (ns), default 1000 ns. Exceeding the threshold triggers the DCSyncLost event |
| Redundancy status | RedundancyActive | bool | Read-only | Always on | Redundancy protection is running = RingMode>=1 (Dual/Degraded) and both ports carry frame traffic in this window; for ring-less topologies such as chain (end foldback) it is false even when both ports carry frames |
RedundancyRingMode | RingMode | Read-only | Always on | Redundant ring operating mode; the RingMode property is a compatibility alias | |
BreakPoint | BreakPointInfo? | Read-only | Always on | Current fault point (only the first is returned when there are several). Supports link break and CRC fault; cleared automatically after recovery. null means both "no fault" and "query failed" — to tell them apart use TryGetBreakPoint(queryOk) or GetAllBreakPoints(null = failure) | |
| Diagnostic control | Enabled | bool | Read/write | Diagnostic data collection switch (off by default). When enabled, samples periodically and records the statistics marked [Yes] |
Calculation formulas
| Metric | Formula | Description |
|---|---|---|
| RTcnt | Frames in the sampling period / window seconds | Sliding-window average frame rate |
| ErrorCnt | Errors in the sampling period / window seconds | Sliding-window average error rate |
| PacketLossRate | (TX-RX-pipeline) / TX | 5-second sliding-window packet loss rate; frames in flight on the full-duplex pipeline do not count as lost |
| LateFrameRate | LateDrop / TX | Late frame rate (an index that leaves the 8-frame window is stale and not counted as packet loss) |
Requires Enabled = true.
PDOFrameLossStats structure
| Category | Property | Type | Access | Description |
|---|---|---|---|---|
| Frame loss statistics | TotalLost | uint | Read-only | Total lost frames |
| ConsecutiveLost | uint | Read-only | Current consecutive lost frames | |
| MaxConsecutiveLost | uint | Read-only | Maximum consecutive lost frames on record |
Example:
var diag = master.Diagnostics;
diag.Enabled = true; // Enable diagnostic data collection
// Frame counts
Console.WriteLine($"帧频: {diag.RTcnt} Hz"); // Frame rate: {diag.RTcnt} Hz
Console.WriteLine($"丢包率: {diag.PacketLossRate:P2}"); // Packet loss rate: {diag.PacketLossRate:P2}
Console.WriteLine($"错误数: {diag.ErrorCnt}"); // Error count: {diag.ErrorCnt}
// Cycle and jitter
Console.WriteLine($"周期时间: {diag.CycleTimeSpan} µs"); // Cycle time: {diag.CycleTimeSpan} µs
Console.WriteLine($"周期计数: {diag.CycleCount}"); // Cycle count: {diag.CycleCount}
Console.WriteLine($"总线抖动: 平均 {diag.AvgJitterUs:F2} µs"); // Bus jitter: average {diag.AvgJitterUs:F2} µs
// Mailbox latency (round-trip time of acyclic CoE/SoE/FoE/EoE/AoE/VoE transactions)
Console.WriteLine($"邮箱延迟: 平均 {diag.MailboxLatencyAvgUs:F2} µs, 最大 {diag.MailboxLatencyUs:F2} µs"); // Mailbox latency: average {diag.MailboxLatencyAvgUs:F2} µs, max {diag.MailboxLatencyUs:F2} µs
// PDO frame loss (summary across all groups)
var pdo = diag.PDO;
Console.WriteLine($"PDO 丢帧: 累计={pdo.TotalLost}, 连续={pdo.ConsecutiveLost}"); // PDO frame loss: total={pdo.TotalLost}, consecutive={pdo.ConsecutiveLost}
if (pdo.ConsecutiveLost > 10)
Console.WriteLine("警告: PDO 连续丢帧!"); // Warning: consecutive PDO frame loss!
// Frame loss by group (0-7; valid PDO groups are 1-7; group 0 is the unassigned marker with no PDO data segment)
var group1Stats = pdo.GetFrameLossStats(1); // Group 1 (default group, used before slave mapping)
var group2Stats = pdo.GetFrameLossStats(2); // Group 2
Console.WriteLine($"组1丢帧: {group1Stats.TotalLost}, 组2丢帧: {group2Stats.TotalLost}"); // Group1 frame loss: {group1Stats.TotalLost}, group2 frame loss: {group2Stats.TotalLost}
// Slave anomalies
Console.WriteLine($"最差从站: #{diag.WorstSlaveIndex} ({diag.WorstLinkQuality}%)"); // Worst slave: #{diag.WorstSlaveIndex} ({diag.WorstLinkQuality}%)
// Port status
Console.WriteLine($"主端口: {(diag.PrimaryPortOk ? "正常" : "异常")}"); // Primary port: {(diag.PrimaryPortOk ? "OK" : "fault")}
Console.WriteLine($"副端口: {(diag.SecondaryPortOk ? "正常" : "未连接")}"); // Secondary port: {(diag.SecondaryPortOk ? "OK" : "not connected")}
// Topology information
Console.WriteLine($"拓扑: {diag.TopologyDescription}"); // Topology: {diag.TopologyDescription}
Console.WriteLine($"定时: {diag.TimingModeDescription}"); // Timing: {diag.TimingModeDescription}
Read the ESC port errors of each slave through slave.Diagnostics.ReadPortErrors().
WKC mirror (lost slaves observable)
WkcActualMirror / WkcExpectedMirror / WcDeficit are the master-level aggregate of the per-slave process data contribution state: a read generates no bus frames and always reflects the measured bus state of the current cycle, with no extra refresh. Together with slave.WcContributed per slave you can locate exactly which slave dropped.
Observability contract:
WkcExpectedMirror= the fixed 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.WkcActualMirror= the measured bus value, reported as measured, reflecting which slaves really respond right now, never altered.WcDeficitis judged by the engine over the topology union (each slave counted at most once); when the engine has not produced a verdict this session, it falls back to the raw kernel mirror value. Do not subtractWkcExpectedMirror − WkcActualMirroryourself: the three values come from different producers with different refresh beats, and a healthy bus with Extra / branch groups also shows a structural difference.WcDeficit > 0is not a master fault: a mapped slave is not contributing WKC right now (suspected lost slave / Hot-plug recovery). Once the slave recovers,WcDeficitreturns to 0 automatically, without needing any reset call.
Example:
var diag = master.Diagnostics;
// Master-level WKC mirror (real time)
Console.WriteLine($"WKC: {diag.WkcActualMirror} / {diag.WkcExpectedMirror} (映射从站 {diag.MappedSlaveCount} 个)"); // WKC: {diag.WkcActualMirror} / {diag.WkcExpectedMirror} ({diag.MappedSlaveCount} mapped slaves)
if (diag.WcDeficit > 0)
{
Console.WriteLine($"⚠️ WKC 缺额 {diag.WcDeficit} — 有从站没在响应,逐个从站定位:"); // ⚠️ WKC deficit {diag.WcDeficit} — some slaves are not responding, locate them one by one:
foreach (var slave in master.Slaves)
if (slave.WcContributed == WcContribution.NotContributed)
Console.WriteLine($" 从站 {slave.SlaveNum} 未贡献 WKC (AL={slave.AlStatusCode})"); // slave {slave.SlaveNum} contributes no WKC (AL={slave.AlStatusCode})
}
// Whether the mirror data is ready (do not draw conclusions before it is)
bool ready = diag.GetSnapshot().HasWkcMirrorData;
Use slave.WcContributed (WcContribution enumeration) for the contribution state of an individual slave. When WcDeficit > 0, iterate the slaves to locate the lost one.
Secondary-port WKC "unknown" state
SecondaryWKC is the measured value for the current cycle of the 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 | Access | Description |
|---|---|---|---|---|
| Redundancy WKC | SecondaryWKC | ushort | Read-only | Secondary-port WKC measured in this cycle. Returns 0xFFFF (= WkcUnknown) when this cycle has no fresh measurement |
| Redundancy WKC | MasterDiagnosticsInfo.WkcUnknown | const ushort | Read-only | "No measurement" sentinel, value 0xFFFF |
| Redundancy WKC | SecondaryWkcKnown | bool | Read-only | Whether this cycle has a measurement. false only means SecondaryWKC == 0xFFFF |
| Redundancy WKC | SecondaryWkcRt | ushort | Read-only | Real-time filtered secondary-port value (drops in the same cycle a slave is unplugged or the link breaks); use this for "right now" |
On a single port (no secondary leg configured) a return of 0 is a valid reading and counts as "known". So to decide "unknown" you must read SecondaryWkcKnown; neither "is the value 0" nor treating 0xFFFF as a full count works.
Example:
var diag = master.Diagnostics;
if (!diag.SecondaryWkcKnown)
Console.WriteLine("副口 WKC: 未知(本拍无实测)"); // Secondary port WKC: unknown (no measurement this tick)
else if (diag.SecondaryWKC == 0)
Console.WriteLine("副口 WKC: 0(单网口 / 副口本拍无贡献)"); // Secondary port WKC: 0 (single port / secondary contributed nothing this tick)
else
Console.WriteLine($"副口 WKC: {diag.SecondaryWKC},实时值 {diag.SecondaryWkcRt}"); // Secondary port WKC: {diag.SecondaryWKC}, real-time value {diag.SecondaryWkcRt}
Single source-of-truth snapshot (MasterTruthSnapshot)
Contradictions within one cycle, such as "alive 1/6 / WKC=12/12 / redundant WKC=0 (sWkc=6)", come from each surface reading and assembling its own values. MasterTruthSnapshot assembles WKC (fixed expectation / measured value / per-port split) + per-slave tri-state + link form + master-level attribution into one immutable same-cycle object; the status bar, topology page, diagnostics page and redundancy diagnostics should all consume the same object instead of each taking its own set.
| Category | Member | Returns | Access | Description |
|---|---|---|---|---|
| Entry | master.Diagnostics.Truth | MasterTruthSnapshot | Read-only | Assembles one cycle per get; equivalent to CaptureTruthSnapshot() |
| Entry | master.Diagnostics.CaptureTruthSnapshot() | MasterTruthSnapshot | Read-only | Explicitly assembles one cycle; call it once and pass the object down when several places need to share it |
MasterTruthSnapshot
(Category: diagnostics; access: all read-only)
| Category | Property | Type | Description |
|---|---|---|---|
| Timing | Sequence | long | Snapshot sequence number, monotonically increasing per master; the same number = the same data from the same cycle |
| Timing | CapturedAtUtc | DateTime | Assembly time (UTC) |
| Scale | SlaveCount | int | Number of master table rows (including placeholder rows; no slave is dropped) |
| WKC | WkcExpected | ushort | Fixed expectation from configuration time, never lowered dynamically |
| WKC | WkcActual | ushort | Measured value in merged terms (primary + secondary under redundancy) |
| WKC | WkcDeficit | int | expected - actual; a negative value = measurement above expectation (for example the redundancy merge) |
| WKC | PrimaryWkc / SecondaryWkc | ushort | Single-port measurements of the primary / secondary port (SecondaryWkc is sWkc) |
| WKC | PrimaryExpectedWkc / SecondaryExpectedWkc | ushort | Expectation for frames sent on the primary / secondary port; 0 when the topology is not identified, falling back to WkcExpected |
| Process data | NoProcessData | bool | Master-level measurement: true = the cycle runs but process data is dead (false OP) |
| Lost slaves | LostSlaveCount | int | Lost slaves found by bus measurement outside the topology coverage |
| Link | Link | TruthLinkInfo | Both-port tri-state + redundancy operating mode + derived form (see below) |
| Redundancy | SecondaryAdapterConfigured | bool | Configuration fact: whether a secondary NIC is configured. ≠ "a redundancy ring exists" |
| Redundancy | SecondaryAdapterBound | bool | Binding fact: whether the secondary NIC is actually bound successfully; configured true but false here = configured but not bound, link verdicts are unusable |
| Attribution | Attribution | TruthAttribution | The single interpretation of this cycle's facts (see the enumeration table) |
| Attribution | AttributionDetail | string | Readable detail (WKC split per port + list of abnormal slaves) |
| Per slave | Slaves | SlaveTruthEntry?[] | 1-based array, [0] is always null; every access returns a copy |
| Summary | AliveCount | int | The single definition of "alive N/M" = slaves confirmed to contribute process data (slaves with insufficient evidence are not counted) |
| Summary | LostCount | int | Number of slaves with the Offline verdict |
| Summary | UnknownCount | int | Number of slaves with insufficient evidence / unknown (including placeholder rows) |
TruthLinkInfo
(Category: diagnostics / link; access: all read-only)
| Category | Property | Type | Description |
|---|---|---|---|
| Physical link | PrimaryPhyLink / SecondaryPhyLink | PhyLinkState | Primary / secondary port tri-state: Up=1 / Down=0 / Unknown=-1 |
| Redundancy operation | RedundancyActive | bool | Redundancy protection is running: RingMode>=1 (Dual/Degraded) and both ports carry frame traffic; always false for line / end-foldback topologies |
| Redundancy operation | RingMode | RingMode | Redundant ring operating mode |
| Redundancy operation | RunModeSemantics | RingRunModeSemantics | Tri-state projection of RingMode |
| Redundancy operation | RingModeUnread | bool | true = the ring mode value could not be read (older SDK / read failure) |
| Topology | TopologyState | TopologyModelState | Topology model form (the first criterion for form decisions) |
| Topology | TopologyKnown | bool | true = the model was computed successfully and the form is interpretable |
| Topology | TopologyUnavailableReason | string | Reason the model is unavailable; non-empty when TopologyKnown = false, safe to display directly |
| Topology | TopologyModeRaw | int | Raw form code of the static port model (0=line / 1=ring / 2=ring + branch); -1 = not obtained |
| Topology | RuntimeTopologyMode | int | Runtime form code: 0=line / 1=ring / 2=ring + branch / 3=ring degraded to line; -1 = not obtained |
| Derived | Shape | TruthLinkShape | Link form conclusion (see the enumeration table); Unknown when it cannot be decided |
SlaveTruthEntry
(Category: diagnostics; access: all read-only)
| Category | Property | Type | Description |
|---|---|---|---|
| Identity | SlaveIndex | int | Slave index (1-based) |
| State | SnapshotPending | bool | The placeholder row is still waiting for data to be filled in; after a successful read it turns false in the next cycle, with no permanent unknown |
| State | Liveness | SlaveLivenessState | Confirmed alive / confirmed offline / unknown |
| State | Probe | SlaveProbeState | Measured probe tri-state |
| State | Contribution | WcContribution | Process data contribution tri-state (Contributed / NotContributed / Unknown) |
| Topology | RingMembership | TopologyRingMembership | Whether the slave is on the redundancy ring (tri-state; unknown must not be treated as "not on the ring") |
| Verdict | Verdict | SlaveVerdict | Five-state display verdict (single decision source) |
| Verdict | Detail | SlaveVerdictDetail | Verdict detail (AL state / error flags / false OP flag) |
| AL | Status | EcSlaveStatus | Measured AL state (including the Error bit); meaningless when StatusUnread = true |
| AL | StatusUnread | bool | AL not sampled / read failed |
| AL | AlStatusCode | EcALState | Sampled AL status code (0 = no error code); meaningless when StatusUnread = true, and must not be treated as "no error" |
| Offline | OfflineReason | SlaveOfflineReason | Offline reason category for this slave right now: always RealOffline when the verdict is Offline; otherwise split by probe / contribution evidence (Unreachable = process data still contributed, Unknown = insufficient evidence); same scale as the SlaveOfflineDetailed event |
Related structure:
public readonly struct SlaveVerdictDetail
{
public SlaveVerdict Verdict { get; } // Five-state display verdict
public byte BaseState { get; } // AL base state low 4 bits (measured)
public bool HasError { get; } // AL error bit (0x10) is set
public bool NoPdMark { get; } // Fake-OP downgrade marker: no process data and not proven offline; shown in the tree with a "*" suffix
public bool RecoveryActive { get; } // A recovery ladder is active (display only, not part of the verdict)
}
NoPdMark expresses only one kind of degradation — "process data missing but offline not proven" — for tree display and diagnostic reads; it does not change Verdict, and it does not mean the slave is confirmed offline.
Enumerations
| Enumeration | Values | Meaning |
|---|---|---|
SlaveLivenessState | Unknown=0 / Alive=1 / Lost=2 | Insufficient evidence / confirmed process data contribution / offline verdict |
SlaveProbeState | NotResponding=0 / Responding=1 / Unknown=2 | Probe measured missing / measured responding / insufficient evidence |
TruthLinkShape | Unknown=0 / SingleLine=1 / RingDual=2 / RingDegraded=3 / TotalLost=4 | Undecidable / single line / bidirectional redundancy ring / redundancy degraded (ring open / partial ring + branch / single leg running) / both ports lost |
TruthAttribution | Unknown=0 / Healthy=1 / SlaveLost=2 / SlaveUnreachable=3 / NoProcessData=4 / WkcDeficit=5 / RedundancyCarry=6 | Insufficient evidence / healthy / a slave is confirmed offline / probe blind spot but process data still contributed / process data dead / WKC deficit / primary port 0 carried by the secondary port |
TopologyRingMembership | Unknown=0 / OnRing=1 / NotOnRing=2 | Model unavailable or does not contain this slave / on the ring / branch or line segment |
SlaveVerdict | Unknown=0 / RealOp=1 / OpNoProcessData=2 / Abnormal=3 / Offline=4 | Insufficient evidence / real OP / false OP / abnormal but not disconnected / offline |
Single-point mapping helpers (shared by events and the snapshot; never judge separately in two places):
| Member | Returns | Description |
|---|---|---|
MasterTruthSnapshot.ProbeStateOf(int rawProbe) | SlaveProbeState | Raw probe value 0/1/2 → tri-state; out-of-range values become Unknown and are never mapped to online |
MasterTruthSnapshot.ContributionOf(byte rawWcState) | WcContribution | 0x01 contributed / 0x00 not contributed / anything else unknown |
MasterTruthSnapshot.ContributionOf(bool? pdAliveConfirmed) | WcContribution | true / false / null → contribution tri-state |
MasterTruthSnapshot.ClassifyOfflineReason(SlaveProbeState, WcContribution) | SlaveOfflineReason | Process data still contributed → Unreachable; confirmed not contributed → RealOffline; contribution unknown and probe missing → RealOffline; otherwise Unknown |
Within one refresh cycle, all surfaces should share the object obtained from one Truth read. Reading Truth again assembles a new cycle (Sequence increments); different surfaces holding different sequence numbers are no longer looking at the same cycle.
Example:
var t = master.Diagnostics.Truth;
Console.WriteLine($"活 {t.AliveCount}/{t.SlaveCount}, 离线 {t.LostCount}, 未知 {t.UnknownCount}"); // alive {t.AliveCount}/{t.SlaveCount}, offline {t.LostCount}, unknown {t.UnknownCount}
Console.WriteLine($"WKC {t.WkcActual}/{t.WkcExpected}(主 {t.PrimaryWkc}/副 {t.SecondaryWkc})"); // WKC {t.WkcActual}/{t.WkcExpected} (primary {t.PrimaryWkc}/secondary {t.SecondaryWkc})
Console.WriteLine($"链路形态 {t.Link.Shape}, 归因 {t.Attribution} — {t.AttributionDetail}"); // Link shape {t.Link.Shape}, attribution {t.Attribution} — {t.AttributionDetail}
foreach (var row in t.Slaves)
{
if (row == null) continue;
if (row.Verdict == SlaveVerdict.Offline)
Console.WriteLine($"从站 {row.SlaveIndex}: 离线 ({row.OfflineReason}), 环成员={row.RingMembership}"); // Slave {row.SlaveIndex}: offline ({row.OfflineReason}), ring member={row.RingMembership}
}
Per-slave process data truth
| Category | Member | Type | Access | Description |
|---|---|---|---|---|
| Per-slave PD | master.Diagnostics.SlavePdAlive | int[] | Read-only | Raw contribution bits: 1 = confirmed contributing / 0 = not contributing / 2 = unknown. 1-based index, [0] is always 0. This is the positive-evidence scale for the offline red verdict; 0 must stay 0 |
| Per-slave PD | master.Diagnostics.SlavePdTruth | int[] | Read-only | Display scale: 1 = PD alive / 0 = PD dead / 2 = unknown. When the master level has not concluded "no process data", 0 is raised to 1 (so that no slave is marked as false OP), therefore it must not be used for the offline red verdict |
| Per-slave probe | master.Diagnostics.SlaveProbeAlive | int[] | Read-only | Probe tri-state encoding: 1 = online / 0 = missing / 2 = unknown |
| Verdict input | SlaveVerdictInput.PdAliveConfirmed | bool? | Read/write (filled by the caller) | Per-slave confirmed contribution raw bit; display / diagnostic input only, not part of the offline red verdict |
SlavePdTruth is the display scale for "is the PD of this slave dead" (with a fallback); SlavePdAlive is the positive-evidence scale for "is this slave still alive" (0 stays 0). Using the display scale for an offline decision means a really lost slave reads as "contributing" through the fallback, and the red verdict never fires.
Real OP verdict (RealOp)
"Reading OP from the AL state" is not the same as "this cycle really exchanges process data". The AL state can lag: after a slave drops out, the status word still reports OP while the merged WKC is already short, and looking only at the status word shows this case as "all OP".
RealOpTruth gives two layers of conclusions. They hold separately and cannot replace each other:
- Per-slave real OP — the AL state of the slave is OP, no error flag is set, and it is not judged offline.
- Master-level real OP — all required slaves (not optional and with process data configured) reach per-slave real OP, and the merged measured WKC is not below the fixed expectation from configuration time. All per-slave real OP verdicts holding does not necessarily mean the whole machine is in real OP.
Contributed (whether this cycle has a WKC contribution) and StableStreak (consecutive satisfied count) are used only for display and anti-flap; they are not part of the verdict. To judge real OP, read RealOp / Reason from this API group; do not build your own judgement from the AL status word.
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 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 | Access | Description |
|---|---|---|---|---|
| Diagnostics | master.Diagnostics.RealOpTruth | MasterRealOpTruth | Read-only | Captures one cycle; equivalent to CaptureRealOpTruth() |
| Diagnostics | master.Diagnostics.CaptureRealOpTruth() | MasterRealOpTruth | Read-only | Captures one cycle of real OP truth (master level + per slave) |
| Diagnostics | master.Diagnostics.EvaluateSlaveRealOp(slave) | SlaveRealOpState? | Read-only | Single-slave verdict; null = cannot evaluate, reported honestly as unknown |
| Diagnostics | master.Diagnostics.EvaluateRealOp(evidence, wkcActual, wkcExpected) | 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.
StableStreak is a display counter that advances with bus cycles (repeated reads within the same cycle do not accumulate); it is used only for display and anti-flap, not for the verdict.
Reason enumeration
| Value | Name | Meaning |
|---|---|---|
| 0 | Ok | Real OP: both the per-slave and master-level thresholds pass |
| 1 | AlNotClean | A required slave has not reached a clean OP (not OP, an error flag is set, or it is judged offline) |
| 2 | NoContribution | Historical reason code: no longer produced by the per-slave verdict (the value is kept for compatibility) |
| 3 | Unstable | Historical reason code: no longer produced by the per-slave verdict (the value is kept for compatibility) |
| 4 | WkcDeficit | Master level: all required slaves reach real OP, but the merged measured WKC is below the fixed expectation |
| 5 | Unknown | Insufficient evidence (verdict unavailable / no master context / no required slaves) |
Result structure
MasterRealOpTruth (category: diagnostics; access: read-only)
| Field | Type | Description |
|---|---|---|
| Sequence | long | Evaluation sequence number, monotonically increasing per master |
| RealOp | bool | Master-level real OP |
| Reason | RealOpReason | Main reason the master-level verdict does not hold |
| RequiredCount | int | Number of required slaves |
| RealOpCount | int | Number of required slaves in per-slave real OP |
| FailedCount | int | Number of required slaves that have not reached 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 | IReadOnlyList<SlaveRealOpState> | Per-slave results |
| DetailText | string | Readable detail (master conclusion + list of slaves that fell short + WKC comparison) |
SlaveRealOpState (category: diagnostics; access: read-only)
| Field | Type | Description |
|---|---|---|
| SlaveIndex | int | Slave index (1-based) |
| Required | bool | Whether it participates in the master-level verdict (not optional and has PDO) |
| AlCleanOp | bool | Whether the slave is currently in a clean OP (AL is OP, no error flag, not judged offline); the AL status code is not a criterion for this field |
| Contributed | bool | This cycle has a WKC contribution — display evidence only, not part of the verdict |
| StableStreak | int | Consecutive satisfied count at the display layer (anti-flap only, not part of the verdict; not a decision threshold) |
| RealOp | bool | The slave is in real OP |
| Reason | RealOpReason | Reason it does not hold (Ok when it is in real OP) |
| Detail | string | Readable reason detail (not part of the decision) |
Example:
var truth = master.Diagnostics.RealOpTruth;
if (truth.RealOp)
{
Console.WriteLine($"真 OP: 必需站 {truth.RealOpCount}/{truth.RequiredCount}, " + // Real OP: required slaves {truth.RealOpCount}/{truth.RequiredCount},
$"WKC {truth.WkcActual}/{truth.WkcExpected}");
}
else
{
Console.WriteLine($"非真 OP [{truth.Reason}] {truth.DetailText}"); // Not real OP [{truth.Reason}] {truth.DetailText}
foreach (var s in truth.Slaves)
if (s.Required && !s.RealOp)
Console.WriteLine($" 从站 {s.SlaveIndex}: {s.Reason} — {s.Detail}"); // slave {s.SlaveIndex}: {s.Reason} — {s.Detail}
}
Topology rebuild and hot-plug
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). Healthy OP slaves receive no state-change command and the PDO cycle keeps running. The application needs no rebuild entry point - and none is public.
Cases that are not handled automatically (the master reports them truthfully and the operator re-scans after fixing them):
- A module inserted mid-chain that shifts the physical positions of the modules after it: the master sees that the candidate position's STADR belongs to another slot, stops the automatic discover and asks for a re-scan; it never steals another slot's address.
- An extra device not declared in DENI: no mapping, no group, no OP.
- An identity that does not match the declaration (wrong model / old firmware): hard refusal until the correct device is fitted.
- Ambiguous ownership (several slots of the same model / several stations with the same ident): no guessing.
RefreshTopology()
public void RefreshTopology()
After the wiring has been explicitly changed on site (for example chain end fold-back to a true ring), force one fresh port-topology read: rescan the ports (FPRD), rebuild the topology graph and recompute the per-path expected WKC (PrimaryExpectedWKC / SecondaryExpectedWKC) from the current physical port graph. It does not restart the bus, change slave states or reconfigure PDO.
It recomputes the expected baseline against the current port graph (allow_relock). Calling it after unplugging a branch deliberately shrinks the expectation to the current topology: that is the user declaring a new topology, the exact opposite of what the automatic path does. R1 requires expected_wkc to stay fixed from configuration time and a missing station to be reported truthfully, never silently absorbed by lowering the expectation.
Example:
master.Diagnostics.RefreshTopology();
Console.WriteLine($"刷新后期望 WKC: 主 {master.Diagnostics.PrimaryExpectedWKC}, 副 {master.Diagnostics.SecondaryExpectedWKC}"); // Expected WKC after refresh: primary {master.Diagnostics.PrimaryExpectedWKC}, secondary {master.Diagnostics.SecondaryExpectedWKC}
Automatic hot-plug (no call needed)
Hot-plug is handled inside the master; the application only reads the result. Each real automatic rebuild records one accounting entry:
public int HotSwapRescanCount { get; } // completed rounds
public int LastHotSwapRescanResult { get; } // last result code
public DateTime LastHotSwapRescanTime { get; } // last completion time (UTC)
0success;-20another rebuild is in progress;-21the rescan found 0 reachable slaves (R0: do not blame the link);-23slaves present but not in OP;-25resources exhausted; gates-1/-6.
Example:
var diag = master.Diagnostics;
Console.WriteLine($"自动重建 {diag.HotSwapRescanCount} 轮,上次结果 {diag.LastHotSwapRescanResult},时刻 {diag.LastHotSwapRescanTime:O}"); // Auto-rebuild {diag.HotSwapRescanCount} rounds, last result {diag.LastHotSwapRescanResult}, at {diag.LastHotSwapRescanTime:O}
After the kernel appends a new station, it appears in master.Slaves within one polling beat and existing Slave object references stay unchanged - no disconnect to connect needed. The managed table refresh only reads the accounting above (it probes the table only when the count advances), so steady-state cost is zero extra native reads.
master.RebuildTopology()
public void RebuildTopology()
Rebuilds only the slave topology view (refreshes the parent-child port relation cache): it does not rescan the bus, does not touch slave states and does not change the expected WKC. Use it when the slave list has changed and the topology tree must align with the current list; when the per-path expected WKC must be recomputed as well, use master.Diagnostics.RefreshTopology() above.
Example:
master.AcknowledgeSlaveReplacement(3);
master.RebuildTopology();
master.TopologyMismatchMessage
public string TopologyMismatchMessage { get; }
Mismatch information found by the most recent topology check (filled in by the SDK when the ENI topology and the measured topology differ), usually appended to the tail of the Build() success message.
Example:
if (!string.IsNullOrEmpty(master.TopologyMismatchMessage))
Console.WriteLine(master.TopologyMismatchMessage);
Link observation
| Member | Returns | Description |
|---|---|---|
PrimaryPhyLinkState / SecondaryPhyLinkState | PhyLinkState | Physical link of the primary / secondary port: Up=1, Down=0, Unknown=-1. When it cannot be read it is Unknown and is never treated as Up |
SecondaryFrameLinkState | PhyLinkState | Frame-level link tri-state of the secondary port; use it separately from the physical link reading |
PhyLinkBitMask | uint | Bitmap of both ports: bit0 = primary Up, bit1 = secondary Up; 0xFFFF = not observable. Check for 0xFFFF before using the bits |
Unknown only means the value cannot be read or has not been decided yet (no data, older SDK, frame-level link has no result yet); it does not equal Down: do not report a broken link, a lost slave or fault handling from it. Only an explicit Down is a broken link.
var diag = master.Diagnostics;
if (diag.PrimaryPhyLinkState == PhyLinkState.Down)
Console.WriteLine("主口明确 Down"); // Primary port explicitly Down
else if (diag.PrimaryPhyLinkState == PhyLinkState.Unknown)
Console.WriteLine("主口状态未知"); // Primary port state unknown
PrimaryPhyLinkUp / SecondaryPhyLinkUp are compatibility boolean health checks: they return true only for an explicit Up, and false for both Down and Unknown. Read the tri-state properties when you need to tell the latter two apart.
P1 foldback topology
Read-only query of the P1 foldback topology calibration result and slave reachability. Master-level properties are read from master.Diagnostics (MasterDiagnosticsInfo); slave-level properties are read from master.Slaves[n] (the list is 0-based, Slaves[0] is slave 1).
| Category | Property | Returns | Access | Description |
|---|---|---|---|---|
| Foldback topology | TopoP1FoldbackMode | int | Read-only | 0=NONE (no foldback needed or not calibrated in this cycle), 1=SINGLE_NIC (single NIC, no foldback window), 2=DUAL_RING_BRANCH (dual NIC ring + branch, foldback required); -1 = invalid master index |
| Foldback topology | TopoP1Mode | int | Read-only | Compatibility alias of TopoP1FoldbackMode, with exactly the same values and semantics |
| Foldback topology | TopoP1Measured | int | Read-only | 1 = on-site topology was measured in this cycle; 0 = not measured in this cycle; -1 = invalid master index |
| Foldback topology | TopoP1RingEndAdp | int | Read-only | Slave address of the foldback position; -1 = unavailable (not calibrated / not dual NIC ring + branch / invalid index) |
| Foldback topology | TopoP1FullWkc | int | Read-only | Measured full WKC at that foldback position; -1 = same as above |
| Foldback topology | TopoMeasuredRingCount | int | Read-only | Measured number of slaves on the ring; branch count = TopoP1FullWkc - this value; -1 = same as above |
| Slave level | master.Slaves[n].P1FoldbackOnly | int | Read-only | 1 = the slave is reachable only through the foldback window; when set, addressing its position requires opening the foldback window first (such slaves have an index above the measured ring count); 0 = not a branch slave / property not calibrated; -1 = invalid master index or slave index |
All members are read-only queries and change no state. -1 only means unavailable / not calibrated / invalid parameter (master index or slave index out of range, master released); it is not a measurement, so treat it as "cannot read". 0 is a real measurement, not a failure: TopoP1FoldbackMode returning 0 means NONE, TopoP1Measured returning 0 means no on-site topology measurement in this cycle, and TopoMeasuredRingCount returning 0 means the measurement found 0 slaves; do not treat 0 as an error.
Example:
var diag = master.Diagnostics;
// TopoP1FoldbackMode: 0=NONE, 1=SINGLE_NIC, 2=DUAL_RING_BRANCH; -1 = cannot read
int mode = diag.TopoP1FoldbackMode;
if (mode == -1)
Console.WriteLine("P1 拓扑模式不可用(主站索引非法 / 主站已释放)"); // P1 topology mode unavailable (invalid master index / master already released)
else
Console.WriteLine($"P1 拓扑模式: {mode}"); // P1 topology mode: {mode}
// TopoP1Measured: 1=measured in this cycle, 0=not measured; -1 = cannot read
int measured = diag.TopoP1Measured;
Console.WriteLine($"实测状态: {(measured == -1 ? "不可用" : measured == 1 ? "已实测" : "未实测")}"); // Measured status: {(measured == -1 ? "unavailable" : measured == 1 ? "measured" : "not measured")}
// The next 3 values are meaningful only when this cycle was measured; -1 = cannot read (not calibrated / not dual NIC ring + branch / invalid index)
int ringEndAdp = diag.TopoP1RingEndAdp; // foldback position slave address (ADP)
int fullWkc = diag.TopoP1FullWkc; // measured full WKC at the foldback position
int ringCount = diag.TopoMeasuredRingCount; // measured slaves on the ring; 0 = measured as 0 (not a failure)
int branchCount = (fullWkc >= 0 && ringCount >= 0) ? (fullWkc - ringCount) : -1;
if (ringEndAdp != -1 && fullWkc != -1 && ringCount != -1)
{
Console.WriteLine($"ring-end: ADP={ringEndAdp}, 满 WKC={fullWkc}"); // ring-end: ADP={ringEndAdp}, full WKC={fullWkc}
Console.WriteLine($"环上 {ringCount} 站, 分支 {branchCount} 站"); // {ringCount} slaves on the ring, {branchCount} on branches
}
// Per-slave reachability: slaves with an index above the measured ring count are reachable only through the foldback window
// Slaves is a 0-based list: index 0 = slave 1
if (master.Slaves.Count > 0)
{
var slave1 = master.Slaves[0];
int foldbackOnly = slave1.P1FoldbackOnly; // 1 = reachable only through the foldback window, 0 = not a branch slave / not calibrated, -1 = cannot read
if (foldbackOnly == 1)
Console.WriteLine($"从站 {slave1.SlaveNum} 只能经折返窗口可达——对它的位置寻址需要先打开折返窗口"); // Slave {slave1.SlaveNum} is reachable only through the fold-back window — positional addressing of it requires opening the fold-back window first
else if (foldbackOnly == -1)
Console.WriteLine($"从站 {slave1.SlaveNum} 折返属性不可用(站号越界 / 主站已释放)"); // Slave {slave1.SlaveNum} fold-back property unavailable (slave index out of range / master already released)
}
DC synchronization
Automatic monitoring (ETG.1500 5.13.3) checks the time deviation of each slave every second. Exceeding the SyncWindowThreshold threshold triggers the DCSyncLost event.
For the synchronization state of an individual slave use slave.Diagnostics.DC.IsInSync and slave.Diagnostics.DC.SyncTimeDifference.
DC diagnostics 2-second snapshot
master.DcDiagnostics and master.Diagnostics.DcDiagnostics return the same object (one 2-second TTL cache). All consumers within the same 2 seconds share one instance, so screens no longer split into a different reading per column. Everything read is diagnostic data already available locally and generates no bus frames; historical fields (frozen reading, jitter, convergence) accumulate on the 2-second sampling surface.
| Member | Type | Category | Access | Unavailable indication | Description |
|---|---|---|---|---|---|
MasterIndex | ushort | DC diagnostics | Read-only | — | Master index |
CapturedAtUtc | DateTime | DC diagnostics | Read-only | — | Assembly time of this cycle (UTC) |
HasDc | bool | DC diagnostics | Read-only | with HasDcKnown | Whether the network has slaves with DC capability (capability bit scale) |
HasDcKnown | bool | DC diagnostics | Read-only | — | false = slave enumeration / capability read failed; HasDc = false then does not mean "the bus really has no DC slaves" |
AllInSync | bool? | DC diagnostics | Read-only | null = no confirmed participants (not true) | Whether all SYNC0 participants are inside the synchronization window; participants exist but were not sampled / cannot be read → false; any DC slave with an unknown armed state → conservatively false |
MaxDriftNs | int? | DC diagnostics | Read-only | null = no usable window (not 0) | Maximum absolute synchronization difference among all usable windows (ns); the reference clock itself is not counted |
SyncWindowThresholdNs | int? | DC diagnostics | Read-only | null = cannot read | Synchronization window threshold (ns) |
ReferenceClock | DcReferenceClockInfo | DC diagnostics | Read-only | explicit None instance / Tier = Unknown | Reference clock facts: SlaveIndex (0 = none), Tier, TierText, IsChainHeadFallback, Known |
ArmedSlaveCount | int | DC diagnostics | Read-only | 0 is a valid count | Number of slaves with Sync0Armed == true |
ActiveSlaveCount | int | DC diagnostics | Read-only | 0 is a valid count | Number of slaves with DC in effect |
ArmedUnknownCount | int | DC diagnostics | Read-only | 0 is a valid count | Number of slaves with an unknown armed verdict |
ArmedSyncParticipantCount | int | DC diagnostics | Read-only | 0 = no slave on which a synchronization conclusion can be drawn | Number of participant slaves that are armed and are not the reference clock |
ApplicableWindowCount | int | DC diagnostics | Read-only | 0 = MaxDriftNs is null | Number of slaves with a usable measured window |
ActiveWithoutProcessDataCount | int | DC diagnostics | Read-only | 0 is a valid count | Number of slaves with DC in effect but without process data bytes |
ExpectedWkc | ushort | DC diagnostics | Read-only | — | Master expected WKC (fixed value from configuration time); compare it with ArmedSlaveCount to see the WKC coverage of DC slaves |
PropagationDelayResolvedAtUtc | DateTime? | DC diagnostics | Read-only | null = not observed by this process | Time of the most recent successful propagation delay resolution actively triggered by the SDK; not the same as the physical measurement time |
PropagationDelayResolveCount | int | DC diagnostics | Read-only | 0 = not observed | Number of successes on the same accounting scale |
Slaves / Find(index) | DcSlaveSnapshot[] / DcSlaveSnapshot? | DC diagnostics | Read-only | Find out of range / not sampled → null | Per-slave snapshot (ascending by slave index); Find is an O(1) lookup |
AnyReadFailure | bool | DC diagnostics | Read-only | — | At least one slave / the reference clock failed to read in this cycle; failed items are already reported as Unknown / null |
The master object also exposes direct entry points that read the same snapshot: master.DcArmedSlaveCount, master.DcActiveSlaveCount; the reference clock and the threshold have direct entry points too: master.DcReferenceClock / master.DcSyncWindowThresholdNs / master.ReferenceClockSlaveIndex (another reading surface for the same facts).
The elements of the Slaves array are DcSlaveSnapshot; inside the snapshot they also carry SlaveIndex, Name, ShiftNs (phase offset), OutputBytes / InputBytes, IsDcActive, IsReferenceClock, ConvergenceMeasuredAtUtc.
DcDiagnostics reuses the same result for 2 seconds and does not trigger a bus read, so it can be read on the UI thread. When you need a tri-state conclusion (AllInSync / MaxDriftNs / Sync0Armed), always read the snapshot; do not fall back to legacy summary properties such as Diagnostics.DcAllInSync (bool) or Diagnostics.DcMaxDriftNs (int).
Redundancy status
RingMode reflects the operating state of ring-topology redundancy. Inactive means redundancy is not initialized, Dual means bidirectional redundancy works normally, and Degraded means the secondary link is unavailable and only the primary works.
RedundancyActive means "redundancy protection is running", not "both ports carry frames"RedundancyActive = RingMode is Dual or Degraded 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 RingMode == Inactive.
To see "whether both ports carry frames", read PrimaryPortTx / PrimaryPortRx / SecondaryPortTx / SecondaryPortRx, or PrimaryPortOk / SecondaryPortOk; do not infer it from this property. slave.Diagnostics.RedundancyActivated is the same master-level criterion (RingMode >= 1), not an independent per-slave conclusion.
BreakPoint detects two kinds of physical fault in one place:
| Type | FaultType | Detection | Typical scenario |
|---|---|---|---|
| Link break | 0 | Port physical link lost | Cable unplugged, cable broken |
| CRC fault | 1 | Port error count keeps rising | Poor contact, aged cable, oxidized connector |
null does not mean "no fault"BreakPoint has a single return value, and both a failed query (read failure / diagnostic channel unavailable / exception) and a genuine absence of faults return null. To tell them apart use:
TryGetBreakPoint(out BreakPointInfo bp, out bool queryOk):queryOk = truemeans the query succeeded, and only then does afalsereturn mean "genuinely no fault";queryOk = false= query failed, the fault state is unknown.GetAllBreakPoints():null= query failed; an empty array = query succeeded and there is 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.
RingMode enumeration
| Value | Name | Description |
|---|---|---|
| -1 | Unknown | Unknown: unreadable / out-of-range value; must not be folded into Inactive |
| 0 | Inactive | Not active: redundancy monitoring is not initialized |
| 1 | Dual | Bidirectional redundancy: both ports transmit, normal operation |
| 2 | Degraded | Degraded mode: the secondary link is unavailable, only the primary works |
BreakPointInfo structure
| Category | Property | Type | Access | Description |
|---|---|---|---|---|
| Fault location | SlaveIndex | ushort | Read-only | Faulty slave index (1-based) |
| Port | byte | Read-only | Faulty port number (0-3, corresponding to P0-P3) | |
| FaultType | byte | Read-only | Fault type: 0 = link break, 1 = CRC fault | |
| IsLinkDown | bool | Read-only | Whether it is a link break fault | |
| IsCrcFault | bool | Read-only | Whether it is a CRC fault (cable / connector degradation) |
Example:
var diag = master.Diagnostics;
// Ring topology redundancy mode
Console.WriteLine($"冗余模式: {diag.RedundancyRingMode}"); // Redundancy mode: {diag.RedundancyRingMode}
if (diag.RedundancyRingMode == RingMode.Degraded)
Console.WriteLine("警告: secondary链路不可用,仅primary工作"); // Warning: secondary link unavailable, only primary is working
if (diag.RedundancyActive)
Console.WriteLine("冗余已激活"); // Redundancy activated
var bp = diag.BreakPoint;
if (bp != null)
{
Console.WriteLine($"故障: {bp}"); // output: "slave 5 P3 link down" or "slave 3 P1 CRC fault"
if (bp.Value.IsCrcFault)
Console.WriteLine("建议检查线缆/连接器"); // Recommend checking the cable/connector
}
Topology model and link semantics
RingMode is the runtime state, and it lumps "line / not initialized / cannot read" into one Inactive; on its own it cannot distinguish a pure line, a fully open ring, or a partial ring with several branches. Judging "is there a protection path, which slaves are on the ring" requires the topology model; "a second NIC is configured", "both ports are linked" and "RedundancyActive" are not topology criteria.
The system has two models; do not mix them:
| Model | Data source | Values | Purpose |
|---|---|---|---|
| Static port model | Computed uniformly by the SDK; the legacy interface stays compatible | Form code 0=line / 1=ring / 2=ring + branch; the "no ring" form is further split by TopologyModel.ChainForm (public enumeration TopologyChainForm) | "ring covers 0 slaves / some slaves / all slaves", per-slave ring membership |
| Runtime form model | RuntimeTopologyMode | 0 / 1 / 2, plus 3 = ring degraded to line | Captures "the configuration has a ring and it is open right now" |
MasterDiagnosticsInfo.TopologyModel
public DarraEtherCAT.SlaveTopology.RingBranchInfo TopologyModel { get; }
The only reading surface for the static port model (the result is reused for 2 seconds, so UI refreshes do not recompute it repeatedly). The return value is never null: when it cannot be obtained you get an instance with State = Unknown and a non-empty UnavailableReason.
RingBranchInfo (category: topology; access: read-only):
| Category | Member | Type | Description |
|---|---|---|---|
| Scale | TotalCount | int | Total number of slaves in the model |
| Scale | RingCount | int | Number of ring members; usable only when ModelKnown = true |
| Scale | BranchCount | int | Branch count = TotalCount - RingCount; likewise usable only when ModelKnown |
| Form | State | TopologyModelState | Form after the strict mapping; unrecognized values → Unknown |
| Form | Mode | string | Readable form: "line" / "ring" / "ring + branch" / "unknown" |
| Form | ModeRaw | int | Raw form code (0=line / 1=ring / 2=ring + branch); -1 = not obtained |
| Form | ModelKnown | bool | Whether the SDK computed the model successfully; when false all ring membership fields below are unusable |
| Form | UnavailableReason | string | Reason the model is unavailable; non-empty when ModelKnown = false, safe to display directly |
| Form | ChainForm | TopologyChainForm | "No ring" form split: Linear (pure line) / Foldback (chain (end foldback)) / Unknown (not applicable). Trustworthy only when State == Linear; ring / ring + branch / unknown model are always Unknown, which is not "line". The value comes from the SDK topology model; this property does no second derivation |
| Closure | ClosureSlaveNum | int | Slave index of the closure point; -1 = no closure point. It is also -1 when the model is unknown, but that means "unknown", not "line", so check ModelKnown first |
| Per slave | RingSlaveNums | HashSet<int> | Set of slave indices that are ring members |
| Per slave | IsRing(int) | bool | true = on the ring. Returns false when the model is unknown, which only means "unknown", not "not on the ring" |
| Per slave | RingMembershipKnown | bool | Whether the ring member list is trustworthy (model known and form interpretable) |
| Per slave | TryIsRing(int, out bool) | bool | Tri-state decision: a false return = this model does not know; when it returns true the out parameter gives the truth |
RuntimeTopologyMode
public int RuntimeTopologyMode { get; } // MasterDiagnosticsInfo
Raw runtime form value: 0=line / 1=ring / 2=ring + branch / 3=ring degraded to line / -1=cannot read. Out-of-range values are returned unchanged for the caller to label honestly as "unrecognized". 3 means "the ring still exists, it is just open" and must not be reported as a pure line.
TopologyModelState
(Category: topology; enumeration)
| Value | Name | Meaning |
|---|---|---|
| 0 | Unknown | Model not computed / SDK unavailable / mode outside the contract — unknown, no guessing |
| 1 | Linear | Line (no closure point, the ring covers 0 slaves) |
| 2 | Ring | Ring (the ring covers all slaves) |
| 3 | RingBranch | Ring + branch (the ring covers some slaves; branch count in BranchCount) |
TopologyChainForm
(Category: topology; enumeration)
The split of the "no ring" form made by the static port model. The value comes from the SDK topology model; this property only translates the enumeration and makes no derivation.
| Value | Name | Meaning |
|---|---|---|
| 0 | Unknown | Not applicable — ring / ring + branch / unknown model / SDK unavailable / out-of-range value. Not "line" |
| 1 | Linear | Pure line: all slaves in series, the end is one active port with no foldback |
| 2 | Foldback | Chain (end foldback): the end folds back inside a single port, the primary port sends and the secondary port receives, there is only one physical path end to end, no redundancy protection |
This split is meaningful only when the topology form is line; under ring / ring + branch the raw value is fixed at 0, and that 0 does not mean line. This SDK therefore reports Linear / Foldback only when State == TopologyModelState.Linear; all other forms report Unknown (not applicable), and out-of-range values also report Unknown with the reason written to UnavailableReason.
The enumeration values and the raw form codes are not the same numbering: do not compare the values of Linear / Foldback / Unknown directly with raw form codes.
Both forms are "no ring", and Linear and Foldback are identical field by field in RingCount / BranchCount / ClosureSlaveNum; only ChainForm tells them apart. Although Foldback has a single continuous physical path, it has no second return line, so any break in a chain segment disconnects everything downstream — do not treat the no-ring split as the only criterion for "is there redundancy"; redundancy protection still follows IsRedundancyProtected / State.
The legacy topology query interface and result structure stay compatible; use the current TopologyModel interface when you need to read ChainForm.
Per-slave reachable legs / liveness reason / clean OP / SYNC0 armed
This group is read-only query; the public entry points for SDK users are in the table below.
| Category | Entry point | Type | Access | Description |
|---|---|---|---|---|
| Topology | slave.TryGetReachableLegs(slaveNum, out ReachableLegs legs) | public C# projection | Read-only | Per-slave reachable legs. A false return = no conclusion this time (master released / slave index out of range / topology model unavailable / reachability unknown). slave.ProtectionState (SlavePathProtection) is derived from the same entry point |
| Diagnostics | MasterTruthSnapshot.TryReadNativeOfflineReason(master, slave, out int nativeReason) | public static method | Read-only | Returns the query status code; nativeReason is an SDK internal reason code (0..7). For normal display use SlaveTruthEntry.OfflineReason (SlaveOfflineReason, three values); the raw value is for logs and diagnostics only |
| Diagnostics | master.Diagnostics.RealOpTruth / CaptureRealOpTruth() | MasterRealOpTruth | Read-only | Verdict results for clean OP and real OP |
| Diagnostics | slave.Sync0Armed (bool?, null = cannot decide) | public property | Read-only | Per-slave SYNC0 armed verdict; null means the interface is unavailable or the data is not ready, and must not be collapsed to false. slave.Diagnostics.DC.IsInSync (bool) and slave.GetSyncWindowStatus() consume the same conclusion |
- When a query has no conclusion, output parameters keep the value they had before the call. The caller must check the return value first, must not reuse an old value as this call's conclusion, and must not read a pre-cleared 0 as "the result of this query".
ReachableLegs.Unknownnever equals "neither leg can reach": it means "insufficient evidence to prove which leg can reach"; the fail-safe behaviour = no re-routing, no duplicate transmission.- Topology model not ready ≠ not armed / no ring / not in a clean state; it means "there are no facts to decide on".
Reachable legs: ReachableLegs values
| Value | Name | Meaning |
|---|---|---|
| 0 | Unknown | Insufficient evidence to prove which leg can reach — not "neither leg can reach"; fail-safe treats it as no re-routing / no duplicate transmission |
| 1 | PrimaryOnly | Reachable through the primary leg only |
| 2 | SecondaryOnly | Reachable through the secondary leg only |
| 3 | Both | Reachable through both legs = a ring member of a genuine closed loop |
Passing slaveNum 0 means the master slot (no leg semantics, returns Unknown); each per-slave conclusion is self-consistent, but conclusions across slaves are not guaranteed to come from the same publish.
Lost slave reason
For the per-slave lost reason use SlaveTruthEntry.OfflineReason (SlaveOfflineReason: Unknown / RealOffline / Unreachable). The raw internal reason codes are for logs and diagnostics only and are not part of the public contract; their per-value semantics are not promised.
Clean OP and display consecutive count
The per-slave clean OP follows SlaveRealOpState.AlCleanOp; for the real OP conclusion see Real OP verdict (RealOp). StableStreak is only a display-layer anti-flap count and is not part of the verdict; this page promises no internal decision threshold or counter value.
SYNC0 armed
Read-only: it modifies no state.
armedonly means the slave promises to generate SYNC0 (the configuration is in place); it does not mean the network clock has converged — for that see the synchronization window /IsInSync.- When DC is not in effect (FreeRun / not yet configured / degraded)
armed= 0, which is a normal conclusion, not an error.
Example:
// Reachable legs: public projection; false = no conclusion this time, not "neither leg can reach"
if (slave.TryGetReachableLegs(slave.SlaveNum, out ReachableLegs legs))
Console.WriteLine($"从站 {slave.SlaveNum} 可达腿: {legs}"); // Slave {slave.SlaveNum} reachable legs: {legs}
else
Console.WriteLine($"从站 {slave.SlaveNum} 可达腿: 未证(模型未就绪 / 证据不足)"); // Slave {slave.SlaveNum} reachable legs: not proven (model not ready / insufficient evidence)
// Lost slave reason: the reason code is meaningful only when the return code is 0; for normal display read the three-value OfflineReason
int rc = MasterTruthSnapshot.TryReadNativeOfflineReason(
master.MasterNumber, slave.SlaveNum, out int nativeReason);
if (rc == 0)
Console.WriteLine($"掉站原因码 {nativeReason}: " + // Slave loss reason code {nativeReason}:
MasterTruthSnapshot.DescribeNativeOfflineReason(nativeReason));
// AL-OP verdict / real OP: AlCleanOp is the verdict, StableStreak is display anti-flap only
var truth = master.Diagnostics.RealOpTruth;
foreach (var row in truth.Slaves)
Console.WriteLine($"从站 {row.SlaveIndex}: 干净OP={row.AlCleanOp}, " + // Slave {row.SlaveIndex}: cleanOP={row.AlCleanOp},
$"真OP={row.RealOp}, 展示连击={row.StableStreak}"); // realOP={row.RealOp}, display streak={row.StableStreak}
// SYNC0 armed verdict: slave.Sync0Armed is tri-state; null must not be collapsed to false
bool? armed = slave.Sync0Armed;
if (armed == null)
Console.WriteLine("SYNC0 武装结论未知(接口不可用或数据未就绪)"); // SYNC0 arm status unknown (interface unavailable or data not ready)
else
Console.WriteLine($"SYNC0 已武装: {armed.Value}"); // SYNC0 armed: {armed.Value}
var window = slave.GetSyncWindowStatus();
if (window == null)
Console.WriteLine("同步窗口结论未知"); // Sync window conclusion unknown
else
Console.WriteLine($"SYNC0 已武装且实测在窗: {window.Value.InSync}"); // SYNC0 armed and measured in window: {window.Value.InSync}
RingRunModeSemantics
Read-only tri-state projection of RingMode that separates "not calibrated" from "confirmed no ring / line". It does not change the values / ordinals / serialization layout of RingMode.
| Value | Name | Meaning |
|---|---|---|
| 0 | Uncalibrated | Monitoring not initialized / not running; you can say neither "redundant" nor "line" |
| 1 | RedundantRunning | Dual-path redundancy confirmed running |
| 2 | Degraded | The ring exists but only one leg is running |
| 3 | Unreadable | Cannot read / unrecognized (older SDK / out-of-range value) |
public static RingRunModeSemantics ToSemantics(this RingMode mode, bool unread)
Single mapping point: unread: true is always Unreadable; out-of-range enumeration values are likewise Unreadable ("unrecognized" does not equal "not calibrated").
DarraEtherCAT.SecondaryLinkRole
public SecondaryLinkRole SecondaryLinkRole { get; } // on master
The role of the secondary port in the topology — decided by the topology model, not by an existence criterion such as "a second NIC is configured".
| Value | Name | Meaning |
|---|---|---|
| 0 | Unknown | Model unavailable / not calibrated / read failed — unknown whether the secondary port carries a protection path |
| 1 | NoProtectionPath | The model confirms there is no protection path (line / single NIC / ring covers 0 slaves) |
| 2 | ProtectionPath | The model confirms a ring or ring + branch, and the secondary port is part of the protection path |
The property is decided by the topology model: ProtectionPath when the model confirms a protection path exists, NoProtectionPath when it confirms none, and Unknown when the model is unavailable / not calibrated. A read failure is treated as Unknown and never collapsed into "redundant" or "not redundant".
Per-slave ring membership and outer projection
- Snapshot per-slave rows use
SlaveTruthEntry.RingMembership(TopologyRingMembershiptri-state). - The slave-level link protection form uses
slave.ProtectionState(SlavePathProtection), and reachable legs useslave.TryGetReachableLegs()(ReachableLegs).
Example:
var model = master.Diagnostics.TopologyModel;
if (!model.ModelKnown)
{
Console.WriteLine($"拓扑模型不可用: {model.UnavailableReason}"); // Topology model unavailable: {model.UnavailableReason}
}
else
{
Console.WriteLine($"{model.Mode}: 环上 {model.RingCount} 站, 分支 {model.BranchCount} 站, " + // {model.Mode}: {model.RingCount} slaves on the ring, {model.BranchCount} on branches,
$"闭合点 #{model.ClosureSlaveNum}"); // closure point #{model.ClosureSlaveNum}
foreach (var s in master.Slaves)
if (model.TryIsRing(s.SlaveNum, out bool onRing) && onRing)
Console.WriteLine($"从站 {s.SlaveNum} 在环上(双路径)"); // Slave {s.SlaveNum} is on the ring (dual path)
}
Console.WriteLine($"副口角色: {master.SecondaryLinkRole}"); // Secondary port role: {master.SecondaryLinkRole}
Console.WriteLine($"运行形态: {master.Diagnostics.RuntimeTopologyMode}"); // Runtime topology: {master.Diagnostics.RuntimeTopologyMode}
Cycle run state
Read-only. It answers "is the cycle actually running" and keeps the three meanings "not started / started but not advancing / really running at 0 Hz" apart instead of covering them with a single 0.
| Category | Property | Type | Access | Description |
|---|---|---|---|---|
| Cycle and jitter | BusCycleReadState | DiagnosticsReadState | Read-only | Read state of the bus frequency window: NotReady = no sample taken yet / Ready = a real frequency has been sampled / Error = the most recent read failed. When the frequency reads 0, check this item before drawing a conclusion |
| Cycle and jitter | CycleState | CycleRunState | Read-only | Tri-state of the cycle counter. When the frame rate, the cycle time and the bus frequency are all 0, only this item tells "not started", "started but not advancing" and "advancing normally" apart |
| Cycle and jitter | HasBusCycleSample | bool | Read-only | Whether a real cycle sample has been taken (frequency above 0, or round-trip delay above 0.5 µs). false = not sampled yet; do not treat it as "the cycle is healthy" |
| Cycle and jitter | CyclicLostFrameCount | uint | Read-only | Cumulative number of lost cyclic frames, on the ETG.1510 0xF120:01 Cyclic Lost Frames scale. It is a cumulative count, not a packet loss percentage, and it is not truncated by an integer. 0 while the bus has not started |
| Runtime | IsWdkMapped | bool | Read-only | Whether the diagnostics channel of the real-time runtime is ready to read. true only means the master is initialized and the channel is readable; it does not mean cycles are being sampled, and it never fabricates a frequency |
| Runtime | LastDiagnosticsReadError | string | Read-only | Details of the most recent failed diagnostic read (operation name + exception type + message + first 500 characters of the stack); null when it has never failed. Logging is rate-limited per operation; this property updates on every failure |
| Runtime | WindowsProcessorPerformance | WindowsProcessorPerformanceSnapshot | Read-only | Per-logical-processor DPC / interrupt / Idle / Kernel / User time delta snapshot. The first read only establishes a baseline and returns BaselinePending; read it again after the observation interval |
DiagnosticsReadState enumeration
| Value | Name | Meaning |
|---|---|---|
| 0 | NotReady | No usable frequency window sample has been taken yet |
| 1 | Ready | A real frequency has been sampled and can be used to judge the cycle |
| 2 | Error | The most recent read failed; the value cannot be used as a criterion |
CycleRunState enumeration
| Value | Name | Meaning |
|---|---|---|
| 0 | NotStarted | The cycle runtime is not established (after stop / pause); a count of 0 is truthful |
| 1 | StartedNoAdvance | The runtime is established but the count did not move within the observation window (stuck, or the cycle stopped advancing) |
| 2 | Advancing | The count really was growing within the most recent window |
WindowsProcessorPerformanceSnapshot structure
| Field | Type | Description |
|---|---|---|
| Available | bool | Whether a usable delta interval was obtained this time. When false you must read Error; never interpret missing data as 0 |
| Error | WindowsProcessorPerformanceError | Reason it is unavailable (0 = none / 1 = baseline pending / 2 = platform not supported / 3 = architecture not supported / 4 = record layout mismatch / 5 = query failed / 6 to 15 = specific failures such as buffer, processor count, counters, timestamp, overflow, allocation) |
| ErrorDetail | string | Readable detail of the unavailable reason; null when available |
| Elapsed | TimeSpan? | Length of the observation interval between the two reads; null when unavailable |
| Processors | IReadOnlyList | Set of delta samples per logical processor; an empty set when unavailable — partial values are never returned |
| ProcessorCount | int | Number of samples |
TryGetBusCycleHz(out uint hz)
public bool TryGetBusCycleHz(out uint hz)
Reads the complete frequency window. 0 Hz no longer passes itself off as "a valid sampled value"; to tell stopped from never started, read CycleState.
Parameters:
hz(out uint) — on success, receives the bus frequency (Hz); stays 0 on failure
Return value:
bool— true = a usable frequency was obtained; false = not ready / not advancing / read error
Example:
if (master.Diagnostics.TryGetBusCycleHz(out uint hz))
Console.WriteLine($"总线频率: {hz} Hz"); // Bus frequency: {hz} Hz
else
Console.WriteLine($"无可用频率,周期状态: {master.Diagnostics.CycleState}"); // No usable frequency, cycle state: {master.Diagnostics.CycleState}
Real-time runtime counters
Transmit, receive and scheduling counters accumulated per cycle by the real-time runtime. A read generates no bus frames; the value you get is the current value.
| Category | Property | Type | Access | Description |
|---|---|---|---|---|
| Network and link | WdkPrimaryFrameTx | uint | Read-only | Cumulative frames sent on the primary port |
| Network and link | WdkPrimaryFrameRx | uint | Read-only | Cumulative frames received on the primary port |
| Network and link | WdkSecondaryFrameTx | uint | Read-only | Cumulative frames sent on the secondary port |
| Network and link | WdkSecondaryFrameRx | uint | Read-only | Cumulative frames received on the secondary port |
| Network and link | WdkPdoIdxDropCount | uint | Read-only | Cumulative late frames dropped: the frame arrived but its sequence number had already left the 8-frame window. This is not packet loss |
| Network and link | WdkWkcMismatchCount | uint | Read-only | Cumulative WKC mismatch count |
| Network and link | WdkPrimaryRingFullDrop | uint | Read-only | Drops caused by the primary receive ring being full |
| Network and link | WdkSecondaryRingFullDrop | uint | Read-only | Drops caused by the secondary receive ring being full |
| Network and link | WdkPrimaryTxBailBusy | uint | Read-only | Primary transmit returned early — resource busy |
| Network and link | WdkPrimaryTxBailPreallocMiss | uint | Read-only | Primary transmit returned early — preallocation miss |
| Network and link | WdkPrimaryTxFallbackSent | uint | Read-only | Number of times the primary port switched to the fallback transmit path |
| Network and link | WdkSecondaryTxBailBusy | uint | Read-only | Secondary transmit returned early — resource busy |
| Network and link | WdkSecondaryTxBailPreallocMiss | uint | Read-only | Secondary transmit returned early — preallocation miss |
| Network and link | WdkSecondaryTxFallbackSent | uint | Read-only | Number of times the secondary port switched to the fallback transmit path |
| Network and link | WdkPrimaryNdisCall | uint | Read-only | Number of receive calls on the primary NIC |
| Network and link | WdkPrimaryEcatMatch | uint | Read-only | Number of frames on the primary port recognized as EtherCAT frames |
| Network and link | WdkSecondaryNdisCall | uint | Read-only | Number of receive calls on the secondary NIC |
| Network and link | WdkSecondaryEcatMatch | uint | Read-only | Number of frames on the secondary port recognized as EtherCAT frames |
| Runtime | WdkPollCallbackTxTicks | uint | Read-only | Number of entries into the cyclic transmit callback |
| Runtime | WdkPollCallbackRxTicks | uint | Read-only | Number of wake-ups where the receive-drain wait was satisfied by the deadline timer |
| Runtime | WdkRtCpuCore | int | Read-only | CPU core the real-time thread is currently bound to; -1 = not started or not readable |
| Runtime | WdkRxCpuCore | int | Read-only | CPU core the receive-drain thread is currently bound to; -1 = not enabled or not readable |
WdkHealthSnapshot structure
| Category | Property | Type | Access | Description |
|---|---|---|---|---|
| Primary transmit | PrimaryTxSubmitted | uint | Read-only | Primary transmit submissions |
| Primary transmit | PrimaryTxCompleted | uint | Read-only | Primary transmit completions |
| Primary transmit | PrimaryTxFailed | uint | Read-only | Primary transmit failures |
| Primary transmit | PrimaryTxBailNotConn | uint | Read-only | Primary transmit returned early — link not connected |
| Primary transmit | PrimaryTxBailInvalid | uint | Read-only | Primary transmit returned early — invalid parameter |
| Primary transmit | PrimaryTxBailNoPool | uint | Read-only | Primary transmit returned early — no free buffer |
| Primary transmit | PrimaryTxBailBusy | uint | Read-only | Primary transmit returned early — resource busy |
| Primary transmit | PrimaryTxBailPreallocMiss | uint | Read-only | Primary transmit returned early — preallocation miss |
| Primary transmit | PrimaryTxFallbackSent | uint | Read-only | Number of times the primary port switched to the fallback transmit path |
| Primary receive | PrimaryRingDrop | uint | Read-only | Primary receive ring-full drops |
| Primary receive | PrimaryNdisCall | uint | Read-only | Number of receive calls on the primary NIC |
| Primary receive | PrimaryEcatMatch | uint | Read-only | Number of frames on the primary port recognized as EtherCAT frames |
| Secondary transmit | SecondaryTxSubmitted | uint | Read-only | Secondary transmit submissions |
| Secondary transmit | SecondaryTxCompleted | uint | Read-only | Secondary transmit completions |
| Secondary transmit | SecondaryTxFailed | uint | Read-only | Secondary transmit failures |
| Secondary transmit | SecondaryTxBailNotConn | uint | Read-only | Secondary transmit returned early — link not connected |
| Secondary transmit | SecondaryTxBailInvalid | uint | Read-only | Secondary transmit returned early — invalid parameter |
| Secondary transmit | SecondaryTxBailNoPool | uint | Read-only | Secondary transmit returned early — no free buffer |
| Secondary transmit | SecondaryTxBailBusy | uint | Read-only | Secondary transmit returned early — resource busy |
| Secondary transmit | SecondaryTxBailPreallocMiss | uint | Read-only | Secondary transmit returned early — preallocation miss |
| Secondary transmit | SecondaryTxFallbackSent | uint | Read-only | Number of times the secondary port switched to the fallback transmit path |
| Secondary receive | SecondaryRingDrop | uint | Read-only | Secondary receive ring-full drops |
| Secondary receive | SecondaryNdisCall | uint | Read-only | Number of receive calls on the secondary NIC |
| Secondary receive | SecondaryEcatMatch | uint | Read-only | Number of frames on the secondary port recognized as EtherCAT frames |
| Scheduling | PollCallbackTxTicks | uint | Read-only | Number of entries into the cyclic transmit callback |
| Scheduling | PollCallbackRxTicks | uint | Read-only | Number of wake-ups where the receive-drain wait was satisfied by the deadline timer |
| Errors | PdoIdxDrop | uint | Read-only | Cumulative late frames dropped |
| Errors | WkcMismatch | uint | Read-only | Cumulative WKC mismatch count |
| Reading | HasTrafficCounters | bool | Read-only | Any transmit / receive counter differs from 0, so the counter surface really holds traffic samples |
| Reading | HasHardErrors | bool | Read-only | Any hard-error counter differs from 0 (WKC mismatch, ring-full drop, early transmit return, transmit failure) |
WdkDiagCounter counter id table
| id | Corresponding member | Description |
|---|---|---|
| 1 | WdkWkcMismatchCount | Cumulative WKC mismatch count |
| 2 | WdkPrimaryRingFullDrop | Primary receive ring-full drops |
| 3 | WdkSecondaryRingFullDrop | Secondary receive ring-full drops |
| 4 | PrimaryTxBailNotConn | Primary transmit returned early: link not connected |
| 5 | PrimaryTxBailInvalid | Primary transmit returned early: invalid parameter |
| 6 | PrimaryTxBailNoPool | Primary transmit returned early: no free buffer |
| 7 | WdkPrimaryTxBailBusy | Primary transmit returned early: resource busy |
| 8 | WdkPrimaryTxBailPreallocMiss | Primary transmit returned early: preallocation miss |
| 9 | WdkPrimaryTxFallbackSent | Number of times the primary port switched to the fallback transmit path |
| 10 | SecondaryTxBailNotConn | Secondary transmit returned early: link not connected |
| 11 | SecondaryTxBailInvalid | Secondary transmit returned early: invalid parameter |
| 12 | SecondaryTxBailNoPool | Secondary transmit returned early: no free buffer |
| 13 | WdkSecondaryTxBailBusy | Secondary transmit returned early: resource busy |
| 14 | WdkSecondaryTxBailPreallocMiss | Secondary transmit returned early: preallocation miss |
| 15 | WdkSecondaryTxFallbackSent | Number of times the secondary port switched to the fallback transmit path |
| 16 | WdkPollCallbackTxTicks | Cyclic transmit callback entries |
| 17 | WdkPollCallbackRxTicks | Wake-ups where the receive-drain wait was satisfied by the deadline timer |
| 20 | WdkPrimaryNdisCall | Number of receive calls on the primary NIC |
| 21 | WdkPrimaryEcatMatch | Number of frames on the primary port recognized as EtherCAT frames |
| 22 | WdkSecondaryNdisCall | Number of receive calls on the secondary NIC |
| 23 | WdkSecondaryEcatMatch | Number of frames on the secondary port recognized as EtherCAT frames |
| 24 | PrimaryTxSubmitted | Primary transmit submissions |
| 25 | PrimaryTxCompleted | Primary transmit completions |
| 26 | PrimaryTxFailed | Primary transmit failures |
| 27 | SecondaryTxSubmitted | Secondary transmit submissions |
| 28 | SecondaryTxCompleted | Secondary transmit completions |
| 29 | SecondaryTxFailed | Secondary transmit failures |
IDs not listed belong to internal drain and ring-index diagnostics; their value semantics are not promised, so do not use them as production criteria.
GetWdkHealthSnapshot()
public WdkHealthSnapshot GetWdkHealthSnapshot()
Assembles a health counter snapshot of the real-time runtime in one call (send / receive / early-return / drop counters for each port, plus the two reading flags). Use it when several counters must be compared within one cycle, so that reading them one by one does not cross cycles.
Return value:
WdkHealthSnapshot— health counter snapshot; fields are in the WdkHealthSnapshot structure table above
Example:
var health = master.Diagnostics.GetWdkHealthSnapshot();
Console.WriteLine($"主口 提交={health.PrimaryTxSubmitted} 完成={health.PrimaryTxCompleted} 失败={health.PrimaryTxFailed}"); // Primary port submitted={health.PrimaryTxSubmitted} completed={health.PrimaryTxCompleted} failed={health.PrimaryTxFailed}
Console.WriteLine($"副口 提交={health.SecondaryTxSubmitted} 完成={health.SecondaryTxCompleted} 失败={health.SecondaryTxFailed}"); // Secondary port submitted={health.SecondaryTxSubmitted} completed={health.SecondaryTxCompleted} failed={health.SecondaryTxFailed}
if (!health.HasTrafficCounters)
Console.WriteLine("尚未采到流量计数样本(不要据此判断链路好坏)"); // No traffic counter sample collected yet (do not judge link quality from this)
if (health.HasHardErrors)
Console.WriteLine($"存在硬错误:WKC 不匹配={health.WkcMismatch}, 环满丢弃={health.PrimaryRingDrop}/{health.SecondaryRingDrop}"); // Hard errors present: WKC mismatch={health.WkcMismatch}, ring-full drops={health.PrimaryRingDrop}/{health.SecondaryRingDrop}
WdkDiagCounter(uint counterId)
public uint WdkDiagCounter(uint counterId)
Reads a single real-time runtime diagnostic counter by id. A read generates no bus frames. Value semantics are in the counter id table above.
Parameters:
counterId(uint) — counter id; valid values are in the id table above
Return value:
uint— cumulative value of that counter; 0 when the id is out of range or the read fails
Example:
uint wkcMismatch = master.Diagnostics.WdkDiagCounter(1);
uint primaryTxBusy = master.Diagnostics.WdkDiagCounter(7);
Console.WriteLine($"WKC 不匹配={wkcMismatch}, 主口发送繁忙={primaryTxBusy}"); // WKC mismatch={wkcMismatch}, primary port TX busy={primaryTxBusy}
Jitter and scheduling counters
Jitter distribution, path classification and scheduling deviation collected per cycle by the real-time runtime. All values are cumulative or window peaks; a read generates no bus frames.
| Category | Property | Type | Access | Description |
|---|---|---|---|---|
| Cycle and jitter | JitterInstrumentVersion | uint | Read-only | Version of the jitter statistics surface; 0 = the current real-time runtime does not provide this group of fields |
| Cycle and jitter | JitterTotalSamples | ulong | Read-only | Total jitter sample count (equal to the sum of the 7 histogram bucket counts) |
| Cycle and jitter | JitterMinUs | double | Read-only | Minimum jitter within the window (µs); returns NaN when the read fails |
| Cycle and jitter | JitterHistogramBins | uint[] | Read-only | Cumulative counts of the 7 jitter histogram buckets; bucket boundaries are in the table below |
| Cycle and jitter | DispatchCycleMaxJitterUs | double | Read-only | Maximum jitter within the transmit-only cycle window (µs); returns NaN when the read fails |
| Cycle and jitter | DrainCycleMaxJitterUs | double | Read-only | Maximum jitter within the receive-drain cycle window (µs); returns NaN when the read fails |
| Cycle and jitter | PathCountFast | uint | Read-only | Number of samples on the full busy-spin path (cycle shorter than 50 µs) |
| Cycle and jitter | PathCountMed | uint | Read-only | Number of samples on the park-and-wait path (cycle between 50 and 250 µs) |
| Cycle and jitter | PathCountSlow | uint | Read-only | Number of samples on the timer-sleep path (cycle not shorter than 250 µs) |
| Cycle and jitter | KtimerWakeNormalCount | uint | Read-only | Number of times the timer wake-up still left margin for cycle calibration |
| Cycle and jitter | KtimerWakeOverrunCount | uint | Read-only | Number of times the timer wake-up was already past the next cycle boundary; a common source of elevated jitter |
| Runtime | RtPreemptCount | ulong | Read-only | Cumulative number of times the real-time thread was preempted or showed an undecidable large gap |
| Runtime | RtPreemptPeakNs | uint | Read-only | Peak of those large gaps (ns) |
| Runtime | BigGapUnknownCount | ulong | Read-only | Cumulative number of large gaps that could not be attributed because the hardware SMI count was unavailable |
| Runtime | SmiMsrAvailable | uint | Read-only | Whether the hardware SMI count is available: 0 = unavailable (common on non-Intel platforms or in virtual machines), a value other than 0 = available |
| Runtime | HardwareSmiCounterAvailable | bool | Read-only | Boolean projection of SmiMsrAvailable; false = do not explain jitter with the SMI count |
Jitter histogram bucket boundaries
| Index | Interval | Description |
|---|---|---|
| 0 | below 1 µs | Smallest jitter band |
| 1 | 1 to 2 µs | — |
| 2 | 2 to 5 µs | — |
| 3 | 5 to 10 µs | — |
| 4 | 10 to 50 µs | — |
| 5 | 50 to 100 µs | — |
| 6 | 100 µs and above | Largest jitter band |
Counts accumulate from the start of the real-time runtime and are never reset; the difference between two consecutive reads gives the window distribution.
Per-slave WKC probe
An observation-only channel, off by default. Once enabled it samples the true WKC of the process data frames per slave, so a lost slave can be located without stopping the bus. The probe drives no verdict and changes no control path.
| Category | Property | Type | Access | Description |
|---|---|---|---|---|
| WKC | WkcProbeMode | int | Read-only | Probe mode: 0 = off (default, no sampling) / 1 = per-slave true-value sampling; returns -1 when the read fails |
| WKC | SlaveWkcProbeActual | int[] | Read-only | Per-slave true WKC of the data frame, 1-based, [0] unused. 0 or above = true value (0 means the frame came back but this slave does not contribute, which is a valid reading) / -2 = sent without a reply / -1 = no sample |
| WKC | SlaveWkcProbeExpected | int[] | Read-only | Whether each slave can be probed: 1 = the slave has a read mapping and can be probed; -1 = not probeable (output-only slave or not mapped) |
| WKC | SlaveWkcProbeAgeMs | int[] | Read-only | Freshness of the per-slave sample (ms): 0 or above = time since the most recent sample; -1 = never sampled |
| Slave anomalies | ProbeAliveCount | int | Read-only | Probe summary: number of slaves with a measured reply; 0 when there is no true-value sample |
| Slave anomalies | ProbeUnknownCount | int | Read-only | Probe summary: number of slaves with insufficient evidence; 0 when there is no true-value sample |
-2 (sent without a reply), -1 (no sample) and 0 (a reply came back but this slave does not contribute) have completely different meanings: neither -1 nor -2 may be folded into 0, and neither may lead to any conclusion other than "this slave did not respond"; a read failure always keeps -1.
SetWkcProbeMode(int mode)
public bool SetWkcProbeMode(int mode)
Sets the per-slave WKC probe mode.
Parameters:
mode(int) — 0 = off / 1 = per-slave true-value sampling
Return value:
bool— true = issued; false = issuing failed (the failure detail is recorded and available through LastDiagnosticsReadError)
Example:
var diag = master.Diagnostics;
if (diag.SetWkcProbeMode(1))
{
Console.WriteLine($"探针已开启,当前模式 {diag.WkcProbeMode}"); // Probe enabled, current mode {diag.WkcProbeMode}
for (int i = 1; i < diag.SlaveWkcProbeActual.Length; i++)
Console.WriteLine($"从站 {i}: 实测={diag.SlaveWkcProbeActual[i]}, 可探={diag.SlaveWkcProbeExpected[i]}, 样本年龄={diag.SlaveWkcProbeAgeMs[i]}ms"); // Slave {i}: measured={diag.SlaveWkcProbeActual[i]}, probeable={diag.SlaveWkcProbeExpected[i]}, sample age={diag.SlaveWkcProbeAgeMs[i]}ms
}
else
{
Console.WriteLine($"探针开启失败: {diag.LastDiagnosticsReadError}"); // Probe enable failed: {diag.LastDiagnosticsReadError}
}
Online and lost-slave truth
Each of the two master-level measured conclusions — "is process data dead" and "how many slaves are lost" — carries a companion valid bit. Always read the companion bit first.
| Category | Property | Type | Access | Description |
|---|---|---|---|---|
| Diagnostics | NoProcessDataKnown | bool | Read-only | Whether NoProcessData has a measured sample. false = read failed or unavailable; NoProcessData has no meaning then and must be shown as "unknown" |
| Diagnostics | LostSlaveCountKnown | bool | Read-only | Whether LostSlaveCount has a measured sample. false = read failed; LostSlaveCount is -1 then and does not mean "zero lost slaves" |
On a read failure NoProcessData returns true (missing evidence is never passed off as healthy) and LostSlaveCount returns -1 (never folded into 0 lost slaves). These two values are only fail-safe placeholders; the real conclusion follows the companion valid bit. Use GetSnapshot() or Truth when you need all truth values from the same cycle.
Recovery ladder observation
The recovery-process observation surface at slave and master level. Every field is for display and diagnostics only; none of them participates in control or changes the "is this slave in real OP right now" verdict.
| Category | Property | Type | Access | Description |
|---|---|---|---|---|
| Diagnostics | SlaveRecovery | SlaveRecoveryStatusView[] | Read-only | Per-slave recovery ladder observation, 1-based, [0] unused. An element with Available = false means recovery observation is unavailable for that slave (not "no recovery") |
| Diagnostics | MasterRecoveryLadder | Master recovery escalation observation | Read-only | Master-level recovery escalation observation: rebuild request pending / running / consecutive failures / backoff, plus the cumulative suppression count of "trigger hit but not executed in this round". Available = false = observation unavailable |
| Diagnostics | RecoveryLadderSeq | ulong | Read-only | Freshness token of the recovery ladder sequence, monotonically increasing; if it stops growing the recording thread is not advancing; 0 = unavailable |
| Diagnostics | RecoveryEvents | RecoveryEventView[] | Read-only | Incremental recovery events: new events since the previous read. Every read advances the internal cursor, so events are taken away only once |
SlaveRecoveryStatusView structure
| Field | Type | Description |
|---|---|---|
| Available | bool | false = recovery observation unavailable (older runtime or no mirror), not "no recovery" |
| Level | SlaveRecoveryLevel | Current recovery level |
| Step | SlaveRecoveryStep | Current step; unrecognized values are passed through unchanged |
| LastStep | SlaveRecoveryStep | Previous step, for tracing transitions |
| Reason | SlaveRecoveryReason | Reason the previous step failed; 0 = none |
| FailAlsc | ushort | Measured raw AL status code at failure; 0 = none or not read |
| RetryCount | ushort | Consecutive failure / attempt count in this round; cleared when the slave leaves or returns |
| BackoffRemainMs | uint | Remaining slave-level cool-down (ms); 0 = free to move at any time |
| StepElapsedMs | uint | Time elapsed in the current step (ms), to tell which step it is stuck at |
| SkipFrames | uint | Cumulative number of skipped recovery frames |
| Seq | ulong | State transition count, incremented on every transition, for judging mirror freshness |
| FlagsRaw | byte | Raw flag byte |
| PausedA | bool | Link-break class exception pause handling in progress |
| NeedsReconfig | bool | Configuration not replayed yet |
| LadderExhausted | bool | Consecutive failures have escalated to master-level recovery |
| Epilogue | bool | OP epilogue in progress |
| LastResultOk | SlaveRecoveryResultOk | Result of the previous step: success / failure / suppressed without running |
| Classify | SlaveRecoveryClass | Recovery classification (A / B1 / B2 / B3); None = not classified yet |
| IsActive | bool | The ladder is active (not idle, not finished, not an unknown level) |
| LadderKey | string | Cross-surface consistency key shaped level-step-reason-consecutive-failures-flags; time variables are deliberately excluded so that several places can compare whether they are on the same cycle |
Master-level recovery escalation observation structure
| Field | Type | Description |
|---|---|---|
| Available | bool | false = observation unavailable; true only means the structure was obtained — whether each field has a sample depends on whether that field is null |
| TriggerBlockedTotal | uint | Cumulative count of "trigger hit but not executed in this round", always a measured value |
| RebuildReqPending | bool? | Rebuild request pending and not consumed; null = not sampled, not "not pending" |
| RebuildActive | bool? | Rebuild in progress; null = not sampled |
| RebuildFail | byte? | Consecutive failure count; null = not sampled, not "zero failures" |
| AlarmOnly | bool? | Alarm-only tier (after several ineffective attempts, raise an alarm but do not give up); null = not sampled |
| HandoffBusy | bool? | Orchestration busy; null = not sampled |
| ASuppressed | bool? | Link-break class exception suppressed; null = not sampled |
| BadPersistent | bool? | The bad state has lasted beyond the criterion; null = not sampled |
| LadderExhausted | bool? | Some slave's consecutive failures have escalated to master-level recovery; null = not sampled |
| BackoffRemainMs | uint? | Remaining backoff (ms); null = not sampled, not "no backoff" |
| BadSinceMs | uint? | How long the bad state has lasted (ms); null = not sampled |
| RebuildTotal | uint? | Cumulative whole-network rebuild count in this session; null = not sampled |
| Seq | ulong? | State transition count; null = not sampled. Use RecoveryLadderSeq when you need a reliable freshness token |
The current implementation samples only TriggerBlockedTotal; every other field returns null rather than 0. Consumers must not read null as "no rebuild / no failure / no backoff"; show it as "unknown".
RecoveryEventView structure
| Field | Type | Description |
|---|---|---|
| Seq | uint | Global monotonic sequence number, the incremental cursor base (pass this Seq as the next sinceSeq) |
| Slave | ushort | Slave index; 0 = master-level event |
| Kind | SlaveRecoveryEventKind | Event category (step transition / level transition / power-up return / suppression / throttling / penalty reset and so on) |
| FromLevel / ToLevel | SlaveRecoveryLevel | Recovery level before / after the event |
| FromStep / ToStep | SlaveRecoveryStep | Recovery step before / after the event |
| Reason | SlaveRecoveryReason | Event reason |
| Ok | SlaveRecoveryResultOk | 1 = success / 0 = failure / 2 = suppressed without running |
| Alsc | ushort | Measured raw AL status code; 0 = none |
| TickMs | uint | Event time (millisecond timer) |
| IsEscalation | bool | Escalation event (master-level pending / execution / exit verification, or a level step up). Escalation is a normal process and must not be rendered as an abnormal alarm |
ReadRecoveryEvents(uint sinceSeq, uint max)
public RecoveryEventView[] ReadRecoveryEvents(uint sinceSeq, uint max)
Explicit incremental read of recovery events: returns at most max events whose sequence number is strictly greater than sinceSeq. The caller keeps its own cursor and records the Seq of the last event taken as the next sinceSeq. Unlike the RecoveryEvents property, this method does not advance the shared cursor, so it suits secondary consumption.
Parameters:
sinceSeq(uint) — starting sequence number; only events with a larger number are returnedmax(uint) — maximum number of events to take this time; 0 returns an empty array, and a value above the ring capacity is truncated to the ring capacity
Return value:
RecoveryEventView[]— event array; an empty array when there are no new events or the read fails (a failed read is logged, never invented)
Example:
uint cursor = 0;
var events = master.Diagnostics.ReadRecoveryEvents(cursor, 32);
foreach (var e in events)
{
Console.WriteLine($"[{e.TickMs}] 从站 {(e.Slave == 0 ? "主站" : e.Slave.ToString())} " + // [{e.TickMs}] slave {(e.Slave == 0 ? "master" : e.Slave.ToString())}
$"{e.Kind}: {e.FromStep} -> {e.ToStep} ({e.Ok})");
cursor = e.Seq;
}
Automatic hot-plug observability
The only trigger for an automatic rebuild lives in the kernel StateGuard (OP steady state, about 1 second throttle): when the physical station count exceeds the registered live count, the candidate position holds an unaddressed new module or the station configured for that slot, and the "declared + identity verified" criteria pass, the master runs discover, mapping and RecoverSlaveToOP by itself. There is no user-space switch, no period setting and no manual rebuild entry point.
| Category | Property | Type | Access | Description |
|---|---|---|---|---|
| Diagnostic | HotSwapRescanCount | int | read-only | Completed automatic rebuild rounds (calls rejected before execution do not count); 0 = never |
| Diagnostic | LastHotSwapRescanResult | int | read-only | Last result code. 0 = never happened or last succeeded; see below for negative values |
| Diagnostic | LastHotSwapRescanTime | DateTime | read-only | Last completion time (UTC); DateTime.MinValue when never |
Result codes:
0- never happened, or the last one succeeded (check HotSwapRescanCount to tell)-20- another rebuild round is in progress-21- the rescan found 0 reachable slaves (not the same as a broken link)-23- slaves are present but not in OP (the first AL status code is carried; the whole line is not rolled back)-25- resources exhausted (above the slave limit / no free group / revision or WKC gate rejected / buffer capacity exceeded)-1- invalid master index;-6- master not initialized
An automatic rebuild failure is only written to the kernel log; it raises no alarm, event, restart or rollback. To judge "did the last one succeed", read LastHotSwapRescanResult; do not infer it from HotSwapRescanCount.
Example:
var diag = master.Diagnostics;
Console.WriteLine($"自动重建 {diag.HotSwapRescanCount} 轮,上次结果 {diag.LastHotSwapRescanResult}," + // Auto-rebuild {diag.HotSwapRescanCount} rounds, last result {diag.LastHotSwapRescanResult},
$"时刻 {diag.LastHotSwapRescanTime:O}"); // at {diag.LastHotSwapRescanTime:O}
DC diagnostics summary and per-slave snapshot
Master-level DC conclusions come from the forwarding properties on master.Diagnostics; per-slave facts come from the per-slave entries of the 2-second snapshot object. Every forwarding property has a companion valid bit: when the companion is false, the value of the old property has no meaning.
| Category | Property | Type | Access | Description |
|---|---|---|---|---|
| DC diagnostics | DcHasDc | bool | Read-only | Whether the network contains slaves with DC capability (capability bit scale). Returns false when the read fails, but it must be read together with DcHasDcKnown |
| DC diagnostics | DcHasDcKnown | bool | Read-only | Whether DcHasDc has a confirmed conclusion. false = slave enumeration or capability read failed; the false of DcHasDc then does not mean "the bus really has no DC slaves" |
| DC diagnostics | DcReferenceClockSlave | ushort | Read-only | Reference clock slave index (1-based; 0 = no DC slave or no reference clock). Returns 0 when the read fails, so it must be read together with DcReferenceClockSlaveKnown |
| DC diagnostics | DcReferenceClockSlaveKnown | bool | Read-only | Whether DcReferenceClockSlave has a confirmed source. When true, a 0 also means "confirmed no reference clock"; false = read failed and the 0 has no meaning |
| DC diagnostics | ReferenceClockKnown | bool | Read-only | Same-source conclusion on the 2-second snapshot object: whether the reference clock slave index has a confirmed source. Same semantics as DcReferenceClockSlaveKnown |
DcSlaveSnapshot per-slave fields
| Category | Property | Type | Access | Description |
|---|---|---|---|---|
| DC diagnostics | Capability | DcCapability | Read-only | DC capability tier (ESC capability bits + the highest tier declared by the ESI). It answers "can this slave do SYNC0", not "is it armed right now"; Unknown is not "no capability" |
| DC diagnostics | ArmOutcome | DcArmResult | Read-only | Final conclusion of the automatic DC arming policy at start-up. Unknown = no terminal record at all, which is neither failure nor success |
| DC diagnostics | Sync0CycleNs | int? | Read-only | Value actually applied to the SYNC0 cycle register (ns); null = no DC or cannot read; 0 = the cycle value was not applied |
| DC diagnostics | Sync1CycleNs | int? | Read-only | Value actually applied to the SYNC1 cycle register (ns); null has the same meaning as above |
| DC diagnostics | PropagationDelayNs | int? | Read-only | Value actually applied for the propagation delay (ns); null = no DC or cannot read |
| DC diagnostics | PropagationDelayOrigin | DcPropagationDelayOrigin | Read-only | Origin tier of the propagation delay. 0 ns has two causes (domain root / not measured yet) that cannot be told apart right now, so it is always reported honestly as ZeroNsAmbiguous |
| DC diagnostics | SyncWindow | DcSyncWindowInfo | Read-only | Synchronization window (including the unavailable reason and the historical conclusion "reading not updated"). When unavailable, every numeric field is null, not 0 |
| DC diagnostics | Jitter | DcJitterStats? | Read-only | Steady-state quality (mean, σ, peak-to-peak, largest adjacent change and average sample interval of the 2-second sampling surface); null when there are fewer than 2 samples or the slave is not a participant |
| DC diagnostics | ConvergenceMs | int? | Read-only | Convergence time (ms, observation scale); null = no complete transition observed |
Example:
var diag = master.Diagnostics;
Console.WriteLine($"存在 DC 从站: {diag.DcHasDc}(确证={diag.DcHasDcKnown})"); // DC slaves present: {diag.DcHasDc} (confirmed={diag.DcHasDcKnown})
Console.WriteLine($"参考钟: {diag.DcReferenceClockSlave} 号(确证={diag.DcReferenceClockSlaveKnown})"); // Reference clock: slave {diag.DcReferenceClockSlave} (confirmed={diag.DcReferenceClockSlaveKnown})
var dc = diag.DcDiagnostics;
foreach (var s in dc.Slaves)
{
Console.WriteLine($"从站 {s.SlaveIndex}: 能力={s.Capability}, 武装={s.ArmOutcome}, " + // Slave {s.SlaveIndex}: capability={s.Capability}, arm={s.ArmOutcome},
$"SYNC0周期={s.Sync0CycleNs}ns, 在窗={s.SyncWindow.InSync}"); // SYNC0 cycle={s.Sync0CycleNs}ns, in window={s.SyncWindow.InSync}
}
Slave diagnostics data (SlaveDiagnosticsData)
The slave-level diagnostic snapshot returned by master.GetDiagnostics(): port link state of each slave + cumulative physical-layer counters + slave-level aggregates. All array indexes are 1-based; [0] is unused.
| Category | Property | Type | Access | Description |
|---|---|---|---|---|
| Port status | PortLinkStatus | byte[] | Read-only | Port link state bitmap of each slave, index = slave index (1-based). bit0 = P0, bit1 = P1, bit2 = P2, bit3 = P3; 1 = link up, 0 = down |
| Port status | LinkQualityPercent | uint[] | Read-only | Link quality percentage of each slave. 1 to 100 is measured; 0 means both "no sample / unknown" and "measured 0%", so read SlaveLinkQualityPercent (short, -1 = not sampled) when you need to tell them apart |
| Port status | PortErrorCount | uint[] | Read-only | Total receive errors of each slave port (cumulative). 0 = no port receive error ever occurred, or not sampled yet |
| Port status | LostLinkCount | uint[] | Read-only | Cumulative link loss count of each slave. 0 = never lost, or not sampled yet; for the current port link state read PortLinkStatus |
| Slave anomalies | TotalSlaveRxErrors | uint | Read-only | Sum of receive errors of all slaves (cumulative). Above 0 = the bus may have a CRC or signal integrity problem |
| Slave anomalies | TotalSlaveInvalidFrames | uint | Read-only | Sum of invalid frames of all slaves (cumulative); the real source of checksum errors |
| Slave anomalies | TotalSlaveLostLinks | uint | Read-only | Sum of link losses of all slaves (cumulative). Above 0 = unstable cable or port contact |
| Slave anomalies | AvgLinkQualityPercent | ushort | Read-only | Average link quality of the slaves currently online (1 to 100); 0 = no online sample (unknown), not "the worst link" |
A 0 in LinkQualityPercent, PortErrorCount, LostLinkCount and AvgLinkQualityPercent may mean "never happened" or "not sampled yet". To tell "unknown" from a real 0, read the per-slave short link quality array provided by the same object: all values below 0 means unknown.
Example:
var slaveDiag = master.GetDiagnostics();
if (slaveDiag != null)
{
for (int i = 1; i < slaveDiag.PortLinkStatus.Length; i++)
Console.WriteLine($"从站 {i}: 端口位图=0x{slaveDiag.PortLinkStatus[i]:X2}, " + // Slave {i}: port bitmap=0x{slaveDiag.PortLinkStatus[i]:X2},
$"质量={slaveDiag.LinkQualityPercent[i]}%, 端口错误={slaveDiag.PortErrorCount[i]}, " + // quality={slaveDiag.LinkQualityPercent[i]}%, port errors={slaveDiag.PortErrorCount[i]},
$"丢链路={slaveDiag.LostLinkCount[i]}"); // lost links={slaveDiag.LostLinkCount[i]}
Console.WriteLine($"合计: 接收错误={slaveDiag.TotalSlaveRxErrors}, " + // Total: receive errors={slaveDiag.TotalSlaveRxErrors},
$"无效帧={slaveDiag.TotalSlaveInvalidFrames}, " + // invalid frames={slaveDiag.TotalSlaveInvalidFrames},
$"丢链路={slaveDiag.TotalSlaveLostLinks}, " + // lost links={slaveDiag.TotalSlaveLostLinks},
$"平均质量={slaveDiag.AvgLinkQualityPercent}%"); // average quality={slaveDiag.AvgLinkQualityPercent}%
}
Slave diagnostics snapshot (SlaveDiagnosticsSnapshot)
A single-slave consistent snapshot returned by slave.Diagnostics.GetSnapshot(). Every DC-related field carries a validity bit: when the valid bit is false, the accompanying 0 / false is only a placeholder and has no meaning.
| Category | Property | Type | Access | Description |
|---|---|---|---|---|
| Basic information | SlaveNumber | int | Read-only | Slave index (1-based) |
| DC diagnostics | DcInSync | bool | Read-only | Whether this cycle is inside the synchronization window. Read DcInSyncValid first: when invalid, a false here does not mean "not synchronized" |
| DC diagnostics | DcInSyncValid | bool | Read-only | Whether DcInSync has a valid conclusion. false = the conclusion for this cycle is unknown (armed state unknown / window read failed / the reference clock itself / stale sample / never sampled) |
| DC diagnostics | DcSyncTimeDifferenceNs | int | Read-only | Current synchronization error (ns). When DcSyncTimeDifferenceValid is false, 0 has no meaning (0 would be misread as "zero deviation") |
| DC diagnostics | DcSyncTimeDifferenceValid | bool | Read-only | Whether DcSyncTimeDifferenceNs is valid; same source as the window valid bit |
| DC diagnostics | DcSync0Armed | bool? | Read-only | Whether SYNC0 is armed (tri-state). null = cannot decide, which does not equal not armed |
| DC diagnostics | DcSyncMaxDiffNs | int | Read-only | Maximum time difference within the window (ns); valid only when DcSyncWindowValid is true |
| DC diagnostics | DcSyncMinDiffNs | int | Read-only | Minimum time difference within the window (ns); valid only when DcSyncWindowValid is true |
| DC diagnostics | DcOutOfSyncCount | uint | Read-only | Cumulative number of excursions outside the synchronization window; valid only when DcSyncWindowValid is true |
| DC diagnostics | DcSyncWindowValid | bool | Read-only | Whether the three window statistics above are valid |
| DC diagnostics | DcReadFaulted | bool | Read-only | Whether the DC diagnostic read failed; sticky until the next successful read |
| DC diagnostics | DcActiveAssign | ushort | Read-only | Raw mirror of the AssignActivate register (the ESI configuration value, which does not mean armed). Valid only when DcRegisterFactsValid is true |
| DC diagnostics | DcCycle0Ns | int | Read-only | Raw mirror of the SYNC0 cycle register (ns). Valid only when DcRegisterFactsValid is true |
| DC diagnostics | DcCycle1Ns | int | Read-only | Raw mirror of the SYNC1 cycle register (ns). Valid only when DcRegisterFactsValid is true |
| DC diagnostics | DcShiftNs | int | Read-only | Raw mirror of the DC phase shift (ns). Valid only when DcRegisterFactsValid is true |
| DC diagnostics | DcRegisterFactsValid | bool | Read-only | Whether the four register mirrors above come from one successful read. When true, 0 is a valid value (not active / cycle not in place / shift 0); when false, the four 0s are placeholders only and must not be read as "DC not active" |
| Runtime | HasRequiredRuntimeData | bool | Read-only | Whether the required runtime data for this cycle is complete: the slave index is above 0 and the AL state mirror has been sampled |
| Runtime | MissingDataReason | string | Read-only | Text of the reason the data is incomplete; an empty string when complete |
SlaveDiagnosticsSnapshot.AlStatusCode is taken from the slave object's ErrorCode — the full 16-bit ALstatuscode field in the slave structure, which the state machine refreshes by reading 0x0134 on demand. So it is not the same thing as the high byte of AlStatusMirror. The AL mirror reads 6 bytes in one go (0x0130 AL Status + 0x0134 AL Status Code) and encodes the low 8 bits of the AL Status Code into the high byte only when the Error bit is set and the code differs from 0; the mirror high byte is therefore only 8 bits wide and codes ≥ 0x0100 are truncated, while without the Error bit the high byte stays 0. slave.AlStatusCode (the mirror decode) can only honestly return Unknown when the Error bit is set but the high byte is 0. Use this snapshot field (or slave.ErrorCode) when you need the full 16-bit AL error code.
Example:
var snap = slave.Diagnostics.GetSnapshot();
Console.WriteLine($"从站 {snap.SlaveNumber}: 在窗={snap.DcInSync}(有效={snap.DcInSyncValid}), " + // Slave {snap.SlaveNumber}: in window={snap.DcInSync} (valid={snap.DcInSyncValid}),
$"SYNC0 武装={snap.DcSync0Armed}"); // SYNC0 armed={snap.DcSync0Armed}
if (snap.DcRegisterFactsValid)
Console.WriteLine($"寄存器: AssignActivate=0x{snap.DcActiveAssign:X4}, " + // Registers: AssignActivate=0x{snap.DcActiveAssign:X4},
$"SYNC0={snap.DcCycle0Ns}ns, SYNC1={snap.DcCycle1Ns}ns, 偏移={snap.DcShiftNs}ns"); // SYNC0={snap.DcCycle0Ns}ns, SYNC1={snap.DcCycle1Ns}ns, offset={snap.DcShiftNs}ns
else
Console.WriteLine($"寄存器快照不可用(读失败={snap.DcReadFaulted})"); // Register snapshot unavailable (read failed={snap.DcReadFaulted})
if (!snap.HasRequiredRuntimeData)
Console.WriteLine($"运行数据不全: {snap.MissingDataReason}"); // Runtime data incomplete: {snap.MissingDataReason}
Diagnostics snapshot extended fields (DiagnosticsSnapshot)
The diagnostic extended fields on the object returned by GetSnapshot() (base frame counts / WKC / port fields are in GetSnapshot() above). Everything is read-only; each Has-prefixed field is the criterion for "is this group of data usable", so read the criterion before the value.
| Category | Property | Type | Access | Description |
|---|---|---|---|---|
| WKC | WkcActualKnown | bool | Read-only | Whether WkcActual has measured evidence; when false its 0 means only unknown and produces no verdict |
| WKC | WkcExpectedKnown | bool | Read-only | Whether WkcExpected has measured evidence; when false its 0 means only unknown |
| WKC | WkcTripleConsistent | bool | Read-only | Always false: WkcActual / WkcExpected / WcDeficit are assembled by three different producers on three different beats and are never a same-cycle consistent triple; never subtract them or cross-check them |
| Cycle and jitter | JitterInstrumentVersion | uint | Read-only | Version of the jitter statistics surface; 0 = this group of fields is not provided |
| Cycle and jitter | JitterTotalSamples | ulong | Read-only | Total jitter sample count |
| Cycle and jitter | JitterMinUs | double | Read-only | Minimum jitter within the window (µs) |
| Cycle and jitter | JitterHistogramBins | uint[] | Read-only | Cumulative counts of the 7 jitter histogram buckets |
| Cycle and jitter | DispatchCycleMaxJitterUs | double | Read-only | Maximum jitter within the transmit-only cycle window (µs) |
| Cycle and jitter | DrainCycleMaxJitterUs | double | Read-only | Maximum jitter within the receive-drain cycle window (µs) |
| Cycle and jitter | PathCountFast | uint | Read-only | Number of samples on the short-cycle path |
| Cycle and jitter | PathCountMed | uint | Read-only | Number of samples on the medium-cycle path |
| Cycle and jitter | PathCountSlow | uint | Read-only | Number of samples on the long-cycle path |
| Cycle and jitter | KtimerWakeNormalCount | uint | Read-only | Number of timer wake-ups that still left margin for calibration |
| Cycle and jitter | KtimerWakeOverrunCount | uint | Read-only | Number of timer wake-ups already past the next cycle boundary |
| Runtime | RtPreemptCount | ulong | Read-only | Cumulative number of times the real-time thread was preempted or showed an undecidable large gap |
| Runtime | RtPreemptPeakNs | uint | Read-only | Peak of those large gaps (ns) |
| Runtime | BigGapUnknownCount | ulong | Read-only | Cumulative number of large gaps that could not be attributed because the hardware SMI count was unavailable |
| Runtime | SmiMsrAvailable | uint | Read-only | Whether the hardware SMI count is available; 0 = unavailable |
| Runtime | WdkRtCpuCore | int | Read-only | CPU core the real-time thread is bound to; -1 = not bound or not readable |
| Runtime | WdkRxCpuCore | int | Read-only | CPU core the receive-drain thread is bound to; -1 = not enabled or not readable |
| Network and link | WdkPrimaryFrameTx | uint | Read-only | Cumulative frames sent on the primary port |
| Network and link | WdkPrimaryFrameRx | uint | Read-only | Cumulative frames received on the primary port |
| Network and link | WdkSecondaryFrameTx | uint | Read-only | Cumulative frames sent on the secondary port |
| Network and link | WdkSecondaryFrameRx | uint | Read-only | Cumulative frames received on the secondary port |
| Network and link | WdkPdoIdxDropCount | uint | Read-only | Cumulative late frames dropped |
| Network and link | WdkHealth | WdkHealthSnapshot? | Read-only | Health counter snapshot of the real-time runtime (one cycle taken while this snapshot was assembled); null = not obtained this cycle |
| Reading | HasJitterInstrumentation | bool | Read-only | Whether the jitter statistics surface is usable (version differs from 0 and sample count above 0) |
| Reading | HasJitterWindowData | bool | Read-only | Whether the jitter window data is usable (version at least 2 and both maximum / average jitter finite) |
| Reading | HasPdoFrameCounters | bool | Read-only | Whether frame counters were obtained for either path (any send / receive counter above 0) |
| Reading | HasCpuBindingData | bool | Read-only | Whether the CPU binding of the real-time thread was obtained (bound core number at least 0) |
| Reading | HasHardwareSmiCounter | bool | Read-only | Whether the hardware SMI count is usable |
| Reading | HasRtGapCounters | bool | Read-only | Whether the large-gap counters are usable (same criterion as the jitter statistics surface) |
| Reading | HasTimingData | bool | Read-only | Whether timing data is usable (timing mode code differs from 0 and cycle time above 0) |
| Reading | HasBusFrequencyData | bool | Read-only | Whether the bus frequency window is ready (read state is Ready) |
| Reading | HasWdkDiagnostics | bool | Read-only | Whether the real-time runtime diagnostics surface as a whole is ready: cycle count, timing, core binding, jitter and frequency window all ready, with no read error in this cycle |
| Reading | HasRequiredRuntimeData | bool | Read-only | Whether the required runtime data is complete: the missing-item list is empty and the read state is Ready |
| Diagnostics | ReadError | string | Read-only | Failure detail when the read state is Error; null otherwise |
| Diagnostics | MissingDataReasons | string[] | Read-only | List of missing data items; an empty array = nothing missing |
| Diagnostics | MissingDataSummary | string | Read-only | One-line summary of the missing data items; none when nothing is missing |
| Diagnostics | SlaveRecovery | SlaveRecoveryStatusView[] | Read-only | Per-slave recovery ladder observation (1-based; Available = false means the observation is unavailable) |
| Diagnostics | MasterLadder | MasterLadderView | Read-only | Master-level recovery escalation observation inside the snapshot, from the same source and with the same values as master.Diagnostics.MasterRecoveryLadder; fields are in the MasterLadderView structure below |
| Diagnostics | RecoveryEvents | RecoveryEventView[] | Read-only | Incremental recovery events taken while assembling this snapshot |
This table lists diagnostic fields only. Process data truth, per-slave probes, lost-slave counts and other display-verdict fields are also on the snapshot; their semantics are in the "Online and lost-slave truth", "Per-slave WKC probe" and truth snapshot sections of this page.
Cyclic-frame AL state refresh and freshness
The channel that attaches slave AL state reads to cyclic frames, its cumulative counters, and the freshness of the most recent parsing. Both counter groups are process-global cumulative values.
GetPiggybackConsumeCounters(out uint calls, out uint skipAdo, out uint skipLen, out uint skipActive, out uint writes)
public void GetPiggybackConsumeCounters(out uint calls, out uint skipAdo, out uint skipLen,
out uint skipActive, out uint writes)
Reads the 5 cumulative counters of the consumer side.
Parameters:
calls(out uint) — number of consumer-side callsskipAdo(out uint) — number of skips because the segment target was not the AL status registerskipLen(out uint) — number of skips because the segment length was not 2 bytesskipActive(out uint) — number of skips because the previous round had not finished consumingwrites(out uint) — number of successful writes into the master state
Example:
master.Diagnostics.GetPiggybackConsumeCounters(out uint calls, out uint skipAdo,
out uint skipLen, out uint skipActive, out uint writes);
Console.WriteLine($"消费侧: 调用={calls}, 跳过目标={skipAdo}, 跳过长度={skipLen}, " + // Consumer side: calls={calls}, skipped target={skipAdo}, skipped length={skipLen},
$"跳过未完成={skipActive}, 写入={writes}"); // skipped in-flight={skipActive}, writes={writes}
GetPiggybackCallCounters(out uint callTotal, out uint opBranch, out uint opInactive, out uint opQueued)
public void GetPiggybackCallCounters(out uint callTotal, out uint opBranch,
out uint opInactive, out uint opQueued)
Reads the 4 cumulative counters of the caller side. These are not the same counters as the consumer side; do not add them together.
Parameters:
callTotal(out uint) — total number of aggregate state read callsopBranch(out uint) — number of calls that took the running-state fast pathopInactive(out uint) — number of calls not appended because the channel slot was already occupiedopQueued(out uint) — number of calls successfully queued into the channel slot
Example:
master.Diagnostics.GetPiggybackCallCounters(out uint total, out uint branch,
out uint inactive, out uint queued);
Console.WriteLine($"发起侧: 总={total}, 快速路径={branch}, 槽位占用={inactive}, 已排队={queued}"); // Initiator side: total={total}, fast path={branch}, slot occupied={inactive}, queued={queued}
TryGetMasterAlstatRefresh(out ulong refreshUs, out ushort aggregate, out ushort wkcMatch)
public bool TryGetMasterAlstatRefresh(out ulong refreshUs, out ushort aggregate, out ushort wkcMatch)
This version always returns false. The runtime has no data source for "AL state parsing carried on the cyclic frame": it always reports failure and writes none of the three output parameters. It therefore cannot be used to identify a "false OP" — a failure is just a failure, and 0 is not evidence that the timestamp stopped refreshing.
To decide "the master reports OP but process data stopped long ago", use an entry point that truthfully reflects reality:
- Whether the cycle advances:
Diagnostics.CycleRunState(three states: not started / started but not advancing / advancing) together withBusCycleHz - Slave AL state: the per-slave
ErrorCode/AlStatusCode, orDarraEtherCAT.GetSlaveALStatusCode(masterIndex, slaveIndex) - Group WKC:
GetGroupActualWKCcompared with the expected value fixed at configuration time (groupActualWKC/ExpectedWKC)
Parameters:
refreshUs(out ulong) — valid only when the call returns true; fixed at 0 when it returns false and not a real readingaggregate(out ushort) — same as abovewkcMatch(out ushort) — same as above
Return value:
bool— alwaysfalsein this version (no data source / read failed);truecan only appear once a future runtime provides a data source
Example:
if (master.Diagnostics.TryGetMasterAlstatRefresh(out ulong refreshUs, out ushort al, out ushort match))
{
Console.WriteLine($"AL 状态={al}, WKC 匹配={match}, 上次解析时戳={refreshUs}"); // AL state={al}, WKC match={match}, last parse timestamp={refreshUs}
}
else
{
// Normal path for this version: there is no ALSTAT freshness data source.
// Do not conclude "false OP" from this; use CycleRunState / per-slave AlStatusCode / group WKC.
Console.WriteLine("AL 状态新鲜度不可用"); // AL state freshness unavailable
}
Group-level WKC static query
Group-level working counters are accounted per group: each group has one independent logical read/write frame, with its own actual value and its own expected value fixed at configuration time. The valid group range is 1 to 7; group 0 is the unassigned marker and has no process data segment.
DarraEtherCAT.GetGroupActualWKC(ushort masterIndex, byte group)
public static ushort GetGroupActualWKC(ushort masterIndex, byte group)
Reads the actual working counter of the specified group for the previous cycle (the measured result of that group's PDO exchange).
Parameters:
masterIndex(ushort) — master indexgroup(byte) — group number (1 to 7)
Return value:
ushort— actual WKC of that group; 0 when the group does not exist or the read fails
Example:
for (byte g = 1; g <= 7; g++)
{
ushort actual = DarraEtherCAT.GetGroupActualWKC(master.MasterNumber, g);
ushort expected = DarraEtherCAT.GetGroupExpectedWKC(master.MasterNumber, g);
if (expected == 0) continue; // Empty group, nothing accounted
Console.WriteLine($"组 {g}: WKC {actual}/{expected}"); // Group {g}: WKC {actual}/{expected}
}
DarraEtherCAT.GetGroupExpectedWKC(ushort masterIndex, byte group)
public static ushort GetGroupExpectedWKC(ushort masterIndex, byte group)
Reads the expected working counter fixed for the specified group once mapping is complete. This value is the configuration-time truth and is never lowered because the bus degrades.
Parameters:
masterIndex(ushort) — master indexgroup(byte) — group number (1 to 7)
Return value:
ushort— expected WKC of that group; 0 for an empty group (no slaves) or when the read fails
Example:
ushort expected = DarraEtherCAT.GetGroupExpectedWKC(master.MasterNumber, 1);
ushort actual = DarraEtherCAT.GetGroupActualWKC(master.MasterNumber, 1);
if (expected > 0 && actual < expected)
Console.WriteLine($"组 1 有从站未响应: 实际 {actual} / 期望 {expected}"); // Group 1 has an unresponsive slave: actual {actual} / expected {expected}
Diagnostics snapshot
GetSnapshot()
public DiagnosticsSnapshot GetSnapshot()
Fetches everything in one call, saving the per-property read overhead; it suits UI refresh and logging scenarios. Note: the fields are read one after another in sequence and are not a consistent snapshot taken in the same cycle; WkcActual / WkcExpected / WcDeficit come respectively from the user-mode measured live source, the expected live source and the native deficit (the engine topology union takes priority, falling back to the kernel mirror when the engine has not ruled), and subtracting them from one another or cross-checking them against one another is not allowed. To interpret "unknown", use WkcActualKnown / WkcExpectedKnown.
The table below is a quick reference for the common fields; extended fields such as real-time runtime counters, reading flags and recovery observation are in the "Diagnostics snapshot extended fields" section of this page.
Return value:
DiagnosticsSnapshot— diagnostic data snapshot object
Related structure:
public class DiagnosticsSnapshot
{
public int Frequency { get; } // frames per second (Hz)
public uint ErrorCount { get; } // errors per second
public float PacketLossRate { get; } // packet loss rate (0.0-1.0) — TX vs RX, 5-second sliding window
public float LateFrameRate { get; } // late frame rate (0.0-1.0) — an index leaving the 8-frame window is stale, not counted as lost
public double AvgJitterUs { get; } // average bus jitter (µs)
public double MailboxLatencyUs { get; } // mailbox latency - maximum (µs)
public double MailboxLatencyAvgUs { get; } // mailbox latency - average (µs)
public int CycleTimeUs { get; } // actual cycle time (µs)
public ushort WkcActual { get; } // current WKC (0 = both live sources unavailable = unknown)
public bool WkcActualKnown { get; } // whether the measured WKC is backed by measured evidence (0 is meaningless when false)
public ushort WkcExpected { get; } // expected WKC (0 = unknown)
public bool WkcExpectedKnown { get; } // whether the expected WKC is backed by measured evidence
public int WcDeficit { get; } // WKC deficit (engine first / kernel-mirror fallback; not expected − actual)
public bool WkcTripleConsistent { get; } // always false: the three fields are not a same-cycle-consistent triple; never subtract them
public int MappedSlaveCount { get; } // number of mapped slaves (participating in WKC)
public int WkcActualMirror { get; } // measured WKC mirror
public int WkcExpectedMirror { get; } // expected WKC mirror
public ushort PrimaryWKC { get; } // primary-port WKC
public ushort SecondaryWKC { get; } // secondary-port WKC
public ushort PrimaryExpectedWKC { get; } // expected WKC for frames sent on the primary port
public ushort SecondaryExpectedWKC { get; } // expected WKC for frames sent on the secondary port
public uint BusCycleHz { get; } // bus frequency (Hz)
public double BusLoadPercent { get; } // communication load (%)
public bool PrimaryPortOk { get; } // primary port healthy
public bool SecondaryPortOk { get; } // secondary port healthy
public bool RedundancyActive { get; } // redundancy active
public bool HasWkcMirrorData { get; } // whether WKC mirror data is ready (false when there are no mapped slaves / the expected WKC is unknown)
}
Example:
var snap = master.Diagnostics.GetSnapshot();
Console.WriteLine($"频率: {snap.Frequency} Hz, 抖动: {snap.AvgJitterUs:F2} µs"); // Frequency: {snap.Frequency} Hz, jitter: {snap.AvgJitterUs:F2} µs
Console.WriteLine($"WKC: {snap.WkcActual}/{snap.WkcExpected}");
if (snap.RedundancyActive)
Console.WriteLine("冗余已激活"); // Redundancy activated
Diagnostic control
Properties marked "Yes" require Enabled = true first to start periodic sampling; functions marked "Always on" are always active.
Reset (diagnostic counters)
public void Reset()
Reset all diagnostic statistics at once, including:
- Basic diagnostic statistics (frame errors and so on)
- PDO frame loss statistics
- DC synchronization window statistics
- Port error counters of all slaves
It clears only master-level statistics and does not affect the FSoE safety connection state machine (slave.FSoE.Reset).
AL error classification
Classifies the AL Status Code to help judge the nature of an error and the handling strategy quickly.
ALErrorClassifier.Classify
public static ALErrorCategory Classify(ushort alStatusCode)
public static ALErrorCategory Classify(EcALState alState)
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. Both the ushort and EcALState parameter types are supported.
The classification rules are provided uniformly by the SDK; ALErrorClassifier.Classify only maps int → ALErrorCategory (0=None / 1=Transient / 2=Configuration / 3=Hardware / 4=Unknown) and holds no local classification table. It returns Unknown when the SDK is unavailable.
Parameters:
alStatusCode(ushort) oralState(EcALState) — AL Status Code, obtained fromslave.ErrorCodeor when a state transition fails
Return value:
ALErrorCategory— error category enumeration
Related structure:
None(0) — no errorTransient(1) — transient error; retry the state transition, it usually recovers automaticallyConfiguration(2) — configuration error; check the PDO mapping, SM configuration, Startup parameters and so onHardware(3) — hardware error; check the slave hardware, cable and power supplyUnknown(4) — unknown error; consult ETG.1000 or the slave manual
Example:
var slave = master.Slaves[1];
if (slave.ErrorCode != EcALState.NoError)
{
var category = ALErrorClassifier.Classify(slave.ErrorCode);
Console.WriteLine($"从站 {slave.SlaveNum} 错误 0x{(ushort)slave.ErrorCode:X4}: {category}"); // Slave {slave.SlaveNum} error 0x{(ushort)slave.ErrorCode:X4}: {category}
switch (category)
{
case ALErrorCategory.Transient:
Console.WriteLine("瞬态错误,尝试重新切换状态..."); // Transient error, retrying the state transition...
break;
case ALErrorCategory.Configuration:
Console.WriteLine("配置错误,请检查 PDO/SM 配置"); // Configuration error, check the PDO/SM configuration
break;
case ALErrorCategory.Hardware:
Console.WriteLine("硬件错误,请检查从站设备"); // Hardware error, check the slave device
break;
}
}
0x0024invalid input mapping (InvalidInputMapping) — Configuration0x0025invalid output mapping (InvalidOutputMapping) — Configuration0x0015invalid mailbox configuration in BOOT state (InvalidMailboxConfig) — Configuration0x001Asynchronization error (SyncError) — Configuration0x001BSM watchdog (SyncManagerWatchdog) — Transient0x0034DC synchronization timeout (DcSyncTimeout) — Transient0x0051EEPROM error (EepromError) — Hardware
Slave error counters
ReadSlaveErrorCounters(int slaveIndex)
public SlaveErrorCounters ReadSlaveErrorCounters(int slaveIndex)
Reads the error counter summary of the specified slave (CRC errors, frame errors, lost frame statistics).
Parameters:
slaveIndex(int) — slave index (1-based)
Return value:
SlaveErrorCounters— error counter summary
Related structure:
public class SlaveErrorCounters
{
public int SlaveIndex { get; } // slave index
public uint Port0CrcErrors { get; } // port 0 CRC errors
public uint Port1CrcErrors { get; } // port 1 CRC errors
public uint Port2CrcErrors { get; } // port 2 CRC errors
public uint Port3CrcErrors { get; } // port 3 CRC errors
public uint FrameErrors { get; } // frame error count
public uint LostFrames { get; } // lost frame count
}
Example:
var counters = master.Diagnostics.ReadSlaveErrorCounters(1);
if (counters.Port0CrcErrors + counters.FrameErrors + counters.LostFrames > 0)
{
Console.WriteLine($"从站 1 错误计数:"); // Slave 1 error counters:
Console.WriteLine($" CRC 错误: P0={counters.Port0CrcErrors}, P1={counters.Port1CrcErrors}, P2={counters.Port2CrcErrors}, P3={counters.Port3CrcErrors}"); // CRC errors: P0={counters.Port0CrcErrors}, P1={counters.Port1CrcErrors}, P2={counters.Port2CrcErrors}, P3={counters.Port3CrcErrors}
Console.WriteLine($" 帧错误: {counters.FrameErrors}"); // frame errors: {counters.FrameErrors}
Console.WriteLine($" 丢帧: {counters.LostFrames}"); // frame loss: {counters.LostFrames}
}
Diagnostic messages
slave.CoE.ReadDiagnosticMessages()
public List<DiagnosticMessage> ReadDiagnosticMessages()
Reads the diagnostic messages in slave object 0x10F3 (diagnostic history object, ETG.1020) over CoE. Returns the list of diagnostic events recorded by the slave, including timestamp, error code and description.
Access path: slave.CoE.ReadDiagnosticMessages()
Return value:
List<DiagnosticMessage>— list of diagnostic messages; an empty list when there are none
Example:
foreach (var slave in master.Slaves)
{
var messages = slave.CoE?.ReadDiagnosticMessages();
if (messages == null || messages.Count == 0) continue;
foreach (var msg in messages)
{
Console.WriteLine($"[从站 {slave.SlaveNum}] " + // [Slave {slave.SlaveNum}]
$"代码=0x{msg.DiagCode:X8}, {msg}"); // code=0x{msg.DiagCode:X8}, {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.
Diagnostic field guide by problem
This chapter is organised by on-site symptom to help you locate the problem. Every field has a real data source; there is no fake data that is always 0.
Site problem → field mapping
- Packet loss? —
LostFrames+PacketLossRate - Sporadic or persistent? —
master.Groups[g].ConsecutiveMiss(≥5 = persistent) - Which slave is unstable? —
SlaveDiagnosticsData.SlaveOfflineCount[i](cumulative offline count) - Unstable cable contact? —
SlaveDiagnosticsData.SlaveLostLinks[i](link jitter count) - CRC / signal problem? —
SlaveDiagnosticsData.SlaveInvalidFrames[i](CRC / invalid frame count) - Which cable is broken? —
BreakPoint(locates the specific slave and port) - Are primary and secondary TX/RX balanced? —
PrimaryPortTxvsPrimaryPortRx - Is redundancy protection really running? —
RedundancyActive(already includesRingMode>=1and frames on both ports); to confirm only "do both ports carry frames" look atPrimaryPortTx/Rx+SecondaryPortTx/Rx - Is the real-time runtime stable? —
WdkDropouts - DC synchronization accuracy? —
master.GetMaxSyncDifference()/master.MaxSyncDifferenceNs(int?tri-state:null= cannot read / slave table incomplete,-1= no DC-active slave,>= 0= measured ns. The legacyGetMaxSyncDifferenceLegacy()collapsesnullinto-1, making a read failure indistinguishable from no DC) - Is the bus bandwidth sufficient? —
BusLoadPercent
Frame error statistics (TX vs RX)
Frames sent by the master vs frames received back; the difference is the loss. The most important network-layer diagnostic.
LostFrames(uint) — frames that never came backTimeoutFrames(uint) — no response received within the PDO cycle (fallback classification)TotalWkcMismatches(uint) — cumulative WKC mismatches (frames received but not all slaves responded)master.Groups[g].ConsecutiveMiss(ushort) — consecutive WKC shortfall count (the core of telling sporadic from persistent; queried per group)FrameErrors(uint) — derived = LostFrames + Timeout + WkcErrorsChecksumErrors(uint) — physical-layer CRC errors (derived from the slave port CRC / invalid frame counts)
Port TX/RX counters
Diagnose whether primary and secondary TX/RX are balanced (the core of redundancy diagnostics).
PrimaryPortTx/PrimaryPortRx— cumulative frames sent / received on the primary NICSecondaryPortTx/SecondaryPortRx— secondary NIC (redundancy mode)PrimaryPortErrors/SecondaryPortErrors— port errors over the 5-second sliding window
How to read it:
PrimaryPortTx == PrimaryPortRx→ primary path OKPrimaryPortTx > PrimaryPortRx→ frame loss on the primary pathSecondaryPortTx > 0 && SecondaryPortRx > 0→ both ports carry frames; this only means the secondary port is carrying frames, it does not mean redundancy protection is active (a chain with end foldback also has frames on both ports). Whether protection is running is shown byRedundancyActive(RingMode>=1and frames on both ports)SecondaryPortTx > 0 && SecondaryPortRx == 0→ frames do not come back on the secondary path
Per-slave physical-layer errors
Pinpoint which slave and which cable has the problem. Collected from the slaves by the master every second and accumulated.
Access it through the SlaveDiagnosticsData object returned by master.GetDiagnostics():
SlaveRxErrors[i](uint[]) — physical receive failure countSlaveInvalidFrames[i](ushort[]) — CRC / invalid frame countSlaveLostLinks[i](ushort[]) — link loss count (unstable cable contact)SlaveLinkQualityPercent[i](short[]) — link quality computed by the SDK (0-100, -1=unknown)
Index is 1-based; [0] is unused.
Slave offline statistics
Identify the most unstable slave and tell "momentary jitter" from "long-term drop-out".
SlaveOfflineCount[i]— cumulative offline count of slave i (since boot)SlaveOfflineTotalMs[i]— cumulative total offline time of slave i (ms)
How to read it:
- 100 dips + 300 ms = unstable contact (3 ms per dip on average)
- 1 drop-out + 5000 ms = a long disconnection that then recovered
Real-time performance and runtime stability
BusCycleHz— actual frame transmission frequencyBusMaxJitterUs / BusAvgJitterUs / BusCleanMaxJitterUs— bus jitterBusRoundtripUs(RTT) — frame round-trip delayBusLoadPercent— communication load = RTT / cycle (>70% requires reducing the frequency)SmiCount / SmiPeakUs— system management interrupt (BIOS / hardware) interferenceWdkDropouts— number of real-time runtime drop-outs (a heartbeat not updated for 5 seconds counts as 1)
Persistent vs sporadic classification
Derived from the master.Groups[g].ConsecutiveMiss threshold:
- 0 → healthy
- 1-4 → sporadic (USB NIC jitter, usually recoverable)
- ≥5 → persistent (a real problem that must be investigated)
Complete diagnostics procedure example
var diag = master.Diagnostics;
var slaveDiag = master.GetDiagnostics();
// 1. Persistent vs sporadic (query the consecutive WKC shortfall count per group)
ushort consecutiveMiss = master.Groups[1].ConsecutiveMiss;
if (consecutiveMiss >= 5)
Console.WriteLine($"⚠️ 持续 WKC 错误 ({consecutiveMiss})"); // ⚠️ Persistent WKC errors ({consecutiveMiss})
else if (consecutiveMiss > 0)
Console.WriteLine($"偶发 WKC 错误, 一般可恢复"); // Occasional WKC errors, usually recoverable
// 2. Packet loss rate
if (diag.PacketLossRate > 0.01)
Console.WriteLine($"⚠️ 丢包率 {diag.PacketLossRate:P2} 严重"); // ⚠️ Packet loss rate {diag.PacketLossRate:P2} is severe
// 3. Fault location — BreakPoint gives the slave and port directly
var bp = diag.BreakPoint;
if (bp != null)
Console.WriteLine($"故障点: {bp}"); // Fault point: {bp}
// 4. Find the most unstable slave
if (slaveDiag?.SlaveOfflineCount != null)
{
int worst = 0; uint worstCount = 0;
for (int i = 1; i < slaveDiag.SlaveOfflineCount.Length; i++)
if (slaveDiag.SlaveOfflineCount[i] > worstCount)
{ worstCount = slaveDiag.SlaveOfflineCount[i]; worst = i; }
if (worstCount > 0)
Console.WriteLine($"最不稳定从站: #{worst} ({worstCount} 次, {slaveDiag.SlaveOfflineTotalMs[worst]} ms)"); // Least stable slave: #{worst} ({worstCount} times, {slaveDiag.SlaveOfflineTotalMs[worst]} ms)
}
// 5. Physical-layer CRC location
if (slaveDiag?.SlaveInvalidFrames != null)
{
for (int i = 1; i < slaveDiag.SlaveInvalidFrames.Length; i++)
if (slaveDiag.SlaveInvalidFrames[i] > 0)
Console.WriteLine($"从站 {i} CRC 错: {slaveDiag.SlaveInvalidFrames[i]}"); // Slave {i} CRC errors: {slaveDiag.SlaveInvalidFrames[i]}
}
// 6. Bus bandwidth
if (diag.BusLoadPercent > 70)
Console.WriteLine($"⚠️ 总线负载 {diag.BusLoadPercent:F1}%, 必须降频"); // ⚠️ Bus load {diag.BusLoadPercent:F1}%, the rate must be reduced
// 7. Real-time runtime drop-outs
if (slaveDiag?.WdkDropouts > 0)
Console.WriteLine($"⚠️ 实时运行时失联 {slaveDiag.WdkDropouts} 次"); // ⚠️ Lost contact with the real-time runtime {slaveDiag.WdkDropouts} times