Skip to main content

Properties and state machine

Properties​

CategoryPropertyTypeR/WDescription
Basic informationmaster_indexintread-onlyMaster instance index
master_numberintread-onlyMaster number (alias of master_index)
slave_countintread-onlyNumber of online slaves
slavesList[Slave]read-onlySlave list (1-based index mapping)
is_disposedboolread-onlyWhether the master has been released
Network and linklink_statusEcLinkStateread-onlyNetwork link state
link_stateEcLinkStateread-onlyLink state (alias of link_status)
redundancy_ring_modeRingModeread-onlyRedundancy ring operating mode; ring_mode is a compatibility alias
secondary_frame_link_statePhyLinkStateread-onlySecondary port frame-level link tri-state: UP=1, DOWN=0, UNKNOWN=-1
secondary_link_okboolread-onlyCompatibility health check: True only when explicitly Up; False for both Down and unknown
udp_modeboolread-writeWhether UDP frame mode is used; a failed write does not raise, so read it back to confirm
udp_availableboolread-onlyWhether UDP frame mode is available (whether the UDP channel of this master was established successfully)
Error codeserror_codeEcALStateread-onlyAL Status Code, the cause of failure when a state transition fails
last_errorintread-onlyWindows error code passed through from the underlying layer when the last set_network() failed; 0 means no failure
Slave groupinggroups_GroupAccessorread-onlyGroup indexer
active_group_countintread-onlyNumber of active groups
IO mappingobytesintread-onlyTotal output bytes
ibytesintread-onlyTotal input bytes
obitsintread-onlyTotal output bits
ibitsintread-onlyTotal input bits
DC and cyclehas_dcOptional[bool]read-onlyWhether DC slaves exist: True / False is a definite answer; a failed read returns None (unknown)
loop_cycleintread-writePDO exchange cycle time (nanoseconds)
DiagnosticsidentityOptional[dict]read-onlyMaster identity information (ETG.1510)
diagnosticsOptional[dict]read-onlyETG.1510 diagnostics data
diagnostics_infoMasterDiagnosticsInforead-onlyAdvanced diagnostics information object
last_state_errorOptional[dict]read-onlyReal state snapshot from the last failed set_state(); cleared to None after success
Runtimeaggregated_stateEcStateread-onlySystem aggregate state: the lowest base state across all real slaves plus the aggregated Error bit; returns EcState.NONE (unknown) when no slave takes part and never falls back to the master-state cache
Runtimecommunication_statsOptional[dict]read-onlyCommunication statistics: total / successful / failed / timed-out cycles and average / maximum / minimum cycle time (microseconds); None when the master number is invalid
pdo_monitoringboolread-writePDO statistics collection switch (process-wide); turning it off clears the per-slave PDO statistics; off by default
pdo_thread_cpu_effective_coreintread-onlyCPU core number the PDO thread is actually bound to; -1 = not bound / multi-core mask / thread not started / unreadable
on_init_progressobjectread-onlyInitialization progress subscription proxy (supports add / remove / decorator form); multicast during build_async / set_state_async
is_async_operation_in_progressboolread-onlyWhether an asynchronous operation is currently queued or running; for diagnostics only, not as a control-flow criterion

last_error​

@property
def last_error(self) -> int

Windows error code passed through from the underlying layer when the last set_network() failed. 0 means the previous call did not fail or was not set.

set_network() returning 0 has two meanings — failure, or success with no slaves on the bus, so this property must be read to tell them apart.

ValueMeaningAction
0The previous set_network() did not fail—
5ERROR_ACCESS_DENIED — the current runtime library and the installed driver are not the same identity pair (the runtime only accepts a runtime library built in the same batch as this driver), or the instance shutdown/claim window has not endedReinstall the matching runtime with the official installer; do not replace the DLL on its own
21The driver's network protocol layer is not ready (re-enumeration / self-repair in progress, transient)Retry later
1168The network protocol is not bound to a NICRebind the NIC with the official installer
170ERROR_BUSY — device busy. The specific cause is determined by the driver instance's LastError; four values can come back with 170: 30 = RT real-time channels exhausted; 2 = the instance is still held by a live handle; 23 = the NIC is occupied by another master instance; 22 = the polling thread failed to start/rebuild. In addition, 20 = driver network initialization failure (the underlying NTSTATUS is passed through as-is) and 31 = the admission quota was exhausted, set by the polling thread after StartRT succeeded — neither of these is a 170 replyDispatch on LastError; this SDK only passes the Windows error code through and does not classify it kernel-side
5023The data gate is closed (licensing not passed), unrelated to the NICCheck / fix the license and runtime environment; do not swap the network cable

Other values are interpreted as Windows system error codes.

last_state_error​

@property
def last_state_error(self) -> Optional[dict]

Real state snapshot recorded when the last set_state() failed; cleared to None after successfully entering the target state.

set_state() only returns bool; whether a failure means "the master did not move" or "a slave's AL rejected the transition" must be checkable — this property, together with the failure log, gives per-slave state and AL code instead of leaving the cause in free text.

Return value Optional[dict]:

  • target (int) — target base state (0x00..0x08)
  • master_state (int | None) — aggregated master state at the moment of failure; None if unreadable
  • slaves (List[dict]) — one entry per slave:
    • index (int) — slave index (1-based)
    • state (int | None) — low 4 bits of the AL state at the moment of failure; None if unreadable
    • error_flag (bool) — Error bit of AL Status (0x10)
    • al_status_code (int | None) — AL Status Code of that slave; None if unreadable
    • at_target (bool) — whether that slave is already in the target base state

Read-only snapshot only; it does not change any state transition criteria.

Example:

if not master.set_state(EcState.OP):
snap = master.last_state_error
if snap is not None:
print(f"目标=0x{snap['target']:02X}, 主站={snap['master_state']}") # target=0x{snap['target']:02X}, master={snap['master_state']}
for s in snap['slaves']:
if not s['at_target']:
print(f" #{s['index']} state={s['state']} "
f"AL=0x{(s['al_status_code'] or 0):04X}")

communication_stats​

@property
def communication_stats(self) -> Optional[dict]

Cumulative communication statistics of this master. The PDO cycle thread updates them once per completed cycle (success / failure / timeout counted separately), for observing communication health and cycle duration.

