Skip to main content

Master diagnostics

Access all diagnostics, monitoring and statistics through master.Diagnostics.​

Use with events

Drive exception handling from events instead of polling on your own.
Reading diagnostic properties directly suits UI display and similar scenarios.

Feature overview​

FeatureDescription
Communication and performance statisticsFrame counts, packet loss, jitter, PDO frame loss, port status, topology
DC synchronizationSync window threshold, DCSyncLost event
Redundancy statusRedundancy active, fault point detection (link break and CRC fault location)
Diagnostic controlStart and stop data collection, reset statistics

Communication and performance statistics​

CategoryPropertyTypeAccessEnable controlDescription
Frame countsRTcntintRead-onlyYesFrames per second (Hz), 5-second average
ErrorCntuintRead-onlyYesErrors per second, 5-second average
PacketLossRatefloatRead-onlyYesPacket 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
LateFrameRatefloatRead-onlyYesLate frame rate (0.0~1.0) — an index that leaves the 8-frame window is stale and not counted as packet loss
Cycle and jitterCycleTimeSpanintRead-onlyYesActual 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.
CycleCountulongRead-onlyAlways onCycle counter, incremented on every bus cycle.
AvgJitterUsdoubleRead-onlyYesAverage 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.
RTcntintRead-onlyYesFrames 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 latencyMailboxLatencyUsdoubleRead-onlyYesMailbox 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)
MailboxLatencyAvgUsdoubleRead-onlyYesMailbox latency — average (µs). Average round-trip time of the same transactions (settled over the last second)
PDO frame lossPDO.TotalLostuintRead-onlyAlways onTotal lost frames (sum of all groups)
PDO.ConsecutiveLostuintRead-onlyAlways onCurrent consecutive lost frames (maximum across all groups)
PDO.GetFrameLossStats(byte group)PDOFrameLossStatsRead-onlyAlways onGet 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 anomaliesWorstSlaveIndexushortRead-onlyAlways onSlave index with the highest error rate
WorstLinkQualityshortRead-onlyAlways onCommunication health of the worst slave (%), lower is worse; -1 = unknown
Master truth values / input validityLostSlaveCountintRead-onlyAlways onLost-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)
LostSlaveCountKnownboolRead-onlyAlways onWhether LostSlaveCount has a measured sample; when false the -1 carries no meaning and must be shown as "unknown"
NoProcessDataboolRead-onlyAlways onMaster-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)
NoProcessDataKnownboolRead-onlyAlways onWhether NoProcessData has a measured sample; when false the return value carries no meaning and must be shown as "unknown"
ProbeAliveCountintRead-onlyAlways onProbe truth summary — number of slaves with a real reply (0 when there is no true-value sample)
ProbeUnknownCountintRead-onlyAlways onProbe truth summary — number of slaves with insufficient evidence (unknown) (0 when there is no true-value sample)
StaleInputCountintRead-onlyAlways onNumber of slaves whose input data is confirmed STALE; Unknown/Degraded are not counted; -1 = a slave read failed / unavailable (use together with StaleInputCountKnown)
StaleInputCountKnownboolRead-onlyAlways onWhether StaleInputCount has a complete measured sample; when false the -1 carries no meaning
Topology changesTopologyFingerprintulongRead-onlyAlways onTopology fingerprint (stable hash of the slave count + each slave's VendorId/ProductId/RevId); a changed fingerprint = the topology changed; TopologyFingerprintKnown says whether sampling succeeded
TopologyFingerprintKnownboolRead-onlyAlways onWhether the topology fingerprint has been sampled successfully at least once; when false the value carries no meaning
TopologyChangeCountulongRead-onlyAlways onNumber of observed topology changes (the first sampling is not counted; observed on read, several changes between two reads are merged into one)
LastTopologyChangeUtcDateTime?Read-onlyAlways onTime of the most recently observed topology change (UTC); null = no change observed yet
WKCWKCushortRead-onlyAlways onCurrent working counter (actual WKC). WKC ≠ ExpectedWKC means a slave is not responding correctly
ExpectedWKCushortRead-onlyAlways onExpected working counter (expected WKC). A fixed value determined at configuration time / when entering OP; it is never lowered dynamically to accommodate a degraded bus
PrimaryWKCushortRead-onlyAlways onPrimary-port working counter (tracked independently in redundancy mode)
SecondaryWKCushortRead-onlyAlways onWKC 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
SecondaryWkcKnownboolRead-onlyAlways onWhether 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
SecondaryWkcRtushortRead-onlyAlways onReal-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
PrimaryExpectedWKCushortRead-onlyAlways 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
SecondaryExpectedWKCushortRead-onlyAlways 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
PrimaryWkcRtushortRead-onlyAlways onReal-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 mirrorWkcActualMirrorintRead-onlyAlways onMirror 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
WkcExpectedMirrorintRead-onlyAlways onMirror 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
WcDeficitintRead-onlyAlways onWKC 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
MappedSlaveCountintRead-onlyAlways onNumber of mapped slaves (participating in the WKC calculation)
HasWkcMirrorDataboolRead-onlyAlways onWhether 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 statusPrimaryPortOkboolRead-onlyAlways onWhether the primary port is healthy (traffic present and no errors within 5 seconds)
SecondaryPortOkboolRead-onlyAlways onWhether the secondary port is healthy (traffic present and no errors within 5 seconds; always false without redundancy)
PrimaryPortErrorsuintRead-onlyAlways onPrimary-port errors in the last 5 seconds
SecondaryPortErrorsuintRead-onlyAlways onSecondary-port errors in the last 5 seconds
TopologyTopologyDescriptionstringRead-onlyAlways onTopology mode description ("line" / "ring" / "ring + branch")
TimingModeCodeuintRead-onlyAlways onRaw value of the current timing mode
TimingModeDescriptionstringRead-onlyAlways onText of the current timing mode ("hardware timer" / "RT ready" / "degraded" / "RT error"). The real-time runtime must be ready before operation
DC synchronizationSyncWindowThresholdintRead/writeAlways onSynchronization window threshold (ns), default 1000 ns. Exceeding the threshold triggers the DCSyncLost event
Redundancy statusRedundancyActiveboolRead-onlyAlways onRedundancy 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
RedundancyRingModeRingModeRead-onlyAlways onRedundant ring operating mode; the RingMode property is a compatibility alias
BreakPointBreakPointInfo?Read-onlyAlways onCurrent 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 controlEnabledboolRead/writeDiagnostic data collection switch (off by default). When enabled, samples periodically and records the statistics marked [Yes]

Calculation formulas​

MetricFormulaDescription
RTcntFrames in the sampling period / window secondsSliding-window average frame rate
ErrorCntErrors in the sampling period / window secondsSliding-window average error rate
PacketLossRate(TX-RX-pipeline) / TX5-second sliding-window packet loss rate; frames in flight on the full-duplex pipeline do not count as lost
LateFrameRateLateDrop / TXLate frame rate (an index that leaves the 8-frame window is stale and not counted as packet loss)

Requires Enabled = true.

PDOFrameLossStats structure
CategoryPropertyTypeAccessDescription
Frame loss statisticsTotalLostuintRead-onlyTotal lost frames
ConsecutiveLostuintRead-onlyCurrent consecutive lost frames
MaxConsecutiveLostuintRead-onlyMaximum 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}
Slave communication diagnostics

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.
  • WcDeficit is 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 subtract WkcExpectedMirror − WkcActualMirror yourself: 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 > 0 is not a master fault: a mapped slave is not contributing WKC right now (suspected lost slave / Hot-plug recovery). Once the slave recovers, WcDeficit returns 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;
