Skip to main content

Events

Register callbacks to subscribe to all master-level events.

When to register callbacks

The registration functions are global: call them before or after Initialize(). Callbacks fire on a thread inside the DLL.

Automatic logging

Every event (except the PDO cyclic callback) is logged automatically when it fires, whether or not it is subscribed. Critical runtime state is never lost silently.

The PDO cyclic synchronous callback (RegisterProcessDataCyclicCallbackSync) is a high-frequency callback and is not logged.

PDO data path

PDO process data is sent and received by the real-time communication layer. The recommended path is to call GetIO once after entering OP, cast the pointer to a packed struct mapped onto the process image, and then read fields directly in a callback or on any thread. CopySlaveInputPdo is the snapshot alternative; write whole frames with WriteSlaveOutputPdo (a complete frame from a single real-time owner) and use versioned transactions for partial updates. RegisterProcessDataCyclicCallbackSync is for application logic that must align with the cycle (including FSoE). The asynchronous cyclic callback and the input-change callback are disabled.

Feature overview​

CategoryFunctionRead/writeDescriptionAuto logging
PDO cyclicRegisterProcessDataCyclicCallbackSyncWrite-onlyPDO cyclic synchronous callback (runs on the PDO thread; for real-time control such as FSoE)—
State changeRegisterSlaveStateChangeCallbackSync / AsyncWrite-onlySlave state change (merged view, includes master aggregate events)✓
State changedarra_register_master_state_change / _asyncWrite-onlyMaster aggregate state callback (receives only the slave_index==0 path)✓
State changedarra_register_slave_state_change / _asyncWrite-onlySlave state callback (receives only 1..N, never 0)✓
Hot-plugRegisterSlaveDiscoveryCallbackSync / AsyncWrite-onlySlave discovery / removal✓
darra_register_slave_offline_detailedWrite-onlySlave offline rich payload (reason classification + delivery-time evidence, delivered on the same tick as the discovery offline callback)✓
RegisterSlaveIdentityMismatchCallbackWrite-onlySlave identity mismatch✓
Exception eventsRegisterEmergencyEventCallbackWrite-onlyCoE Emergency message✓
PDO frame lossRegisterPDOFrameLossCallbackWrite-onlyConsecutive frame loss notification (tracked independently per group)✓
DC sync lostSetDCSyncLostCallbackWrite-onlyDC sync deviation out of range✓
RedundancyRegisterRedundancyModeChangedCallbackWrite-onlyRedundancy mode change✓
RegisterSlavePortLinkChangedCallbackWrite-onlySlave port link change (P0-P3)✓
Diagnosticsdarra_register_wkc_shortageWrite-onlyGroup WKC shortage edge (measured < expected); requires periodic darra_poll_diagnostics_edges()—
Diagnosticsdarra_register_nic_link_changedWrite-onlyMaster physical port link up/down edge; requires periodic darra_poll_diagnostics_edges()—
PreOP reconfigRegisterSlavePreOpReconfigCallbackWrite-onlySlave PreOP reconfiguration✓
LoggingSetLogCallbackWrite-onlyDLL-internal log messages—
CrashSetCrashCallbackWrite-onlyCrash notification—
Router equivalents

master/callback_router.h also provides router versions of every entry in the table above, isolated by master_index: darra_register_pdo_cyclic_sync / darra_register_emergency / darra_register_discovery_sync / darra_register_discovery_async / darra_register_pdo_frame_loss / darra_register_redundancy_changed / darra_register_preop_reconfig / darra_register_dc_sync_lost / darra_register_slave_identity_mismatch / darra_register_slave_port_link_changed. The table lists the module-header direct forwarders (a single process-wide slot); do not mix the two registration styles for the same callback type.

Events not provided in this language

The following logical events have no corresponding entry point in the C SDK; this page does not invent APIs:

  • Slave-lost marking and evidence-contradiction event: the C SDK provides only the discovery online/offline callbacks and the offline rich payload, and does not list this event separately.
  • SDO error / mailbox error events: SDO calls in the C SDK go through the public SDO interfaces; there is no unified exit point for failed SDO or mailbox transactions.
  • Generic error / generic warning callbacks: the C SDK has no such entry point; errors surface through specific events and return values.
  • Placeholder-slave re-read recovery event: the C SDK does not expose this refresh event.

Callback type definitions​

