Skip to main content

Events

Master and slave events are registered with add_* methods and removed with remove_* methods.

Master-level callbacks

Master-level events can be registered directly through the master.on_* compatibility entry points; these entry points all route to this instance's master.events (they do not overwrite other masters or other listeners).

Advanced event system

Use the MasterEvents and SlaveEvents classes for finer-grained event management, with support for multiple listeners and automatic routing.

Automatic logging

Whether an event is written to the log depends on whether logging happens at the trigger site (see the "Automatic logging" column in the table below). Offline/online, offline rich context, SDO/mailbox failures, DC events and diagnostic polling events are logged; state changes, EMCY, PDO frame loss, DC sync loss, redundancy mode, identity mismatch, port link and similar callbacks do not write additional log entries (the underlying layer does not log these events either). The PDO cycle callback is a high-frequency callback and is not logged.

Architecture change (2026-05-21)

Two non-working callbacks have been removed:

  • Asynchronous PDO cycle callback (old on_pdo_cycle(sync=False)) — the asynchronous variant has been removed; the sync parameter is kept only for backward compatibility, and any value registers the same latest-only worker callback.
  • Input data change callback (old on_input_changed() / slave.events.add_input_changed()) — this mechanism relied on the underlying library comparing input data byte by byte every cycle and is no longer driven.

The recommended approach is to map once with inputs_mapping / from_address. To detect input changes, read the fields of the mapped struct, or compare a snapshot with the previous cycle.

Feature overview​

CategoryMethodR/WDescriptionAutomatic logging
PDO cycle callbackmaster.on_pdo_cycle()write-onlyPDO cycle callback (latest-only worker thread)—
State eventsmaster.on_state_changedwrite-onlyMaster's own (aggregate) state changes—
master.on_state_change()write-onlySlave state changes—
Hot-plug eventsmaster.on_slave_discovery()write-onlySlave discovery/loss✓
master.events.add_slave_offline_detailed()write-onlySlave offline rich context (same tick as the offline of on_slave_discovery)✓
master.events.add_slave_offline_disputed()write-onlySlave loss marking contradicts the evidence at delivery time (the offline event is not delivered; this event is delivered instead)✓
master.events.add_slave_identity_mismatch()write-onlySlave identity mismatch (wrong model swapped in; the revision number takes no part in the check)—
Exception eventsmaster.on_emergency()write-onlyCoE Emergency message—
master.on_pdo_frame_loss()write-onlyConsecutive PDO frame loss (tracked per group)—
master.set_dc_sync_lost_callback()write-onlyDC sync loss—
master.events.add_sdo_error()write-onlySDO read/write failure (success does not trigger)✓
master.events.add_mailbox_error()write-onlyMailbox timeout / protocol error / channel-closed dead letter✓
DC state eventsmaster.set_log_callback(...)write-onlyDC arming / window / reference clock / propagation delay / hot-plug / convergence events arrive on the log stream—
master.events.add_dc_event_raised()write-onlyUnified DC state event stream (arming / sync window / reference clock / propagation delay / hot-plug / convergence)✓
master.events.add_dc_sync_restored()write-onlyDC sync-loss recovery edge (same edge as the sync window recovery event, includes the lost duration)✓
Diagnostic eventsmaster.events.add_wkc_shortage_occurred()write-onlyGroup WKC shortage (actual < expected, edge-triggered)✓
master.events.add_nic_link_changed()write-onlyMaster NIC link up/down edge (primary / redundant)✓
Redundancy eventsmaster.on_redundancy_mode_changed()write-onlyRedundancy mode change—
master.events.add_slave_port_link_changed()write-onlySlave port link change (P0-P3 disconnect/recover)—
Loggingmaster.set_log_callback()write-onlyLog message callback (category, message)—
Events not provided by this language

The following logical events have no corresponding entry point in the Python SDK; the documentation does not invent APIs:

  • Slave PreOp reconfiguration event: MasterEvents does not expose this listener.
  • Generic error / generic warning callbacks: not provided by Python.
  • Placeholder slave re-read recovery event: not provided by Python.
Duplicate registration does not double-trigger

Registering the same callback repeatedly (events.add_*(), and the same subscription table used by on_pdo_cycle()) keeps only one copy (plain functions are compared by identity, bound methods by (self, func) equality), so one event does not trigger twice. The subscription table is snapshotted when an event fires, so adding or removing subscriptions inside a callback (or from another thread) does not lose events and does not hit list changed size during iteration. The on_pdo_cycle() callback must be callable (a non-callable raises TypeError).

PDO cycle callback​

on_pdo_cycle()​

def on_pdo_cycle(self, callback: Callable[[int], None], sync: bool = True)

Register a PDO cycle callback. The underlying library publishes only the latest cycle stamp per cycle, and the Python callback runs on an ordinary daemon worker thread (not the PDO cycle thread): a slow callback only drops cycles and does not hold up the bus.

The sync parameter (backward compatibility only since 2026-05-21)

The asynchronous cycle callback mechanism has been removed. The sync parameter is kept only so that existing code keeps working; any value registers the same latest-only worker callback, and user code always runs on an ordinary worker thread.

Parameters:

  • callback — callback function (master_index)
  • sync (bool) — deprecated, kept only for backward compatibility; the value does not affect behaviour (always synchronous)
This is not a complete CiA 402 enable sequence

The example below only demonstrates the PDO write itself. 0x000F must only be held after completing 0x06→0x07→0x0F with (statusWord & 0x6F) == 0x27; when not enabled / faulty / NotReady, write 0x0006 with target = actual. For CSP do not write 0x001F; for multi-axis, issue to each axis in the same callback. The full state machine is in CiA 402.

Example (direct mapping, zero-copy; map once outside the callback):

inputs = slave.pdo.inputs_mapping(InPdo)
outputs = slave.pdo.outputs_mapping(OutPdo)

def on_pdo_sync(master_index):
outputs.control_word = 0x000F
outputs.target_position = inputs.actual_position

master.on_pdo_cycle(on_pdo_sync)

Snapshot alternative (copy each tick; the copied instance does not change by itself; do not use from_buffer_copy as a stand-in for direct mapping):

import struct

def on_pdo_sync(master_index):
raw = slave.pdo.inputs
frame = bytearray(slave.pdo.outputs or b'')
if len(frame) >= 2:
struct.pack_into('<H', frame, 0, 0x000F)
slave.pdo.write_outputs(bytes(frame))

master.on_pdo_cycle(on_pdo_sync)
warning

Do not perform time-consuming operations in the callback (such as SDO read/write, file I/O, lock waits): the callback runs on an ordinary worker thread, so a slow callback does not block the bus, but it does drop intermediate cycles.

State events​

on_state_changed (master aggregate)​