Per-slave WKC contribution

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.

CategoryMemberTypeAccessDescription
Redundancy WKCSecondaryWKCushortRead-onlySecondary-port WKC measured in this cycle. Returns 0xFFFF (= WkcUnknown) when this cycle has no fresh measurement
Redundancy WKCMasterDiagnosticsInfo.WkcUnknownconst ushortRead-only"No measurement" sentinel, value 0xFFFF
Redundancy WKCSecondaryWkcKnownboolRead-onlyWhether this cycle has a measurement. false only means SecondaryWKC == 0xFFFF
Redundancy WKCSecondaryWkcRtushortRead-onlyReal-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.

CategoryMemberReturnsAccessDescription
Entrymaster.Diagnostics.TruthMasterTruthSnapshotRead-onlyAssembles one cycle per get; equivalent to CaptureTruthSnapshot()
Entrymaster.Diagnostics.CaptureTruthSnapshot()MasterTruthSnapshotRead-onlyExplicitly 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)

CategoryPropertyTypeDescription
TimingSequencelongSnapshot sequence number, monotonically increasing per master; the same number = the same data from the same cycle
TimingCapturedAtUtcDateTimeAssembly time (UTC)
ScaleSlaveCountintNumber of master table rows (including placeholder rows; no slave is dropped)
WKCWkcExpectedushortFixed expectation from configuration time, never lowered dynamically
WKCWkcActualushortMeasured value in merged terms (primary + secondary under redundancy)
WKCWkcDeficitintexpected - actual; a negative value = measurement above expectation (for example the redundancy merge)
WKCPrimaryWkc / SecondaryWkcushortSingle-port measurements of the primary / secondary port (SecondaryWkc is sWkc)
WKCPrimaryExpectedWkc / SecondaryExpectedWkcushortExpectation for frames sent on the primary / secondary port; 0 when the topology is not identified, falling back to WkcExpected
Process dataNoProcessDataboolMaster-level measurement: true = the cycle runs but process data is dead (false OP)
Lost slavesLostSlaveCountintLost slaves found by bus measurement outside the topology coverage
LinkLinkTruthLinkInfoBoth-port tri-state + redundancy operating mode + derived form (see below)
RedundancySecondaryAdapterConfiguredboolConfiguration fact: whether a secondary NIC is configured. ≠ "a redundancy ring exists"
RedundancySecondaryAdapterBoundboolBinding fact: whether the secondary NIC is actually bound successfully; configured true but false here = configured but not bound, link verdicts are unusable
AttributionAttributionTruthAttributionThe single interpretation of this cycle's facts (see the enumeration table)
AttributionAttributionDetailstringReadable detail (WKC split per port + list of abnormal slaves)
Per slaveSlavesSlaveTruthEntry?[]1-based array, [0] is always null; every access returns a copy
SummaryAliveCountintThe single definition of "alive N/M" = slaves confirmed to contribute process data (slaves with insufficient evidence are not counted)
SummaryLostCountintNumber of slaves with the Offline verdict
SummaryUnknownCountintNumber of slaves with insufficient evidence / unknown (including placeholder rows)

TruthLinkInfo​

(Category: diagnostics / link; access: all read-only)

CategoryPropertyTypeDescription
Physical linkPrimaryPhyLink / SecondaryPhyLinkPhyLinkStatePrimary / secondary port tri-state: Up=1 / Down=0 / Unknown=-1
Redundancy operationRedundancyActiveboolRedundancy protection is running: RingMode>=1 (Dual/Degraded) and both ports carry frame traffic; always false for line / end-foldback topologies
Redundancy operationRingModeRingModeRedundant ring operating mode
Redundancy operationRunModeSemanticsRingRunModeSemanticsTri-state projection of RingMode
Redundancy operationRingModeUnreadbooltrue = the ring mode value could not be read (older SDK / read failure)
TopologyTopologyStateTopologyModelStateTopology model form (the first criterion for form decisions)
TopologyTopologyKnownbooltrue = the model was computed successfully and the form is interpretable
TopologyTopologyUnavailableReasonstringReason the model is unavailable; non-empty when TopologyKnown = false, safe to display directly
TopologyTopologyModeRawintRaw form code of the static port model (0=line / 1=ring / 2=ring + branch); -1 = not obtained
TopologyRuntimeTopologyModeintRuntime form code: 0=line / 1=ring / 2=ring + branch / 3=ring degraded to line; -1 = not obtained
DerivedShapeTruthLinkShapeLink form conclusion (see the enumeration table); Unknown when it cannot be decided

SlaveTruthEntry​

(Category: diagnostics; access: all read-only)

CategoryPropertyTypeDescription
IdentitySlaveIndexintSlave index (1-based)
StateSnapshotPendingboolThe 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
StateLivenessSlaveLivenessStateConfirmed alive / confirmed offline / unknown
StateProbeSlaveProbeStateMeasured probe tri-state
StateContributionWcContributionProcess data contribution tri-state (Contributed / NotContributed / Unknown)
TopologyRingMembershipTopologyRingMembershipWhether the slave is on the redundancy ring (tri-state; unknown must not be treated as "not on the ring")
VerdictVerdictSlaveVerdictFive-state display verdict (single decision source)
VerdictDetailSlaveVerdictDetailVerdict detail (AL state / error flags / false OP flag)
ALStatusEcSlaveStatusMeasured AL state (including the Error bit); meaningless when StatusUnread = true
ALStatusUnreadboolAL not sampled / read failed
ALAlStatusCodeEcALStateSampled AL status code (0 = no error code); meaningless when StatusUnread = true, and must not be treated as "no error"
OfflineOfflineReasonSlaveOfflineReasonOffline 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​

EnumerationValuesMeaning
SlaveLivenessStateUnknown=0 / Alive=1 / Lost=2Insufficient evidence / confirmed process data contribution / offline verdict
SlaveProbeStateNotResponding=0 / Responding=1 / Unknown=2Probe measured missing / measured responding / insufficient evidence
TruthLinkShapeUnknown=0 / SingleLine=1 / RingDual=2 / RingDegraded=3 / TotalLost=4Undecidable / single line / bidirectional redundancy ring / redundancy degraded (ring open / partial ring + branch / single leg running) / both ports lost
TruthAttributionUnknown=0 / Healthy=1 / SlaveLost=2 / SlaveUnreachable=3 / NoProcessData=4 / WkcDeficit=5 / RedundancyCarry=6Insufficient 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
TopologyRingMembershipUnknown=0 / OnRing=1 / NotOnRing=2Model unavailable or does not contain this slave / on the ring / branch or line segment
SlaveVerdictUnknown=0 / RealOp=1 / OpNoProcessData=2 / Abnormal=3 / Offline=4Insufficient 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):

MemberReturnsDescription
MasterTruthSnapshot.ProbeStateOf(int rawProbe)SlaveProbeStateRaw probe value 0/1/2 → tri-state; out-of-range values become Unknown and are never mapped to online
MasterTruthSnapshot.ContributionOf(byte rawWcState)WcContribution0x01 contributed / 0x00 not contributed / anything else unknown
MasterTruthSnapshot.ContributionOf(bool? pdAliveConfirmed)WcContributiontrue / false / null → contribution tri-state
MasterTruthSnapshot.ClassifyOfflineReason(SlaveProbeState, WcContribution)SlaveOfflineReasonProcess data still contributed → Unreachable; confirmed not contributed → RealOffline; contribution unknown and probe missing → RealOffline; otherwise Unknown
Same-cycle sharing

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​