typedef void (*log_callback_t)(int category, const char* message);
typedef void (*crash_callback_t)(int exception_code, const char* message);
typedef void (*pdo_cyclic_callback_t)(uint16_t master_index);
typedef void (*state_change_callback_t)(uint16_t master_index, uint16_t slave_index,
int old_state, int new_state);
typedef void (*emergency_callback_t)(uint16_t master_index, uint16_t slave_index,
uint16_t error_code, uint16_t error_reg, uint8_t b1, uint16_t w1, uint16_t w2);
typedef void (*discovery_callback_t)(uint16_t master_index, uint16_t slave_index,
BOOL is_found);
typedef void (*frame_loss_callback_t)(uint16_t master_index, uint8_t group,
uint32_t consecutive_lost, uint32_t total_lost);
typedef void (*redundancy_changed_callback_t)(uint16_t master_index,
int old_mode, int new_mode);
typedef void (*preop_reconfig_callback_t)(uint16_t master_index, uint16_t slave_index);
typedef void (*dc_sync_lost_callback_t)(uint16_t master_index, uint16_t slave_index,
int diff_ns);
typedef void (*identity_mismatch_callback_t)(uint16_t master_index, uint16_t slave_index,
uint32_t expected_vendor, uint32_t expected_product, uint32_t expected_revision,
uint32_t actual_vendor, uint32_t actual_product, uint32_t actual_revision);
typedef void (*port_link_changed_callback_t)(uint16_t master_index, uint16_t slave_index,
uint8_t port, BOOL is_up);
typedef void (*darra_wkc_shortage_callback_t)(uint16_t master_index, uint8_t group,
uint16_t actual_wkc, uint16_t expected_wkc);
typedef void (*darra_nic_link_changed_callback_t)(uint16_t master_index, uint8_t port,
BOOL is_up);
C-specific sugar

After registering callbacks you usually need to check the return values of Initialize / SetNetwork / SetStateSequence and so on. C can use the EC_TRY(...) macro to simplify error checking and route every failure to a single goto fail for centralized cleanup.

PDO cyclic callback​

RegisterProcessDataCyclicCallbackSync​

Fires once per PDO cycle (synchronous mode). The callback runs directly on the PDO real-time thread with the lowest latency, for same-cycle real-time control such as FSoE. The callback must return quickly.

This is not a complete CiA 402 enable recipe

The example below shows the PDO write only. 0x000F may be held only 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. For multi-axis, command each axis from the same callback. See CiA 402 for the complete state machine.

Example (direct mapping with zero-copy, GetIO called only once outside the callback):

static in_pdo_t  *in;
static out_pdo_t *out;

static void on_pdo_cyclic(uint16_t master_index)
{
out->control_word = 0x000F;
out->target_position = in->actual_position;
(void)master_index;
}

/* after calling GetIO once: */
in = (in_pdo_t *)in_ptr;
out = (out_pdo_t *)out_ptr;
RegisterProcessDataCyclicCallbackSync(on_pdo_cyclic);

Snapshot alternative (copy each tick; the copied struct does not change underneath you):

static uint8_t in_snapshot[256];

static void on_pdo_cyclic(uint16_t master_index)
{
uint32_t copied = 0, required = 0;
CopySlaveInputPdo(master_index, 1, in_snapshot,
(uint32_t)sizeof(in_snapshot), &copied, &required);
/* in_snapshot is this tick's input frame copy; safe to parse inside the callback */
}
RegisterProcessDataCyclicCallbackSync(on_pdo_cyclic);
warning

Do not perform time-consuming operations in a synchronous callback (such as SDO read/write, file I/O, lock waits), or they block the real-time thread and cause frame loss.

Asynchronous cyclic PDO callbacks are disabled

The asynchronous cyclic PDO callback has been removed. PDOWriteOutput* can still write a single output value: it takes a shadow copy of the whole frame, changes only the target field, and commits it with the same ticket. It fails closed and returns FALSE when the slave is not in OP, the RxPDO is not mapped, the byte offset is out of range, or the transaction conflicts (the primitive logs a WARNING), so the return value must be checked, never ignored.

State events​

RegisterSlaveStateChangeCallbackAsync​

Fires when a slave's EtherCAT state changes. A background thread inside the DLL monitors and invokes the callback. Always logged automatically.

Callback parameters: master_index, slave_index (1-based), old_state, new_state (EC_STATE_*).

static void on_state_change(uint16_t mi, uint16_t si, int old_s, int new_s) {
printf("从站 %d: %d -> %d\n", si, old_s, new_s); /* Slave %d: %d -> %d */
uint16_t err = GetSlaveALStatusCode(mi, si);
if (err) printf(" 错误码: 0x%04X\n", err); /* Error code: 0x%04X */
}
RegisterSlaveStateChangeCallbackAsync(on_state_change);

RegisterSlaveStateChangeCallbackSync​

