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 synchronizationDC state and deviation, DCSyncLost event
Redundancy statusRedundancy active, fault point detection (link break and CRC fault location)
Diagnostics snapshotA consistent snapshot of every diagnostic metric in one call
Diagnostics controlStart and stop data collection, reset statistics

Communication and performance statistics​

CategoryMethodTypeR/WDescription
Frame countsgetRTcnt()intread-onlyFrames per second (Hz); 5-second sliding window, falls back to the runtime summary when not ready
Frame countsgetErrorCnt()longread-onlyErrors per second, 5-second average
Frame countsgetPacketLossRate()floatread-onlyPacket loss rate (0.0~1.0) = merged bus WKC deficit ÷ expected WKC (instantaneous value); 0 = no frame was really lost (a redundancy takeover without interruption also counts as no loss); only a cold start that has not yet reached OP falls back to the TX vs RX counter difference
Frame countsgetLateFrameRate()floatread-onlyLate frame rate (0.0~1.0): the frame index is stale within an 8-frame window and is not counted as packet loss
Cycle and jittergetCycleTimeSpan()intread-onlyActual cycle time (µs). Compare it with the LoopCycle setting; it is not hard-coded to 1 ms
Cycle and jittergetAvgJitterUs()doubleread-onlyAverage jitter over the last 5 seconds (µs). Jitter grows when isolation is not in effect; the cycle should still hold at the configured value. There is no product minimum cycle time (the configured value is applied as given, with no silent clamping); the actual value is what you measure on site
Mailbox latencygetMailboxLatencyUs()doubleread-onlyMaximum mailbox transaction round-trip time (µs, settled over the last 1 second)
Mailbox latencygetMailboxLatencyAvgUs()doubleread-onlyAverage mailbox transaction round-trip time (µs, settled over the last 1 second)
Bus real-time performancegetBusCycleHz()longread-onlyBus frequency (Hz)
Bus real-time performancegetBusMaxJitterUs()doubleread-onlyMaximum bus jitter (µs)
Bus real-time performancegetBusAvgJitterUs()doubleread-onlyAverage bus jitter (µs)
Bus real-time performancegetBusRoundtripUs()doubleread-onlyFrame round-trip delay (µs)
Bus real-time performancegetBusLoadPercent()doubleread-onlyCommunication load (%), derived value = round-trip delay / cycle × 100
Bus real-time performancegetSmiCount()longread-onlyCumulative number of system management interrupts
Bus real-time performancegetSmiPeakUs()doubleread-onlyPeak jitter of system management interrupts (µs)
Bus real-time performancegetCycleCount()longread-onlyTotal number of completed PDO cycles
Bus real-time performanceisHardwareSmiCounterAvailable()booleanread-onlyWhether the hardware SMI counter is readable
PDO frame lossgetPDO().getTotalLost()intread-onlyCumulative lost frames (sum of all groups)
PDO frame lossgetPDO().getConsecutiveLost()intread-onlyCurrent consecutive lost frames (maximum across all groups)
PDO frame lossgetPDO().getFrameLossStats(int)int[]read-onlyFrame loss statistics of the specified group [total, consecutive, max consecutive]; group numbers are 0~7, passing 255 returns the summary for all groups, and any other out-of-range value throws IllegalArgumentException (it no longer silently returns the summary). For group-level criteria see group diagnostics
Slave anomaliesgetWorstSlaveIndex()intread-onlyIndex of the slave with the worst link quality (not an "error rate")
Slave anomaliesgetWorstLinkQuality()shortread-onlyWorst link quality (%), -1 = unknown
Master truthlostSlaveCount()intread-onlyLost-slave census count (the single authority for the bus-level lost-slave count); >0 = a slave is lost; -1 = read failed / unavailable (use it together with lostSlaveCountKnown())
noProcessData()booleanread-onlyMaster-level "no process data / false OP" truth value: true = the cycle is running but the process data is dead; a read failure returns true (fail-safe)
noProcessDataKnown()booleanread-onlyWhether noProcessData() has a measured sample; when false the return value carries no meaning and must be shown as "unknown"
probeAliveCount() / probeUnknownCount()intread-onlyProbe truth summary (number of slaves that answered / number of slaves with insufficient evidence); 0 when there is no true-value sample
staleInputCount()intread-onlyNumber of slaves whose input data is confirmed STALE (per slave inputDataValidity()==STALE); UNKNOWN / DEGRADED are not counted; -1 = a slave read failed / is unavailable
Cycle runcycleState()CycleRunStateread-onlyMaster cycle tri-state: NotStarted / StartedNoAdvance / Advancing; 0 no longer blurs three different meanings into one value
Topology changetopologyFingerprint()longread-onlyTopology fingerprint (slave count + a stable hash of each slave's VendorId/ProductId/RevId); topologyFingerprintKnown() reports whether sampling succeeded
topologyChangeCount()longread-onlyNumber of observed topology changes (the first sample is not counted; observed at read time, multiple changes between two reads are merged into one)
lastTopologyChangeUtc()java.time.Instantread-onlyTime of the most recent observed topology change (UTC); null = no change observed yet
Port statusisPrimaryPortOk()booleanread-onlyWhether the primary port is healthy
Port statusisSecondaryPortOk()booleanread-onlyWhether the secondary port is healthy
Port statusgetPrimaryPortErrors()longread-onlyPrimary-port errors in the last 5 seconds
Port statusgetSecondaryPortErrors()longread-onlySecondary-port errors in the last 5 seconds
Redundancy statusisRedundancyActive()booleanread-onlyRedundancy protection is running = redundancyRingMode() >= 1 and both ports carry frame traffic within this window; always false for line / end-foldback topologies
redundancyRingModeEnum()RingModeread-onlyRedundancy ring operating mode enum: UNKNOWN(-1) / INACTIVE(0) / DUAL(1) / DEGRADED(2); unreadable / out-of-range value → UNKNOWN, never folded into INACTIVE
TopologygetTopologyDescription()Stringread-onlyTopology mode description (line / ring / ring + branch)
TopologygetTimingMode()Stringread-onlyTiming mode: FreeRun / DC Sync0 / DC Sync01

Packet loss is counted by WKC deficit: merged bus WKC deficit ÷ expected WKC; 0 means no frame was really lost (a redundancy takeover without interruption also counts as no loss); only a cold start that has not yet reached OP and cannot obtain the expected WKC falls back to the TX vs RX counter difference. Late frames are not counted as packet loss and are reflected separately by getLateFrameRate().

Window statistics such as frame rate, error count and jitter require setEnabled(true) to start sliding-window sampling first; setEnabled is not the master switch for diagnostics collection (see diagnostics control). Mailbox latency, bus real-time performance, PDO frame loss, port status, topology and redundancy status are always readable and are not affected by that switch.

Mailbox latency measures the time from request to response for acyclic request-response transactions (CoE / SoE / FoE / EoE / AoE / VoE): getMailboxLatencyUs() is the maximum and getMailboxLatencyAvgUs() the average, settled over the last 1 second.

Example:

MasterDiagnosticsInfo diag = master.diagnostics();
diag.setEnabled(true); // Enable diagnostics data collection

// Frame counts
System.out.println("帧频: " + diag.getRTcnt() + " Hz"); // Frame rate: {diag.getRTcnt()} Hz
System.out.printf("丢包率: %.2f%%%n", diag.getPacketLossRate() * 100); // Packet loss rate: %.2f%%%n

// Cycle and jitter
System.out.println("周期时间: " + diag.getCycleTimeSpan() + " us"); // Cycle time: {diag.getCycleTimeSpan()} us
System.out.printf("抖动: 平均 %.2f us%n", diag.getAvgJitterUs()); // Jitter: average %.2f us%n

// Mailbox round-trip latency
System.out.printf("邮箱延迟: 平均 %.2f us, 最大 %.2f us%n", // Mailbox latency: average %.2f us, max %.2f us%n
diag.getMailboxLatencyAvgUs(), diag.getMailboxLatencyUs());

// PDO frame loss
MasterDiagnosticsInfo.MasterPDODiagnostics pdo = diag.getPDO();
System.out.printf("PDO 丢帧: 累计=%d, 连续=%d%n", // PDO frame loss: cumulative=%d, consecutive=%d%n
pdo.getTotalLost(), pdo.getConsecutiveLost());

// Slave anomalies
System.out.printf("最差从站: #%d (%d%%)%n", // Worst slave: #%d (%d%%)%n
diag.getWorstSlaveIndex(), diag.getWorstLinkQuality());

// Port status
System.out.println("主端口: " + (diag.isPrimaryPortOk() ? "正常" : "异常")); // Primary port: normal / abnormal
System.out.println("副端口: " + (diag.isSecondaryPortOk() ? "正常" : "未连接")); // Secondary port: normal / not connected

// Topology information
System.out.println("拓扑: " + diag.getTopologyDescription()); // Topology: {diag.getTopologyDescription()}
System.out.println("定时: " + diag.getTimingMode()); // Timing: {diag.getTimingMode()}

// Cycle count / SMI hardware counter
System.out.println("周期计数: " + diag.getCycleCount()); // Cycle count: {diag.getCycleCount()}
System.out.println("SMI 计数可读: " + diag.isHardwareSmiCounterAvailable()); // SMI counter readable: {diag.isHardwareSmiCounterAvailable()}
Slave communication diagnostics

Per-slave port errors and link quality come from readPortErrors() / linkQuality() on slave.diagnostics(); the master-side readSlaveErrorCounters() is a compatibility entry point (with known reductions), see slave error counters.

WKC (Working Counter) observation​

The overall measured / expected WKC is read through the master properties master.WKC() / master.expectedWKC(), and is returned at once in the diagnostics snapshot as the WkcActual / WkcExpected fields. Use slave.wcContributed() (the EcWcContributed enum) for each slave's contribution state, which pinpoints exactly which slave dropped out.

Observability conventions (mandatory):

  • master.expectedWKC() = the fixed true value determined at configuration time / when entering OP; it is fixed once the topology is fixed, conceptually immutable, and never lowered dynamically to accommodate a degraded bus.
  • master.WKC() = the measured bus value, reported as measured, reflecting which slaves really respond at this instant; never altered.
  • WKC < ExpectedWKC is not a master fault; a mapped slave is simply not contributing WKC at this instant (suspected slave loss / hot-plug recovery in progress). Once the slave recovers, the measured value climbs back to match the expected value with no reset call.

Master-level WKC mirror (real-time)​

master.diagnostics() also exposes a group of master-level aggregated WKC mirror getters that reflect, in real time, the master-level summary of the per-slave WcState diagnostics. Together with the per-slave slave.wcContributed() they pinpoint exactly which slave dropped out.

The following getters all belong to the WKC mirror category; they are read-only and always active:

CategoryMemberTypeR/WDescription
WKC mirrorgetWkcActualMirror()intread-onlyWKC measured in this cycle; 0 = unknown (not ready yet)
WKC mirrorgetWkcExpectedMirror()intread-onlyExpected WKC fixed at configuration time; 0 = unknown; never lowered to accommodate a degraded bus
WKC mirrorgetWcDeficit()intread-onlyDeficit = expected − actual; >0 means a mapped slave is not contributing WKC (suspected slave loss / hot-plug recovery in progress), and it returns to 0 automatically after recovery
WKC mirrorgetMappedSlaveCount()intread-onlyNumber of mapped slaves already issued; 0 = the contract is not ready / OP not reached, in which case it reads "unknown" rather than "lost slave"

When an older runtime does not provide this group of getters they return 0 (nothing is invented).

Example:

MasterDiagnosticsInfo diag = master.diagnostics();

// Master-level WKC mirror (real-time)
System.out.printf("WKC: %d / %d (映射从站 %d 个)%n", // WKC: %d / %d (%d mapped slaves)%n
diag.getWkcActualMirror(), diag.getWkcExpectedMirror(), diag.getMappedSlaveCount());

if (diag.getWcDeficit() > 0) {
System.out.printf("WKC 亏空 %d — 有从站没在响应,逐个从站定位:%n", diag.getWcDeficit()); // WKC deficit %d — some slaves are not responding, locate them one by one:%n
for (Slave slave : master.slaves()) {
if (slave.wcContributed() == EcatSlaveDiag.EcWcContributed.NOT_CONTRIBUTED) {
System.out.printf(" 从站 %d 未贡献 WKC%n", slave.SlaveNum); // Slave %d not contributing WKC%n
}
}
}

// You can still use the overall WKC (measured / expected) for a rough check
System.out.printf("整体 WKC: %d / %d%n", master.WKC(), master.expectedWKC()); // Overall WKC: %d / %d%n
per-slave WcState

Use slave.wcContributed() (the EcWcContributed enum) for an individual slave's WKC contribution state. When getWcDeficit() > 0, iterate the slaves to locate the lost one.

Secondary-port WKC "unknown" state​

secondaryWkc() is the secondary-port working counter measured in this cycle: if a fresh value was sampled this cycle it returns the measured value, otherwise it returns "unknown"; it never returns a stale full count and never returns a value held over from an earlier cycle.

CategoryMemberTypeR/WDescription
Redundancy WKCdiagnostics().secondaryWkc()intread-onlySecondary-port WKC measured in this cycle (0..65535). Returns WKC_UNKNOWN when this cycle has no fresh measurement
Redundancy WKCMasterDiagnosticsInfo.WKC_UNKNOWNstatic final intread-only"no measurement" sentinel, value 0xFFFF
Redundancy WKCdiagnostics().secondaryWkcKnown()booleanread-onlyWhether this cycle has a measurement. false only means secondaryWkc() is WKC_UNKNOWN
Redundancy WKCmaster.secondaryWkcRt()shortread-onlyReal-time filtered value of the secondary port (drops in the same cycle a slave is unplugged or the link breaks); use this for the current instant

0 on a single-port setup (no secondary leg configured) is a valid reading and counts as "known". So judging "unknown" must go through secondaryWkcKnown(): neither "is the value 0" nor treating 0xFFFF as a full count works.

Java numeric width trap

The value is an unsigned 16-bit quantity, but Java's short is signed, so 0xFFFF reads back as -1. Comparing short == 0xFFFF directly is always false. secondaryWkc() already restores it to an int in the range 0..65535 via & 0xFFFF; use secondaryWkcKnown() consistently to test for unknown.

Example:

MasterDiagnosticsInfo diag = master.diagnostics();

if (!diag.secondaryWkcKnown()) {
System.out.println("副口 WKC: 未知(本拍无实测)"); // Secondary port WKC: unknown (no measurement this cycle)
} else if (diag.secondaryWkc() == 0) {
System.out.println("副口 WKC: 0(单网口 / 副口本拍无贡献)"); // Secondary port WKC: 0 (single network port / secondary port contributed nothing this cycle)
} else {
System.out.printf("副口 WKC: %d,实时值 %d%n", // Secondary port WKC: %d, live value %d%n
diag.secondaryWkc(), master.secondaryWkcRt());
}

Real OP verdict (RealOp)​

"AL status word reads OP" is not the same as "this cycle really is exchanging process data". The status word can stick: after a slave drops out the AL state may still report OP, and the UI still shows "all OP" while the merged WKC is down to 6/12. The per-slave "real OP" comes from the SDK's per-slave verdict.

  • Only a holding verdict counts as a clean OP: the AL state is OP (0x08), the Error bit (0x10) is 0, and the slave has not dropped out;
  • WKC contribution is display evidence only and cannot be used to overturn a verdict.

The master-level "real OP" is a separate conclusion: every required slave (not optional and with process data) holds its per-slave verdict, and the merged measured WKC is not below the fixed expectation from configuration time. Per-slave verdicts holding on their own does not equal a whole-machine real OP.

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

Read-only verdict, not part of control

This group of APIs only makes and displays verdicts: it does not trigger recovery, stop PDO, leave OP, change the expected value, or alter any existing control criterion. Any evidence that cannot be read is judged RealOpReason.UNKNOWN; cached or stale values are never passed off as real OP; the expected WKC is never lowered.

Entry points​

CategoryMemberReturnsR/WDescription
Diagnosticsdiagnostics().captureRealOpTruth()MasterRealOpTruthread-onlyCapture one cycle of real-OP truth (master-level + per-slave)
Diagnosticsdiagnostics().evaluateSlaveRealOp(int)SlaveRealOpStateread-onlySingle-slave verdict; null = cannot be evaluated, shown honestly as unknown
Diagnosticsdiagnostics().evaluateRealOp(evidence, wkcActual, wkcExpected)MasterRealOpTruthread-onlyEvaluate from same-cycle evidence (no re-read when a snapshot already exists); evidence may be null / an empty list

Application code should call these entry points directly; there is no need to write another "is it real OP" check, and doing so is discouraged.

SlaveRealOpEvidence on evaluateRealOp is a public value object holding the per-slave raw quantities for the same cycle (slaveIndex / required are mandatory; the rest such as alive, probeAlive, pdContributed, noProcessData and the measured AL value are display evidence only) and does not take part in the verdict.

Reason enumeration​

RealOpReason (code values map one-to-one to the other language SDKs, so logs line up across languages)

ValueNameMeaning
0OKReal OP: the per-slave verdicts hold
1AL_NOT_CLEANThe per-slave verdict does not hold (not in OP / Error bit set / slave dropped out)
2NO_CONTRIBUTIONHistorical / compatibility value: no longer produced by the per-slave verdict (the code is kept so logs line up across languages)
3UNSTABLEHistorical / compatibility value: no longer produced by the per-slave verdict (the code is kept so logs line up across languages)
4WKC_DEFICITMaster-level: every required slave holds its verdict, but the merged measured WKC is below the fixed expectation
5UNKNOWNInsufficient evidence (the data the verdict needs cannot be read / no required slaves)

Result structure​

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

FieldTypeDescription
sequencelongEvaluation sequence number, monotonically increasing per master
realOpbooleanMaster-level real OP
reasonRealOpReasonMain reason the master-level verdict does not hold
requiredCountintNumber of required slaves
realOpCountintNumber of required slaves whose per-slave verdict is real OP
failedCountintNumber of required slaves that did not reach real OP
wkcActualintMerged measured WKC (as measured)
wkcExpectedintExpected WKC fixed at configuration time (never lowered)
wkcDeficitintDeficit = expected − actual (≤0 means no deficit)
slavesList<SlaveRealOpState>Per-slave results
detailTextStringReadable detail (master conclusion + list of slaves that did not reach real OP + WKC comparison)

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

FieldTypeDescription
slaveIndexintSlave index (1-based)
requiredbooleanWhether it takes part in the master-level verdict (not optional and has PDO)
alCleanOpbooleanPer-slave verdict (AL is OP ∧ Error bit = 0 ∧ not dropped out)
contributedbooleanHas a WKC contribution this cycle — display evidence only, not part of the verdict
stableStreakintDisplay-layer run length (maintained by the SDK's stability tracking for display / debouncing); not part of the verdict and cannot be used to overturn realOp
realOpbooleanReal OP for this slave
reasonRealOpReasonReason it does not hold (OK when it is real OP)
detailStringReadable reason detail (not part of the verdict)

Example:

MasterRealOpTruth truth = master.diagnostics().captureRealOpTruth();

if (truth.realOp) {
System.out.printf("真 OP: 必需站 %d/%d, WKC %d/%d%n", // True OP: required slaves %d/%d, WKC %d/%d%n
truth.realOpCount, truth.requiredCount, truth.wkcActual, truth.wkcExpected);
} else {
System.out.printf("非真 OP [%s] %s%n", truth.reason, truth.detailText); // Not true OP [%s] %s%n
for (SlaveRealOpState s : truth.slaves) {
if (s.required && !s.realOp)
System.out.printf(" 从站 %d: %s — %s%n", s.slaveIndex, s.reason, s.detail); // Slave %d: %s — %s%n
}
}

Hot-plug (automatic)​

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

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

Automatic rebuild observation​

public int getHotSwapRescanCount()          // completed rounds
public int getLastHotSwapRescanResult() // last result code
public long getLastHotSwapRescanTimeMs() // last completion time (Unix ms UTC)
Where the entry points live

The three read-only methods live on com.darra.ethercat.master.Diagnostics; master.diagnostics() returns a MasterDiagnosticsInfo, which is a different class. Call them like this:

Diagnostics diag = new Diagnostics(master.MasterIndex);
System.out.println(diag.getHotSwapRescanCount());

Result codes: 0 succeeded / -20 BUSY (another round in progress) / -21 RESCAN_0 (0 reachable slaves; R0: do not blame the link) / -23 NO_OP (slaves present but not in OP, first AL carried) / -25 IDX_FULL (resources exhausted); gates -1 invalid master index / -6 not initialized. Historical -22 / -24 / -26 only from an old DLL.

Example:

int rounds = diag.getHotSwapRescanCount();
int last = diag.getLastHotSwapRescanResult();
long when = diag.getLastHotSwapRescanTimeMs();
System.out.printf("自动重建 %d 轮,上次结果 %d,时刻 %d%n", rounds, last, when); // Auto rebuild %d rounds, last result %d, at %d%n
MethodReturnsDescription
diag.getPrimaryPhyLinkState() / getSecondaryPhyLinkState()EtherCATTypes.PhyLinkStatePhysical link of the primary / secondary port: UP=1, DOWN=0, UNKNOWN=-1; a failed read also gives UNKNOWN
master.secondaryFrameLinkState()EtherCATTypes.PhyLinkStateThree-state frame-level link of the secondary port; use it separately from the NIC's physical reading
diag.getPhyLinkBitMask()intTwo-port bitmap: bit0 = primary port up, bit1 = secondary port up; 0xFFFF = not observable

UNKNOWN only means the value cannot be read or has not been decided yet (unsupported version, frame-level link not yet resolved); it does not equal DOWN. Do not report a link break or slave loss, or trigger fault handling, based on it. Only an explicit DOWN means the link is down.

if (diag.getPrimaryPhyLinkState() == EtherCATTypes.PhyLinkState.DOWN)
System.out.println("主口明确 Down"); // Primary port definitively down

master.secondaryLinkStatus() is a compatibility boolean health check: it returns true only for an explicit Up, and false for both Down and unknown. Call secondaryFrameLinkState() when the latter two must be distinguished.

Static port topology model (ring / branch / chain form)​

The static port model is provided by the SDK; the caller assembles the input list from each slave's port topology, and the result is returned directly with no second derivation. This encoding is not the same value set as the runtime form returned by getTopologyMode(); a raw cast between the two is forbidden. When the model cannot be read or decided, treat it as "unknown", never as line.

MethodReturnsDescription
master.computeRingBranch(slaves)DarraCore.TopoRingBranchOutv1 entry point; the signature and semantics are unchanged and it remains usable. Read-only, changes no state
master.computeRingBranchEx(slaves)DarraCore.TopoRingBranchOut2v2 entry point; the first 5 fields are identical to v1 one by one, with chain_form appended at the end. Read-only, changes no state. Recommended for new code

Input list (one row per slave, DarraCore.TopoRingSlaveIn):

FieldTypeDescription
slave_numshortSlave index
phys_apbytePhysical port mask (bit0..3 = P0..P3)
entry_portbyteEntry port 0..3; 0xFF = unknown / not filled in
parentshortParent slave index; 0 = root
parent_portbytePort 0..3 on this slave through which it connects to its parent; 0xFF = unknown / not filled in

Both entry points throw on failure instead of returning an object with a negative code: a null / empty input list, or a null slave in the list, throws IllegalArgumentException; a computation error throws IllegalStateException (the message carries the original code and the slave count). After catching it, treat the model as unknown; do not turn it into a line or empty-topology conclusion.

Output fields (DarraCore.TopoRingBranchOut2, 6 ints, fixed order):

FieldTypeDescription
total_countintTotal slave count
ring_countintNumber of ring members (truncated to the capacity the caller supplied when it is too small)
branch_countintBranch count = total_count − ring_count
closure_slave_numintClosing-point slave index; -1 = none (line / chain (foldback at end))
modeintStatic port model: 0 = line / 1 = ring / 2 = ring + branch
chain_formintSub-form for the no-ring case, meaningful only when mode == 0

chain_form values:

ValueConstantMeaning
0CHAIN_FORM_LINEARLine (Linear)
1CHAIN_FORM_FOLDBACKChain (foldback at end)
Check mode before interpreting chain_form

chain_form is interpreted only when mode == 0. Under ring / ring + branch the field is always 0, and that 0 is a placeholder: it does not mean line. The SDK returns it as is — no conversion, no guessing — so the caller must read mode first and then decide whether to interpret the field.

Both forms are "without a ring": in a line the end is a single active port with all slaves in series; in a chain (foldback at end) the end folds back inside a single port (frames go out the primary port and come back on the secondary, and the whole chain is traversed twice). A chain has no redundancy protection — do not treat chain_form as "the only criterion for redundancy".

Return codes (the original code inside the exception message): 0 = success; -1 = bad parameter; -2 = no port measurement; -3 = degenerate input; -4 = undecided. A negative value always means there is no reliable answer; treat it as "model unknown", never as a line or empty-topology conclusion. computeRingBranch and computeRingBranchEx have exactly the same return-code set.

Example:

try (EtherCATMaster master = EtherCATMaster.create()) {
master.setNetwork("\\Device\\NPF_{...}");

// slaves: List<DarraCore.TopoRingSlaveIn>, filled in per slave's port topology
// slave 1 = root (P0/P1 active); slave 2 = end with a single active port, parent 1
DarraCore.TopoRingBranchOut2 out = master.computeRingBranchEx(slaves);
System.out.printf("总站数 %d, 环 %d, 分支 %d, 闭合点 %d%n", // Total slaves %d, ring %d, branches %d, closure points %d%n
out.total_count, out.ring_count, out.branch_count, out.closure_slave_num);

if (out.mode == 0) {
// interpret chain_form only when mode == 0
switch (out.chain_form) {
case 0:
System.out.println("形态: 线性 (Linear)"); // Shape: linear (Linear)
break;
case 1:
System.out.println("形态: 链式(末端折返)(Chain (foldback at end))"); // Shape: chain (foldback at end) (Chain (foldback at end))
break;
default:
System.out.println("形态: 未知 chain_form=" + out.chain_form); // Shape: unknown chain_form={out.chain_form}
break;
}
} else {
System.out.println("形态: 环 / 环+分支,chain_form 不参与解释"); // Shape: ring / ring + branches, chain_form is not used in the interpretation
}
}

v1 computeRingBranch(...) remains usable; new code should use computeRingBranchEx(...).

DC synchronization​

Automatic monitoring (ETG.1500 5.13.3) checks each slave's time deviation every second. When the sync window threshold is exceeded, a DCSyncLost event is raised.

Read and write the sync window threshold through getSyncWindowThreshold() / setSyncWindowThreshold(int thresholdNs) (nanoseconds, default 1000ns); see DC synchronization for details.

Example:

MasterDiagnosticsInfo diag = master.diagnostics();
diag.setSyncWindowThreshold(500); // 500 ns threshold
Single slave

Use the slave-level DC diagnostics methods for an individual slave's synchronization state.

DC diagnostics 2-second snapshot​

master.diagnostics().dcDiagnostics() returns the per-slave and master-level DC conclusions in one call. The snapshot has a 2-second TTL: within the same 2 seconds every consumer gets the same object, so "each column read separately" cannot split the picture. Assembly reads local state only (slave structure / sync state / armed mask) and sends no bus frames, so it can be called from the UI thread or a diagnostics thread.

CategoryMemberTypeR/WDescription
DC diagnosticsdcDiagnostics()DcDiagnosticsSnapshotread-onlySnapshot entry (never null; throws IllegalStateException when the master has been released)
DC diagnosticscapturedAtUtcInstantread-onlyTime this cycle's snapshot was assembled (UTC)
DC diagnosticshasDcbooleanread-onlyWhether DC slaves exist on the network
DC diagnosticsallInSyncBooleanread-onlyWhether all SYNC0 participants are inside the window. null = no confirmed participant (not true); false when a participant was not sampled / cannot be read / any slave's armed state is unknown
DC diagnosticsmaxDriftNsIntegerread-onlyLargest absolute synchronization difference among usable windows. null = no measured window at all (not 0)
DC diagnosticssyncWindowThresholdNsIntegerread-onlySync window threshold (nanoseconds). null = cannot be read
DC diagnosticsreferenceClockDcReferenceClockInforead-onlyReference-clock slave index + tier + reason (never null)
DC diagnosticsarmedSlaveCountintread-onlyNumber of slaves with SYNC0 armed (sync0Armed == true); 0 is a valid count
DC diagnosticsactiveSlaveCountintread-onlyNumber of DC-active slaves (the value landed in 0x0980 is anything other than 0); not the same conclusion as "armed"
DC diagnosticsarmedUnknownCountintread-onlyNumber of slaves whose armed state is unknown (the conclusion cannot be read); 0 is a valid count
DC diagnosticsarmedSyncParticipantCountintread-onlyNumber of sync participants (armed + not the reference clock); 0 = no slave on this network can carry a synchronization conclusion
DC diagnosticsapplicableWindowCountintread-onlyNumber of slaves with a measured window; when it is 0, maxDriftNs is necessarily null
DC diagnosticsactiveWithoutProcessDataCountintread-onlyNumber of slaves that are DC-active but have no process data (such slaves are judged a hard DC failure)
DC diagnosticsexpectedWkcintread-onlyMaster expected WKC (the fixed value from configuration time); compare it with the armed slave count to see WKC coverage
DC diagnosticspropagationDelayResolvedAtUtc / propagationDelayResolveCountInstant / intread-onlyTime and count of the most recent successful propagation-delay resolution triggered by the SDK; null / 0 = not observed in this process
DC diagnosticsslaves / find(index)List<DcSlaveSnapshot> / DcSlaveSnapshotread-onlyPer-slave snapshots (ascending slave index); find returns null when out of range or not sampled
DC diagnosticsanyReadFailurebooleanread-onlyAt least one read failed this cycle (failed items are already set to null / Unknown)

The fields of the per-slave DcSlaveSnapshot map one-to-one to the slave-level DC diagnostics, plus shiftNs, outputBytes / inputBytes, isDcActive, isReferenceClock and convergenceMeasuredAtUtc.

Example:

DcDiagnosticsSnapshot dc = master.diagnostics().dcDiagnostics();

if (dc.anyReadFailure) {
System.out.println("本拍部分 DC 读数失败,结论按不可用处理"); // Some DC readings failed this cycle, the conclusion is treated as unavailable
}
if (Boolean.TRUE.equals(dc.allInSync)) {
System.out.println("全部 SYNC0 参与者都在窗口内,最大差 " + dc.maxDriftNs + "ns"); // All SYNC0 participants are within the window, max difference {dc.maxDriftNs}ns
} else if (dc.allInSync == null) {
System.out.println("没有确认参与者,同步结论不可谈"); // No confirmed participants, no sync conclusion can be drawn
} else {
System.out.println("存在不在窗或未采样的参与者"); // There are participants out of the window or not sampled
}

DcSlaveSnapshot s3 = dc.find(3);
if (s3 != null) {
System.out.printf("从站 3: 武装=%s, 窗口=%s%n", s3.sync0Armed, s3.syncWindow); // Slave 3: armed=%s, window=%s%n
}

allInSync / maxDriftNs inside the snapshot are three-state. The boolean / -1 convention of older summary surfaces such as isAllSlavesInSync(int) / getMaxSyncDifference() cannot replace the three states.

Redundancy status​

getRingMode() reflects the running state of ring-topology redundancy; the returned strings are "无冗余" (SDK output, = no redundancy) / "双向冗余" (SDK output, = bidirectional redundancy) / "降级(仅primary)" (SDK output, = degraded (primary only)) / "降级(仅secondary)" (SDK output, = degraded (secondary only)) / "离线" (SDK output, = offline).

isRedundancyActive() means redundancy protection is running: master.redundancyRingMode() >= 1 and both the primary and secondary ports carry frame traffic within this window. In a chain (foldback at end) topology frames go out the primary port and come back on the secondary, traversing the whole chain twice, so both ports carry frames, but physically there is no second independent path — this method returns false, consistent with redundancyRingMode() being INACTIVE. To learn "do both ports carry frames", read the primary / secondary port TX-RX counters or isPrimaryPortOk() / isSecondaryPortOk(); do not infer it from this method. slave.redundancyActivated() is the same master-level criterion (RingMode >= 1), not a per-slave independent conclusion.

getBreakPoint() / getAllBreakPoints() detect two kinds of physical fault uniformly:

TypefaultTypeDetectionTypical scenario
Link break0Physical link loss reported on the DL Status portCable unplugged, cable break
CRC fault1Port-level RxError + InvalidFrame keep increasingPoor contact, ageing cable, oxidized connector
The three states of getAllBreakPoints()

getBreakPoint() returning null means both "genuinely no fault" and "the query failed" (that return type has no third state). Use getAllBreakPoints() when the two must be distinguished: null = the query failed, an empty array = the query succeeded with no fault. An empty array must not be taken as "the query failed", and null must not be taken as "no fault".

Faulty cable segment location: 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 between them is at fault. If only one side reports a fault, the fault is located at that port's connector.

BreakPointInfo structure:

public static class BreakPointInfo {
public final int slaveIndex; // faulty slave index (1-based)
public final int port; // faulty port number (0-3, corresponding to P0-P3)
public final int faultType; // fault type: 0 = link break, 1 = CRC fault

public boolean isLinkDown(); // whether it is a link-break fault
public boolean isCrcFault(); // whether it is a CRC fault
}

Example:

MasterDiagnosticsInfo diag = master.diagnostics();

// Ring-topology redundancy mode
System.out.println("冗余模式: " + diag.getRingMode()); // Redundancy mode: {diag.getRingMode()}

if (diag.isRedundancyActive()) {
System.out.println("冗余已激活"); // Redundancy is active
}

MasterDiagnosticsInfo.BreakPointInfo bp = diag.getBreakPoint();
if (bp != null) {
System.out.println("故障: " + bp); // Fault: {bp}
if (bp.isCrcFault()) {
System.out.println("建议检查线缆/连接器"); // Check the cable/connector
}
}

// Get all fault points (null = the query failed, an empty array = the query succeeded with no fault)
MasterDiagnosticsInfo.BreakPointInfo[] all = diag.getAllBreakPoints();
if (all == null) {
System.out.println("故障点查询失败: 状态未知, 不当作无故障"); // Fault point query failed: state unknown, do not treat as fault-free
} else if (all.length == 0) {
System.out.println("当前无故障点"); // No fault point at present
} else {
for (MasterDiagnosticsInfo.BreakPointInfo b : all) {
System.out.println("故障点: " + b); // Fault point: {b}
}
}

Diagnostics snapshot​

getSnapshot()​

public DiagnosticsSnapshot getSnapshot()

Returns a DiagnosticsSnapshot that packs the items above into one read-only object in a single call, suitable for UI refresh and logging. It reads field by field in sequence and does not guarantee same-cycle consistency: comparing fields across the snapshot can tear; when single-cycle consistency matters, use the matching dedicated snapshot (such as dcDiagnostics()).

Returns:

  • DiagnosticsSnapshot — diagnostics data snapshot object

Related structures:

public static class DiagnosticsSnapshot {
public final int Frequency; // application frequency (Hz)
public final long ErrorCount; // errors per second
public final float PacketLossRate; // packet loss rate (0.0~1.0) — WKC deficit / expected WKC
public final float LateFrameRate; // late frame rate (0.0~1.0)
public final double AvgJitterUs; // average jitter (µs)
public final double MailboxLatencyUs; // mailbox round-trip latency - maximum (µs)
public final double MailboxLatencyAvgUs; // mailbox round-trip latency - average (µs)
public final int CycleTimeUs; // actual cycle time (µs)
public final short WkcActual; // WKC actual value
public final short WkcExpected; // WKC expected value
public final long BusCycleHz; // bus frequency (Hz)
public final double BusMaxJitterUs; // maximum bus jitter (µs)
public final double BusAvgJitterUs; // average bus jitter (µs)
public final double BusRoundtripUs; // frame round-trip delay (µs)
public final double BusLoadPercent; // communication load (%) — RTT/cycle×100
public final long SmiCount; // cumulative SMI count
public final double SmiPeakUs; // SMI peak jitter (µs)
public final boolean PrimaryPortOk; // whether the primary port is healthy
public final boolean SecondaryPortOk; // whether the secondary port is healthy
public final boolean RedundancyActive; // redundancy protection running (RingMode>=1 and both ports carry frames; always false for line/end foldback)
}

Example:

MasterDiagnosticsInfo diag = master.diagnostics();
diag.setEnabled(true);

MasterDiagnosticsInfo.DiagnosticsSnapshot snap = diag.getSnapshot();
System.out.printf("频率: %d Hz, 丢包: %.2f%%, 抖动: %.2f us%n", // Frequency: %d Hz, packet loss: %.2f%%, jitter: %.2f us%n
snap.Frequency, snap.PacketLossRate * 100, snap.AvgJitterUs);
System.out.printf("WKC: %d/%d, 总线: %d Hz%n", // WKC: %d/%d, bus: %d Hz%n
snap.WkcActual, snap.WkcExpected, snap.BusCycleHz);
if (snap.RedundancyActive) {
System.out.println("冗余已激活"); // Redundancy is active
}

Diagnostics control​

setEnabled(...) is not the master switch for diagnostics collection: it turns optional diagnostics statistics on and off, and starts or stops the Java-side sliding-window sampling timer. When it is off, optional statistics such as frame errors, jitter, mailbox latency and port activity stop accumulating; PDO frame loss statistics, redundancy detection, DC synchronization and WKC baseline statistics are not affected by the switch.

setEnabled(boolean)​

public void setEnabled(boolean enable)
public boolean isEnabled()

Parameters:

  • enable (boolean) — true turns on the optional diagnostics statistics and starts sliding-window sampling (off by default); false stops them.

Returns: isEnabled() returns the current switch state.

Behaviour: once on, window statistics such as frame counts, jitter and error rate are recorded; window metrics like getRTcnt() / getErrorCnt() / getAvgJitterUs() depend on that sampling; for the other metrics see communication and performance statistics.

reset (diagnostic counters)​

public void reset()

Resets master-level statistics: the basic diagnostic counters (frame errors and so on) and PDO frame loss statistics (groups 0–7). It does not clear DC sync window statistics or slave port error counters — those two are cleared separately by slave.DC().resetSyncWindowStats() and slave.diagnostics().resetPortErrors(). It does not affect the FSoE safety connection state machine (slave.fsoe().resetConnection()).

Example:

MasterDiagnosticsInfo diag = master.diagnostics();
diag.setEnabled(true); // enable collection
// ... run for a while ...
diag.reset(); // reset statistics

AL error categories​

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

EtherCATTypes.classifyALError​

public static EtherCATTypes.ALErrorCategory classifyALError(int alStatusCode)

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

The classification is provided uniformly by the SDK (values map one-to-one across languages): NONE / TRANSIENT / CONFIGURATION / HARDWARE / UNKNOWN. A failed read returns UNKNOWN.

Parameters:

  • alStatusCode (int) — AL Status Code, obtained from slave.errorCode() or when a state transition fails

Returns:

  • ALErrorCategory — error category enum

Related structures:

public enum ALErrorCategory {
NONE, // no error
TRANSIENT, // transient error; the state transition can be retried and usually recovers automatically
CONFIGURATION, // configuration error; check the PDO mapping, SM configuration, startup parameters, etc.
HARDWARE, // hardware error; check the slave hardware, cabling and power
UNKNOWN // unknown error; consult ETG.1000 or the slave manual
}

Example:

Slave slave = master.getSlave(1);
EtherCATTypes.EcALState errorCode = slave.errorCode();
if (errorCode != EtherCATTypes.EcALState.NO_ERROR) {
EtherCATTypes.ALErrorCategory category =
EtherCATTypes.classifyALError(errorCode.value);
System.out.printf("从站 1 错误 %s (0x%04X): %s%n", // Slave 1 error %s (0x%04X): %s%n
errorCode, errorCode.value, category);

switch (category) {
case TRANSIENT:
System.out.println("瞬态错误,尝试重新切换状态..."); // Transient error, retrying the state switch...
break;
case CONFIGURATION:
System.out.println("配置错误,请检查 PDO/SM 配置"); // Configuration error, check the PDO/SM configuration
break;
case HARDWARE:
System.out.println("硬件错误,请检查从站设备"); // Hardware error, check the slave device
break;
default:
break;
}
}

Frequent codes and actions:

  • 0x001D / 0x001E invalid output / input configuration (CONFIGURATION) — check the PDO mapping and SM configuration; 0x0024 / 0x0025 are the ones for invalid input / output mapping
  • 0x0015 / 0x0016 invalid mailbox configuration (BOOT / PreOp state respectively, CONFIGURATION) — check the mailbox SM and startup parameters in that state; note that 0x0011 is an invalid state transition (TRANSIENT), not a mailbox configuration error
  • 0x001A synchronization error (CONFIGURATION) / 0x0034 DC synchronization timeout (TRANSIENT) (also 0x002C fatal synchronization error and 0x0032 PLL error, both TRANSIENT) — check the DC configuration and reference clock, then retry the state transition
  • 0x0050 no EEPROM access permission / 0x0051 EEPROM error (HARDWARE) — check the slave hardware and power supply

Slave error counters​

readSlaveErrorCounters(int slaveIndex)​

public EtherCATTypes.SlaveErrorCounters readSlaveErrorCounters(int slaveIndex)

Reads the error counter summary of the specified slave (CRC errors, frame errors, lost-frame statistics). This is a compatibility entry point with known reductions: port0CrcErrors~port3CrcErrors are the per-port values of the four ports, while frameErrors / lostFrames are sums over the four ports (frameErrors = total invalid frames across the four ports from ESC 0x0308-0x030B, lostFrames = total link losses across the four ports from ESC 0x0310-0x0313, the same convention as C++/Rust/C#), but the two are not split by port and do not include forwarding RX errors.

Parameters:

  • slaveIndex (int) — slave index (1-based, valid range 1–65535)

Returns:

  • SlaveErrorCounters — error counter summary; null = the read failed (it does not impersonate a "healthy" value of all 0s)

Exceptions:

  • IllegalArgumentException — slave index out of range (not in 1–65535)
  • IllegalStateException — the master has been released

Alternative entry point: for precise diagnostics use slave.diagnostics().readPortErrors() from the single authoritative entry point for per-slave port / mailbox data, slave diagnostics (four-port RX errors / invalid frames / link loss + forwarding RX errors).

Related structures:

public static class SlaveErrorCounters {
public int slaveIndex; // slave index
public long port0CrcErrors; // port 0 CRC errors
public long port1CrcErrors; // port 1 CRC errors
public long port2CrcErrors; // port 2 CRC errors
public long port3CrcErrors; // port 3 CRC errors
public long frameErrors; // frame error count (ESC 0x0308-0x030B invalid frames, summed over the four ports)
public long lostFrames; // lost-frame count (ESC 0x0310-0x0313 link loss, summed over the four ports)
}

Example:

EtherCATTypes.SlaveErrorCounters counters = master.diagnostics().readSlaveErrorCounters(1);
if (counters == null) {
System.out.println("从站 1 错误计数读取失败(不按 0 充当健康)"); // Slave 1 error counters could not be read (a 0 is not passed off as healthy)
} else if (counters.port0CrcErrors + counters.frameErrors + counters.lostFrames > 0) {
System.out.println("从站 1 错误计数:"); // Slave 1 error counters:
System.out.printf(" CRC 错误: P0=%d, P1=%d, P2=%d, P3=%d%n", // CRC errors: P0=%d, P1=%d, P2=%d, P3=%d%n
counters.port0CrcErrors, counters.port1CrcErrors,
counters.port2CrcErrors, counters.port3CrcErrors);
System.out.println(" 帧错误: " + counters.frameErrors); // Frame errors: {counters.frameErrors}
System.out.println(" 丢帧: " + counters.lostFrames); // Frame loss: {counters.lostFrames}
}

Diagnostic messages​

slave.coe().readDiagnosticMessages()​

public List<CoE.DiagnosticMessage> readDiagnosticMessages()

Reads diagnostic messages from slave object 0x10F3 (the diagnostics history object, ETG.1510) over CoE: first read the message count (subindex 0), then read subindices 1..N one by one. Returns the list of diagnostic events recorded by the slave.

Access path: slave.coe().readDiagnosticMessages()

Parameters: none (the slave is determined by the slave that slave.coe() belongs to).

Returns:

  • List<CoE.DiagnosticMessage> — list of diagnostic messages; returns an empty list when 0x10F3 is unsupported / the read fails / there are no messages

Failure semantics: an overall read failure returns an empty list (and is logged); a single failed read or an entry shorter than 8 bytes is skipped and logged, so the returned count may be smaller than the count the device declares — do not read an empty list as "this slave has no diagnostics".

Related structures:

public static class CoE.DiagnosticMessage {
public final byte SubIndex; // subindex
public final int DiagCode; // diagnostic code
public final short Flags; // flags
public final short TextIndex; // text index
public final byte[] RawData; // raw data
}

Example:

for (Slave slave : master.slaves()) {
// slave.coe() is created lazily and always returns an instance (never null)
CoE coe = slave.coe();

List<CoE.DiagnosticMessage> messages = coe.readDiagnosticMessages();
if (messages.isEmpty()) continue;

for (CoE.DiagnosticMessage msg : messages) {
System.out.printf("[从站 %d] 代码=0x%08X, %s%n", // [Slave %d] code=0x%08X, %s%n
slave.SlaveNum, msg.DiagCode, msg);
}
}
note

Not every slave supports the 0x10F3 diagnostics history object. Calling it on an unsupported slave returns an empty list. This method reads over SDO and should not be called at high frequency on a real-time path.

Diagnostics field guide by problem​

The diagnostics interfaces are all accessed through master.diagnostics() (which returns MasterDiagnosticsInfo). The table below maps on-site symptoms to the real getter:

SymptomField (Java getter / access path)
Is it packet loss?getPacketLossRate() + getLateFrameRate()
Are PDO frames being lost continuously?getPDO().getConsecutiveLost() (≥5 = sustained) + getPDO().getTotalLost()
Is cycle jitter large?getAvgJitterUs() / getBusMaxJitterUs() / getBusAvgJitterUs()
Are mailbox transactions slow?getMailboxLatencyUs() (maximum) / getMailboxLatencyAvgUs() (average)
Which slave is unstable?getWorstSlaveIndex() + getWorstLinkQuality()
CRC / frame errors on a slave?slave.diagnostics().readPortErrors() (see slave diagnostics); for the compatibility entry point readSlaveErrorCounters(i) see slave error counters
Which cable is broken / has CRC degradation?getBreakPoint() / getAllBreakPoints()
Are the primary and secondary ports healthy?isPrimaryPortOk() / isSecondaryPortOk() + getPrimaryPortErrors() / getSecondaryPortErrors()
Is redundancy really protecting?isRedundancyActive() (already includes redundancyRingMode() >= 1 and frames on both ports; to check frames on both ports only, read the primary / secondary port TX-RX counters)
Is the real-time runtime stable?getTimingMode() (FreeRun / DC Sync0 / DC Sync01) + getSmiCount() / getSmiPeakUs() / getCycleCount() / isHardwareSmiCounterAvailable()

Frames / packet loss​

  • getPacketLossRate(): packet loss rate = merged bus WKC deficit ÷ expected WKC (instantaneous value); 0 = not a single frame was really lost; only a cold start that has not reached OP falls back to the TX vs RX counter difference
  • getLateFrameRate(): late frame rate (the frame index is stale within an 8-frame window and is not counted as packet loss)
  • getPDO().getConsecutiveLost(): current consecutive lost frames (separates occasional from sustained loss; the key metric)
  • getPDO().getTotalLost(): cumulative lost frames (sum of all groups)
  • getErrorCnt(): errors per second (5-second average)

Port TX/RX​

  • isPrimaryPortOk() / isSecondaryPortOk(): whether the primary / secondary port is healthy
  • getPrimaryPortErrors() / getSecondaryPortErrors(): primary / secondary port errors in the last 5 seconds

Per-slave physical layer (port error counters)​

The single authoritative entry point for per-slave port errors is slave.diagnostics().readPortErrors(), which returns RX errors / invalid frames / link loss for the four ports plus forwarding RX errors (whether they were really read is marked by FwdRxErrorReadOK); use slave.diagnostics().linkQuality() for link quality.

The master-side master.diagnostics().readSlaveErrorCounters(slaveIndex) is a compatibility entry point that returns SlaveErrorCounters containing:

  • port0CrcErrors ~ port3CrcErrors: per-port CRC error counts (ESC 0x0300 / 0x0304)
  • frameErrors: frame error count (ESC 0x0308-0x030B invalid frames, summed over the four ports)
  • lostFrames: lost-frame count (ESC 0x0310-0x0313 link loss, summed over the four ports)

Bus real-time performance​

  • getBusCycleHz(): bus frequency (Hz)
  • getBusMaxJitterUs() / getBusAvgJitterUs(): maximum / average bus jitter (µs)
  • getBusRoundtripUs(): frame round-trip delay (µs)
  • getBusLoadPercent(): communication load (%)

Real-time runtime stability​

  • getTimingMode(): timing mode (FreeRun / DC Sync0 / DC Sync01)
  • getSmiCount() / getSmiPeakUs(): cumulative system management interrupt count and peak jitter (µs)
  • getCycleCount(): total number of completed PDO cycles
  • isHardwareSmiCounterAvailable(): whether the hardware SMI counter is readable

Full diagnostics workflow example​

MasterDiagnosticsInfo diag = master.diagnostics();
diag.setEnabled(true);

// 1. Sustained vs occasional PDO loss
if (diag.getPDO().getConsecutiveLost() >= 5) {
System.out.println("持续 PDO 丢帧"); // Persistent PDO frame loss
}

// 2. Packet loss rate
if (diag.getPacketLossRate() > 0.01f) {
System.out.printf("丢包率 %.2f%% 严重%n", diag.getPacketLossRate() * 100); // Packet loss rate %.2f%% is severe%n
}

// 3. Fault location
MasterDiagnosticsInfo.BreakPointInfo bp = diag.getBreakPoint();
if (bp != null) {
System.out.printf("故障点: 从站 %d P%d (%s)%n", // Fault point: slave %d P%d (%s)%n
bp.slaveIndex, bp.port, bp.isCrcFault() ? "CRC劣化" : "断线"); // CRC degradation / cable break
}

// 4. Most unstable slave
int worst = diag.getWorstSlaveIndex();
if (worst > 0) {
System.out.printf("最不稳定从站: #%d (链路质量 %d%%)%n", // Least stable slave: #%d (link quality %d%%)%n
worst, diag.getWorstLinkQuality());
}

// 5. Timing mode of the real-time runtime
System.out.println("定时模式: " + diag.getTimingMode()); // Timing mode: {diag.getTimingMode()}

NIC health diagnostics​

On site, "the scan finds no slaves" is often blamed directly on the slaves or the cabling, but the NIC transmit and receive path can be the real cause. The three entry points have distinct jobs: classify with a self-check first, then prove the fault with active probing, and only then consider recovery. All three are on master.diagnostics() (MasterDiagnosticsInfo).

CategoryMethodTypeR/WDescription
NIC self-checkdiagnoseNicHealth()intcallTwo-port health classification
NIC probeverifyNicHealth(int, int)intcallActively sends probe frames and gives a confirmed conclusion by comparing the transmit / receive counter growth before and after
NIC recoveryautoRecoverNic()intcallSoft-restarts the transmit and receive path (equivalent to a soft unplug and replug)

diagnoseNicHealth()​

public int diagnoseNicHealth()

Read-only self-check: it sends no operational frames and changes no configuration. It returns a classification result, not a generic error code.

Returns:

CategoryAttributeTypeR/WDescription
Self-check result0intread-onlyBoth ports healthy — the problem is on the slave or cabling side
Self-check result1intread-onlyPrimary port abnormal
Self-check result2intread-onlySecondary port abnormal
Self-check result3intread-onlyBoth ports abnormal
Self-check result-1intread-onlyThe current operating mode does not support this check

The detailed reason for the classification is written to the runtime log. Throws IllegalStateException when the master has been released.

Example:

int health = master.diagnostics().diagnoseNicHealth();
if (health > 0) {
System.out.println("网卡异常分类: " + health); // NIC fault classification: {health}
}

verifyNicHealth(int numProbes, int timeoutMs)​

public int verifyNicHealth(int numProbes, int timeoutMs)

Actively sends numProbes broadcast read probe frames and waits timeoutMs; the verdict rests on the actual growth of the transmit and receive counters before and after the probe, not on the link LED or the link status word.

Parameters:

  • numProbes (int) — number of probe frames, recommended 5, valid range 1–50
  • timeoutMs (int) — how long to wait for a reply (ms), recommended 200, valid range 50–5000

Returns:

CategoryAttributeTypeR/WDescription
Probe result0intread-onlyNIC healthy — the problem is on the slave side, so automatic recovery would not help
Probe result1intread-onlyPrimary-port transmit confirmed abnormal
Probe result2intread-onlyPrimary-port receive confirmed abnormal
Probe result3intread-onlyThe path from the application side to the NIC is not working (set the network again and scan again)
Probe result4intread-onlySecondary port abnormal
Probe result-1intread-onlyInvalid parameter, or the current operating mode does not support this check

Example:

int verdict = master.diagnostics().verifyNicHealth(5, 200);
switch (verdict) {
case 0:
System.out.println("网卡健康,去查从站侧"); // The NIC is healthy, look at the slave side
break;
case 1:
System.out.println("主口发送异常"); // Primary port transmit fault
break;
case 2:
System.out.println("主口接收异常"); // Primary port receive fault
break;
case 3:
System.out.println("提交路径不通,重新设置网络后重扫"); // The commit path is not working, reset the network and rescan
break;
default:
System.out.println("副口异常 / 参数或模式不支持: " + verdict); // Secondary port fault / parameter or mode unsupported: {verdict}
break;
}

autoRecoverNic()​

public int autoRecoverNic()

Soft-restarts the transmit and receive path (stops it, then starts it again after about 200 ms); the effect equals a soft unplug and replug of a USB NIC.

Returns: 1 = success, 0 = failure.

Behaviour / constraints:

  • The SDK never calls this method automatically. Call it only after the caller has explicitly confirmed the intent to repair, and log the operation so it can be traced.
  • After a successful recovery you must set the network again and start a new scan; the old topology view and the old slave handles no longer describe the current state.
  • Do not retry recovery repeatedly after a single failure. Go back to diagnoseNicHealth() / verifyNicHealth() to establish which segment is not working before deciding the next step.

Example:

if (master.diagnostics().verifyNicHealth(5, 200) == 2) {
System.out.println("主口接收确诊异常,执行软恢复"); // Primary port receive fault confirmed, performing a soft recovery
if (master.diagnostics().autoRecoverNic() == 1) {
master.setNetwork(networkPath);
// Re-scan / rebuild the topology
}
}

getPhyLinkState() is on master.diagnostics(); topoP1FullWkc() is on master.

CategoryMethodTypeR/WDescription
Port linkgetPhyLinkState()intcallPhysical link bitmap of the two ports
Port topologytopoP1FullWkc()intcallMeasured full-load WKC calibration value for P1

getPhyLinkState()​

public int getPhyLinkState()

Same value as getPhyLinkBitMask(): the physical link bitmap of the two ports.

Returns: bit0 = primary port Up, bit1 = secondary port Up; 0xFFFF = not observable. When you need a per-port tri-state value (UP / DOWN / UNKNOWN), use getPrimaryPhyLinkState() / getSecondaryPhyLinkState().

UNKNOWN only means the value cannot be read or has not been decided yet; it is not DOWN. Do not report a link break or trigger fault handling on the strength of it.

Example:

int mask = master.diagnostics().getPhyLinkState();
if (mask != 0xFFFF) {
System.out.println("主口 Up: " + ((mask & 0x1) != 0)); // Primary port up: {(mask & 0x1) != 0}
System.out.println("副口 Up: " + ((mask & 0x2) != 0)); // Secondary port up: {(mask & 0x2) != 0}
}

topoP1FullWkc()​

public int topoP1FullWkc()

The measured full-load WKC calibration value of the P1 foldback topology (dual-NIC ring plus branch), i.e. the expected Working Counter when the whole ring is traversed.

Returns: full-load WKC; -1 = not available (not calibrated, or the current topology is not dual-NIC ring plus branch). When it cannot be read it returns -1 as it is — do not scale it to 0 and do not use it as a general expected value.

Example:

int full = master.topoP1FullWkc();
if (full > 0) {
System.out.println("P1 满载 WKC: " + full); // P1 full-load WKC: {full}
}

DC reference clock and drift​

The master-level DC summary settles once per second; read dcDiagnostics() when you need a tri-state conclusion. A 0 on the summary side often does not distinguish "no DC slave / not armed / genuinely 0", so check getDcHasDc() before interpreting it. Every entry point in this group is on master.diagnostics().

CategoryMethodTypeR/WDescription
DC presencegetDcHasDc()booleancallWhether a DC slave exists on the network
DC driftgetDcMaxDriftNs()intcallMaximum absolute synchronization difference (ns)
DC reference clockgetDcReferenceClockSlave()intcallReference-clock slave index (1-based)
DC sync conclusiongetDcAllInSync()BooleancallTri-state synchronization conclusion
DC reference clockdcReferenceClock()DcReferenceClockInfocallReference-clock slave index + tier + reason
DC countsdcArmedSlaveCount()intcallNumber of slaves with SYNC0 armed
DC countsdcActiveSlaveCount()intcallNumber of DC-active slaves

getDcHasDc()​

public boolean getDcHasDc()

Whether a DC (Distributed Clocks) slave exists on the network.

Returns: true = yes; when the summary cannot be read it returns false, which means "not confirmed" — do not conclude that the slaves do not support DC.

Example:

if (!master.diagnostics().getDcHasDc()) {
System.out.println("未确认网内有 DC 从站,暂不解读同步结论"); // No DC slaves confirmed in the network, sync conclusions are not interpreted for now
}

getDcMaxDriftNs()​

public int getDcMaxDriftNs()

Current maximum absolute system-time difference across all DC slaves (ns). The reference clock itself is not counted — by definition it has no synchronization error.

Returns: the maximum deviation; 0 is the summary default and does not distinguish 「no DC slave / not armed / genuinely 0 ns」. For a tri-state answer read dcDiagnostics().maxDriftNs (null = no applicable window).

getDcReferenceClockSlave()​

public int getDcReferenceClockSlave()

Returns: reference-clock slave index (1-based); 0 = no DC slave on the network, or the summary cannot be read. To learn why that slave was chosen and which tier it has, use dcReferenceClock().

getDcAllInSync()​

public Boolean getDcAllInSync()

The summary-level "everything is inside the sync window" conclusion, tri-state.

Returns:

  • true — every DC participant is inside the window;
  • false — some slave is outside the window, or the failing conclusion "zero DC participants" (treated as a failure, not as "nothing can be out of sync");
  • null — the summary cannot be read and the conclusion is unknown; do not pass off true / false in its place.

When you need participant semantics (which slaves take part in the decision), read dcDiagnostics().allInSync.

dcReferenceClock()​

public DcReferenceClockInfo dcReferenceClock()

Master-level reference-clock facts.

Returns: DcReferenceClockInfo, never null; with no DC slave it returns DcReferenceClockInfo.NONE and never fabricates a fact such as 「slave index 0 + armed」.

CategoryAttributeTypeR/WDescription
Reference clockslaveIndexintread-onlyReference-clock slave index (1-based); 0 = none
Reference clocktierDcReferenceClockTierread-onlyTier, used for display only and not part of clock selection
Reference clocktierTextStringread-onlyTier reason text, suitable for showing to on-site staff as it is
Reference clockisChainHeadFallbackbooleanread-onlytrue = no armed slave was found, so it fell back to the chain-head DC slave (that slave is not the real reference clock)
Reference clockisKnown()booleanread-onlytrue = a reference-clock slave index exists (it does not mean the tier has been decided)

DcReferenceClockTier values:

CategoryAttributeTypeR/WDescription
TierUNKNOWNint = 0read-onlyCannot be decided (slave snapshot unreadable / reference-clock object unavailable)
TierNONEint = 1read-onlyNo armed DC slave; fell back to the chain-head DC slave
TierUSERint = 2read-onlyExplicitly set by the user (the current SDK has no configuration entry point for it, so this face never produces it)
TierPDO_PROVENint = 3read-onlyHas PDO + SYNC0 armed + valid cycle0 (the best tier)
TierPDO_ARMEDint = 4read-onlyArmed slave with PDO
TierNO_PDOint = 5read-onlyArmed slave without PDO (fallback tier; keep an eye on it on site)

Example:

DcReferenceClockInfo ref = master.diagnostics().dcReferenceClock();
if (ref.isChainHeadFallback) {
System.out.println("参考钟是链首回退,不是真参考钟: #" + ref.slaveIndex); // The reference clock is a fallback to the head of the chain, not a real reference clock: #{ref.slaveIndex}
} else {
System.out.printf("参考钟: #%d,档位 %s(%s)%n", // Reference clock: #%d, tier %s (%s)%n
ref.slaveIndex, ref.tier, ref.tierText);
}

dcArmedSlaveCount()​

public int dcArmedSlaveCount()

From the 2-second DC snapshot: the number of slaves whose SYNC0 is really armed (sync0Armed == true).

Returns: slave count; 0 is a legitimate count (this network really has no armed slave). The conclusion comes from the 2-second DC snapshot; throws IllegalStateException when the master has been released.

dcActiveSlaveCount()​

public int dcActiveSlaveCount()

Number of DC-active slaves (the landed DC activation value is anything other than 0). This is not the same conclusion as "armed": armed reflects intent, active reflects what landed.

Returns: slave count; 0 is a legitimate count. The conclusion comes from the 2-second DC snapshot; throws IllegalStateException when the master has been released.

Example:

MasterDiagnosticsInfo diag = master.diagnostics();
System.out.printf("已武装 %d 站,DC-active %d 站%n", // %d slaves armed, %d slaves DC-active%n
diag.dcArmedSlaveCount(), diag.dcActiveSlaveCount());

DC sync window​

Every entry point in this group is on master.diagnostics().

CategoryMethodTypeR/WDescription
Sync windowdcSyncWindowThresholdNs()IntegercallSync window threshold (ns)
DC samplingtryGetDcSample(int)DcSlaveSnapshotcallReturns the conclusion for one slave from the most recent completed sampling without triggering a new one
DC samplinginvalidateDcSnapshot()voidcallInvalidates the current DC sampling cache and the per-slave history

dcSyncWindowThresholdNs()​

public Integer dcSyncWindowThresholdNs()

Sync window threshold (ns), used to interpret whether the measured difference in DcSyncWindowInfo is inside the window.

Returns: the threshold; null = cannot be read (distinct from 「threshold 0」). The default is 1000 ns and it can be changed with setSyncWindowThreshold(int) (see DC synchronization).

tryGetDcSample(int slaveIndex)​

public DcSlaveSnapshot tryGetDcSample(int slaveIndex)

Returns the conclusion for one slave from the most recently completed DC sampling without triggering a new one. It suits read-only paths such as slave properties and UI rendering, so that reading a property does not in turn trigger a full snapshot.

Parameters:

  • slaveIndex (int) — slave index (1-based)

Returns: DcSlaveSnapshot; not sampled yet / out of range returns null (do not read that as "in sync").

Example:

DcSlaveSnapshot s = master.diagnostics().tryGetDcSample(2);
if (s == null) {
System.out.println("从站 2 还没有 DC 采样结论"); // Slave 2 has no DC sampling conclusion yet
} else {
System.out.println("从站 2 武装: " + s.sync0Armed + ", 窗口: " + s.syncWindow); // Slave 2 armed: {s.sync0Armed}, window: {s.syncWindow}
}

invalidateDcSnapshot()​

public void invalidateDcSnapshot()

Invalidates the current DC sampling cache and the per-slave sampling history; the next read assembles them again. The SDK also calls it internally when the master closes, so a diagnostics object you hold does not read old samples after shutdown.

Returns: none. After the call tryGetDcSample(...) returns null until the next sampling completes.

Propagation delay resolution​

Once the DC propagation delay (the fixed latency introduced by the cabling and by processing inside the slaves) has been resolved successfully, the master records it so that on-site staff can tell which resolution the current DC offset rests on. The entry points in this group are on master (EtherCATMaster).

CategoryMethodTypeR/WDescription
Propagation delaydcPropagationDelayResolvedAtUtc()InstantcallTime of the most recent successful resolution (UTC)
Propagation delaydcPropagationDelayResolveCount()intcallNumber of successful resolutions in this process (recorded together with that time)

dcPropagationDelayResolvedAtUtc()​

public Instant dcPropagationDelayResolvedAtUtc()

Time (UTC) of the most recent propagation-delay resolution triggered explicitly by the SDK. Triggers: updatePropagationDelays() / autoCalculateDCShift() / configureDCAll(int, int).

Returns: the time of a successful resolution; null = none observed in this process (for example, only the measurement completed automatically at startup).

Reading convention: that time is not the physical measurement time — the same session may reuse an existing baseline. It only answers "when the most recent resolution was recorded" and is no evidence that "the cable has just been measured".

dcPropagationDelayResolveCount()​

public int dcPropagationDelayResolveCount()

The count recorded together with dcPropagationDelayResolvedAtUtc().

Returns: number of resolutions triggered explicitly by the SDK and successful in this process; 0 = none observed.

Example:

Instant at = master.dcPropagationDelayResolvedAtUtc();
int n = master.dcPropagationDelayResolveCount();
System.out.println(n == 0
? "本进程未观测到传播延迟解析" // No propagation delay resolution observed in this process
: ("已解析 " + n + " 次,最近一次 " + at)); // Resolved {n} times, most recently {at}

Master recovery observation​

Recovery advances as a ladder: classify first, then recover level by level, with readable state and events at every step. Every entry point in this group is read-only, neither triggers recovery nor affects the cycle, and all are on master.diagnostics().

CategoryMethodTypeR/WDescription
Recovery observationslaveRecovery(int)SlaveRecoveryStatuscallPer-slave recovery status
Recovery observationmasterRecoveryLadder()read-only observation objectcallMaster-level recovery observation
Recovery observationrecoveryLadderSeq()longcallMaster-level observation freshness token
Recovery eventrecoveryEvents(int, int)List<RecoveryEvent>callIncremental read of recovery events

slaveRecovery(int slaveIndex)​

public SlaveRecoveryStatus slaveRecovery(int slaveIndex)

Per-slave recovery status projection. When observation is unavailable (older runtime / no instance / slave index out of range / master unavailable) it returns a sentinel with available=false; it never fabricates Idle and never throws to the caller (the reason is written to the runtime log).

Parameters:

  • slaveIndex (int) — slave index (1-based)

Returns: SlaveRecoveryStatus, non-null. When available == false the following fields are meaningless.

CategoryAttributeTypeR/WDescription
Recovery stateavailablebooleanread-onlyfalse = observation unavailable (not "no recovery")
Recovery statelevelSlaveRecoveryLevelread-onlyCurrent level
Recovery statestepSlaveRecoveryStepread-onlyCurrent step; null = a step outside the domain (unknown, never fabricated)
Recovery statelastStepSlaveRecoveryStepread-onlyPrevious step (transitions stay traceable)
Recovery statefailReasonSlaveRecoveryReasonread-onlyReason the previous step failed (None = none)
Recovery statefailAlscintread-onlyAL status code measured at the failure; 0 = none / not read
Recovery stateretryCountintread-onlyAttempts in this round
Recovery statebackoffRemainMslongread-onlyBackoff remaining (ms); 0 = free to act at any time
Recovery statestepElapsedMslongread-onlyTime already spent in the current step (ms); use it to tell where it is stuck
Recovery stateskipFrameslongread-onlyCumulative skipped recovery frames
Recovery stateseqlongread-onlyState-transition counter (judge observation freshness with it)
Recovery stateflagsintread-onlyRaw state-bit byte
Recovery statelastResultOkSlaveRecoveryResultread-onlyPrevious step result (Ok / Failed / Suppressed / Unknown)
Recovery stateclassifySlaveRecoveryClassread-onlyRecovery classification (None / A / B1 / B2 / B3 / Unknown)
Recovery statepausedA / needsReconfig / ladderExhausted / epiloguebooleanread-onlyFour state bits: paused / configuration not replayed / suspended after repeated failures / finishing up
Recovery stateisActive()booleanread-onlyThe ladder is advancing (not Idle / Done / Unknown)

Example:

SlaveRecoveryStatus st = master.diagnostics().slaveRecovery(3);
if (!st.available) {
System.out.println("从站 3 恢复观测不可用"); // Slave 3 recovery observation unavailable
} else if (st.isActive()) {
System.out.printf("从站 3: %s/%s 已耗时 %d ms(%s)%n", // Slave 3: %s/%s has been running %d ms (%s)%n
st.level, st.step, st.stepElapsedMs, st.failReason);
}

masterRecoveryLadder()​

Snapshot entry point for master-level recovery observation; it returns the read-only observation object published on MasterDiagnosticsInfo. When unavailable it returns a sentinel with available=false and does not throw; a read error is logged and treated as unavailable.

At present only triggerBlockedTotal has a real collected value; every other extended field is null = not collected, not 0 (EXTENDED_FIELDS_COLLECTED is false at present).

CategoryAttributeTypeR/WDescription
Master recoveryavailablebooleanread-onlyfalse = observation unavailable
Master recoverytriggerBlockedTotalLongread-onlyCumulative "trigger hit but not executed in this round"; null = observation unavailable (not 0 times)
Master recoveryrebuildReqPendingBooleanread-onlyA full-network rebuild request is pending and unconsumed; null = not collected
Master recoveryrebuildActiveBooleanread-onlyA full-network rebuild is running; null = not collected
Master recoveryrebuildFailIntegerread-onlyConsecutive full-network rebuild failures; null = not collected
Master recoveryalarmOnlyBooleanread-onlyAlarm-only tier; null = not collected
Master recoveryhandoffBusyBooleanread-onlyOrchestration is busy; null = not collected
Master recoveryaSuppressedBooleanread-onlySuppression is in effect; null = not collected
Master recoverybadPersistentBooleanread-onlyThe criterion stays abnormal; null = not collected
Master recoveryladderExhaustedBooleanread-onlySome slave is suspended after repeated failures; null = not collected
Master recoverybackoffRemainMsLongread-onlyBackoff remaining (ms); null = not collected
Master recoverybadSinceMsLongread-onlyStart of the sustained abnormality (ms); null = not collected
Master recoveryrebuildTotalLongread-onlyFull-network rebuilds in this session; null = not collected
Master recoveryseqLongread-onlyToken inside the structure (not produced at present, always null); use recoveryLadderSeq() for the real token

Example:

var ladder = master.diagnostics().masterRecoveryLadder();
if (!ladder.available) {
System.out.println("主站级恢复观测不可用"); // Master-level recovery observation unavailable
} else if (ladder.triggerBlockedTotal != null && ladder.triggerBlockedTotal > 0) {
System.out.println("触发被压制累计: " + ladder.triggerBlockedTotal); // Triggers suppressed, cumulative: {ladder.triggerBlockedTotal}
}

recoveryLadderSeq()​

public long recoveryLadderSeq()

Freshness token for master-level recovery observation (monotonically increasing).

Returns: the token; 0 = unavailable or no transition yet (an honest value, not a guess). A token that stops increasing means the recording thread is not running — do not treat an old observation as the current state.

recoveryEvents(int sinceSeq, int max)​

public List<RecoveryEvent> recoveryEvents(int sinceSeq, int max)

Incremental read of recovery events: returns the events whose seq is strictly greater than sinceSeq. To consume continuously, convert the last event's seq to its int bit pattern and pass it back as the cursor.

Parameters:

  • sinceSeq (int) — cursor (32-bit unsigned bit pattern); 0 = start from the oldest readable event in the ring
  • max (int) — how many to return at most; <= 0 is treated as 256; the upper bound is MasterDiagnosticsInfo.RECOVERY_EVENT_RING_CAPACITY (= 256)

Returns: List<RecoveryEvent>; no new events / unavailable returns an empty list (it does not throw). The event ring has a fixed capacity, so when sinceSeq has expired you can only continue from the oldest readable event; the caller de-duplicates by seq.

RecoveryEvent fields:

CategoryAttributeTypeR/WDescription
Recovery eventseqlongread-onlyEvent sequence number (monotonic; use it as the next cursor)
Recovery eventslaveintread-onlySlave index; 0 = a master-level event
Recovery eventkindSlaveRecoveryEventKindread-onlyEvent kind
Recovery eventfromLevel / toLevelSlaveRecoveryLevelread-onlyLevel before / after the transition
Recovery eventfromStep / toStepSlaveRecoveryStepread-onlyStep before / after the transition; null = a step outside the domain
Recovery eventreasonSlaveRecoveryReasonread-onlyReason (None = none)
Recovery eventokSlaveRecoveryResultread-onlyExecution result
Recovery eventalscintread-onlyMeasured AL status code; 0 = none
Recovery eventtickMslongread-onlyEvent time (ms)

Example:

MasterDiagnosticsInfo diag = master.diagnostics();
int cursor = 0;
for (RecoveryEvent e : diag.recoveryEvents(cursor, 64)) {
System.out.printf("[%d] 从站 %d %s→%s (%s)%n", // [%d] slave %d %s→%s (%s)%n
e.seq, e.slave, e.fromLevel, e.toLevel, e.reason);
cursor = (int) e.seq;
}

Lost-slave counting and probe truth​

Across the SDK the lost-slave count has exactly one definition: lostSlaveCensus(). Probe truth splits the per-slave replies into three states, and a slave with insufficient evidence must not be used to blame anything. Every entry point in this group is on master.diagnostics().

CategoryMethodTypeR/WDescription
Lost slaveslostSlaveCensus()LostSlaveCensuscallLost-slave count and the index of the first lost slave (the single definition)
Probe truthprobeTruth()ProbeTruthcallSummary of the slaves that replied / contribute WKC / lack evidence

lostSlaveCensus()​

public LostSlaveCensus lostSlaveCensus()

Returns: LostSlaveCensus, non-null; when the call fails, count = 0 (honestly unknown; it does not invent lost slaves).

CategoryAttributeTypeR/WDescription
Lost slavescountintread-onlyLost-slave count; 0 = no lost slave or probing not observable (the two are not distinguished)
Lost slavesfirstSlaveIndexintread-onlyIndex of the first lost slave (1-based); 0 = none. This is an index, not a count

Example:

LostSlaveCensus census = master.diagnostics().lostSlaveCensus();
System.out.printf("丢站数 %d,首个 #%d%n", census.count, census.firstSlaveIndex); // %d slaves lost, first one #%d%n

probeTruth()​

public ProbeTruth probeTruth()

Real-time truth summary of the per-slave addressing replies.

Returns: ProbeTruth, non-null; available = false = no truth sample in this round (nothing is invented).

CategoryAttributeTypeR/WDescription
Probe truthavailablebooleanread-onlyfalse = probing not observable (do not read the 0 at that moment as "everything is offline")
Probe truthaliveCountintread-onlyNumber of slaves that really replied in this round
Probe truthwkcBoundSlavesintread-onlyNumber of slaves that replied and contribute WKC
Probe truthunknownCountintread-onlyNumber of slaves with insufficient evidence (must not be used to blame anyone)

Example:

ProbeTruth truth = master.diagnostics().probeTruth();
if (!truth.available) {
System.out.println("本轮没有可用探测真值"); // No usable probe ground truth in this round
} else {
System.out.printf("有应答 %d,贡献 WKC %d,证据不足 %d%n", // %d responding, %d contributing WKC, %d with insufficient evidence%n
truth.aliveCount, truth.wkcBoundSlaves, truth.unknownCount);
}

Cycle statistics sliding window​

Every entry point in this group is on master.diagnostics().

CategoryMethodTypeR/WDescription
Cycle sliding windowdiagCsWindowStats()CsWindowStatscallReturns the 5-second sliding-window statistics (cycle frequency / error rate / average jitter)
Cycle sliding windowdiagCsWindowSample(long, long)voidcallFeeds one sample into the sliding window (for external feeding or replay)
Cycle sliding windowdiagCsWindowReset()voidcallEmpties the sliding window

diagCsWindowStats()​

public CsWindowStats diagCsWindowStats()

Returns the 5-second sliding-window statistics and does not throw to the caller.

Returns: CsWindowStats, non-null.

CategoryAttributeTypeR/WDescription
Window statisticsavailablebooleanread-onlyfalse = the window is unavailable (illegal master number / not ready yet); the numeric fields are meaningless then
Window statisticserrorPerSecdoubleread-onlyErrors per second (Σerr×1000/Σms inside the window; a window shorter than 1 ms records 0)
Window statisticscycleHzdoubleread-onlyCycle frequency (Hz, same formula as above)
Window statisticsavgJitterUsdoubleread-onlyAverage jitter (µs); records 0 when the sample count is 0
Window statisticsfilledintread-onlyNumber of samples already fed into the window

Only when available == true does a 0 mean a measured 0; when available == false a 0 only means "no data".

Example:

CsWindowStats cs = master.diagnostics().diagCsWindowStats();
if (cs.available) {
System.out.printf("周期 %.1f Hz,错误 %.2f/s,平均抖动 %.2f us(已填 %d 拍)%n", // Cycle %.1f Hz, errors %.2f/s, average jitter %.2f us (%d cycles filled)%n
cs.cycleHz, cs.errorPerSec, cs.avgJitterUs, cs.filled);
} else {
System.out.println("周期滑窗尚不可用"); // The cycle sliding window is not available yet
}

diagCsWindowSample(long nowTimestamp, long timestampFreq)​

public void diagCsWindowSample(long nowTimestamp, long timestampFreq)

Feeds one sample into the sliding window. Normally the master's cycle path feeds it automatically; call it only when an external source feeds or replays the window.

Parameters:

  • nowTimestamp (long) — current timestamp (same clock source as timestampFreq)
  • timestampFreq (long) — timestamp frequency (ticks per second)

Returns: none. A failure is only written to the runtime log and does not throw.

diagCsWindowReset()​

public void diagCsWindowReset()

Empties the sliding window: the sample count returns to zero and statistics accumulate again.

Returns: none; when an older runtime lacks this entry point it is only written to the runtime log.

Diagnostics control and snapshot refresh​

This group of switches on the master (methods of EtherCATMaster) and master.diagnostics() operate on the same runtime state, but they are not equivalent: diagnostics().setEnabled(true) also starts the Java-side sliding-window sampling timer, while setDiagnosticsEnabled(true) only toggles the runtime-side collection switch. For window metrics (frame rate / jitter / error rate) use diagnostics().setEnabled(...).

CategoryMethodTypeR/WDescription
Diagnostics controlsetDiagnosticsEnabled(boolean)voidcallToggles the runtime-side diagnostics collection switch
Diagnostics controldiagnosticsEnabled()booleancallCurrent switch state
Diagnostics controlresetDiagnostics()voidcallResets master-level diagnostic counters
Snapshot refreshupdateDiagnosticsSnapshot()voidcallSamples the diagnostics snapshot once again
Snapshot refreshupdateDiagnosticsWithESCErrors()voidcallFolds in the ESC error counters before settling diagnostics
Snapshot refreshrecordWKC(short)voidcallRecords one measured WKC into the statistics window
Detail entry pointdetailedDiagnostics()PointercallPointer to the detailed diagnostics data structure (read-only view)
Master diagnostics objectgetMasterDiagData()DarraCore.MasterDiagDatacallReads the master diagnostics data of ETG.1510 object 0xF120

setDiagnosticsEnabled(boolean enable)​

public void setDiagnosticsEnabled(boolean enable)

Access path: master.setDiagnosticsEnabled(boolean)

Parameters:

  • enable (boolean) — true turns on the runtime-side optional statistics; false turns them off.

Returns: none. Throws IllegalStateException when the master has been released.

Difference from diagnostics().setEnabled: this method only toggles the runtime-side switch; it does not start or stop the Java-side sliding-window sampling. When you need window metrics such as getRTcnt() / getAvgJitterUs(), still use diagnostics().setEnabled(true) from diagnostics control.

diagnosticsEnabled()​

public boolean diagnosticsEnabled()

Access path: master.diagnosticsEnabled()

Returns: the current switch state. Throws IllegalStateException when the master has been released.

resetDiagnostics()​

public void resetDiagnostics()

Access path: master.resetDiagnostics()

Resets master-level diagnostic counters.

Returns: none. It clears only the runtime-side counters; to also clear the PDO frame-loss groups and the Java-side sliding-window accumulation, use diagnostics().reset() (see diagnostics control). Slave port error counters and DC sync window statistics are cleared separately by slave.diagnostics().resetPortErrors() and slave.DC().resetSyncWindowStats().

updateDiagnosticsSnapshot()​

public void updateDiagnosticsSnapshot()

Access path: master.updateDiagnosticsSnapshot()

Samples the master-level diagnostics snapshot again immediately, so that the window metrics read afterwards reflect the newest sample.

Returns: none. When you need a conclusion that is consistent within one sample, use a dedicated snapshot (such as dcDiagnostics()); do not rely on this method to turn field-by-field reads into an atomic read.

updateDiagnosticsWithESCErrors()​

public void updateDiagnosticsWithESCErrors()

Access path: master.updateDiagnosticsWithESCErrors()

Folds ESC-side error counters such as invalid frames and link loss into the diagnostics summary, so that physical errors on the slave side show up in the master statistics.

Returns: none.

recordWKC(short wkc)​

public void recordWKC(short wkc)

Access path: master.recordWKC(short)

Records one measured Working Counter into the master statistics window. The cycle path normally records it automatically; feed it manually only for custom acquisition or replay scenarios.

Parameters:

  • wkc (short) — WKC measured in this sample

Returns: none.

detailedDiagnostics()​

public Pointer detailedDiagnostics()

Access path: master.detailedDiagnostics()

Returns a read-only view pointer to the detailed diagnostics data structure. Use it for cross-language comparison or when you need every raw field; for everyday diagnostics prefer getSnapshot() and the dedicated getters.

Returns: the pointer object; throws IllegalStateException when the master has been released. Read-only: do not write through it or release it.

getMasterDiagData()​

public DarraCore.MasterDiagData getMasterDiagData()

Reads the master diagnostics data corresponding to ETG.1510 object 0xF120.

Returns: DarraCore.MasterDiagData; a failed read returns null (it does not return an all 0s object pretending to be a success).

CategoryAttributeTypeR/WDescription
Master diagnosticsCyclicLostFramesintread-onlyLost cyclic frames
Master diagnosticsAcyclicLostFramesintread-onlyLost acyclic frames
Master diagnosticsCyclicFramesPerSecintread-onlyCyclic frames per second
Master diagnosticsAcyclicFramesPerSecintread-onlyAcyclic frames per second
Master diagnosticsMasterStateshortread-onlyCurrent master state

Example:

DarraCore.MasterDiagData d = master.getMasterDiagData();
if (d == null) {
System.out.println("主站诊断数据读取失败"); // Failed to read master diagnostic data
} else {
System.out.printf("周期丢帧 %d,非周期丢帧 %d,状态 %d%n", // Cyclic frame loss %d, non-cyclic frame loss %d, state %d%n
d.CyclicLostFrames, d.AcyclicLostFrames, d.MasterState);
}

Diagnostic event callbacks​

The entry points in this group are on EtherCATMaster.

CategoryMethodTypeR/WDescription
Event callbackregisterRedundancyModeChangedCallback(DarraCore.RedundancyModeChangedCallback)voidcallRegisters a redundancy-mode change callback
Event callbacksetDCSyncLostCallback(DarraCore.DCSyncLostCallback)voidcallRegisters a DC sync-loss callback

registerRedundancyModeChangedCallback(DarraCore.RedundancyModeChangedCallback callback)​

public void registerRedundancyModeChangedCallback(DarraCore.RedundancyModeChangedCallback callback)

Registers a redundancy-mode change callback; the parameters are (short masterIndex, int oldMode, int newMode).

Access path: master.registerRedundancyModeChangedCallback(callback)

Parameters:

  • callback — the callback implementation; a later registration overrides the earlier one, and passing null means no more dispatch.

Returns: none. The callback runs on the SDK event thread, so do not block inside it; exceptions thrown by the callback are swallowed, so do not rely on them to carry errors.

setDCSyncLostCallback(DarraCore.DCSyncLostCallback callback)​

public void setDCSyncLostCallback(DarraCore.DCSyncLostCallback callback)

Registers a DC sync-loss callback; the parameters are (short masterIndex, short slaveIndex, int diffNs).

Access path: master.setDCSyncLostCallback(callback)

Parameters:

  • callback — the callback implementation; a later registration overrides the earlier one, and passing null means no more dispatch.

Returns: none. This callback and the DCSyncLost event listener are two independent channels and both fire; register the same handling logic in only one of them to avoid processing the same event twice.

PDO thread binding measurement​

This entry point is on EtherCATMaster.

pdoThreadCpuEffectiveCore()​

public int pdoThreadCpuEffectiveCore()

The CPU core the PDO thread is actually bound to (it reads the real thread mask).

Returns: the core number when a single core is bound; -1 as it is when the thread is unbound / bound to a multi-core mask / not running / unreadable.

It is not the same as "what the user configured": the configured value only reflects the intent of the setting, and it may have been set without ever being bound. Use this method to judge whether isolation really took effect.

Example:

int core = master.pdoThreadCpuEffectiveCore();
System.out.println(core >= 0
? ("PDO 线程实际绑定核 " + core) // PDO thread actually bound to core {core}
: "PDO 线程未绑定 / 不可读"); // PDO thread not bound / unreadable

Clean jitter observation​

This entry point is on master.diagnostics().

getBusCleanMaxJitterUs()​

public double getBusCleanMaxJitterUs()

The maximum jitter with system management interrupt effects excluded (µs). Compare it with getBusMaxJitterUs(): a large gap between the two means the jitter comes mainly from system management interrupts.

Returns: the maximum jitter with system management interrupt effects excluded (µs); a failed read returns 0.0 — interpret it as "not sampled", not as "zero jitter".

Example:

MasterDiagnosticsInfo diag = master.diagnostics();
System.out.printf("最大抖动 %.2f us,干净最大抖动 %.2f us%n", // Max jitter %.2f us, clean max jitter %.2f us%n
diag.getBusMaxJitterUs(), diag.getBusCleanMaxJitterUs());