CategoryMemberTypeAccessDescription
Per-slave PDmaster.Diagnostics.SlavePdAliveint[]Read-onlyRaw 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 PDmaster.Diagnostics.SlavePdTruthint[]Read-onlyDisplay 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 probemaster.Diagnostics.SlaveProbeAliveint[]Read-onlyProbe tri-state encoding: 1 = online / 0 = missing / 2 = unknown
Verdict inputSlaveVerdictInput.PdAliveConfirmedbool?Read/write (filled by the caller)Per-slave confirmed contribution raw bit; display / diagnostic input only, not part of the offline red verdict
Do not mix the two PD scales

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.

Read-only verdict, not part of control

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​

CategoryMemberReturnsAccessDescription
Diagnosticsmaster.Diagnostics.RealOpTruthMasterRealOpTruthRead-onlyCaptures one cycle; equivalent to CaptureRealOpTruth()
Diagnosticsmaster.Diagnostics.CaptureRealOpTruth()MasterRealOpTruthRead-onlyCaptures one cycle of real OP truth (master level + per slave)
Diagnosticsmaster.Diagnostics.EvaluateSlaveRealOp(slave)SlaveRealOpState?Read-onlySingle-slave verdict; null = cannot evaluate, reported honestly as unknown
Diagnosticsmaster.Diagnostics.EvaluateRealOp(evidence, wkcActual, wkcExpected)MasterRealOpTruthRead-onlyEvaluates 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​

ValueNameMeaning
0OkReal OP: both the per-slave and master-level thresholds pass
1AlNotCleanA required slave has not reached a clean OP (not OP, an error flag is set, or it is judged offline)
2NoContributionHistorical reason code: no longer produced by the per-slave verdict (the value is kept for compatibility)
3UnstableHistorical reason code: no longer produced by the per-slave verdict (the value is kept for compatibility)
4WkcDeficitMaster level: all required slaves reach real OP, but the merged measured WKC is below the fixed expectation
5UnknownInsufficient evidence (verdict unavailable / no master context / no required slaves)

Result structure​

MasterRealOpTruth (category: diagnostics; access: read-only)

FieldTypeDescription
SequencelongEvaluation sequence number, monotonically increasing per master
RealOpboolMaster-level real OP
ReasonRealOpReasonMain reason the master-level verdict does not hold
RequiredCountintNumber of required slaves
RealOpCountintNumber of required slaves in per-slave real OP
FailedCountintNumber of required slaves that have not reached real OP
WkcActualintMerged measured WKC (as measured)
WkcExpectedintFixed expected WKC from configuration time (never lowered)
WkcDeficitintDeficit = expected − actual (≤0 means no deficit)
SlavesIReadOnlyList<SlaveRealOpState>Per-slave results
DetailTextstringReadable detail (master conclusion + list of slaves that fell short + WKC comparison)

SlaveRealOpState (category: diagnostics; access: read-only)

FieldTypeDescription
SlaveIndexintSlave index (1-based)
RequiredboolWhether it participates in the master-level verdict (not optional and has PDO)
AlCleanOpboolWhether 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
ContributedboolThis cycle has a WKC contribution — display evidence only, not part of the verdict
StableStreakintConsecutive satisfied count at the display layer (anti-flap only, not part of the verdict; not a decision threshold)
RealOpboolThe slave is in real OP
ReasonRealOpReasonReason it does not hold (Ok when it is in real OP)
DetailstringReadable 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.

This is an explicit user re-baseline, not a hot-plug trigger

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)
  • 0 success; -20 another rebuild is in progress; -21 the rescan found 0 reachable slaves (R0: do not blame the link); -23 slaves present but not in OP; -25 resources 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}
The managed slave table follows automatically

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​

MemberReturnsDescription
PrimaryPhyLinkState / SecondaryPhyLinkStatePhyLinkStatePhysical 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
SecondaryFrameLinkStatePhyLinkStateFrame-level link tri-state of the secondary port; use it separately from the physical link reading
PhyLinkBitMaskuintBitmap 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).

CategoryPropertyReturnsAccessDescription
Foldback topologyTopoP1FoldbackModeintRead-only0=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 topologyTopoP1ModeintRead-onlyCompatibility alias of TopoP1FoldbackMode, with exactly the same values and semantics
Foldback topologyTopoP1MeasuredintRead-only1 = on-site topology was measured in this cycle; 0 = not measured in this cycle; -1 = invalid master index
Foldback topologyTopoP1RingEndAdpintRead-onlySlave address of the foldback position; -1 = unavailable (not calibrated / not dual NIC ring + branch / invalid index)
Foldback topologyTopoP1FullWkcintRead-onlyMeasured full WKC at that foldback position; -1 = same as above
Foldback topologyTopoMeasuredRingCountintRead-onlyMeasured number of slaves on the ring; branch count = TopoP1FullWkc - this value; -1 = same as above
Slave levelmaster.Slaves[n].P1FoldbackOnlyintRead-only1 = 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.

Single slave

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.

MemberTypeCategoryAccessUnavailable indicationDescription
MasterIndexushortDC diagnosticsRead-only—Master index
CapturedAtUtcDateTimeDC diagnosticsRead-only—Assembly time of this cycle (UTC)
HasDcboolDC diagnosticsRead-onlywith HasDcKnownWhether the network has slaves with DC capability (capability bit scale)
HasDcKnownboolDC diagnosticsRead-only—false = slave enumeration / capability read failed; HasDc = false then does not mean "the bus really has no DC slaves"
AllInSyncbool?DC diagnosticsRead-onlynull = 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
MaxDriftNsint?DC diagnosticsRead-onlynull = no usable window (not 0)Maximum absolute synchronization difference among all usable windows (ns); the reference clock itself is not counted
SyncWindowThresholdNsint?DC diagnosticsRead-onlynull = cannot readSynchronization window threshold (ns)
ReferenceClockDcReferenceClockInfoDC diagnosticsRead-onlyexplicit None instance / Tier = UnknownReference clock facts: SlaveIndex (0 = none), Tier, TierText, IsChainHeadFallback, Known
ArmedSlaveCountintDC diagnosticsRead-only0 is a valid countNumber of slaves with Sync0Armed == true
ActiveSlaveCountintDC diagnosticsRead-only0 is a valid countNumber of slaves with DC in effect
ArmedUnknownCountintDC diagnosticsRead-only0 is a valid countNumber of slaves with an unknown armed verdict
ArmedSyncParticipantCountintDC diagnosticsRead-only0 = no slave on which a synchronization conclusion can be drawnNumber of participant slaves that are armed and are not the reference clock
ApplicableWindowCountintDC diagnosticsRead-only0 = MaxDriftNs is nullNumber of slaves with a usable measured window
ActiveWithoutProcessDataCountintDC diagnosticsRead-only0 is a valid countNumber of slaves with DC in effect but without process data bytes
ExpectedWkcushortDC diagnosticsRead-only—Master expected WKC (fixed value from configuration time); compare it with ArmedSlaveCount to see the WKC coverage of DC slaves
PropagationDelayResolvedAtUtcDateTime?DC diagnosticsRead-onlynull = not observed by this processTime of the most recent successful propagation delay resolution actively triggered by the SDK; not the same as the physical measurement time
PropagationDelayResolveCountintDC diagnosticsRead-only0 = not observedNumber of successes on the same accounting scale
Slaves / Find(index)DcSlaveSnapshot[] / DcSlaveSnapshot?DC diagnosticsRead-onlyFind out of range / not sampled → nullPer-slave snapshot (ascending by slave index); Find is an O(1) lookup
AnyReadFailureboolDC diagnosticsRead-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.