Same as above, synchronous mode. Runs on the real-time thread; the callback must return quickly.

State event routing (master vs slave)​

state_change callbacks use slave_index == 0 to mean the master aggregate state (summarized and reported once per cycle); valid slave indices are always 1..N. The two RegisterSlaveStateChangeCallback* functions above use the merged view (for backward compatibility): master aggregate events (slave_index == 0) and all slave events arrive together, so the caller must split on slave_index == 0 itself — leave out one if and you get the non-existent event "slave 0", which pollutes runtime state indexed by slave index.

When the SDK should do the routing for you, use this group of interfaces from master/callback_router.h:

typedef void (*darra_master_state_callback_t)(uint16_t master_index,
int old_state, int new_state);
typedef void (*darra_slave_state_callback_t)(uint16_t master_index, uint16_t slave_index,
int old_state, int new_state);

int darra_register_master_state_change (uint16_t master_index, darra_master_state_callback_t cb);
int darra_register_slave_state_change (uint16_t master_index, darra_slave_state_callback_t cb);
int darra_register_master_state_change_async(uint16_t master_index, darra_master_state_callback_t cb);
int darra_register_slave_state_change_async (uint16_t master_index, darra_slave_state_callback_t cb);
  • darra_master_state_callback_t — receives only master aggregate events with slave_index == 0; the callback no longer carries a slave index
  • darra_slave_state_callback_t — receives only slave events for 1..N; 0 never appears

Each event goes to exactly one of the two paths, so master events no longer fall into the slave channel.

Return value (darra_callback_router_status_t):

  • 0 — registered
  • -1 — master_index out of range, not registered
  • -2 — runtime not initialized / not ready: the callback is held in the router table, and calling this function once more after the runtime is ready completes delivery
  • -6 — cb is null: the slot is cleared (the old "pass NULL to unregister" usage is kept), but this does not count as a successful registration

BUSY (-3) / TIMEOUT (-4) are used for PDO cleanup waits, not for state callback registration.

The old interfaces have no failure channel

darra_register_state_change_sync / _async (state_change_callback_t) return void: a failed registration (index out of range / runtime not ready) cannot be reported. To get the registration result, use the routing interfaces above (they return int).

Example:

#include "master/callback_router.h"   /* this header pulls in ethercat.h itself */

static void on_master_state(uint16_t mi, int old_s, int new_s) {
printf("主站 %u: %d -> %d\n", mi, old_s, new_s); /* Master %u: %d -> %d */
}
static void on_slave_state(uint16_t mi, uint16_t si, int old_s, int new_s) {
printf("从站 %u/%u: %d -> %d\n", mi, si, old_s, new_s); /* si is always in 1..N */
}

int rc = darra_register_master_state_change(master, on_master_state);
if (rc != DARRA_CB_ROUTER_OK)
printf("主站状态回调注册失败: %d\n", rc); /* Master state callback registration failed: %d */

rc = darra_register_slave_state_change_async(master, on_slave_state);
if (rc == DARRA_CB_ROUTER_NATIVE_UNAVAILABLE)
/* register once more after the runtime is ready */
rc = darra_register_slave_state_change_async(master, on_slave_state);

Hot-plug events​

RegisterSlaveDiscoveryCallbackAsync​

Fires when a slave goes offline or comes online. When a Hot-plug slave drops, the recovery state machine built into the PDO thread restores it automatically. Always logged automatically.

Callback parameters: master_index, slave_index (1-based), is_found (TRUE = online, FALSE = offline).

static void on_discovery(uint16_t mi, uint16_t si, BOOL is_found) {
printf("从站 %d %s\n", si, is_found ? "上线" : "离线"); /* Slave %d %s (online / offline) */
}
RegisterSlaveDiscoveryCallbackAsync(on_discovery);

RegisterSlaveDiscoveryCallbackSync​

Same as above, synchronous mode.

darra_register_slave_offline_detailed​

Registers a callback for the rich payload of a normal slave offline, delivered on the same tick as RegisterSlaveDiscoveryCallbackSync with is_found == FALSE. It shares one event dispatcher with the ordinary discovery callback: when only this interface is registered, the router installs the sync discovery dispatcher automatically, so a standalone subscription still receives events.

typedef void (*slave_offline_event_callback_t)(uint16_t master_index,
const ec_slave_offline_event_t* event);

int darra_register_slave_offline_detailed(uint16_t master_index,
slave_offline_event_callback_t cb);
int darra_unregister_slave_offline_detailed(uint16_t master_index);

