Skip to main content

Slave events

Accessed through slave.events (a SlaveEvents object). Register callbacks with the add_* methods and remove them with the remove_* methods.​

Automatic event routing

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

Feature overview​

CategoryMethodRead/writeDescription
State eventsslave.events.add_state_changed()write-onlySlave EtherCAT state change
slave.events.add_state_changed_with_al()write-onlySlave state change, carrying the AL code at the moment of the change (16-bit raw code + whether it is trustworthy)
Emergencyslave.events.add_emergency()write-onlyCoE Emergency message
Hot-plugslave.events.add_offline() / add_online()write-onlySlave offline / online
DC synchronizationslave.events.add_dc_sync_lost()write-onlyDC synchronization lost
FSoEslave.events.add_fsoe_state_changed() and otherswrite-onlyFSoE safety events
Duplicate registration does not fire twice

Repeated add_*() of the same callback keeps a single entry (plain functions compare by identity, bound methods compare by (self, func) equality); passing None is ignored outright. The subscription table is snapshotted when an event fires, so adding or removing subscriptions inside a callback (or on another thread) neither loses events nor hits list changed size during iteration.

Slave state events​

add_state_changed()​

def add_state_changed(self, callback: Callable[[int, int], None]) -> None

Registers a listener for slave state changes. Callback arguments: (old_state, new_state).

Example:

slave = master[1]

def on_state_changed(old_state, new_state):
print(f"状态变化: 0x{old_state:02X} -> 0x{new_state:02X}") # State change: 0x{old_state:02X} -> 0x{new_state:02X}

slave.events.add_state_changed(on_state_changed)

add_state_changed_with_al()​

def add_state_changed_with_al(
self, callback: Callable[[int, int, int, bool], None]) -> None

Registers a listener for "slave state change + the AL code at the moment of the change". Callback arguments: (old_state, new_state, al_status_code, al_status_code_known). Dispatched on the same tick, side by side with add_state_changed(), not replacing the old listener; registering the same callback twice does not fire it twice.

The master-level entry point has the same name plus two index arguments: master.events.add_slave_state_changed_with_al(), with callback signature (master_index, slave_index, old_state, new_state, al_status_code, al_status_code_known).

al_status_code is 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.

al_status_code_known=False conditions: slave index < 1 (the master aggregate state does not go through this channel) / master closed / null slave pointer / read failure / is_lost is true / value == 0xFFFF. In that case al_status_code must not be read as "no error"; for the live truth "right now", use al_status_code_live_read.

Remove a listener with remove_state_changed_with_al(callback) / remove_slave_state_changed_with_al(callback).

Example:

def on_state_changed_with_al(old_state, new_state, al_code, known):
if known:
print(f"状态: 0x{old_state:02X} -> 0x{new_state:02X}, AL=0x{al_code:04X}") # State: 0x{old_state:02X} -> 0x{new_state:02X}, AL=0x{al_code:04X}
else:
print(f"状态: 0x{old_state:02X} -> 0x{new_state:02X}, AL 码不可信") # State: 0x{old_state:02X} -> 0x{new_state:02X}, AL code unreliable

slave.events.add_state_changed_with_al(on_state_changed_with_al)

add_emergency()​

def add_emergency(self, callback: Callable[[int, int, int, int, int], None]) -> None

Registers an emergency listener. Callback arguments: (error_code, error_reg, b1, w1, w2).

Example:

slave.events.add_emergency(lambda ec, er, b1, w1, w2:
print(f"紧急消息: 错误码=0x{ec:04X}")) # Emergency message: error code=0x{ec:04X}

add_offline() / add_online()​

def add_offline(self, callback: Callable[[], None]) -> None
def add_online(self, callback: Callable[[], None]) -> None

Registers a slave offline / online listener. The callback takes no arguments.

Example:

slave.events.add_offline(lambda: print("从站离线"))   # Slave offline
slave.events.add_online(lambda: print("从站上线")) # Slave online

add_dc_sync_lost()​

def add_dc_sync_lost(self, callback: Callable[[int], None]) -> None