The snapshot is not an online sample

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:

TypeFaultTypeDetectionTypical scenario
Link break0Port physical link lostCable unplugged, cable broken
CRC fault1Port error count keeps risingPoor contact, aged cable, oxidized connector
Break point query tri-state: 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 = true means the query succeeded, and only then does a false return 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
ValueNameDescription
-1UnknownUnknown: unreadable / out-of-range value; must not be folded into Inactive
0InactiveNot active: redundancy monitoring is not initialized
1DualBidirectional redundancy: both ports transmit, normal operation
2DegradedDegraded mode: the secondary link is unavailable, only the primary works
BreakPointInfo structure
CategoryPropertyTypeAccessDescription
Fault locationSlaveIndexushortRead-onlyFaulty slave index (1-based)
PortbyteRead-onlyFaulty port number (0-3, corresponding to P0-P3)
FaultTypebyteRead-onlyFault type: 0 = link break, 1 = CRC fault
IsLinkDownboolRead-onlyWhether it is a link break fault
IsCrcFaultboolRead-onlyWhether 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:

ModelData sourceValuesPurpose
Static port modelComputed uniformly by the SDK; the legacy interface stays compatibleForm 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 modelRuntimeTopologyMode0 / 1 / 2, plus 3 = ring degraded to lineCaptures "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):

CategoryMemberTypeDescription
ScaleTotalCountintTotal number of slaves in the model
ScaleRingCountintNumber of ring members; usable only when ModelKnown = true
ScaleBranchCountintBranch count = TotalCount - RingCount; likewise usable only when ModelKnown
FormStateTopologyModelStateForm after the strict mapping; unrecognized values → Unknown
FormModestringReadable form: "line" / "ring" / "ring + branch" / "unknown"
FormModeRawintRaw form code (0=line / 1=ring / 2=ring + branch); -1 = not obtained
FormModelKnownboolWhether the SDK computed the model successfully; when false all ring membership fields below are unusable
FormUnavailableReasonstringReason the model is unavailable; non-empty when ModelKnown = false, safe to display directly
FormChainFormTopologyChainForm"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
ClosureClosureSlaveNumintSlave 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 slaveRingSlaveNumsHashSet<int>Set of slave indices that are ring members
Per slaveIsRing(int)booltrue = on the ring. Returns false when the model is unknown, which only means "unknown", not "not on the ring"
Per slaveRingMembershipKnownboolWhether the ring member list is trustworthy (model known and form interpretable)
Per slaveTryIsRing(int, out bool)boolTri-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)

ValueNameMeaning
0UnknownModel not computed / SDK unavailable / mode outside the contract — unknown, no guessing
1LinearLine (no closure point, the ring covers 0 slaves)
2RingRing (the ring covers all slaves)
3RingBranchRing + 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.

ValueNameMeaning
0UnknownNot applicable — ring / ring + branch / unknown model / SDK unavailable / out-of-range value. Not "line"
1LinearPure line: all slaves in series, the end is one active port with no foldback
2FoldbackChain (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
Meaningful only under Linear

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.

CategoryEntry pointTypeAccessDescription
Topologyslave.TryGetReachableLegs(slaveNum, out ReachableLegs legs)public C# projectionRead-onlyPer-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
DiagnosticsMasterTruthSnapshot.TryReadNativeOfflineReason(master, slave, out int nativeReason)public static methodRead-onlyReturns 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
Diagnosticsmaster.Diagnostics.RealOpTruth / CaptureRealOpTruth()MasterRealOpTruthRead-onlyVerdict results for clean OP and real OP
Diagnosticsslave.Sync0Armed (bool?, null = cannot decide)public propertyRead-onlyPer-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
Unified contract (all queries use the same scale)
  • 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.Unknown never 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

ValueNameMeaning
0UnknownInsufficient evidence to prove which leg can reach — not "neither leg can reach"; fail-safe treats it as no re-routing / no duplicate transmission
1PrimaryOnlyReachable through the primary leg only
2SecondaryOnlyReachable through the secondary leg only
3BothReachable 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.

  • armed only 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.

ValueNameMeaning
0UncalibratedMonitoring not initialized / not running; you can say neither "redundant" nor "line"
1RedundantRunningDual-path redundancy confirmed running
2DegradedThe ring exists but only one leg is running
3UnreadableCannot 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".

ValueNameMeaning
0UnknownModel unavailable / not calibrated / read failed — unknown whether the secondary port carries a protection path
1NoProtectionPathThe model confirms there is no protection path (line / single NIC / ring covers 0 slaves)
2ProtectionPathThe 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 (TopologyRingMembership tri-state).
  • The slave-level link protection form uses slave.ProtectionState (SlavePathProtection), and reachable legs use slave.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.

CategoryPropertyTypeAccessDescription
Cycle and jitterBusCycleReadStateDiagnosticsReadStateRead-onlyRead 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 jitterCycleStateCycleRunStateRead-onlyTri-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 jitterHasBusCycleSampleboolRead-onlyWhether 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 jitterCyclicLostFrameCountuintRead-onlyCumulative 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
RuntimeIsWdkMappedboolRead-onlyWhether 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
RuntimeLastDiagnosticsReadErrorstringRead-onlyDetails 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
RuntimeWindowsProcessorPerformanceWindowsProcessorPerformanceSnapshotRead-onlyPer-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
ValueNameMeaning
0NotReadyNo usable frequency window sample has been taken yet
1ReadyA real frequency has been sampled and can be used to judge the cycle
2ErrorThe most recent read failed; the value cannot be used as a criterion
CycleRunState enumeration
ValueNameMeaning
0NotStartedThe cycle runtime is not established (after stop / pause); a count of 0 is truthful
1StartedNoAdvanceThe runtime is established but the count did not move within the observation window (stuck, or the cycle stopped advancing)
2AdvancingThe count really was growing within the most recent window
WindowsProcessorPerformanceSnapshot structure
FieldTypeDescription
AvailableboolWhether a usable delta interval was obtained this time. When false you must read Error; never interpret missing data as 0
ErrorWindowsProcessorPerformanceErrorReason 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)
ErrorDetailstringReadable detail of the unavailable reason; null when available
ElapsedTimeSpan?Length of the observation interval between the two reads; null when unavailable
ProcessorsIReadOnlyListSet of delta samples per logical processor; an empty set when unavailable — partial values are never returned
ProcessorCountintNumber 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.