Payload fields the application should read:

  • timestamp_unix_ms — delivery time (UTC Unix milliseconds)
  • reason — tri-state (ec_slave_offline_reason_t): EC_SLV_OFFLINE_REASON_UNKNOWN(0) insufficient evidence, EC_SLV_OFFLINE_REASON_REAL_OFFLINE(1) loss confirmed, EC_SLV_OFFLINE_REASON_UNREACHABLE(2) the lost-slave marking contradicts delivery-time evidence (process data still contributing).
  • probe — probe measurement (ec_slave_probe_state_t): EC_SLV_PROBE_NOT_RESPONDING(0) / EC_SLV_PROBE_RESPONDING(1) / EC_SLV_PROBE_UNKNOWN(2); when the entry point is unavailable the value is EC_SLV_PROBE_UNKNOWN.
  • contribution — this cycle's process data contribution (ec_slave_wc_contribution_t): EC_SLV_WC_NOT_CONTRIBUTED(0x00) not contributed, EC_SLV_WC_CONTRIBUTED(0x01) contributed normally, EC_SLV_WC_UNKNOWN(0xFF) unavailable (treat it as unknown).
  • Clean OP flag — 1 = yes, 0 = no, -1 = unavailable.
  • Consecutive clean sample count — not a public criterion: the count is always unavailable and the threshold field only echoes state, -1 = unavailable.

Registration semantics: single-slot overwrite (registering again for the same master_index replaces); returns DARRA_CB_ROUTER_OK / INVALID_ARGUMENT (index out of range) / NULL_CALLBACK (cb == NULL, clears the slot). The event pointer is valid only during this callback and must not be stored.

Combining with the discovery callback

If you register both the sync and the async discovery path, each reported event fires once on each (in the same phase as the ordinary discovery callback). The C SDK does not list a separate "lost marking contradicts evidence" event; reason / the clean OP flag report actual values as they are.

RegisterSlaveIdentityMismatchCallback​

Fires when a slave is identified as a different device after a power cycle or reinsertion: 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 identity judgment is fixed to Vendor + Product only — if those two match, the device is taken to be the same one. The C interface exposes no switch for the revision matching mode; if you need a strict revision check, compare expected_revision with actual_revision in your own code. Always logged automatically.

After firing, the slave enters the IDENT_REJECTED state and is not re-probed automatically (this keeps a wrong device from flooding the log). After the operator checks or replaces the device, call AcknowledgeSlaveReplacement to let the SDK probe again.

Callback parameters: master_index, slave_index, and 3 uint32_t values each for the expected and actual vendor/product/revision.

static void on_identity_mismatch(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("从站 %d 身份不符: 期望 Vendor=0x%08X, 实际 Vendor=0x%08X\n", si, ev, av); /* Slave %d identity mismatch: expected Vendor=0x%08X, actual Vendor=0x%08X */
/* after showing a UI prompt, call AcknowledgeSlaveReplacement(mi, si) */
}
RegisterSlaveIdentityMismatchCallback(on_identity_mismatch);
Deduplication

A slave entering the IDENT_REJECTED state fires the event only once. AcknowledgeSlaveReplacement resets probing; if the identity still does not match, the event fires again.

Exception events​

Cycle anomalies must raise an alarm

The cycle follows the DENI/LoopCycle setting, with a minimum of 31 µs (= 31,000 ns, whole microseconds, the specification floor; on Windows 125 µs or more is recommended). It is not hard-coded to 1 ms. The diagnostic snapshot frequency should align with 1e9 / DarraEcat_GetMasterLoopCycleTime(master). A continuous deviation of ±20% from the setting, or a max jitter above 25% of the cycle, must be logged and raised in the UI. Check PDOFrameLoss and DCSyncLost as well. When isolation is not in effect only jitter may grow; a drifting cycle without an alarm is not acceptable. Do not do alarm I/O on the PDO hot path.

RegisterEmergencyEventCallback​

CoE Emergency message event. Sent by slave firmware when it detects an error; the data format follows the CANopen Emergency protocol (CiA 301). Always logged automatically.

Callback parameters: master_index, slave_index, error_code (CANopen Emergency Error Code), error_reg (object 0x1001), b1/w1/w2 (manufacturer-specific data).

Common Emergency Error Codes: 0x1000 generic / 0x2000 current / 0x3000 voltage / 0x4000 temperature / 0x5000 hardware / 0x6000 software / 0x8000 communication monitoring.

static void on_emcy(uint16_t mi, uint16_t si,
uint16_t code, uint16_t reg, uint8_t b1, uint16_t w1, uint16_t w2)
{
printf("从站 %d EMCY: 错误码=0x%04X, 寄存器=0x%02X\n", si, code, reg); /* Slave %d EMCY: error code=0x%04X, register=0x%02X */
}
RegisterEmergencyEventCallback(on_emcy);