Registers a DC synchronization loss listener. Callback argument: (diff_ns).

Example:

slave.events.add_dc_sync_lost(lambda diff_ns:
print(f"DC 同步丢失: 偏差 {diff_ns}ns")) # DC sync lost: deviation {diff_ns}ns

Input data changes (removed, use polling)​

Removed (2026-05-21)

slave.events.add_input_changed() has been removed. The old mechanism compared the input PDO byte by byte every cycle in the underlying layer and fired a callback; once the application layer holds its own process image (map once and read directly, or copy the whole frame as a snapshot), that mechanism is no longer driven.

PDO data access​

Snapshot reads go through slave.pdo.inputs (a whole-frame snapshot), not a live IOmap pointer. To detect "the input changed", read it in the master.on_pdo_cycle() callback (which runs on a worker thread, not the PDO cycle thread) or in your own polling thread, and compare it with the previous cycle's snapshot.

bind_pdo_struct is built on inputs_mapping / outputs_mapping and is a direct from_address mapping (not a snapshot): on the input side every read returns the latest value, and on the output side changing a field writes to the bus. When you only need a snapshot, copy the whole frame from inputs and use struct.unpack_from; to write, assemble the complete frame and then call write_outputs.

Example:

import struct

_last_pos = None

def on_pdo_cycle(mi):
global _last_pos
raw = slave.pdo.inputs
if raw and len(raw) >= 6:
_, pos = struct.unpack_from('<Hi', raw, 0)
if pos != _last_pos:
_last_pos = pos
print(f"当前位置: {pos}") # Current position: {pos}

master.on_pdo_cycle(on_pdo_cycle)

FSoE safety events​

# FSoE state change (old_state, new_state)
slave.events.add_fsoe_state_changed(lambda old, new:
print(f"FSoE: {old} -> {new}"))

# FSoE error (error_code)
slave.events.add_fsoe_error(lambda code:
print(f"FSoE 错误: 0x{code:04X}")) # FSoE error: 0x{code:04X}

# FSoE enters failsafe (the callback takes no arguments and carries no reason)
slave.events.add_fsoe_failsafe_triggered(lambda:
print("进入失效安全模式!")) # Entering failsafe mode!

# FSoE data exchange (input_data, output_data)
slave.events.add_fsoe_data_exchange(lambda inp, out:
print(f"输入: {inp.hex()}, 输出: {out.hex()}")) # Inputs: {inp.hex()}, outputs: {out.hex()}
The FSoE safe data update event does not exist in the Python SDK

Earlier documentation listed an add_fsoe_safe_data_updated() subscription entry and the FSoEDataUpdatedEventArgs argument type; the current Python SDK does not have either member, so such a subscription cannot compile. Use add_fsoe_data_exchange() for safe data exchange (argument FSoEDataExchangeEvent).

FSoE subscriptions are not wired up yet (pending)

SlaveEvents already provides the 4 pairs of add_fsoe_* / remove_fsoe_* registration interfaces above, but the Python SDK currently does not connect the underlying FSoE callbacks to these subscription tables (_trigger_fsoe_* has no caller), so registering them does not fire anything. For periodic FSoE data use SafeMdp.add_data_exchanged_callback(cb) (darra_ethercat.slave.fsoe.SafeMdp), which calls back once per PDO cycle with a FSoEDataExchangeEvent (containing safe_inputs / safe_outputs / current_state / in_failsafe).

has_fsoe_listeners()​

def has_fsoe_listeners(self) -> bool

Whether any FSoE listener has been registered for this slave (any of the four FSoE subscription tables is non-empty).

Returns:

  • bool — True = at least one FSoE listener is registered; False = none at all

Notes:

  • Lets the cycle side decide "whether safety data should be read for the events": when it returns False nothing is read or sent, avoiding a useless safety data read every cycle.
  • False only means this slave has no listeners; it does not mean the slave has no FSoE facts / no safety data.
  • Reads only the in-memory subscription table; it sends no bus frames and does not access the slave.

