Events
All master-level events are subscribed through master.Events.
All event callbacks and the logging system are registered automatically at Build(); no manual calls are required.
The system logs every event automatically when it fires (except the PDO cyclic callback), whether or not it is subscribed. Critical runtime state is never lost silently.
The PDO cyclic callback (ProcessDataCyclicSync) is a high-frequency callback and is not logged.
Feature overview
| Category | Event | Read/write | Description | Auto logging |
|---|---|---|---|---|
| PDO cyclic callback | master.Events.ProcessDataCyclicSync | Read-only | PDO cyclic callback (synchronous; for real-time control such as FSoE) | — |
| Initialization progress | master.OnInitProgress | Read-only | BuildAsync long-running progress messages (fired on a background thread, Action<string>) | — |
| State events | master.Events.StateChanged | Read-only | Master EtherCAT state change (including fault degradation) | ✓ |
| master.StateChanged | Read-only | Convenience entry point for the same event (attached directly to the master instance, forwarded to master.Events.StateChanged) | ✓ | |
| master.Events.SlaveStateChanged | Read-only | Slave EtherCAT state change | ✓ | |
| Hot-plug events | master.Events.SlaveOffline | Read-only | Slave offline (disconnected) | ✓ |
| master.Events.SlaveOfflineDetailed | Read-only | Slave offline with rich context (delivered on the same tick as SlaveOffline; the payload carries time, reason and evidence) | ✓ | |
| master.Events.SlaveOnline | Read-only | Slave online (recovered) | ✓ | |
| master.Events.SlaveOfflineDisputed | Read-only | Offline marking contradicts delivery-time evidence (no offline event is delivered; this event is delivered instead) | ✓ | |
| master.Events.SlaveIdentityMismatch | Read-only | Slave identity mismatch (wrong model swapped in; the revision number takes no part in the check) | ✓ | |
| master.SlaveSnapshotRecovered | Read-only | Lightweight refresh after placeholder slave rows are re-read successfully (many rows recovering within one scan fires it once) | — | |
| Exception events | master.Events.EmergencyEventDetailed | Read-only | CoE Emergency message | ✓ |
| master.Events.SdoError | Read-only | SDO read/write failure (not fired on success) | ✓ | |
| master.Events.MailboxError | Read-only | Mailbox timeout / protocol error / channel closed | ✓ | |
| master.Events.DcEventRaised | Read-only | Unified DC state event stream (arming / sync window / reference clock / propagation delay / Hot-plug / convergence) | ✓ | |
| master.Events.DCSyncRestored | Read-only | DC lock-loss recovery edge (payload = slave + recovery time + lock-loss duration) | ✓ | |
| master.Events.WkcShortageOccurred | Read-only | Group WKC shortage (measured < expected, fired on entering the shortage edge) | ✓ | |
| master.Events.NicLinkChanged | Read-only | Master NIC link up/down edge (NIC name / MAC / time) | ✓ | |
| master.Events.PDOFrameLoss | Read-only | Consecutive PDO frame loss (tracked independently per group) | ✓ | |
| master.Events.DCSyncLost | Read-only | DC synchronization lost | ✓ | |
| Redundancy events | master.Events.RedundancyModeChanged | Read-only | Redundancy mode change (Inactive/Dual/Degraded) | ✓ |
| master.Events.SlavePortLinkChanged | Read-only | Slave port link change (P0-P3 down/recovered) | ✓ | |
| Logging | Logs.Updated | Read-only | Log data update notification | — |
The following logical events have no corresponding public event in C#; this page does not invent APIs:
- Slave PreOp reconfiguration event: C#
MasterEventsdoes not expose it (PreOp replay is handled automatically by the SDK). - Generic error / generic warning callbacks: C# errors go through the specific events
SdoError/MailboxError/DcEventRaised; there is no aggregate entry point.
SDK events are organized into four categories: state (state transitions / online and offline / redundancy / port link), mailbox protocols (EMCY / SDO / FoE / SoE / AoE / FSoE notifications), process data (cyclic callback / frame loss), and fault diagnostics (DC synchronization / identity mismatch / mailbox errors). This page groups them by usage scenario.
Initialization progress
OnInitProgress
public event Action<string>? OnInitProgress;
BuildAsync reports progress item by item during the long-running build ("scanning" / "configuring" / "entering OP" and so on). It is equivalent to the IProgress<string> parameter of BuildAsync(progress, ct); both are best-effort: if one subscriber throws, only that subscriber is skipped and the main build flow is unaffected.
This event fires on a background thread; marshal it yourself before updating the UI (WPF Dispatcher.Invoke / WinForms Control.Invoke).
master.OnInitProgress += msg => Console.WriteLine(msg);
var result = await master.BuildAsync();
PDO cyclic callback
PDO process data is exchanged by the real-time engine. The preferred path is to map InputsMapping / OutputsMapping once after entering OP, so the ref stays pinned to the process image and any thread can read the fields directly (read-only on the input side; writing a field on the output side sends it on the bus). CopyInputPdo / WriteOutputPdo are snapshot alternatives. ProcessDataCyclicSync is for application logic that must align with the cycle (including FSoE); C# forbids lambda capture of ref locals (CS8175), so inside the callback either map again on the spot (slave.PDO.InputsMapping<T>(), still zero-copy) or keep the control law in your own loop and read/write the mapping directly.
ProcessDataCyclicSync
public event ProcessDataCyclicSyncEventHandler? ProcessDataCyclicSync;
// delegate void ProcessDataCyclicSyncEventHandler(ushort masterIndex);
Fires once per PDO cycle (synchronous mode). The callback runs directly on the real-time thread: latency is lowest, but the callback must return quickly.
Do not perform time-consuming work in the synchronous callback (such as SDO reads or writes, file I/O, waiting on locks); it blocks the real-time thread and causes frame loss.
The code below shows the PDO write only. 0x000F must only be held after the sequence 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 (pinned zero-copy; a lambda cannot capture a ref local, so map once inside the callback body):
master.Events.ProcessDataCyclicSync += (masterIndex) =>
{
ref readonly ServoInput input = ref slave.PDO.InputsMapping<ServoInput>();
ref ServoOutput output = ref slave.PDO.OutputsMapping<ServoOutput>();
output.ControlWord = 0x000F;
output.TargetPosition = input.ActualPosition;
};
Snapshot alternative (copy on every cycle; the copied struct does not change by itself):
byte[] inputFrame = new byte[slave.InputsByteCount];
byte[] outputFrame = new byte[slave.OutputsByteCount];
master.Events.ProcessDataCyclicSync += (masterIndex) =>
{
if (slave.CopyInputPdo(inputFrame, out int copied, out int required) != PdoIoStatus.Success
|| copied != required)
return;
var input = MemoryMarshal.Read<ServoInput>(inputFrame);
var output = new ServoOutput { ControlWord = 0x000F, TargetPosition = input.ActualPosition };
MemoryMarshal.Write(outputFrame, ref output);
slave.WriteOutputPdo(outputFrame, out _, out _);
};
State events
Master.StateChanged
master.Events.StateChanged += (sender, e) => { };
// EventHandler<StateChangedEventArgs>
Fires when the master's EtherCAT state changes (both deliberate switches and fault degradation). Always logged automatically. This event reflects only the master's own EcState and is independent of individual slave states (slave.Events.StateChanged) and of the FSoE safety connection state (slave.FSoE.StateChanged).
Callback parameters:
public class StateChangedEventArgs
{
public EcState OldState { get; } // state before the change
public EcState NewState { get; } // state after the change
}
Example:
master.Events.StateChanged += (sender, e) =>
{
Console.WriteLine($"主站状态: {e.OldState} → {e.NewState}"); // Master state: {e.OldState} → {e.NewState}
};
SlaveStateChanged
master.Events.SlaveStateChanged += (masterIndex, slaveIndex, oldState, newState) => { };
// delegate void SlaveStateChangeEventHandler(ushort masterIndex, ushort slaveIndex, EcState oldState, EcState newState);
Fires when a slave's EtherCAT state changes. Monitored automatically in the background. Always logged automatically.
Callback parameters:
masterIndex(ushort) — master indexslaveIndex(ushort) — slave index (1-based)oldState(EcState) — state before the changenewState(EcState) — state after the change
Example:
master.Events.SlaveStateChanged += (masterIndex, slaveIndex, oldState, newState) =>
{
Console.WriteLine($"从站 {slaveIndex}: {oldState} → {newState}"); // Slave {slaveIndex}: {oldState} → {newState}
var slave = master.Slaves[slaveIndex - 1];
if (slave.ErrorCode != EcALState.NoError)
Console.WriteLine($" 错误码: {slave.ErrorCode}"); // error code: {slave.ErrorCode}
};
slave.ErrorCode reads the AL Status Code and returns the specific reason a state transition failed.
Hot-plug events
SlaveOffline
master.Events.SlaveOffline += (slaveIndex) => { };
// delegate void SlaveOfflineEventHandler(ushort slaveIndex);
Slave offline event. Fires when a Hot-plug link drops; the recovery state machine built into the PDO cycle restores the slave automatically (no PDO impact). Always logged automatically.
Example:
master.Events.SlaveOffline += (slaveIndex) =>
{
Console.WriteLine($"从站 {slaveIndex} 离线"); // Slave {slaveIndex} offline
};
SlaveOnline
master.Events.SlaveOnline += (slaveIndex) => { };
// delegate void SlaveOnlineEventHandler(ushort slaveIndex);
Slave online event. Fires when Hot-plug recovers. Always logged automatically.
Example:
master.Events.SlaveOnline += (slaveIndex) =>
{
Console.WriteLine($"从站 {slaveIndex} 上线"); // Slave {slaveIndex} online
};
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 classifies the case. The classification result is SlaveOfflineReason.
Related structure:
public enum SlaveOfflineReason : byte
{
Unknown = 0, // insufficient evidence — do not invent a real offline
RealOffline = 1, // really offline — process data confirmed not contributing, or the probe confirmed loss
Unreachable = 2 // not confirmed by the service side — the service side / probe did not see it, but process data is confirmed contributing
}
Evidence one: the measured three-state probe result SlaveProbeState (a real-response window of ≤2.52s):
Related structure:
public enum SlaveProbeState : byte
{
NotResponding = 0, // probe measured loss (no reply in N consecutive windows)
Responding = 1, // probe measured a reply (positive evidence of being online)
Unknown = 2 // insufficient evidence (interface missing / not measured / read failed)
}
Evidence two: process data contribution WcContribution (this cycle's image). Contributed = confirmed to be contributing WKC this cycle; NotContributed = confirmed not contributing; Unknown = this cycle's image is not ready 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 declared a loss but the delivery-time evidence contradicts offline (process data is still confirmed contributing), the SDK does not deliver SlaveOffline, nor the slave-level slave.Events.Offline; it delivers SlaveOfflineDisputed instead. Event semantics must match the evidence they carry: an event cannot say "offline" while carrying "process data still contributing".
master.Events.SlaveOfflineDisputed += (sender, e) => { };
// EventHandler<SlaveOfflineEventArgs>, payload type identical to SlaveOfflineDetailed
SlaveOfflineDetailed is the normal offline event with rich context, delivered on the same tick as SlaveOffline; when the evidence contradicts offline, neither is delivered.
Callback parameters (SlaveOfflineEventArgs):
public sealed class SlaveOfflineEventArgs : EventArgs
{
public ushort MasterIndex { get; } // master index
public ushort SlaveIndex { get; } // slave index (1-based)
public DateTime TimestampUtc { get; } // event time (UTC); also the read time of the evidence in this payload
public SlaveOfflineReason Reason { get; }
public SlaveProbeState Probe { get; }
public WcContribution Contribution { get; }
}
Consumers use it to report "suspected brief interruption / 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 SlaveOffline.
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,
SlaveOnlineis not delivered (online and offline stay strictly paired).
Reason lookup:
public bool TryGetSlaveOfflineReason(ushort slaveIndex, out SlaveOfflineReason reason)
public IReadOnlyDictionary<ushort, SlaveOfflineReason> GetSlaveOfflineReasons()
TryGetSlaveOfflineReason lets a UI that started after the offline event, or re-subscribed midway, fetch the reason classification; 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 SlaveOfflineDisputed is delivered; IsSlaveOffline and the lost-slave count keep their existing meaning.
Example:
master.Events.SlaveOfflineDisputed += (sender, e) =>
{
Console.WriteLine($"从站 {e.SlaveIndex} 掉站标记与证据不符: " + // Slave {e.SlaveIndex} slave-loss flag contradicts the evidence:
$"探针={e.Probe}, PD贡献={e.Contribution}, 证据时刻={e.TimestampUtc:O}"); // probe={e.Probe}, PD contribution={e.Contribution}, evidence timestamp={e.TimestampUtc:O}
// report "suspected brief interruption" only; do not set red / stop the line
};
if (master.Events.TryGetSlaveOfflineReason(2, out var reason))
Console.WriteLine($"从站 2 离线原因: {reason}"); // Slave 2 offline reason: {reason}
IsSlaveOffline(ushort slaveIndex)
public bool IsSlaveOffline(ushort slaveIndex)
Queries whether the event system has confirmed the slave as offline.
Parameters:
slaveIndex(ushort) — slave index
Returns:
bool—trueif the slave is offline
Example:
if (master.Events.IsSlaveOffline(2))
Console.WriteLine("从站 2 处于离线状态"); // Slave 2 is offline
HasSlaveEnteredOp(ushort slaveIndex)
public bool HasSlaveEnteredOp(ushort slaveIndex)
Queries whether the slave has ever entered OP during this run (latched by the slave state change callback: it becomes true after the first entry and stays true after the slave drops out of OP again). For a slave that has never entered OP, use slave.ErrorCode to look up the specific reason.
Parameters:
slaveIndex(ushort) — slave index (1-based)
Returns:
bool—trueif the slave has ever entered OP
Example:
if (!master.Events.HasSlaveEnteredOp(3))
Console.WriteLine($"从站 3 未进过 OP: {master.Slaves[2].ErrorCode}"); // Slave 3 never reached OP: {master.Slaves[2].ErrorCode}
SlaveIdentityMismatch
master.Events.SlaveIdentityMismatch += (sender, args) => { };
// EventHandler<SlaveIdentityMismatchEventArgs>
Fires after a slave is power-cycled and re-plugged with a mismatched identity: the Vendor/Product read by the EtherCAT identification state machine do not match the configuration. Always logged automatically.
The revision number (Revision) does not take part in rejection: by default matching runs under IgnoreRevision, and as long as Vendor + Product match the device is taken to be the same one. To fold the revision number into the check, change master.Config.ScanRevisionMatch: Exact requires an identical revision number, CompatibleHigher requires the actual revision number to be ≥ the configured value. Note that this setting only takes effect when C# parses the configuration file itself; with any other configuration-loading path it does not take part in matching, the SDK writes a warning entry to the log, and this run still matches under IgnoreRevision.
After it fires, 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 has checked or replaced the device, call master.AcknowledgeSlaveReplacement to make the SDK probe again.
Callback parameters (SlaveIdentityMismatchEventArgs):
public class SlaveIdentityMismatchEventArgs
{
public ushort MasterIndex { get; } // master index
public ushort SlaveIndex { get; } // slave index (1-based)
public uint ExpectedVendor { get; } // vendor ID expected from the configuration
public uint ExpectedProduct { get; } // product code expected from the configuration
public uint ExpectedRevision { get; } // revision number expected by the configuration (for reference only; not part of the identity check)
public uint ActualVendor { get; } // actual vendor ID
public uint ActualProduct { get; } // actual product code
public uint ActualRevision { get; } // actual revision
public DateTime TimestampUtc { get; } // event time (UTC)
}
Example:
master.Events.SlaveIdentityMismatch += (sender, args) =>
{
Console.WriteLine($"从站 {args.SlaveIndex} 身份不符:"); // Slave {args.SlaveIndex} identity mismatch:
Console.WriteLine($" 期望: Vendor=0x{args.ExpectedVendor:X8}, Product=0x{args.ExpectedProduct:X8}, Rev=0x{args.ExpectedRevision:X8}"); // expected: Vendor=0x{args.ExpectedVendor:X8}, Product=0x{args.ExpectedProduct:X8}, Rev=0x{args.ExpectedRevision:X8}
Console.WriteLine($" 实际: Vendor=0x{args.ActualVendor:X8}, Product=0x{args.ActualProduct:X8}, Rev=0x{args.ActualRevision:X8}"); // actual: Vendor=0x{args.ActualVendor:X8}, Product=0x{args.ActualProduct:X8}, Rev=0x{args.ActualRevision:X8}
// ask the user to swap back the correct device in the UI, then call master.AcknowledgeSlaveReplacement(args.SlaveIndex)
};
Entering IDENT_REJECTED for the same slave fires the event only once. Calling AcknowledgeSlaveReplacement resets probing; if the identity still does not match, the event fires again.
master.SlaveSnapshotRecovered
public event Action<DarraEtherCAT> SlaveSnapshotRecovered;
While the link is still being established and the SDK cannot read a station yet, it keeps a placeholder row for the corresponding slave index (state unknown / not identified) and fills it in during later scans. When a placeholder row has been re-read successfully, this event fires to tell subscribers to rebuild the slave tree / topology immediately, so "unknown" does not stay on screen forever.
- Many rows recovering within one scan fires it only once; the argument is the master instance.
- The callback runs synchronously on the scan sampling thread: subscribers may only signal the UI (for example
BeginInvoke) and must not perform blocking SDK reads inside the callback. - Multicast isolation per subscriber: if one subscriber throws, only that subscriber is skipped; the others still receive the event.
master.SlaveSnapshotRecovered += m =>
dispatcher.BeginInvoke(() => RebuildSlaveTree(m));
Exception events
The cycle follows the DENI/LoopCycle setting and can be as short as 125 µs — it is not hard-wired to 1ms. Diagnostics.RTcnt should match 1e9/LoopCycleNs. If it deviates from the setting by ±20% continuously, or max jitter exceeds 25% of the cycle, you must log it and raise a UI alarm. Also check PDOFrameLoss and DCSyncLost. If isolation is not in effect, larger jitter is the only acceptable consequence; a drifting cycle must never go unreported. Do not perform alarm I/O on the PDO data path.
EmergencyEventDetailed
master.Events.EmergencyEventDetailed += (sender, e) => { };
// delegate void EventHandler<EmergencyEventDetailedEventArgs>(object? sender, EmergencyEventDetailedEventArgs e);
CoE Emergency message event. Sent when slave firmware detects an error; the data format follows the CANopen Emergency protocol (CiA 301). Always logged automatically.
Slave event entry points (EMCY / offline / online / DC sync lost / port link change) validate the index first: slaveIndex == 0 is the master aggregate row (SOEM ec_slave[0]), not a slave, so the SDK drops it and logs a Warning; it never enters slave event routing.
Related structure:
public sealed class EmergencyEventDetailedEventArgs : EventArgs
{
public ushort MasterIndex { get; } // master index
public ushort SlaveIndex { get; } // source slave index (1-based)
public ushort ErrorCode { get; } // error code (CANopen Emergency Error Code, object 0x603F)
public ushort ErrorReg { get; } // error register (object 0x1001)
public byte B1 { get; } // manufacturer-specific data (byte 3)
public ushort W1 { get; } // manufacturer-specific data (bytes 4-5)
public ushort W2 { get; } // manufacturer-specific data (bytes 6-7)
public DateTime TimestampUtc { get; } // UTC time recorded on the event
}
Common Emergency Error Codes:
0x0000— error reset0x1000— generic error0x2000— current error0x3000— voltage error0x4000— temperature error0x5000— device hardware error0x6000— device software error0x7000— additional module error0x8000— monitoring error (communication)0xFF00— manufacturer-specific error
Example:
master.Events.EmergencyEventDetailed += (sender, e) =>
{
Console.WriteLine($"从站 {e.SlaveIndex} 紧急消息: 错误码=0x{e.ErrorCode:X4}, 寄存器=0x{e.ErrorReg:X2}"); // Slave {e.SlaveIndex} emergency message: error code=0x{e.ErrorCode:X4}, register=0x{e.ErrorReg:X2}
};
SdoError
master.Events.SdoError += (sender, args) => { };
// event EventHandler<SdoErrorEventArgs>
Fires when an SDO read/write fails (WKC=0 with no response / Abort / timeout); it does not fire on success. The failure is logged first, then dispatched asynchronously through the thread pool.
Event parameters:
SlaveIndex(ushort) — slave index (1-based)Index(ushort) /SubIndex(byte) — the object that failedIsWrite(bool) —true= write failure,false= read failureError(SDOError) — enum mapped from the Abort Code; a transport-level failure (the device sent no abort code) isSDOProtocolTimeout (0x05040000);GeneralError (0x08000000)only means the device really returned that codeAbortCode(uint) — raw Abort Code;0means a non-Abort failure (WKC=0 / timeout)TimestampUtc(DateTime) — event time (UTC)
Example:
master.Events.SdoError += (_, args) =>
Console.WriteLine($"SDO {(args.IsWrite ? "写" : "读")}失败 从站{args.SlaveIndex} " + // SDO {(args.IsWrite ? "write" : "read")} failed, slave {args.SlaveIndex}
$"0x{args.Index:X4}:{args.SubIndex:X2} abort=0x{args.AbortCode:X8} {args.Error}");
MailboxError
master.Events.MailboxError += (sender, args) => { };
// event EventHandler<MailboxErrorEventArgs>
Fires on mailbox transaction-level failures (timeout / protocol error / dead letter when the channel closes). Wired up: mailbox transaction failures (timeout, protocol error, invalidated when the channel closes), CoE mailbox queue transactions invalidated by a channel close, and SDO Information (object dictionary) transaction failures all raise this event at their failure exit — once per transaction-level failure (a batch invalidated by a channel close is aggregated into one event, so the log is not flooded). CoE SDO-level failures are reported separately by SdoError and are not repeated through this event.
Event parameters:
SlaveIndex(ushort) — slave index (1-based)Protocol(MailboxType) —CANopenOverEtherCAT/FileOverEtherCAT/ServoOverEtherCAT/ADSOverEtherCAT/EthernetOverEtherCAT/VendorOverEtherCATKind(MailboxErrorKind) —Timeout/ProtocolError/ChannelClosedDetail(string) — readable detail (error code / context)TimestampUtc(DateTime) — event time (UTC)
DcEventRaised
master.Events.DcEventRaised += (sender, args) => { };
// EventHandler<DcEventArgs>
Unified DC state event stream: arming success / failure rollback, no SYNC0 period unit, window exceeded / recovered, reference clock switch / freeze, propagation delay re-measure / reuse / invalidate, Hot-plug recovery, convergence too slow / severely overdue. It fires when the corresponding DC state event occurs (the emitter side already debounces and rate-limits by its own rules).
Event parameters:
MasterIndex/SlaveIndex(ushort) — master / slave (for master-level events (reference clock / propagation delay) SlaveIndex=0)Code(DcEventCode) — event type enum (members frozen; the member name is the event name)Params(string) — raw event parameters (for diagnostics)TimestampUtc(DateTime) — event time (UTC)
It does not replace the strongly typed edges DCSyncLost / DCSyncRestored; you can subscribe to both.
DCSyncRestored
master.Events.DCSyncRestored += (sender, args) => { };
// EventHandler<DCSyncRestoredEventArgs>
DC lock-loss recovery edge (the same edge as the sync window recovery event): a slave recovers from out-of-sync back into the sync window.
Event parameters:
MasterIndex/SlaveIndex(ushort)TimestampUtc(DateTime) — recovery time (UTC)LostDuration(TimeSpan) — lock-loss duration (from loss of sync until recovery)
WkcShortageOccurred
master.Events.WkcShortageOccurred += (sender, args) => { };
// EventHandler<WkcShortageEventArgs>
Group WKC shortage (measured < expected; a mapped slave is not contributing). Edge detection: fires when a shortage starts or the shortage value changes; a persistent shortage does not repeat and flood the log.
Event parameters:
MasterIndex(ushort) /Group(byte) — group number 0-7ActualWkc/ExpectedWkc(ushort) — measured / expectedTimestampUtc(DateTime)
NicLinkChanged
master.Events.NicLinkChanged += (sender, args) => { };
// EventHandler<NicLinkChangedEventArgs>
Master NIC link up/down edge (detected from NIC link-state changes).
Event parameters:
MasterIndex(ushort) /AdapterName(string) /Mac(string)IsUp(bool) — true=up, false=downTimestampUtc(DateTime)
Timestamped variants (XxxDetailed)
Existing events keep their original signatures; a rich-context event on the same tick is delivered in addition (payload style matches SlaveOfflineEventArgs; all carry TimestampUtc):
| Existing event | Timestamped variant |
|---|---|
| SlaveStateChanged | SlaveStateChangedDetailed |
| SlaveOnline | SlaveOnlineDetailed |
| EmergencyEvent | EmergencyEventDetailed |
| PDOFrameLoss | PDOFrameLossDetailed |
| DCSyncLost | DCSyncLostDetailed |
| RedundancyModeChanged | RedundancyModeChangedDetailed |
| SlavePortLinkChanged | SlavePortLinkChangedDetailed |
| SlaveOffline | SlaveOfflineDetailed (existing) |
Payload fields of each variant (all read-only properties):
| Variant | Fields |
|---|---|
| SlaveStateChangedDetailed | MasterIndex / SlaveIndex / OldState / NewState / TimestampUtc |
| SlaveOnlineDetailed | MasterIndex / SlaveIndex / TimestampUtc |
| EmergencyEventDetailed | MasterIndex / SlaveIndex / ErrorCode / ErrorReg / B1 / W1 / W2 / TimestampUtc |
| PDOFrameLossDetailed | MasterIndex / Group / ConsecutiveLostCount / TotalLostCount / TimestampUtc |
| DCSyncLostDetailed | MasterIndex / SlaveIndex / DiffNs / TimestampUtc |
| RedundancyModeChangedDetailed | MasterIndex / OldMode / NewMode / TimestampUtc |
| SlavePortLinkChangedDetailed | MasterIndex / SlaveIndex / Port / IsUp / TimestampUtc |
SdoErrorEventArgs / MailboxErrorEventArgs / SlaveIdentityMismatchEventArgs gained a TimestampUtc property without breaking changes (the old constructors fill it with the construction time; separate timestamped constructor overloads are also available). StateChangedEventArgs keeps the two properties OldState / NewState and has no time field.
PDOFrameLoss
master.Events.PDOFrameLoss += (masterIndex, group, consecutiveLostCount, totalLostCount) => { };
// delegate void PDOFrameLossEventHandler(ushort masterIndex, byte group,
// uint consecutiveLostCount, uint totalLostCount);
PDO consecutive frame loss event. Fires when consecutive lost frames reach the threshold; a single lost frame is only counted and does not fire. Each group is tracked independently. Always logged automatically.
Callback parameters:
masterIndex(ushort) — master indexgroup(byte) — group number where the loss occurred (0-7), corresponding to slave groupingconsecutiveLostCount(uint) — consecutive lost frames in that grouptotalLostCount(uint) — total lost frames in that group
Example:
master.Events.PDOFrameLoss += (masterIndex, group, consecutive, total) =>
{
Console.WriteLine($"组 {group} 丢帧: 连续={consecutive}, 累计={total}"); // Group {group} frame loss: consecutive={consecutive}, total={total}
};
DCSyncLost
master.Events.DCSyncLost += (masterIndex, slaveIndex, diffNs) => { };
// delegate void DCSyncLostEventHandler(ushort masterIndex, ushort slaveIndex, int diffNs);
DC synchronization loss event. Fires once when a slave goes from in sync → out of sync (beyond the threshold); staying beyond the threshold does not fire again. Always logged automatically.
Callback parameters:
masterIndex(ushort) — master indexslaveIndex(ushort) — index of the out-of-sync slave (1-based)diffNs(int) — current time difference from the reference clock (nanoseconds)
Example:
master.Diagnostics.SyncWindowThreshold = 500; // 500ns
master.Events.DCSyncLost += (masterIndex, slaveIndex, diffNs) =>
{
Console.WriteLine($"从站 {slaveIndex} DC 同步丢失: 偏差 {diffNs}ns"); // Slave {slaveIndex} DC sync lost: deviation {diffNs}ns
};
slave.Diagnostics.DC.IsInSync and slave.Diagnostics.DC.SyncTimeDifference query the slave's current synchronization state.
DC state events (arming / sync window / reference clock / propagation delay / Hot-plug / convergence)
DC arming, window entry and exit, reference clock switch / freeze, propagation delay re-measure / reuse / invalidate, Hot-plug recovery, and slow convergence all enter the unified DC state event stream. Measured values are carried in the event payload as they are (0x0980 write / read-back, 0x09A0, difference, threshold, duration, propagation delay, AL code); never write value-less text such as "DC abnormal".
| Event | Level | Category | Read/write | Debounce | Key payload |
|---|---|---|---|---|---|
| Arming success | Message | DC event | Read-only | Fires only when the published arming mask changes; the same mask does not repeat | 0x0980 write / read-back, 0x09A0, ESI level, required mask, evidence strength |
| Arming failure / rollback | Warning | DC event | Read-only | Always fires the first time; at most one per 10 s while the failure persists | reason, whether it was rolled back, AL status / code, write WKC, 0x0980 read-back |
| No SYNC0 period unit | Message | DC event | Read-only | Once per (master, slave) | evidence that 0x0980 went unanswered for three consecutive cycles |
| Sync window exceeded | Warning | DC event | Read-only | Once on entry; at most one per 10 s while it persists | current difference, threshold, duration so far, consecutive ticks |
| Sync window recovered | Message | DC event | Read-only | Once per recovery (paired with sync window exceeded) | current difference, threshold, out-of-sync duration |
| Reference clock established / switched / lost | Message; Warning when warning=1 | DC event | Read-only | One per switch, minimum interval 1 s | old / new reference clock, level, reason |
| Reference clock frozen | Warning | DC event | Read-only | At most one per slave per 60 s | 1:1 ramp slope (ppm), current difference, duration |
| Propagation delay re-measured | Message | DC event | Read-only | Minimum interval 1 s | reason, station count, maximum propagation delay across the bus, session generation |
| Propagation delay reused | Debug | DC event | Read-only | Minimum interval 10 s; the same generation does not repeat | reason, station count, maximum propagation delay, generation |
| Propagation delay baseline invalidated | Message | DC event | Read-only | Minimum interval 1 s | reason; the next update must re-measure the whole bus |
| Recovery after Hot-plug | Message; Warning when warning=1 | DC event | Read-only | Minimum interval 2 s per slave | arming result, 0x0980 read-back, AL status / code, propagation delay |
Slow convergence (> 5 s) | Warning | DC event | Read-only | One per episode per 60 s; hard floor of 5 s between any two | duration so far, tick count, difference |
Severe convergence timeout (> 30 s) | Error | DC event | Read-only | Same as slow convergence | duration so far, tick count, difference |
Consumption channels: DC state events can be subscribed to as strongly typed events through master.Events.DcEventRaised; the same events also enter the read-only log view DarraEtherCAT.Logs (the log callback is registered automatically at Build(), no manual hook is needed), and can be consumed through DarraEtherCAT.Logs.Updated notifications or by iterating the view directly.
- The
master.Events.DCSyncLoststrongly typed callback is unchanged. It only covers the "in sync → out of sync" strongly typed subscription; this channel covers arming, window entry and exit, reference clock, propagation delay, Hot-plug, and convergence. The two are not substitutes and can be used at the same time. - Levels:
Message= ordinary event level, also emitted in production;Warning= alarm, also emitted in production;Error= severe (convergence over 30 s);Debug= reuse-type detail, not emitted in Release builds. - Debounce semantics: the emitter side has one slot per (master, slave) with atomic claim, so concurrent calls produce only one record; reference clock and propagation delay events are rate-limited independently (sharing one timestamp would suppress each other); convergence events are gated per episode — one per episode per 60 s, with at least 5 s between any two.
- Master-level events (reference clock / propagation delay) use the slave-index 0 slot and do not contend with slave-level events; a slave-level event passed with index 0 is rejected and only leaves a Debug hint.
- This channel does not change the public API, does not change the ABI, and adds no internal identifiers; internally it only does O(1) table lookups and low-frequency formatting, and must not poll on the hot path.
Redundancy events
RedundancyModeChanged
master.Events.RedundancyModeChanged += (masterIndex, oldMode, newMode) => { };
// delegate void RedundancyModeChangedEventHandler(ushort masterIndex, int oldMode, int newMode);
Fires when the redundancy operating mode changes. oldMode / newMode are RingMode enum values (0=Inactive, 1=Dual, 2=Degraded).
Example:
master.Events.RedundancyModeChanged += (masterIndex, oldMode, newMode) =>
{
Console.WriteLine($"冗余模式: {oldMode} → {newMode}"); // Redundancy mode: {oldMode} → {newMode}
};
SlavePortLinkChanged
master.Events.SlavePortLinkChanged += (masterIndex, slaveIndex, port, isUp) => { };
// delegate void SlavePortLinkChangedEventHandler(ushort masterIndex, ushort slaveIndex, byte port, bool isUp);
Fires when the physical link of a slave ESC port changes (one of P0-P3 goes down or recovers). A link edge may be reported once by each of several detection paths (1s diagnostic cycle / PDO cycle of about 100ms / topology model); the SDK remembers the last isUp per (slaveIndex, port) and delivers one user event per physical flip — repeated reports only produce Debug log entries. Always logged automatically.
Use it to pinpoint the faulty cable segment (if the facing ports of two adjacent slaves report a break at the same time, the cable between them is the problem).
Callback parameters:
masterIndex(ushort) — master indexslaveIndex(ushort) — slave index (1-based)port(byte) — port number0-3, corresponding toP0/P1/P2/P3isUp(bool) —true= link recovered,false= link down
Example:
master.Events.SlavePortLinkChanged += (masterIndex, slaveIndex, port, isUp) =>
{
string state = isUp ? "恢复" : "断开"; // up / down
Console.WriteLine($"从站 {slaveIndex} 端口 P{port} link {state}"); // Slave {slaveIndex} port P{port} link {state}
};
master.Diagnostics.BreakPoint / GetAllBreakPoints() provide an aggregated view of fault points (broken line + CRC errors). SlavePortLinkChanged is the raw event source, suitable for real-time alarms.
Unsubscribing
In C#, unsubscribe with -=. Delegate equality is decided by (target instance + method), so:
Named methods can simply be written twice:
master.Events.StateChanged += OnMasterStateChanged;
master.Events.StateChanged -= OnMasterStateChanged; // correctly removed
A lambda must be stored in a variable before you unsubscribe (every lambda you write creates a new delegate instance):
EventHandler<SlaveOfflineEventArgs> onOffline = (sender, e) =>
Console.WriteLine($"从站 {e.SlaveIndex} 离线"); // Slave {e.SlaveIndex} offline
master.Events.SlaveOfflineDetailed += onOffline;
// ...
master.Events.SlaveOfflineDetailed -= onOffline; // correctly removed
master.Events.StateChanged += (sender, e) => Handle(e);
master.Events.StateChanged -= (sender, e) => Handle(e); // ← will not remove; these are two different delegate objects
This compiles and does not fail at run time, yet the subscription stays forever — the symptom is "the window is closed but events keep arriving". Either use a variable or use a named method.
When you unsubscribe from ProcessDataCyclicSync, the SDK unregisters the synchronous callback after the last subscriber is removed, so the 1 kHz PDO path no longer carries extra callback overhead (subscribing again hooks it back automatically).
To remove everything, see ClearAll() in the next section.
Clearing event subscriptions
Events.ClearAll()
public void ClearAll()
Clears all master-level event subscriptions to prevent memory leaks. Call it before destroying or re-initializing the master.
Example:
// clear all events before disposal
master.Events.ClearAll();
master.Close();
The slave also has a slave.Events.ClearAll() method that clears all event subscriptions of that slave.
Delivery statistics
Events go through a process-wide dispatch queue. The two static counters below answer "why do I occasionally not receive an event"; read them for diagnostics only, they do not change any event behavior.
MasterEvents.EventsDropped
public static long EventsDropped { get; }
Number of events dropped so far by the process-wide event dispatch queue. The queue has an entry limit (10000); when it is exceeded, the oldest entry is dropped. This counter only increases.
Returns:
long— cumulative drop count;0= no event has ever been dropped because the queue was full
It uses the same count as the logging side's "one Warning per 1000 entries", so it can be taken directly as evidence that "events occasionally do not arrive": a rising value means callback processing cannot keep up with event production.
MasterEvents.TotalSubscriberFailures
public static long TotalSubscriberFailures { get; }
Cumulative number of subscriber callback failures in the process. When one subscriber throws, the SDK catches the exception and skips that subscriber; other subscribers are unaffected and event delivery is not interrupted. This counter records those caught failures.
Returns:
long— cumulative failure count
The warning log for an individual failure is rate-limited to one per 60 s; this counter is not affected by that limit — use it to find out "how many failures in total", and the log to find out "what the latest one looked like".
These two counters are process-wide static properties. Write MasterEvents.EventsDropped / MasterEvents.TotalSubscriberFailures directly; do not access them through a master.Events instance.
Example:
if (MasterEvents.EventsDropped > 0 || MasterEvents.TotalSubscriberFailures > 0)
Console.WriteLine($"事件丢弃 {MasterEvents.EventsDropped} 条," + // {MasterEvents.EventsDropped} events dropped,
$"订阅者回调失败 {MasterEvents.TotalSubscriberFailures} 次"); // subscriber callbacks failed {MasterEvents.TotalSubscriberFailures} times
Thread safety
Event callbacks fire on non-UI threads. Synchronize when updating the UI:
// WinForms
master.Events.SlaveOffline += (idx) =>
this.Invoke(() => labelStatus.Text = $"从站 {idx} 离线"); // Slave {idx} offline
// WPF
master.Events.SlaveOffline += (idx) =>
Dispatcher.Invoke(() => StatusText = $"从站 {idx} 离线"); // Slave {idx} offline
Full example
// ===== master state =====
master.Events.StateChanged += (sender, e) =>
Console.WriteLine($"主站: {e.OldState} → {e.NewState}"); // Master: {e.OldState} → {e.NewState}
//slave state
master.Events.SlaveStateChanged += (masterIndex, slaveIndex, oldState, newState) =>
{
var slave = master.Slaves[slaveIndex - 1];
Console.WriteLine($"从站 {slaveIndex}: {oldState} → {newState}"); // Slave {slaveIndex}: {oldState} → {newState}
if (slave.ErrorCode != EcALState.NoError)
Console.WriteLine($" 错误码: {slave.ErrorCode}"); // error code: {slave.ErrorCode}
};
// ===== Hot-plug =====
master.Events.SlaveOffline += (slaveIndex) =>
Console.WriteLine($"从站 {slaveIndex} 离线"); // Slave {slaveIndex} offline
master.Events.SlaveOnline += (slaveIndex) =>
Console.WriteLine($"从站 {slaveIndex} 上线"); // Slave {slaveIndex} online
// ===== exception events =====
master.Events.EmergencyEventDetailed += (sender, e) =>
Console.WriteLine($"从站 {e.SlaveIndex} 紧急消息: 0x{e.ErrorCode:X4}"); // Slave {e.SlaveIndex} emergency message: 0x{e.ErrorCode:X4}
master.Events.PDOFrameLoss += (masterIndex, group, consecutive, total) =>
Console.WriteLine($"组 {group} 丢帧: 连续={consecutive}, 累计={total}"); // Group {group} frame loss: consecutive={consecutive}, total={total}
master.Events.DCSyncLost += (masterIndex, slaveIndex, diffNs) =>
Console.WriteLine($"从站 {slaveIndex} DC 同步丢失: {diffNs}ns"); // Slave {slaveIndex} DC sync lost: {diffNs}ns
// ===== redundancy events =====
master.Events.RedundancyModeChanged += (masterIndex, oldMode, newMode) =>
Console.WriteLine($"冗余模式变化: {oldMode} → {newMode}"); // Redundancy mode change: {oldMode} → {newMode}
master.Events.SlavePortLinkChanged += (masterIndex, slaveIndex, port, isUp) =>
Console.WriteLine($"从站 {slaveIndex} P{port} link {(isUp ? "恢复" : "断开")}"); // Slave {slaveIndex} P{port} link {(isUp ? "up" : "down")}
// ===== Hot-plug identity mismatch =====
master.Events.SlaveIdentityMismatch += (sender, args) =>
Console.WriteLine($"从站 {args.SlaveIndex} 身份不符, 换设备后调用 AcknowledgeSlaveReplacement({args.SlaveIndex})"); // Slave {args.SlaveIndex} identity mismatch; after replacing the device call AcknowledgeSlaveReplacement({args.SlaveIndex})
// ===== PDO cyclic callback (synchronous; for real-time control such as FSoE; PDO data is usually polled directly from the process image pointer) =====
master.Events.ProcessDataCyclicSync += (masterIndex) =>
{
// real-time control per cycle
};