CategoryPropertyTypeAccessDescription
Network and linkWdkPrimaryFrameTxuintRead-onlyCumulative frames sent on the primary port
Network and linkWdkPrimaryFrameRxuintRead-onlyCumulative frames received on the primary port
Network and linkWdkSecondaryFrameTxuintRead-onlyCumulative frames sent on the secondary port
Network and linkWdkSecondaryFrameRxuintRead-onlyCumulative frames received on the secondary port
Network and linkWdkPdoIdxDropCountuintRead-onlyCumulative late frames dropped: the frame arrived but its sequence number had already left the 8-frame window. This is not packet loss
Network and linkWdkWkcMismatchCountuintRead-onlyCumulative WKC mismatch count
Network and linkWdkPrimaryRingFullDropuintRead-onlyDrops caused by the primary receive ring being full
Network and linkWdkSecondaryRingFullDropuintRead-onlyDrops caused by the secondary receive ring being full
Network and linkWdkPrimaryTxBailBusyuintRead-onlyPrimary transmit returned early — resource busy
Network and linkWdkPrimaryTxBailPreallocMissuintRead-onlyPrimary transmit returned early — preallocation miss
Network and linkWdkPrimaryTxFallbackSentuintRead-onlyNumber of times the primary port switched to the fallback transmit path
Network and linkWdkSecondaryTxBailBusyuintRead-onlySecondary transmit returned early — resource busy
Network and linkWdkSecondaryTxBailPreallocMissuintRead-onlySecondary transmit returned early — preallocation miss
Network and linkWdkSecondaryTxFallbackSentuintRead-onlyNumber of times the secondary port switched to the fallback transmit path
Network and linkWdkPrimaryNdisCalluintRead-onlyNumber of receive calls on the primary NIC
Network and linkWdkPrimaryEcatMatchuintRead-onlyNumber of frames on the primary port recognized as EtherCAT frames
Network and linkWdkSecondaryNdisCalluintRead-onlyNumber of receive calls on the secondary NIC
Network and linkWdkSecondaryEcatMatchuintRead-onlyNumber of frames on the secondary port recognized as EtherCAT frames
RuntimeWdkPollCallbackTxTicksuintRead-onlyNumber of entries into the cyclic transmit callback
RuntimeWdkPollCallbackRxTicksuintRead-onlyNumber of wake-ups where the receive-drain wait was satisfied by the deadline timer
RuntimeWdkRtCpuCoreintRead-onlyCPU core the real-time thread is currently bound to; -1 = not started or not readable
RuntimeWdkRxCpuCoreintRead-onlyCPU core the receive-drain thread is currently bound to; -1 = not enabled or not readable
WdkHealthSnapshot structure
CategoryPropertyTypeAccessDescription
Primary transmitPrimaryTxSubmitteduintRead-onlyPrimary transmit submissions
Primary transmitPrimaryTxCompleteduintRead-onlyPrimary transmit completions
Primary transmitPrimaryTxFaileduintRead-onlyPrimary transmit failures
Primary transmitPrimaryTxBailNotConnuintRead-onlyPrimary transmit returned early — link not connected
Primary transmitPrimaryTxBailInvaliduintRead-onlyPrimary transmit returned early — invalid parameter
Primary transmitPrimaryTxBailNoPooluintRead-onlyPrimary transmit returned early — no free buffer
Primary transmitPrimaryTxBailBusyuintRead-onlyPrimary transmit returned early — resource busy
Primary transmitPrimaryTxBailPreallocMissuintRead-onlyPrimary transmit returned early — preallocation miss
Primary transmitPrimaryTxFallbackSentuintRead-onlyNumber of times the primary port switched to the fallback transmit path
Primary receivePrimaryRingDropuintRead-onlyPrimary receive ring-full drops
Primary receivePrimaryNdisCalluintRead-onlyNumber of receive calls on the primary NIC
Primary receivePrimaryEcatMatchuintRead-onlyNumber of frames on the primary port recognized as EtherCAT frames
Secondary transmitSecondaryTxSubmitteduintRead-onlySecondary transmit submissions
Secondary transmitSecondaryTxCompleteduintRead-onlySecondary transmit completions
Secondary transmitSecondaryTxFaileduintRead-onlySecondary transmit failures
Secondary transmitSecondaryTxBailNotConnuintRead-onlySecondary transmit returned early — link not connected
Secondary transmitSecondaryTxBailInvaliduintRead-onlySecondary transmit returned early — invalid parameter
Secondary transmitSecondaryTxBailNoPooluintRead-onlySecondary transmit returned early — no free buffer
Secondary transmitSecondaryTxBailBusyuintRead-onlySecondary transmit returned early — resource busy
Secondary transmitSecondaryTxBailPreallocMissuintRead-onlySecondary transmit returned early — preallocation miss
Secondary transmitSecondaryTxFallbackSentuintRead-onlyNumber of times the secondary port switched to the fallback transmit path
Secondary receiveSecondaryRingDropuintRead-onlySecondary receive ring-full drops
Secondary receiveSecondaryNdisCalluintRead-onlyNumber of receive calls on the secondary NIC
Secondary receiveSecondaryEcatMatchuintRead-onlyNumber of frames on the secondary port recognized as EtherCAT frames
SchedulingPollCallbackTxTicksuintRead-onlyNumber of entries into the cyclic transmit callback
SchedulingPollCallbackRxTicksuintRead-onlyNumber of wake-ups where the receive-drain wait was satisfied by the deadline timer
ErrorsPdoIdxDropuintRead-onlyCumulative late frames dropped
ErrorsWkcMismatchuintRead-onlyCumulative WKC mismatch count
ReadingHasTrafficCountersboolRead-onlyAny transmit / receive counter differs from 0, so the counter surface really holds traffic samples
ReadingHasHardErrorsboolRead-onlyAny hard-error counter differs from 0 (WKC mismatch, ring-full drop, early transmit return, transmit failure)
WdkDiagCounter counter id table
idCorresponding memberDescription
1WdkWkcMismatchCountCumulative WKC mismatch count
2WdkPrimaryRingFullDropPrimary receive ring-full drops
3WdkSecondaryRingFullDropSecondary receive ring-full drops
4PrimaryTxBailNotConnPrimary transmit returned early: link not connected
5PrimaryTxBailInvalidPrimary transmit returned early: invalid parameter
6PrimaryTxBailNoPoolPrimary transmit returned early: no free buffer
7WdkPrimaryTxBailBusyPrimary transmit returned early: resource busy
8WdkPrimaryTxBailPreallocMissPrimary transmit returned early: preallocation miss
9WdkPrimaryTxFallbackSentNumber of times the primary port switched to the fallback transmit path
10SecondaryTxBailNotConnSecondary transmit returned early: link not connected
11SecondaryTxBailInvalidSecondary transmit returned early: invalid parameter
12SecondaryTxBailNoPoolSecondary transmit returned early: no free buffer
13WdkSecondaryTxBailBusySecondary transmit returned early: resource busy
14WdkSecondaryTxBailPreallocMissSecondary transmit returned early: preallocation miss
15WdkSecondaryTxFallbackSentNumber of times the secondary port switched to the fallback transmit path
16WdkPollCallbackTxTicksCyclic transmit callback entries
17WdkPollCallbackRxTicksWake-ups where the receive-drain wait was satisfied by the deadline timer
20WdkPrimaryNdisCallNumber of receive calls on the primary NIC
21WdkPrimaryEcatMatchNumber of frames on the primary port recognized as EtherCAT frames
22WdkSecondaryNdisCallNumber of receive calls on the secondary NIC
23WdkSecondaryEcatMatchNumber of frames on the secondary port recognized as EtherCAT frames
24PrimaryTxSubmittedPrimary transmit submissions
25PrimaryTxCompletedPrimary transmit completions
26PrimaryTxFailedPrimary transmit failures
27SecondaryTxSubmittedSecondary transmit submissions
28SecondaryTxCompletedSecondary transmit completions
29SecondaryTxFailedSecondary 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.