Example:

if slave.events.has_fsoe_listeners():
print("本从站有 FSoE 监听,周期侧会读取安全数据") # This slave has an FSoE listener; the cyclic side reads the safety data
else:
print("本从站无 FSoE 监听,周期侧跳过安全数据读取") # This slave has no FSoE listener; the cyclic side skips reading the safety data

Removing listeners​

Every add_* method has a matching remove_* method (the FSoE event interfaces have them too, but see "not wired up yet" above):

slave.events.remove_state_changed(my_callback)
slave.events.remove_emergency(my_callback)
slave.events.remove_offline(my_callback)
slave.events.remove_online(my_callback)
slave.events.remove_dc_sync_lost(my_callback)

slave.events.remove_fsoe_state_changed(my_callback)
slave.events.remove_fsoe_error(my_callback)
slave.events.remove_fsoe_failsafe_triggered(my_callback)
slave.events.remove_fsoe_data_exchange(my_callback)

# clear all subscriptions of this slave at once (including FSoE)
slave.events.clear_all()

remove_* returns silently when removing a callback that was never registered and does not throw. For the master-level compatibility entry master.on_*(), pass None to clear; see master events.

Thread safety​

Event callbacks are raised on non-UI threads. Updating the UI requires thread synchronization:

import queue
data_queue = queue.Queue()

def on_offline():
data_queue.put(("offline", slave.index))

slave.events.add_offline(on_offline)
warning

Avoid time-consuming work inside callbacks. To process large amounts of data, put the data in a queue and handle it asynchronously. In the PDO cycle callback, read the slave.pdo process image and only enqueue quickly, leaving the slow processing to a background thread.

Complete example​

import ctypes
from darra_ethercat import EtherCATMaster, EcState

class ServoInput(ctypes.Structure):
_pack_ = 1
_fields_ = [
("status_word", ctypes.c_uint16),
("actual_position", ctypes.c_int32),
("actual_velocity", ctypes.c_int32),
]

with EtherCATMaster() as master:
master.set_network(r"\Device\NPF_{GUID}")
master.set_state(EcState.OP)
master.start()

slave = master[1]

# ===== Slave state events =====
slave.events.add_state_changed(lambda old, new:
print(f"状态: 0x{old:02X} -> 0x{new:02X}")) # State: 0x{old:02X} -> 0x{new:02X}

slave.events.add_emergency(lambda ec, er, b1, w1, w2:
print(f"紧急消息: 0x{ec:04X}")) # Emergency message: 0x{ec:04X}

slave.events.add_offline(lambda: print("从站离线")) # Slave offline
slave.events.add_online(lambda: print("从站上线")) # Slave online

slave.events.add_dc_sync_lost(lambda diff:
print(f"DC 同步丢失: {diff}ns")) # DC sync lost: {diff}ns

# ===== Input data access (zero-copy structure + PDO cycle polling comparison) =====
input_ref = slave.pdo.bind_pdo_struct(ServoInput, is_input=True)
_last_pos = [None]

def on_pdo_cycle(mi):
if input_ref and input_ref.actual_position != _last_pos[0]:
_last_pos[0] = input_ref.actual_position
print(f"位置: {input_ref.actual_position}") # Position: {input_ref.actual_position}

master.on_pdo_cycle(on_pdo_cycle)

# ===== FSoE safety events (protocol specific) =====
if slave.fsoe is not None:
slave.events.add_fsoe_state_changed(lambda old, new:
print(f"FSoE: {old} -> {new}"))

slave.events.add_fsoe_error(lambda code:
print(f"FSoE 错误: 0x{code:04X}")) # FSoE error: 0x{code:04X}

slave.events.add_fsoe_failsafe_triggered(lambda:
print("进入失效安全模式!")) # Entering failsafe mode!

slave.events.add_fsoe_data_exchange(lambda inp, out:
print(f"输入: {inp.hex()}, 输出: {out.hex()}")) # Inputs: {inp.hex()}, outputs: {out.hex()}

import time
time.sleep(30)
master.stop()