Skip to main content

Slave events

Accessed through slave.Events. Event arguments are pre-filtered to the current slave, keeping signatures concise.​

Automatic event routing

Master-level slave callbacks are routed automatically to the matching slave's slave.Events. Subscribing to slave events needs no masterIndex/slaveIndex arguments; the system already filters to the current slave.

Protocol-specific events

FSoE safety events are subscribed through slave.FSoE.

Feature overview​

CategoryEvent / methodRead/writeDescription
Slave state eventsslave.Events.StateChangedRead-onlySlave EtherCAT state change
slave.Events.StateChangedWithAlRead-onlySlave state change, carrying the AL code at the moment of the change (16-bit raw code + whether it is trustworthy)
slave.Events.EmergencyRead-onlyCoE Emergency message
slave.Events.OfflineRead-onlySlave offline (hot-plug disconnect)
slave.Events.OnlineRead-onlySlave online (hot-plug recovery)
slave.Events.DCSyncLostRead-onlyDC synchronization lost
PDO data changesslave.PDO.InputsMapping (onChanged overload) / ProcessDataCyclicSyncRead-onlyMap once to pin the page; the change callback notifies automatically, or compare fields in the cyclic callback
Protocol instance eventsPer-protocol instance events on slave.CoE / FoE / SoE / AoE / EoE / VoE / FSoERead-onlyProtocol-specific events (value changes / diagnostics / transfer progress / notifications / safety); see that section for trigger timing and payload

Slave state events​

Slave.StateChanged​

slave.Events.StateChanged += (oldState, newState) => { };
// Action<EcState, EcState>

Fires when the slave's EtherCAT state changes. Routed automatically from master.Events.SlaveStateChanged. This event reflects only this slave's EcState (Init/PreOp/SafeOp/OP) and is independent of the master global state (master.Events.StateChanged) and of the FSoE safety connection state (slave.FSoE.StateChanged).

Example:

slave.Events.StateChanged += (oldState, newState) =>
{
Console.WriteLine($"状态变化: {oldState} → {newState}"); // State change: {oldState} → {newState}
};

Slave.StateChangedWithAl​

slave.Events.StateChangedWithAl += (oldState, newState, alStatusCode, alStatusCodeKnown) => { };
// Action<EcState, EcState, ushort, bool>

