Skip to main content

Master diagnostics

Use with events

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

Feature overview​

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

Communication and performance statistics​

CategoryFunctionTypeRead/writeDescription
Frame countsGetPacketLossRate(mi)floatRead-onlyPacket loss rate (0.0~1.0), TX vs RX over a 5-second sliding window
Frame countsGetLateFrameRate(mi)floatRead-onlyLate frame rate (0.0~1.0); an index that leaves the 8-frame window is stale
Cycle and jitterGetDiagnosticsSnapshot(mi, &snapshot)BOOLRead-onlyCycle, lost frames, latency and more in one read
Cycle and jitterGetDiagnosticsSnapshot → cycle_time_usintRead-onlyActual cycle time (microseconds), corresponding to CycleTimeSpan in the diagnostics struct. When the field is 0, fall back to 1e6/Hz (1000000/frequency); do not hard-code 1 ms.
Cycle and jitterGetDiagnosticsSnapshot → bus_avg_jitter_us / bus_max_jitter_usdoubleRead-onlyAverage jitter / maximum jitter over the last 5 seconds (microseconds). Jitter grows when real-time isolation is not in effect; the cycle should still hold at the configured value. Minimum cycle time 31 µs (= 31,000 ns, integer microseconds, specification lower bound; on Windows, 125 µs or more is recommended).
Cycle and jitterGetDiagnosticsSnapshot → frequencyintRead-onlyFrames per second (Hz) = 1e9/LoopCycleNs. A sustained deviation of ±20% from the configured value, or max jitter above 25% of the cycle time, must be logged and alarmed. Use it together with PDOFrameLoss / DCSyncLost. Do not hard-code 1000 Hz.
WKCGetExpectedWKC(mi) / SetExpectedWKC(mi, wkc)uint16_tRead/writeExpected working counter
WKCGetPrimaryWKC()uint16_tRead-onlyPrimary-port WKC (tracked independently in redundancy mode)
WKCGetSecondaryWKC()uint16_tRead-onlySecondary-port WKC: on the real-time backend this is the measurement of the current cycle; without a fresh measurement it returns 0xFFFF (EC_WKC_UNKNOWN). Use Diagnostics_SecondaryWkcKnown to test for unknown; 0 on a single-port setup is a valid reading. Backends that cannot decide fall back to the hold-window latch
WKCDiagnostics_SecondaryWkcKnown(mi)BOOLRead-onlyWhether the secondary-port WKC has a measurement in this cycle. FALSE only means the reading is 0xFFFF; 0 on a single-port setup still counts as known
WKCGetPrimaryWkcRt(mi)uint16_tRead-onlyPer-cycle real-time primary-port WKC (drops in the same cycle when a slave is unplugged or the primary port breaks). 0 is a valid reading; this entry point has no not-ready sentinel, so check SDK readiness with DarraEcat_ShellReady()
WKCGetSecondaryWkcRt(mi)uint16_tRead-onlyReal-time filtered secondary-port WKC (drops in the same cycle when a slave is unplugged or the link breaks)
WKC mirrorGetWkcActualMirror(mi)uint16_tRead-onlyMeasured working counter mirror (actual WKC) — reflects which slaves are really responding right now. The measured value is never altered. Read in real time
WKC mirrorGetWkcExpectedMirror(mi)uint16_tRead-onlyExpected working counter mirror (expected WKC) — a fixed value determined at configuration time / when entering OP. Never lowered dynamically to accommodate a degraded bus. Read in real time
WKC mirrorGetWcDeficit(mi)uint16_tRead-onlyWKC deficit = expected − actual (>0 means a mapped slave is not contributing WKC right now, suspected lost slave / Hot-plug). Returns to 0 automatically once the slave recovers. Read in real time
WKC mirrorGetMappedSlaveCount(mi)uint16_tRead-onlyNumber of mapped slaves (participating in the WKC calculation). Read in real time
WKC mirrorMirror-ready predicate GetMappedSlaveCount(mi)uint16_tRead-onlyPublic predicate for whether the per-slave WKC mirror is ready: GetMappedSlaveCount(mi) > 0 = ready; = 0 = the contract is not ready and per-slave getters (GetSlaveWcState etc.) return an unknown value. The property reads in real time (what you read is the bus state at that moment); no refresh sequence is needed
Master truthGetLostSlaveCount(mi, &first)intRead-onlyLost-slave census count (the single authority for the bus-level lost-slave count); >0 = a slave is lost; first = index of the first lost slave (1-based, 0 = none); 0 = no lost slave or the probing mechanism is not observable
GetNoProcessData(mi)intRead-onlyMaster-level "no process data / false OP" truth value: a value other than 0 = the cycle is running but the process data is dead; returns 1 (fail-safe) when the master is unavailable
GetNoProcessDataKnown(mi)intRead-onlyWhether GetNoProcessData() has a measured sample; 0 = unavailable and the return value carries no meaning
GetProbeTruth(mi, &alive, &wkcBound, &unknown)intRead-onlyProbe truth summary; returns 1 = a true-value sample exists, 0 = the probing mechanism is not observable (the out parameters are invalid)
GetStaleInputCount(mi)int32_tRead-onlyNumber of slaves whose input data is confirmed STALE (per slave GetSlaveInputValidity()==EC_PDO_INPUT_STALE); UNKNOWN / DEGRADED are not counted; -1 = a slave read failed / is unavailable
Cycle runGetCycleRunState(mi)ec_cycle_run_state_tRead-onlyMaster cycle tri-state: EC_CYCLE_NOT_STARTED / EC_CYCLE_STARTED_NO_ADVANCE / EC_CYCLE_ADVANCING; 0 no longer blurs three different meanings into one value
Topology changeGetTopologyFingerprint(mi, &out)intRead-onlyTopology fingerprint (slave count + a stable hash of each slave's VendorId/ProductId/RevId); 1 = valid / 0 = not sampled or invalid parameter
GetTopologyChangeCount(mi, &count, &last_ms)intRead-onlyNumber of observed topology changes + Unix milliseconds of the most recent change; 1 = valid / 0 = not sampled or invalid parameter. Observed at read time; multiple changes between two reads are merged into one
Slave anomaliesGetSlaveLinkQuality(mi, si)int16_tRead-onlySlave link quality 0-100%, -1 = unknown
Detailed diagnosticsGetDetailedDiagnostics(mi)void*Read-onlyDetailed diagnostics data pointer (no need to free)
Communication statisticsGetCommunicationStats(mi) / ResetCommunicationStats(mi)void*Read/writeCommunication statistics pointer + reset

Detailed diagnostics data structure:

typedef struct {
uint32_t FrameErrors;
uint32_t LostFrames;
uint32_t ChecksumErrors;
uint32_t TimeoutFrames;
uint32_t RxErrorCount[EC_MAXSLAVE];
uint32_t TxErrorCount[EC_MAXSLAVE];
uint16_t LostLinkCount[EC_MAXSLAVE];
uint16_t InvalidFrameCount[EC_MAXSLAVE];
uint16_t WorkingCounterErrors;
uint16_t ConsecutiveWkcErrors;
uint32_t TotalWkcMismatches;
uint32_t PdoLostFrames[EC_MAXGROUP];
uint32_t PdoConsecutiveLost[EC_MAXGROUP];
uint32_t PdoMaxConsecutiveLost[EC_MAXGROUP];
int16_t LinkQualityPercent[EC_MAXSLAVE];
uint32_t PrimaryPortTxCount;
uint32_t PrimaryPortRxCount;
uint32_t SecondaryPortTxCount;
uint32_t SecondaryPortRxCount;
uint32_t PrimaryPortErrors;
uint32_t SecondaryPortErrors;

/* [v2.2.0] Per-slave offline statistics (diagnose slave connection flapping). Index 1 and up are valid; [0] is the master slot. */
uint32_t SlaveOfflineCount[EC_MAXSLAVE]; /* cumulative offline count per slave */
uint64_t SlaveOfflineTotalMs[EC_MAXSLAVE]; /* cumulative offline time per slave (ms) */
} ec_diagnostics_data_t;

For the actual cycle time (microseconds), read CycleTimeSpan in the diagnostics struct or cycle_time_us in the snapshot. When the field is 0, fall back to 1e6 / Hz (1000000 / frequency); do not hard-code 1000 µs.

Example:

ec_diagnostics_snapshot_t snap;
if (GetDiagnosticsSnapshot(master, &snap)) {
int cycle_us = snap.cycle_time_us;
if (cycle_us <= 0 && snap.frequency > 0)
cycle_us = (int)(1000000 / snap.frequency);
printf("周期=%d us, 频率=%d Hz\n", cycle_us, snap.frequency); /* Cycle=%d us, frequency=%d Hz */
}

PDO frame loss statistics​

void GetPDOFrameLossStats(uint16_t master_index, uint8_t group,
uint32_t* total_lost, uint32_t* consecutive_lost,
uint32_t* max_consecutive_lost);
void ResetPDOFrameLossStats(uint16_t master_index, uint8_t group);

Query PDO frame loss statistics per group (0-7): total lost frames, current consecutive lost frames, and the historical maximum consecutive lost frames.

WKC mirror (lost slaves observable)​

uint16_t GetWkcActualMirror(uint16_t master_index);   /* measured WKC mirror */
uint16_t GetWkcExpectedMirror(uint16_t master_index); /* expected WKC mirror (fixed value) */
uint16_t GetWcDeficit(uint16_t master_index); /* deficit = expected - actual */
uint16_t GetMappedSlaveCount(uint16_t master_index); /* number of mapped slaves */
/* Per-slave mirror readiness predicate (public surface): GetMappedSlaveCount(mi) > 0 = contract published, per-slave getters usable;
* = 0 = not ready (per-slave getters return an unknown value). Mirror properties read in real time; no refresh sequence needed */

The WKC mirror is the master-level aggregate mirror of the per-slave WcState diagnostic cache; all values are read directly in real time (no refresh needed — the runtime maintains them every cycle and immediately on a WKC anomaly, so what you read is the real bus state at that moment). Combined with each slave's GetSlaveWcState(mi, si), you can locate exactly which slave dropped.

Observability rules (not negotiable):

  • GetWkcExpectedMirror(mi) = the fixed true value determined at configuration time / when entering OP. It is fixed as long as the topology is fixed, conceptually immutable, and never lowered dynamically to accommodate a degraded bus.
  • GetWkcActualMirror(mi) = the measured bus value, which faithfully reflects which slaves are really responding right now and is never altered.
  • GetWcDeficit(mi) = expected − actual. > 0 is not a master fault: a mapped slave is not contributing WKC right now (suspected lost slave / Hot-plug recovery). It returns to 0 automatically once the slave recovers, with no reset call.

Example:

uint16_t act = GetWkcActualMirror(master);
uint16_t exp = GetWkcExpectedMirror(master);
printf("WKC: %u / %u (映射从站 %u 个)\n", act, exp, GetMappedSlaveCount(master)); /* WKC: %u / %u (%u mapped slaves) */

uint16_t deficit = GetWcDeficit(master);
if (deficit > 0) {
printf("WKC 缺额 %u — 有从站没在响应, 逐个从站定位:\n", deficit); /* WKC deficit %u — some slaves are not responding, locating them one by one: */
for (int si = 1; si <= GetMappedSlaveCount(master); si++) { /* mapped slaves covered by the mirror */
if (GetSlaveWcState(master, si) == 0) /* 0 = no contribution */
printf(" 从站 %d 未贡献 WKC\n", si); /* Slave %d contributes no WKC */
}
}

if (GetMappedSlaveCount(master) > 0) /* > 0 = per-slave mirror ready; = 0 = contract not ready (per-slave getters return an unknown value) */
printf("逐站 WKC 镜像就绪, 映射从站 %u 个\n", GetMappedSlaveCount(master)); /* Per-slave WKC mirror ready, %u mapped slaves */

Mirror refresh sequence (direct entry points)​

Two more read-only sequence entry points tell you whether the mirror was refreshed in this cycle. They are provided only under long DarraEcat_ names, with no short-name counterparts, and belong to the direct diagnostics surface:

  • DarraEcat_GetWcStateSeq(master) — refresh sequence of the per-slave WcState diagnostic cache. It increases monotonically while running; when it stops growing, the cache has not been refreshed for that period.
  • DarraEcat_GetRedundancyEngineSeq(master) — update sequence of redundancy verdicts. Monotonic increase means the redundancy analysis really ran in this cycle. Its source differs from the WcState sequence above; neither can replace the other.

Neither sequence promises a specific refresh timing; they only answer "is it advancing". Do not assume their increments follow a fixed cycle. How to read the return values:

  • A sequence that is increasing — the corresponding mirror / verdict is being refreshed;
  • Unchanged for a long time — the corresponding cache is no longer advancing (this is not "the data is invalid", and it is not a lost slave);
  • 0 — unknown: no usable data source, or the corresponding counter has not started advancing;
  • All 1s (0xFFFFFFFFFFFFFFFF for DarraEcat_GetWcStateSeq, 0xFFFFFFFFFFFFFFFF for DarraEcat_GetRedundancyEngineSeq) — the SDK is not ready; treat it as a failure and get the reason from DarraEcat_ShellStatus().
The sequence only tells you "refreshed", not "valid"

A changed sequence only means the cache was written; it does not mean the WKC of this cycle can be used for control. To decide whether the WKC mirror is usable and how to use it, follow the public rules in the previous section:

  • Whether the per-slave mirror is ready: GetMappedSlaveCount(mi) > 0;
  • Deficit and per-slave location: GetWcDeficit(mi) / GetSlaveWcState(mi, si);
  • Expected and measured values: GetWkcExpectedMirror(mi) / GetWkcActualMirror(mi).

Do not declare a lost slave just because the sequence did not change, and do not use the sequence in place of any of the WKC criteria above.

When to call: read it only on diagnostic / display paths that need to know whether the mirror was refreshed; do not put it into real-time control criteria of the PDO cycle.

Example:

uint64_t wc_seq = DarraEcat_GetWcStateSeq(master);
uint32_t rd_seq = DarraEcat_GetRedundancyEngineSeq(master);

if (wc_seq == (uint64_t)-1 || rd_seq == (uint32_t)-1) {
printf("SDK 未就绪,序号不可用\n"); /* all 1s = not ready */
} else if (wc_seq == 0) {
printf("WcState 镜像序号未知\n"); /* 0 = unknown, not a real sequence */
} else {
/* compare with the last recorded value: changed = the mirror was refreshed; unchanged for a long time = the cache is no longer advancing */
printf("WcState 序号 %llu, 冗余引擎序号 %u\n", /* WcState sequence %llu, redundancy engine sequence %u */
(unsigned long long)wc_seq, rd_seq);
}

Secondary-port WKC "unknown" state​

When there is no fresh measurement, the secondary-port WKC returns EC_WKC_UNKNOWN (0xFFFF); it never returns a stale full count and never returns a peak value carried across cycles.

CategoryNameTypeRead/writeDescription
WKCGetSecondaryWKC()uint16_tRead-onlySecondary-port WKC (process-wide scale, no master_index parameter); EC_WKC_UNKNOWN when there is no fresh measurement
WKCEC_WKC_UNKNOWNMacro (0xFFFF)Read-only"No measurement" sentinel
WKCDiagnostics_SecondaryWkcKnown(mi)BOOLRead-onlyWhether this cycle has a measurement; FALSE only means the reading is 0xFFFF
WKCGetSecondaryWkcRt(mi)uint16_tRead-onlyReal-time filtered secondary-port value (drops in the same cycle when a slave is unplugged or the link breaks)

On a single-port setup (no secondary leg configured), 0 is a valid reading and counts as "known". So testing for "unknown" must use Diagnostics_SecondaryWkcKnown(); neither wkc != 0 nor treating 0xFFFF as a full count works.

Note also that on the real-time backend GetSecondaryWKC() is the measurement of the current cycle (no fresh measurement = 0xFFFF), not a carried peak; only backends that cannot decide fall back to the hold-window latch. For the per-cycle real-time filtered value use GetSecondaryWkcRt().

Example:

uint16_t sec = GetSecondaryWKC();   /* process-wide scale: no master_index parameter */

if (!Diagnostics_SecondaryWkcKnown(master)) {
printf("副口 WKC: 未知(本拍无实测)\n"); /* Secondary port WKC: unknown (no measurement this cycle) */
} else if (sec == 0) {
printf("副口 WKC: 0(单网口 / 副口本拍无贡献)\n"); /* Secondary port WKC: 0 (single NIC / secondary port contributed nothing this cycle) */
} else {
printf("副口 WKC: %u, 实时值 %u\n", sec, GetSecondaryWkcRt(master)); /* Secondary port WKC: %u, real-time value %u */
}

Real-time WKC readings​

uint16_t GetPrimaryWkcRt(uint16_t master_index);
uint16_t GetSecondaryWkcRt(uint16_t master_index);

Keep the real-time scale distinct from the peak-carrying scale of GetPrimaryWKC(): in redundancy mode, once the primary-port peak has been reached, it does not fall within the hold window after a slave is unplugged, so it can only answer "how many slaves this path once reached"; the real-time value drops with the measurement of the current cycle and can answer "is this path still receiving frames right now". On the real-time backend, the secondary-port GetSecondaryWKC() is already the measurement of the current cycle (no measurement = 0xFFFF). Do not substitute one scale for the other.

  • GetPrimaryWkcRt() — per-cycle real-time primary-port WKC; it drops to 0 in the same cycle when the primary port physically breaks.
  • GetSecondaryWkcRt() — real-time filtered secondary-port value; it falls with the filter window after a slave is unplugged. Use Diagnostics_SecondaryWkcKnown() to tell whether the secondary port has a fresh measurement in this cycle.

A return of 0 is a valid reading, not an error code: a broken primary link, no traffic on the secondary port and a non-real-time backend all read 0. This group of entry points has no "not ready" sentinel, so checking "is the runtime loaded" must use DarraEcat_ShellReady(); do not infer it from 0.

Example:

uint16_t pri_rt = GetPrimaryWkcRt(master);
uint16_t sec_rt = GetSecondaryWkcRt(master);
printf("实时 WKC: 主口=%u 副口=%u (粘峰值 主=%u 副=%u)\n", /* Real-time WKC: primary=%u secondary=%u (sticky peak primary=%u secondary=%u) */
pri_rt, sec_rt, GetPrimaryWKC(), GetSecondaryWKC());

Real OP verdict (RealOp)​

"AL status word reads OP" does not equal "this cycle is really exchanging process data". The status word sticks: after a slave drops, AL may still report OP, and the UI still shows "all OP" when the combined WKC is down to 6/12. Per-slave "real OP" is decided by the public diagnostic entry points from the evidence of the current cycle; a single status bit is not used in its place.

  • Conditions for the verdict to hold: the low 4 bits of the AL status = OP (0x08) and the Error bit (0x10) = 0, and the slave is not judged as a lost slave;
  • The AL status code is not checked: AL Status Code is not part of the criteria, and the SDK adds no second criterion either;
  • No WKC contribution bit is required: whether WKC is contributed in this cycle is display evidence only and cannot be used to overturn the verdict;
  • No consecutive-cycle count is required: the consecutive-cycle count takes no part in the verdict and is not a threshold; the struct carries a display-layer consecutive count stable_streak for UI anti-flap only, and it cannot overturn the verdict.

The master-level "real OP" is a separate layer (layered on top of the per-slave verdict; neither replaces the other): every required slave (not optional and with process data) must have a verdict that holds, and the combined measured WKC must not be below the fixed expectation from configuration time. Per-slave verdicts holding on their own does not mean the machine is in real OP.

Read-only verdict, not part of control

This API group only makes verdicts and drives display: it does not trigger recovery, stop PDO, leave OP, change the expected value, or change any existing control criterion. Evidence that cannot be read is always judged REAL_OP_REASON_UNKNOWN; cache or stale values are never passed off as real OP; the expected WKC is never lowered.

Entry points​

CategoryFunctionReturn typeRead/writeDescription
Diagnosticsmaster_capture_real_op_truth(mi, out)voidRead-onlyCaptures one cycle of real OP truth (master level + per slave); tracks stability internally
Diagnosticsmaster_evaluate_slave_real_op(mi, si, out)voidRead-onlySingle-slave verdict; no need to pay a full-bus cost for one row
Diagnosticsmaster_evaluate_real_op(mi, ev, n, wkc_actual, wkc_expected, out)voidRead-onlyEvaluates from same-cycle evidence (no re-read when a snapshot already exists)
Diagnosticsreal_op_reason_label(reason)const char*Read-onlyConverts the reason enumeration to a short Chinese label (display only)

A per-slave verdict must carry master context (otherwise UNKNOWN is returned honestly); the verdict uses only the evidence of the current cycle, and the consecutive-cycle count takes no part in it (the display-layer consecutive count stable_streak serves UI anti-flap only and cannot overturn the verdict).

A pair of lower-level direct entry points also exists (provided directly under DarraEcat_ names, without short-name wrappers): DarraEcat_ec_realop_judge(master, out) fills ec_realop_result_t (size / version / verdict / slave_count / op_count / degraded_count / unknown_count / wkc_actual / wkc_expected / flags), and DarraEcat_ec_realop_get_slave(master, slave, out) fills ec_realop_slave_t. Everyday applications only need the four entry points above — they already translate the lower-level verdict into the reason enumeration; go direct only when you need to read the raw verdict by slave index.

Reason enumeration real_op_reason_t​

ValueNameMeaning
0REAL_OP_REASON_OKReal OP: the per-slave verdict holds
1REAL_OP_REASON_AL_NOT_CLEANNot in OP base state / Error bit set / judged as a lost slave
2REAL_OP_REASON_NO_CONTRIBUTIONHistorical reason code: no longer produced by the per-slave verdict (value retained for compatibility)
3REAL_OP_REASON_UNSTABLEHistorical reason code: no longer produced by the per-slave verdict (value retained for compatibility)
4REAL_OP_REASON_WKC_DEFICITMaster level: every required slave holds, but the combined measured WKC is below the fixed expectation
5REAL_OP_REASON_UNKNOWNInsufficient evidence (criteria unavailable / no master context / no required slaves)

Result structure​

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

FieldTypeDescription
sequencelong longEvaluation sequence, increasing monotonically per master
real_opintMaster-level real OP
reasonreal_op_reason_tMain reason the master-level verdict does not hold
required_countintNumber of required slaves
real_op_countintNumber of required slaves in per-slave real OP
failed_countintNumber of required slaves not in real OP
wkc_actualintCombined measured WKC (as measured)
wkc_expectedintFixed expected WKC from configuration time (never lowered)
wkc_deficitintDeficit = max(0, expected − actual)
slavesslave_real_op_state_t[]Per-slave results (fixed capacity REAL_OP_MAX_SLAVES)
slave_countintNumber of entries written to slaves[]; count fields still cover the full input
detail_textchar[]Human-readable master detail

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

FieldTypeDescription
slave_indexintSlave index (1-based)
requiredintWhether it participates in the master-level verdict (not optional and has PDO)
al_clean_opintVerdict for this cycle (real OP = 1); same source and value as real_op, with the old field name kept for existing consumers
contributedintHas a WKC contribution in this cycle — display evidence only, not part of the verdict
stable_streakintDisplay-layer count of consecutive satisfied cycles, for UI anti-flap only; the criteria do not require consecutive cycles and it cannot overturn the verdict
real_opintThe slave is in real OP
reasonreal_op_reason_tReason it does not hold (REAL_OP_REASON_OK when it is in real OP)
detailchar[]Human-readable reason detail (not part of the verdict)

Example:

#include "master/real_op.h"

master_real_op_truth_t truth;
master_capture_real_op_truth(master, &truth);

if (truth.real_op) {
printf("真 OP: 必需站 %d/%d, WKC %d/%d\n", /* Real OP: required slaves %d/%d, WKC %d/%d */
truth.real_op_count, truth.required_count,
truth.wkc_actual, truth.wkc_expected);
} else {
printf("非真 OP [%s] %s\n", real_op_reason_label(truth.reason), truth.detail_text); /* Not real OP [%s] %s */
for (int i = 0; i < truth.slave_count; i++) {
const slave_real_op_state_t* s = &truth.slaves[i];
if (s->required && !s->real_op)
printf(" 从站 %d: %s — %s\n", s->slave_index, /* Slave %d: %s — %s */
real_op_reason_label(s->reason), s->detail);
}
}

Probe truth and lost-slave census​

int DarraEcat_Diagnostics_GetLostSlaveCensus(uint16_t master_index, uint16_t* out_count);
int DarraEcat_Diagnostics_GetNoProcessData(uint16_t master_index);
int DarraEcat_Diagnostics_GetProbeTruth(uint16_t master_index, int* out_a, uint16_t* out_b, int* out_c);
int DarraEcat_Diagnostics_GetSlaveProbeAlive(uint16_t master_index, uint16_t slave_index);
CategoryFunctionReturn typeRead/writeDescription
Probe truthDarraEcat_Diagnostics_GetLostSlaveCensus(mi, out_count)intRead-onlyLost-slave census: number of slaves currently judged lost; 0 = success
Probe truthDarraEcat_Diagnostics_GetNoProcessData(mi)intRead-onlyNumber of slaves without process data / flag; master-level, shared by all slaves in the same cycle
Probe truthDarraEcat_Diagnostics_GetProbeTruth(mi, out_a, out_b, out_c)intRead-onlyProbe truth triple (liveness probe / probe verdict); the three out parameters are int, uint16_t, int in order; 0 = success
Probe truthDarraEcat_Diagnostics_GetSlaveProbeAlive(mi, si)intRead-onlyWhether the single-slave probe answers: 1 = answers / 0 = no answer (lost) / negative = invalid parameter or not ready

These interfaces are provided in the C SDK only under DarraEcat_* names (declared in darra_ethercat_shell.h), with no short-name wrappers. They are read-only: they do not trigger recovery, stop PDO, or change the expected WKC. Treat anything unreadable as "unknown"; it must not be turned into "healthy". A probe answering 1 also does not mean the slave is in real OP — see the real OP criteria above.

Example:

uint16_t lost = 0;
if (DarraEcat_Diagnostics_GetLostSlaveCensus(master, &lost) == 0)
printf("当前判定为丢失的从站: %u 个\n", lost); /* Slaves currently judged lost: %u */

int no_pd = DarraEcat_Diagnostics_GetNoProcessData(master);
for (uint16_t s = 1; s <= slave_count; s++) {
int alive = DarraEcat_Diagnostics_GetSlaveProbeAlive(master, s);
if (alive == 0)
printf("从站 %u 探针无应答 (无过程数据标志=%d)\n", s, no_pd); /* Slave %u probe got no response (no process data flag=%d) */
}

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). Healthy OP slaves receive no state-change command and the PDO cycle keeps running. There is no public rebuild trigger (the former manual rebuild entry is retired: ordinal 1739 tombstone, never reused).

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 (the master asks for a re-scan and never rewrites another slot's address), an extra device not declared in DENI, an identity mismatch, or ambiguous ownership with several identical modules.

Do not - and cannot - "call a rebuild"

The only trigger lives in the kernel StateGuard. User space has no trigger function, no switch and no period setting; the application only reads the accounting below to see how many rounds ran and with what result.

Automatic rebuild accounting (read-only, zero frames):

FunctionReturnsMeaning
GetHotSwapRescanCount(mi)uint32_tCompleted automatic rebuild rounds (rejected before execution do not count); 0 = never
GetHotSwapRescanLastResult(mi)intLast result code: 0 succeeded / -20 BUSY / -21 RESCAN_0 / -23 NO_OP / -25 IDX_FULL; gates -1 / -6; historical -22 / -24 / -26 only from an old DLL
GetHotSwapRescanLastTimeMs(mi)int64_tLast completion time (Unix ms UTC); 0 = never

Example:

uint32_t rounds = GetHotSwapRescanCount(master);
int last = GetHotSwapRescanLastResult(master);
int64_t when = GetHotSwapRescanLastTimeMs(master);
if (rounds == 0) printf("自动热插拔重建:尚未发生\n"); /* Automatic hot-plug rebuild: has not happened yet */
else printf("自动重建 %u 轮,上次结果 %d,时刻 %lld\n", /* Automatic rebuild %u rounds, last result %d, at %lld */
rounds, last, (long long)when);

P1 foldback topology​

Read-only query of the P1 foldback topology calibration result and slave reachability. Declared in master/diagnostics.h and slave/core.h; all return int.

CategoryMemberReturnRead/writeDescription
P1 foldbackGetTopoP1Mode(mi)intRead-only0=NONE (no foldback needed or not calibrated in this cycle), 1=SINGLE_NIC (single NIC, no foldback window), 2=DUAL_RING_BRANCH (dual NIC ring + branch, foldback required); -1=invalid master index
P1 foldbackGetTopoP1Measured(mi)intRead-only1 = on-site topology was measured in this cycle; 0 = not measured in this cycle; -1 = invalid master index
P1 foldbackGetTopoP1FullWkc(mi)intRead-onlyMeasured total working counter at that foldback position; -1 = unavailable
P1 foldbackGetTopoMeasuredRingCount(mi)intRead-onlyMeasured number of slaves on the ring; -1 = unavailable
P1 foldbackGetSlaveP1FoldbackOnly(mi, si)intRead-only1 = the slave is reachable only through the foldback window; 0 = not a branch slave / property not calibrated; -1 = invalid master index or slave index. When set, addressing its position requires opening the foldback window first.

All members are read-only queries and change no state. -1 only means unavailable / not calibrated / invalid parameter (master index or slave index out of range, master released); treat it as "cannot read". 0 is a real value, not a failure: GetTopoP1Mode returning 0 means NONE, GetTopoP1Measured returning 0 means no on-site topology measurement in this cycle, and GetTopoMeasuredRingCount returning 0 means the measurement found 0 slaves; do not treat 0 as an error.

Example:

uint16_t master = Initialize();
uint16_t slave_count = SetNetwork(master, "\\Device\\NPF_{GUID}", ""); /* returns the number of slaves found; 0xFFFF on failure */
Start(master);

int mode = GetTopoP1Mode(master);
int measured = GetTopoP1Measured(master);
int full_wkc = GetTopoP1FullWkc(master);
int ring_count = GetTopoMeasuredRingCount(master);

if (measured < 0) {
/* unavailable: invalid master index */
printf("主站 %u 不可用\n", (unsigned)master); /* Master %u is unavailable */
} else if (measured == 0) {
printf("P1 属性本轮未实测\n"); /* P1 properties were not measured this round */
} else if (mode == 2) {
printf("双 NIC 环+分支: 满 WKC=%d, 环 %d 站\n", full_wkc, ring_count); /* Dual-NIC ring + branch: full WKC=%d, %d slaves on the ring */
} else if (mode == 1) {
printf("单 NIC, 无折返窗口\n"); /* Single NIC, no loopback window */
} else {
printf("NONE\n"); /* mode == 0 is a valid value, not a failure */
}

/* slave level: 1 = reachable only through the foldback window, 0 = not a branch slave / not calibrated, -1 = invalid master index or slave index */
for (int si = 1; si <= slave_count; si++) { /* slave_count = number of slaves found, as returned by SetNetwork */
int foldback = GetSlaveP1FoldbackOnly(master, si);
if (foldback < 0) continue; /* unavailable, not 0 */
if (foldback == 1)
printf("从站 %d 只能经折返窗口可达, 位置寻址前先打开折返窗口\n", si); /* Slave %d is reachable only through the loopback window; open the loopback window before position addressing */
}

DC synchronization​

Automatic monitoring (ETG.1500 5.13.3): the time deviation of each slave is checked every second. When it exceeds the SyncWindowThreshold threshold, the DCSyncLost callback fires.

void SetSyncWindowThreshold(uint16_t master_index, int threshold_ns);
int GetSyncWindowThreshold(uint16_t master_index);

threshold_ns defaults to 1000 ns.

Single slave

For the synchronization state of an individual slave use GetSlaveSyncWindowStatus().

DC diagnostics 2-second snapshot​

Per-slave and master-level DC verdicts are assembled once; all consumers within the same 2 seconds share one object, so different columns do not end up reading separate scales. Everything the snapshot reads is a local cache and sends no bus frames.

CategoryC entry pointC++ lower-level entry pointRead/writeDescription
Snapshotdc_diagnostics_get(mi)MasterDiagnosticsInfo::DcDiagnostics()Read-onlyReturns a borrowed pointer; the same buffer may be reused after as little as 2 seconds, so copy immediately when using it across threads
Single-slave lookupdc_diagnostics_find(snapshot, si)Snapshot member Find(si) / FindDcSample(si)Read-onlyOut of range / not sampled returns NULL (nullptr / std::nullopt in C++); no placeholder row is fabricated
Single-slave historydc_diagnostics_try_get_slave(mi, si, &out)FindDcSample(si)Read-onlyReads only the most recent completed sample and does not trigger a new sample
Invalidate cachedc_diagnostics_invalidate(mi)—WriteCall after the master is released / re-initialized; drops samples and the slave table so old values are not reused across contexts

Master-level fields (ec_dc_diagnostics_snapshot_t):

CategoryFieldRead/writeDescription
DC diagnosticscaptured_at_utc_msRead-onlyAssembly time of this cycle (UTC milliseconds)
DC diagnosticshas_dcRead-onlyWhether the network has slaves with DC capability (capability-bit scale)
DC diagnosticshas_sync_window_threshold_ns / sync_window_threshold_nsRead-onlyWhen the threshold cannot be read, has = FALSE, distinct from "threshold is 0"
DC diagnosticsreference_clockRead-onlyReference clock slave index + tier + reason; when there is no DC slave, an explicit instance is returned (slave index 0)
DC diagnosticsactive_slave_countRead-onlyNumber of slaves whose 0x0980 applied value is anything other than 0
DC diagnosticsarmed_slave_countRead-onlyNumber of slaves known to have SYNC0 armed
DC diagnosticsarmed_unknown_countRead-onlyNumber of slaves with an unknown armed verdict
DC diagnosticsactive_without_process_data_countRead-onlyNumber of slaves that are DC-active but have no process data bytes
DC diagnosticsapplicable_window_countRead-onlyNumber of slaves with a usable measured window; 0 = the maximum synchronization difference is unavailable
DC diagnosticsarmed_sync_participant_countRead-onlyNumber of participant slaves that are armed and are not the reference clock
DC diagnosticshas_max_drift_ns / max_drift_nsRead-onlyWhen there is no usable window, has = FALSE, not 0
DC diagnosticsall_in_sync_known / all_in_syncRead-onlyWhen there are no confirmed participants, known = FALSE (unknown), not TRUE
DC diagnosticsexpected_wkcRead-onlyExpected WKC fixed at configuration time
DC diagnosticshas_propagation_delay_resolved_at_utc / propagation_delay_resolved_at_utc_msRead-onlyAlways FALSE / 0 on the C side (the SDK maintains this accounting internally and C has no equivalent source); not fabricated
DC diagnosticshas_propagation_delay_resolve_count / propagation_delay_resolve_countRead-onlyCount form of the same accounting; likewise always FALSE / 0 on the C side
DC diagnosticsany_read_failureRead-onlyAt least one slave or the reference clock failed to read in this cycle
DC diagnosticsslaves / slave_countRead-onlyPer-slave array (borrowed pointer, ascending by slave index, no placeholder rows)
Tri-state must not be folded into 0

all_in_sync_known = FALSE and has_max_drift_ns = FALSE both mean "no conclusion", not "all synchronized" or "the difference is 0". For tri-state you must read this snapshot; the older two-state summary fields (for example the C# SDK DcMaxDriftNs returns -1 without a measurement and DcAllInSync returns false without a conclusion, each with a companion *Known bit) are a reduced surface kept for existing consumers and must not be used as tri-state.

Sampling cadence

The C dc_diagnostics_get() returns a borrowed pointer, and the same buffer may be reused after as little as 2 seconds, so copy the fields you need immediately when using it across threads. The C++ lower layer has no background sampling thread; the 2-second TTL advances when the caller polls DcDiagnostics(). For history-type conclusions on a 2-second cadence (frozen cycle count / jitter σ / convergence time), read roughly every 200 milliseconds.

Redundancy status​

int  GetBreakPoints(uint16_t master_index,
uint16_t* out_slaves, uint8_t* out_ports,
uint8_t* out_types, uint16_t max_results);
int GetRingMode(uint16_t master_index); /* ring redundancy operating mode, not the P1 foldback requirement mode */
BOOL GetSecondaryLinkStatus(uint16_t master_index); /* TRUE = explicitly Up; FALSE = Down or unknown */

GetBreakPoints() detects all current fault points and covers two kinds of physical fault with one call:

FaultTypeTypeDetectionTypical scenario
EC_DIAG_BP_LINK_LOST(0)Link breakPhysical link loss on the DL Status portCable unplugged, cable broken
EC_DIAG_BP_CRC_FAULT(1)CRC faultPort-level RxError + InvalidFrame keep growingPoor contact, cable aging

GetBreakPoints() returns >= 0 = the number of fault points (0 = the diagnostic cache has not been built yet, or there really is no fault); -1 = invalid parameter / master, i.e. a failed query, and must not be treated as "no fault". The C ABI has no separate "query succeeded" flag; for a reliable tri-state use the per-language wrappers: C++ LastBreakPointsQueryOk() / master_redundancy::GetBreakPoints(..., &queryOk), C# TryGetBreakPoint / GetAllBreakPoints(), Java getAllBreakPoints(), Python get_break_points(), Rust all_break_points().

GetRingMode() returns ec_ring_mode_t: EC_RING_INACTIVE(0) = inactive, EC_RING_DUAL(1) = bidirectional redundancy, EC_RING_DEGRADED(2) = the secondary link is unavailable and only the primary works.

redundancy_active means "redundancy protection is running", not "both ports carry frames"

redundancy_active in GetDiagnosticsSnapshot() / GetDiagnosticsSummaryMirror() = GetRingMode(mi) >= 1 and both the primary and secondary ports carry frame traffic in this window. In a chain (end foldback) topology the primary port sends and the secondary port receives, the whole chain is traversed twice and both ports carry frames, but physically there is no second independent path — this field is FALSE, consistent with RingMode = 0.

For the fact of "do both ports carry frames", read PrimaryPortTxCount / PrimaryPortRxCount / SecondaryPortTxCount / SecondaryPortRxCount from ec_diagnostics_data_t, or primary_port_ok / secondary_port_ok from the summary; do not infer it from this field. GetSlaveRedundancyActivated() uses the same master-level criterion (GetRingMode >= 1); it is not a per-slave independent conclusion.

Locating a faulty cable segment: when the facing ports of adjacent slaves (for example P1 of slave N and P0 of slave N+1) report faults at the same time, the cable segment between them is suspect; a fault reported on one side only points to that port connector.

Link diagnostics events​

uint32_t GetLinkDiagEventCount(uint16_t master_index);
uint32_t GetLinkDiagEvents(uint16_t master_index, uint32_t since_seq,
ec_link_diag_event_t* out, uint32_t max);
uint32_t GetLinkDiagSeq(uint16_t master_index);
CategoryFunctionReturn typeRead/writeDescription
Link eventsGetLinkDiagEventCount(mi)uint32_tRead-onlyCumulative event count (including history already overwritten by wraparound); use it to tell whether there are new events
Link eventsGetLinkDiagEvents(mi, since_seq, out, max)uint32_tRead-onlyCopies at most max events starting from since_seq and returns the actual count; 0 = no new events
Link eventsGetLinkDiagSeq(mi)uint32_tRead-onlyFreshness token: monotonic increase = the event ring is being written; stops increasing = the recording thread is not running

Event kind values: 1=A_LINK_DOWN, 2=B_LINK_DOWN, 3=MIDDLE_BROKEN, 4=HEALTHY, 5=TOTAL_LOST, 6=PHY_A, 7=PHY_B, 8=FAILOVER, 9=RECOVER, 10=QUICK_FLAP, 11=WKC_TUPLE.

Polling pattern: read GetLinkDiagSeq() first; only when it differs from the last recorded seq, fetch incrementally with GetLinkDiagEvents(mi, last_seq, buf, cap), then advance last_seq after the fetch. To tell whether recording is running, check whether seq is still increasing; do not infer that nothing went wrong from an event count of 0.

Example:

ec_link_diag_event_t evs[16];
uint32_t seq = GetLinkDiagSeq(master);
if (seq != last_seq) {
uint32_t n = GetLinkDiagEvents(master, last_seq, evs, 16);
for (uint32_t i = 0; i < n; i++)
printf("链路事件 kind=%u, seq=%u, 时刻=%llu us\n", /* Link event kind=%u, seq=%u, at=%llu us */
evs[i].kind, evs[i].seq, (unsigned long long)evs[i].t_us);
last_seq = seq;
}

Diagnostics snapshot​

BOOL GetDiagnosticsSnapshot(uint16_t master_index, ec_diagnostics_snapshot_t* snapshot);

One call gets a consistent snapshot of all diagnostic data (thread-safe), avoiding the inconsistency and overhead of multiple property accesses. Suits UI refresh and logging scenarios.

typedef struct {
int frequency; /* frames per second (Hz) */
uint32_t error_count; /* errors per second */
float packet_loss_rate; /* packet loss rate (0.0-1.0) */
float late_frame_rate; /* late frame rate (0.0-1.0) */
double mailbox_latency_avg_us; /* mailbox round-trip latency - average (microseconds) */
double mailbox_latency_us; /* mailbox round-trip latency - maximum (microseconds) */
int cycle_time_us; /* actual cycle time (microseconds); falls back to 1e6/Hz when 0 */
uint16_t wkc_actual; /* current WKC */
uint16_t wkc_expected; /* expected WKC */
uint32_t bus_cycle_hz; /* bus frequency (Hz) */
double bus_max_jitter_us; /* maximum bus jitter (microseconds) */
double bus_avg_jitter_us; /* average bus jitter (microseconds) */
double bus_roundtrip_us; /* bus round-trip latency (microseconds) */
double bus_load_percent; /* communication load (%) */
uint32_t smi_count; /* SMI count */
double smi_peak_us; /* SMI peak (microseconds) */
int primary_port_ok; /* primary port OK (BOOL) */
int secondary_port_ok; /* secondary port OK (BOOL) */
int redundancy_active; /* redundancy active (BOOL) */
} ec_diagnostics_snapshot_t;
Mailbox round-trip latency (formerly "application jitter")

mailbox_latency_us / mailbox_latency_avg_us reflect the round-trip latency of mailbox transactions (acyclic request-response exchanges such as CoE/SoE/FoE/EoE/AoE/VoE) — the time from sending the request to receiving the response (maximum / average settled over the last 1 second).

PDO process data is already sent and received by the real-time communication layer with zero-copy pointers into the real-time process image, so there is no "per-cycle notification on the application side" step; the old "application jitter" metric lost its meaning and was replaced by mailbox transaction latency. Bus timing is still reflected by bus_max_jitter_us / bus_avg_jitter_us.

Example:

ec_diagnostics_snapshot_t snap;
if (GetDiagnosticsSnapshot(master, &snap)) {
printf("频率: %d Hz, 邮箱收发延迟: %.2f us, WKC: %d/%d, 丢包: %.4f\n", /* Frequency: %d Hz, mailbox latency: %.2f us, WKC: %d/%d, packet loss: %.4f */
snap.frequency, snap.mailbox_latency_us,
snap.wkc_actual, snap.wkc_expected, snap.packet_loss_rate);
}

Diagnostic control​

void SetDiagnosticsEnabled(uint16_t master_index, BOOL enable);
BOOL GetDiagnosticsEnabled(uint16_t master_index);
void ResetDiagnostics(uint16_t master_index);

SetDiagnosticsEnabled() enables/disables diagnostic data collection (off by default; periodic sampling starts once enabled). ResetDiagnostics() resets all diagnostic statistics in one call: basic diagnostic statistics, PDO frame loss statistics, DC synchronization window statistics, and the port error counters of all slaves. It clears master-level statistics only and does not affect the FSoE safety connection state machine.

Cycle sliding-window statistics (CS)​

Cycle statistics over a 5-second window with 0.2-second sampling. Window advancement and sampling throttling are done on the runtime side; the SDK does no second-level computation.

CategoryFunctionReturn typeRead/writeDescription
CS windowDiagCsWindow_Sample(mi, now_ts, ts_freq)voidWrite-onlyTakes one sample; the two timestamp parameters must use the same unit
CS windowDiagCsWindow_GetStats(mi, out)BOOLRead-onlyGets the current window statistics; TRUE = statistics available, FALSE = none and out is not zeroed
CS windowDiagCsWindow_Reset(mi)voidWrite-onlyClears the window statistics

Related structure:

typedef struct ec_diag_cs_window_stats {
double error_per_sec; /* error rate: errors per second */
double cycle_hz; /* cycle frequency (Hz) */
double avg_jitter_us; /* average jitter (microseconds) */
int32_t filled; /* number of samples in the window */
int32_t reserved; /* reserved, always 0 */
} ec_diag_cs_window_stats_t;
GetStats does not zero out when it returns FALSE

DiagCsWindow_GetStats() returning FALSE means there are no statistics right now, and out is not zeroed. The caller must zero the structure first and then decide from the return value whether to use it; leftover values from the previous call must not be taken as new statistics.

Example:

ec_diag_cs_window_stats_t cs = {0};   /* must be zeroed first */
DiagCsWindow_Sample(master, now_ts, ts_freq);
if (DiagCsWindow_GetStats(master, &cs)) {
printf("错误/秒=%.2f, 周期=%.1f Hz, 平均抖动=%.2f us (样本 %d)\n", /* Errors/sec=%.2f, cycle=%.1f Hz, average jitter=%.2f us (%d samples) */
cs.error_per_sec, cs.cycle_hz, cs.avg_jitter_us, cs.filled);
}

AL error classification​

/* defined in master/diagnostics_ext.h; per-code classification, authoritative source = the runtime AL status table */
typedef enum {
AL_ERR_NONE = 0, /* no error (0x0000) */
AL_ERR_TRANSIENT = 1, /* transient: retry the state transition, usually recovers on its own */
AL_ERR_CONFIGURATION = 2, /* configuration: PDO mapping / SM / Startup parameters need fixing */
AL_ERR_HARDWARE = 3, /* hardware: slave device / cabling / power / mailbox / EEPROM */
AL_ERR_UNKNOWN = 4 /* unknown: vendor-specific / unlisted code, or classification unavailable */
} DarraAlErrorClass;

DarraAlErrorClass diagnostics_classify_al_error(uint16_t alStatusCode);

Classifies a slave AL Status Code to help determine the nature of the error and the handling strategy. The classification is per code: the single authority is the AL status table built into the runtime (k_al_status_table[].recovery_class in status_codes.c, implemented once by the runtime and exposed as a classification result). The C SDK keeps no second classification table and no longer buckets by the high-order segment of the code — different codes inside one segment can belong to different classes (for example 0x0024 invalid input mapping = configuration, 0x002C fatal sync error = transient).

ClassValueSuggested handling
AL_ERR_NONE0No error, nothing to do
AL_ERR_TRANSIENT1Transient error; retry the state transition, usually recovers on its own
AL_ERR_CONFIGURATION2Configuration error; check PDO mapping, SM configuration and Startup parameters
AL_ERR_HARDWARE3Hardware error; check slave device, cabling, power supply and EEPROM
AL_ERR_UNKNOWN4Unlisted code / vendor-specific code / classification unavailable; consult ETG.1000 or the slave manual

The values are identical to the return codes of the runtime classification entry (0..4), and the per-code results match C++ / C# / Java / Python / Rust exactly. When the runtime is unavailable (shell not bound / library not loaded) the function returns AL_ERR_UNKNOWN, never AL_ERR_NONE — "cannot classify" must stay distinguishable from "no error".

Common AL Status Codes
  • 0x0011 invalid requested state change — AL_ERR_TRANSIENT
  • 0x001D invalid output configuration — AL_ERR_CONFIGURATION
  • 0x001E invalid input configuration — AL_ERR_CONFIGURATION
  • 0x002D sync not received (the ETG.1000.6 literal name "No sync error" does not mean error-free) — AL_ERR_TRANSIENT
  • 0x0032 PLL error — AL_ERR_TRANSIENT
  • 0x0052 external hardware not ready — AL_ERR_HARDWARE
C-specific syntactic sugar

When printing slave state, C can use the inline ec_state_name(state) to turn EC_STATE_INIT/PRE_OP/SAFE_OP/OP/BOOT directly into a string, masking off the error bits (& 0x0F); likewise ec_link_name(ec_link(mi)) outputs "DOWN" / "UP" / "PRIMARY_ONLY" / "SECONDARY_ONLY" / "UNKNOWN" (unknown is a word of its own and is not merged into link down).

Slave error counters​

BOOL ResetSlavePortErrorCounters(uint16_t master_index, uint16_t slave_index);
BOOL ReadSlavePortErrorCounters(uint16_t master_index, uint16_t slave_index,
uint8_t* rx_error, uint8_t* invalid_frame, uint8_t* lost_link);
int ReadAllSlavePortErrorCounters(uint16_t master_index);
void* GetSlavePortErrorStats(uint16_t master_index, uint16_t slave_index);

Read/reset the slave ESC port error counters (ETG.1000.4). rx_error / invalid_frame / lost_link are each 4-byte arrays corresponding to ports P0-P3 (ec_esc_port_error_stats_t, returned by GetSlavePortErrorStats(), additionally carries FwdRxErrorCount[4]).

Example:

uint8_t rx[4], inv[4], lost[4];
if (ReadSlavePortErrorCounters(master, 1, rx, inv, lost)) {
for (int p = 0; p < 4; p++) {
if (rx[p] || inv[p] || lost[p])
printf("从站1 P%d: rx=%u inv=%u lost=%u\n", p, rx[p], inv[p], lost[p]); /* Slave 1 P%d: rx=%u inv=%u lost=%u */
}
}

Configuration pre-check​

int ec_validate_config(uint16_t master_index);

Pre-check before Build that the master configuration is complete (network adapter, slave discovery, PDO mapping, etc.). 0 means the configuration is valid; a non-0 value is the number of configuration problems.

Master identity and diagnostic objects​

BOOL GetMasterIdentity(uint16_t master_index, ec_master_identity_t* identity);
BOOL GetMasterDiagData(uint16_t master_index, ec_master_diag_data_t* diag);

Reads the master's ETG.1510 standard objects: identity object 0x1018 (VendorID/ProductCode/RevisionNumber/SerialNumber) and diagnostic data object 0xF120.

Diagnostic messages (CoE 0x10F3 diagnostic history)​

Slave object 0x10F3 (diagnostic history object, ETG.1020) is a standard object-dictionary object; the application layer can read its subindices directly through the public typed SDO interfaces (such as sdo_read_u16 / sdo_read_string): 0x10F3:04 whether there is a new message, 0x10F3:02 the latest number, 0x10F3:05 flags, 0x10F3:06..FF the individual messages, 0x10F3:03 writing a number to acknowledge it as read.

note

Not every slave supports the 0x10F3 diagnostic history object. On a slave that does not, sdo_read_typed_ex fills out_abort with an object-does-not-exist error. This object is read over SDO; calling it frequently on a real-time path is not recommended.

Emergency control and abort​

void AbortScan(void);
void AbortNetwork(void);
void ResetAbortNetwork(void);

Aborts an in-progress network scan so that a long operation does not block the caller.

Full example​

#include "ethercat.h"
#include <stdio.h>

int main(void) {
uint16_t master = Initialize();
SetNetwork(master, "\\Device\\NPF_{GUID}", "");
SetStateSequence(master, EC_STATE_OPERATIONAL, 10000);
Start(master);

SetDiagnosticsEnabled(master, TRUE);

/* consistent snapshot */
ec_diagnostics_snapshot_t snap;
if (GetDiagnosticsSnapshot(master, &snap)) {
printf("频率: %d Hz, 邮箱收发延迟: %.2f us, 丢包: %.4f\n", /* Frequency: %d Hz, mailbox latency: %.2f us, packet loss: %.4f */
snap.frequency, snap.mailbox_latency_us, snap.packet_loss_rate);
}

/* PDO frame loss */
uint32_t total, cur, max;
GetPDOFrameLossStats(master, 0, &total, &cur, &max);
if (cur > 10) printf("警告: PDO 连续丢帧 %u\n", cur); /* Warning: %u consecutive PDO frame losses */

/* fault points */
uint16_t bp_s[8]; uint8_t bp_p[8], bp_t[8];
int n = GetBreakPoints(master, bp_s, bp_p, bp_t, 8);
for (int i = 0; i < n; i++) {
printf("故障: 从站%d P%d %s\n", bp_s[i], bp_p[i], /* Fault: slave %d P%d %s */
bp_t[i] == EC_DIAG_BP_LINK_LOST ? "断线" : "CRC故障"); /* cable break / CRC fault */
}

/* AL error classification */
uint16_t al = GetSlaveALStatusCode(master, 1);
if (al) {
DarraAlErrorClass c = diagnostics_classify_al_error(al);
printf("从站1 错误 0x%04X: 分类=%d\n", al, c); /* Slave 1 error 0x%04X: category=%d */
}

ResetDiagnostics(master);
Stop(master);
Dispose(master);
return 0;
}

Diagnostic field guide by problem (C style)​

GetDetailedDiagnostics(mi) returns ec_diagnostics_data_t* (all fields PascalCase). Bus RT performance metrics come from ec_diagnostics_snapshot_t, filled by GetDiagnosticsSnapshot().

Site symptomC interface
Is it packet loss?diag->LostFrames + GetPacketLossRate(mi)
Sporadic or persistent?diag->ConsecutiveWkcErrors (≥5 = persistent)
Cumulative WKC mismatch?diag->TotalWkcMismatches / diag->WorkingCounterErrors
CRC problem?diag->InvalidFrameCount[i] (ESC 0x0304)
Which cable is broken?GetBreakPoints(mi, ...)
Bus jitter / cycle?snap.bus_max_jitter_us / snap.bus_cycle_hz (GetDiagnosticsSnapshot)

Frame errors (TX vs RX comparison)​

ec_diagnostics_data_t fields:

  • LostFrames: frames that never came back
  • TimeoutFrames: no response within the PDO cycle
  • WorkingCounterErrors: WKC mismatch
  • ConsecutiveWkcErrors: consecutive WKC errors (the key to distinguishing sporadic from persistent)
  • TotalWkcMismatches: cumulative total of WKC mismatches
  • FrameErrors: derived sum
  • ChecksumErrors: physical-layer CRC (derived from the ESC)

Port transmit and receive​

PrimaryPortTxCount / PrimaryPortRxCount, SecondaryPortTxCount / SecondaryPortRxCount, PrimaryPortErrors / SecondaryPortErrors (5-second sliding window)

Per-slave physical layer (ESC registers, arrays 1-based)​

RxErrorCount[i] (ESC 0x0300) | InvalidFrameCount[i] (ESC 0x0304 CRC) | LostLinkCount[i] (ESC 0x0310) | LinkQualityPercent[i]

PDO frame loss (per group)​

PdoLostFrames[g] (cumulative lost frames) | PdoConsecutiveLost[g] (current consecutive) | PdoMaxConsecutiveLost[g] (historical maximum consecutive)

Bus RT performance​

Read ec_diagnostics_snapshot_t consistently through GetDiagnosticsSnapshot(mi, &snap):

  • bus_cycle_hz / bus_max_jitter_us / bus_avg_jitter_us / bus_roundtrip_us
  • frequency / mailbox_latency_us / mailbox_latency_avg_us / cycle_time_us / packet_loss_rate

Complete diagnostic workflow example (C)​

ec_diagnostics_data_t* diag = (ec_diagnostics_data_t*)GetDetailedDiagnostics(mi);

// 1. Persistent vs sporadic
if (diag->ConsecutiveWkcErrors >= 5)
printf("持续 WKC 错误\n"); /* Persistent WKC error */

// 2. Packet loss rate
float loss = GetPacketLossRate(mi);
if (loss > 0.01f) printf("丢包率 %.2f%% 严重\n", loss * 100.0f); /* Packet loss rate %.2f%% is severe */

// 3. Fault location
uint16_t bp_slaves[16]; uint8_t bp_ports[16]; uint8_t bp_types[16];
int bpn = GetBreakPoints(mi, bp_slaves, bp_ports, bp_types, 16);
for (int i = 0; i < bpn; i++)
printf("故障点: 从站 %d P%d (类型=%d)\n", bp_slaves[i], bp_ports[i], bp_types[i]); /* Fault point: slave %d P%d (type=%d) */

// 4. Most unstable slave (by ESC CRC error count)
int worst = 0; uint16_t worstCnt = 0;
for (int i = 1; i < EC_MAXSLAVE; i++)
if (diag->InvalidFrameCount[i] > worstCnt)
{ worstCnt = diag->InvalidFrameCount[i]; worst = i; }
if (worstCnt > 0) printf("CRC 错误最多的从站: #%d (%u 次)\n", worst, worstCnt); /* Slave with the most CRC errors: #%d (%u times) */

// 5. Bus RT performance
ec_diagnostics_snapshot_t snap;
if (GetDiagnosticsSnapshot(mi, &snap))
printf("总线 %u Hz, 最大抖动 %.2f us\n", /* Bus %u Hz, max jitter %.2f us */
snap.bus_cycle_hz, snap.bus_max_jitter_us);

Low-level diagnostic entry points and window counters​

This section gathers the lower-level entry points of master diagnostics: hot-plug rescan accounting, per-port frame counters, the per-slave WKC probe, read-only internal views, and cyclic writes and export. In master/diagnostics.h they are all static inline and forward one-to-one to the DarraEcat_* export of the same name; there is no second implementation.

Low-level / debug entry points

Apart from "read-only internal views", most entry points in this section are for the runtime itself, diagnostic tools and on-site troubleshooting, and ordinary applications do not need to call them directly. Day-to-day diagnostics still go through the high-level entry points above such as GetDiagnosticsSnapshot(), the WKC mirror and GetDetailedDiagnostics(): low-level entry points only answer "what the counter is now / what this probe read this cycle" and carry no control verdict.

General reading rules:

  • The same 0 means different things in different families (a 0 counter = never / none, a 0 result code = success); interpret each table entry by entry and do not apply one family's rule to another.
  • Negative values from int entry points are "unavailable / unreadable" sentinels or failure codes, not measurements; before judging 0, confirm that the value is not a negative sentinel.
  • None of these entry points trigger recovery, stop PDO or change the expected WKC.

Automatic rebuild accounting​

Three entry points answer "how many automatic rebuilds have run / the last result / when the last one was". They record rounds the kernel really executed; a round rejected before it started (gate codes -1 / -6) is not counted. There is no manual entry point to call.

CategoryFunctionReturn typeRead/writeDescription
Hot-plugGetHotSwapRescanCount(mi)uint32_tread-onlyCompleted automatic rebuild rounds; calls rejected before execution are not counted. 0 = never
GetHotSwapRescanLastResult(mi)intread-onlyResult code of the last automatic rebuild: 0 success / -20 BUSY (a rebuild is already in progress) / -21 RESCAN_0 (a rescan can reach 0 slaves) / -23 NO_OP (slaves are present but not in OP, carrying the first AL) / -25 IDX_FULL (resources exhausted); gate codes -1 invalid master index / -6 master not initialized. -22 / -24 / -26 are historical codes returned only by older runtimes. 0 = never or last succeeded, disambiguate with Count / LastTimeMs
GetHotSwapRescanLastTimeMs(mi)int64_tread-onlyTime the last automatic rebuild completed (Unix milliseconds UTC). 0 = never

-21 (a rescan can reach 0 slaves) is not attributed to a broken link under the EtherCAT physical mechanism — it is the fact that "no slave on this side answered", not the conclusion "the cable is cut"; the runtime rolls back the removal re-baseline already applied in this round instead of blindly raising the state.

These three values only count automatic rebuilds that really executed: a round rejected by a gate code or by parameter validation before it starts is not counted, and they stay at 0 when no automatic rebuild has ever run. A count of 0 only means "no automatic rebuild really executed"; it does not imply "no slave ever dropped".

Example:

uint32_t rounds = GetHotSwapRescanCount(master);
int last = GetHotSwapRescanLastResult(master);
int64_t when = GetHotSwapRescanLastTimeMs(master);

if (rounds == 0 && when == 0) {
printf("尚未执行过运行中重扫\n"); /* No in-operation rescan has been run yet */
} else if (last == 0) {
printf("最近一次重扫成功(累计 %u 轮), 完成于 %lld ms\n", /* Last rescan succeeded (%u rounds so far), completed at %lld ms */
rounds, (long long)when);
} else {
printf("最近一次重扫失败: 结果码 %d\n", last); /* -20 / -21 / -23 / -25 */
}

Per-port frame counters and drops​

The four frame counters are raw per-port counts answering "how many frames did the primary / secondary port send and receive"; they are also direct evidence for "is there frame traffic on both ports". For a packet-loss rate / late-frame rate, use GetPacketLossRate() / GetLateFrameRate() (5-second sliding window) — those are ratios, a different measure from the raw counters here, and the two cannot replace each other.

CategoryFunctionReturn typeRead/writeDescription
Per-port frame countersGetWdkPrimaryFrameTx(mi)uint32_tread-onlyPrimary-port transmitted frame count (raw per-port count)
GetWdkPrimaryFrameRx(mi)uint32_tread-onlyPrimary-port received frame count
GetWdkSecondaryFrameTx(mi)uint32_tread-onlySecondary-port transmitted frame count
GetWdkSecondaryFrameRx(mi)uint32_tread-onlySecondary-port received frame count
GetWdkPdoIdxDropCount(mi)uint32_tread-onlyPDO frame sequence number (idx) drop count
P1 foldbackGetTopoP1RingEndAdp(mi)intread-onlyRing-end adapter number of the P1 foldback (= 1 - k); -1 = unavailable (not calibrated / not a dual-NIC ring with branches / invalid master index)

Strictly speaking GetTopoP1RingEndAdp() is a P1 foldback topology property (same family as 「P1 foldback topology」 above) rather than a frame counter; it is listed in this group because it is produced in the same on-site calibration pass as the per-port frame counters. -1 only means unavailable; do not use it as a measurement.

Example:

printf("主口 TX=%u RX=%u, 副口 TX=%u RX=%u\n",   /* Primary port TX=%u RX=%u, secondary port TX=%u RX=%u */
GetWdkPrimaryFrameTx(master), GetWdkPrimaryFrameRx(master),
GetWdkSecondaryFrameTx(master), GetWdkSecondaryFrameRx(master));
printf("PDO idx 丢弃 %u 次\n", GetWdkPdoIdxDropCount(master)); /* PDO idx dropped %u times */

int ring_end = GetTopoP1RingEndAdp(master);
if (ring_end >= 0)
printf("环末端适配器号 = %d\n", ring_end); /* -1 = not available, not a measured value*/

Per-slave WKC probe​

The probe sends a 1-byte read-only LRD to that slave's FMMU logical address, and the WKC of that datagram is "the truth about that slave's hardware" (input side). It is read-only with zero side effects: no output writes, no register writes, and it does not enter any aggregated WKC accounting. The mode defaults to OFF; while it is off the runtime returns early every cycle without sending frames, so the mainline behaviour is unchanged. Slave indices are 1-based (1..MAXSLAVE-1), the same convention as GetSlaveWcState().

CategoryFunctionReturn typeRead/writeDescription
Per-slave probePerSlaveWkcProbe_SetMode(mi, mode)voidwrite-onlySets the probe mode; an invalid mode is rejected by the runtime and the previous value is kept. The function returns nothing, so re-check with GetMode after setting
PerSlaveWkcProbe_GetMode(mi)uint16_tread-only0 = OFF (default) / 1 = PROBE_READ; returns (uint16_t)-1 (all 1s) when the runtime is not ready, never pretending to be 0 = OFF
PerSlaveWkcProbe_GetExpectedWkc(mi, si)intread-only1 = this slave has a read FMMU and is expected to be probed; -1 = not probeable (no read FMMU / out of range)
PerSlaveWkcProbe_GetActualWkc(mi, si)intread-only>=0 = the true datagram WKC (0 = an echo came back but this slave contributes nothing, which is a legitimate true value); -2 = sent but no echo (no datagram WKC to read); -1 = no sample (not enabled / not reached yet / slave not probeable / out of range)
PerSlaveWkcProbe_GetSampleAgeMs(mi, si)intread-only>=0 = milliseconds since the most recent sample; -1 = never sampled

Mode values:

ValueNameMeaning
0OFFDefault; no probe frames are sent
1PROBE_READEnables the per-slave read probe

The sentinel semantics are honest: -1 / -2 always mean 「unreadable / unknown」 and must not be folded into 0 for display; 0 is a legitimate true value, so when judging 0 you must explicitly distinguish 「true 0」 from 「negative sentinel」. When the runtime is not ready the sentinel is returned as well; an older runtime without these exports degrades to the sentinel too — no crash, no pretence.

Example:

PerSlaveWkcProbe_SetMode(master, 1);          /* 1 = PROBE_READ */

uint16_t mode = PerSlaveWkcProbe_GetMode(master);
if (mode == (uint16_t)-1) {
printf("探针不可用(运行环境未就绪)\n"); /* All 1s = unknown, not OFF*/
} else if (mode == 1) {
for (uint16_t si = 1; si < slave_count + 1; si++) {
int act = PerSlaveWkcProbe_GetActualWkc(master, si);
if (act >= 0) {
printf("从站 %u 探针 WKC=%d, 样本 %d ms 前\n", si, act, /* Slave %u probe WKC=%d, sample from %d ms ago */
PerSlaveWkcProbe_GetSampleAgeMs(master, si));
} else if (act == -2) {
printf("从站 %u 已发无回声\n", si); /* Slave %u was sent but produced no echo */
} else {
printf("从站 %u 无样本(未轮到 / 不可探)\n", si); /* -1 */
}
}
}

Read-only internal views​

Three entry points return borrowed pointers to storage inside the runtime ([所有权: 只读借用]): they do not need to be released and must not be written.

CategoryFunctionReturn typeRead/writeDescription
Read-only internal viewsGetDiagnosticsPointer(mi)const void*read-onlyPointer to the internal diagnostics block; no release needed
GetSummaryPointer(mi)const void*read-onlyPointer to the internal summary block; no release needed
GetMasterStateCache(mi)void*read-onlyPointer to the thread-local master state cache; no release needed

GetDiagnosticsPointer() reads live diagnostic data, provided that diagnostic collection is on: the recommended flow in the header is to call SetDiagnosticsEnabled(master, TRUE) first and then read the pointer periodically (or use GetCommunicationStats() / ec_perf_export_csv() instead).

GetSummaryPointer() and the typed GetDiagnosticsSummaryMirror() are two views of the same storage: the former gives a const void*, the latter turns the same pointer into a read-only ec_diagnostics_summary_mirror_t* view with zero-copy. For field-level reads of the summary, use GetDiagnosticsSummaryMirror() directly rather than dereferencing by offset yourself.

Returning NULL means the master has been released / is not initialized / the runtime does not provide that summary. Lifetime: the pointer is stable for the lifetime of the master (GetMasterStateCache() is a thread-local cache), the fields are refreshed by the runtime itself, and the caller must not write to them or release them. When reading across threads, treat each field as an independent snapshot — the runtime does not guarantee that the whole block is atomic while refreshing, and fields are not required to be strictly from the same cycle.

The header does not give the field layout of these three void* values: for field-level consistent reads use the typed entry points (GetDiagnosticsSummaryMirror() for the summary, GetDiagnosticsSnapshot() for the snapshot). GetMasterState() / GetMasterStateCache() are also the underlying pointer entry points for config_get_* / config_set_*; applications should call config_* directly instead of dereferencing themselves (see Configuration).

Example:

const ec_diagnostics_summary_mirror_t* sum = GetDiagnosticsSummaryMirror(master);
if (sum) {
printf("5 秒窗口错误 %u, 每千次循环错误率 %.3f\n", /* 5-second window errors %u, error rate %.3f per thousand cycles */
sum->total_errors, sum->error_rate_per_1000);
} else {
printf("摘要不可用(主站未初始化或已释放)\n"); /* Summary unavailable (master not initialized or already released) */
}

const void* raw = GetSummaryPointer(master); /* Same storage as the pointer above*/
printf("摘要块地址 %p\n", raw); /* Borrowed read-only, do not free it*/

Cyclic sampling and snapshots​

These three are the low-level write entry points the runtime itself uses inside the PDO cycle, and belong to the "diagnostic data collection" group in the header.

CategoryFunctionReturn typeRead/writeDescription
Cyclic writesRecordPDOCycleStart(mi)voidwrite-onlyMarks the start of one PDO cycle, used by the runtime to account for cycle and frequency
RecordWKC(mi, wkc)voidwrite-onlyRecords the WKC measured this cycle into the diagnostic statistics
UpdateDiagnosticsSnapshot(mi)voidwrite-onlySettles the accumulated statistics into the internal summary snapshot

Ordinary applications do not need to call them directly: turn on SetDiagnosticsEnabled(master, TRUE) and read GetDiagnosticsSnapshot() / the summary, with the accounting cadence owned by the runtime. Inserting these calls by hand is not normal application usage.

RecordCycleTime() is not part of the public interface: master/diagnostics.h says so explicitly. Historical comments in other headers may still mention it, but the C public surface does not provide that entry point; do not call it because an old comment says so.

Export and struct self-check​

CategoryFunctionReturn typeRead/writeDescription
Exportec_perf_export_csv(mi, filepath)intwrite-onlyExports the performance statistics as CSV to filepath. It returns int, and the header makes no further stipulation about the values; judge success by the file that was produced
Struct self-checkDumpSlaveStructOffsets()voidread-onlyDebug use: prints the byte offset of each field in the slave structure to check that the layout / alignment of this layer matches the runtime. No parameters, no return value, does not change master state

Example:

ec_perf_export_csv(master, "ecat_perf.csv");
/* The header does not define the return value semantics: just confirm whether the file was created*/
FILE* f = fopen("ecat_perf.csv", "rb");
if (f) {
printf("性能统计已导出\n"); /* Performance statistics exported */
fclose(f);
} else {
printf("导出文件未生成, 检查路径与写权限\n"); /* Export file not created, check the path and the write permission */
}
DumpSlaveStructOffsets();   /* Call only when troubleshooting struct alignment / ABI mismatches*/