Return value Optional[dict]:

  • total_cycles (int) — total number of cycles
  • successful_cycles (int) — number of successful cycles
  • failed_cycles (int) — number of failed cycles
  • timeout_cycles (int) — number of timed-out cycles
  • avg_cycle_time_us (float) — average duration of successful cycles (microseconds)
  • max_cycle_time_us (float) — maximum cycle duration (microseconds)
  • min_cycle_time_us (float) — minimum cycle duration (microseconds)

Returns None when the master number is invalid; when the master has not run a PDO cycle yet it returns a dictionary of all 0 (not None). The counter fields are 32-bit and wrap around during long runs.

After reset_communication_stats(), min_cycle_time_us is first set to the placeholder maximum 999999.0 and only becomes a real value after the next successful cycle.

Example:

stats = master.communication_stats
if stats is not None:
print(f"周期 {stats['total_cycles']} / 失败 {stats['failed_cycles']} / " # cycles {stats['total_cycles']} / failures {stats['failed_cycles']} /
f"平均 {stats['avg_cycle_time_us']:.1f} µs") # average {stats['avg_cycle_time_us']:.1f} µs

pdo_thread_cpu_effective_core​

@property
def pdo_thread_cpu_effective_core(self) -> int

The CPU core the PDO thread is actually bound to (read from the thread's real mask), not the configured value. The value set by set_cpu_affinity() may be rejected by the system or rewritten by the scheduling policy; only this property tells you whether the binding really took effect.

Return value:

  • int — core number, starting at 0
  • -1 — no single core number can be given: the thread is not started, not bound, the mask covers multiple cores, or the mask is unreadable

Example:

core = master.pdo_thread_cpu_effective_core
print("PDO 线程核:", core if core >= 0 else "未绑定/不可用") # PDO thread core: not bound / unavailable

udp_mode / udp_available​

@property
def udp_mode(self) -> bool

@udp_mode.setter
def udp_mode(self, enable: bool)

@property
def udp_available(self) -> bool

udp_mode controls whether this master encapsulates EtherCAT datagrams in UDP/IP; udp_available indicates whether the UDP channel was established successfully when this master was initialized.

Standard EtherCAT slaves only accept standard Ethernet frames. UDP mode applies only to gateways / EAP devices that support UDP; enabling it for standard slaves makes communication fail outright.

The setter reports nothing; you must read back to confirm

master.udp_mode = True is rejected by the underlying layer when the UDP channel is unavailable or the master is not initialized, but the Python setter does not raise — it only writes a log entry. After switching, always read master.udp_mode back to confirm it really took effect; do not try to enable it when udp_available is False.

Example:

if master.udp_available:
master.udp_mode = True
if not master.udp_mode:
print("UDP 模式未生效,仍走标准 EtherCAT 帧") # UDP mode is not in effect; still using standard EtherCAT frames

pdo_monitoring​

@property
def pdo_monitoring(self) -> bool

@pdo_monitoring.setter
def pdo_monitoring(self, enabled: bool)

Collection switch for PDO performance statistics. It is process-wide, not per master, and off by default.

  • When off, the read / write counts and duration fields of pdo_stats() stop growing (error_count keeps accumulating as usual).
  • Turning it off also clears the PDO statistics of all slaves.
  • When an older runtime library lacks this entry point, reading always yields False and writing is silently ignored.

Example:

master.pdo_monitoring = True
# ... run for a while, then read master.pdo_stats() ...
master.pdo_monitoring = False # disabling it also clears the statistics

on_init_progress​

@property
def on_init_progress(self)

Initialization progress subscription proxy. build_async() / set_network_async() / set_state_async() report progress text in Chinese from a background thread, so the UI can display "scanning / entering OP".

Supported registration forms:

  • master.on_init_progress.add(callback)
  • master.on_init_progress.remove(callback)
  • decorator: @master.on_init_progress
  • store the proxy in a variable first, then ev += callback / ev -= callback
Callbacks fire on a background thread

Do not modify UI controls directly inside the callback; switch back to the main thread yourself (asyncio with loop.call_soon_threadsafe, Qt signals, tkinter after). An exception raised by a subscriber is only logged at DEBUG level and does not affect the initialization flow.

You cannot use += directly on the property

on_init_progress is a read-only property; master.on_init_progress += callback raises AttributeError. To use +=, store the proxy in a variable first (ev = master.on_init_progress; ev += callback).

Example:

master.on_init_progress.add(lambda msg: print("[初始化]", msg))   # [Init]

EcLinkState​

from enum import IntEnum

class EcLinkState(IntEnum):
DISCONNECTED = 0 # Confirmed disconnected: both configured ports explicitly DOWN
CONNECTED = 1 # Both the primary and the redundancy port are connected
PRIMARY_ONLY = 3 # Only the primary port is connected
SECONDARY_ONLY = 4 # Only the redundancy port is connected
UNKNOWN = 5 # Unknown: not initialized / underlying state not observable / PHY has not reported yet

DISCONNECTED only means "confirmed disconnected"; when the physical link cannot be read, UNKNOWN is returned — it does not mean disconnected, so the UI should show "unknown" rather than "link down".

Python-specific syntax sugar

Besides master.slaves (List[Slave]), the main SDK already supports for slave in master: / master[1] / len(master); sugar further wires up chained queries such as slave in master (index or identity containment check) / master.where(p) / master.first(p) / master.group_by(k).

State machine control​

state​

@property
def state(self) -> Optional[EcState]

Get the master's current EtherCAT state (read-only).

EcState enum:

from enum import IntEnum

class EcState(IntEnum):
NONE = 0x00
INIT = 0x01
PRE_OP = 0x02
BOOT = 0x03
SAFE_OP = 0x04
OP = 0x08
ACK = 0x10
ERROR = 0x10

Extra EcState property base_state:

@property
def base_state(self) -> 'EcState'

Returns the base state from the low 4 bits (equivalent to EcState(self.value & 0x0F)), stripping the Error/Ack flag 0x10 before comparing.

EcState can also carry a composite state directly: EcState(0x14) (SafeOp+Error) / EcState(0x18) (OP+Error) both construct fine, and an unnamed value is named like STATE_0x1A — it no longer raises ValueError because "the low 4 bits are not a defined state value / a flag is set in the high bits". has_error / base_state / format() all parse such values correctly.

EcState(0x18).base_state    # EcState.OP (0x08)
EcState(0x12).base_state # EcState.PRE_OP (0x02)
EcState(0x18) != EcState.OP # True - it carries the Error bit, so it is not a healthy OP
EcState(0x18).has_error # True
EcState(0x18).format() # "OP+Error"
Python-specific syntax sugar

EcState is an IntEnum, so Python 3.10+ can use match state: case EcState.OP: ... pattern matching directly; sugar also provides the semantic functions classify_state(s) / is_running(s) / is_error(s).

set_state()​

def set_state(self, state: EcState) -> bool

Switch the EtherCAT master state. This is the only public synchronous state machine API. Internally it performs the chained transitions across levels (INIT → PRE_OP → SAFE_OP → OP), executes the Before/After startup parameters at each step, and starts the PDO thread after entering SafeOp/OP. The per-step timeout is not a fixed value; it is calculated dynamically from the workload of the startup parameters; when the target is OP the lower bound is higher; a timeout fails that step immediately. On failure it returns False and records the cause (see last_state_error).

Internal automatic retry

The SDK automatically retries each state transition step internally (a retry only resumes the failed state step), which absorbs transient issues such as hardware self-adaptation and link jitter. The application layer does not need to wrap a for _ in range(3): master.set_state(...) loop around it; repeated retries only lengthen the total time of the failure path.

Automatic sync configuration for SafeOp

When switching to SAFE_OP, the SDK automatically configures the sync cycle count threshold and the SyncManager sync type (FreeRun fallback) for non-DC slaves according to the ETG standard, the application layer does not need to write them manually.

DC slaves skip this automatic configuration to avoid conflicting with the DC time base. If a custom sync strategy is needed, override it after switching to SAFE_OP.

Parameters:

  • state (EcState) — target state (INIT / PRE_OP / SAFE_OP / OP)

Returns:

  • bool — whether it succeeded (False if all internal retries fail, or if a single step times out)

Example:

from darra_ethercat import EcState

# Switch the master state (only care whether it succeeds)
if not master.set_state(EcState.OP):
print(f"状态切换失败, 错误码: {master.error_code}") # State transition failed, error code: {master.error_code}

On failure, read slave.error_code / slave.al_status_code for each slave to identify which slave and which AL Status Code caused the failure.

Async variant (does not block the calling thread):

async def set_state_async(self, state: EcState,
progress: Optional[Callable[[str], None]] = None,
cancel=None) -> bool

The async version of set_state(): the state transition runs on a background thread (including retries and the OP demote-grace wait), queues through this master's serial gate and does not run concurrently with other async EtherCAT operations; returns bool. Optional progress (progress callback) and cancel (cancel token; cancelling requests aborting the blocked transition and makes the call return); when the async isolation layer has not taken over, it degrades to thread-pool execution. On failure, likewise read slave.error_code / slave.al_status_code per slave to locate the cause.

A cancel token can be created with from darra_ethercat import CancelToken (thread-safe; token.cancel() requests cancellation, token.is_cancelled queries it), or an asyncio.Event / threading.Event can be passed directly. After cancellation, the await point raises asyncio.CancelledError.

import asyncio
from darra_ethercat import EcState

async def main():
ok = await master.set_state_async(EcState.OP)
if not ok:
print(f"状态切换失败, 错误码: {master.error_code}") # State transition failed, error code: {master.error_code}

asyncio.run(main())

execute_with_state_management()​

def execute_with_state_management(self, required_state: EcState,
operation: Callable[[], bool],
operation_name: str = "") -> bool

Wraps an operation that "can only be done in a given state" in automatic state management: first switch the master to required_state (underlying state sequence, fixed 5000 ms timeout), then run operation() once the switch succeeds.

  • The original state is not restored after the operation; to step back down, call set_state() yourself.
  • Re-entrancy protection: if a state transition is already in progress, operation() runs directly without a nested transition.
  • operation must not be None, takes no arguments, and success is judged by the truthiness of its return value.
  • An exception thrown by operation is swallowed and reported as failure; it does not propagate.

Parameters:

  • required_state (EcState) — state required by the operation
  • operation (Callable[[], bool]) — the operation to run
  • operation_name (str) — operation name, used only to distinguish log entries; defaults to an empty string

Returns:

  • bool — True when the state switch succeeded and the operation returned a truthy value; False when the switch failed, the operation raised, or it returned a falsey value

Raises:

  • ValueError — operation is None

Example:

ok = master.execute_with_state_management(
EcState.SAFE_OP,
lambda: slave.coe.sdo_write(0x1C12, 0, bytes([1])),
"写 PDO 分配", # Write PDO assignment
)
master.set_state(EcState.OP) # this method will not restore the previous state for you

execute_with_state_management_value()​

def execute_with_state_management_value(self, required_state: EcState,
operation: Callable,
operation_name: str = "",
default_value=None)

The value-returning version of execute_with_state_management(): it returns the result of operation() after the state switch succeeds, and returns default_value if any step fails.

Re-entrancy protection and exception handling are the same: when a state transition is already in progress the operation runs directly; an exception thrown by the operation counts as failure and default_value is returned.

Parameters:

  • required_state (EcState) — state required by the operation
  • operation (Callable) — the operation to run; it may return any type
  • operation_name (str) — operation name, used only to distinguish log entries; defaults to an empty string
  • default_value — value returned on failure, default None

Returns:

  • the operation's return value; default_value when the state switch fails, the operation raises, or the re-entrant branch raises

Raises:

  • ValueError — operation is None

Example:

count = master.execute_with_state_management_value(
EcState.SAFE_OP,
lambda: master.slave_count,
"读从站数", # Read slave count
default_value=0,
)

validate()​

def validate(self) -> ValidationResult

Configuration pre-check before Build. Checks whether the master configuration meets the minimum requirements; use it before calling build().

Returns:

  • ValidationResult — contains is_valid (bool) and errors (List[str])

Example:

result = master.validate()
if not result.is_valid:
for err in result.errors:
print(f"配置错误: {err}") # Configuration error: {err}
else:
master.build()

deconstruct()​

def deconstruct(self)

Works with chained construction to support destructuring assignment; returns (master, build_result). build() itself returns the instance, so deconstruct() must be chained to actually unpack it.

Return value:

  • master (EtherCATMaster) — the current instance
  • result (dict) — build result:
    • success (bool) — whether the master initialized successfully; when auto-configuration was requested, a failed auto-configuration also counts as False
    • slave_count (int) — number of slaves at build time
    • master_index (int) — master index
    • esi_matched (bool | None) — whether an ESI is bound; None when no ESI was loaded
    • esi_matched_count (int | None) — number of matched slaves; None when no ESI was loaded
    • auto_startup_rc (int | None) — auto-configuration return code; None when auto-configuration was not requested

Before build() has been called, result has only the first three keys, and success is decided by whether the master index is valid.

Example:

master, result = EtherCATMaster().set_network(adapter).build().deconstruct()
if not result["success"]:
print("构建失败, 主站索引:", result["master_index"]) # Build failed, master index:

start() / stop()​

def start(self) -> None
def stop(self) -> None

Start/stop the PDO cycle thread and the state monitoring thread.

Example:

master.set_state(EcState.OP)
master.start()
# ... run ...
master.stop()

Safe stop​

safe_stop()​

def safe_stop(self) -> None

Performs a controlled stop on this instance (not an emergency stop): for slaves with registered axes it freezes the target position to the actual position, and it writes CiA402 ControlWord 0x0006 (Shutdown, controlled disable) to each slave. It does not write 0x0000 and does not trigger STO; the deceleration behaviour is decided by the slave's own Shutdown option.

It affects only this master; other masters in the same process are unaffected. Failures do not raise, they only log a warning — whether the stop actually took effect must be judged from the slave state and the logs, not from whether this method reported an error.

Example:

master.safe_stop()

EtherCATMaster.safe_stop_all()​

@staticmethod
def safe_stop_all() -> None

Runs the same controlled stop on all active masters in this process. Multi-master applications affect other instances too; use safe_stop() for single-instance scenarios.

It is skipped with a warning when the runtime library is unavailable; no exception ever propagates.

Example:

EtherCATMaster.safe_stop_all()

Process data watchdog​

set_all_watchdog()​

def set_all_watchdog(self, timeout_ms: int) -> int

Set the process data watchdog timeout for all slaves in one batch.

Parameters:

  • timeout_ms (int) — timeout (milliseconds), 0 = disabled; only 0–6553 accepted (register limit)

Returns:

  • int — number of slaves actually written (including slaves written after being raised by the safety lower bound); 0 = 0 written successfully (not a synonym for failure)

Raises (three states reported truthfully; never reports "all set as requested"):

  • WatchdogTimeoutError with actual_ms=None — the request is outside 0–6553, the whole batch is rejected, no slave is written
  • WatchdogTimeoutError with actual_ms / actual_by_slave / success_count — some slaves in this batch were raised by the safety lower bound (branch slaves 5000 ms / ring PDO slaves 400 ms, required by the topology protocol): actual_by_slave = {从站号: 实际毫秒 or None} (only slaves whose read-back value differs from the request or that cannot be read; None = that slave cannot be read), success_count = number of slaves written
  • No exception = all written as requested, returns the number of slaves written
from darra_ethercat import WatchdogTimeoutError

try:
count = master.set_all_watchdog(100)
print(f"已按请求写入 {count} 个从站") # Wrote {count} slaves as requested
except WatchdogTimeoutError as e:
if e.actual_ms is None:
print("整批拒绝: 请求超出 0-6553ms 范围,一个站都没写") # Whole batch rejected: request outside the 0-6553ms range, no slave written
else:
print(f"部分被安全下限抬升: 已写 {e.success_count} 站, 逐站实际 {e.actual_by_slave}") # Some were raised to the safety floor: {e.success_count} slaves written, actual per slave {e.actual_by_slave}
0 means 0 written successfully

Returning 0 means "0 slaves written successfully" (for example when there are currently no slaves), which differs from "failure"; failures always go through exceptions.

set_all_pdi_watchdog()​

def set_all_pdi_watchdog(self, timeout_ms: int) -> int

Set the PDI watchdog timeout for all slaves in one batch; used to detect interface faults between the ESC and the slave MCU.

Parameters:

  • timeout_ms (int) — timeout (milliseconds), 0 = disabled; only 0–6553 accepted

Returns:

  • int — number of slaves actually written (0 = 0 written successfully)

Raises: WatchdogTimeoutError (actual_ms=None) — the whole batch is rejected when the request is out of range. PDI has no safety lower bound, so the "raised" signal does not normally occur.

Diagnostics control methods​

reset_diagnostics()​

def reset_diagnostics(self) -> None

Clear all diagnostic counters (frame loss / jitter / WKC / RX errors, and so on); usually reset before long-term observation.

reset_slave_port_error_counters()​

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

Clear the ESC error counters of the 4 ports of the specified slave (0x300/0x302/0x304/0x306, used for physical-layer link diagnostics).

Parameters:

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

Returns:

  • bool — True on success
Companion APIs

master.lock_iomap() / unlock_iomap() let you disable mutex_protection and then lock manually for multi-axis batched atomic writes; writes go through the direct mapping path outputs_mapping (fields write the process image at the same address), while whole-frame replacement with write_outputs is the snapshot path. update_diagnostics_snapshot() works with diagnostics_info to read real-time performance metrics.

Cycle time statistics are maintained automatically by the RT PDO thread and can be read directly through the diagnostics API; the application layer does not need to and cannot inject cycle times manually anymore.

reset_communication_stats()​

def reset_communication_stats(self) -> None

Clears the communication statistics counters of this master (see communication_stats). After the reset the minimum cycle time is first set to the placeholder value 999999.0; it becomes a real reading only after the next successful cycle.

Example:

master.reset_communication_stats()

perf_export_csv()​

def perf_export_csv(self, filename: str) -> int

Exports the performance statistics to a CSV file.

Parameters:

  • filename (str) — target file path (passed to the runtime library as UTF-8)

Returns:

  • int — 0 on success; other values are error codes:
    • -1 — invalid parameter, or the file cannot be created
    • -2 — performance collection is not initialized
    • -3 — performance collection has been turned off
    • -4 — there are no samples to export (no file is created)

No CSV is produced on failure. Judge success by a return value of 0 and the file actually existing, not just by whether a file was created.

Example:

rc = master.perf_export_csv("ecat_perf.csv")
if rc != 0:
print("导出失败, 返回码:", rc) # Export failed, return code:

get_pdo_frame_loss_stats()​

def get_pdo_frame_loss_stats(self, group: int = 0) -> dict

Reads the cumulative PDO frame loss statistics of the specified group.

Parameters:

  • group (int) — group index, default 0

Returns:

  • total_lost (int) — cumulative number of lost frames
  • consecutive_lost (int) — current consecutive frame loss count (cleared after a good frame)
  • max_consecutive_lost (int) — historical maximum consecutive frame loss count

When the group number is out of range all three values come back 0 and no error is raised — 0/0/0 can only be read as "this group lost no frames"; do not use it to infer whether the group number is valid.

Example:

loss = master.get_pdo_frame_loss_stats(0)
print(loss["total_lost"], loss["consecutive_lost"], loss["max_consecutive_lost"])

reset_pdo_frame_loss_stats()​

def reset_pdo_frame_loss_stats(self, group: int = 0) -> None

Clears the cumulative / consecutive / maximum consecutive frame loss counters of the specified group. It does nothing, silently, when the group number is invalid.

Example:

master.reset_pdo_frame_loss_stats(0)
def get_slave_link_quality(self, slave_index: int) -> int

Reads the link quality percentage of a slave.

Parameters:

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

Returns:

  • 0–100 — measured quality. 0 is a legitimate "worst" value, not unknown
  • -1 — unknown: diagnostics not initialized yet, the slave has not been sampled yet, or the slave index is invalid

Example:

quality = master.get_slave_link_quality(1)
print("链路质量:", f"{quality}%" if quality >= 0 else "未知") # Link quality: unknown

get_slave_port_error_stats()​

def get_slave_port_error_stats(self, slave_index: int)

Reads a snapshot of the ESC error counters of the 4 ports of the specified slave.

Parameters:

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

Returns:

  • Optional[dict] — None when the read fails, the runtime library lacks this entry point, or the slave index is invalid; on success:
    • rx_error_count (List[int]) — RX error counts of ports 0–3
    • invalid_frame_count (List[int]) — invalid frame counts of ports 0–3
    • lost_link_count (List[int]) — lost link counts of ports 0–3

Each list always has 4 elements, ordered by port 0–3; a single counter is an 8-bit snapshot value that wraps above 255, so long-term observation should use differences. This entry point returns only these three groups; the forwarded RX error counter is not among them.

To clear them, use reset_slave_port_error_counters().

Example:

stats = master.get_slave_port_error_stats(1)
if stats is not None:
print("端口 RX 错误:", stats["rx_error_count"]) # Port RX errors:

PDO statistics and direct read/write​

pdo_stats()​

def pdo_stats(self, slave_index: int) -> Optional[dict]

Reads the PDO read/write performance statistics of the specified slave. The read / write counts and duration fields only grow while master.pdo_monitoring = True.

Parameters:

  • slave_index (int) — slave index (1-based); passing 0 reads the reserved slot (no slave writes it), not an aggregate

Returns:

  • Optional[dict] — None when the slave index is out of range or the read fails; on success:
    • read_count (int) — number of reads
    • write_count (int) — number of writes
    • error_count (int) — number of failed reads/writes (not affected by the monitoring switch, always accumulated)
    • total_bytes_read (int) — cumulative bytes read
    • total_bytes_written (int) — cumulative bytes written
    • last_cycle_time_ns (int) — duration of the most recent read (nanoseconds)
    • min_cycle_time_ns (int) — minimum read duration (nanoseconds)
    • max_cycle_time_ns (int) — maximum read duration (nanoseconds)
    • avg_cycle_time_ns (int) — average read duration (nanoseconds), smoothed per call as (旧值 + 本次) / 2, not a strict arithmetic mean

The counter fields are 32-bit and wrap around on long runs. Statistics are stored per slave index and are not isolated per master — with multiple masters, slaves with the same number share one set of statistics.

Example:

master.pdo_monitoring = True
stats = master.pdo_stats(1)
if stats is not None:
print(f"读 {stats['read_count']} 次, 平均 {stats['avg_cycle_time_ns']} ns") # {stats['read_count']} reads, average {stats['avg_cycle_time_ns']} ns

reset_pdo_stats()​

def reset_pdo_stats(self, slave_index: int) -> None

Clears PDO statistics. Passing 0 clears the statistics of all slaves; pass a slave index starting at 1 to clear a single slave; out-of-range slave indices are silently ignored.

Example:

master.reset_pdo_stats(1)   # clear slave 1 only
master.reset_pdo_stats(0) # clear everything (mind the scope)

pdo_read_direct()​

def pdo_read_direct(self, slave_index: int, pdo_index: int, buffer_size: int) -> Optional[bytes]

Reads the slave's input process data (TxPDO byte stream) directly from the process image.

Parameters:

  • slave_index (int) — slave index (1-based)
  • pdo_index (int) — reserved by the calling convention; the current read always takes the slave's complete input process data and does not slice it by index. Passing 0 is recommended
  • buffer_size (int) — read buffer size in bytes, must be greater than 0

Returns:

  • bytes — the input data actually read, length ≤ buffer_size; empty bytes when it succeeds but there is no data
  • None — buffer_size <= 0, invalid slave index, or the underlying read failed

Example:

data = master.pdo_read_direct(1, 0, 256)
if data is not None:
print("输入字节数:", len(data)) # Input byte count:

pdo_write_direct()​

def pdo_write_direct(self, slave_index: int, pdo_index: int, data: bytes) -> bool

Compatibility write entry point: updates the leading bytes of the RxPDO through the slave's single versioned transaction path.

Parameters:

  • slave_index (int) — slave index (1-based)
  • pdo_index (int) — only 0 is accepted. The historical implementation never interpreted this parameter, and a value other than 0 cannot be mapped reliably to a byte offset, so it always fails
  • data (bytes) — output data to write, must not be empty

Returns:

  • bool — True = written as a versioned transaction; False = invalid parameter (pdo_index != 0, empty data, invalid slave index) or the write failed
A pdo_index other than 0 is not a "partial write"

Passing a value other than 0 does not degrade to "write at some offset"; it returns False outright. To rewrite by offset, use the output data API on the slave object.

Example:

ok = master.pdo_write_direct(1, 0, b"\x01\x00")
if not ok:
print("写入被拒绝:检查 pdo_index 是否为 0、数据是否为空") # Write rejected: check whether pdo_index is 0 and whether the data is empty

Hot-plug self-repair​

When the power is cut and the slave is replugged / replaced, the SDK automatically detects the identity mismatch and enters a protected state, so that a wrong device is not mistakenly included in the control loop.

acknowledge_slave_replacement()​

def acknowledge_slave_replacement(self, slave_num: int) -> bool

The user confirms that the slave replacement is complete, which triggers the EtherCAT identification state machine to probe that slave again.

When to call: after subscribing to master.events.add_slave_identity_mismatch() and receiving an identity mismatch alarm, once the operator has finished checking / replacing the device, call this method to let the SDK re-detect.

Behavior:

  • If the identity has been corrected (the correct device restored / same model with an upgraded Revision) → restores automatically and fires the slave_online event
  • If the identity still does not match → fires slave_identity_mismatch again and returns to the IDENT_REJECTED state

Parameters:

  • slave_num (int) — slave index (1-based, consistent with the configuration)

Returns:

  • bool — True = accepted and the FSM has been reset; False = the parameter is invalid, or the slave is currently not in the IDENT_REJECTED / FAILED state (calling before receiving a slave_identity_mismatch event returns False)
The event must arrive first

Calling this method has no effect before the slave_identity_mismatch event has fired. While the slave has not entered the protected state, the SDK keeps probing normally and no manual confirmation is needed.

Example:

# Must use master.events: it is the event container registered with the master
events = master.events

def on_identity_mismatch(args):
print(f"从站 {args.slave_index} 身份不符: " # Slave {args.slave_index} identity mismatch:
f"期望 Vendor=0x{args.expected_vendor:08X}, " # expected Vendor=0x{args.expected_vendor:08X},
f"实际 Vendor=0x{args.actual_vendor:08X}") # actual Vendor=0x{args.actual_vendor:08X}

# UI dialog: "Check the device of slave N and click confirm after restoring the correct model"
if show_replacement_dialog(args.slave_index):
ok = master.acknowledge_slave_replacement(args.slave_index)
if not ok:
print("确认失败: 从站不在 IDENT_REJECTED 状态") # Acknowledge failed: the slave is not in IDENT_REJECTED state

events.add_slave_identity_mismatch(on_identity_mismatch)
Do not create your own event container

MasterEvents(master) constructs an unregistered standalone object: it is not on the master's dispatch path, so callbacks added to it never fire. Always use master.events for event subscriptions.

Difference from slave_offline / slave_online
  • slave_offline — the slave lost power / connection (identity still matches), recovers automatically and fires slave_online
  • slave_identity_mismatch — the slave identity changed (wrong device, i.e. Vendor + Product do not match the configuration; the revision is not part of the identity check), which requires a manual call to acknowledge_slave_replacement()

Identity verification and cache pool​

verify_all_slave_identities()​

def verify_all_slave_identities(self, expected_identities: list = None,
check_revision: bool = False,
check_serial: bool = False) -> dict

Checks all online slaves against expected identities in one batch; index 0 of the expected list corresponds to slave 1. Use it before going live and after replacing parts to confirm the same batch of devices is connected.

Parameters:

  • expected_identities (list) — list of SlaveIdentity. Passing None takes the current online slave identities as the expectation: that is a self-comparison which can only reveal "the identity changed during the read" and cannot be used to verify which devices should be connected
  • check_revision (bool) — whether to compare RevisionNo, default False
  • check_serial (bool) — whether to compare SerialNo, default False

Returns:

  • success (bool) — True when everything matches; False when anything mismatches, or when the master has 0 registered slaves but verification was requested
  • mismatch_mask (int) — bitmask of mismatching slaves, bit N = slave N+1. The mask is only 64 bits wide, so mismatches beyond slave 65 do not appear in it, but success is still False

The range actually checked is min(len(expected_identities), 主站在册站数); when the expected list is longer than the bus, the extra entries are not checked. With None and 0 registered slaves it returns success=True immediately.

Example:

from darra_ethercat import SlaveIdentity

expected = [SlaveIdentity(vendor_id=0x00000002, product_code=0x0C1C3052,
revision_no=0x00100000, serial_no=0)]
result = master.verify_all_slave_identities(expected, check_revision=True)
if not result["success"]:
print(f"身份不符掩码: 0x{result['mismatch_mask']:016X}") # Identity mismatch mask: 0x{result['mismatch_mask']:016X}

check_buffer_integrity()​

def check_buffer_integrity(self) -> bool

Cache pool buffer tamper check. It is not a license check and does not mean the license is valid; for the real license status use the licensing API Authorization.license_status (a read-only property — read it directly, do not add parentheses; Authorization.LicenseStatus is the same value).

Returns:

  • bool — the current binding treats "the underlying return code is exactly 1" as true. The underlying convention is 0 for a passed check and non-zero as a failure code, so this method returns False when the check passes and returns True when the certificate file cannot be found (return code 1).
The current implementation has a defect in the direction of the return value

This bool cannot currently be used to judge "integrity passed" or "license valid": the direction is the opposite of the underlying convention and is a known defect. Until it is fixed, treat it only as diagnostic evidence and rely on the runtime library logs for the conclusion. Use the licensing API for a license verdict.

Example:

# Kept only as a diagnostic trace; do not use the return value to decide whether it passed
print("缓存池防篡改返回值:", master.check_buffer_integrity()) # Buffer pool tamper-check return value:

Topology refresh​

rebuild_topology()​

def rebuild_topology(self) -> None

Rebuild the slave topology accessor. Call it after the slave list changes (hot-plug / rescan) to force the slave_topology view to re-derive the parent-child relationships and port mapping.

# Refresh the topology view after rescanning
master.set_network(adapter)
master.rebuild_topology()

topology = master.slave_topology
# SlaveTopology has no __iter__; do not write for node in master.slave_topology
# (out-of-range indexing returns None instead of raising IndexError, so implicit iteration never stops)
print(f"根节点数: {len(topology)}") # Root node count: {len(topology)}

def walk(node, depth=0):
print(f"{' ' * depth}slave {node.index} parent={node.parent_index}")
for child in topology.get_children(node):
walk(child, depth + 1)

for root in topology.root_slaves:
walk(root)

To traverse the whole chain you can also use master.topology directly (returns an iterable List[dict]). The entry points of SlaveTopology are root_slaves / get_children() / [索引或地址字符串].

SlaveTopology.find_by_vendor_product()​

def find_by_vendor_product(self, vendor_id: int, product_code: int) -> List[Slave]

Filters slaves by vendor ID and product code.

Parameters:

  • vendor_id (int) — vendor ID (object dictionary 0x1018:1)
  • product_code (int) — product code (object dictionary 0x1018:2)

Returns:

  • List[Slave] — the matching slaves; an empty list when nothing matches; slaves whose identity cannot be read are skipped

Every call re-reads the identity of all online slaves, so this is a low-frequency query — do not call it repeatedly from a cycle callback.

Example:

same_model = master.slave_topology.find_by_vendor_product(0x00000002, 0x0C1C3052)
print("同型号从站:", [s.index for s in same_model]) # Slaves of the same model:

SlaveTopology.get_child_count()​

def get_child_count(self, parent: Slave) -> int

Returns the number of direct child modules of the specified slave, equivalent to len(get_children(parent)).

Parameters:

  • parent (Slave) — parent slave

Returns:

  • int — number of child modules; 0 when parent is None

Example:

root = master.slave_topology.root_slaves[0]
print("子模块数:", master.slave_topology.get_child_count(root)) # Submodule count:

SlaveTopology.rebuild()​

def rebuild(self) -> None

Rebuilds the topology view: re-reads each slave's parent, entry port, physical type and configured address, and rebuilds the root / child / address indexes. Call it after the slave list changes (hot-plug, rescan).

  • Normally you do not call it directly: master.rebuild_topology() forwards to this method and only rebuilds topology accessors that have already been created.
  • When the master is empty or the online slave count is 0, it clears the view and returns without raising.
  • When a slave's topology fields cannot be read, that slave takes part in the tree with all-0 fields and no exception is raised.

Example:

topology = master.slave_topology
topology.rebuild() # rebuild the view after the slave list changes

topology / topology_children() / topology_roots()​

@property
def topology(self) -> List[dict]

def topology_children(self, parent_index: int, max_results: int = 64) -> List[int]
def topology_roots(self, max_results: int = 64) -> List[int]

Build the network topology node list; query the child nodes of the specified parent slave / the network root nodes (directly connected to the master). The returned dictionaries contain slave_index / config_addr / parent_index / entry_port / active_ports / topology / port_type.

IOmap lock​

lock_iomap() / unlock_iomap()​

def lock_iomap(self) -> bool
def unlock_iomap(self) -> None

Manually acquire / release the process image mutex; used to commit multiple slave output groups atomically per batch when mutex_protection is disabled. lock_iomap() is a try-lock (non-blocking): returning True means the lock is held, and unlock_iomap() must be called in a matching way when the critical section ends; returning False means the lock is not held (held by another thread / the master is not ready / shutting down), and in that case you must not enter the critical section, nor call unlock_iomap(). Writes go through the direct mapping path outputs_mapping (fields write the process image at the same address), while whole-frame replacement with write_outputs is the snapshot path.

master.mutex_protection = False
if not master.lock_iomap():
raise RuntimeError("LockIOmap 未取得锁:另一线程仍持有,拒绝进入临界区") # LockIOmap did not acquire the lock: another thread still holds it, refusing to enter the critical section
try:
for slave in master.slaves:
frame = bytearray(slave.pdo.outputs or b'')
if len(frame) >= 2:
frame[0:2] = (0x0F).to_bytes(2, 'little')
slave.pdo.write_outputs(bytes(frame))
finally:
master.unlock_iomap()

copy_io()​

def copy_io(self, slave_index: int) -> Optional[Tuple[bytes, bytes]]

Get a snapshot of the slave's complete RxPDO / TxPDO (the complete output / input process data is read from the underlying layer). Not an IOmap pointer. Returns None on failure.

Returns:

  • (output_data, input_data) — tuple of owned bytes

State machine granularity​

The Python SDK only exposes the whole-device chained state transition master.set_state() (internally performing the step-by-step INIT → PRE_OP → SAFE_OP → OP transitions and retries). Standalone state machine management classes for single-step / single-slave granularity currently have no public entry point; do not follow old documentation and try from darra_ethercat.master import MasterStateManager (that module has been removed and the import will fail). To locate a failure cause, use master.last_state_error together with per-slave slave.state / slave.al_status_code.

ESM timeouts (EsmTimeouts)​

The default ETG.1020 state transition timeouts (milliseconds). The values are provided by the runtime library; the values actually in effect for this master are shown in config.timeout_init_to_preop / config.timeout_preop_to_safeop / config.timeout_safeop_to_op.

MethodReturnsPurposeKey value
init_to_preop()int (ms)Init → PreOp3000
preop_to_safeop()int (ms)PreOp → SafeOp (includes PDO mapping)10000
safeop_to_op()int (ms)SafeOp → OP10000
op_to_safeop()int (ms)OP → SafeOp200
safeop_to_preop()int (ms)SafeOp → PreOp200
preop_to_init()int (ms)PreOp → Init5000
to_boot()int (ms)Any → Boot10000
boot_to_init()int (ms)Boot → Init5000
get_transition_timeout(current_state, target_state, dll=None)int (ms)Look up by state pair0 = illegal transition / value retrieval failed (no fabricated timeout); self-transition 100
SDO_TIMEOUT / MAILBOX_TIMEOUT / STATE_STABILIZE_DELAYintCommunication timeout / settle wait after a state transition3000 / 5000 / 100
from darra_ethercat import EcState, EsmTimeouts

print(EsmTimeouts.get_transition_timeout(EcState.PRE_OP, EcState.SAFE_OP)) # 10000

AL status code categories​

MethodReturnsPurposeKey value
classify_al_error(code)ALErrorCategoryProgramming decision (whether to retry)NONE=0 / TRANSIENT=1 retryable / CONFIGURATION=2 needs reconfiguration / HARDWARE=3 needs intervention / UNKNOWN=4
EcALState(code).describe()strHuman-readable display (in Chinese; the single source of wording is the underlying library's AL Status table)≥ 0x8000 → vendor-specific; codes outside the table fall back to 未知(0x....) (SDK output, = unknown), with no invented wording

The single authority for classification is the runtime library; the Python side only maps 0..4 → ALErrorCategory; when unavailable it returns UNKNOWN. English AL Status descriptions are not currently provided.

from darra_ethercat import ALErrorCategory, classify_al_error

cat = classify_al_error(int(master.error_code))
if cat == ALErrorCategory.TRANSIENT:
master.set_state(EcState.OP) # Transient error, can retry
elif cat == ALErrorCategory.CONFIGURATION:
print("配置错误, 检查 ENI / startup 参数") # Configuration error, check the ENI / startup parameters

Process-level checks​

EtherCATMaster.is_adapter_available()​

@staticmethod
def is_adapter_available(adapter: str, dll_path: Optional[str] = None) -> bool

Check whether this NIC can be used by a new master instance within this process; use it to ask "will this collide" before opening a second master.

  • Returns False: a master instance that is still alive in this process and has not really been released is bound to this NIC.
  • Returns True: there is no such occupant (never bound, or the occupant has been close()d / has been reclaimed).

The criterion comes from the in-process NIC binding registry: binding the NIC successfully in set_network() registers it, and completing the release in close() unregisters it; after the occupant is reclaimed the registration becomes invalid automatically. This is in-process coordination; it does not cross processes and does not probe NIC binding or link state (cross-process exclusivity is decided by the runtime layer). Passing an empty string as adapter always returns False; dll_path is kept only for compatibility, and the underlying library is no longer loaded.

if EtherCATMaster.is_adapter_available("\\Device\\NPF_{GUID-A}"):
master = EtherCATMaster().set_network("\\Device\\NPF_{GUID-A}")

EtherCATMaster.validate_timer_accuracy()​

@staticmethod
def validate_timer_accuracy(expected_usec: int, tolerance_usec: int,
dll_path: Optional[str] = None) -> int

Verify the actual accuracy of the OS high-precision timer. Returning 0 means within tolerance, non-zero means outside tolerance; on Windows, a non-zero return usually means the high-precision timer service is not enabled or HPET is disabled in the BIOS.

EtherCATMaster.get_active_instance_count()​

@staticmethod
def get_active_instance_count(dll_path: Optional[str] = None) -> int

Number of master instance slots currently in use (not the limit). It prefers the authoritative count from the runtime library; when that read fails it falls back to counting the master objects still registered in this process; when neither is available it returns 0 and logs a warning — that 0 does not mean the real count is 0. When the runtime library itself fails to load, the exception propagates.

Parameters:

  • dll_path (Optional[str]) — runtime library path; None means automatic search

Returns:

  • int — number of occupied slots

Example:

print("当前实例数:", EtherCATMaster.get_active_instance_count())   # Current instance count:

EtherCATMaster.get_max_instance_count()​

@staticmethod
def get_max_instance_count(dll_path: Optional[str] = None) -> int

Maximum number of master instances that can be created on this machine: the smaller of the runtime library's instance limit and the number of available real-time cores.

Parameters:

  • dll_path (Optional[str]) — runtime library path; None means automatic search

Returns:

  • int — maximum instance count; 0 means no instance can be created right now (also returned when the instance count calculation fails)

The exception propagates when the runtime library fails to load.

Example:

print("实例上限:", EtherCATMaster.get_max_instance_count())   # Instance limit:

EtherCATMaster.get_available_cpu_cores()​

@staticmethod
def get_available_cpu_cores(dll_path: Optional[str] = None) -> int

Total number of logical processors available on the system (including hyper-threading); this is not the number of isolated cores, nor the number of cores reserved for a particular master. get_max_instance_count() derives from this using the real-time core count, so do not mix the two up.

Parameters:

  • dll_path (Optional[str]) — runtime library path; None means automatic search

Returns:

  • int — total number of logical processors

The exception propagates when the runtime library fails to load.

Example:

print("逻辑处理器:", EtherCATMaster.get_available_cpu_cores())   # Logical processors:

EtherCATMaster.get_serial_number()​

@staticmethod
def get_serial_number(dll_path: Optional[str] = None) -> str

Reads the device serial number string of this machine.

Parameters:

  • dll_path (Optional[str]) — runtime library path; None means automatic search

Returns:

  • str — serial number; an empty string means it cannot be read (not "the device has no serial number")

The exception propagates when the runtime library fails to load.

Example:

print(EtherCATMaster.get_serial_number())

EtherCATMaster.get_device_name()​

@staticmethod
def get_device_name(dll_path: Optional[str] = None) -> str

Reads the device name (used as a device identifier), not the NIC name.

Parameters:

  • dll_path (Optional[str]) — runtime library path; None means automatic search

Returns:

  • str — device name; an empty string means it cannot be read

The exception propagates when the runtime library fails to load.

Example:

print(EtherCATMaster.get_device_name())

EtherCATMaster.get_driver_list()​

@staticmethod
def get_driver_list(dll_path: Optional[str] = None) -> str

Reads the driver service list text of this machine, in the format 驱动名|显示名|状态;..., where state is Running / Stopped / StartPending / StopPending / Unknown.

Parameters:

  • dll_path (Optional[str]) — runtime library path; None means automatic search

Returns:

  • str — driver service list; an empty string when the read fails. The result is cached in-process after the first read and does not refresh when the system changes

Example:

for entry in filter(None, EtherCATMaster.get_driver_list().split(";")):
parts = entry.split("|")
if len(parts) == 3:
print(parts[0], parts[2])

Emergency shutdown​

EtherCATMaster.emergency_cleanup()​

@staticmethod
def emergency_cleanup(dll_path: Optional[str] = None) -> None

Fallback shutdown when the process exits / crashes: first request an abort and send a controlled stop to the slaves, then close all NIC handles of this process directly without waiting for threads to exit gracefully.

  • The scope is the whole process, not a single master instance.
  • After the call the runtime library's internal state cannot be recovered; the only way back is to restart the process and create the master again.
  • All exceptions are swallowed — nothing is raised, and success or failure is not reflected in a return value.

Parameters:

  • dll_path (Optional[str]) — runtime library path; None means automatic search

Example:

# When the process is about to exit and a normal close() is no longer possible
EtherCATMaster.emergency_cleanup()

emergency_close_nics()​

def emergency_close_nics(self) -> None

Performs the same shutdown actions as EtherCATMaster.emergency_cleanup(); the only difference is that the entry point hangs off the instance: the effect is still to close all NICs for the whole process and abort all masters, not just this instance.

Use it only on the exit path

After the call, normal sending and receiving cannot continue; the process must be restarted and the master created again. For everyday stopping use stop() / close(); for a controlled stop use safe_stop().

Example:

master.emergency_close_nics()