RegisterPDOFrameLossCallback​

PDO consecutive frame loss event. Fires when consecutive lost frames reach the threshold; a single lost frame is only counted. Each group is tracked independently. Always logged automatically.

Callback parameters: master_index, group (0-7), consecutive_lost, total_lost.

static void on_frame_loss(uint16_t mi, uint8_t grp, uint32_t cons, uint32_t total) {
printf("组 %d 丢帧: 连续=%u, 累计=%u\n", grp, cons, total); /* Group %d frame loss: consecutive=%u, total=%u */
}
RegisterPDOFrameLossCallback(on_frame_loss);

SetDCSyncLostCallback​

DC sync lost event. Fires once when a slave goes from synchronized to out of sync (beyond the threshold); a sustained violation does not fire again. Always logged automatically.

Callback parameters: master_index, slave_index, diff_ns (current time difference from the reference clock).

SetSyncWindowThreshold(master, 500);  /* 500ns */
static void on_dc_lost(uint16_t mi, uint16_t si, int diff) {
printf("从站 %d DC 同步丢失: 偏差 %dns\n", si, diff); /* Slave %d lost DC sync: deviation %dns */
}
SetDCSyncLostCallback(on_dc_lost);

DC state events (arming / sync window / reference clock / propagation delay / Hot-plug / convergence)​

DC arming, window entry and exit, reference clock switching and freezing, propagation delay re-measurement / reuse / invalidation, Hot-plug recovery and slow convergence are all folded into one DC state event stream, delivered entirely through the log callback channel, so you no longer have to read the process log.

Not interchangeable with DCSyncLost

SetDCSyncLostCallback covers only the strongly typed "synchronized → out of sync" subscription edge; this channel carries the full set of DC state events. Register them independently; neither replaces the other, and do not wait on one for the other.

CategoryEventLevelTrigger and debounceKey payloadRead/write
DC eventArming succeededMessageEmitted only when the published arming state changes; no repeat when the state is unchangedWritten/read-back 0x0980, 0x09A0, ESI tier, required configuration, evidence strengthRead-only
DC eventArming failed / rolled backWarningAlways fires the first time; at most one entry per 10 seconds while it persistsReason, whether it was rolled back, AL status/code, write WKC, read-back 0x0980Read-only
DC eventNo SYNC0 cycle unitMessageOnce per (master, slave)Evidence that three consecutive rounds of 0x0980 got no responseRead-only
DC eventSync window exceededWarningOnce on entry; at most one entry per 10 seconds while it persistsCurrent difference, threshold, duration so far, sample countRead-only
DC eventSync window recoveredMessageOnce per recovery (paired with sync window exceeded)Current difference, thresholdRead-only
DC eventReference clock established / switched / lostMessage; Warning when the alarm flag is setOne entry per switch, minimum interval 1 secondOld/new reference clock, tier, reasonRead-only
DC eventReference clock frozenWarningAt most one entry per slave per 60 seconds1:1 ramp slope (ppm), reasonRead-only
DC eventPropagation delay re-measuredMessageMinimum interval 1 secondReason, slave count, maximum propagation delay on the whole bus, session generationRead-only
DC eventPropagation delay reusedDebugMinimum interval 10 seconds; no repeat within the same generationReason, slave count, maximum propagation delay, generationRead-only
DC eventPropagation delay baseline invalidatedMessageMinimum interval 1 secondReason; the next update must re-measure the whole busRead-only
DC eventRecovered after Hot-plugMessage; Warning when the alarm flag is setMinimum interval 2 seconds per slaveArming result, 0x0980 read-back, AL status/code, propagation delayRead-only
DC eventSlow convergence (over 5 seconds)WarningOne entry per episode per 60 seconds; hard floor of 5 seconds between any twoDuration so far, sample count, differenceRead-only
DC eventSevere convergence timeout (over 30 seconds)ErrorSame as slow convergenceDuration so far, sample count, differenceRead-only

The event channel registration entry point SetLogCallback(...) (C) / LogManager::Instance().SetLogCallback(...) (C++ low level) is write (register); each event in the table is itself read-only.

darra_register_dc_event_raised / darra_register_dc_sync_restored​

When you need structured DC event payloads, take them directly from these static library entry points in master/callback_router.h:

typedef void (*darra_dc_event_callback_t)(uint16_t master_index, uint16_t slave_index,
int code, const char* params);
typedef void (*darra_dc_sync_restored_callback_t)(uint16_t master_index,
uint16_t slave_index,
uint64_t lost_us);