master.on_state_changed = lambda old_state, new_state: ...

Triggered when the master's own (aggregate) state changes; the callback arguments are (old_state, new_state) and carry no slave index. Internally slave_index == 0 denotes the master aggregate state, and this path never mixes into the slave state callbacks. Use on_state_change() below for slave state changes.

master.on_state_changed = lambda old, new: print(f"主站: 0x{old:02X} -> 0x{new:02X}")   # Master: 0x{old:02X} -> 0x{new:02X}

on_state_change()​

def on_state_change(self, callback: Callable[[int, int, int, int], None],
sync: bool = True) -> None

Register a slave state change callback. Monitored and invoked by a background thread.

Callback arguments:

  • master_index (int) — master index
  • slave_index (int) — slave index (1-based)
  • old_state (int) — state before the change (EcState enum value)
  • new_state (int) — state after the change (EcState enum value)

Example:

from darra_ethercat import EcALState

def on_state_change(mi, si, old, new):
print(f"从站 {si}: 0x{old:02X} -> 0x{new:02X}") # Slave {si}: 0x{old:02X} -> 0x{new:02X}

slave = master[si]
if slave.error_code != EcALState.NO_ERROR:
print(f" 错误码: 0x{slave.error_code.value:04X}") # Error code: 0x{slave.error_code.value:04X}

master.on_state_change(on_state_change)
error_code

slave.error_code returns the EcALState enum (AL Status Code), i.e. the specific reason a state transition failed.

Hot-plug events​

on_slave_discovery()​

def on_slave_discovery(self, callback: Callable[[int, int, bool], None],
sync: bool = True) -> None

Register a slave discovery/loss callback. Triggered when a hot-plug slave disconnects; the recovery state machine built into the PDO thread restores the slave automatically (zero PDO impact). The offline/online paths are logged by the SDK (the callback itself writes nothing extra).

Callback arguments:

  • master_index (int) — master index
  • slave_index (int) — slave index (1-based)
  • is_found (bool) — True = slave online, False = slave offline

Example:

def on_discovery(mi, si, found):
if found:
print(f"从站 {si} 上线") # Slave {si} online
else:
print(f"从站 {si} 离线") # Slave {si} offline

master.on_slave_discovery(on_discovery)

add_slave_offline_detailed (MasterEvents)​

def add_slave_offline_detailed(self,
callback: Callable[[SlaveOfflineEventArgs], None]) -> None

Register a slave offline rich context listener (accessed through master.events); it is delivered on the same tick as the offline events of add_slave_offline() / on_slave_discovery(). The payload type is the same as add_slave_offline_disputed() (SlaveOfflineEventArgs), and the event name distinguishes the semantics: this listener is delivered only when the offline state has been announced (real offline / unknown); when the evidence contradicts offline, only the dispute listener is delivered.

Payload SlaveOfflineEventArgs (frozen dataclass):

  • master_index (int) — master index
  • slave_index (int) — slave index (1-based)
  • timestamp_utc (datetime) — event time (UTC); also the time at which this payload's evidence was read
  • reason (SlaveOfflineReason) — offline reason classification
  • probe (SlaveProbeState) — slave response verdict at delivery time
  • contribution (WcContribution) — process data contribution at delivery time
master.events.add_slave_offline_detailed(lambda e:
print(f"从站 {e.slave_index} 离线: 原因={e.reason.name} " # Slave {e.slave_index} offline: reason={e.reason.name}
f"响应={e.probe.name} PD贡献={e.contribution.name}")) # response={e.probe.name} PD contribution={e.contribution.name}

Slave loss events and dispute notices (SlaveOfflineDisputed)​

When a slave is judged lost, the SDK reports the offline reason at delivery time along with the event; the classification result is SlaveOfflineReason.

Related structures:

class SlaveOfflineReason(IntEnum):
Unknown = 0 # cannot determine
RealOffline = 1 # confirmed offline — process data not contributing
Unreachable = 2 # unconfirmed — process data still contributing

SlaveProbeState is the three-state response verdict at delivery time:

class SlaveProbeState(IntEnum):
NotResponding = 0 # no response
Responding = 1 # responding
Unknown = 2 # cannot determine

Process data contribution WcContribution (mirror of the current cycle). CONTRIBUTED = positively contributing WKC this cycle; NOT_CONTRIBUTED = positively not contributing; UNKNOWN = no conclusion yet.

  • Process data positively still contributing → do not deliver the offline listener; deliver add_slave_offline_disputed instead
  • Process data positively not contributing → RealOffline
  • Contribution cannot be determined: no response → RealOffline, otherwise → Unknown

When the slave loss marking contradicts the evidence at delivery time (process data positively still contributing), the SDK does not deliver the offline listeners registered with master.events.add_slave_offline(), nor the slave-level slave.events.add_offline(); it delivers add_slave_offline_disputed instead. The event semantics stay consistent with the evidence it carries: it never says "offline" while also carrying "process data still contributing".

master.events.add_slave_offline_disputed(lambda e: ...)

Related structures:

@dataclass(frozen=True)
class SlaveOfflineEventArgs:
master_index: int # master index
slave_index: int # slave index (1-based)
timestamp_utc: datetime # event time (UTC)
reason: SlaveOfflineReason
probe: SlaveProbeState
contribution: WcContribution

Consumers use it to hint at a "suspected momentary disconnection / slave loss marking does not match the evidence"; do not use it to flag an alarm or stop the line. Confirmed offline still goes through master.events.add_slave_offline().

Reason queries:

def try_get_slave_offline_reason(self, slave_index: int) -> Optional[SlaveOfflineReason]
def get_slave_offline_reasons(self) -> Dict[int, SlaveOfflineReason]

try_get_slave_offline_reason lets a UI that started after the offline event, or that resubscribed midway, fetch the reason classification afterwards (returns None if not available); get_slave_offline_reasons fetches all reasons at once. The semantics of is_slave_offline() and the slave loss counter are unchanged.

Example:

from darra_ethercat import SlaveOfflineReason

def on_disputed(e):
print(f"从站 {e.slave_index} 掉站标记与证据不符: " # Slave {e.slave_index} slave-loss flag conflicts with the evidence:
f"原因={e.reason.name}") # reason={e.reason.name}
# only hints "suspected momentary disconnect"; no alarm, no line stop

master.events.add_slave_offline_disputed(on_disputed)

if master.events.try_get_slave_offline_reason(2) == SlaveOfflineReason.RealOffline:
print("从站 2 确证离线") # Slave 2 confirmed offline

is_slave_offline() (MasterEvents)​

def is_slave_offline(self, slave_index: int) -> bool

Query whether a slave has been registered as offline (slave loss marking) by the event system. Must be accessed through a MasterEvents instance.