CategoryPropertyTypeAccessDescription
Cycle and jitterJitterInstrumentVersionuintRead-onlyVersion of the jitter statistics surface; 0 = the current real-time runtime does not provide this group of fields
Cycle and jitterJitterTotalSamplesulongRead-onlyTotal jitter sample count (equal to the sum of the 7 histogram bucket counts)
Cycle and jitterJitterMinUsdoubleRead-onlyMinimum jitter within the window (µs); returns NaN when the read fails
Cycle and jitterJitterHistogramBinsuint[]Read-onlyCumulative counts of the 7 jitter histogram buckets; bucket boundaries are in the table below
Cycle and jitterDispatchCycleMaxJitterUsdoubleRead-onlyMaximum jitter within the transmit-only cycle window (µs); returns NaN when the read fails
Cycle and jitterDrainCycleMaxJitterUsdoubleRead-onlyMaximum jitter within the receive-drain cycle window (µs); returns NaN when the read fails
Cycle and jitterPathCountFastuintRead-onlyNumber of samples on the full busy-spin path (cycle shorter than 50 µs)
Cycle and jitterPathCountMeduintRead-onlyNumber of samples on the park-and-wait path (cycle between 50 and 250 µs)
Cycle and jitterPathCountSlowuintRead-onlyNumber of samples on the timer-sleep path (cycle not shorter than 250 µs)
Cycle and jitterKtimerWakeNormalCountuintRead-onlyNumber of times the timer wake-up still left margin for cycle calibration
Cycle and jitterKtimerWakeOverrunCountuintRead-onlyNumber of times the timer wake-up was already past the next cycle boundary; a common source of elevated jitter
RuntimeRtPreemptCountulongRead-onlyCumulative number of times the real-time thread was preempted or showed an undecidable large gap
RuntimeRtPreemptPeakNsuintRead-onlyPeak of those large gaps (ns)
RuntimeBigGapUnknownCountulongRead-onlyCumulative number of large gaps that could not be attributed because the hardware SMI count was unavailable
RuntimeSmiMsrAvailableuintRead-onlyWhether the hardware SMI count is available: 0 = unavailable (common on non-Intel platforms or in virtual machines), a value other than 0 = available
RuntimeHardwareSmiCounterAvailableboolRead-onlyBoolean projection of SmiMsrAvailable; false = do not explain jitter with the SMI count
Jitter histogram bucket boundaries
IndexIntervalDescription
0below 1 µsSmallest jitter band
11 to 2 µs—
22 to 5 µs—
35 to 10 µs—
410 to 50 µs—
550 to 100 µs—
6100 µs and aboveLargest 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.

CategoryPropertyTypeAccessDescription
WKCWkcProbeModeintRead-onlyProbe mode: 0 = off (default, no sampling) / 1 = per-slave true-value sampling; returns -1 when the read fails
WKCSlaveWkcProbeActualint[]Read-onlyPer-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
WKCSlaveWkcProbeExpectedint[]Read-onlyWhether 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)
WKCSlaveWkcProbeAgeMsint[]Read-onlyFreshness of the per-slave sample (ms): 0 or above = time since the most recent sample; -1 = never sampled
Slave anomaliesProbeAliveCountintRead-onlyProbe summary: number of slaves with a measured reply; 0 when there is no true-value sample
Slave anomaliesProbeUnknownCountintRead-onlyProbe summary: number of slaves with insufficient evidence; 0 when there is no true-value sample
Sentinel values are not true values

-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.

CategoryPropertyTypeAccessDescription
DiagnosticsNoProcessDataKnownboolRead-onlyWhether NoProcessData has a measured sample. false = read failed or unavailable; NoProcessData has no meaning then and must be shown as "unknown"
DiagnosticsLostSlaveCountKnownboolRead-onlyWhether LostSlaveCount has a measured sample. false = read failed; LostSlaveCount is -1 then and does not mean "zero lost slaves"
A failed read is not health

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.

