Master diagnostics
Access all diagnostics, monitoring and statistics through master.diagnostics().
Drive exception handling from events instead of polling on your own. Reading diagnostic properties directly suits UI display and similar scenarios.
Feature overview
| Feature | Description |
|---|---|
| Communication and performance statistics | Frame counts, packet loss, jitter, PDO frame loss, port status, topology |
| DC synchronization | DC state and deviation, DCSyncLost event |
| Redundancy status | Redundancy active, fault point detection (link break and CRC fault location) |
| Diagnostics snapshot | A consistent snapshot of every diagnostic metric in one call |
| Diagnostics control | Start and stop data collection, reset statistics |
Communication and performance statistics
| Category | Method | Type | R/W | Description |
|---|---|---|---|---|
| Frame counts | getRTcnt() | int | read-only | Frames per second (Hz); 5-second sliding window, falls back to the runtime summary when not ready |
| Frame counts | getErrorCnt() | long | read-only | Errors per second, 5-second average |
| Frame counts | getPacketLossRate() | float | read-only | Packet loss rate (0.0~1.0) = merged bus WKC deficit ÷ expected WKC (instantaneous value); 0 = no frame was really lost (a 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 counts | getLateFrameRate() | float | read-only | Late 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 jitter | getCycleTimeSpan() | int | read-only | Actual cycle time (µs). Compare it with the LoopCycle setting; it is not hard-coded to 1 ms |
| Cycle and jitter | getAvgJitterUs() | double | read-only | Average 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 latency | getMailboxLatencyUs() | double | read-only | Maximum mailbox transaction round-trip time (µs, settled over the last 1 second) |
| Mailbox latency | getMailboxLatencyAvgUs() | double | read-only | Average mailbox transaction round-trip time (µs, settled over the last 1 second) |
| Bus real-time performance | getBusCycleHz() | long | read-only | Bus frequency (Hz) |
| Bus real-time performance | getBusMaxJitterUs() | double | read-only | Maximum bus jitter (µs) |
| Bus real-time performance | getBusAvgJitterUs() | double | read-only | Average bus jitter (µs) |
| Bus real-time performance | getBusRoundtripUs() | double | read-only | Frame round-trip delay (µs) |
| Bus real-time performance | getBusLoadPercent() | double | read-only | Communication load (%), derived value = round-trip delay / cycle × 100 |
| Bus real-time performance | getSmiCount() | long | read-only | Cumulative number of system management interrupts |
| Bus real-time performance | getSmiPeakUs() | double | read-only | Peak jitter of system management interrupts (µs) |
| Bus real-time performance | getCycleCount() | long | read-only | Total number of completed PDO cycles |
| Bus real-time performance | isHardwareSmiCounterAvailable() | boolean | read-only | Whether the hardware SMI counter is readable |
| PDO frame loss | getPDO().getTotalLost() | int | read-only | Cumulative lost frames (sum of all groups) |
| PDO frame loss | getPDO().getConsecutiveLost() | int | read-only | Current consecutive lost frames (maximum across all groups) |
| PDO frame loss | getPDO().getFrameLossStats(int) | int[] | read-only | Frame 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 anomalies | getWorstSlaveIndex() | int | read-only | Index of the slave with the worst link quality (not an "error rate") |
| Slave anomalies | getWorstLinkQuality() | short | read-only | Worst link quality (%), -1 = unknown |
| Master truth | lostSlaveCount() | int | read-only | Lost-slave census count (the single authority for the bus-level lost-slave count); >0 = a slave is lost; -1 = read failed / unavailable (use it together with lostSlaveCountKnown()) |
| noProcessData() | boolean | read-only | Master-level "no process data / false OP" truth value: true = the cycle is running but the process data is dead; a read failure returns true (fail-safe) | |
| noProcessDataKnown() | boolean | read-only | Whether noProcessData() has a measured sample; when false the return value carries no meaning and must be shown as "unknown" | |
| probeAliveCount() / probeUnknownCount() | int | read-only | Probe truth summary (number of slaves that answered / number of slaves with insufficient evidence); 0 when there is no true-value sample | |
| staleInputCount() | int | read-only | Number of slaves whose input data is confirmed STALE (per slave inputDataValidity()==STALE); UNKNOWN / DEGRADED are not counted; -1 = a slave read failed / is unavailable | |
| Cycle run | cycleState() | CycleRunState | read-only | Master cycle tri-state: NotStarted / StartedNoAdvance / Advancing; 0 no longer blurs three different meanings into one value |
| Topology change | topologyFingerprint() | long | read-only | Topology fingerprint (slave count + a stable hash of each slave's VendorId/ProductId/RevId); topologyFingerprintKnown() reports whether sampling succeeded |
| topologyChangeCount() | long | read-only | Number of observed topology changes (the first sample is not counted; observed at read time, multiple changes between two reads are merged into one) | |
| lastTopologyChangeUtc() | java.time.Instant | read-only | Time of the most recent observed topology change (UTC); null = no change observed yet | |
| Port status | isPrimaryPortOk() | boolean | read-only | Whether the primary port is healthy |
| Port status | isSecondaryPortOk() | boolean | read-only | Whether the secondary port is healthy |
| Port status | getPrimaryPortErrors() | long | read-only | Primary-port errors in the last 5 seconds |
| Port status | getSecondaryPortErrors() | long | read-only | Secondary-port errors in the last 5 seconds |
| Redundancy status | isRedundancyActive() | boolean | read-only | Redundancy protection is running = redundancyRingMode() >= 1 and both ports carry frame traffic within this window; always false for line / end-foldback topologies |
| redundancyRingModeEnum() | RingMode | read-only | Redundancy ring operating mode enum: UNKNOWN(-1) / INACTIVE(0) / DUAL(1) / DEGRADED(2); unreadable / out-of-range value → UNKNOWN, never folded into INACTIVE | |
| Topology | getTopologyDescription() | String | read-only | Topology mode description (line / ring / ring + branch) |
| Topology | getTimingMode() | String | read-only | Timing 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()}
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 < ExpectedWKCis 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:
| Category | Member | Type | R/W | Description |
|---|---|---|---|---|
| WKC mirror | getWkcActualMirror() | int | read-only | WKC measured in this cycle; 0 = unknown (not ready yet) |
| WKC mirror | getWkcExpectedMirror() | int | read-only | Expected WKC fixed at configuration time; 0 = unknown; never lowered to accommodate a degraded bus |
| WKC mirror | getWcDeficit() | int | read-only | Deficit = 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 mirror | getMappedSlaveCount() | int | read-only | Number 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
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.
| Category | Member | Type | R/W | Description |
|---|---|---|---|---|
| Redundancy WKC | diagnostics().secondaryWkc() | int | read-only | Secondary-port WKC measured in this cycle (0..65535). Returns WKC_UNKNOWN when this cycle has no fresh measurement |
| Redundancy WKC | MasterDiagnosticsInfo.WKC_UNKNOWN | static final int | read-only | "no measurement" sentinel, value 0xFFFF |
| Redundancy WKC | diagnostics().secondaryWkcKnown() | boolean | read-only | Whether this cycle has a measurement. false only means secondaryWkc() is WKC_UNKNOWN |
| Redundancy WKC | master.secondaryWkcRt() | short | read-only | Real-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.
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.
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
| Category | Member | Returns | R/W | Description |
|---|---|---|---|---|
| Diagnostics | diagnostics().captureRealOpTruth() | MasterRealOpTruth | read-only | Capture one cycle of real-OP truth (master-level + per-slave) |
| Diagnostics | diagnostics().evaluateSlaveRealOp(int) | SlaveRealOpState | read-only | Single-slave verdict; null = cannot be evaluated, shown honestly as unknown |
| Diagnostics | diagnostics().evaluateRealOp(evidence, wkcActual, wkcExpected) | MasterRealOpTruth | read-only | Evaluate 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)
| Value | Name | Meaning |
|---|---|---|
| 0 | OK | Real OP: the per-slave verdicts hold |
| 1 | AL_NOT_CLEAN | The per-slave verdict does not hold (not in OP / Error bit set / slave dropped out) |
| 2 | NO_CONTRIBUTION | Historical / compatibility value: no longer produced by the per-slave verdict (the code is kept so logs line up across languages) |
| 3 | UNSTABLE | Historical / compatibility value: no longer produced by the per-slave verdict (the code is kept so logs line up across languages) |
| 4 | WKC_DEFICIT | Master-level: every required slave holds its verdict, but the merged measured WKC is below the fixed expectation |
| 5 | UNKNOWN | Insufficient evidence (the data the verdict needs cannot be read / no required slaves) |
Result structure
MasterRealOpTruth (category: diagnostics; read-write: read-only)
| Field | Type | Description |
|---|---|---|
| sequence | long | Evaluation sequence number, monotonically increasing per master |
| realOp | boolean | Master-level real OP |
| reason | RealOpReason | Main reason the master-level verdict does not hold |
| requiredCount | int | Number of required slaves |
| realOpCount | int | Number of required slaves whose per-slave verdict is real OP |
| failedCount | int | Number of required slaves that did not reach real OP |
| wkcActual | int | Merged measured WKC (as measured) |
| wkcExpected | int | Expected WKC fixed at configuration time (never lowered) |
| wkcDeficit | int | Deficit = expected − actual (≤0 means no deficit) |
| slaves | List<SlaveRealOpState> | Per-slave results |
| detailText | String | Readable detail (master conclusion + list of slaves that did not reach real OP + WKC comparison) |
SlaveRealOpState (category: diagnostics; read-write: read-only)
| Field | Type | Description |
|---|---|---|
| slaveIndex | int | Slave index (1-based) |
| required | boolean | Whether it takes part in the master-level verdict (not optional and has PDO) |
| alCleanOp | boolean | Per-slave verdict (AL is OP ∧ Error bit = 0 ∧ not dropped out) |
| contributed | boolean | Has a WKC contribution this cycle — display evidence only, not part of the verdict |
| stableStreak | int | Display-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 |
| realOp | boolean | Real OP for this slave |
| reason | RealOpReason | Reason it does not hold (OK when it is real OP) |
| detail | String | Readable 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)
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
Link observation
| Method | Returns | Description |
|---|---|---|
diag.getPrimaryPhyLinkState() / getSecondaryPhyLinkState() | EtherCATTypes.PhyLinkState | Physical link of the primary / secondary port: UP=1, DOWN=0, UNKNOWN=-1; a failed read also gives UNKNOWN |
master.secondaryFrameLinkState() | EtherCATTypes.PhyLinkState | Three-state frame-level link of the secondary port; use it separately from the NIC's physical reading |
diag.getPhyLinkBitMask() | int | Two-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.
| Method | Returns | Description |
|---|---|---|
| master.computeRingBranch(slaves) | DarraCore.TopoRingBranchOut | v1 entry point; the signature and semantics are unchanged and it remains usable. Read-only, changes no state |
| master.computeRingBranchEx(slaves) | DarraCore.TopoRingBranchOut2 | v2 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):
| Field | Type | Description |
|---|---|---|
| slave_num | short | Slave index |
| phys_ap | byte | Physical port mask (bit0..3 = P0..P3) |
| entry_port | byte | Entry port 0..3; 0xFF = unknown / not filled in |
| parent | short | Parent slave index; 0 = root |
| parent_port | byte | Port 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):
| Field | Type | Description |
|---|---|---|
| total_count | int | Total slave count |
| ring_count | int | Number of ring members (truncated to the capacity the caller supplied when it is too small) |
| branch_count | int | Branch count = total_count − ring_count |
| closure_slave_num | int | Closing-point slave index; -1 = none (line / chain (foldback at end)) |
| mode | int | Static port model: 0 = line / 1 = ring / 2 = ring + branch |
| chain_form | int | Sub-form for the no-ring case, meaningful only when mode == 0 |
chain_form values:
| Value | Constant | Meaning |
|---|---|---|
| 0 | CHAIN_FORM_LINEAR | Line (Linear) |
| 1 | CHAIN_FORM_FOLDBACK | Chain (foldback at end) |
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
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.
| Category | Member | Type | R/W | Description |
|---|---|---|---|---|
| DC diagnostics | dcDiagnostics() | DcDiagnosticsSnapshot | read-only | Snapshot entry (never null; throws IllegalStateException when the master has been released) |
| DC diagnostics | capturedAtUtc | Instant | read-only | Time this cycle's snapshot was assembled (UTC) |
| DC diagnostics | hasDc | boolean | read-only | Whether DC slaves exist on the network |
| DC diagnostics | allInSync | Boolean | read-only | Whether 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 diagnostics | maxDriftNs | Integer | read-only | Largest absolute synchronization difference among usable windows. null = no measured window at all (not 0) |
| DC diagnostics | syncWindowThresholdNs | Integer | read-only | Sync window threshold (nanoseconds). null = cannot be read |
| DC diagnostics | referenceClock | DcReferenceClockInfo | read-only | Reference-clock slave index + tier + reason (never null) |
| DC diagnostics | armedSlaveCount | int | read-only | Number of slaves with SYNC0 armed (sync0Armed == true); 0 is a valid count |
| DC diagnostics | activeSlaveCount | int | read-only | Number of DC-active slaves (the value landed in 0x0980 is anything other than 0); not the same conclusion as "armed" |
| DC diagnostics | armedUnknownCount | int | read-only | Number of slaves whose armed state is unknown (the conclusion cannot be read); 0 is a valid count |
| DC diagnostics | armedSyncParticipantCount | int | read-only | Number of sync participants (armed + not the reference clock); 0 = no slave on this network can carry a synchronization conclusion |
| DC diagnostics | applicableWindowCount | int | read-only | Number of slaves with a measured window; when it is 0, maxDriftNs is necessarily null |
| DC diagnostics | activeWithoutProcessDataCount | int | read-only | Number of slaves that are DC-active but have no process data (such slaves are judged a hard DC failure) |
| DC diagnostics | expectedWkc | int | read-only | Master expected WKC (the fixed value from configuration time); compare it with the armed slave count to see WKC coverage |
| DC diagnostics | propagationDelayResolvedAtUtc / propagationDelayResolveCount | Instant / int | read-only | Time and count of the most recent successful propagation-delay resolution triggered by the SDK; null / 0 = not observed in this process |
| DC diagnostics | slaves / find(index) | List<DcSlaveSnapshot> / DcSlaveSnapshot | read-only | Per-slave snapshots (ascending slave index); find returns null when out of range or not sampled |
| DC diagnostics | anyReadFailure | boolean | read-only | At 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/maxDriftNsinside the snapshot are three-state. The boolean /-1convention of older summary surfaces such asisAllSlavesInSync(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:
| Type | faultType | Detection | Typical scenario |
|---|---|---|---|
| Link break | 0 | Physical link loss reported on the DL Status port | Cable unplugged, cable break |
| CRC fault | 1 | Port-level RxError + InvalidFrame keep increasing | Poor contact, ageing cable, oxidized connector |
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) —trueturns on the optional diagnostics statistics and starts sliding-window sampling (off by default);falsestops 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 fromslave.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/0x001Einvalid output / input configuration (CONFIGURATION) — check the PDO mapping and SM configuration;0x0024/0x0025are the ones for invalid input / output mapping0x0015/0x0016invalid mailbox configuration (BOOT / PreOp state respectively,CONFIGURATION) — check the mailbox SM and startup parameters in that state; note that0x0011is an invalid state transition (TRANSIENT), not a mailbox configuration error0x001Asynchronization error (CONFIGURATION) /0x0034DC synchronization timeout (TRANSIENT) (also0x002Cfatal synchronization error and0x0032PLL error, bothTRANSIENT) — check the DC configuration and reference clock, then retry the state transition0x0050no EEPROM access permission /0x0051EEPROM 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);
}
}
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:
| Symptom | Field (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-0x030Binvalid frames, summed over the four ports) - lostFrames: lost-frame count (ESC
0x0310-0x0313link 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).
| Category | Method | Type | R/W | Description |
|---|---|---|---|---|
| NIC self-check | diagnoseNicHealth() | int | call | Two-port health classification |
| NIC probe | verifyNicHealth(int, int) | int | call | Actively sends probe frames and gives a confirmed conclusion by comparing the transmit / receive counter growth before and after |
| NIC recovery | autoRecoverNic() | int | call | Soft-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:
| Category | Attribute | Type | R/W | Description |
|---|---|---|---|---|
| Self-check result | 0 | int | read-only | Both ports healthy — the problem is on the slave or cabling side |
| Self-check result | 1 | int | read-only | Primary port abnormal |
| Self-check result | 2 | int | read-only | Secondary port abnormal |
| Self-check result | 3 | int | read-only | Both ports abnormal |
| Self-check result | -1 | int | read-only | The 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, recommended5, valid range 1–50timeoutMs(int) — how long to wait for a reply (ms), recommended200, valid range 50–5000
Returns:
| Category | Attribute | Type | R/W | Description |
|---|---|---|---|---|
| Probe result | 0 | int | read-only | NIC healthy — the problem is on the slave side, so automatic recovery would not help |
| Probe result | 1 | int | read-only | Primary-port transmit confirmed abnormal |
| Probe result | 2 | int | read-only | Primary-port receive confirmed abnormal |
| Probe result | 3 | int | read-only | The path from the application side to the NIC is not working (set the network again and scan again) |
| Probe result | 4 | int | read-only | Secondary port abnormal |
| Probe result | -1 | int | read-only | Invalid 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
}
}
Port link and port topology measurements
getPhyLinkState() is on master.diagnostics(); topoP1FullWkc() is on master.
| Category | Method | Type | R/W | Description |
|---|---|---|---|---|
| Port link | getPhyLinkState() | int | call | Physical link bitmap of the two ports |
| Port topology | topoP1FullWkc() | int | call | Measured 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().
| Category | Method | Type | R/W | Description |
|---|---|---|---|---|
| DC presence | getDcHasDc() | boolean | call | Whether a DC slave exists on the network |
| DC drift | getDcMaxDriftNs() | int | call | Maximum absolute synchronization difference (ns) |
| DC reference clock | getDcReferenceClockSlave() | int | call | Reference-clock slave index (1-based) |
| DC sync conclusion | getDcAllInSync() | Boolean | call | Tri-state synchronization conclusion |
| DC reference clock | dcReferenceClock() | DcReferenceClockInfo | call | Reference-clock slave index + tier + reason |
| DC counts | dcArmedSlaveCount() | int | call | Number of slaves with SYNC0 armed |
| DC counts | dcActiveSlaveCount() | int | call | Number 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 offtrue/falsein 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」.
| Category | Attribute | Type | R/W | Description |
|---|---|---|---|---|
| Reference clock | slaveIndex | int | read-only | Reference-clock slave index (1-based); 0 = none |
| Reference clock | tier | DcReferenceClockTier | read-only | Tier, used for display only and not part of clock selection |
| Reference clock | tierText | String | read-only | Tier reason text, suitable for showing to on-site staff as it is |
| Reference clock | isChainHeadFallback | boolean | read-only | true = no armed slave was found, so it fell back to the chain-head DC slave (that slave is not the real reference clock) |
| Reference clock | isKnown() | boolean | read-only | true = a reference-clock slave index exists (it does not mean the tier has been decided) |
DcReferenceClockTier values:
| Category | Attribute | Type | R/W | Description |
|---|---|---|---|---|
| Tier | UNKNOWN | int = 0 | read-only | Cannot be decided (slave snapshot unreadable / reference-clock object unavailable) |
| Tier | NONE | int = 1 | read-only | No armed DC slave; fell back to the chain-head DC slave |
| Tier | USER | int = 2 | read-only | Explicitly set by the user (the current SDK has no configuration entry point for it, so this face never produces it) |
| Tier | PDO_PROVEN | int = 3 | read-only | Has PDO + SYNC0 armed + valid cycle0 (the best tier) |
| Tier | PDO_ARMED | int = 4 | read-only | Armed slave with PDO |
| Tier | NO_PDO | int = 5 | read-only | Armed 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().
| Category | Method | Type | R/W | Description |
|---|---|---|---|---|
| Sync window | dcSyncWindowThresholdNs() | Integer | call | Sync window threshold (ns) |
| DC sampling | tryGetDcSample(int) | DcSlaveSnapshot | call | Returns the conclusion for one slave from the most recent completed sampling without triggering a new one |
| DC sampling | invalidateDcSnapshot() | void | call | Invalidates 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).
| Category | Method | Type | R/W | Description |
|---|---|---|---|---|
| Propagation delay | dcPropagationDelayResolvedAtUtc() | Instant | call | Time of the most recent successful resolution (UTC) |
| Propagation delay | dcPropagationDelayResolveCount() | int | call | Number 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().
| Category | Method | Type | R/W | Description |
|---|---|---|---|---|
| Recovery observation | slaveRecovery(int) | SlaveRecoveryStatus | call | Per-slave recovery status |
| Recovery observation | masterRecoveryLadder() | read-only observation object | call | Master-level recovery observation |
| Recovery observation | recoveryLadderSeq() | long | call | Master-level observation freshness token |
| Recovery event | recoveryEvents(int, int) | List<RecoveryEvent> | call | Incremental 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.
| Category | Attribute | Type | R/W | Description |
|---|---|---|---|---|
| Recovery state | available | boolean | read-only | false = observation unavailable (not "no recovery") |
| Recovery state | level | SlaveRecoveryLevel | read-only | Current level |
| Recovery state | step | SlaveRecoveryStep | read-only | Current step; null = a step outside the domain (unknown, never fabricated) |
| Recovery state | lastStep | SlaveRecoveryStep | read-only | Previous step (transitions stay traceable) |
| Recovery state | failReason | SlaveRecoveryReason | read-only | Reason the previous step failed (None = none) |
| Recovery state | failAlsc | int | read-only | AL status code measured at the failure; 0 = none / not read |
| Recovery state | retryCount | int | read-only | Attempts in this round |
| Recovery state | backoffRemainMs | long | read-only | Backoff remaining (ms); 0 = free to act at any time |
| Recovery state | stepElapsedMs | long | read-only | Time already spent in the current step (ms); use it to tell where it is stuck |
| Recovery state | skipFrames | long | read-only | Cumulative skipped recovery frames |
| Recovery state | seq | long | read-only | State-transition counter (judge observation freshness with it) |
| Recovery state | flags | int | read-only | Raw state-bit byte |
| Recovery state | lastResultOk | SlaveRecoveryResult | read-only | Previous step result (Ok / Failed / Suppressed / Unknown) |
| Recovery state | classify | SlaveRecoveryClass | read-only | Recovery classification (None / A / B1 / B2 / B3 / Unknown) |
| Recovery state | pausedA / needsReconfig / ladderExhausted / epilogue | boolean | read-only | Four state bits: paused / configuration not replayed / suspended after repeated failures / finishing up |
| Recovery state | isActive() | boolean | read-only | The 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).
| Category | Attribute | Type | R/W | Description |
|---|---|---|---|---|
| Master recovery | available | boolean | read-only | false = observation unavailable |
| Master recovery | triggerBlockedTotal | Long | read-only | Cumulative "trigger hit but not executed in this round"; null = observation unavailable (not 0 times) |
| Master recovery | rebuildReqPending | Boolean | read-only | A full-network rebuild request is pending and unconsumed; null = not collected |
| Master recovery | rebuildActive | Boolean | read-only | A full-network rebuild is running; null = not collected |
| Master recovery | rebuildFail | Integer | read-only | Consecutive full-network rebuild failures; null = not collected |
| Master recovery | alarmOnly | Boolean | read-only | Alarm-only tier; null = not collected |
| Master recovery | handoffBusy | Boolean | read-only | Orchestration is busy; null = not collected |
| Master recovery | aSuppressed | Boolean | read-only | Suppression is in effect; null = not collected |
| Master recovery | badPersistent | Boolean | read-only | The criterion stays abnormal; null = not collected |
| Master recovery | ladderExhausted | Boolean | read-only | Some slave is suspended after repeated failures; null = not collected |
| Master recovery | backoffRemainMs | Long | read-only | Backoff remaining (ms); null = not collected |
| Master recovery | badSinceMs | Long | read-only | Start of the sustained abnormality (ms); null = not collected |
| Master recovery | rebuildTotal | Long | read-only | Full-network rebuilds in this session; null = not collected |
| Master recovery | seq | Long | read-only | Token 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 ringmax(int) — how many to return at most;<= 0is treated as256; the upper bound isMasterDiagnosticsInfo.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:
| Category | Attribute | Type | R/W | Description |
|---|---|---|---|---|
| Recovery event | seq | long | read-only | Event sequence number (monotonic; use it as the next cursor) |
| Recovery event | slave | int | read-only | Slave index; 0 = a master-level event |
| Recovery event | kind | SlaveRecoveryEventKind | read-only | Event kind |
| Recovery event | fromLevel / toLevel | SlaveRecoveryLevel | read-only | Level before / after the transition |
| Recovery event | fromStep / toStep | SlaveRecoveryStep | read-only | Step before / after the transition; null = a step outside the domain |
| Recovery event | reason | SlaveRecoveryReason | read-only | Reason (None = none) |
| Recovery event | ok | SlaveRecoveryResult | read-only | Execution result |
| Recovery event | alsc | int | read-only | Measured AL status code; 0 = none |
| Recovery event | tickMs | long | read-only | Event 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().
| Category | Method | Type | R/W | Description |
|---|---|---|---|---|
| Lost slaves | lostSlaveCensus() | LostSlaveCensus | call | Lost-slave count and the index of the first lost slave (the single definition) |
| Probe truth | probeTruth() | ProbeTruth | call | Summary 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).
| Category | Attribute | Type | R/W | Description |
|---|---|---|---|---|
| Lost slaves | count | int | read-only | Lost-slave count; 0 = no lost slave or probing not observable (the two are not distinguished) |
| Lost slaves | firstSlaveIndex | int | read-only | Index 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).
| Category | Attribute | Type | R/W | Description |
|---|---|---|---|---|
| Probe truth | available | boolean | read-only | false = probing not observable (do not read the 0 at that moment as "everything is offline") |
| Probe truth | aliveCount | int | read-only | Number of slaves that really replied in this round |
| Probe truth | wkcBoundSlaves | int | read-only | Number of slaves that replied and contribute WKC |
| Probe truth | unknownCount | int | read-only | Number 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().
| Category | Method | Type | R/W | Description |
|---|---|---|---|---|
| Cycle sliding window | diagCsWindowStats() | CsWindowStats | call | Returns the 5-second sliding-window statistics (cycle frequency / error rate / average jitter) |
| Cycle sliding window | diagCsWindowSample(long, long) | void | call | Feeds one sample into the sliding window (for external feeding or replay) |
| Cycle sliding window | diagCsWindowReset() | void | call | Empties 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.
| Category | Attribute | Type | R/W | Description |
|---|---|---|---|---|
| Window statistics | available | boolean | read-only | false = the window is unavailable (illegal master number / not ready yet); the numeric fields are meaningless then |
| Window statistics | errorPerSec | double | read-only | Errors per second (Σerr×1000/Σms inside the window; a window shorter than 1 ms records 0) |
| Window statistics | cycleHz | double | read-only | Cycle frequency (Hz, same formula as above) |
| Window statistics | avgJitterUs | double | read-only | Average jitter (µs); records 0 when the sample count is 0 |
| Window statistics | filled | int | read-only | Number 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 astimestampFreq)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(...).
| Category | Method | Type | R/W | Description |
|---|---|---|---|---|
| Diagnostics control | setDiagnosticsEnabled(boolean) | void | call | Toggles the runtime-side diagnostics collection switch |
| Diagnostics control | diagnosticsEnabled() | boolean | call | Current switch state |
| Diagnostics control | resetDiagnostics() | void | call | Resets master-level diagnostic counters |
| Snapshot refresh | updateDiagnosticsSnapshot() | void | call | Samples the diagnostics snapshot once again |
| Snapshot refresh | updateDiagnosticsWithESCErrors() | void | call | Folds in the ESC error counters before settling diagnostics |
| Snapshot refresh | recordWKC(short) | void | call | Records one measured WKC into the statistics window |
| Detail entry point | detailedDiagnostics() | Pointer | call | Pointer to the detailed diagnostics data structure (read-only view) |
| Master diagnostics object | getMasterDiagData() | DarraCore.MasterDiagData | call | Reads 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) —trueturns on the runtime-side optional statistics;falseturns 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).
| Category | Attribute | Type | R/W | Description |
|---|---|---|---|---|
| Master diagnostics | CyclicLostFrames | int | read-only | Lost cyclic frames |
| Master diagnostics | AcyclicLostFrames | int | read-only | Lost acyclic frames |
| Master diagnostics | CyclicFramesPerSec | int | read-only | Cyclic frames per second |
| Master diagnostics | AcyclicFramesPerSec | int | read-only | Acyclic frames per second |
| Master diagnostics | MasterState | short | read-only | Current 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.
| Category | Method | Type | R/W | Description |
|---|---|---|---|---|
| Event callback | registerRedundancyModeChangedCallback(DarraCore.RedundancyModeChangedCallback) | void | call | Registers a redundancy-mode change callback |
| Event callback | setDCSyncLostCallback(DarraCore.DCSyncLostCallback) | void | call | Registers 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 passingnullmeans 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 passingnullmeans 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());