int darra_register_dc_event_raised(uint16_t master_index, darra_dc_event_callback_t cb);
int darra_unregister_dc_event_raised(uint16_t master_index);
int darra_register_dc_sync_restored(uint16_t master_index, darra_dc_sync_restored_callback_t cb);
int darra_unregister_dc_sync_restored(uint16_t master_index);

Callback parameters:

  • master_index (uint16_t) — master index
  • slave_index (uint16_t) — slave index; master-level events of the reference clock and propagation delay kind are always 0, other events carry the slave index and 0 when absent
  • code (int) — event type identifier (semantics in the table above)
  • params (const char*) — raw event parameters, valid only during this callback, must not be stored

darra_register_dc_sync_restored delivers only on sync window recovery events; the lost_us payload is how long lock was lost (microseconds), 0 when unavailable.

Data source: DC state events arrive through the SDK's unified event stream. A custom log callback takes over log output, so in that case use the DC event APIs directly (darra_register_dc_event_raised / darra_register_dc_sync_restored).

Registration semantics: single-slot overwrite; returns DARRA_CB_ROUTER_OK / INVALID_ARGUMENT / NULL_CALLBACK. The callback runs synchronously on the application log callback thread; do not block.

Consumption channels:

/* C: events arrive with the log callback */
static void on_log(int category, const char* message) {
printf("[%d] %s\n", category, message);
}
SetLogCallback(on_log);
/* C++ low level: the same log channel */
LogManager::Instance().SetLogCallback([](int category, const char* message) {
printf("[%d] %s\n", category, message);
});
  • Level mapping: Message = informational event level, also emitted in production; Warning = alarm, also emitted in production; Error = severe (convergence over 30 seconds); Debug is emitted in Debug builds only, never in Release.
  • Debouncing happens on the emitting side: one slot per (master, slave), claimed atomically; reference clock and propagation delay events are rate-limited independently (sharing one timestamp would suppress each other); convergence events are gated per episode.
  • 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.
  • This channel adds no public symbols and does not change the ABI; internally it does O(1) table lookups and low-frequency formatting only, and must not be called on the PDO hot path.

Diagnostic events (WKC shortage / NIC link edges)​

These two event classes are edge events; the data source is the runtime's group WKC and the PHY link state of the master's physical ports. The C SDK starts no threads implicitly: after registering a callback, the application must call darra_poll_diagnostics_edges(master_index) at ≤1 s intervals to advance the poll; only then are edges delivered. Without polling there are no events at all (which is not the same as "no faults").

darra_register_wkc_shortage​

typedef void (*darra_wkc_shortage_callback_t)(uint16_t master_index, uint8_t group,
uint16_t actual_wkc, uint16_t expected_wkc);
int darra_register_wkc_shortage(uint16_t master_index, darra_wkc_shortage_callback_t cb);

Fires when the group process data WKC is short (actual_wkc < expected_wkc). expected_wkc is the expected value fixed at configuration time and must not be lowered to accommodate a degraded bus; actual_wkc reports the current contribution as it is.

Trigger and debounce:

  • group is 0-7, judged independently per group.
  • A group with expected_wkc == 0 counts as unused: its baseline is cleared and no event fires (an unconfigured group is not misreported as a shortage).
  • Fires only when this sample is short and one of the following holds: first shortage / the previous sample was not short / actual or expected changed; a persistent shortage with unchanged values is not delivered again.
  • Recovery (actual >= expected) only updates the baseline; no recovery event is delivered.
  • Returns immediately when the runtime is not ready or master_index is out of range; no edge is invented.

Callback parameters:

  • master_index (uint16_t) — master index
  • group (uint8_t) — group number 0-7
  • actual_wkc (uint16_t) — WKC measured in this sample
  • expected_wkc (uint16_t) — expected WKC fixed at configuration time

Registration semantics: single-slot overwrite (registering again for the same master_index replaces, it does not stack); returns DARRA_CB_ROUTER_OK / INVALID_ARGUMENT (index out of range) / NULL_CALLBACK (cb == NULL, clears the slot). Unregister with darra_unregister_wkc_shortage(master_index).

typedef void (*darra_nic_link_changed_callback_t)(uint16_t master_index, uint8_t port,
BOOL is_up);
int darra_register_nic_link_changed(uint16_t master_index, darra_nic_link_changed_callback_t cb);

Fires when the physical port link of the master flips up/down. port 0 = primary port P1 (GetPrimaryPhyLinkState), port 1 = secondary port P2 (GetSecondaryPhyLinkState). The C SDK provides no NIC name / MAC; the payload carries only the physical port identifier and does not fabricate an empty name.