Dispatched in parallel on the same tick with slave.Events.StateChanged, not replacing the old event; routed automatically from master.Events.SlaveStateChangedWithAl. alStatusCode is the full 16-bit AL Status Code "at the moment of the change", taken from a 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:

  • oldState (EcState) — old state
  • newState (EcState) — new state
  • alStatusCode (ushort) — AL Status Code at the moment of the change; meaningless when alStatusCodeKnown=false
  • alStatusCodeKnown (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.

Example:

slave.Events.StateChangedWithAl += (oldState, newState, alCode, known) =>
{
Console.WriteLine(known
? $"从站 {slave.SlaveNum}: {oldState} → {newState}, AL=0x{alCode:X4}" // Slave {slave.SlaveNum}: {oldState} → {newState}, AL=0x{alCode:X4}
: $"从站 {slave.SlaveNum}: {oldState} → {newState}, AL 码不可信"); // Slave {slave.SlaveNum}: {oldState} → {newState}, AL code not trustworthy
};

Slave.Emergency​

slave.Events.Emergency += (errorCode, errorReg, b1, w1, w2) => { };
// Action<ushort, ushort, byte, ushort, ushort>

CoE Emergency message. Routed automatically from master.Events.EmergencyEventDetailed.

Callback parameters:

// Action<ushort, ushort, byte, ushort, ushort>
errorCode, // ushort — error code (CANopen Emergency Error Code)
errorReg, // ushort — error register (object 0x1001)
b1, // byte — manufacturer-specific data (byte 3)
w1, // ushort — manufacturer-specific data (bytes 4-5)
w2 // ushort — manufacturer-specific data (bytes 6-7)

Example:

slave.Events.Emergency += (errorCode, errorReg, b1, w1, w2) =>
{
Console.WriteLine($"紧急消息: 错误码=0x{errorCode:X4}"); // Emergency message: error code=0x{errorCode:X4}
};

Slave.Offline​

slave.Events.Offline += () => { };
// Action

Slave offline (hot-plug disconnect). Routed automatically from master.Events.SlaveOffline.

Example:

slave.Events.Offline += () =>
{
Console.WriteLine("从站离线"); // Slave offline
};

Slave.Online​

slave.Events.Online += () => { };
// Action

Slave online (hot-plug recovery). Routed automatically from master.Events.SlaveOnline.

Example:

slave.Events.Online += () =>
{
Console.WriteLine("从站上线"); // Slave online
};

Slave.DCSyncLost​

slave.Events.DCSyncLost += (diffNs) => { };
// Action<int>

DC synchronization lost. Routed automatically from master.Events.DCSyncLost.

Example:

slave.Events.DCSyncLost += (diffNs) =>
{
Console.WriteLine($"DC 同步丢失: 偏差 {diffNs}ns"); // DC sync lost: deviation {diffNs}ns
};

Protocol instance events​

The mailbox protocol instances are exposed on slave.CoE / slave.FoE / slave.SoE / slave.AoE / slave.EoE / slave.VoE / slave.FSoE (created on demand, may be null — check before use). Event callbacks are dispatched asynchronously: each subscriber is isolated, and an exception thrown by one subscriber does not affect the others.

CoE.ValueChanged​

slave.CoE.ValueChanged += (sender, e) => { };
// EventHandler<CoEValueChangedEventArgs>

Trigger timing: the subscribed value changes. Subscribed objects are polled cyclically and fire as soon as the value differs from the previous one. Payload:

FieldTypeDescription
SlaveIndexushortSlave index
Index / SubIndexushort / byteObject that changed
OldValue / NewValuebyte[]Value before / after the change

CoE.DiagnosticMessageReceived​

slave.CoE.DiagnosticMessageReceived += (sender, e) => { };
// EventHandler<DiagnosticMessageEventArgs>

Trigger timing: ETG.1510 diagnostic messages. Diagnostic polling detects new diagnostic messages (after de-duplication). Payload: SlaveIndex (int), NewMessages (list of messages added in this round; each contains SubIndex / DiagCode / Flags / TextIndex / RawData / Timestamp / SlaveIndex).

FoE.ProgressChanged / FoE.BusyReceived​

slave.FoE.ProgressChanged += (sender, e) => { };   // EventHandler<FoEProgressEventArgs>
slave.FoE.BusyReceived += (sender, e) => { }; // EventHandler<FoEBusyEventArgs>

Trigger timing: ProgressChanged — once per data packet sent or received during file upload/download; BusyReceived — the slave returns a BUSY frame (reported cyclically during firmware flashing). Payload:

EventFields
ProgressChangedSlave, PacketNumber, DataSize, ProgressPercent, BusyDone, BusyEntire, BusyText
BusyReceivedSlaveIndex, Done, Entire, Text, RetryIndex, Percent (= Done/Entire)

SoE.NotificationReceived / SoE.EmergencyReceived​

slave.SoE.NotificationReceived += e => { };   // Action<SoENotificationEventArgs>
slave.SoE.EmergencyReceived += e => { }; // Action<SoEEmergencyEventArgs>

Trigger timing: NotificationReceived — the slave reports an IDN data change notification; EmergencyReceived — an SoE emergency frame is received. Payload:

EventFields
NotificationReceivedSlaveIndex, DriveNumber, IDN, ElementFlags, NewValue, OldValue
EmergencyReceivedSlaveIndex, DriveNumber, ErrorCode (Sercos emergency error code), Timestamp

AoE.Subscriptions.DataNotification / Error / SubscriptionStateChanged​

slave.AoE.Subscriptions.DataNotification += (sender, e) => { };          // EventHandler<AoENotificationEventArgs>
slave.AoE.Subscriptions.Error += (sender, e) => { }; // EventHandler<AoESubscriptionErrorEventArgs>
slave.AoE.Subscriptions.SubscriptionStateChanged += (sender, e) => { }; // EventHandler<AoESubscription>

Trigger timing: DataNotification — an ADS device notification arrives; Error — a subscription error occurs; SubscriptionStateChanged — a subscription is created / activated / removed. Payload:

EventFields
DataNotificationSubscriptionId, NotificationHandle, SlaveIndex, IndexGroup, IndexOffset, Data, Timestamp, DeviceTimestamp (100ns)
ErrorSubscriptionId, ErrorMessage, Exception, Timestamp
SubscriptionStateChangedId, IndexGroup, IndexOffset, DataLength, TransmissionMode, IsActive

EoE.FrameReceived​

slave.EoE.FrameReceived += (sender, e) => { };
// EventHandler<EoEFrameEventArgs>

Trigger timing: an EoE Ethernet frame arrives from the slave (the frame is copied and may be retained long-term). Payload: MasterIndex, SlaveIndex, Frame (the complete Ethernet frame), ReceivedAt (UTC).

VoE.NotificationReceived​

slave.VoE.NotificationReceived += (sender, e) => { };
// EventHandler<VoENotificationEventArgs>

Trigger timing: a vendor-defined mailbox frame is received. Payload: MasterIndex, SlaveIndex, VendorId, VendorType, Data (payload, copied), Timestamp (UTC).

FSoE safety connection events​

slave.FSoE.StateChanged += (sender, e) => { };       // EventHandler<FSoEStateChangedEventArgs>
slave.FSoE.ErrorOccurred += (sender, e) => { }; // EventHandler<FSoEErrorEventArgs>
slave.FSoE.FailsafeTriggered += (sender, e) => { }; // EventHandler<FSoEFailsafeEventArgs>
slave.FSoE.DataExchanged += (sender, e) => { }; // EventHandler<FSoEDataExchangeEventArgs>
slave.FSoE.DataExchange += () => { }; // Action (lightweight, per cycle)

Trigger timing: StateChanged — FSoE connection state transition (Reset/Session/Connection/Parameter/Data/Failsafe); ErrorOccurred — safety protocol error; FailsafeTriggered — entering or leaving failsafe; DataExchanged / DataExchange — after the data exchange of every PDO cycle. Payload:

EventFields
StateChangedSlaveIndex, ConnectionIndex, OldState, NewState, Timestamp
ErrorOccurredSlaveIndex, ConnectionIndex, Error, CurrentState, Description, Timestamp
FailsafeTriggeredSlaveIndex, ConnectionIndex, Reason, EnteringFailsafe, Timestamp
DataExchangedSlaveIndex, CurrentState, SafeInputs, SafeOutputs, InFailsafe, CycleCount, Timestamp
SafeDataUpdated does not exist in the C# SDK

Older documentation listed a slave.FSoE.SafeDataUpdated event (argument type FSoEDataUpdatedEventArgs); the current C# SDK does not have either member, so such a subscription does not compile. Use DataExchanged for safety data exchange.

PDO data changes​

Getting a notification only when something changed

slave.PDO.InputsMapping<T>(onChanged) / slave.PDO.InputsSliceMapping<T>(offset, onChanged) provide a built-in change callback (the SDK continuously compares the full frame in the background; the comparison does not run inside the PDO cycle), so there is no need to compare fields in a cyclic callback.

Struct mapping with cyclic sampling

After entering OP, map a packed struct onto the process image and compare fields in the cyclic callback (a lambda cannot capture a ref local, so take the mapping inside the callback body).

Example:

[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct InPdo
{
public ushort StatusWord;
public int ActualPosition;
public int ActualVelocity;
}

InPdo previous = default;

master.Events.ProcessDataCyclicSync += (mi) =>
{
ref readonly InPdo current = ref slave.PDO.InputsMapping<InPdo>();
if (current.ActualPosition != previous.ActualPosition)
Console.WriteLine($"位置变化: {previous.ActualPosition} -> {current.ActualPosition}"); // Position change: {previous.ActualPosition} -> {current.ActualPosition}
previous = current;
};
Module offset

For MDP modular devices, use slave.PDO.InputsSliceMapping<T>(offset) to map a struct from a module byte offset.

Unsubscribing​

In C#, unsubscribe with -= and pass the same method reference (delegate equality is decided by "target instance + method").

A named method can simply be written twice:

slave.Events.StateChanged += OnSlaveStateChanged;
slave.Events.StateChanged -= OnSlaveStateChanged; // correctly removed

A lambda must be stored in a variable before unsubscribing (every lambda expression creates a new delegate instance):

Action<EcState, EcState> onStateChanged = (oldState, newState) =>
Console.WriteLine($"{oldState} → {newState}");

slave.Events.StateChanged += onStateChanged;
// ...
slave.Events.StateChanged -= onStateChanged; // correctly removed

The same applies to protocol instance events (the events on slave.CoE / slave.FoE / slave.SoE / slave.AoE / slave.EoE / slave.VoE / slave.FSoE are all standard C# events and are unsubscribed with -=):

slave.FoE.ProgressChanged += onProgress;
slave.FoE.ProgressChanged -= onProgress;
A lambda cannot be unsubscribed
slave.Events.Offline += () => HandleOffline();
slave.Events.Offline -= () => HandleOffline(); // ← does not remove it; these are two different delegate objects

It compiles and runs without error, but the subscription stays forever. Use a variable or a named method.

To clear all subscriptions of this slave at once, use slave.Events.ClearAll() (events on protocol instances are cleared individually).

Thread safety​

Event callbacks fire on non-UI threads. Synchronize with the UI thread when updating it:

// take a value snapshot on the event thread first (a ref local cannot be captured in a lambda), then hand it to the UI thread
InPdo snapshot = slave.PDO.InputsMapping<InPdo>();

// WinForms
this.Invoke(() => labelValue.Text = $"位置: {snapshot.ActualPosition}"); // Position: {snapshot.ActualPosition}

// WPF
Dispatcher.Invoke(() => PositionText = $"位置: {snapshot.ActualPosition}"); // Position: {snapshot.ActualPosition}
warning

Avoid long-running work in callbacks. When large amounts of data must be processed, put it in a queue and handle it asynchronously:

master.Events.ProcessDataCyclicSync += (mi) =>
{
_dataQueue.Enqueue(slave.PDO.InputsMapping<InPdo>()); // enqueue a value snapshot without blocking the cycle
};

Full example​

var slave = master.Slaves[0];

// ===== slave state events =====
slave.Events.StateChanged += (oldState, newState) =>
Console.WriteLine($"状态: {oldState} → {newState}"); // State: {oldState} → {newState}

slave.Events.Emergency += (errorCode, errorReg, b1, w1, w2) =>
Console.WriteLine($"紧急消息: 0x{errorCode:X4}"); // Emergency message: 0x{errorCode:X4}

slave.Events.Offline += () =>
Console.WriteLine("从站离线"); // Slave offline

slave.Events.Online += () =>
Console.WriteLine("从站上线"); // Slave online

slave.Events.DCSyncLost += (diffNs) =>
Console.WriteLine($"DC 同步丢失: {diffNs}ns"); // DC sync lost: {diffNs}ns

// ===== PDO data changes (pinned page, zero-copy; compare fields in the callback) =====
InPdo previous = default;

master.Events.ProcessDataCyclicSync += (mi) =>
{
ref readonly InPdo current = ref slave.PDO.InputsMapping<InPdo>();
if (current.ActualPosition != previous.ActualPosition)
Console.WriteLine($"位置变化: {previous.ActualPosition} -> {current.ActualPosition}"); // Position change: {previous.ActualPosition} -> {current.ActualPosition}
previous = current;
};

// ===== FSoE safety events (protocol-specific) =====
if (slave.FSoE != null)
{
slave.FSoE.StateChanged += (sender, e) =>
Console.WriteLine($"FSoE: {e.OldState} → {e.NewState}");
}