Registration semantics include "evidence dispute"

is_slave_offline() is judged by the offline registry: real offline, unknown, and "slave loss marking contradicts the evidence at delivery time" (SlaveOfflineReason.Unreachable; only add_slave_offline_disputed is delivered, no offline event) all return True. To distinguish the specific reason use try_get_slave_offline_reason() / get_slave_offline_reasons(); do not treat True on its own as "device confirmed disconnected".

Parameters:

  • slave_index (int) — slave index (1-based)

Returns:

  • bool — True if the slave is offline

Example:

events = master.events
# ... register callbacks ...

if events.is_slave_offline(2):
print("从站 2 处于离线状态") # Slave 2 is offline

# get the set of all offline slaves
offline = events.offline_slaves # Set[int]
print(f"离线从站: {offline}") # Offline slaves: {offline}

slave_identity_mismatch (MasterEvents)​

def add_slave_identity_mismatch(self,
callback: Callable[[SlaveIdentityMismatchEventArgs], None]) -> None

Triggered when the slave identity does not match after power-cycling and reinsertion: the Vendor/Product read by the EtherCAT identification state machine does not match the configuration. In the current version the identity check only looks at Vendor + Product — the revision number (Revision) does not take part in rejection. MasterConfig.scan_revision_match is always ScanRevisionMatchMode.IGNORE_REVISION; EXACT (exact revision match) and COMPATIBLE_HIGHER (scanned revision number ≥ the configured value) are declared values of that enum, but the current version offers no entry point that sets them and assigning one raises NotImplementedError.

After triggering, the slave enters the IDENT_REJECTED state and is not re-probed automatically (to prevent a wrong device from repeating endlessly). After the operator checks or replaces the device, call master.acknowledge_slave_replacement() to let the SDK probe again.

Related structures:

@dataclass(frozen=True)
class SlaveIdentityMismatchEventArgs:
master_index: int # master index
slave_index: int # slave index (1-based)
expected_vendor: int # vendor ID expected by the configuration
expected_product: int # product code expected by the configuration
expected_revision: int # revision number expected by the configuration (for reference only; not part of the identity check)
actual_vendor: int # current actual vendor ID
actual_product: int # current actual product code
actual_revision: int # current actual revision

Example:

from darra_ethercat import SlaveIdentityMismatchEventArgs

events = master.events

def on_identity_mismatch(args: SlaveIdentityMismatchEventArgs):
print(f"从站 {args.slave_index} 身份不符:") # Slave {args.slave_index} identity mismatch:
print(f" 期望: Vendor=0x{args.expected_vendor:08X}, " # expected: Vendor=0x{args.expected_vendor:08X},
f"Product=0x{args.expected_product:08X}, Rev=0x{args.expected_revision:08X}")
print(f" 实际: Vendor=0x{args.actual_vendor:08X}, " # actual: Vendor=0x{args.actual_vendor:08X},
f"Product=0x{args.actual_product:08X}, Rev=0x{args.actual_revision:08X}")
# the UI prompts the user to refit the correct device; after confirmation call:
# master.acknowledge_slave_replacement(args.slave_index)

events.add_slave_identity_mismatch(on_identity_mismatch)
Deduplication mechanism

A slave entering the IDENT_REJECTED state triggers the event only once. Calling acknowledge_slave_replacement() resets the probe; if the identity still does not match, it triggers again.

Exception events​

Cycle anomalies must raise an alarm

The cycle is set by DENI/LoopCycle, with a minimum of 125 µs; it is not hard-coded to 1ms. rt_cnt should align with 1e9/LoopCycleNs. If it deviates from the setting by ±20% continuously, or max jitter exceeds 25% of the cycle, you must write a log entry and raise an alarm in the UI. Also check pdo_frame_loss and dc_sync_lost. If isolation is not in effect, only the jitter may grow — the cycle must not drift without an alarm. Do not do alarm I/O on the PDO hot path.

on_emergency()​

def on_emergency(self, callback: Callable) -> None

Register a CoE Emergency message callback. Sent by the slave firmware when it detects an error; the data format follows the CANopen Emergency protocol (CiA 301).

Callback arguments: (master_index, slave_index, error_code, error_reg, b1, w1, w2)

  • master_index (int) — master index
  • slave_index (int) — slave index (1-based)
  • error_code (int) — error code (CANopen Emergency Error Code, CiA 301 Table 24, transmitted with the EMCY frame)
  • error_reg (int) — error register (object 0x1001)
  • b1 (int) — manufacturer-specific data (byte 3)
  • w1 (int) — manufacturer-specific data (bytes 4-5)
  • w2 (int) — manufacturer-specific data (bytes 6-7)

Common Emergency Error Codes:

  • 0x0000 — error reset
  • 0x1000 — generic error
  • 0x2000 — current error
  • 0x3000 — voltage error
  • 0x4000 — temperature error
  • 0x5000 — device hardware error
  • 0x6000 — device software error
  • 0x7000 — additional module error
  • 0x8000 — monitoring error (communication)
  • 0xFF00 — manufacturer-specific error

Example:

def on_emcy(mi, si, err_code, err_reg, b1, w1, w2):
print(f"从站 {si} 紧急消息: 错误码=0x{err_code:04X}, 寄存器=0x{err_reg:02X}") # Slave {si} emergency message: error code=0x{err_code:04X}, register=0x{err_reg:02X}

master.on_emergency(on_emcy)
Python-specific syntax sugar

Besides the callback style, Python can consume EMCY events stream-wise with the async generator async for ev in master.emergencies(): (the same applies to master.state_changes() / master.slave_state_changes()).

on_pdo_frame_loss()​

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

Register a PDO consecutive frame loss callback. Triggered when consecutive frame loss reaches the threshold; a single lost frame is only counted and does not trigger. Each group is tracked independently.

Callback arguments: (master_index, group, consecutive_lost, total_lost)

  • master_index (int) — master index
  • group (int) — group number where the frame loss occurred (0-7), corresponding to slave grouping
  • consecutive_lost (int) — consecutive lost frames in that group
  • total_lost (int) — cumulative lost frames in that group

Example:

def on_loss(mi, group, consecutive, total):
print(f"组 {group} 丢帧: 连续={consecutive}, 累计={total}") # Group {group} frame loss: consecutive={consecutive}, total={total}

master.on_pdo_frame_loss(on_loss)

set_dc_sync_lost_callback()​

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

Set the DC sync loss callback. Triggered once when a slave goes from synchronized → out of sync (beyond the threshold); it is not repeated while the condition persists. Pass None to clear the callback.

Callback arguments: (master_index, slave_index, diff_ns)

  • master_index (int) — master index
  • slave_index (int) — index of the slave that lost sync (1-based)
  • diff_ns (int) — current time difference from the reference clock (nanoseconds)

