Slave diagnostics
Each slave provides its own diagnostic properties and methods for querying port errors, redundancy, DC synchronization and so on.
Prefer driving exception handling from events (such as SlaveStateChanged, SlaveOffline, DCSyncLost) rather than polling. Reading slave diagnostic properties directly suits scenarios such as UI display.
Feature overview
| Feature | Access | Description |
|---|---|---|
| WKC and health mirror | dm::slave_wc_contributed(mi, si) / slave.MailboxHealth() and so on | Per-slave WKC/AL/mailbox health low-level diagnostic mirror (WKC and mailbox are real-time direct reads; the AL mirror is a cache sampled while the master is in OP) |
| Communication diagnostics | slave_stats::read_port_errors(dll, mi, si) | ESC port error counters (free function) |
| Redundancy diagnostics | slave.RedundancyActivated() / PrimaryLinkBroken() / SecondaryLinkBroken() | Redundancy activation, primary/redundant line break detection |
| DC synchronization | slave.IsInSync() / SyncTimeDifference() / GetSyncWindowStatus() | Sync state, time difference, out-of-sync count |
| Topology information | slave.ActivePorts() / ParentStation() | Port connections and parent node (note: ParentStation is actually a 1-based slave index, not a station address; 0 means the parent node is the master) |
| Link quality | slave_stats::get_slave_link_quality(dll, mi, si) | Slave link quality (free function) |
The WKC/health mirror, redundancy and DC properties are "always-on" (always active) and do not require enabling master.GetDiagnostics().Enabled.
slave_stats::read_port_errors() reads the slave in real time; do not call it at high frequency.
WKC and health mirror
The per-slave WKC contribution / AL status mirror is provided by the darra::ethercat::diag_mirror
namespace in the header slave/diag_mirror.hpp (free functions, not Slave members); mailbox health is a
Slave member method. The WKC contribution and mailbox health are real-time direct reads of the low-level per-slave
diagnostic cache — the runtime maintains the cache every cycle (immediately on a WKC exception), so
what you read is the true bus reality at that moment, with no refresh needed.
dm::slave_al_status_mirror() is the exception: this value is a cache refreshed by the master only while it is in OP; it is not the live truth at read time. When the master is not currently in OP (or no sample has been taken yet) the getter returns 0 = not sampled / unknown; only a value other than 0 is a trustworthy sample. Once the master leaves OP the sampler stops and the cache keeps its last sample, so this property no longer claims realtime behaviour.
Together with the master-level dm::wc_deficit(mi) it can pinpoint the specific slave when one drops out.
#include "slave/diag_mirror.hpp"
namespace dm = darra::ethercat::diag_mirror;
dm::slave_wc_contributed() — slave WKC contribution
dm::WcContribution dm::slave_wc_contributed(uint16_t mi, uint16_t si);
This slave's contribution status to the Working Counter (WKC). Observability convention: NotContributed is not a master fault;
it means the slave is not responding at this moment (suspected dropout / hot-plug recovery in progress). After repair it returns to Contributed automatically. When the low-level diagnostic mirror is not populated it honestly returns
Unknown (0xFF) instead of making something up.
enum class dm::WcContribution : uint8_t {
NotContributed = 0, // This slave is not responding right now (lost / Hot-plug in progress) - exposed honestly, not an error-handling failure
Contributed = 1, // This slave is contributing WKC normally right now
Unknown = 0xFF // Underlying cache unknown (not mapped / not refreshed) - exposed honestly, never guessed
};
dm::slave_al_status_mirror() — slave AL status mirror
dm::AlStatusMirror dm::slave_al_status_mirror(uint16_t mi, uint16_t si);
Returns the parsed structure of the low-level 16-bit AL mirror. When raw == 0, known == false, meaning no sample has been taken yet / the master is not currently in OP; the state is not guessed.
This value is a cache refreshed by the master only while it is in OP; it is not the live truth at read time. When the master is not currently in OP (or no sample has been taken yet) the getter returns 0 = not sampled / unknown; only a value other than 0 is a trustworthy sample. Once the master leaves OP the sampler stops and the cache keeps its last sample, so this property no longer claims realtime behaviour.
struct dm::AlStatusMirror {
uint16_t raw; // Raw 16-bit mirror (0 = unknown / not refreshed)
uint8_t state; // AL State low 4 bits (1/2/4/8 = INIT/PREOP/SAFEOP/OP)
bool error; // AL Status Error bit (bit4)
uint8_t code; // low 8 bits of the AL Status Code (valid only when error is set; codes >= 0x0100 are truncated)
bool known; // true when raw != 0; false = the underlying layer has no mirror of that slave yet
bool is_op() const; // Whether AL State is OP
bool is_safeop() const; // Whether in SAFEOP
bool is_preop() const; // Whether in PREOP
bool is_init() const; // Whether in INIT
};
Example:
#include "slave/diag_mirror.hpp"
namespace dm = darra::ethercat::diag_mirror;
uint16_t mi = master.MasterNumber();
for (int si = 1; si <= master.SlaveCount(); ++si) {
// WKC contribution: lost-slave localisation
if (dm::slave_wc_contributed(mi, si) == dm::WcContribution::NotContributed)
printf("从站 %d 本周期未贡献 WKC, 疑似掉站\n", si); // Slave %d contributed no WKC this cycle, suspected slave loss\n
// AL state mirror
auto al = dm::slave_al_status_mirror(mi, si);
if (al.known && al.error)
printf("从站 %d AL 错误: state=0x%X code=0x%02X\n", si, al.state, al.code); // Slave %d AL error: state=0x%X code=0x%02X\n
}
Reading ESC port errors is provided by free functions in the darra::ethercat::slave_stats
namespace, which explicitly take dll_t& / master index / slave index parameters.
Redundancy / DC diagnostics (RedundancyActivated() / IsInSync() / GetSyncWindowStatus() and so on) are the Slave member methods.
Communication diagnostics
slave_stats::read_port_errors()
namespace darra::ethercat::slave_stats {
std::optional<EscPortErrors> read_port_errors(dll_t& dll, uint16_t mi, uint16_t si);
}
Read the slave ESC port error counters; returns the physical-layer error statistics for each port. This is a free function in the darra::ethercat::slave_stats
namespace and explicitly takes a DLL reference, master index and slave index.
Parameters:
dll(dll_t&) — DLL reference (obtained throughmaster.Dll())mi(uint16_t) — master index (master.MasterNumber())si(uint16_t) — slave index (1-based)
Return value:
std::optional<EscPortErrors>— port error counters; returnsstd::nulloptwhen the read fails
Related structures (EscPortErrors is in slave/slave_stats.hpp, SyncWindowStatus is in slave/dc.hpp):
struct EscPortErrors {
uint8_t rx_error[4]; // Per-port RX error counter (0x0300-0x0303)
uint8_t invalid_frame[4]; // Per-port invalid frame counter (0x0304-0x0307)
uint8_t lost_link[4]; // Per-port lost link counter (0x0310-0x0313)
uint8_t fwd_rx_error[4]; // Per-port forwarding RX error counter (0x0308-0x030B)
bool has_errors() const; // Whether any error exists
};
struct SyncWindowStatus {
int DiffNs; // Time difference to the reference clock (nanoseconds)
int MaxDiffNs; // Maximum time difference (nanoseconds)
int MinDiffNs; // Minimum time difference (nanoseconds)
bool InSync; // Whether inside the sync window
uint32_t OutOfSyncCount; // Lost step count
};
Companion free functions (same slave_stats namespace):
namespace darra::ethercat::slave_stats {
// Batch-read the port errors of all slaves
std::vector<std::optional<EscPortErrors>>
read_all_port_errors(dll_t& dll, uint16_t mi, int slave_count);
// Reset the port error counters
bool reset_port_errors(dll_t& dll, uint16_t mi, uint16_t si);
int reset_all_port_errors(dll_t& dll, uint16_t mi, int slave_count);
// Link quality assessment
LinkQuality get_slave_link_quality(dll_t& dll, uint16_t mi, uint16_t si);
std::vector<LinkQuality>
get_all_slave_link_quality(dll_t& dll, uint16_t mi, int slave_count);
}
Example:
using namespace darra::ethercat;
dll_t& dll = master.Dll();
uint16_t mi = master.MasterNumber();
for (int i = 1; i <= master.SlaveCount(); ++i) {
auto errors = slave_stats::read_port_errors(dll, mi, static_cast<uint16_t>(i));
if (errors && errors->has_errors()) {
printf("从站 %d: RX=[%d,%d,%d,%d] 无效帧=[%d,%d,%d,%d] 链路丢失=[%d,%d,%d,%d]\n", i, // Slave %d: RX=[%d,%d,%d,%d] invalid frames=[%d,%d,%d,%d] lost links=[%d,%d,%d,%d]\n
errors->rx_error[0], errors->rx_error[1], errors->rx_error[2], errors->rx_error[3],
errors->invalid_frame[0], errors->invalid_frame[1], errors->invalid_frame[2], errors->invalid_frame[3],
errors->lost_link[0], errors->lost_link[1], errors->lost_link[2], errors->lost_link[3]);
}
}
Redundancy diagnostics
Access redundancy state through the slave object. Only meaningful when redundancy is enabled on the master. RedundancyActivated() means redundancy protection is running = the master-level RingMode is DUAL / DEGRADED; for a line / end foldback topology it is always false, so it is not a per-slave conclusion. PrimaryLinkBroken() / SecondaryLinkBroken() mean there is a break (a LinkDown break point) on the primary/secondary port path. CRC faults do not trigger these flags.
Example:
for (int i = 1; i <= master.SlaveCount(); ++i) {
auto& s = master.GetSlave(i);
if (!s.RedundancyActivated()) continue;
printf("从站 %d: 冗余激活", i); // Slave %d: redundancy active
if (s.PrimaryLinkBroken()) printf(", 主线路断路"); // , primary link broken
if (s.SecondaryLinkBroken()) printf(", 冗余线路断路"); // , redundancy link broken
printf("\n");
}
DC synchronization
Access DC synchronization state through the slave object. IsInSync(int thresholdNs = 1000) returns whether the slave can be treated as synchronized (SYNC0 is armed and the runtime sync window judges it inside the window; the only authority for the threshold is the runtime — thresholdNs is kept for source compatibility only and does not participate in the judgment; to change the threshold use the thresholdNs parameter of SlaveDC::IsAllSlavesInSync: when > 0 it writes the threshold first and then judges, when <= 0 it keeps the current threshold); SyncTimeDifference() returns the nanosecond time difference from the reference clock (std::optional<int>; std::nullopt when there is no DC or the read fails, not folded into 0); GetSyncWindowStatus() returns the complete SyncWindowStatus structure.
The reference clock itself: 0x092C (time difference) is N/A for it by definition; the low level no longer synthesizes an in-sync value. When this station is the reference clock and SYNC0 is armed,
IsInSync()/TryIsInSync()returntrue— the reference clock cannot be out of sync with itself, and this is the only conclusion that can be drawn (non-reference clocks still go through the runtime sync window criteria). The value only means "can be treated as synchronized"; it does not mean there is a measured deviation, and it does not mean the whole network clock has converged;GetSyncWindowStatus()still returns the raw runtime window values.
Example:
for (int i = 1; i <= master.SlaveCount(); ++i) {
auto& s = master.GetSlave(i);
if (!s.HasDC()) continue;
auto status = s.GetSyncWindowStatus();
if (status) {
printf("从站 %d: 时间差=%dns 最大=%dns 同步=%s 失步=%u\n", i, // Slave %d: time diff=%dns max=%dns synced=%s out-of-sync=%u\n
status->DiffNs, status->MaxDiffNs,
status->InSync ? "是" : "否", status->OutOfSyncCount);
}
}
Full example
#include "ethercat.hpp"
using namespace darra::ethercat;
void slave_diagnostics_report(EtherCATMaster& master) {
auto& diag = master.GetDiagnostics();
dll_t& dll = master.Dll();
uint16_t mi = master.MasterNumber();
for (int i = 1; i <= master.SlaveCount(); ++i) {
auto& s = master.GetSlave(i);
printf("--- 从站 %d: %s ---\n", i, s.Name().c_str()); // --- slave %d: %s ---\n
// Port errors come from the slave_stats free function, not a Slave member method
auto errors = slave_stats::read_port_errors(dll, mi, static_cast<uint16_t>(i));
if (errors && errors->has_errors()) {
printf(" 端口错误: RX=[%d,%d,%d,%d]\n", // port errors: RX=[%d,%d,%d,%d]\n
errors->rx_error[0], errors->rx_error[1],
errors->rx_error[2], errors->rx_error[3]);
}
if (s.RedundancyActivated()) {
printf(" 冗余激活: 主线路断=%s 冗余线路断=%s\n", // redundancy active: primary link broken=%s redundancy link broken=%s\n
s.PrimaryLinkBroken() ? "是" : "否",
s.SecondaryLinkBroken() ? "是" : "否");
}
if (s.HasDC()) {
auto sync = s.GetSyncWindowStatus();
if (sync) {
printf(" DC: 时间差=%dns 同步=%s 失步=%u\n", // DC: time diff=%dns synced=%s out-of-sync=%u\n
sync->DiffNs, sync->InSync ? "是" : "否",
sync->OutOfSyncCount);
}
}
// Note: ParentStation is really a 1-based slave index, not a station address; 0 means the parent is the master
printf(" 活动端口=0x%02X 父节点=%u 链路质量=%d\n", // active port=0x%02X parent=%u link quality=%d\n
s.ActivePorts(), s.ParentStation(), diag.SlaveLinkQuality(i));
}
}
Mailbox health observability (new in 2.5.x)
Slave-level mailbox health observation under the reliability rules — making the half-failed state "the slave is still in OP but the mailbox channel is half-failed (CoE/SDO may block)"
visible to upper layers. All of it is a real-time direct read, reflecting reality honestly, and does not participate in WKC tampering. These four are Slave member methods.
class Slave {
public:
// Mailbox health: Unknown / Healthy / Degraded
// Degraded = in OP but the mailbox is half dead (handler lost / DC degraded with 0x001F)
ethercat::slave_stats::MailboxHealth MailboxHealth() const;
// Whether it was forced down to FreeRun synchronisation (DC requested at configuration but backed off to FreeRun at runtime)
bool IsFreeRunDemoted() const;
// Consecutive half-dead mailbox count (roughly seconds); 0 = healthy or not assessed
uint32_t HealthDegradedCount() const;
// Manually trigger the half-dead mailbox repair (the runtime usually repairs it automatically, so this normally does not need calling)
bool RecoverMailboxHealth() const;
};
Related enum:
namespace darra::ethercat::slave_stats {
enum class MailboxHealth : uint8_t {
Unknown = 0, // Unknown / no mailbox / not in OP - mailbox health is meaningless right now
Healthy = 1, // Healthy - in OP and the mailbox is available
Degraded = 2 // Degraded - in OP but the mailbox is half dead
};
}
Example:
using darra::ethercat::slave_stats::MailboxHealth;
for (int i = 1; i <= master.SlaveCount(); ++i) {
auto& s = master.GetSlave(i);
if (s.MailboxHealth() == MailboxHealth::Degraded) {
printf("从站 %d 邮箱半失效已 %u 秒 — 仍在 OP, WKC 未篡改\n", // Slave %d mailbox has been half-failing for %u s — still in OP, WKC left untampered\n
i, s.HealthDegradedCount());
// Normally no manual call is needed; the runtime repairs it automatically after detecting the half-dead state for a few seconds
s.RecoverMailboxHealth();
}
if (s.IsFreeRunDemoted())
printf("从站 %d 被迫从 DC 降级到 FreeRun\n", i); // Slave %d forced to degrade from DC to FreeRun\n
}
The C++ SDK currently does not provide a separate wrapper for the GetSlaveStateLive / GetSlaveALStatusCodeLive real-time read entries.
For the slave's current state and AL error code use Slave::State() / Slave::ErrorCode() / Slave::GetALStatusCode() directly; these read the cached view, not the live truth at read time. When a forced true-value read is needed, use Slave::StateLive() / Slave::ALStatusCodeLive().
Topology foldback (P1)
With a dual-NIC ring + branch topology, master-sent frames only travel the ring, and slaves with a station order greater than the number of stations on the ring can only be reached through the foldback window. This set of read-only queries answers three things: whether the foldback calibration ran this round, where the foldback position is, and whether a station can only be addressed through the foldback window.
The master level is on MasterDiagnosticsInfo (constructed from the Diagnostics& returned by master.GetDiagnostics()); the slave level is a Slave member method.
| Category | Method | Type or return type | Read/write | Description |
|---|---|---|---|---|
| P1 foldback (master level) | MasterDiagnosticsInfo::TopoP1Mode() | int | Read-only | Foldback requirement mode: 0 = NONE (no foldback requirement / not calibrated this round), 1 = SINGLE_NIC (single NIC, no foldback window), 2 = DUAL_RING_BRANCH (dual-NIC ring + branch, foldback required); -1 = invalid master index |
| MasterDiagnosticsInfo::TopoP1Measured() | int | Read-only | Whether the on-site topology measurement completed this round: 1 = measured, 0 = not measured, -1 = invalid master index | |
| MasterDiagnosticsInfo::TopoP1FullWkc() | int | Read-only | Full working counter measured at the foldback position; -1 = unavailable (not calibrated / not a dual-NIC ring + branch / invalid index) | |
| MasterDiagnosticsInfo::TopoMeasuredRingCount() | int | Read-only | Measured number of slaves on the ring; 0 is a valid measured value; -1 = unavailable (same as above) | |
| P1 foldback (slave level) | Slave::P1FoldbackOnly() | int | Read-only | 1 = this station is reachable only through the foldback window, and when set, positional addressing of it requires opening the foldback window first; 0 = not a branch station or not calibrated; -1 = invalid master index or station number |
-1 only means unavailable / not calibrated / invalid parameter (master index or station number out of range, master released); treat it as "cannot read", not as a measurement. Conversely 0 is a real value: TopoP1Mode() returning 0 means NONE, TopoP1Measured() returning 0 means not measured this round, TopoMeasuredRingCount() returning 0 means 0 stations measured on the ring. Folding -1 into 0 disguises "cannot read" as "indeed none".
The runtime topology in the diagnostic summary summary.topology_mode (Diagnostics::Summary(); for the text version see MasterDiagnosticsInfo::TopologyDescription()) uses 0 = line / 1 = ring / 2 = ring + branch / 3 = ring degraded to line — one value (3) more than TopoP1Mode(). The two are not the same encoding; do not cast raw values between them, and do not use the value of one to explain the other.
Example:
auto& base = master.GetDiagnostics();
MasterDiagnosticsInfo p1(base, master.MasterNumber());
int mode = p1.TopoP1Mode();
if (mode < 0) {
printf("P1 折返拓扑不可用 (主站索引非法)\n"); // P1 loopback topology unavailable (invalid master index)
} else if (mode == 2 && p1.TopoP1Measured() == 1) {
int full = p1.TopoP1FullWkc();
int ring = p1.TopoMeasuredRingCount();
printf("双 NIC 环+分支: 环上 %d 站, 折返完整 WKC %d\n", ring, full); // Dual-NIC ring + branches: %d slaves on the ring, full WKC %d when folded back\n
}
// Slave level: whether this slave is reachable only through the foldback window
for (int si = 1; si <= master.SlaveCount(); ++si) {
int foldbackOnly = master.GetSlave(si).P1FoldbackOnly();
if (foldbackOnly < 0) continue; // -1 = could not be read, which is not the same as "not a branch station"
if (foldbackOnly == 1)
printf("从站 %d 只能经折返窗口可达, 寻址前需先打开折返窗口\n", si); // Slave %d is reachable only through the fold-back window; the fold-back window must be opened before addressing it\n
}
To rescan ports, rebuild the topology graph and recompute the expected WKC per path after a hot-plug, call RefreshTopology(uint16_t master_index) from the C header (C++ calls it by the same name; ethercat.hpp already includes ethercat.h): the bus is not restarted and the PDO cycle does not stop. The entry returns void; read the rebuilt topology values for the result.