Skip to main content

Python-specific syntax sugar

On top of the standard API, the DarraEtherCAT Python SDK also provides Python-specific syntax sugar that makes code more Pythonic while not changing standard API behavior.

Enable it in one line:

import darra_ethercat
import darra_ethercat.sugar # injects all the syntactic sugar automatically

Import on demand:

from darra_ethercat.sugar import SlaveIdentityKey
from darra_ethercat.sugar.async_streams import EmergencyEvent
from darra_ethercat.sugar.pattern_match import classify_state, is_running
Design principles
  • Zero intrusion: sugar only monkey-patches the classes of the main SDK and does not modify any main .py file
  • Idempotent: repeating import darra_ethercat.sugar does not inject again
  • Optional: without importing sugar, main SDK behavior is unchanged
  • Backward compatible: sugar does not override the dunders the main SDK already provides (__iter__/__len__/__getitem__ ...)

Context managers​

When to useRecommended form
Synchronous script, one-off sessionwith EtherCATMaster.opening(nic, state=EcState.OP) as m:
Synchronous script, master already exists and you want to start it temporarilywith master.session(state=EcState.OP):
Switch state temporarily / manage Start-Stop / lock the IOmapmaster.scoped_state(...) / scoped_start() / scoped_lock_io()
Asynchronous application (FastAPI / aiohttp)async with EtherCATMaster() as m:
Standard formwith EtherCATMaster() as m: (built into the main SDK)

Already supported by the main SDK (no sugar needed)​

from darra_ethercat import EtherCATMaster, EcState

# Synchronous with: automatic close (stop and release)
with EtherCATMaster() as master:
master.set_network(r"\Device\NPF_{GUID}")
master.set_state(EcState.OP)
master.start()
# ... application logic
# Leaving the with-block does master.close() automatically

Sugar enhancements​

1) master.session() — start and clean up in one line​

import darra_ethercat.sugar  # activate
from darra_ethercat import EtherCATMaster, EcState

with EtherCATMaster() as master:
master.set_network(r"\Device\NPF_{GUID}")
with master.session(state=EcState.OP):
# Already OP here; the exit path calls stop() automatically
for slave in master:
print(slave.summary())

2) EtherCATMaster.opening() — factory-style context​

import darra_ethercat.sugar
from darra_ethercat import EtherCATMaster, EcState

with EtherCATMaster.opening(r"\Device\NPF_{GUID}", state=EcState.OP) as master:
print(f"已 OP, 共 {len(master)} 个从站") # Now in OP, {len(master)} slaves in total

opening() does everything on one line: create the master + set_network + set_state + start. On exit it stops and closes automatically.

3) async with master: — asyncio friendly​

import asyncio
import darra_ethercat.sugar
from darra_ethercat import EtherCATMaster

async def main():
async with EtherCATMaster() as master:
master.set_network(r"\Device\NPF_{GUID}")
master.start()
# ...
# Exit goes through the executor, so the event loop is not blocked

asyncio.run(main())

The asynchronous side also has two factories: master.async_session(state=...) (starts on entry, only stops on exit) and EtherCATMaster.aopening(nic, state=...) (create + bind the NIC + switch state + start, stop and close on exit); use them with async with.

4) Scoped guards — scoped_start / scoped_state / scoped_lock_io​

Three lightweight guards, each handling one pair of start-stop, switch or lock operations. Exit behavior:

GuardOn entryOn exit
master.scoped_start()start()stop() (does not switch state or close)
master.scoped_state(target)switch to targetrestore the state from before entry
master.scoped_lock_io()lock_iomap()unlock_iomap()
import darra_ethercat.sugar
from darra_ethercat import EcState

with master.scoped_state(EcState.PRE_OP):
... # temporary PreOp for the mailbox
# Restores the original state on exit

with master.scoped_lock_io():
... # critical section reading/writing the IOmap