Example:

master.diagnostics_info.sync_window_threshold = 500  # 500ns

def on_sync_lost(mi, si, diff_ns):
print(f"从站 {si} DC 同步丢失: 偏差 {diff_ns}ns") # Slave {si} DC sync lost: deviation {diff_ns}ns

master.set_dc_sync_lost_callback(on_sync_lost)
Per-slave DC diagnostics

slave.diagnostics.dc.is_in_sync and slave.diagnostics.dc.sync_time_difference query the slave's current sync state.

add_sdo_error​

def add_sdo_error(self, callback: Callable[[SdoErrorEventArgs], None]) -> None

Register an SDO read/write failure listener (accessed through master.events). Triggered only when an SDO read or write fails; success does not trigger.

The data source is the single exit for slave-side SDO reads and writes — reads go through the unified read-result exit, writes through the unified write-result exit; each failure is reported once after the result is produced and before it is returned:

  • WKC=0 no response / timeout / slave Abort all count as failures and all go through this one exit;
  • a read failure from a NotPresent negative-cache hit is also reported (the cache remembers the Abort Code from that time, so it is still reported even though the cache was used);
  • sdo_write() with empty data is a local immediate failure and is also reported through the same exit (in this case abort_code = 0 and error is normalized to SDOError.SDO_PROTOCOL_TIMEOUT);
  • the success path does not call the reporting exit.

Payload SdoErrorEventArgs (frozen dataclass):

  • slave_index (int) — slave index (1-based)
  • index (int) — object index of the failure (normalized with & 0xFFFF)
  • sub_index (int) — object subindex of the failure (normalized with & 0xFF)
  • is_write (bool) — True = write failure, False = read failure
  • error (SDOError) — error enum mapped from the Abort Code; transport-level failures with abort_code == 0 are normalized to SDOError.SDO_PROTOCOL_TIMEOUT, not judged by a separate scheme
  • abort_code (int) — raw Abort Code (& 0xFFFFFFFF); 0 means the failure is not an Abort-class failure (WKC=0 / timeout)
  • timestamp_utc (datetime) — time the SDK produced this event (UTC, timezone-aware), not the time the slave produced the Abort

Threading and synchronization: the callback executes synchronously on the thread that initiated the SDO call (in the return path of that SDO call), not on the underlying callback thread and not on the PDO worker. Callback duration adds directly to that SDO call; a fault in the event layer itself only writes a debug log and does not change the SDO result semantics. It is not reported when the master is not registered in the callback registry or has already been released.

Example:

from darra_ethercat import SDOError

def sdo_failed(args):
kind = "写" if args.is_write else "读"
print(f"从站 {args.slave_index} SDO {kind}失败 " # Slave {args.slave_index} SDO {kind} failed
f"0x{args.index:04X}:{args.sub_index:02X} "
f"abort=0x{args.abort_code:08X} 归一={args.error.name}") # abort=0x{args.abort_code:08X} normalized={args.error.name}

master.events.add_sdo_error(sdo_failed)
Abort codes are authoritative as raw values

abort_code keeps the raw value supplied by the device (including vendor-specific codes that are not in the SDOError enum); error is only its enum view. Use abort_code to determine the real abort cause.

add_mailbox_error​

def add_mailbox_error(self, callback: Callable[[MailboxErrorEventArgs], None]) -> None

Register a mailbox transaction-level exception listener (accessed through master.events): timeout / protocol error / channel-closed dead letter.

The data source is the terminal-state exit of MailboxTransaction.execute() — at most one report per execute():

  • MailboxStatus.TIMEOUT → MailboxErrorKind.Timeout
  • MailboxStatus.CANCELLED (transaction voided after the mailbox channel closed) → MailboxErrorKind.ChannelClosed
  • all other failure terminal states → MailboxErrorKind.ProtocolError

Not reported: SUCCESS, NOT_IMPLEMENTED (the underlying library does not support that capability and the transaction never really ran), PENDING (not converged), NOT_SENT (the frame never got on the wire, so this round produced no conclusion and no bus evidence; callers treat it as retryable) — "did not run / no conclusion" is not written up as a failure.

CoE SDO-level failures do not go through this event: SDO reads and writes go through the slave's SDO exit and are covered separately by master.events.add_sdo_error(), so they are not reported twice by this event.

Payload MailboxErrorEventArgs (frozen dataclass):

  • slave_index (int) — slave index (1-based)
  • protocol (MailboxType) — protocol type enum; protocol codes not covered by the enum (such as FSoE=8) are reported as MailboxType.ERROR_MAILBOX and the raw code is kept in detail
  • kind (MailboxErrorKind) — Timeout(0) / ProtocolError(1) / ChannelClosed(2)
  • detail (str) — readable detail, of the form 邮箱事务失败: Status=... ErrorCode=0x........ Protocol=0xNN (master=N slave=N) (SDK output, = mailbox transaction failed: …) (the runtime prefixes the detail with the Chinese text shown)
  • timestamp_utc (datetime) — time the SDK produced this event (UTC)

Threading and synchronization: the callback executes synchronously on the thread that calls execute() (before execute() returns); an exception in the event layer only writes a debug log and does not change the transaction's terminal-state result. It is not reported when the master is not registered or has already been released.

Example:

from darra_ethercat import MailboxErrorKind

def mailbox_failed(args):
if args.kind == MailboxErrorKind.ChannelClosed:
print(f"从站 {args.slave_index} 邮箱通道已关闭: {args.detail}") # Slave {args.slave_index} mailbox channel closed: {args.detail}
else:
print(f"从站 {args.slave_index} 邮箱异常 {args.kind.name}: {args.detail}") # Slave {args.slave_index} mailbox exception {args.kind.name}: {args.detail}

master.events.add_mailbox_error(mailbox_failed)

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

DC state changes (arming, entering/leaving the sync window, reference clock switch / freeze, propagation delay re-measurement / reuse / invalidation, hot-plug recovery, slow convergence) are delivered over a unified event stream; the consumption entry point can be master.set_log_callback(...).

The "R/W" column in the table refers to reading the event itself (read-only). Registering the consumption channel set_log_callback(...) is a write (registration) and does not change the event content.

