Slave events
Obtain MasterEvents& through master.Events(), and register callbacks with On*() / SetPDOCallbackSync().
Each event on MasterEvents is a multi-subscriber std::vector<std::function>; you must call the On*() registration method. You cannot assign with =.
In the C++ API, master-level callback functions include masterIndex and slaveIndex parameters; the caller filters them to the matching slave.
Feature overview
| Category | Registration method | Read/write | Description |
|---|---|---|---|
| Slave state change | OnSlaveStateChanged(cb) | Write (register) | EtherCAT state change |
| Slave state change with AL code | OnSlaveStateChangedWithAl(cb) | Write (register) | State change plus the AL code at the moment of the change (16-bit raw code + whether it is trustworthy) |
| Emergency message | OnEmergency(cb) | Write (register) | CoE Emergency message |
| Slave online | OnSlaveDiscovered(cb) | Write (register) | Slave came online |
| Slave offline | OnSlaveLost(cb) | Write (register) | Slave went offline |
| DC sync lost | OnDCSyncLost(cb) | Write (register) | DC sync deviation out of limits |
| PDO cycle | SetPDOCallbackSync(cb) | Write (register) | PDO cycle notification (delivered by a separate thread; slow callbacks are merged into the latest one; does not carry FSoE / the same-cycle safety loop) |
| PDO frame loss | OnPDOFrameLoss(cb) | Write (register) | PDO frame lost |
| Hot-plug identity mismatch | OnSlaveIdentityMismatch(cb) | Write (register) | Vendor/Product/Revision mismatch after replacement or reinsertion |
| Slave port link change | OnSlavePortLinkChanged(cb) | Write (register) | P0-P3 port down/restored |
| Slave PreOP reconfiguration | OnSlavePreOpReconfig(cb) | Write (register) | Startup configuration must be rerun after a hot-plug reinsertion (callback parameters mi, si) |
Slave event set (SlaveEvents)
SlaveEvents (master/events.hpp) is the event set already filtered per slave by the master event routing layer: the parameters contain no masterIndex / slaveIndex, and events are delivered only to the slave they are associated with. Master-level events carry the same names but different semantics; do not confuse them (for example, the master aggregate state only goes through master.Events().OnStateChanged).
Registration: MasterEvents::RegisterSlaveEvents(slaveIndex, &slaveEvents) registers the slave index and the instance in the routing table, and the master forwards that slave's events here (the Slave class itself does not expose an Events() accessor). The instance lifetime must cover the subscription period; call ClearAll() before destroying it.
| Event | Registration method | Callback signature | Category | Read/write |
|---|---|---|---|---|
| State change | OnStateChanged(cb) | void(EcState oldState, EcState newState) | State machine | Write (register) |
| Emergency message | OnEmergency(cb) | void(uint16_t errorCode, uint16_t errorReg, uint8_t b1, uint16_t w1, uint16_t w2) | 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 diffNs) | DC | Write (register) |
| Clear subscriptions | RemoveAll() / ClearAll() | void() | -- | Write (clear) |
Trigger semantics:
OnStateChanged: delivered once per slave EtherCAT state transition (old state, new state). The master aggregate state (slaveIndex == 0) only goes through the masterOnStateChangedchannel and never enters this set.OnOffline/OnOnline: strictly paired.OnOnlineis delivered only when a slave that was previously announced as offline comes online; when the evidence disproves offline (process data confirms the slave still contributes,SlaveOfflineReason::Unreachable), neitherOnOfflineis delivered norOnOnlineis made up afterwards; instead the masterOnSlaveOfflineDisputedis delivered.OnEmergency: delivered when a CoE Emergency arrives; the parameters are the rawerrorCode/errorReg/b1/w1/w2values.OnDCSyncLost: delivered on the edge from DC in sync to out of sync; the parameter is the time difference from the reference clock (ns).
Threading and synchronization:
- Callbacks run on the master event dispatch thread (the same tick as master-level events) and are invoked while the subscription table lock is held; do not call the registration / unregistration methods of
master.Events()inside a callback, or callRemoveAll()/ClearAll()/On*()(std::mutexis not reentrant), otherwise it deadlocks itself; when you need to change subscriptions, queue the action to another thread. - An exception thrown by a single callback is swallowed and does not affect later subscribers of the same event.
Example:
darra::SlaveEvents slaveEvents; // The lifetime must cover the subscription period
master.Events().RegisterSlaveEvents(1, &slaveEvents);
slaveEvents.OnStateChanged([](EcState oldState, EcState newState) {
printf("从站 1 状态: %s -> %s\n", // Slave 1 state: %s -> %s\n
EcStateFormat::Format(oldState).c_str(),
EcStateFormat::Format(newState).c_str());
});
slaveEvents.OnOffline([]() { printf("从站 1 离线\n"); }); // Slave 1 offline\n
slaveEvents.OnOnline([]() { printf("从站 1 上线\n"); }); // Slave 1 online\n
// Clear it before destroying the master, so the callback cannot capture a dangling reference
slaveEvents.ClearAll();
Slave state change
master.Events().OnSlaveStateChanged([](uint16_t mi, uint16_t si,
EcState oldState, EcState newState) {
printf("[从站%d] 状态: %s -> %s\n", si, // [Slave%d] state: %s -> %s\n
EcStateFormat::Format(oldState).c_str(),
EcStateFormat::Format(newState).c_str());
});
State change with AL code
master.Events().OnSlaveStateChangedWithAl(
[](uint16_t mi, uint16_t si, EcState oldState, EcState newState,
uint16_t alStatusCode, bool alStatusCodeKnown) {
// ...
});
Delivered on the same tick, side by side with OnSlaveStateChanged, and does not replace the old channel. alStatusCode is the full 16-bit AL Status Code "at the moment of the change", taken from a native zero-frame cached field with no extra bus frame — so even after the slave has dropped out of OP and recovered, you still get the reason code from the moment it dropped.
Callback parameters: (SlaveStateChangeWithAlCallback)
mi(uint16_t) — master indexsi(uint16_t) — slave indexoldState(EcState) — old statenewState(EcState) — new statealStatusCode(uint16_t) — AL Status Code at the moment of the change; meaningless whenalStatusCodeKnown=falsealStatusCodeKnown(bool) — whether the AL code is trustworthy
alStatusCodeKnown=false conditions: slave index < 1 (the master aggregate state does not go through this channel) / master closed / null slave pointer / read failure / IsLost() is true / value == 0xFFFF. In that case alStatusCode must not be read as "no error"; for the live truth "right now", use ALStatusCodeLiveRead().
This entry point is registered on MasterEvents and filters by masterIndex / slaveIndex yourself; the SlaveEvents filtered set has no corresponding AL-code entry point.
Example:
master.Events().OnSlaveStateChangedWithAl(
[](uint16_t mi, uint16_t si, EcState oldState, EcState newState,
uint16_t alCode, bool known) {
if (known)
printf("[%u:%u] %s -> %s, AL=0x%04X\n", mi, si,
EcStateFormat::Format(oldState).c_str(),
EcStateFormat::Format(newState).c_str(), alCode);
else
printf("[%u:%u] %s -> %s, AL 码不可信\n", mi, si, // [%u:%u] %s -> %s, AL code not trustworthy\n
EcStateFormat::Format(oldState).c_str(),
EcStateFormat::Format(newState).c_str());
});
Emergency messages
master.Events().OnEmergency([](uint16_t mi, uint16_t si,
uint16_t errorCode, uint16_t errorReg,
uint8_t b1, uint16_t w1, uint16_t w2) {
printf("[从站%d] 紧急消息: 错误码=0x%04X\n", si, errorCode); // [Slave%d] emergency message: error code=0x%04X\n
});
Slave online/offline
master.Events().OnSlaveDiscovered([](uint16_t si) {
printf("[从站%d] 上线\n", si); // [Slave%d] online\n
});
master.Events().OnSlaveLost([](uint16_t si) {
printf("[从站%d] 离线\n", si); // [Slave%d] offline\n
});
The offline event with reason classification and delivery-time evidence (OnSlaveOfflineDetailed), and the conflicting event delivered instead when the evidence disproves offline (OnSlaveOfflineDisputed), both hang off the master MasterEvents.
Input data changes
The old InputDataChanged event relied on the SDK layer comparing the input PDO bytes every cycle. When you need to detect input changes, the recommended path is to map the inputs once with darra::SlavePDO::InputsMapping<T> and reference the real-time process image directly, polling the field and comparing it with the previous value; you can also take a whole-frame snapshot of the current generation every cycle with CopyInputFrame and compare it (the snapshot is not zero-copy).
Detecting changes by polling the process image
You can also take a CopyInputFrame generation whole-frame snapshot every cycle and compare it with the previous value:
#pragma pack(push, 1)
struct ServoInput {
uint16_t statusWord;
int32_t actualPosition;
int32_t actualVelocity;
};
#pragma pack(pop)
ServoInput prev{};
std::vector<uint8_t> inFrame;
while (running) {
if (darra::SlavePDO::CopyInputFrame(dll, master.MasterNumber(), 1, inFrame) &&
inFrame.size() >= sizeof(ServoInput)) {
ServoInput input{};
std::memcpy(&input, inFrame.data(), sizeof(input));
if (std::memcmp(&input, &prev, sizeof(ServoInput)) != 0) {
prev = input;
printf("位置变化: %d\n", input.actualPosition); // Position changed: %d\n
}
}
std::this_thread::sleep_for(std::chrono::milliseconds(10));
}
DC sync lost
master.Events().OnDCSyncLost([](uint16_t mi, uint16_t si, int diffNs) {
printf("[从站%d] DC 同步丢失: 偏差 %dns\n", si, diffNs); // [Slave%d] DC sync lost: deviation %dns\n
});
PDO cycle callback
master.Events().SetPDOCallbackSync([&](uint16_t mi) {
std::vector<uint8_t> inFrame;
darra::SlavePDO::CopyInputFrame(dll, master.MasterNumber(), 1, inFrame);
});
PDO frame loss
master.Events().OnPDOFrameLoss([](uint16_t mi, uint8_t group,
uint32_t consecutive, uint32_t total) {
printf("组%d 丢帧: 连续=%u, 总计=%u\n", group, consecutive, total); // Group%d frame loss: consecutive=%u, total=%u\n
});
Thread safety
Event callbacks do not fire on the main thread: the PDO cycle callback is executed by a single NORMAL worker, and the remaining events are executed in sequence on the event dispatch thread (callbacks of SlaveEvents additionally hold their own mutex, see the previous section). Updating shared data requires synchronization:
#include <atomic>
#include <queue>
#include <mutex>
// Option 1: atomic variable (good for simple data)
std::atomic<int32_t> shared_position{0};
master.Events().SetPDOCallbackSync([&](uint16_t mi) {
auto& slave = master.GetSlave(1);
uint8_t buf[64];
int bytes = slave.ReadInputDirect(buf, sizeof(buf));
if (bytes >= 6) {
int32_t pos;
std::memcpy(&pos, buf + 2, 4);
shared_position.store(pos, std::memory_order_release);
}
});
// Option 2: queue (good for complex data) - enqueue inside the synchronous PDO callback
std::queue<ServoInput> dataQueue;
std::mutex queueMutex;
master.Events().SetPDOCallbackSync([&](uint16_t mi) {
std::vector<uint8_t> inFrame;
if (darra::SlavePDO::CopyInputFrame(dll, master.MasterNumber(), 1, inFrame) &&
inFrame.size() >= sizeof(ServoInput)) {
ServoInput input{};
std::memcpy(&input, inFrame.data(), sizeof(input));
std::lock_guard<std::mutex> lock(queueMutex);
dataQueue.push(input);
}
});
Avoid long-running work in callbacks. If you need to process large amounts of data, put the data into a queue and handle it asynchronously.
Full example
#include "ethercat.hpp"
#include <cstdio>
#include <atomic>
using namespace darra;
#pragma pack(push, 1)
struct ServoInput {
uint16_t statusWord;
int32_t actualPosition;
int32_t actualVelocity;
};
#pragma pack(pop)
int main() {
EtherCATMaster master(dll);
master.SetNetwork("\\Device\\NPF_{...}")
.SetENI("config.deni")
.Build();
auto& ev = master.Events();
// ===== Slave state events (register with On*()) =====
ev.OnSlaveStateChanged([](uint16_t mi, uint16_t si,
EcState o, EcState n) {
printf("[从站%d] 状态: %s -> %s\n", si, // [Slave%d] state: %s -> %s\n
EcStateFormat::Format(o).c_str(),
EcStateFormat::Format(n).c_str());
});
ev.OnEmergency([](uint16_t mi, uint16_t si,
uint16_t ec, uint16_t er,
uint8_t b1, uint16_t w1, uint16_t w2) {
printf("[从站%d] 紧急消息: 0x%04X\n", si, ec); // [Slave%d] emergency message: 0x%04X\n
});
ev.OnSlaveDiscovered([](uint16_t si) {
printf("[从站%d] 上线\n", si); // [Slave%d] online\n
});
ev.OnSlaveLost([](uint16_t si) {
printf("[从站%d] 离线\n", si); // [Slave%d] offline\n
});
ev.OnDCSyncLost([](uint16_t mi, uint16_t si, int diff) {
printf("[从站%d] DC 同步丢失: %dns\n", si, diff); // [Slave%d] DC sync lost: %dns\n
});
// ===== PDO cycle notification (delivered by a separate worker, carries no FSoE / same-cycle safety loop; read inputs from a CopyInputFrame snapshot) =====
ev.SetPDOCallbackSync([&](uint16_t mi) {
std::vector<uint8_t> inFrame;
if (darra::SlavePDO::CopyInputFrame(dll, master.MasterNumber(), 1, inFrame) &&
inFrame.size() >= sizeof(ServoInput)) {
ServoInput input{};
std::memcpy(&input, inFrame.data(), sizeof(input));
printf("[从站1] 位置: %d\n", input.actualPosition); // [Slave1] position: %d\n
}
});
// ===== PDO frame loss =====
ev.OnPDOFrameLoss([](uint16_t mi, uint8_t group,
uint32_t consecutive, uint32_t total) {
printf("组%d 丢帧: 连续=%u, 总计=%u\n", group, consecutive, total); // Group%d frame loss: consecutive=%u, total=%u\n
});
master.SetState(EcState::OP);
master.Start();
getchar();
return 0;
}
Unsubscribing
| Level | Unsubscribe entry | Description |
|---|---|---|
| Master event slot | master.Events().RemoveCallback(EventKind, index) | Remove a single subscriber by event slot + 0-based index; for the slot table see Master events |
| Master clear all | master.Events().RemoveAll() / ClearAll() | Clear all event slots at once, and clear the slave offline reason registry |
| Slave event set | slaveEvents.RemoveAll() / ClearAll() | SlaveEvents has only a clear-all entry, no per-subscriber removal method |
| PDO cycle subscription | master.Events().RemoveAll() / PreparePDOForDispose(timeoutMs) | SetPDOCallbackSync is not in an EventKind slot and cannot be removed individually |
The lifetime of a SlaveEvents instance must cover the subscription period: call ClearAll() before destroying it and detach it from the RegisterSlaveEvents routing table (or clear the master events first), otherwise callbacks may land on a destructed object. Do not call these unsubscribe methods from inside a callback (dispatch holds the lock, and std::mutex is not reentrant).