scoped_start / scoped_state / session all have release(): once it is called, exiting no longer rolls back (no stop, no state restore). scoped_state also has a previous property that reads the state snapshot from before entry; the timeout_ms parameter exists only for signature compatibility (the actual per-step timeout is decided by set_state()). scoped_lock_io has no release(); it always unlocks on exit. lock_iomap() on entry is a try-lock: when the lock is not acquired it throws RuntimeError instead of pretending to be in the critical section.

Iteration / indexing / containment​

Already supported by the main SDK​

# for iteration (already supported by the main SDK)
for slave in master:
print(slave.name)

# Subscript indexing (already supported by the main SDK)
slave = master[1] # 1-based, matching the EtherCAT specification

# Length (already supported by the main SDK)
n = len(master) # number of slaves

# Convert to a list (already supported by the main SDK)
slaves = master.slaves # List[Slave]

Sugar enhancement: slave in master​

import darra_ethercat.sugar

# Index existence
if 5 in master:
print(master[5].name)

# Slave instance identity (within one master compared by (master_index, slave_index); across masters matched by identity)
if some_slave in another_master:
print("从站迁移到了另一个主站") # The slave has migrated to another master

# Query the whole network with SlaveIdentityKey
from darra_ethercat.sugar import SlaveIdentityKey

beckhoff_ek1100 = SlaveIdentityKey(
vendor_id=0x00000002, product_code=0x044C2C52,
revision_no=0, serial_no=0,
)
if beckhoff_ek1100 in master:
print("发现 EK1100") # EK1100 found

Sugar enhancement: chained filtering​

The main SDK uses the [s for s in master if ...] list comprehension. Sugar provides the shorter chained form:

from darra_ethercat import EcState

# Filter
running = master.where(lambda s: s.state == EcState.OP)

# Projection
names = master.select(lambda s: s.name)

# First match
first_beck = master.first(lambda s: s.vendor_id == 0x00000002)

# Throw when not found
master.first_or_raise(lambda s: s.name == "EL1008", message="缺 EL1008")

# Group
by_vendor = master.group_by(lambda s: s.vendor_id)
# {0x2: [Slave[1], Slave[2]], 0x66f: [Slave[3]]}

# Count
n_dc = master.count_where(lambda s: s.has_dc)
  • master.where(p) — equivalent to [s for s in master if p(s)]; suits chaining and short expressions
  • master.select(f) — equivalent to [f(s) for s in master]; suits chained projection
  • master.first(p) — equivalent to next((s for s in master if p(s)), None); suits finding the first match
  • master.first_or_raise(p) — equivalent to next + KeyError; suits cases where a match must exist
  • master.group_by(k) — equivalent to itertools.groupby + sort; suits cases that do not require sorted output

Sugar enhancement: reverse iteration / bounds checks / chained query views​

import darra_ethercat.sugar
from darra_ethercat import EcState

# Iterate in reverse (highest 1-based index first)
for slave in reversed(master):
...

# Bounds-checked access (1-based; the main SDK's master[idx] lazily creates on out of range)
s = master.at(5) # out of range raises IndexError
s = master.slave_opt(5) # out of range returns None

# Chained query view: one materialised snapshot, so iterating it repeatedly does not hammer the underlying library
q = master.query().with_vendor(0x66F).in_state(EcState.OP)
for s in q:
...
drive = q.find_by_id(0x66F, 0x10040305) # first by vendor+product, returns None if absent
by_name = master.find_by_name("EL2004")
op_list = master.in_state(EcState.OP) # list[Slave], ignores the ACK/Error bits and compares only the base state
  • master.at(i) / master.slave_opt(i) — a bounds-checked master[i], 1-based
  • master.query() — a SlaveQuery chained view (where / select / in_state / with_vendor / with_product / with_group / online_only / with_dc / with_protocol / first / last / first_or_raise / last_or_raise / any_where / all_where / count_where / group_by / skip / take / slice / find_by_id / find_by_name / to_list / to_identity_strings)
  • master.find_by_id(vendor_id, product_id) / master.find_by_name(name) — find the first match by identity or name; returns None when there is none
  • master.in_state(state) — one-step filter for the given base state, returns list[Slave]