CategoryEventLevelTrigger and debounceKey payloadR/W
DC eventArming succeededMessageOnly sent when the published arming mask changes; the same mask does not repeatWrites / readback of 0x0980, 0x09A0, ESI profile, required mask, evidence strengthread-only
DC eventArming failed / rolled backWarningAlways sent on the first occurrence; while it persists, at most one per 10 secondsReason, whether rolled back, AL status / code, write WKC, readback of 0x0980read-only
DC eventNo SYNC0 cycle unitMessageOnce per (master, slave)Evidence of three consecutive attempts of 0x0980 with no responseread-only
DC eventSync window exceededWarningSent once on entry; while it persists, at most one per 10 secondsCurrent difference, threshold, duration so far, tick countread-only
DC eventSync window recoveredMessageSent once per recovery (paired with sync window exceeded)Current difference, thresholdread-only
DC eventReference clock established / switched / lostMessage; Warning when warning=1One per switch, minimum interval 1 secondOld / new reference clock, profile, reasonread-only
DC eventReference clock frozenWarningAt most one 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 warning=1Minimum interval 2 seconds per slaveArming result, 0x0980 readback, AL status / code, propagation delayread-only
DC eventSlow convergence (greater than 5 seconds)WarningOne per episode per 60 seconds; hard minimum of 5 seconds between any twoDuration so far, tick count, differenceread-only
DC eventSevere convergence timeout (greater than 30 seconds)ErrorSame as the slow convergence eventDuration so far, tick count, differenceread-only

Relation to set_dc_sync_lost_callback(): the two do not replace each other.

  • set_dc_sync_lost_callback() is unchanged and is responsible only for the strongly typed subscription of "synchronized → out of sync" (callback arguments (master_index, slave_index, diff_ns)).
  • This channel delivers all DC arming, window transitions, reference clock, propagation delay, hot-plug and convergence events into the event stream; subscribe to the log callback when you need the full set of DC state changes.

Levels and builds: Message = event-level Info, also emitted in production; Warning and Error are also emitted in production; Debug = reuse-class detail, not output in Release builds.

Debounce semantics: on the emitting side, one slot is atomically claimed per (master, slave); reference clock and propagation delay events are rate-limited independently (sharing a single timestamp would suppress each other); convergence events are gated per episode — one per episode per 60 seconds, with at least 5 seconds between any two. Master-level events (reference clock / propagation delay) use the slave index 0 slot and do not compete with slave-level events; slave-level events that incorrectly pass slave index 0 are rejected.

Boundary: this channel does not change the underlying API; event dispatch performs only constant-time table lookups and low-frequency formatting and must not be called on the hot path.

Example:

def on_log(category, message):
print(f"[{category}] {message}")

master.set_log_callback(on_log)

# the strongly typed sync-loss callback stays independent and is used alongside the log subscription above
master.set_dc_sync_lost_callback(
lambda mi, si, diff_ns: print(f"从站 {si} DC 同步丢失: {diff_ns}ns")) # Slave {si} DC sync lost: {diff_ns}ns

add_dc_event_raised​

def add_dc_event_raised(self, callback: Callable[[DcEventArgs], None]) -> None

Register a unified stream listener for DC state events (accessed through master.events): covers arming success / failure rollback, no SYNC0 unit, window exceeded / recovered, reference clock switch / freeze, propagation delay re-measurement / reuse / invalidation, hot-plug recovery, slow convergence / severe timeout. It does not replace the log channel — you can subscribe to this event and still subscribe to set_log_callback(...); the two channels deliver independently.

Trigger conditions:

  • Delivered once for every DC state event produced; the emitting side already debounces and rate-limits by event type (see "Trigger and debounce" in the table above), and the SDK side does not debounce a second time;
  • The data source is the SDK's DC state event stream; a custom log callback takes over log output, in which case use the DC event API directly;
  • When the corresponding master cannot be found (closed / not registered) it is silently skipped without error.

Payload DcEventArgs (frozen dataclass):

  • master_index (int) — master index; 0 when unknown
  • slave_index (int) — slave index; 0 when the event carries no slave index, -1 when the slave index cannot be parsed; master-level events (reference clock / propagation delay) are always 0
  • code (DcEventCode) — event type enum (members are frozen; the member name is the event name)
  • params (str) — raw event parameters; the SDK does not rewrite or translate them (for diagnostics)
  • timestamp_utc (datetime) — time the SDK produced this event (UTC), not the time the bus event occurred

Threading and synchronization: executes on the underlying log callback thread. For the same event, it first writes to LogManager, then forwards this event, and only then dispatches to user listeners registered with set_log_callback(...) — this callback runs before the user listeners for the same event.

Example:

from darra_ethercat import DcEventCode

def dc_event(args):
if args.code == DcEventCode.WindowExceeded:
print(f"从站 {args.slave_index} 同步窗口超限: {args.params}") # Slave {args.slave_index} sync window exceeded: {args.params}
elif args.code == DcEventCode.RefClockSwitch:
print(f"参考钟切换: {args.params}") # Reference clock switched: {args.params}

master.events.add_dc_event_raised(dc_event)
Relation to the strongly typed edges

The sync window exceeded and sync window recovered events also have a strongly typed stream: sync loss uses master.events.add_dc_sync_lost(), recovery uses master.events.add_dc_sync_restored(). The unified stream and the strongly typed stream do not replace each other and can be subscribed at the same time.

add_dc_sync_restored​

def add_dc_sync_restored(self, callback: Callable[[DCSyncRestoredEventArgs], None]) -> None

Register a recovery edge listener for DC sync loss (accessed through master.events): a slave recovers from out of sync back into the sync window. It is the same edge as the sync window recovery event — within the same dispatch round, the unified stream of add_dc_event_raised is delivered first, then this event.

Trigger conditions:

  • Delivered only for sync window recovery events; other DC state events are not delivered;
  • Not delivered when slave_index < 1 (including the master-level slot 0); only a debug log entry is kept — a valid slave index is always 1..N;
  • If the event does not carry the lost duration it is still delivered, with lost_duration as timedelta(0) (honestly meaning "duration not provided", without inventing one).

Payload DCSyncRestoredEventArgs (frozen dataclass):

  • master_index (int) — master index
  • slave_index (int) — index of the recovered slave (1-based)
  • timestamp_utc (datetime) — time the SDK produced this event (UTC)
  • lost_duration (timedelta) — lost duration, constructed in microseconds (timedelta(microseconds=N)); timedelta(0) when the event does not carry the field

Threading and synchronization: same thread as add_dc_event_raised (the underlying log callback thread); within the same dispatch round it runs immediately after the unified stream.

Example:

def dc_restored(args):
ms = args.lost_duration.total_seconds() * 1000.0
print(f"从站 {args.slave_index} DC 同步恢复,失锁 {ms:.0f} ms") # Slave {args.slave_index} DC sync restored, lock lost for {ms:.0f} ms

master.events.add_dc_sync_restored(dc_restored)

Diagnostic events​

Diagnostic events are produced by the SDK's diagnostic polling thread: the background poll starts with the first subscription (one per master) and samples diagnostic data on a 1-second cycle; it stops when the last subscription is removed or after clear_all(). No subscriptions = no thread, zero overhead; if the master has no available diagnostic data source, no thread is created either — it does not pretend to be polling.