CategoryPropertyTypeAccessDescription
DiagnosticsSlaveRecoverySlaveRecoveryStatusView[]Read-onlyPer-slave recovery ladder observation, 1-based, [0] unused. An element with Available = false means recovery observation is unavailable for that slave (not "no recovery")
DiagnosticsMasterRecoveryLadderMaster recovery escalation observationRead-onlyMaster-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
DiagnosticsRecoveryLadderSequlongRead-onlyFreshness token of the recovery ladder sequence, monotonically increasing; if it stops growing the recording thread is not advancing; 0 = unavailable
DiagnosticsRecoveryEventsRecoveryEventView[]Read-onlyIncremental recovery events: new events since the previous read. Every read advances the internal cursor, so events are taken away only once
SlaveRecoveryStatusView structure
FieldTypeDescription
Availableboolfalse = recovery observation unavailable (older runtime or no mirror), not "no recovery"
LevelSlaveRecoveryLevelCurrent recovery level
StepSlaveRecoveryStepCurrent step; unrecognized values are passed through unchanged
LastStepSlaveRecoveryStepPrevious step, for tracing transitions
ReasonSlaveRecoveryReasonReason the previous step failed; 0 = none
FailAlscushortMeasured raw AL status code at failure; 0 = none or not read
RetryCountushortConsecutive failure / attempt count in this round; cleared when the slave leaves or returns
BackoffRemainMsuintRemaining slave-level cool-down (ms); 0 = free to move at any time
StepElapsedMsuintTime elapsed in the current step (ms), to tell which step it is stuck at
SkipFramesuintCumulative number of skipped recovery frames
SequlongState transition count, incremented on every transition, for judging mirror freshness
FlagsRawbyteRaw flag byte
PausedAboolLink-break class exception pause handling in progress
NeedsReconfigboolConfiguration not replayed yet
LadderExhaustedboolConsecutive failures have escalated to master-level recovery
EpilogueboolOP epilogue in progress
LastResultOkSlaveRecoveryResultOkResult of the previous step: success / failure / suppressed without running
ClassifySlaveRecoveryClassRecovery classification (A / B1 / B2 / B3); None = not classified yet
IsActiveboolThe ladder is active (not idle, not finished, not an unknown level)
LadderKeystringCross-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
FieldTypeDescription
Availableboolfalse = observation unavailable; true only means the structure was obtained — whether each field has a sample depends on whether that field is null
TriggerBlockedTotaluintCumulative count of "trigger hit but not executed in this round", always a measured value
RebuildReqPendingbool?Rebuild request pending and not consumed; null = not sampled, not "not pending"
RebuildActivebool?Rebuild in progress; null = not sampled
RebuildFailbyte?Consecutive failure count; null = not sampled, not "zero failures"
AlarmOnlybool?Alarm-only tier (after several ineffective attempts, raise an alarm but do not give up); null = not sampled
HandoffBusybool?Orchestration busy; null = not sampled
ASuppressedbool?Link-break class exception suppressed; null = not sampled
BadPersistentbool?The bad state has lasted beyond the criterion; null = not sampled
LadderExhaustedbool?Some slave's consecutive failures have escalated to master-level recovery; null = not sampled
BackoffRemainMsuint?Remaining backoff (ms); null = not sampled, not "no backoff"
BadSinceMsuint?How long the bad state has lasted (ms); null = not sampled
RebuildTotaluint?Cumulative whole-network rebuild count in this session; null = not sampled
Sequlong?State transition count; null = not sampled. Use RecoveryLadderSeq when you need a reliable freshness token
Not sampled is reported as null

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
FieldTypeDescription
SequintGlobal monotonic sequence number, the incremental cursor base (pass this Seq as the next sinceSeq)
SlaveushortSlave index; 0 = master-level event
KindSlaveRecoveryEventKindEvent category (step transition / level transition / power-up return / suppression / throttling / penalty reset and so on)
FromLevel / ToLevelSlaveRecoveryLevelRecovery level before / after the event
FromStep / ToStepSlaveRecoveryStepRecovery step before / after the event
ReasonSlaveRecoveryReasonEvent reason
OkSlaveRecoveryResultOk1 = success / 0 = failure / 2 = suppressed without running
AlscushortMeasured raw AL status code; 0 = none
TickMsuintEvent time (millisecond timer)
IsEscalationboolEscalation 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 returned
  • max (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.

CategoryPropertyTypeAccessDescription
DiagnosticHotSwapRescanCountintread-onlyCompleted automatic rebuild rounds (calls rejected before execution do not count); 0 = never
DiagnosticLastHotSwapRescanResultintread-onlyLast result code. 0 = never happened or last succeeded; see below for negative values
DiagnosticLastHotSwapRescanTimeDateTimeread-onlyLast 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 not an error state

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.

CategoryPropertyTypeAccessDescription
DC diagnosticsDcHasDcboolRead-onlyWhether 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 diagnosticsDcHasDcKnownboolRead-onlyWhether 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 diagnosticsDcReferenceClockSlaveushortRead-onlyReference 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 diagnosticsDcReferenceClockSlaveKnownboolRead-onlyWhether 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 diagnosticsReferenceClockKnownboolRead-onlySame-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
CategoryPropertyTypeAccessDescription
DC diagnosticsCapabilityDcCapabilityRead-onlyDC 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 diagnosticsArmOutcomeDcArmResultRead-onlyFinal conclusion of the automatic DC arming policy at start-up. Unknown = no terminal record at all, which is neither failure nor success
DC diagnosticsSync0CycleNsint?Read-onlyValue actually applied to the SYNC0 cycle register (ns); null = no DC or cannot read; 0 = the cycle value was not applied
DC diagnosticsSync1CycleNsint?Read-onlyValue actually applied to the SYNC1 cycle register (ns); null has the same meaning as above
DC diagnosticsPropagationDelayNsint?Read-onlyValue actually applied for the propagation delay (ns); null = no DC or cannot read
DC diagnosticsPropagationDelayOriginDcPropagationDelayOriginRead-onlyOrigin 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 diagnosticsSyncWindowDcSyncWindowInfoRead-onlySynchronization window (including the unavailable reason and the historical conclusion "reading not updated"). When unavailable, every numeric field is null, not 0
DC diagnosticsJitterDcJitterStats?Read-onlySteady-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 diagnosticsConvergenceMsint?Read-onlyConvergence 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.

CategoryPropertyTypeAccessDescription
Port statusPortLinkStatusbyte[]Read-onlyPort 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 statusLinkQualityPercentuint[]Read-onlyLink 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 statusPortErrorCountuint[]Read-onlyTotal receive errors of each slave port (cumulative). 0 = no port receive error ever occurred, or not sampled yet
Port statusLostLinkCountuint[]Read-onlyCumulative link loss count of each slave. 0 = never lost, or not sampled yet; for the current port link state read PortLinkStatus
Slave anomaliesTotalSlaveRxErrorsuintRead-onlySum of receive errors of all slaves (cumulative). Above 0 = the bus may have a CRC or signal integrity problem
Slave anomaliesTotalSlaveInvalidFramesuintRead-onlySum of invalid frames of all slaves (cumulative); the real source of checksum errors
Slave anomaliesTotalSlaveLostLinksuintRead-onlySum of link losses of all slaves (cumulative). Above 0 = unstable cable or port contact
Slave anomaliesAvgLinkQualityPercentushortRead-onlyAverage link quality of the slaves currently online (1 to 100); 0 = no online sample (unknown), not "the worst link"
The two meanings of 0

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.

CategoryPropertyTypeAccessDescription
Basic informationSlaveNumberintRead-onlySlave index (1-based)
DC diagnosticsDcInSyncboolRead-onlyWhether this cycle is inside the synchronization window. Read DcInSyncValid first: when invalid, a false here does not mean "not synchronized"
DC diagnosticsDcInSyncValidboolRead-onlyWhether 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 diagnosticsDcSyncTimeDifferenceNsintRead-onlyCurrent synchronization error (ns). When DcSyncTimeDifferenceValid is false, 0 has no meaning (0 would be misread as "zero deviation")
DC diagnosticsDcSyncTimeDifferenceValidboolRead-onlyWhether DcSyncTimeDifferenceNs is valid; same source as the window valid bit
DC diagnosticsDcSync0Armedbool?Read-onlyWhether SYNC0 is armed (tri-state). null = cannot decide, which does not equal not armed
DC diagnosticsDcSyncMaxDiffNsintRead-onlyMaximum time difference within the window (ns); valid only when DcSyncWindowValid is true
DC diagnosticsDcSyncMinDiffNsintRead-onlyMinimum time difference within the window (ns); valid only when DcSyncWindowValid is true
DC diagnosticsDcOutOfSyncCountuintRead-onlyCumulative number of excursions outside the synchronization window; valid only when DcSyncWindowValid is true
DC diagnosticsDcSyncWindowValidboolRead-onlyWhether the three window statistics above are valid
DC diagnosticsDcReadFaultedboolRead-onlyWhether the DC diagnostic read failed; sticky until the next successful read
DC diagnosticsDcActiveAssignushortRead-onlyRaw mirror of the AssignActivate register (the ESI configuration value, which does not mean armed). Valid only when DcRegisterFactsValid is true
DC diagnosticsDcCycle0NsintRead-onlyRaw mirror of the SYNC0 cycle register (ns). Valid only when DcRegisterFactsValid is true
DC diagnosticsDcCycle1NsintRead-onlyRaw mirror of the SYNC1 cycle register (ns). Valid only when DcRegisterFactsValid is true
DC diagnosticsDcShiftNsintRead-onlyRaw mirror of the DC phase shift (ns). Valid only when DcRegisterFactsValid is true
DC diagnosticsDcRegisterFactsValidboolRead-onlyWhether 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"
RuntimeHasRequiredRuntimeDataboolRead-onlyWhether the required runtime data for this cycle is complete: the slave index is above 0 and the AL state mirror has been sampled
RuntimeMissingDataReasonstringRead-onlyText of the reason the data is incomplete; an empty string when complete
Where the snapshot's AlStatusCode comes from

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.

CategoryPropertyTypeAccessDescription
WKCWkcActualKnownboolRead-onlyWhether WkcActual has measured evidence; when false its 0 means only unknown and produces no verdict
WKCWkcExpectedKnownboolRead-onlyWhether WkcExpected has measured evidence; when false its 0 means only unknown
WKCWkcTripleConsistentboolRead-onlyAlways 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 jitterJitterInstrumentVersionuintRead-onlyVersion of the jitter statistics surface; 0 = this group of fields is not provided
Cycle and jitterJitterTotalSamplesulongRead-onlyTotal jitter sample count
Cycle and jitterJitterMinUsdoubleRead-onlyMinimum jitter within the window (µs)
Cycle and jitterJitterHistogramBinsuint[]Read-onlyCumulative counts of the 7 jitter histogram buckets
Cycle and jitterDispatchCycleMaxJitterUsdoubleRead-onlyMaximum jitter within the transmit-only cycle window (µs)
Cycle and jitterDrainCycleMaxJitterUsdoubleRead-onlyMaximum jitter within the receive-drain cycle window (µs)
Cycle and jitterPathCountFastuintRead-onlyNumber of samples on the short-cycle path
Cycle and jitterPathCountMeduintRead-onlyNumber of samples on the medium-cycle path
Cycle and jitterPathCountSlowuintRead-onlyNumber of samples on the long-cycle path
Cycle and jitterKtimerWakeNormalCountuintRead-onlyNumber of timer wake-ups that still left margin for calibration
Cycle and jitterKtimerWakeOverrunCountuintRead-onlyNumber of timer wake-ups already past the next cycle boundary
RuntimeRtPreemptCountulongRead-onlyCumulative number of times the real-time thread was preempted or showed an undecidable large gap
RuntimeRtPreemptPeakNsuintRead-onlyPeak of those large gaps (ns)
RuntimeBigGapUnknownCountulongRead-onlyCumulative number of large gaps that could not be attributed because the hardware SMI count was unavailable
RuntimeSmiMsrAvailableuintRead-onlyWhether the hardware SMI count is available; 0 = unavailable
RuntimeWdkRtCpuCoreintRead-onlyCPU core the real-time thread is bound to; -1 = not bound or not readable
RuntimeWdkRxCpuCoreintRead-onlyCPU core the receive-drain thread is bound to; -1 = not enabled or not readable
Network and linkWdkPrimaryFrameTxuintRead-onlyCumulative frames sent on the primary port
Network and linkWdkPrimaryFrameRxuintRead-onlyCumulative frames received on the primary port
Network and linkWdkSecondaryFrameTxuintRead-onlyCumulative frames sent on the secondary port
Network and linkWdkSecondaryFrameRxuintRead-onlyCumulative frames received on the secondary port
Network and linkWdkPdoIdxDropCountuintRead-onlyCumulative late frames dropped
Network and linkWdkHealthWdkHealthSnapshot?Read-onlyHealth counter snapshot of the real-time runtime (one cycle taken while this snapshot was assembled); null = not obtained this cycle
ReadingHasJitterInstrumentationboolRead-onlyWhether the jitter statistics surface is usable (version differs from 0 and sample count above 0)
ReadingHasJitterWindowDataboolRead-onlyWhether the jitter window data is usable (version at least 2 and both maximum / average jitter finite)
ReadingHasPdoFrameCountersboolRead-onlyWhether frame counters were obtained for either path (any send / receive counter above 0)
ReadingHasCpuBindingDataboolRead-onlyWhether the CPU binding of the real-time thread was obtained (bound core number at least 0)
ReadingHasHardwareSmiCounterboolRead-onlyWhether the hardware SMI count is usable
ReadingHasRtGapCountersboolRead-onlyWhether the large-gap counters are usable (same criterion as the jitter statistics surface)
ReadingHasTimingDataboolRead-onlyWhether timing data is usable (timing mode code differs from 0 and cycle time above 0)
ReadingHasBusFrequencyDataboolRead-onlyWhether the bus frequency window is ready (read state is Ready)
ReadingHasWdkDiagnosticsboolRead-onlyWhether 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
ReadingHasRequiredRuntimeDataboolRead-onlyWhether the required runtime data is complete: the missing-item list is empty and the read state is Ready
DiagnosticsReadErrorstringRead-onlyFailure detail when the read state is Error; null otherwise
DiagnosticsMissingDataReasonsstring[]Read-onlyList of missing data items; an empty array = nothing missing
DiagnosticsMissingDataSummarystringRead-onlyOne-line summary of the missing data items; none when nothing is missing
DiagnosticsSlaveRecoverySlaveRecoveryStatusView[]Read-onlyPer-slave recovery ladder observation (1-based; Available = false means the observation is unavailable)
DiagnosticsMasterLadderMasterLadderViewRead-onlyMaster-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
DiagnosticsRecoveryEventsRecoveryEventView[]Read-onlyIncremental recovery events taken while assembling this snapshot
The snapshot covers the diagnostics surface only

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 calls
  • skipAdo (out uint) — number of skips because the segment target was not the AL status register
  • skipLen (out uint) — number of skips because the segment length was not 2 bytes
  • skipActive (out uint) — number of skips because the previous round had not finished consuming
  • writes (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 calls
  • opBranch (out uint) — number of calls that took the running-state fast path
  • opInactive (out uint) — number of calls not appended because the channel slot was already occupied
  • opQueued (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 with BusCycleHz
  • Slave AL state: the per-slave ErrorCode / AlStatusCode, or DarraEtherCAT.GetSlaveALStatusCode(masterIndex, slaveIndex)
  • Group WKC: GetGroupActualWKC compared with the expected value fixed at configuration time (group ActualWKC / ExpectedWKC)

Parameters:

  • refreshUs (out ulong) — valid only when the call returns true; fixed at 0 when it returns false and not a real reading
  • aggregate (out ushort) — same as above
  • wkcMatch (out ushort) — same as above

Return value:

  • bool — always false in this version (no data source / read failed); true can 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 index
  • group (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 index
  • group (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) or alState (EcALState) — AL Status Code, obtained from slave.ErrorCode or when a state transition fails

Return value:

  • ALErrorCategory — error category enumeration

Related structure:

  • None (0) — no error
  • Transient (1) — transient error; retry the state transition, it usually recovers automatically
  • Configuration (2) — configuration error; check the PDO mapping, SM configuration, Startup parameters and so on
  • Hardware (3) — hardware error; check the slave hardware, cable and power supply
  • Unknown (4) — unknown error; consult ETG.1000 or the slave manual

Example:

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;
}
}
Common AL Status Codes
  • 0x0024 invalid input mapping (InvalidInputMapping) — Configuration
  • 0x0025 invalid output mapping (InvalidOutputMapping) — Configuration
  • 0x0015 invalid mailbox configuration in BOOT state (InvalidMailboxConfig) — Configuration
  • 0x001A synchronization error (SyncError) — Configuration
  • 0x001B SM watchdog (SyncManagerWatchdog) — Transient
  • 0x0034 DC synchronization timeout (DcSyncTimeout) — Transient
  • 0x0051 EEPROM 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}
}
}
note

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? — PrimaryPortTx vs PrimaryPortRx
  • Is redundancy protection really running? — RedundancyActive (already includes RingMode>=1 and frames on both ports); to confirm only "do both ports carry frames" look at PrimaryPortTx/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 legacy GetMaxSyncDifferenceLegacy() collapses null into -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 back
  • TimeoutFrames (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 + WkcErrors
  • ChecksumErrors (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 NIC
  • SecondaryPortTx / SecondaryPortRx — secondary NIC (redundancy mode)
  • PrimaryPortErrors / SecondaryPortErrors — port errors over the 5-second sliding window

How to read it:

  • PrimaryPortTx == PrimaryPortRx → primary path OK
  • PrimaryPortTx > PrimaryPortRx → frame loss on the primary path
  • SecondaryPortTx > 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 by RedundancyActive (RingMode>=1 and 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 count
  • SlaveInvalidFrames[i] (ushort[]) — CRC / invalid frame count
  • SlaveLostLinks[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 frequency
  • BusMaxJitterUs / BusAvgJitterUs / BusCleanMaxJitterUs — bus jitter
  • BusRoundtripUs (RTT) — frame round-trip delay
  • BusLoadPercent — communication load = RTT / cycle (>70% requires reducing the frequency)
  • SmiCount / SmiPeakUs — system management interrupt (BIOS / hardware) interference
  • WdkDropouts — 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