online_only and the three-state online verdict

online_only() only excludes slaves that are explicitly judged lost; when the online verdict cannot be read (unknown), the slave is not excluded — "could not read it" is not treated as offline, to avoid false negatives.

Sugar enhancement: slaves as set / dict elements​

import darra_ethercat.sugar

s1 = master[1]
s1_again = master[1]

assert s1 == s1_again # __eq__ goes through (master_index, slave_index)
assert hash(s1) == hash(s1_again)

ignored = {master[3], master[5]} # set dedup
if some_slave not in ignored:
...

Async generators​

Turn the "register a callback" pattern into an async for ...: streaming API. Internally an asyncio.Queue acts as the thread bridge. state_changes(maxsize=256) backs up and takes over on_state_changed on entry and restores it on exit; the main SDK has no unregister for slave_state_changes(maxsize=256) / emergencies(maxsize=512), so after a stream exits, an already-registered callback filling a queue with no consumer fails quietly (QueueFull is ignored).

Master state change stream​

import asyncio
import darra_ethercat.sugar
from darra_ethercat import EtherCATMaster, EcState

async def watch_state():
async with EtherCATMaster() as master:
master.set_network(r"\Device\NPF_{GUID}")
master.start()

async for change in master.state_changes():
print(f"主站: {change.old_state} -> {change.new_state}") # Master: {change.old_state} -> {change.new_state}
if change.new_state == EcState.OP:
break

asyncio.run(watch_state())

change is a frozen dataclass StateChange(old_state: int, new_state: int, timestamp: float).

Slave state change stream​

async def watch_slaves():
async with EtherCATMaster() as master:
# ...
async for change in master.slave_state_changes():
print(f"slave[{change.slave_index}]: "
f"0x{change.old_state:02X} -> 0x{change.new_state:02X}")

Emergency message stream​

async def watch_emergency():
async with EtherCATMaster() as master:
# ...
async for ev in master.emergencies():
print(f"slave[{ev.slave_index}] EMCY 0x{ev.error_code:04X} "
f"reg=0x{ev.error_register:02X} @ {ev.timestamp:.3f}s")
if ev.error_code == 0x0000:
# Error cleared, continue
continue

CoE 0x10F3 diagnostic history stream​

The ETG.1020 standard defines the 0x10F3 diagnostic message ring buffer. Sugar wraps the four steps — poll → read meta → read message → ack — into an async stream:

async def watch_diagnostics(slave):
async for raw in slave.coe.diagnostic_stream(poll_ms=50):
# raw is the raw Octet bytes; skip the 8-byte header to get the text
text = raw[8:].decode("utf-8", errors="replace")
print(f"[diag] {text}")
  • poll_ms — polling interval, default 50 ms. Too small a value loads the CoE mailbox; 20-200 is recommended
  • buf_size — buffer for a single message, default 1024 bytes

To exit: just break; the internal sleep ends automatically and no background thread is left behind.

When to use async streams​

  • FastAPI / aiohttp backend pushing EtherCAT events in real time — async stream
  • Continuous monitoring in a Jupyter notebook — async stream + nest_asyncio
  • Legacy synchronous script taking a one-off snapshot — main SDK callbacks (master.on_emergency(cb))

Dataclasses and immutable identity (SlaveIdentityKey)​

In the main SDK, slave.identity returns a dict:

{'vendor_id': 0x2, 'product_code': 0x044C2C52, 'revision_no': 0, 'serial_no': 0}

Sugar provides an immutable wrapper:

from darra_ethercat.sugar import SlaveIdentityKey

key = SlaveIdentityKey.from_slave(master[1])
# repr(key) = SlaveIdentityKey(vendor=0x00000002, product=0x044C2C52, rev=0x00000000, serial=0x00000000)

