Events and callbacks
Get the MasterEvents& reference through master.Events(), and add MasterEvents& callbacks with the On*() registration methods.
Each event of MasterEvents is a multi-subscriber std::vector<std::function<...>> and cannot be assigned directly with =. You must call the matching On*() registration method (call it several times to register several callbacks). Common mappings:
| Event | Registration method | Category | Read/write |
|---|---|---|---|
| PDO cyclic callback (synchronous) | Events().SetPDOCallbackSync(cb) | Cyclic data | Write (register) |
| Master state change | Events().OnStateChanged(cb) | State machine | Write (register) |
| Slave state change | Events().OnSlaveStateChanged(cb) | State machine | Write (register) |
| Slave online / offline | Events().OnSlaveDiscovered(cb) / Events().OnSlaveLost(cb) | Hot-plug | Write (register) |
| Slave identity mismatch | Events().OnSlaveIdentityMismatch(cb) | Hot-plug | Write (register) |
| CoE Emergency | Events().OnEmergency(cb) | Mailbox | Write (register) |
| Consecutive PDO frame loss | Events().OnPDOFrameLoss(cb) | Diagnostics | Write (register) |
| DC sync lost | Events().OnDCSyncLost(cb) | DC | Write (register) |
| DC lock-loss recovery edge | Events().OnDCSyncRestored(cb) | DC | Write (register) |
| DC unified event stream | Events().OnDcEventRaised(cb) | DC | Write (register) |
| DC state event log stream | LogManager::Instance().SetLogCallback(cb) | DC | Write (register) |
| SDO read/write failure | Events().OnSdoError(cb) | Diagnostics | Write (register) |
| Group WKC shortage edge | Events().OnWkcShortageOccurred(cb) | Diagnostics | Write (register) |
| Master physical port link change | Events().OnNicLinkChanged(cb) | Diagnostics | Write (register) |
| Redundancy mode change | Events().OnRedundancyModeChanged(cb) | Redundancy | Write (register) |
| Slave port link change | Events().OnSlavePortLinkChanged(cb) | Diagnostics | Write (register) |
| Error / warning | Events().OnError(cb) / Events().OnWarning(cb) | Diagnostics | Write (register) |
| Slave PreOP reconfiguration | Events().OnSlavePreOpReconfig(cb) | State machine | Write (register) |
MasterEvents events are always subscribed through the registration methods with the On prefix; the argument is a callback and there is no field you can assign directly. The SDK owns the event containers — do not manipulate them from the application.
To start a temporary stretch of cyclic communication, use the darra::sugar::ScopedStart guard(master); RAII guard; it calls Stop() automatically when it leaves scope.
Every event (except the PDO cyclic callback and the group WKC shortage / master physical port link edges) is logged automatically when it fires, whether or not it is subscribed. Critical runtime state is never lost silently.
The PDO cyclic callback (Events().SetPDOCallbackSync()) is a high-frequency callback and is not logged. Group WKC shortage and master physical port link are edge decisions made on the SDK side and do not write logs automatically; if you need a record, log it yourself in the callback.
Feature overview
| Category | Event | Description | Auto logging |
|---|---|---|---|
| PDO cyclic callback | ProcessDataCyclicSync | PDO cyclic notification (merged into the latest one; does not carry a safety loop) | -- |
| State events | StateChanged | Master EtherCAT state change | yes |
| SlaveStateChanged | Slave EtherCAT state change | yes | |
| Hot-plug events | SlaveOffline | Slave offline (disconnected) | yes |
| SlaveOnline | Slave online (recovered) | yes | |
| SlaveOfflineDetailed | Slave offline with rich context (same tick as SlaveOffline; the payload carries the reason classification + delivery-time evidence) | yes | |
| SlaveOfflineDisputed | The offline marking contradicts the delivery-time evidence (no offline event is delivered; this event is delivered instead) | yes | |
| Hot-plug events | SlaveIdentityMismatch | Slave identity mismatch (wrong model swapped in; revision is not part of the identity check) | yes |
| Exception events | EmergencyEvent | CoE Emergency message | yes |
| PDOFrameLoss | Consecutive PDO frame loss | yes | |
| DCSyncLost | DC sync lost | yes | |
| DC state events | OnDCSyncRestored | DC lock-loss recovery edge (the payload carries the lock-loss duration; same edge as the sync window recovery event) | yes |
| OnDcEventRaised | DC arming / window / reference clock / propagation delay state events (strongly typed payload); the same event is still output through the log callback | yes | |
| Diagnostic events | OnSdoError | SDO read/write failure (not fired on success) | yes |
| OnWkcShortageOccurred | Group WKC measured < expected (fired only on entering the shortage or when the shortage value changes) | -- | |
| OnNicLinkChanged | Master physical port P1 / P2 link up/down edge | -- | |
| Redundancy events | RedundancyModeChanged | Redundancy mode change | yes |
| SlavePortLinkChanged | Slave port link change (P0-P3 down/recovered) | yes |
The following logical events have no corresponding entry point in the C++ SDK; this page does not invent APIs:
- Mailbox transaction error event: C++ has no generic mailbox transaction abstraction, so the event is not provided; diagnose mailbox-level problems with
LastCloseError/NativeStatsofMailboxGatewayService, and subscribe toOnSdoErrorfor SDO-level failures. - Placeholder-slave re-read recovery event: the C++ SDK does not expose this refresh event.
The registration entry points OnError(cb) (ErrorCallback) and OnWarning(cb) (WarningCallback) exist, but the trigger entry points TriggerError / TriggerWarning have no caller in the public headers — subscribing to these two slots currently yields no events. For error / warning text use the log channel: LogManager::Instance().SetLogCallback() / SetLogEntryCallback(), or switch to OnSdoError / OnWkcShortageOccurred / OnNicLinkChanged according to semantics.
PDO cyclic callback
ProcessDataCyclicSync
using ProcessDataCyclicCallback = std::function<void(uint16_t masterIndex)>;
PDO process data is sent and received by the runtime in real time. The recommended path is to map InputsMapping / OutputsMapping once after entering OP, so the references point straight at the real-time process image and any callback or thread can read the fields directly. CopyInputFrame / WriteOutputFrame are the snapshot alternatives. SetPDOCallbackSync is a cyclic notification only: the SDK delivers it on a separate thread, new cycles during a slow callback are merged into the latest one, and it must not carry FSoE / same-cycle safety loops.
The asynchronous cyclic callback (the old ProcessDataCyclicAsync) has been removed.
One notification is published per PDO cycle (synchronous mode). The user callback runs on a separate thread, not on the PDO real-time thread; new cycles during a slow callback are merged into the latest one (no unbounded queue is built), and bus send/receive is not blocked.
Register with SetPDOCallbackSync().
Whether the subscription was really established is decided by PdoSubscribeFailed() / PdoSubscribeFailureCount() (sticky): a failure means the registration did not succeed and the application layer receives no cyclic notification — do not read "no callback" as "the bus has no cyclic events". The failure count for stopping delivery in RemoveAll() is reported separately by PdoStopFailureCount().
The example below shows the PDO write only. 0x000F may only be held after 0x06→0x07→0x0F has completed and (statusWord & 0x6F) == 0x27; when not enabled / faulted / NotReady, write 0x0006 with target = actual. Do not write 0x001F in CSP; with multiple axes, issue per axis in the same callback. See CiA 402 for the complete state machine.
Example (direct zero-copy mapping, mapped only once outside the callback):
const InPdo& inputs = darra::SlavePDO::InputsMapping<InPdo>(
dll, master.MasterNumber(), 1);
OutPdo& outputs = darra::SlavePDO::OutputsMapping<OutPdo>(
dll, master.MasterNumber(), 1);
master.Events().SetPDOCallbackSync([&](uint16_t /*mi*/) {
outputs.controlWord = 0x000F;
outputs.targetPosition = inputs.actualPosition;
});
Snapshot alternative (copy every tick; the copied struct does not change by itself):
master.Events().SetPDOCallbackSync([&](uint16_t /*mi*/) {
std::vector<uint8_t> inFrame;
darra::SlavePDO::CopyInputFrame(dll, master.MasterNumber(), 1, inFrame);
});
The callback runs on a separate thread and not on the PDO real-time thread: time-consuming work does not block bus send/receive (new cycles are merged into the latest one), but it skips the intermediate cycles. If every cycle must be processed without gaps, keep the callback within one cycle interval.
State events
StateChanged
std::function<void(EcState oldState, EcState newState)>
Fires when the master's EtherCAT state changes (including deliberate switches and fault degradation). Always logged automatically.
Register with OnStateChanged() (master.OnStateChanged() also works).
Example:
master.Events().OnStateChanged([](EcState oldS, EcState newS) {
printf("主站状态: %s -> %s\n", // Master state: %s -> %s
EcStateFormat::Format(oldS).c_str(),
EcStateFormat::Format(newS).c_str());
});
SlaveStateChanged
using SlaveStateChangeCallback = std::function<void(
uint16_t masterIndex, uint16_t slaveIndex,
EcState oldState, EcState newState)>;
Fires when a slave's EtherCAT state changes (including deliberate switches and fault degradation). Register with OnSlaveStateChanged().
Example:
master.Events().OnSlaveStateChanged([](uint16_t mi, uint16_t si,
EcState oldS, EcState newS) {
printf("从站 %d 状态: %s -> %s\n", si, // Slave %d state: %s -> %s
EcStateFormat::Format(oldS).c_str(),
EcStateFormat::Format(newS).c_str());
});
Slave online/offline events
SlaveOnline / SlaveOffline
using SlaveOnlineCallback = std::function<void(uint16_t slaveIndex)>;
using SlaveOfflineCallback = std::function<void(uint16_t slaveIndex)>;
Fires when a slave comes online or goes offline. Register with OnSlaveDiscovered() (online) / OnSlaveLost() (offline) respectively.
Example:
master.Events().OnSlaveDiscovered([](uint16_t si) {
printf("从站 %d 上线\n", si); // Slave %d online
});
master.Events().OnSlaveLost([](uint16_t si) {
printf("从站 %d 离线!\n", si); // Slave %d offline!
});
SlaveOfflineDetailed
using SlaveOfflineDetailedCallback = std::function<void(const SlaveOfflineEventArgs&)>;
The rich-context event for a normal offline, delivered on the same tick as OnSlaveLost(); the payload type is the same as SlaveOfflineDisputed (SlaveOfflineEventArgs), and the event name distinguishes the semantics: this event is delivered only when the offline has already been announced (real offline / unknown), while a case where the evidence contradicts offline delivers only OnSlaveOfflineDisputed(). Register with OnSlaveOfflineDetailed(cb).
Payload (SlaveOfflineEventArgs):
| Field | Type | Description |
|---|---|---|
master_index | uint16_t | Master index |
slave_index | uint16_t | Slave index (1-based) |
timestamp_utc | std::chrono::system_clock::time_point | Event time (UTC); also the time the evidence was read |
reason | SlaveOfflineReason | Offline reason classification (Unknown / RealOffline / Unreachable) |
probe | SlaveProbeState | Measured three-state probe result at delivery time |
contribution | diag_mirror::WcContribution | Process data contribution three-state at delivery time |
- Delivered twice from the same decision and the same moment as
OnSlaveLost(); it is not a second decision path. probe/contributionare evidence read at delivery time (the probe uses a ≤2.52s response window, the contribution is this cycle's image), not the evidence from the tick where the service side made its decision; logs and UI must not call them "same-tick evidence".- When the evidence contradicts offline (process data is confirmed still contributing,
reason == Unreachable), this event is not delivered andOnSlaveOfflineDisputed()is delivered instead; the two events are mutually exclusive, so subscribe to one or both as needed.
master.Events().OnSlaveOfflineDetailed([](const darra::SlaveOfflineEventArgs& e) {
printf("从站 %u 离线: 原因=%d 探针=%d PD贡献=%d\n", // Slave %u offline: reason=%d probe=%d PD contribution=%d
e.slave_index, static_cast<int>(e.reason), static_cast<int>(e.probe),
static_cast<int>(e.contribution));
});
Offline events and evidence consistency (SlaveOfflineDisputed)
When a slave is judged lost, the SDK does not publish "offline" straight away; it first reads two pieces of delivery-time evidence and then classifies the case. The classification result is SlaveOfflineReason.
Related structure:
enum class SlaveOfflineReason : uint8_t {
Unknown = 0, // Insufficient evidence -- never fabricate a truly-offline verdict
RealOffline = 1, // Truly offline -- the process data proves it is not contributing, or the probe proves it is lost
Unreachable = 2 // Not confirmed by the server -- the server/probe did not see it, but the process data proves it is still contributing
};
Evidence one: the measured three-state probe result SlaveProbeState (a real-response window of ≤2.52s):
enum class SlaveProbeState : uint8_t {
NotResponding = 0, // Probe measured lost (no reply for N consecutive windows)
Responding = 1, // Probe measured a reply (positive evidence of being online)
Unknown = 2 // Insufficient evidence (entry point unavailable / not measured / read failed)
};
Evidence two: the process data contribution darra::ethercat::diag_mirror::WcContribution (this cycle's snapshot; other pages on this site abbreviate it as dm::WcContribution with namespace dm = darra::ethercat::diag_mirror;). Contributed = confirmed to be contributing WKC this cycle; NotContributed = confirmed not contributing; Unknown = no valid value has been obtained yet, so it is unknown.
The classification rules are just these three; do not implement a second set on the application side:
- Process data confirmed contributing →
Unreachable - Process data confirmed not contributing →
RealOffline - When the contribution is unknown: probe confirmed loss →
RealOffline, otherwise →Unknown
When the service side has already judged the slave lost but the delivery-time evidence contradicts offline (process data is confirmed still contributing), the SDK does not deliver the offline callback registered with OnSlaveLost(), nor the slave-level SlaveEvents::OnOffline; it delivers OnSlaveOfflineDisputed() instead.
master.Events().OnSlaveOfflineDisputed([](const darra::SlaveOfflineEventArgs& e) { ... });
Callback parameters (SlaveOfflineEventArgs):
struct SlaveOfflineEventArgs {
uint16_t master_index; // Master index
uint16_t slave_index; // Slave index (1-based)
std::chrono::system_clock::time_point timestamp_utc; // Event time, also the moment the evidence was read
SlaveOfflineReason reason; // Offline reason classification
SlaveProbeState probe; // Tri-state of the probe measurement at delivery time
darra::ethercat::diag_mirror::WcContribution contribution; // Process data contribution at delivery time
};
Consumers use it to report "suspected brief interruption / the offline marking does not match the evidence". Do not turn a status red or stop the line based on it; a real offline still goes through OnSlaveLost().
reason / probe / contribution are all read at event delivery time: the probe is the result of a real-response window of ≤2.52s, and the contribution is this cycle's image. The probe/contribution evidence from the tick where the service side made its decision is not part of the current ABI (the discovery callback only carries master/slave/is_found). They are not the same tick; do not write "same-tick evidence" in logs or on screen.
Deduplication and deferred delivery:
- The registration is one
{原因, 是否已公告离线}entry per slave; each slave announces offline only once, until it comes online. - If the first announcement was withheld because the evidence contradicted offline and later evidence no longer contradicts it → deliver the real offline event once, so a genuine loss is not swallowed by the old registration.
- An announced registration only refines the reason (
Unknown→ explicit classification, one-way); the event is not delivered again. - On coming online, if no offline was ever announced for this cycle,
OnSlaveDiscovered()is not delivered (online and offline stay strictly paired).
Reason lookup:
bool TryGetSlaveOfflineReason(uint16_t slaveIndex, SlaveOfflineReason& reason) const;
std::unordered_map<uint16_t, SlaveOfflineReason> GetSlaveOfflineReasons() const;
TryGetSlaveOfflineReason lets a UI that started after the offline event, or re-subscribed midway, fetch the reason classification (it returns false when nothing is registered); GetSlaveOfflineReasons returns a read-only snapshot of every registration at once. Registered ≠ announced offline — when the evidence contradicts offline, only the reason is registered and only OnSlaveOfflineDisputed is delivered; IsSlaveOffline() and the lost-slave count keep their existing meaning.
Example:
master.Events().OnSlaveOfflineDisputed([](const darra::SlaveOfflineEventArgs& e) {
printf("从站 %d 掉站标记与证据不符 (探针=%d, PD贡献=%d)\n", // Slave %d slave-loss marker contradicts the evidence (probe=%d, PD contribution=%d)
e.slave_index, static_cast<int>(e.probe),
static_cast<int>(e.contribution));
// Report only "suspected brief interruption"; do not fail the test or stop the line
});
darra::SlaveOfflineReason reason;
if (master.Events().TryGetSlaveOfflineReason(2, reason)
&& reason == darra::SlaveOfflineReason::RealOffline) {
printf("从站 2 确证离线\n"); // Slave 2 confirmed offline
}
IsSlaveOffline()
bool IsSlaveOffline(uint16_t slaveIndex) const;
Queries whether the event system has confirmed the slave as offline.
Parameters:
slaveIndex(uint16_t) -- slave index
Returns:
bool--truewhen the slave is offline
Example:
if (master.Events().IsSlaveOffline(2)) {
printf("从站 2 处于离线状态\n"); // Slave 2 is offline
}
SlaveIdentityMismatch
using SlaveIdentityMismatchCallback = std::function<void(
uint16_t masterIndex, uint16_t slaveIndex,
uint32_t expectedVendor, uint32_t expectedProduct, uint32_t expectedRevision,
uint32_t actualVendor, uint32_t actualProduct, uint32_t actualRevision)>;
Fires when the identity does not match after a slave is powered off and plugged back in: the Vendor / Product read by the identification state machine does not match the configuration. The Revision does not participate in rejection and is kept only for logging and troubleshooting: the matching rule is decided by master.GetConfig().ScanRevisionMatch(), which defaults to ScanRevisionMatchMode::IgnoreRevision and compares Vendor + Product only — if those two match, the device is taken to be the same one. ScanRevisionMatchMode also defines the optional Exact (the revision numbers must be identical) and CompatibleHigher (the measured revision must be at least the configured declared value) modes, but this SDK cannot currently send them down to scanning: setting them on the config object returns false and logs a warning, and setting them at the scan or streaming-builder entry raises an error. When strict revision checking is required, read slave.RevId() at the application layer and compare it yourself. Always logged automatically.
After it fires the slave enters the IDENT_REJECTED state and is not re-probed automatically (so a wrong device cannot flood the log). After the operator checks / replaces the device, call acknowledge_slave_replacement to make the SDK probe again.
Callback parameters:
masterIndex(uint16_t) — master indexslaveIndex(uint16_t) — slave index (1-based)expectedVendor(uint32_t) — vendor ID expected by the configurationexpectedProduct(uint32_t) — product code expected by the configurationexpectedRevision(uint32_t) — the revision expected by the configuration (reference only; not part of the identity check)actualVendor(uint32_t) — current actual vendor IDactualProduct(uint32_t) — current actual product codeactualRevision(uint32_t) — current actual revision number
Example:
master.Events().OnSlaveIdentityMismatch(
[&](uint16_t mi, uint16_t si,
uint32_t eV, uint32_t eP, uint32_t eR,
uint32_t aV, uint32_t aP, uint32_t aR) {
printf("从站 %u 身份不符:\n", si); // Slave %u identity mismatch:
printf(" 期望: V=0x%08X P=0x%08X R>=0x%08X\n", eV, eP, eR); // Expected: V=0x%08X P=0x%08X R>=0x%08X
printf(" 实际: V=0x%08X P=0x%08X R=0x%08X\n", aV, aP, aR); // Actual: V=0x%08X P=0x%08X R=0x%08X\n
// Prompt the user to put the correct device back, then call on confirm:
// master_other::acknowledge_slave_replacement(master, si);
});
A slave entering the IDENT_REJECTED state fires the event only once. Calling acknowledge_slave_replacement resets the probe; if the identity still does not match, the event fires again.
acknowledge_slave_replacement()
namespace darra { namespace ethercat { namespace master_other {
bool acknowledge_slave_replacement(EtherCATMaster& m, uint16_t slaveIndex);
} } }
Call it after the operator has checked / replaced the slave, so the SDK resets the identification state machine and probes the slave again. Used together with the SlaveIdentityMismatch event.
Parameters:
m(EtherCATMaster&) — master referenceslaveIndex(uint16_t) — slave index (1-based)
Returns:
bool—true= accepted and the FSM was reset;false= the slave is not in theIDENT_REJECTED/FAILEDstate, or the parameter is invalid
Behavior:
- Identity corrected (the correct device is back / the same model with an upgraded Revision) → automatic recovery, and
SlaveOnlinefires - Identity still does not match →
SlaveIdentityMismatchfires again and the slave returns toIDENT_REJECTED
Calling this function before SlaveIdentityMismatch has fired has no effect and returns false.
Example:
using namespace darra::ethercat;
master.Events().OnSlaveIdentityMismatch(
[&](uint16_t mi, uint16_t si,
uint32_t eV, uint32_t eP, uint32_t eR,
uint32_t aV, uint32_t aP, uint32_t aR) {
printf("从站 %u 身份不符\n", si); // Slave %u identity mismatch\n
if (ShowReplacementDialog(si)) {
bool ok = master_other::acknowledge_slave_replacement(master, si);
if (!ok) printf("确认失败: 从站不在 IDENT_REJECTED 状态\n"); // Acknowledgement failed: the slave is not in the IDENT_REJECTED state
}
});
Emergency message events
The cycle is set by DENI/LoopCycle and can be as short as 125 µs; it is not hard-coded to 1ms. RTcnt() should match 1e9/LoopCycleNs. A sustained deviation of ±20% from the configured value, or a max jitter above 25% of the cycle time, must be logged and alarmed in the UI. Check PDOFrameLoss and DCSyncLost at the same time. When isolation is not in effect only the jitter may grow; a cycle that drifts away without an alarm is not acceptable. Do not do alarm I/O on the PDO hot path.
EmergencyEvent
using EmergencyEventCallback = std::function<void(
uint16_t masterIndex, uint16_t slaveIndex,
uint16_t errorCode, uint16_t errorReg,
uint8_t b1, uint16_t w1, uint16_t w2)>;
CoE Emergency message event. The data format follows the CANopen Emergency protocol (CiA 301). Register with OnEmergency().
Example:
master.Events().OnEmergency([](uint16_t mi, uint16_t si,
uint16_t code, uint16_t reg,
uint8_t b1, uint16_t w1, uint16_t w2) {
printf("从站 %d 紧急消息: 错误码=0x%04X, 寄存器=0x%04X\n", // Slave %d emergency message: error code=0x%04X, register=0x%04X\n
si, code, reg);
});
PDO frame-loss events
PDOFrameLoss
using PDOFrameLossCallback = std::function<void(
uint16_t masterIndex, uint8_t group,
uint32_t consecutiveLost, uint32_t totalLost)>;
Consecutive PDO frame-loss event. Register with OnPDOFrameLoss().
Example:
master.Events().OnPDOFrameLoss([](uint16_t mi, uint8_t grp,
uint32_t consec, uint32_t total) {
printf("组 %d 丢帧: 连续=%u, 累计=%u\n", grp, consec, total); // Group %d frame loss: consecutive=%u, total=%u
});
DC sync lost events
DCSyncLost
using DCSyncLostCallback = std::function<void(
uint16_t masterIndex, uint16_t slaveIndex, int diffNs)>;
DC sync lost event. Register with OnDCSyncLost().
Example:
master.Events().OnDCSyncLost([](uint16_t mi, uint16_t si, int diff) {
printf("从站 %d DC 同步丢失: 偏差 %d ns\n", si, diff); // Slave %d lost DC sync: deviation %d ns
});
OnDCSyncRestored
using DCSyncRestoredCallback = std::function<void(const DCSyncRestoredEventArgs&)>;
The DC lock-loss recovery edge: fires when a slave returns from out of sync to inside the sync window, on the same edge as the sync window recovery event. Register with OnDCSyncRestored(cb).
Payload (DCSyncRestoredEventArgs):
| Field | Type | Description |
|---|---|---|
master_index | uint16_t | Master index |
slave_index | uint16_t | Slave index (1-based) |
timestamp_utc | std::chrono::system_clock::time_point | Recovery time (UTC) |
lost_duration | std::chrono::microseconds | Lock-loss duration (µs precision; treated as 0 when it cannot be read from the payload) |
native_timestamp_us | uint64_t | Monotonic microsecond timestamp recorded by the runtime (ev.timestamp_us) |
- Trigger condition: when a sync window recovery event arrives,
OnDcEventRaisedis delivered first, then this event on the same thread; other DC state events do not deliver this event. - Data source: the SDK's unified DC state event stream. A custom log callback takes over log output, so in that case use the DC event APIs directly (
OnDcEventRaised/OnDCSyncRestored). - Not interchangeable with
OnDCSyncLost:OnDCSyncLostis the "synchronized → out of sync" edge (withdiffNs); this event is the "out of sync → recovered" edge (with the real lock-loss duration). Subscribe to both to cover the complete start and end of one lock loss. lost_durationis the lock-loss duration in microseconds; it is not converted to nanoseconds, not inflated and not rounded.
Example:
master.Events().OnDCSyncRestored([](const darra::DCSyncRestoredEventArgs& e) {
printf("从站 %u DC 恢复, 失锁 %lld us\n", e.slave_index, // Slave %u DC recovered, lost lock %lld us\n
static_cast<long long>(e.lost_duration.count()));
});
DC state events (arming / sync window / reference clock / propagation delay / Hot-plug / convergence)
Every DC state change (arming, sync window entry and exit, reference clock switching / freezing, propagation delay re-measurement / reuse / invalidation, Hot-plug recovery, slow convergence) enters one unified event stream, so you no longer have to dig through the log.
There are two consumption channels, and neither replaces the other:
| Category | Entry point | Type | Read/write | Description |
|---|---|---|---|---|
| DC unified event stream (strongly typed) | Events().OnDcEventRaised(cb) | std::function<void(const DcEventArgs&)> | Write (register) | Payload DcEventArgs |
| DC state events (log) | LogManager::Instance().SetLogCallback(cb) | std::function<void(int, const char*)> | Write (register) | Events arrive with the log callback; the first parameter is the log category code and the message text carries the event body and payload |
OnDcEventRaised payload (DcEventArgs):
| Field | Type | Description |
|---|---|---|
master_index | uint16_t | Master index |
slave_index | uint16_t | Slave index (1-based); master-level events (reference clock / propagation delay) are always 0 |
code | DcEventCode | Event type (the members are frozen; values must not be reordered) |
params | std::string | Raw event parameters (read-only diagnostics; not parsed and not trimmed) |
timestamp_utc | std::chrono::system_clock::time_point | Event time (UTC, taken as the current time when dispatched) |
native_timestamp_us | uint64_t | Monotonic microsecond timestamp recorded by the runtime (ev.timestamp_us), a different source from timestamp_utc |
Trigger condition: delivered when the SDK's unified DC state event stream produces an event. The C++ SDK does not seize the process-wide single-slot log callback; a custom log callback takes over log output, so in that case use the DC event APIs directly.
The C++ SDK starts no implicit thread: the unified stream events are advanced by the application calling master.Events().PollDcEvents() periodically (≤1s recommended), and PollDiagnosticsEdges() also advances them once along the way. Without calling these two entry points, OnDcEventRaised / OnDCSyncRestored produce no events on their own.
- Slave-level events carry the slave index; master-level events (reference clock / propagation delay) always use slave index 0.
- Debouncing and rate limiting are handled by the runtime emitter (see the table below); the strongly typed channel does not deduplicate a second time.
OnDCSyncLost()/OnDCSyncRestored()and the two DC channels above are not interchangeable: the two strongly typed edges only cover entry into / recovery from "synchronized ↔ out of sync"; the log channel and the unified stream cover the whole DC lifecycle (including every state outside those two edges).
Message = event level, also emitted in production; Warning = alarm, also emitted in production; Error = severe (convergence over 30 seconds); Debug = reuse details, not output in Release builds, and collected only when SetDebugLogging(true) is set.
This channel adds no public API and does not change the ABI; do not call it on the hot path (it performs O(1) table lookups and low-frequency formatting only).
| Event | Category | Level | Read/write | Trigger and debounce |
|---|---|---|---|---|
| Arming succeeded | DC state | Message | Read-only | Emitted only when the published arming mask changes; the same mask is not repeated |
| Arming failed / rolled back | DC state | Warning | Read-only | Always fires the first time; at most one entry per 10 seconds while it persists |
| No SYNC0 cycle unit | DC state | Message | Read-only | Once per (master, slave); this is "arming not attempted", distinguished from the arming-failure event |
| Sync window exceeded | DC state | Warning | Read-only | Once on entry; at most one entry per 10 seconds while it persists |
| Sync window recovered | DC state | Message | Read-only | Once per recovery (paired with the sync window exceeded event) |
| Reference clock established / switched / lost | DC state | Message; Warning when warning=1 | Read-only | One entry per switch, minimum interval 1 second |
| Reference clock frozen | DC state | Warning | Read-only | At most one entry per slave per 60 seconds |
| Propagation delay re-measured | DC state | Message | Read-only | Minimum interval 1 second |
| Propagation delay reused | DC state | Debug | Read-only | Minimum interval 10 seconds; no repeat within the same generation |
| Propagation delay baseline invalidated | DC state | Message | Read-only | Minimum interval 1 second; the next update must re-measure the whole bus |
| Recovered after Hot-plug | DC state | Message; Warning when warning=1 | Read-only | Minimum interval 2 seconds per slave |
| Slow convergence (over 5 seconds) | DC state | Warning | Read-only | One entry per episode per 60 seconds; a hard floor of 5 seconds between any two |
| Severe convergence timeout (over 30 seconds) | DC state | Error | Read-only | Same as slow convergence |
Debounce semantics: on the emitter side each (master, slave) slot is claimed atomically, so concurrent calls produce only one entry; reference clock and propagation delay events are rate-limited independently (sharing one timestamp would suppress each other); convergence events are gated per episode — one entry per episode per 60 seconds, with at least 5 seconds between any two.
Master-level events (reference clock / propagation delay) use the slave index 0 slot and do not crowd out slave-level events; a slave-level event that wrongly carries index 0 is rejected and only a Debug trace is left.
Example:
LogManager::Instance().SetLogCallback([](int category, const char* msg) {
// DC state events arrive with the log callback; route them by level as needed
printf("[%d] %s\n", category, msg);
});
Diagnostic events
The data sources of the diagnostic events are all read-only SDK interfaces; the SDK only makes the edge decision and never rewrites the live value:
| Event | Registration method | Payload | Data source / edge advance |
|---|---|---|---|
| SDO read/write failure | Events().OnSdoError(cb) | SdoErrorEventArgs | The single exit point for CoE SDO failures (one delivery per failure, none on success) |
| Group WKC shortage | Events().OnWkcShortageOccurred(cb) | WkcShortageEventArgs | PollDiagnosticsEdges() polls the measured / expected WKC of groups 0-7 |
| Master physical port link | Events().OnNicLinkChanged(cb) | NicLinkChangedEventArgs | PollDiagnosticsEdges() polls the link state of primary port P1 / secondary port P2 |
OnSdoError
using SdoErrorCallback = std::function<void(const SdoErrorEventArgs&)>;
Fires when an SDO read / write fails; it does not fire on success. The data source is the single exit point for CoE SDO failures (the failure path of an SDO read / write), and one SDO call delivers exactly once. Register with OnSdoError(cb).
Payload (SdoErrorEventArgs):
| Field | Type | Description |
|---|---|---|
master_index | uint16_t | Master index |
slave_index | uint16_t | Slave index (1-based) |
index | uint16_t | Object dictionary index |
sub_index | uint8_t | Object dictionary subindex |
is_write | bool | true = write failed, false = read failed |
error | ethercat::SDOError | Normalized SDO error code (an abort from the table maps to that code; abort_code == 0, meaning the device returned no abort code, normalizes to SDOProtocolTimeout (0x05040000); an abort outside the table normalizes to GeneralError) |
abort_code | uint32_t | Raw Abort Code from the device; 0 = the device returned no abort code / transport-level failure (not fabricated) |
timestamp_utc | std::chrono::system_clock::time_point | Event time (UTC) |
- Trigger condition: WKC=0 with no response / Abort / timeout / an invalid write argument (not sent on the bus) are all delivered as failures; the success path (including an empty-string success) is not delivered.
ethercat::SDOError: the enum values are the CiA 301 abort codes (for exampleObjectDoesNotExist= 0x06020000,GeneralError= 0x08000000); the members are frozen — no new members and no reordering of values.NoErrornever appears in this event.- Meaning of
abort_code= 0: the device returned no abort code (transport-level failure / WKC=0 / timeout); it is not "success" and not a fabricatedGeneralError. Logs and UI should show "no abort code returned" and must not name a specific abort. - NotPresent negative-cache hit: when a deterministic abort hits the negative cache no bus traffic is generated, but it is still delivered once as "this read failed", with
abort_code= the deterministic abort cached at the time — so subscribers never see a failure silently disappear. - Reentrancy guard: starting another SDO that is bound to fail inside the callback does not deliver recursively (
thread_localreentrancy guard); that failure is still logged as usual. - Coverage boundary: only CoE SDO-level failures are covered. The C++ SDK has no generic mailbox transaction abstraction, so it does not provide an event equivalent to the C#
MailboxError; diagnose mailbox-level problems yourself withLastCloseError/NativeStatsofMailboxGatewayServiceor with the driver diagnostics — the two are at different levels.
Example:
master.Events().OnSdoError([](const darra::SdoErrorEventArgs& e) {
printf("SDO %s 失败 从站%u 0x%04X:%02X error=0x%08X abort=0x%08X\n", // SDO %s failed, slave %u 0x%04X:%02X error=0x%08X abort=0x%08X\n
e.is_write ? "写" : "读", e.slave_index, e.index, e.sub_index,
static_cast<unsigned>(e.error), e.abort_code);
});
OnWkcShortageOccurred
using WkcShortageCallback = std::function<void(const WkcShortageEventArgs&)>;
Group WKC shortage: the measured WKC of the group is smaller than expected (a mapped slave is not contributing). Register with OnWkcShortageOccurred(cb).
Payload (WkcShortageEventArgs):
| Field | Type | Description |
|---|---|---|
master_index | uint16_t | Master index (valid once bound; 0 when not bound) |
group | uint8_t | Group number 0-7 |
actual_wkc | uint16_t | Measured WKC (the value measured on the bus; the SDK does not rewrite it) |
expected_wkc | uint16_t | Expected WKC (a fixed true value from configuration time; it must not be lowered to accommodate degradation) |
timestamp_utc | std::chrono::system_clock::time_point | Sample time (UTC) |
Trigger condition (edge + deduplication): the application calls master.Events().PollDiagnosticsEdges() at a ≤1s period to feed samples (the SDK starts no implicit thread).
- It is delivered only when the measured value is smaller than expected and one of the following holds: this is the first shortage seen for the group, the previous tick was not short, or the measured / expected values differ from the previous tick. A persistent shortage with unchanged values does not repeat.
- A group with
expected_wkc == 0counts as unused: its baseline is cleared and it is not delivered as a shortage (so "not configured" is not misreported as "shortage"). - Both the measured and the expected value come from the bus measurement; the SDK does not modify, does not pad, and never writes
actual_wkcback intoexpected_wkc. When the slave resumes contributing, the measured value climbs back naturally and the event stops. - When the master is not bound (master index 0) or the runtime is not ready,
PollDiagnosticsEdges()returns immediately and produces no edge.
Example:
master.Events().OnWkcShortageOccurred([](const darra::WkcShortageEventArgs& e) {
printf("组 %u WKC 短缺: actual=%u expected=%u\n", // Group %u WKC deficit: actual=%u expected=%u\n
e.group, e.actual_wkc, e.expected_wkc);
});
// Application-side cycle advance (<= 1 s recommended, same semantics as the C# 1 s timer)
while (running) {
master.Events().PollDiagnosticsEdges();
std::this_thread::sleep_for(std::chrono::seconds(1));
}
OnNicLinkChanged
using NicLinkChangedCallback = std::function<void(const NicLinkChangedEventArgs&)>;
Master physical port link up / down edge. Register with OnNicLinkChanged(cb).
Payload (NicLinkChangedEventArgs):
| Field | Type | Description |
|---|---|---|
master_index | uint16_t | Master index |
port | uint8_t | 0 = primary port P1, 1 = secondary port P2 (the C++ SDK exports no NIC name / MAC, so the payload identifies the physical port and does not fabricate an empty name) |
is_up | bool | true = link up, false = link down |
timestamp_utc | std::chrono::system_clock::time_point | Sample time (UTC) |
Trigger condition (edge + deduplication): also advanced by PollDiagnosticsEdges().
- The first sighting of each physical port only records the baseline and delivers no event; after that, an up / down flip delivers once.
- A link state of
Unknown(unreadable / real-time process image unavailable / the older driver has no such field) produces no edge and does not overwrite the baseline — unknown must not pass for up or down; the next definite reading is judged as a real flip. - The link state of primary port P1 / secondary port P2 is read from
MasterDiagnosticsInfo::PrimaryPhyLinkState()/SecondaryPhyLinkState()respectively (the three-statePhyLinkState); anUnknownreading is skipped.
Example:
master.Events().OnNicLinkChanged([](const darra::NicLinkChangedEventArgs& e) {
printf("主站 %u %s 链路 %s\n", e.master_index, // Master %u %s link %s\n
e.port == 0 ? "主口P1" : "副口P2", e.is_up ? "up" : "down"); // primary port P1 / secondary port P2
});
Input data changes
The old InputDataChanged event relied on the SDK layer detecting input PDO changes byte by byte every cycle. Once the PDO data path became real-time send/receive in the runtime with a zero-copy process image, that mechanism was no longer needed.
To detect input changes, poll the process image pointer yourself and compare it against the previous cycle's snapshot:
// Poll the input PDO pointer every cycle and compare with the previous cycle's snapshot to detect changes
auto& slave = master.GetSlave(1);
auto* inPtr = static_cast<uint8_t*>(slave.InputDataPointer()); // live IOmap pointer, read at the same address
const int inSize = static_cast<int>(slave.Ibytes());
std::vector<uint8_t> prev(inSize, 0);
while (running) {
if (inPtr && std::memcmp(inPtr, prev.data(), inSize) != 0) {
std::memcpy(prev.data(), inPtr, inSize);
printf("从站 1 输入数据变化\n"); // Slave 1 input data changed\n
}
std::this_thread::sleep_for(std::chrono::milliseconds(10));
}
Redundancy events
RedundancyModeChanged
using RedundancyModeChangedCallback = std::function<void(
uint16_t masterIndex, int oldMode, int newMode)>;
Fires when the redundancy operating mode changes. Mode values: 0=Inactive, 1=Dual, 2=Degraded. Register with OnRedundancyModeChanged().
Example:
master.Events().OnRedundancyModeChanged([](uint16_t mi, int oldM, int newM) {
const char* names[] = {"Inactive", "Dual", "Degraded"};
printf("冗余模式: %s -> %s\n", names[oldM], names[newM]); // Redundancy mode: %s -> %s\n
});
SlavePortLinkChanged
using SlavePortLinkChangedCallback = std::function<void(
uint16_t masterIndex, uint16_t slaveIndex, uint8_t port, bool isUp)>;
Fires when the physical link of a slave ESC port changes (one of P0-P3 goes down or recovers). A diagnostic cycle every second checks the link bits of the DL Status register: 1→0 fires "down", 0→1 fires "recovered". Always logged automatically.
Use it to pinpoint the faulty cable segment (two facing ports of adjacent slaves reporting down at the same time means the cable between them is faulty).
Callback parameters:
masterIndex(uint16_t) — master indexslaveIndex(uint16_t) — slave index (1-based)port(uint8_t) — port number 0-3, corresponding to P0 / P1 / P2 / P3isUp(bool) — true = link recovered, false = link down
Example:
master.Events().OnSlavePortLinkChanged(
[](uint16_t mi, uint16_t si, uint8_t port, bool isUp) {
const char* state = isUp ? "恢复" : "断开"; // up / down
printf("从站 %u 端口 P%u link %s\n", si, port, state); // Slave %u port P%u link %s\n
});
master.GetDiagnostics().GetBreakPoints() provides an aggregated view of fault points (broken line + CRC faults, returned as std::vector<BreakPoint>). SlavePortLinkChanged is the raw event source and suits real-time alarming.
OnSlavePreOpReconfig
using SlavePreOpReconfigCallback = std::function<void(uint16_t masterIndex, uint16_t slaveIndex)>;
Fires when a slave needs its startup configuration (CoE Startup parameters) replayed after entering PreOP; the Hot-plug reinsertion recovery flow uses it. Register with OnSlavePreOpReconfig(cb).
Callback parameters:
masterIndex(uint16_t) — master indexslaveIndex(uint16_t) — index of the slave that needs reconfiguration (1-based)
master.Events().OnSlavePreOpReconfig([](uint16_t mi, uint16_t si) {
printf("主站 %u 从站 %d 需要重放启动配置\n", mi, si); // Master %u slave %d needs its startup configuration replayed\n
});
ClearAll()
void ClearAll();
Clears all event subscriptions to prevent memory leaks. Call it before destroying the master or reinitializing.
Example:
// Clear all master events
master.Events().ClearAll();
ClearAll() is equivalent to RemoveAll() and also clears the slave offline state tracking. Call it before Dispose() so captured references in callbacks cannot become dangling pointers.
RemoveCallback(EventKind, std::size_t)
enum class EventKind : std::uint8_t {
StateChanged = 0, SlaveStateChanged, EmergencyEvent, SlaveOffline, SlaveOnline,
SlaveOfflineDetailed, SlaveOfflineDisputed, PdoFrameLoss, DcSyncLost,
RedundancyModeChanged, Error, Warning, SlavePreOpReconfig, SlaveIdentityMismatch,
SlavePortLinkChanged, SdoError, DcEventRaised, DcSyncRestored,
WkcShortageOccurred, NicLinkChanged
};
bool RemoveCallback(EventKind kind, std::size_t index);
The following are members of darra::MasterEvents. Remove a single subscriber by event slot + 0-based index (thread-safe: it takes the MasterEvents mutex internally).
Returns:
true— the subscriber at that index was removedfalse— the index is out of range (index >= 该槽当前订阅者数, nothing happens); an invalidEventKindvalue also returnsfalse
The 20 slots map one-to-one onto the public registration methods (enum values 0..19):
| EventKind | Registration method |
|---|---|
| StateChanged | OnStateChanged |
| SlaveStateChanged | OnSlaveStateChanged |
| EmergencyEvent | OnEmergency |
| SlaveOffline | OnSlaveLost |
| SlaveOnline | OnSlaveDiscovered |
| SlaveOfflineDetailed | OnSlaveOfflineDetailed |
| SlaveOfflineDisputed | OnSlaveOfflineDisputed |
| PdoFrameLoss | OnPDOFrameLoss |
| DcSyncLost | OnDCSyncLost |
| RedundancyModeChanged | OnRedundancyModeChanged |
| Error | OnError |
| Warning | OnWarning |
| SlavePreOpReconfig | OnSlavePreOpReconfig |
| SlaveIdentityMismatch | OnSlaveIdentityMismatch |
| SlavePortLinkChanged | OnSlavePortLinkChanged |
| SdoError | OnSdoError |
| DcEventRaised | OnDcEventRaised |
| DcSyncRestored | OnDCSyncRestored |
| WkcShortageOccurred | OnWkcShortageOccurred |
| NicLinkChanged | OnNicLinkChanged |
Semantics:
- Only one subscriber of the target slot is removed; other subscribers of the same slot and other slots are unaffected.
- The index is the current index in that slot's callback
std::vector. After a removal, the indexes of all later subscribers shift down by one; when deleting several in a row, delete from the highest index down, or re-read the index from the current table each time. - The PDO cyclic subscription (
SetPDOCallbackSync) is not one of these 20 slots and cannot be removed withRemoveCallback; useRemoveAll()orPreparePDOForDispose(timeoutMs). - For events dispatched while holding the lock (state / emergency / online-offline / frame loss / DC sync lost / redundancy / PreOp / identity / port link), do not call
RemoveCallbackinside the callback (std::mutexis not reentrant); diagnostic events and strongly typed DC events are dispatched outside the lock, so calling it inside their callbacks is fine. - This interface only changes the user callback table; it adds no public API and does not change the ABI.
RemoveAll()/ClearAll()remain the full-clear entry points.
Example:
using darra::MasterEvents;
// Remove subscriber 0 of the StateChanged slot
bool removed = master.Events().RemoveCallback(MasterEvents::EventKind::StateChanged, 0);
// Delete from the highest index downwards, so a deletion does not shift later indices
master.Events().RemoveCallback(MasterEvents::EventKind::SdoError, 2);
master.Events().RemoveCallback(MasterEvents::EventKind::SdoError, 1);
master.Events().RemoveCallback(MasterEvents::EventKind::SdoError, 0);
Slave events (SlaveEvents)
The SDK also has a separate slave event collection, the SlaveEvents class (master/events.hpp); the event arguments are already filtered to the current slave.
Register the same way with On*() methods (multi-subscriber std::vector<std::function>), and clear them with ClearAll() / RemoveAll():
| Event | Registration method | Callback signature | Category | Read/write |
|---|---|---|---|---|
| State change | OnStateChanged(cb) | void(EcState, EcState) | State machine | Write (register) |
| Emergency message | OnEmergency(cb) | void(uint16_t, uint16_t, uint8_t, uint16_t, uint16_t) | Mailbox | Write (register) |
| Offline | OnOffline(cb) | void() | Hot-plug | Write (register) |
| Online | OnOnline(cb) | void() | Hot-plug | Write (register) |
| DC sync lost | OnDCSyncLost(cb) | void(int) | DC | Write (register) |
The Slave class itself does not expose an Events() accessor. SlaveEvents is not attached automatically: you must associate it with the routing table per slave index with
MasterEvents::RegisterSlaveEvents(slaveIndex, &events). In most cases it is enough to subscribe directly to master-level events such as
master.Events().OnSlaveStateChanged(...); the callback arguments carry slaveIndex and you can filter yourself.
Thread safety
All event callbacks fire on non-UI threads. Access to shared data from a callback must use a synchronization mechanism.
Thread model:
ProcessDataCyclicSync-- runs on a separate thread (not on the PDO real-time thread, merged into the latest one); an overlong callback skips the intermediate cycles- All other events -- run one after another on the event dispatch thread; do not block for long
OnSdoError-- delivered synchronously on the thread that issued that SDO read / write (inside the failure path); issuing another SDO inside the callback blocks that thread- DC events (
OnDcEventRaised/OnDCSyncRestored) -- delivered on the SDK log callback thread (usually the thread where the application calledSetLogCallback) - Group WKC shortage / master physical port link (
OnWkcShortageOccurred/OnNicLinkChanged) -- delivered on the thread that callsPollDiagnosticsEdges(); these two edges have no implicit thread — the SDK has no internal timer, so without the application advancing at a ≤1s period they are never received - The diagnostic events above and the strongly typed DC events all run outside the
MasterEventsmutex (the subscriber list is snapshotted and then invoked one by one): callingRemoveCallback/RemoveAllinside the callback is safe; subscribers registered while the list is being copied take effect from the next event; an exception thrown by a single callback is swallowed and does not affect later subscribers
Notes:
- Do not call
SetState(),Stop()or similar methods that can deadlock inside a callback - Do not perform blocking operations such as SDO read/write or file I/O in a synchronous callback
- Use
std::atomicfor simple flags andstd::mutexto protect complex data
In C++ prefer std::mutex or std::atomic to protect shared data:
#include <mutex>
#include <atomic>
std::atomic<bool> g_slave_offline{false};
master.Events().OnSlaveLost([&](uint16_t si) {
g_slave_offline.store(true); // Atomic operation
});
// Safe read on the main thread
if (g_slave_offline.load()) {
printf("有从站离线\n"); // A slave went offline\n
}
Full example
#include "ethercat.hpp"
#include <cstdio>
#include <atomic>
using namespace darra;
int main() {
std::atomic<bool> running{true};
try {
EtherCATMaster master(dll);
// Register all callbacks (always through On*() / SetPDOCallbackSync(), not field assignment)
auto& ev = master.Events();
// ===== State events =====
ev.OnStateChanged([](EcState oldS, EcState newS) {
printf("主站: %s -> %s\n", // Master: %s -> %s\n
EcStateFormat::Format(oldS).c_str(),
EcStateFormat::Format(newS).c_str());
});
ev.OnSlaveStateChanged([](uint16_t mi, uint16_t si,
EcState oldS, EcState newS) {
printf("从站 %d: %s -> %s\n", si, // Slave %d: %s -> %s\n
EcStateFormat::Format(oldS).c_str(),
EcStateFormat::Format(newS).c_str());
});
// ===== Hot-plug =====
ev.OnSlaveDiscovered([](uint16_t si) {
printf("从站 %d 上线\n", si); // Slave %d online
});
ev.OnSlaveLost([](uint16_t si) {
printf("从站 %d 离线\n", si); // Slave %d offline\n
});
// ===== Exception events =====
ev.OnEmergency([](uint16_t mi, uint16_t si, uint16_t code,
uint16_t reg, uint8_t b1, uint16_t w1, uint16_t w2) {
printf("从站 %d 紧急: 0x%04X\n", si, code); // Slave %d emergency: 0x%04X\n
});
ev.OnPDOFrameLoss([](uint16_t mi, uint8_t grp, uint32_t c, uint32_t t) {
printf("组 %d 丢帧: %u/%u\n", grp, c, t); // Group %d frame loss: %u/%u\n
});
ev.OnDCSyncLost([](uint16_t mi, uint16_t si, int diff) {
printf("从站 %d DC 偏差: %dns\n", si, diff); // Slave %d DC deviation: %dns\n
});
// ===== Redundancy events =====
ev.OnRedundancyModeChanged([](uint16_t mi, int oldM, int newM) {
const char* names[] = {"Inactive", "Dual", "Degraded"};
printf("冗余模式: %s -> %s\n", names[oldM], names[newM]); // Redundancy mode: %s -> %s\n
});
// ===== PDO cycle callback (cyclic notification, coalesced to the latest one; carries no FSoE / same-cycle safety loop; PDO data is read straight from the process image pointer) =====
ev.SetPDOCallbackSync([&](uint16_t mi) {
if (!running.load()) return;
// PDO data handling
});
// Start
master.SetNetwork("\\Device\\NPF_{...}");
master.Build();
master.SetState(EcState::OP);
master.Start();
printf("运行中... 按 Enter 停止\n"); // Running... press Enter to stop
getchar();
running.store(false);
} catch (const ethercat::DarraException& e) {
printf("错误: %s\n", e.what()); // Error: %s
return -1;
}
return 0;
}