Polling does not touch the PDO hot path and does not occupy the PDO worker: a slow callback can at most delay the next sampling instant and does not affect the bus cycle.

add_wkc_shortage_occurred​

def add_wkc_shortage_occurred(self, callback: Callable[[WkcShortageEventArgs], None]) -> None

Register a group WKC shortage listener (accessed through master.events): delivered when a group's actual WKC is less than the expected WKC (the group has mapped slaves that are not contributing).

Trigger and edges (groups 0-7 are judged independently):

  • Sample the group's expected WKC (master.get_group_expected_wkc()) and the read-only mirror of the group's actual WKC; both are normalized with & 0xFFFF;
  • An unused group whose expected value is 0 is skipped entirely: it is not delivered, and the group's edge baseline is not updated either;
  • The criterion is actual_wkc < expected_wkc (strictly less than; equality does not count as a shortage);
  • Entering a shortage (previously not short, or no baseline) delivers once; any change to actual or expected during the shortage delivers once more;
  • If the shortage persists and neither actual nor expected changes → no repeated trigger (no spam);
  • Recovery (actual >= expected) only updates the baseline and does not deliver a "recovered" event; the next entry into shortage delivers again;
  • On read failure (underlying layer unavailable / master not ready) the group warns once and skips that round, while other groups keep sampling;
  • The polling function returns immediately when there are no subscribers.

Payload WkcShortageEventArgs (frozen dataclass):

  • master_index (int) — master index
  • group (int) — group number (0-7)
  • actual_wkc (int) — actual WKC of the group
  • expected_wkc (int) — expected WKC of the group (fixed at configuration time, not lowered because of a shortage)
  • timestamp_utc (datetime) — time the poll detected this edge (UTC)

Threading and synchronization: the callback executes on the diagnostic polling daemon thread, not the PDO cycle thread; the SDK holds no internal lock when triggering, and the subscription table is iterated over a snapshot.

Example:

def wkc_short(args):
print(f"组 {args.group} WKC 短缺: 实测 {args.actual_wkc} / 期望 {args.expected_wkc}") # Group {args.group} WKC shortfall: measured {args.actual_wkc} / expected {args.expected_wkc}

master.events.add_wkc_shortage_occurred(wkc_short)
The expected value is not lowered because of a shortage

expected_wkc comes from the group expected value fixed at configuration time; the SDK only reports the gap truthfully and does not modify the expectation or bend it to the measurement. After the slave recovers, actual rises naturally and the shortage event stops.

def add_nic_link_changed(self, callback: Callable[[NicLinkChangedEventArgs], None]) -> None

Register a master NIC link up/down edge listener (accessed through master.events): the primary port (primary) and the redundancy port (redundant) are judged independently.

Trigger and edges:

  • Sample the physical link state of the primary / redundancy port; value semantics: 0=DOWN, 1=UP, any other value = UNKNOWN (insufficient evidence);
  • The first observation only establishes a baseline and is not delivered; afterwards only a state flip is delivered (UP→DOWN or DOWN→UP);
  • UNKNOWN is not delivered and does not update the baseline — a failed read is never written up as down;
  • On read failure (underlying layer unavailable / that leg unavailable) each leg warns once and skips that round;
  • No polling when there are no subscribers or when the master has no underlying channel.

Payload NicLinkChangedEventArgs (frozen dataclass):

  • master_index (int) — master index
  • adapter_name (str) — link leg identifier, whose only values are "primary" / "redundant". The Python SDK does not keep the NIC name passed to set_network() on the master object, so this is not an OS NIC name and does not pretend to be
  • mac (str) — always an empty string: the Python SDK has no MAC query surface that avoids an external process, so it is honestly left empty rather than invented
  • is_up (bool) — True = link up (recovered), False = link down (disconnected)
  • timestamp_utc (datetime) — time the poll detected this edge (UTC)

Threading and synchronization: same diagnostic polling daemon thread as add_wkc_shortage_occurred; likewise holds no internal lock and iterates over a snapshot.

Example:

def nic_link(args):
print(f"{args.adapter_name} 链路{'恢复' if args.is_up else '断开'}") # {args.adapter_name} link {'restored' if args.is_up else 'disconnected'}

master.events.add_nic_link_changed(nic_link)

Input data changes (removed, use polling)​

Removed (2026-05-21)

on_input_changed() (master level) and slave.events.add_input_changed() (slave level) have been deleted.

The old mechanism relied on the underlying library comparing input PDO changes byte by byte every cycle and invoking a callback. Once the application layer owns its own process image of the PDOs (map once and read directly, or copy a whole-frame snapshot), that mechanism is no longer driven.

To detect input changes, the recommended approach is to map once (inputs_mapping) and then compare the struct fields every cycle; for snapshot scenarios, read slave.pdo.inputs (an owned snapshot) in the on_pdo_cycle() callback or in a polling thread you create yourself, and compare it with the previous cycle:

_last_inputs = {}

def on_pdo_cycle(mi):
for si in range(1, len(master) + 1):
cur = master[si].pdo.inputs
if cur is not None and _last_inputs.get(si) != cur:
_last_inputs[si] = cur
print(f"从站 {si} 输入变化: {cur[:4].hex()}") # Slave {si} input change: {cur[:4].hex()}

master.on_pdo_cycle(on_pdo_cycle)
Struct view

bind_pdo_struct is implemented on top of inputs_mapping / outputs_mapping and is a from_address direct mapping (not a from_buffer_copy snapshot): on the input side every read gives the latest value, on the output side changing a field writes the bus. When you only need a snapshot, copy the whole inputs frame and use struct.unpack_from.

Redundancy events​

on_redundancy_mode_changed()​

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

Triggered when the redundancy operating mode changes. old_mode / new_mode correspond to RingMode enum values (RingMode.INACTIVE=0, RingMode.DUAL=1, RingMode.DEGRADED=2).

Callback arguments: (master_index, old_mode, new_mode)

Example:

from darra_ethercat import RingMode

def on_red_change(mi, old, new):
print(f"冗余模式: {RingMode(old).name} -> {RingMode(new).name}") # Redundancy mode: {RingMode(old).name} -> {RingMode(new).name}

master.on_redundancy_mode_changed(on_red_change)
def add_slave_port_link_changed(self,
callback: Callable[[int, int, int, bool], None]) -> None

Triggered when the physical link of a slave ESC port changes (one of P0-P3 disconnects or recovers). The diagnostic cycle checks the link bit of the DL Status register once per second; 1→0 triggers "disconnect" and 0→1 triggers "recover".