# Tuple unpacking
vendor, product, rev, serial = key

# Usable as a dict key / set element
seen = {key}
catalog: dict[SlaveIdentityKey, str] = {key: "EK1100"}

# Value comparison
assert SlaveIdentityKey.from_slave(master[1]) == key

# Compatible with the main SDK identity dict
key2 = SlaveIdentityKey.from_dict(master[1].identity)
assert key == key2

# Standard verification logic (revision: actual >= configured counts as compatible)
assert actual_key.matches(configured_key, check_revision=True, check_serial=False)

# Conversions: to_tuple() returns (vendor, product, revision, serial), to_dict() returns a dict shaped like identity
vendor, product, rev, serial = key.to_tuple()
d = key.to_dict() # {'vendor_id': ..., 'product_code': ..., 'revision_no': ..., 'serial_no': ...}

Why a frozen dataclass instead of NamedTuple​

  • A frozen dataclass generates __eq__/__hash__/__repr__ automatically and keeps field type annotations
  • NamedTuple is ambiguous in isinstance checks (it subclasses tuple)
  • Dataclass field names and order stay consistent, which makes the documentation easier to maintain

Pattern matching (Python 3.10+)​

EcState is an IntEnum, so match/case works directly:

from darra_ethercat import EcState

match slave.state:
case EcState.OP:
print("运行中") # Running
case EcState.SAFE_OP:
print("安全运行") # Safe operation
case EcState.PRE_OP | EcState.INIT:
print("启动中") # Starting
case s if s & 0x10:
print(f"错误 ack 待处理: 0x{s:02X}") # Error ack pending: 0x{s:02X}
case other:
print(f"未知 0x{other:02X}") # Unknown 0x{other:02X}

Sugar provides higher-level semantic functions:

from darra_ethercat.sugar import classify_state, is_running, is_error

s = slave.state_raw # raw byte, bit4 (Error) preserved; slave.state has already dropped the Error bit
print(classify_state(s)) # "operational" / "pre-operational" / "operational/ack-pending" ...

if is_running(s): # SafeOp / OP and **no Error bit** (both 0x14 / 0x18 return False)
...
if is_error(s): # Error bit (bit4 = 0x10) = 1
slave.set_error_ack()

classify_state output table (main SDK integer → sugar string):

state (hex)classify_state
0x01init
0x02pre-operational
0x03boot
0x04safe-operational
0x08operational
0x12pre-operational/error
0x14safe-operational/error
0x18operational/ack-pending

With the Error bit set, a non-OP base state produces 基础态/error, and the OP base state produces operational/ack-pending.

The same module also provides a match-friendly structured split and AL Status Code classification:

from darra_ethercat.sugar import StatePattern, StateMatch, split_state, classify_al

# StatePattern: semantic constants with the same values as the classify_state labels
match classify_state(slave.state):
case StatePattern.OP:
...
case StatePattern.PREOP:
...

# split_state: split into (base state label, error bit) and then match
match split_state(slave.state):
case StateMatch(base=StatePattern.OP, error=False):
...
case StateMatch(error=True):
... # fields: base / error / raw / code

# AL Status Code -> ALErrorCategory (the main SDK's classify_al_error)
classify_al(0x0021) # transient error / configuration error / hardware error ...

Companion predicates: is_transient / is_configuration / is_hardware (AL Status Code category) and identity_match(slave, vendor_id=..., product_code=...) (filter by identity fields; fields not passed are not checked) can be imported directly from darra_ethercat.sugar; the base-state predicates is_init / is_preop / is_boot / is_safeop / is_op live in the darra_ethercat.sugar.pattern_match submodule.

Debug summary (summary())​

The main SDK's __str__/__repr__ are single-line and suit logs:

>>> print(repr(slave))
Slave(index=3)