Trigger and debounce:

  • The first sighting of each physical port only establishes the baseline; no event fires.
  • After that, an up → down or down → up flip fires once.
  • When the link state is not observable (raw < 0, Unknown) no edge is produced and the baseline is not overwritten — "cannot read" is never written as down.
  • Also advanced by darra_poll_diagnostics_edges(); without polling no events occur.

Callback parameters:

  • master_index (uint16_t) — master index
  • port (uint8_t) — 0 = primary port P1, 1 = secondary port P2
  • is_up (BOOL) — TRUE = link up, FALSE = link down

Registration semantics: single-slot overwrite, return codes as above; unregister with darra_unregister_nic_link_changed(master_index).

Example:

static void on_wkc_shortage(uint16_t mi, uint8_t group,
uint16_t actual, uint16_t expected) {
printf("主站 %u 组 %u WKC 短缺: 实测=%u 期望=%u\n", mi, group, actual, expected); /* Master %u group %u WKC shortfall: measured=%u expected=%u */
}

static void on_nic_link(uint16_t mi, uint8_t port, BOOL is_up) {
printf("主站 %u 物理口 P%u 链路 %s\n", mi, (unsigned)(port + 1), is_up ? "up" : "down"); /* Master %u physical port P%u link %s */
}

darra_register_wkc_shortage(master, on_wkc_shortage);
darra_register_nic_link_changed(master, on_nic_link);

/* advance edge polling on your own cycle thread (<=1 s recommended) */
while (running) {
darra_poll_diagnostics_edges(master);
sleep_ms(1000);
}

Redundancy events​

RegisterRedundancyModeChangedCallback​

Fires when the redundancy operating mode changes. old_mode/new_mode are values of the redundancy mode enum (ec_ring_mode_t: EC_RING_INACTIVE(0) / EC_RING_DUAL(1) / EC_RING_DEGRADED(2)). Always logged automatically.

static void on_redundancy(uint16_t mi, int old_mode, int new_mode) {
printf("冗余模式: %d -> %d\n", old_mode, new_mode); /* Redundancy mode: %d -> %d */
}
RegisterRedundancyModeChangedCallback(on_redundancy);

RegisterSlavePortLinkChangedCallback​

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 = the cable between them is faulty).

Callback parameters: master_index, slave_index, port (0-3 corresponding to P0-P3), is_up (TRUE = recovered, FALSE = down).

static void on_port_link(uint16_t mi, uint16_t si, uint8_t port, BOOL is_up) {
printf("从站 %d P%d link %s\n", si, port, is_up ? "恢复" : "断开"); /* Slave %d P%d link %s (restored / down) */
}
RegisterSlavePortLinkChangedCallback(on_port_link);
Pinpointing break points

GetBreakPoints() gives an aggregated view of fault points (broken line + CRC faults). SlavePortLinkChanged is the raw event source and suits real-time alarming.

RegisterSlavePreOpReconfigCallback​

typedef void (*preop_reconfig_callback_t)(uint16_t master_index, uint16_t slave_index);
void RegisterSlavePreOpReconfigCallback(preop_reconfig_callback_t callback);

Fires when a slave needs its startup configuration (CoE startup parameters) replayed after entering PreOP; the Hot-plug reinsertion recovery flow uses it. Always logged automatically.

Callback parameters:

  • master_index (uint16_t) — master index
  • slave_index (uint16_t) — index of the slave that needs reconfiguration (1-based)

Clearing event subscriptions​

The C SDK has no ClearAllEvents

ClearAllEvents is not implemented in 2.11.0: master/events.h does not declare it and the SDK provides no equivalent entry point; do not call it.

Remove each callback class with its matching unregister entry point (pass the original callback pointer to remove it; passing NULL is a no-op):

RegisterUnregister (master/events.h)
SetLogCallbackUnsetLogCallback
SetCrashCallbackUnsetCrashCallback
RegisterProcessDataCyclicCallbackSyncUnregisterProcessDataCyclicCallbackSync
RegisterSlaveStateChangeCallbackSync / RegisterSlaveStateChangeCallbackAsyncUnregisterSlaveStateChangeCallbackSync / UnregisterSlaveStateChangeCallbackAsync
RegisterEmergencyEventCallbackUnregisterEmergencyEventCallback
RegisterSlaveDiscoveryCallbackSync / RegisterSlaveDiscoveryCallbackAsyncUnregisterSlaveDiscoveryCallbackSync / UnregisterSlaveDiscoveryCallbackAsync
RegisterPDOFrameLossCallbackUnregisterPDOFrameLossCallback
RegisterRedundancyModeChangedCallbackUnregisterRedundancyModeChangedCallback
RegisterSlavePreOpReconfigCallbackUnregisterSlavePreOpReconfigCallback
SetDCSyncLostCallbackUnsetDCSyncLostCallback
RegisterSlaveIdentityMismatchCallbackUnregisterSlaveIdentityMismatchCallback
RegisterSlavePortLinkChangedCallbackUnregisterSlavePortLinkChangedCallback