Use it to pinpoint the faulty cable segment (when opposite-facing ports of adjacent slaves report a break at the same time, the cable in between is at fault).

Callback arguments:

  • master_index (int) — master index
  • slave_index (int) — slave index (1-based)
  • port (int) — port number 0-3, corresponding to P0 / P1 / P2 / P3
  • is_up (bool) — True = link recovered, False = link disconnected

Example:

events = master.events

def on_port_link(mi, si, port, is_up):
action = "恢复" if is_up else "断开" # restored / disconnected
print(f"从站 {si} 端口 P{port} link {action}") # Slave {si} port P{port} link {action}

events.add_slave_port_link_changed(on_port_link)
Combined with break-point location

master.diagnostics_info.break_point provides an aggregated view of the fault point (broken line + CRC faults). slave_port_link_changed is the raw event source and is suited to real-time alarming.

Log callback​

set_log_callback()​

def set_log_callback(self, callback: Optional[Callable[[int, str], None]]) -> None

Set the log callback; pass None to clear this instance's registration.

Callback arguments:

  • category (int) — log category
  • message (str) — log message

Example:

def on_log(category, message):
labels = {0: "错误", 1: "警告", 2: "消息", 3: "邮箱", 4: "PDO", 5: "调试"} # error / warning / message / mailbox / debug
print(f"[{labels.get(category, str(category))}] {message}")

master.set_log_callback(on_log)

Advanced event system (MasterEvents)​

The MasterEvents class provides multi-listener support and automatic routing of slave-level events. All event callbacks are registered in one place, and MasterEvents dispatches them to the corresponding listeners automatically.

events = master.events

# === PDO cycle callbacks (synchronous only; async callbacks were removed on 2026-05-21) ===
events.add_pdo_cyclic_sync(lambda mi: None) # PDO cycle callback (worker thread)

# === Master state changes ===
events.add_state_changed(lambda old, new:
print(f"主站: 0x{old:02X} -> 0x{new:02X}")) # Master: 0x{old:02X} -> 0x{new:02X}

# === Slave state changes ===
events.add_slave_state_changed(lambda mi, si, old, new:
print(f"从站 {si}: 0x{old:02X} -> 0x{new:02X}")) # Slave {si}: 0x{old:02X} -> 0x{new:02X}

# === Hot-plug ===
events.add_slave_offline(lambda si: print(f"从站 {si} 离线")) # Slave {si} offline
events.add_slave_online(lambda si: print(f"从站 {si} 上线")) # Slave {si} online

# === Exception events ===
events.add_pdo_frame_loss(lambda mi, grp, cons, total:
print(f"组 {grp} 丢帧: {cons}")) # Group {grp} frame loss: {cons}

events.add_emergency(lambda mi, si, ec, er, b1, w1, w2:
print(f"从站 {si} 紧急: 0x{ec:04X}")) # Slave {si} emergency: 0x{ec:04X}

events.add_dc_sync_lost(lambda mi, si, diff:
print(f"从站 {si} DC 同步丢失: {diff}ns")) # Slave {si} DC sync lost: {diff}ns

# Note: the input data change callback (add_input_data_changed) was removed on 2026-05-21,
# poll slave.pdo.inputs inside the on_pdo_cycle callback and compare instead.

# === Redundancy ===
events.add_redundancy_mode_changed(lambda mi, old, new:
print(f"冗余: {old} -> {new}")) # Redundancy: {old} -> {new}

# === Slave port link change (disconnect / recover) ===
events.add_slave_port_link_changed(lambda mi, si, port, is_up:
print(f"从站 {si} P{port} {'恢复' if is_up else '断开'}")) # Slave {si} P{port} {'restored' if is_up else 'disconnected'}

# === Slave identity mismatch (hot-plug self-repair) ===
events.add_slave_identity_mismatch(lambda args:
print(f"从站 {args.slave_index} 身份不符, 实际 Vendor=0x{args.actual_vendor:08X}")) # Slave {args.slave_index} identity mismatch, actual Vendor=0x{args.actual_vendor:08X}

# === Diagnostic events (SDO failure / mailbox exception / DC unified stream / DC recovery edge / WKC shortage / NIC link) ===
events.add_sdo_error(lambda args:
print(f"从站 {args.slave_index} SDO 失败 abort=0x{args.abort_code:08X}")) # Slave {args.slave_index} SDO failed abort=0x{args.abort_code:08X}
events.add_mailbox_error(lambda args:
print(f"从站 {args.slave_index} 邮箱异常 {args.kind.name}")) # Slave {args.slave_index} mailbox exception {args.kind.name}
events.add_dc_event_raised(lambda args:
print(f"DC 事件 {int(args.code)}: {args.params}")) # DC event {int(args.code)}: {args.params}
events.add_dc_sync_restored(lambda args:
print(f"从站 {args.slave_index} DC 恢复, " # Slave {args.slave_index} DC recovered,
f"失锁 {args.lost_duration.total_seconds() * 1000:.0f} ms")) # lock lost for {args.lost_duration.total_seconds() * 1000:.0f} ms
events.add_wkc_shortage_occurred(lambda args:
print(f"组 {args.group} WKC 短缺: {args.actual_wkc}/{args.expected_wkc}")) # Group {args.group} WKC shortfall: {args.actual_wkc}/{args.expected_wkc}
events.add_nic_link_changed(lambda args:
print(f"{args.adapter_name} 链路 {'恢复' if args.is_up else '断开'}")) # {args.adapter_name} link {'restored' if args.is_up else 'disconnected'}

# === Query slave offline state ===
if events.is_slave_offline(2):
print("从站 2 处于离线状态") # Slave 2 is offline

# === Remove listeners ===
events.remove_slave_offline(my_callback)

clear_all() (MasterEvents)​

def clear_all(self) -> bool

Clear all event subscriptions to prevent memory leaks. Removes all callbacks registered through add_* at once, and also stops the PDO worker and clears the offline slave tracking set. Returns True when the PDO worker has stopped safely.

Example:

events = master.events
events.add_slave_offline(lambda si: print(f"从站 {si} 离线")) # Slave {si} offline
events.add_emergency(lambda mi, si, ec, er, b1, w1, w2: None)

# clear all subscriptions
events.clear_all()

Slave-level events (SlaveEvents)​

Slave-level events are accessed through slave.events (you must first obtain a slave instance via master[n]). Event arguments are automatically filtered to the current slave and do not include master_index / slave_index.

slave = master[1]

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

# emergency messages (error_code, error_reg, b1, w1, w2)
slave.events.add_emergency(lambda ec, er, b1, w1, w2:
print(f"紧急: 0x{ec:04X}")) # Emergency: 0x{ec:04X}

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

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