>>> print(slave)
Slave[3] EL2004 (0x00000002:0x07d43052)

Sugar provides a multi-line summary():

>>> print(slave.summary())
Slave[3] @ master 0
name : EL2004
identity : Vendor=0x00000002 Product=0x07D43052 Rev=0x00100000
state : 8
has_dc : True
group : 0

>>> print(master.summary())
EtherCATMaster[0] 7 slaves
state : 8
loop_cycle : 1000000 ns
slaves : 7

summary() does not replace __str__; it is an explicit call. Suits the REPL and fault logs.

Static typing (type hints + Protocol)​

Every public sugar symbol carries type annotations, and the protocols submodule provides PEP 544 structural protocols for mypy / pyright:

from darra_ethercat import EcState
from darra_ethercat.sugar.protocols import MasterLike, SlaveLike, CoELike

def configure_drive(slave: SlaveLike) -> None:
"""任何具备 .coe 等属性的对象都满足 SlaveLike.""" # Any object with attributes such as .coe satisfies SlaveLike.
slave.coe.sdo_write_value(0x6060, 0, 8, dtype="u8")
slave.coe.sdo_write_value(0x6040, 0, 0x06, dtype="u16")

# The main SDK's Slave already satisfies SlaveLike, no inheritance needed
configure_drive(master[1])

# A test mock also satisfies it (duck typing + statically checkable Protocol)
class MockSlave:
coe: CoELike = ...
state: int = EcState.OP
name: str = "mock"
identity: dict | None = None
configure_drive(MockSlave()) # passes mypy

They are decorated with @runtime_checkable, so isinstance(obj, SlaveLike) also works as a runtime check (recommended for debugging only — do not put it on a business hot path: a Protocol isinstance is slower than a nominal one).

Pythonic APIs the main SDK already provides (sugar does not duplicate them)​

CapabilitySource
with EtherCATMaster() as master:EtherCATMaster.__enter__/__exit__
for slave in master:EtherCATMaster.__iter__
master[1]EtherCATMaster.__getitem__
len(master)EtherCATMaster.__len__
master.slaves (List[Slave])EtherCATMaster.slaves
str(slave) / repr(slave)Slave.__str__/__repr__
str(master) / repr(master)EtherCATMaster.__str__/__repr__
master.from_json(cfg) one-step initializationEtherCATMaster.from_json (classmethod)
master.on_state_change(cb) callbackEtherCATMaster.on_state_change
master.on_emergency(cb) callbackEtherCATMaster.on_emergency
master.groups[g][i] group access_GroupAccessor / _GroupView

Calling any of the above does not require import darra_ethercat.sugar.

Cheat sheet​

import darra_ethercat
import darra_ethercat.sugar
from darra_ethercat import EtherCATMaster, EcState
from darra_ethercat.sugar import SlaveIdentityKey, classify_state

# 1) One line to enter OP + cleanup
with EtherCATMaster.opening(r"\Device\NPF_{...}", state=EcState.OP) as master:

# 2) iteration / indexing / containment
for slave in master: # __iter__
if 5 in master and slave.index == 5: # __contains__
print(master[5].summary()) # __getitem__ + summary

# 3) chain filtering
beck = master.where(lambda s: s.vendor_id == 0x00000002)
by_vendor = master.group_by(lambda s: s.vendor_id)
n_op = master.count_where(lambda s: classify_state(s.state) == "operational")

# 4) immutable identity tuple
keys = {SlaveIdentityKey.from_slave(s) for s in master}

# 5) pattern matching
match master[1].state:
case EcState.OP: ...
case EcState.SAFE_OP | EcState.PRE_OP: ...

# 6) async stream (inside an async function)
# async for ev in master.emergencies(): ...
# async for raw in master[1].coe.diagnostic_stream(): ...

Turning sugar off​

Simply do not import darra_ethercat.sugar — main SDK behavior is completely unchanged. Sugar is only an optional enhancement and does not affect production deployment.