The router interfaces in master/callback_router.h are cleared as a whole table per master_index: darra_unregister_master_callbacks(master_index) (clears this master only) and darra_unregister_all_callbacks() (clears everything); single slots can also be unregistered with darra_unregister_slave_offline_detailed() / darra_unregister_dc_event_raised() / darra_unregister_dc_sync_restored() / darra_unregister_wkc_shortage() / darra_unregister_nic_link_changed(); darra_clear_log_callback() clears only the user log slot.

Calling Dispose(master) releases the master instance as a whole and stops all callback threads.

Thread safety​

Event callbacks fire on threads inside the DLL, not on the UI thread. Use a mutex or atomic operations when accessing shared data.

warning

Synchronous callbacks (*Sync) run directly on the real-time PDO thread; do not perform time-consuming operations (such as SDO read/write, file I/O, lock waits), or they block the real-time thread and cause frame loss. Asynchronous callbacks (*Async) such as state change / Hot-plug run on a separate thread: slightly higher latency, but safer.

Thread ownership of diagnostic events is described separately:

  • Callbacks of darra_register_wkc_shortage / darra_register_nic_link_changed run synchronously on the thread that calls darra_poll_diagnostics_edges() (the C SDK creates no thread of its own). Callbacks must return quickly; post time-consuming work to a work queue yourself.
  • Callbacks of the unified DC event stream (darra_register_dc_event_raised / darra_register_dc_sync_restored) run on the application log callback thread; likewise do not block.
  • Do not register or unregister the same slot while a callback is running (single-slot semantics: a re-entrant replace can leave the current call holding an old pointer).
/* Thread-safety example — protect shared data with a mutex */
#include <pthread.h>

static pthread_mutex_t data_lock = PTHREAD_MUTEX_INITIALIZER;
static int shared_counter = 0;

static void on_pdo_cyclic(uint16_t mi) {
pthread_mutex_lock(&data_lock);
shared_counter++;
pthread_mutex_unlock(&data_lock);
}

Full example​

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

static void on_log(int cat, const char* msg) {
const char* tags[] = {"错误","警告","消息","邮箱","PDO","调试"}; /* Error / Warning / Message / Mailbox / PDO / Debug */
printf("[%s] %s\n", (cat >= 0 && cat <= 5) ? tags[cat] : "?", msg);
}
static void on_pdo_cyclic(uint16_t mi) { /* IO read/write */ }
static void on_state_change(uint16_t mi, uint16_t si, int o, int n) {
printf("从站 %d: %d -> %d\n", si, o, n); /* Slave %d: %d -> %d */
}
static void on_discovery(uint16_t mi, uint16_t si, BOOL found) {
printf("从站 %d %s\n", si, found ? "上线" : "离线"); /* Slave %d %s (online / offline) */
}
static void on_emcy(uint16_t mi, uint16_t si,
uint16_t c, uint16_t r, uint8_t b, uint16_t w1, uint16_t w2) {
printf("从站 %d EMCY 0x%04X\n", si, c); /* Slave %d EMCY 0x%04X */
}
static void on_frame_loss(uint16_t mi, uint8_t g, uint32_t c, uint32_t t) {
printf("组 %d 丢帧: 连续=%u\n", g, c); /* Group %d frame loss: consecutive=%u */
}
static void on_dc_lost(uint16_t mi, uint16_t si, int d) {
printf("从站 %d DC 失步 %dns\n", si, d); /* Slave %d lost DC sync %dns */
}

int main(void) {
SetLogCallback(on_log);
RegisterProcessDataCyclicCallbackSync(on_pdo_cyclic);
RegisterSlaveStateChangeCallbackAsync(on_state_change);
RegisterSlaveDiscoveryCallbackAsync(on_discovery);
RegisterEmergencyEventCallback(on_emcy);
RegisterPDOFrameLossCallback(on_frame_loss);
SetDCSyncLostCallback(on_dc_lost);

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

getchar();

Stop(master);
Dispose(master); /* Dispose stops all callback threads as a whole */
return 0;
}