# Note: the slave-level input data change callback (add_input_changed) was removed on 2026-05-21,
# poll slave.pdo.inputs inside the on_pdo_cycle callback and compare instead.

# remove listeners
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)

clear_all() (SlaveEvents)​

def clear_all(self) -> None

Clear all event subscriptions for that slave (including FSoE events) to prevent memory leaks.

Example:

slave = master[1]
slave.events.add_state_changed(lambda old, new: None)
slave.events.add_emergency(lambda ec, er, b1, w1, w2: None)

# clear all subscriptions for this slave
slave.events.clear_all()

Thread safety​

Event callbacks are triggered on non-UI threads. To update a GUI or handle data on the main thread, use the corresponding thread synchronization mechanism:

Which thread delivers each event:

Registration methodDelivery threadInside an SDK internal lock
master.on_pdo_cycle()One latest-only worker thread per master (the PDO cycle thread only publishes the stamp)No
master.events.add_sdo_error()The thread that initiated the SDO call (the synchronous call stack before sdo_read() / sdo_write() returns)No
master.events.add_mailbox_error()The thread that calls MailboxTransaction.execute() (the synchronous call stack before it returns)No
master.events.add_dc_event_raised()Underlying log callback thread (process-wide)No
master.events.add_dc_sync_restored()Underlying log callback thread (immediately after the unified stream within the same log line)No
master.events.add_wkc_shortage_occurred()Diagnostic polling daemon thread (one per master, 1-second cycle)No
master.events.add_nic_link_changed()Diagnostic polling daemon thread (same thread, 1-second cycle)No

Callback exception isolation: every trigger point first snapshots the subscription table with list() and then iterates; an exception thrown by a single callback is caught in place (throttled reporting by exception type: the first 10 occurrences of the same type use logger.exception with the full call stack, the 11th is a single warning, and after that they are silently counted), it does not interrupt subsequent listeners, and it does not change the result semantics of the event source itself.

import queue

# use a queue to pass events across threads (recommended)
event_queue = queue.Queue()

def on_discovery(mi, si, found):
event_queue.put(("discovery", si, found))

master.on_slave_discovery(on_discovery)

# consume on the main thread
while True:
event_type, idx, found = event_queue.get()
print(f"从站 {idx} {'上线' if found else '离线'}") # Slave {idx} {'online' if found else 'offline'}
GIL and performance

The Python GIL makes callbacks thread-safe, but note:

  • The PDO cycle callback runs on an ordinary worker thread (not the PDO cycle thread); a slow callback only drops cycles
  • Do not perform I/O, take locks or do SDO reads/writes inside the callback
  • Pass data across threads with queue.Queue for time-consuming processing; do only fast enqueueing in the callback

Full example​

from darra_ethercat import EtherCATMaster, EcState

with EtherCATMaster() as master:
# ===== Logging =====
master.set_log_callback(lambda cat, msg: print(f"[{cat}] {msg}"))

# ===== State changes =====
master.on_state_change(lambda mi, si, old, new:
print(f"从站 {si}: 0x{old:02X} -> 0x{new:02X}")) # Slave {si}: 0x{old:02X} -> 0x{new:02X}

# ===== Emergency messages =====
master.on_emergency(lambda mi, si, ec, er, b1, w1, w2:
print(f"从站 {si} 紧急: 0x{ec:04X}")) # Slave {si} emergency: 0x{ec:04X}

# ===== Slave discovery/loss =====
master.on_slave_discovery(lambda mi, si, found:
print(f"从站 {si} {'上线' if found else '离线'}")) # Slave {si} {'online' if found else 'offline'}

# ===== PDO frame loss =====
master.on_pdo_frame_loss(lambda mi, grp, cons, total:
print(f"组 {grp} 丢帧: 连续={cons}, 累计={total}")) # Group {grp} frame loss: consecutive={cons}, total={total}

# ===== DC sync loss =====
master.set_dc_sync_lost_callback(lambda mi, si, diff:
print(f"从站 {si} DC 同步丢失: {diff}ns")) # Slave {si} DC sync lost: {diff}ns

# ===== Redundancy mode change =====
master.on_redundancy_mode_changed(lambda mi, old, new:
print(f"冗余: {old} -> {new}")) # Redundancy: {old} -> {new}

# ===== PDO cycle callback (synchronous, for real-time control such as FSoE) =====
# input change detection is now done by polling slave.pdo.inputs in this callback and comparing
master.on_pdo_cycle(lambda mi: None)

# connect and run
master.set_network(r"\Device\NPF_{GUID}")
master.set_state(EcState.OP)
master.start()

Unsubscribe​

Every MasterEvents.add_*() has a matching MasterEvents.remove_*(callback); the master.on_*() compatibility entry points clear the callback registered by this instance last time by passing None (this only affects this instance and does not affect other listeners registered with master.events.add_*()).

events = master.events

# remove one at a time (pass the same callback object used at registration)
events.remove_pdo_cyclic_sync(on_pdo_sync)
events.remove_state_changed(on_state)
events.remove_slave_state_changed(on_slave_state)
events.remove_emergency(on_emcy)
events.remove_slave_offline(on_offline)
events.remove_slave_offline_disputed(on_disputed)
events.remove_slave_offline_detailed(on_offline_detail)
events.remove_slave_online(on_online)
events.remove_pdo_frame_loss(on_frame_loss)
events.remove_dc_sync_lost(on_dc_lost)
events.remove_redundancy_mode_changed(on_red_mode)
events.remove_slave_identity_mismatch(on_identity_mismatch)
events.remove_slave_port_link_changed(on_port_link)
events.remove_sdo_error(on_sdo_error)
events.remove_mailbox_error(on_mailbox_error)
events.remove_dc_event_raised(on_dc_event)
events.remove_dc_sync_restored(on_dc_restored)
events.remove_wkc_shortage_occurred(on_wkc_short)
events.remove_nic_link_changed(on_nic_link)

# clear all subscriptions at once (and stop the PDO worker; returning True means the worker has stopped safely)
events.clear_all()

# master.on_*() compatibility entry points: pass None to clear
master.on_pdo_cycle(None)
master.on_state_change(None)
master.on_emergency(None)
master.on_slave_discovery(None)
master.on_pdo_frame_loss(None)
master.on_redundancy_mode_changed(None)
master.set_dc_sync_lost_callback(None)
master.set_log_callback(None)
master.set_crash_callback(None)
master.on_state_changed = None

remove_* returns silently when removing a callback that was never registered (no exception is thrown); MasterEvents.clear_all() also clears the offline registry, stops the PDO worker and the diagnostic polling. To stop only the PDO callback dispatch, call events.shutdown_pdo() (returns True = the worker has stopped safely and unregistered the underlying dispatcher; False = still draining, call it again to retry).