Skip to main content

CoE (CANopen over EtherCAT)

Access it through slave.coe. The instance is always available; whether a slave supports the CoE mailbox is determined with slave.coe.is_supported. That property is tri-state: True supported / False confirmed unsupported / None read failed (unknown).​

slave.coe is an instance of the CoE class; it provides SDO read/write and object dictionary access.

Quick start​

slave = master[1]

# Read raw SDO bytes — failure / WKC=0 returns None; always check for None before unpack
data = slave.coe.sdo_read(0x1018, 1) # Vendor ID
if data is None:
print(f"SDO 失败: {slave.coe.last_sdo_error}") # SDO_PROTOCOL_TIMEOUT != object does not exist
else:
import struct
vendor_id = struct.unpack('<I', data[:4])[0]

# Numeric read — failure also returns None
status = slave.coe.sdo_read_value(0x6041, 0, dtype='u16')
if status is None:
raise SystemExit(f"SDO 读取失败: {slave.coe.last_sdo_error}") # SDO read failed: {slave.coe.last_sdo_error}
position = slave.coe.sdo_read_value(0x6064, 0, dtype='i32')
if position is None:
raise SystemExit(f"SDO 读取失败: {slave.coe.last_sdo_error}") # SDO read failed: {slave.coe.last_sdo_error}

# Numeric write
slave.coe.sdo_write_value(0x6040, 0, 0x0006, dtype='u16')
slave.coe.sdo_write_value(0x607A, 0, 100000, dtype='i32')

# Raw byte write
import struct
slave.coe.sdo_write(0x6040, 0, struct.pack('<H', 0x0006))
sdo_read failure / WKC=0 returns None

Do not call struct.unpack on the return value directly or parse it as uint32. last_sdo_error == SDOError.SDO_PROTOCOL_TIMEOUT means the mailbox did not come back (WKC=0 / timeout), not "object does not exist". Only deterministic abort codes (6 codes, see last_sdo_error) enter the NotPresent cache; timeouts / WKC=0 are not cached.

SDO read​

sdo_read()​

def sdo_read(self, index: int, subindex: int = 0,
complete_access: bool = False, *,
detail: bool = False) -> bytes | None | SdoReadResult

Read an SDO object and return the raw byte data. With detail=True it returns a detail object (see "sdo_read(..., detail=True)" below); a plain sdo_read(index, subindex) call behaves unchanged.

Failure / WKC=0 returns None. Only an empty b'' plus NO_ERROR is an empty-string success. SDO_PROTOCOL_TIMEOUT (0x05040000) is not "object does not exist" and is not written to NotPresent; only a real abort is cached.

Parameters:

  • index (int) — object dictionary index (0x0000-0xFFFF)
  • subindex (int) — subindex, default 0
  • complete_access (bool) — whether to use complete access, default False. The 3rd positional parameter, it can be written as sdo_read(0x1018, 0, True). When True, subindex may only be 0 or 1; larger subindexes fail immediately and send no request (returns None, last_sdo_error = SDO_PROTOCOL_TIMEOUT)
  • detail (bool) — keyword-only parameter (after * in the signature), it must be written as detail=True; passing it positionally raises TypeError

Returns:

  • bytes | None — the bytes read; failure / WKC=0 returns None
  • with detail=True it returns SdoReadResult, see the next section
  • Length guard: a 0-byte response counts as an empty-object success (b'') only when WKC > 0 and there is no abort code; a 0-byte response with an abort code or a response larger than 10 MiB is returned as failure (None). The actual readable limit is determined by the underlying mailbox capacity and the slave object; split reads for very large objects

sdo_read(..., detail=True)​

result = slave.coe.sdo_read(0x1000, 0, detail=True)   # -> SdoReadResult

Returns ok / data / abort_code / wkc in a single call. When the underlying layer has no detail read entry it falls back to a normal read (in that case abort_code is the device's most recent raw abort code, and wkc is approximated as 1 / 0). After hot-plug call reset_not_present_cache() to clear the NotPresent cache (equivalent to clear_sdo_caches(); the Python layer has no separate SDO value cache). A 0-byte response counts as an empty-object success (data = b'') only when WKC > 0 and there is no abort code; a 0-byte response with an abort code or a response larger than 10 MiB is returned as failure (ok=False, data=None); split reads for very large objects.

Return value SdoReadResult (named tuple):

  • ok (bool) — whether it succeeded
  • data (bytes | None) — data on success (an empty object is b''), None on failure
  • abort_code (int) — slave abort code; if it failed without an abort code, 0x05040000 (SDO_PROTOCOL_TIMEOUT)
  • wkc (int) — working counter of this SDO transaction; <= 0 means the mailbox did not come back

Example:

import struct

result = slave.coe.sdo_read(0x1000, 0, detail=True)
if not result.ok:
print(f"SDO 读取失败: abort=0x{result.abort_code:08X}, wkc={result.wkc}") # SDO read failed: abort=0x{result.abort_code:08X}, wkc={result.wkc}
else:
device_type = struct.unpack('<I', result.data[:4])[0]
print(f"Device Type: 0x{device_type:08X}")
Compatibility

sdo_read_ex(...) is still available and is a compatibility alias equivalent to sdo_read(..., detail=True); new code should use detail=True directly.

sdo_read_value()​

def sdo_read_value(self, index: int, subindex: int = 0,
dtype: str = 'u32') -> Optional[int]

Read an SDO and parse it as a number.

Parameters:

  • index (int) — object dictionary index
  • subindex (int) — subindex
  • dtype (str) — data type: 'u8', 'u16', 'u32', 'u64', 'i8', 'i16', 'i32', 'i64'; an unsupported dtype raises ValueError

Returns:

  • int | None — the parsed value, or None if the SDO read fails; when the response bytes are short, \x00 is appended at the tail (little-endian padding of the high bytes) before parsing

Example:

# Read the status word (StatusWord, 0x6041:00)
status = slave.coe.sdo_read_value(0x6041, 0, dtype='u16')
if status is None:
raise SystemExit(f"SDO 失败: {slave.coe.last_sdo_error}") # SDO failed: {slave.coe.last_sdo_error}
print(f"StatusWord = 0x{status:04X}")

# Read the actual position (0x6064:00)
position = slave.coe.sdo_read_value(0x6064, 0, dtype='i32')
if position is None:
raise SystemExit(f"SDO 失败: {slave.coe.last_sdo_error}") # SDO failed: {slave.coe.last_sdo_error}
print(f"实际位置: {position}") # Actual position: {position}

SDO write​

sdo_write()​

def sdo_write(self, index: int, subindex: int, data: bytes,
complete_access: bool = False, *,
detail: bool = False) -> bool | SdoWriteResult

Write an SDO object. With detail=True it returns a detail object (see "sdo_write(..., detail=True)" below); a plain call behaves unchanged.

Parameters:

  • index (int) — object dictionary index
  • subindex (int) — subindex, required (no default)
  • data (bytes) — the byte data to write; an empty data returns False immediately as failure
  • complete_access (bool) — whether to use complete access, default False, the 4th positional parameter. When True, subindex may only be 0 or 1 (larger values fail immediately and return False)
  • detail (bool) — keyword-only parameter, it must be written as detail=True

Returns:

  • bool — whether the write succeeded (when detail=False)
  • with detail=True it returns SdoWriteResult, see "sdo_write(..., detail=True)" below

Example:

import struct

# Write the control word
slave.coe.sdo_write(0x6040, 0, struct.pack('<H', 0x0006))

# Write the target position
slave.coe.sdo_write(0x607A, 0, struct.pack('<i', 100000))

sdo_write_value()​

def sdo_write_value(self, index: int, subindex: int, value: int,
dtype: str = 'u32') -> bool

Write an SDO of numeric type.

Parameters:

  • index (int) — object dictionary index
  • subindex (int) — subindex
  • value (int) — the numeric value to write
  • dtype (str) — data type: 'u8', 'u16', 'u32', 'u64', 'i8', 'i16', 'i32', 'i64'; an unsupported dtype raises ValueError

Returns:

  • bool — whether the write succeeded

Example:

# Write the control word
slave.coe.sdo_write_value(0x6040, 0, 0x0006, dtype='u16')

# Write the target position
slave.coe.sdo_write_value(0x607A, 0, 100000, dtype='i32')

# Set the operating mode
slave.coe.sdo_write_value(0x6060, 0, 8, dtype='i8') # CSP mode

sdo_write(..., detail=True)​

result = slave.coe.sdo_write(0x6040, 0, struct.pack('<H', 0x0006), detail=True)  # -> SdoWriteResult

Returns ok / abort_code / wkc. An empty data returns failure immediately. When the underlying library does not support detail returns it falls back to a normal write.

Returns:

  • SdoWriteResult — (ok, abort_code, wkc) named tuple; on failure abort_code is the abort code, or SDO_PROTOCOL_TIMEOUT (0x05040000) when there is none

Example:

import struct

result = slave.coe.sdo_write(0x6040, 0, struct.pack('<H', 0x0006), detail=True)
if not result.ok:
print(f"写入失败: abort=0x{result.abort_code:08X}, wkc={result.wkc}") # Write failed: abort=0x{result.abort_code:08X}, wkc={result.wkc}
Compatibility

sdo_write_ex(...) is still available and is a compatibility alias equivalent to sdo_write(..., detail=True); new code should use detail=True directly.

Batch async read​

read_multiple_async()​

async def read_multiple_async(self, entries: list,
cancel_event=None) -> dict

Batch SDO read — read multiple objects in one call. Executed sequentially (calling sdo_read() one by one, not concurrently), running on the default thread pool, without blocking the event loop.

Failure semantics: a single failed read does not affect the other entries; that key's value is None; exceptions thrown by sdo_read() are also folded to None.

Parameters:

  • entries (list) — [(index, subindex), ...] list of objects to read
  • cancel_event (asyncio.Event, optional) — once set, the remaining reads are aborted and CancelledError is raised

Returns:

  • dict — {(index, subindex): bytes 或 None}; entries whose read failed have the value None

Example:

import asyncio

async def read_servo_status():
results = await slave.coe.read_multiple_async([
(0x6041, 0), # StatusWord
(0x6064, 0), # actual position
(0x6077, 0), # actual torque
])
for (idx, sub), data in results.items():
if data is not None:
print(f"0x{idx:04X}:{sub} = {data.hex()}")

asyncio.run(read_servo_status())

Example with cancellation:

import asyncio

cancel = asyncio.Event()

async def read_with_cancel():
try:
results = await slave.coe.read_multiple_async(
[(0x6041, 0), (0x6064, 0)],
cancel_event=cancel
)
except asyncio.CancelledError:
print("读取已取消") # Read cancelled

Async SDO​

Module-level coroutines that correspond one-to-one to sdo_read() / sdo_write(). Failures still return None / False (no business exception is thrown); only timeouts and cancellation raise exceptions.

from darra_ethercat.slave.coe import sdo_read_async, sdo_write_async

async def sdo_read_async(coe: CoE, index: int, subindex: int,
complete_access: bool = False,
timeout_ms: Optional[int] = None) -> Optional[bytes]

async def sdo_write_async(coe: CoE, index: int, subindex: int, data: bytes,
complete_access: bool = False,
timeout_ms: Optional[int] = None) -> bool

Coe instances also have methods of the same name: await slave.coe.sdo_read_async(index, subindex=0, ...) / sdo_write_async(index, subindex, data, ...). Both are equivalent to the module-level functions above (same parameters and return values) and prefer the parent master's serialization gate (falling back to background execution when no parent master is found); you no longer pass coe yourself.

Parameters:

  • coe (CoE) — the slave.coe instance, first positional parameter
  • index / subindex (int) — object index / subindex (subindex is required, no default)
  • complete_access (bool) — complete access, default False
  • timeout_ms (int | None) — timeout in milliseconds, default None means no timeout is set

Returns / exceptions:

  • sdo_read_async — returns bytes on success; returns None on SDO failure (including WKC=0), the error code is still taken from coe.last_sdo_error
  • sdo_write_async — True on success, False on failure
  • asyncio.TimeoutError — not completed within timeout_ms
  • asyncio.CancelledError — cancelled by the caller; the underlying synchronous SDO cannot really be interrupted, so it waits for it to finish naturally before raising

Example:

import asyncio
from darra_ethercat.slave.coe import sdo_read_async, sdo_write_async

async def servo_check(slave):
data = await sdo_read_async(slave.coe, 0x6041, 0, timeout_ms=200)
if data is None:
print(f"SDO 读失败: {slave.coe.last_sdo_error}") # SDO read failed: {slave.coe.last_sdo_error}
return
status = int.from_bytes(data[:2], 'little')

ok = await sdo_write_async(slave.coe, 0x6040, 0, b'\x06\x00', timeout_ms=200)
print(f"StatusWord=0x{status:04X}, 写控制字 {'成功' if ok else '失败'}") # StatusWord=0x{status:04X}, write control word {'success' if ok else 'failure'}

asyncio.run(servo_check(slave))
Different from master.sdo_read_async / Slave.sdo_read_async

This section covers the module-level functions in darra_ethercat.slave.coe, with the signature (coe, index, subindex, complete_access, timeout_ms) and no cancel token.

master.sdo_read_async(slave_index, index, subindex=0, complete_access=False, cancel=None) and Slave.sdo_read_async(index, subindex=0, ...) are another set of entry points; they go through the master serialization gate and have different parameters and return values.

slave.coe.sdo_read_async() / sdo_write_async()​

async def sdo_read_async(self, index: int, subindex: int = 0,
complete_access: bool = False, cancel=None)
async def sdo_write_async(self, index: int, subindex: int, data: bytes,
complete_access: bool = False, cancel=None)

Async SDO methods injected on the CoE instance; their parameters align with the synchronous sdo_read() / sdo_write(), and coe is not passed again.

  • With a parent master: they use the same entry points and the same per-master serialization gate as master.sdo_read_async / master.sdo_write_async (serialized, cancellable per master, completes exactly once). The cancel token takes effect on this path.
  • When no parent master is found (unit tests detached from a master): they fall back to the shared async thread pool; in that case the passed cancel has no effect, and a WARNING is logged first.

Returns / exceptions:

  • read success returns bytes, failure returns None (same semantics as the synchronous sdo_read); write success True / failure False
  • sdo_write_async with data = None raises ValueError
  • asyncio.CancelledError — cancellation took effect (cancelled in the queue, or the underlying blocking call was aborted per master)

Example:

status = await slave.coe.sdo_read_async(0x6041, 0)
ok = await slave.coe.sdo_write_async(0x6040, 0, b'\x06\x00')

shutdown_coe_async_executor()​

from darra_ethercat.slave.coe import shutdown_coe_async_executor

def shutdown_coe_async_executor(wait: bool = True) -> None

Shut down the CoE async thread pool. Call it before the program exits to release the background threads.

Parameters:

  • wait (bool) — default True, waits for the tasks already submitted to the pool to finish before returning; False returns immediately and the tasks keep running in the background until they finish

Returns:

  • None
Interaction with the other *_async entry points

The module-level coroutines in this section and read_multiple_async() use this CoE thread pool; slave.coe.sdo_*_async() goes through the master serialization gate when a parent master exists, and falls back to this thread pool only when no parent master is found. After shutdown the module holds no thread pool; the next call lazily creates one again, so this is not a permanent disable. Do not shut it down while CoE async calls are still outstanding (especially with wait=False).

Example:

import asyncio
from darra_ethercat.slave.coe import shutdown_coe_async_executor

asyncio.run(slave.coe.read_multiple_async([(0x6041, 0)]))
shutdown_coe_async_executor() # Shut the pool down after the event loop ends

Properties​

CategoryPropertyTypeRead/writeDescription
Diagnosticslast_sdo_errorSDOErrorread-onlyError code of the last SDO operation (an enum view; codes outside the table are folded to UNKNOWN_ERROR, never fabricated as GENERAL_ERROR)
Diagnosticslast_sdo_abort_codeintread-onlyThe raw abort code returned by the device on the last SDO failure (0 = success / no abort code; codes outside the table are kept as-is)
Capabilityis_supportedOptional[bool]read-onlyWhether the slave supports the CoE mailbox; True / False are definite conclusions, a failed read returns None (unknown) and is not folded into True / False
Protocolprotocol_typeintread-onlyCoE mailbox protocol type code
Protocolprotocol_namestrread-onlyAlways returns "CoE"
StatisticsstatisticsMailboxStatisticsread-onlySnapshot of the CoE mailbox statistics; returns MailboxStatistics.empty() when the underlying library does not support this capability

last_sdo_error​

@property
def last_sdo_error(self) -> SDOError

Error code of the last SDO operation. When sdo_read() / sdo_write() fails, this property gives the SDO abort code. After a successful operation it resets automatically to SDOError.NO_ERROR.

GENERAL_ERROR / SDO_PROTOCOL_TIMEOUT / UNKNOWN_ERROR are not "object does not exist"
  • SDOError.SDO_PROTOCOL_TIMEOUT (0x05040000) — WKC=0 / mailbox timeout / no communication response (the device returned no abort code). Retryable; do not treat it as object does not exist, and it is not written to NotPresent.
  • SDOError.GENERAL_ERROR (0x08000000) — the device really returned a "general error" but gave no reason; investigate it. Also not written to NotPresent.
  • SDOError.UNKNOWN_ERROR (0xFFFFFFFF) — the SDK code table does not include this abort code (vendor-specific / newer standard code); what the device actually returned must be read from last_sdo_abort_code. This entry is not device behavior and must not be treated as "the slave returned a general error".
  • Only deterministic aborts enter the NotPresent cache (6 codes): 0x06010000, READ_WRITE_ONLY_ERROR (0x06010001), WRITE_READ_ONLY_ERROR (0x06010002), OBJECT_DOES_NOT_EXIST (0x06020000), SUBINDEX_DOES_NOT_EXIST (0x06090011), SUBINDEX_DOES_NOT_EXIST_FOR_OBJECT (0x06090012). Timeouts / toggle / general errors / width errors / WKC=0 are not cached (they may recover).

Example:

data = slave.coe.sdo_read(0x6041, 0)
if data is None:
error = slave.coe.last_sdo_error
print(f"SDO 读取失败: {error.name} (0x{error.value:08X})") # SDO read failed: {error.name} (0x{error.value:08X})
print(f"描述: {error.describe()}") # Description: {error.describe()}
if error == SDOError.SDO_PROTOCOL_TIMEOUT:
print("WKC=0 / 超时,不是对象不存在") # WKC=0 / timeout — this is not 'object does not exist'

last_sdo_abort_code​

@property
def last_sdo_abort_code(self) -> int

The raw abort code returned by the device on the most recent SDO failure (0 = success / no abort code). last_sdo_error is an enum view: codes inside the table hit as-is, codes outside the table only give UNKNOWN_ERROR (0xFFFFFFFF = unknown / out-of-table) and are never folded into GENERAL_ERROR (that one means only that the slave really returned 0x08000000). Read this property when you need to distinguish abort causes precisely (especially out-of-table / vendor-specific abort codes); it performs no normalization.

Example:

data = slave.coe.sdo_read(0x2000, 0)
if data is None:
raw = slave.coe.last_sdo_abort_code
print(f"abort=0x{raw:08X}, 枚举视图={slave.coe.last_sdo_error.name}") # abort=0x{raw:08X}, enum view={slave.coe.last_sdo_error.name}
if slave.coe.last_sdo_error == SDOError.UNKNOWN_ERROR:
print("SDK 码表没收录这个码, 以 abort 原值为准") # The SDK code table does not list this code; take the raw abort value as authoritative

reset_not_present_cache()​

def reset_not_present_cache(self) -> None

Clear the CoE-level NotPresent cache (the negative cache in the master library). Call it only after hot-plug / firmware upgrade / topology change; after clearing, the same "nonexistent" object really sends an SDO again instead of being failed immediately by a cache hit.

No return value; a failed call only logs a warning and does not raise.

clear_sdo_caches()​

def clear_sdo_caches(self) -> None

Equivalent to reset_not_present_cache() (the Python layer has no separate SDO value TTL cache; only NotPresent is cleared).

reset_statistics()​

def reset_statistics(self) -> None

Zero the CoE mailbox statistics counters while keeping the runtime state. Silently ignored when the underlying library does not support this capability; no return value.

Example:

print(f"已发送 {slave.coe.statistics.total_sent} 帧, "   # Sent {slave.coe.statistics.total_sent} frames,
f"超时 {slave.coe.statistics.total_timeout} 次") # {slave.coe.statistics.total_timeout} timeouts

slave.coe.reset_statistics() # clear the counters
slave.coe.reset_not_present_cache() # clear the negative cache after hot-plug

Fields of MailboxStatistics returned by statistics: total_sent / total_received / total_timeout / total_mailbox_error / total_protocol_error / total_cancelled / last_error_code / last_error_time / average_latency_us.

SDO request statistics​

get_sdo_stats()​

def get_sdo_stats(self, *, detail: bool = False)

Read the accumulated SDO statistics for this slave.

Parameters:

  • detail (bool) — False (default) returns a (requests, retries, timeouts) tuple on success; True returns a detailed SdoStats(ok, requests, retries, timeouts) snapshot

Returns:

  • detail=False → tuple[int, int, int] | None; returns None on failure
  • detail=True → SdoStats (namedtuple: ok / requests / retries / timeouts); on failure ok=False and the counters are 0

Failure semantics:

  • underlying library unavailable / returns failure → ok=False (None in default mode); all 0s do not mean "no request was sent"
  • the counters accumulate per slave and are not cleared automatically; measure the cost of a single operation as the difference between two snapshots

Typical usage:

before = slave.coe.get_sdo_stats()
await slave.coe.sdo_read_async(0x6041, 0)
after = slave.coe.get_sdo_stats()
sent_once = (before is not None and after is not None
and after[0] - before[0] == 1
and after[1] - before[1] == 0)

Comparing only completion callback counts cannot distinguish a silent resend after an underlying timeout; the requests delta is the criterion that "really only one request was sent".

Object dictionary direct read (SDO Information)​

These three methods fetch live from the slave every time; they do not use the cached SDO list. They return the payload by default and None on failure; with detail=True they return a named tuple with ok / abort_code / wkc, so the device abort code and transaction result are still readable on failure.

MethodDefault returndetail=True return
load_object_dictionary(*, detail=False)List[ObjectDictionary] | NoneOdListResult(ok, od_list, abort_code, wkc)
get_object_description(index, *, detail=False)ObjectDictionary | NoneOdObjectResult(ok, od, abort_code, wkc)
get_entry_description(index, subindex, *, detail=False)ObjectEntry | NoneOdEntryResult(ok, entry, abort_code, wkc)

Detail field semantics:

  • abort_code (int) — the 16-bit ErrorCode of the SDO Info Error frame returned by the device; 0 = the device returned no abort code (transport-layer failures do not synthesize an abort code)
  • wkc (int) — result of the innermost mailbox transaction; for multiple transactions the worst is taken, any failed transaction makes it 0 (a later success does not mask an earlier failure)
  • ok (bool) — whether the payload is usable

Additional semantics of load_object_dictionary: a single failed subindex description does not make the whole table empty; abort_code takes the first device Info ErrorCode other than 0 (closest to the failure point), and wkc takes the worst value across all transactions.

Example:

res = slave.coe.load_object_dictionary(detail=True)
if not res.ok:
print(f"OD 列表失败: abort=0x{res.abort_code:04X}, wkc={res.wkc}") # OD list failed: abort=0x{res.abort_code:04X}, wkc={res.wkc}
else:
print(f"共 {len(res.od_list)} 个对象") # {len(res.od_list)} objects in total

obj = slave.coe.get_object_description(0x6041, detail=True)
entry = slave.coe.get_entry_description(0x6041, 0, detail=True)
print(f"obj.ok={obj.ok}, entry.ok={entry.ok}, entry.wkc={entry.wkc}")
Difference from load_od_list()

load_od_list() / ODList is the high-level entry with ESI preference and retries; the three methods in this section are direct-read primitives that only use SDO Information — they do not consult the ESI directory and do not retry on an empty table; they are suitable for diagnosing "what abort code the device actually returned".

PDO allocation​

enumerate_default_pdo() reads the slave's default PDO assignment table (RxPDO = 0x1C12, TxPDO = 0x1C13) and returns the currently assigned PDO indexes. The master library completes the enumeration in one call; callers should not loop over 0x1C12 / 0x1C13 themselves.

enumerate_default_pdo()​

def enumerate_default_pdo(self, direction: int, max_count: int = 16) -> Optional[List[int]]

Reads one side's default PDO assignment table and returns the PDO indexes in assignment order.

Parameters:

  • direction (int) — 0 reads the RxPDO assignment table (0x1C12), 1 reads the TxPDO assignment table (0x1C13); any other value raises ValueError
  • max_count (int) — maximum number of entries to enumerate, default 16; allowed range 1..256, out of range raises ValueError

Returns (tri-state):

  • List[int] — read succeeded; the PDO indexes in assignment order, no longer than max_count, empty slots (0) are not returned
  • [] — read succeeded and no PDO is assigned
  • None — read failed (a call error or a negative return), not "no PDO"; do not treat it as an empty table and keep configuring PDOs

Exceptions:

  • ValueError — direction is not 0/1, or max_count is outside 1..256, or an argument cannot be converted to an integer

Example:

rx = slave.coe.enumerate_default_pdo(0)      # 0x1C12
tx = slave.coe.enumerate_default_pdo(1) # 0x1C13

for name, pdos in (("RxPDO", rx), ("TxPDO", tx)):
if pdos is None:
print(f"{name} 分配表读失败,先排查通信,不要当成没有 PDO") # {name} assignment table read failed — troubleshoot the communication first; do not treat this as having no PDO
elif not pdos:
print(f"{name} 确认未分配 PDO") # {name} confirmed to have no PDO assigned
else:
print(f"{name}: " + ", ".join(f"0x{i:04X}" for i in pdos))

EMCY emergency messages​

CoE supports CiA 301 emergency records. Each slave automatically collects the EMCY messages of that slave; the history is kept in an underlying ring buffer (at most 256 entries per slave) and is read through slave properties.

Slave properties​

# Get the EMCY message count
count = slave.emcy_count

# Get the EMCY history
history = slave.emcy_history # List[EmergencyMessage], not a list of dicts

for msg in history: # chronological order, oldest -> newest
print(f"EMCY 0x{msg.error_code:04X} 寄存器=0x{msg.error_register:02X} " # EMCY 0x{msg.error_code:04X} register=0x{msg.error_register:02X}
f"时刻={msg.timestamp_ms}ms(单调)") # timestamp={msg.timestamp_ms}ms (monotonic)

# Clear the EMCY history
slave.clear_emcy()
  • emcy_count is the current number of entries; emcy_history returns at most the latest 256 entries in the ring, chronological order, oldest → newest, the last item is the newest; once the ring is full, new records overwrite the oldest one
  • the sole authority for the history is the underlying ring buffer; the Python side keeps no second copy of the history
  • to process only newly arrived frames use the master.on_emergency callback (parameters are master_index / slave_index / error_code / error_reg / b1 / w1 / w2); when you need history still read slave.emcy_history
  • the callback's b1 / w1 / w2 are the 5 bytes of vendor data in the EMCY frame: data = [b1, w1 低字节, w1 高字节, w2 低字节, w2 高字节], the same source as EmergencyMessage.data; error_reg only takes the low 8 bits
def on_emcy(mi, si, error_code, error_reg, b1, w1, w2):
print(f"从站 {si} EMCY 0x{error_code:04X} 寄存器=0x{error_reg:02X}") # Slave {si} EMCY 0x{error_code:04X} register=0x{error_reg:02X}

master.on_emergency(on_emcy)

EmergencyMessage structure​

Each entry of slave.emcy_history is a read-only snapshot (property access):

class EmergencyMessage:
def __init__(self, error_code: int = 0, error_register: int = 0,
data: bytes = b'', slave_index: int = 0,
timestamp_ms: int = 0): ...

error_code: int # emergency error code (CiA 301 Table 24)
error_register: int # error register (object 0x1001)
data: bytes # vendor-specific data (5 bytes)
slave_index: int # source slave index
timestamp_ms: int # record time (monotonic milliseconds since boot, not a Unix epoch; 0 = unknown)

def get(self, key: str, default=None) # get a value in the old dict shape
def get_error_description(self) -> str # text description of the error code

get_error_description() uses the underlying code table to return a Chinese description (for example "current error", "temperature error", "communication error"); when nothing matches it returns unknown error category (0xXXXX). No second code table is maintained on the Python side. get() only recognizes the five fields above and returns default for other keys — code that read by dict key in the old version can use msg.get("error_code") for compatibility.

Advanced feature: object dictionary tree (ODList)​

The ODList class provides full object dictionary tree traversal and loads the slave OD structure automatically on construction (auto_load=True). prefer_esi=True is the default: it first consults the bound ESI directory (name + subindex, 0 mailbox traffic), and falls back to really sending SDO Information only on a miss; pass prefer_esi=False to force SDO only. An empty dictionary is not success (loaded=False / len(od)==0). A full SDO load = object list (0x01) + object description (0x03) + per-object subindex description, which is mailbox-intensive; a full load in OP / SafeOp eats into the cyclic mailbox, so loading in PreOp is recommended. When you only need the object index table (without reading descriptions) you can use SDO Information Basic (only the 0x01 object list, without pulling a subindex description per object), which uses less mailbox traffic.

Constructing ODList directly is an advanced use

Constructing ODList directly is suitable for full OD tree traversal (diagnostic tools / HMI browsing). The stable entry is slave.coe.load_od_list() (automatic retry on an empty table). For regular SDO read/write, slave.coe.sdo_read_value() / sdo_write_value() is enough; there is no need to load the full OD. The parameter form of direct construction may change later; do not hard-code it in production code for the long term.

load_od_list()​

def load_od_list(self, prefer_esi: bool = True) -> Optional[ODList]

The recommended loading entry. Returns None on failure (both a load failure and an object count of 0 count as failure); it does not raise.

When the first call returns an empty table it waits 80 ms and retries once with pure SDO (the first SDO Information in OP occasionally returns an empty table).

Parameters:

  • prefer_esi (bool) — default True, consult the ESI directory first; False sends SDO directly

Example:

od = slave.coe.load_od_list()
if od is None:
print(f"对象字典加载失败: {slave.coe.last_sdo_error}") # Failed to load the object dictionary: {slave.coe.last_sdo_error}
else:
print(f"共 {od.count} 个对象") # {od.count} objects in total

CoE.LoadODList() is an alias of the same method.

ODList members​

MemberTypeDescription
loadedboolWhether it has been loaded successfully
count / len(od)intNumber of objects
od[index]ObjectDictionaryGet an object by OD index; raises KeyError if absent
od["Name"]ObjectDictionaryGet by object name (case-insensitive); raises KeyError if absent
index in odboolWhether the index / name exists
keys()List[int]All OD indexes (sorted)
get(index, default=None)ObjectDictionary | NoneSafe lookup by int index, does not raise (name strings are not supported)
items()Iterator[Tuple[int, ObjectDictionary]](索引, 对象) iteration
load(prefer_esi=True)boolClears and reloads; returns whether it succeeded
load_async(prefer_esi=True)threading.Thread | NoneBackground thread load; returns None if a load is already in progress
load_awaitable(timeout_ms=None, prefer_esi=True)await → boolasyncio version of the load; timeout raises asyncio.TimeoutError
is_loadingboolWhether a background load is in progress
int keys have a positional fallback

od[0x6041] first looks up by OD index; when it is not found it falls back to a list-position lookup (0 <= key < len(od)). Passing a small integer (such as od[3]) may return the 4th object instead of index 0x0003; confirm with index in od before accessing by index.

from darra_ethercat import ODList

# Load the slave object dictionary (an empty dictionary is not success)
od = slave.coe.load_od_list()

if od is None or not od.loaded or len(od) == 0:
print(f"对象字典加载失败: {slave.coe.last_sdo_error}") # Failed to load the object dictionary: {slave.coe.last_sdo_error}
else:
# Iterate all indexes
for obj in od:
print(f"0x{obj.index:04X}: {obj.name} (subs={len(obj)})")

# Iterate the subindexes
for entry in obj:
print(f" [{entry.subindex}] {entry.name}: {entry.data_type.name}")

# Access by index
if 0x6041 in od:
raw = slave.coe.sdo_read(0x6041, 0)
if raw is None:
print(f"StatusWord 读失败: {slave.coe.last_sdo_error}") # StatusWord read failed: {slave.coe.last_sdo_error}
else:
value = int.from_bytes(raw[:2], 'little')
print(f"StatusWord = 0x{value:04X}")

copy()​

def copy(self) -> 'ODList'

Create a copy of the object dictionary (copies the structure and the subindex entries).

copy() really sends a round of SDO

The copy process itself iterates every subindex and reads entry.bytes once (real SDO traffic), so with many objects in OP the cost is noticeable. On the copy, entry.bytes / typed reads still send SDO live and do not consume the values taken during the copy.

Example:

# Create an ODList copy
od_snapshot = od.copy()

# Create a copy of a single ObjectDictionary
if 0x6040 in od:
od_copy = od[0x6040].copy()

ObjectDictionary properties​

CategoryPropertyTypeRead/writeDescription
Object dictionaryindexintread-onlyObject index
Object dictionarynamestrread-onlyObject name
Object dictionarydata_type / datatypeintread-onlyRaw data type value (not the EcDataType enum)
Object dictionaryobject_codeintread-onlyObject code (7=VAR / 8=ARRAY / 9=RECORD)
Object dictionarycount / len(od)intread-onlyNumber of subindex entries
Object dictionaryis_var / is_array / is_recordboolread-onlyWhether the object code is 7 / 8 / 9
Object dictionaryoe_listOEDictionaryread-onlySubindex container (dictionary-like access)
Object dictionaryEsiDefaultTextstrread-onlyESI pre-filled default display text (empty string if none)

ObjectDictionary methods​

# Get ObjectEntry by subindex (raises KeyError if absent)
entry = od[0x6040][0]

# Get by name (case-insensitive, raises KeyError if absent)
entry = od[0x1018]["Vendor ID"]

# Read all subindexes in bulk -> Dict[int, bytes]
data_dict = od[0x1018].read_all()

# SDO write to the object (returns bool; writes sub_index=0 by default)
ok = od[0x6040].sdo_write(data, complete_access=False)
ok = od[0x6040].sdo_write(data, sub_index=1, complete_access=False)

Failure semantics:

  • od[sub] / od[name] — raises KeyError if the subindex or name is absent; probe with in or contains_key() first
  • read_all() — reads entry.bytes one by one, subindexes whose read fails are skipped (they do not appear in the result); returns {} if all fail
  • sdo_write() — returns False when data is empty; otherwise returns the success of the SDO write

ObjectEntry typed read/write​

False objects obtained through ODList support typed read/write methods:

  • read_u8() / write_u8(v) — unsigned 8-bit
  • read_u16() / write_u16(v) — unsigned 16-bit
  • read_u32() / write_u32(v) — unsigned 32-bit
  • read_u64() / write_u64(v) — unsigned 64-bit
  • read_i8() / write_i8(v) — signed 8-bit
  • read_i16() / write_i16(v) — signed 16-bit
  • read_i32() / write_i32(v) — signed 32-bit
  • read_i64() / write_i64(v) — signed 64-bit
  • read_f32() / write_f32(v) — 32-bit floating point
  • read_f64() / write_f64(v) — 64-bit floating point
  • read_string(encoding=None) / write_string(v, encoding=None) — strings. The default encoding=None selects character semantics from the object OD data type: VISIBLE_STRING / OCTET_STRING use single-byte ISO-8859-1, UNICODE_STRING uses UTF-16LE code units (all through the underlying ec_str_decode / ec_str_encode); when encoding is given explicitly, the raw bytes are decoded with that encoding (old behavior, no terminator padding)
  • read_typed() — parses automatically according to the data type
  • get_value(target_type=None) — converts to the target type after reading

Return value semantics:

  • read_*() — returns the numeric value on success; returns None if the SDO read fails; when the response bytes are short, \x00 is appended at the tail (little-endian padding of the high bytes) before parsing
  • write_*() — returns bool; returns False if the SDO write fails
  • read_string() — by default decodes through the underlying character decoder according to the OD type (returns None on failure / non-string types); with an explicit encoding it strips the trailing \x00 and decodes with errors='replace', and returns None if the read fails
  • read_typed() — fixed-width types are parsed per data_type; string types go through read_string(); the rest (variable-length / out-of-table types) return the raw bytes; returns None if the read fails
  • get_value(target_type) — when target_type is None it is the same as read_typed(); returns None if conversion fails (does not raise)
  • async versions: read_bytes_async(timeout_ms=None) / write_bytes_async(value, timeout_ms=None) / read_typed_async(timeout_ms=None) / get_value_async(target_type=None, timeout_ms=None); a timeout raises asyncio.TimeoutError

ObjectEntry properties​

CategoryPropertyTypeRead/writeDescription
Object entryod_index / ODIndexintread-onlyObject dictionary index
Object entrysubindexintread-onlySubindex
Object entryindexintread-onlySubindex (an alias of subindex, not the OD index)
Object entrynamestrread-onlyName
Object entrydata_type / Datatype / DataTypeEcDataTyperead-onlyData type
Object entrybit_lengthintread-onlyBit length
Object entrybyte_lengthintread-onlyByte length (bit_length rounded up to bytes)
Object entryobj_access / ObjAccessObjAccessread-onlyAccess permission flags
Object entrycan_readboolread-onlyWhether it has any read permission
Object entrycan_writeboolread-onlyWhether it has any write permission
Object entryis_read_onlyboolread-onlyReadable and not writable
Object entrycan_write_pre_opboolread-onlyWritable in PreOP
Object entrycan_write_safe_opboolread-onlyWritable in PreOP / SafeOP
Object entrycan_write_opboolread-onlyWritable in any state (same as can_write)
Object entryaccess_descriptionstrread-onlyPermission description text (Chinese)
Object entryEsiDefaultText / esi_default_textstrread-onlyESI pre-filled default display text
Object entrynot_presentboolread-onlyThis subindex has been judged absent (NotPresent)
entry.index is the subindex

entry.index is equivalent to entry.subindex. For the OD index use entry.od_index (alias ODIndex).

bytes raw byte read/write:

OperationBehavior
Read entry.bytesfirst reads with Complete Access; if that fails it does a normal read; if both fail it returns b'' (not None). Raises CoE_AccessDeniedException when there is no read permission
Write entry.bytes = valuean empty value raises ValueError; no write permission or a final write failure raises CoE_AccessDeniedException; nothing is returned on success

CoE_AccessDeniedException is exported directly by the root package: from darra_ethercat import CoE_AccessDeniedException is enough; writing darra_ethercat.CoE_AccessDeniedException works the same way, so no separate submodule import is needed. The exception object carries index (OD index), sub_index, entry_name, is_read_operation, obj_access (raw permission bits).

Example:

entry = od[0x6040][0]
if entry.can_write:
entry.write_u16(0x0006)

print(f"OD 索引=0x{entry.od_index:04X}, 子索引={entry.subindex}") # OD index=0x{entry.od_index:04X}, subindex={entry.subindex}
print(f"访问权限: {entry.access_description}") # Access permission: {entry.access_description}

Access permission exception​

CoE_AccessDeniedException is the permission exception for object entry read/write: reading or writing ObjectEntry.bytes when the current state lacks the corresponding permission, or a final write failure, raises this type. Catch by exception type; do not match on the message text.

The exception object's fields are fixed at construction:

  • index (int) — object dictionary index
  • sub_index (int) — subindex
  • entry_name (str) — object entry name
  • is_read_operation (bool) — True = read operation, False = write operation
  • obj_access (int) — raw access permission bits (flag definitions see ObjAccess)

CoE_AccessDeniedException.create_with_custom_message()​

@classmethod
def create_with_custom_message(cls, index: int, sub_index: int,
custom_message: str,
is_read_operation: bool,
obj_access: int) -> 'CoE_AccessDeniedException'

Create an exception instance with a custom message, for cases where the permission check may pass but the final write fails and site information needs to be attached.

Parameters:

  • index (int) — object dictionary index
  • sub_index (int) — subindex
  • custom_message (str) — custom exception message; it is also written to the entry_name field (this classmethod does not accept a separate object name argument)
  • is_read_operation (bool) — True means a read operation, False means a write operation
  • obj_access (int) — raw access permission bits

Returns:

  • CoE_AccessDeniedException — the exception instance, raised by the caller with raise

Example:

from darra_ethercat import CoE_AccessDeniedException

try:
entry.bytes = b'\x06\x00'
except CoE_AccessDeniedException as ex:
print(f"0x{ex.index:04X}:{ex.sub_index} 写入被拒: {ex}") # 0x{ex.index:04X}:{ex.sub_index} write rejected: {ex}
print(f"读操作={ex.is_read_operation}, 权限位=0x{ex.obj_access:02X}") # read operation={ex.is_read_operation}, access bits=0x{ex.obj_access:02X}

SDOError enum​

SDO operation error codes (CANopen standard / ETG.1020). SDOError.describe() returns a Chinese description (the sole authority for the text = the underlying library's SDO Abort table). English SDO Abort descriptions are not currently provided.

from darra_ethercat.data.types import SDOError
NameValueDescription
NO_ERROR0x00000000No error
TOGGLE_BIT_NOT_CHANGED0x05030000Toggle bit not changed
SDO_PROTOCOL_TIMEOUT0x05040000SDO protocol timeout
INVALID_COMMAND_SPECIFIER0x05040001Invalid command specifier
INVALID_BLOCK_SIZE0x05040002Invalid block size (CiA 301 block transfer)
INVALID_SEQUENCE_NUMBER0x05040003Invalid block sequence number (CiA 301 block transfer)
CRC_ERROR0x05040004CRC check error (CiA 301 block transfer)
OUT_OF_MEMORY0x05040005Out of memory
UNSUPPORTED_ACCESS0x06010000Unsupported access
READ_WRITE_ONLY_ERROR0x06010001Attempt to read a write-only object
WRITE_READ_ONLY_ERROR0x06010002Attempt to write a read-only object
SUBINDEX_WRITE_ERROR0x06010003Writing to the subindex is not allowed
COMPLETE_ACCESS_NOT_SUPPORTED0x06010004Complete access not supported
OBJECT_LENGTH_EXCEEDED0x06010005Object length exceeded
OBJECT_MAPPED_TO_RXPDO0x06010006Object already mapped to RxPDO
OBJECT_DOES_NOT_EXIST0x06020000Object does not exist
CANNOT_BE_MAPPED_TO_PDO0x06040041Cannot be mapped to PDO
EXCEEDS_PDO_LENGTH0x06040042Exceeds the PDO length
PARAMETER_INCOMPATIBILITY0x06040043Parameter incompatibility
INTERNAL_INCOMPATIBILITY0x06040047Internal incompatibility
HARDWARE_ACCESS_ERROR0x06060000Hardware access error
DATA_TYPE_MISMATCH0x06070010Data type mismatch
DATA_TYPE_TOO_HIGH0x06070012Data type length too large
DATA_TYPE_TOO_LOW0x06070013Data type length too small
SUBINDEX_DOES_NOT_EXIST0x06090011Subindex does not exist
SUBINDEX_DOES_NOT_EXIST_FOR_OBJECT0x06090012Subindex does not exist (object variant)
VALUE_RANGE_EXCEEDED0x06090030Value out of range
VALUE_TOO_HIGH0x06090031Value too high
VALUE_TOO_LOW0x06090032Value too low
MODULE_IDENT_LIST_MISMATCH0x06090033Module list mismatch
MAX_LESS_THAN_MIN0x06090036Maximum less than minimum
RESOURCE_NOT_AVAILABLE0x060A0023Resource not available (SDO connection)
GENERAL_ERROR0x08000000A "general error" really returned by the device (out-of-table codes are not folded into this entry; see UNKNOWN_ERROR)
DATA_TRANSFER_ERROR0x08000020Data cannot be transferred or stored to the application (reported by the device)
LOCAL_CONTROL_ERROR0x08000021Data cannot be transferred or stored because of local control (reported by the device)
DEVICE_STATE_ERROR0x08000022Data cannot be transferred or stored because of the present device state (reported by the device)
DICTIONARY_ERROR0x08000023Dictionary error
LOCAL_REQUEST_NOT_SENT0x0D000001Request not sent (local reject): no frame went on the bus; not an abort code reported by the device
UNKNOWN_ERROR0xFFFFFFFFUnknown error: out-of-table abort codes not covered by the SDK code table land here; the original code is in last_sdo_abort_code
0x0D0000xx are master-side codes

Except for LOCAL_REQUEST_NOT_SENT, these codes are not reported by a device. They only appear when the request did not complete and the device returned no abort frame. Read them from abort_code (the raw integer); the last_sdo_error enum view gives only UNKNOWN_ERROR for codes without a member (it does not fabricate GENERAL_ERROR), so judge the source from abort_code.

CodeMeaningWhat to do
0x0D000002Frame transmitted, but no device counted itCheck whether that slave's mailbox is rejecting or full, and check the receive path
0x0D000003Mailbox layer error (the peer returned a mailbox Error frame)Check the mailbox SM configuration and the request length
0x0D000004Transport layer failure (cancelled / protocol mismatch / local resource shortage / link down / peer not consuming)No retry for a cancel; restore the link first when it is down; for a protocol mismatch check the mailbox type and SM configuration

The codes a device reports — 0x08000020 / 0x08000021 / 0x08000022 — differ from these in both value and meaning.

EcDataType enum​

EtherCAT data type enum (based on ETG.1000.6), deciding the automatic conversion target for ObjectEntry typed read/write.

from darra_ethercat.slave.coe import EcDataType
Enum valueValuePython typeDescription
NONE0x0000bytesUntyped (raw bytes)
BOOLEAN0x0001boolBoolean
INTEGER80x0002intint8
INTEGER160x0003intint16
INTEGER320x0004intint32
UNSIGNED80x0005intuint8
UNSIGNED160x0006intuint16
UNSIGNED320x0007intuint32
REAL320x0008floatSingle-precision floating point
VISIBLE_STRING0x0009strASCII string
OCTET_STRING0x000AbytesByte string
UNICODE_STRING0x000BstrUnicode string
TIME_OF_DAY0x000CbytesTime (raw bytes)
TIME_DIFFERENCE0x000DbytesTime difference (raw bytes; old alias TIME_DIFF)
DOMAIN0x000FbytesRaw data
REAL640x0011floatDouble-precision floating point
INTEGER640x0015intint64
UNSIGNED640x001Bintuint64
UNKNOWN0xFFFFbytesSentinel for unrecognized type codes (raw bytes)

There are also members such as INTEGER24/40/48/56, UNSIGNED24/40/48/56, GUID, BYTE, WORD, DWORD, PDOMAPPING, IDENTITY, COMMANDPAR, PDOPAR, BIT1–BIT8 (0x0030–0x0037); types outside the typed read/write conversion range are returned as raw bytes.

EcDataType helper properties​

# Get the byte size for the type
size = EcDataType.UNSIGNED16.byte_size # 2

# Get the struct format string
fmt = EcDataType.INTEGER32.struct_fmt # '<i'

Return value semantics:

  • byte_size (int) — bit width rounded up to bytes; returns 0 when it cannot be determined (NONE, variable-length string types / DOMAIN, BIT1–BIT8, out-of-table codes GUID / BYTE / WORD / DWORD / UNKNOWN)
  • struct_fmt (str | None) — only the 11 types with a scalar conversion slot return a format string (BOOLEAN, INTEGER8/16/32/64, UNSIGNED8/16/32/64, REAL32/64); the rest return None

Protocol names and display aliases:

  • The authoritative protocol name is provided by the underlying library and returns canonical uppercase names such as INT8 / UINT16 / REAL32 / VISIBLE_STRING / BIT1 / UNKNOWN. The Python entry is darra_ethercat.utils.value_codec.type_name(dt); the static wrapper is ProtocolCodes.pdo_data_type_name(dt) (requires ProtocolCodes.set_dll(dll) first, see darra_ethercat.statics.protocol_codes).
  • Display short names (int8 / float / string) have no separate entry point in the current Python SDK; if you only need them for the UI, lowercase the authoritative protocol name yourself; they do not participate in protocol decisions, bit-width computation, PDO encoding/decoding, or cross-language semantic comparison.
  • The INTEGER8 / REAL32 / VISIBLE_STRING in the "Enum value" column of the table above are Python enum member names, not the strings returned by the underlying library.

ObjAccess access permission flags​

from darra_ethercat.slave.coe import ObjAccess

# Check permissions
if entry.obj_access & ObjAccess.READABLE:
print("可读") # Readable
if entry.obj_access & ObjAccess.WRITE_OP:
print("OP 状态可写") # Writable in OP state

# Get the Chinese description
print(entry.obj_access.access_description) # "读写(PreOP,SafeOP,OP可写)" (SDK output, = read/write (writable in PreOP, SafeOP, OP))
FlagValueDescription
NONE0x0000No permission
READ_PRE0x0001Readable in PreOp
READ_SAFE0x0002Readable in SafeOp
READ_OP0x0004Readable in OP
WRITE_PRE0x0008Writable in PreOp
WRITE_SAFE0x0010Writable in SafeOp
WRITE_OP0x0020Writable in OP
MAPPABLE0x0040Can be mapped to PDO
BACKUP0x0080Backup parameter (stored in EEPROM)
SETTINGS0x0100Configuration parameter
READABLE0x0007Readable in all states (= READ_PRE | READ_SAFE | READ_OP)
WRITABLE0x0038Writable in all states (= WRITE_PRE | WRITE_SAFE | WRITE_OP)
READ_WRITE_ALL0x003FReadable and writable in all states (= READABLE | WRITABLE)

Same-value aliases (same class, not counted as another tier): READ_PREOP = READ_PRE, READ_SAFEOP = READ_SAFE, WRITE_PREOP = WRITE_PRE, WRITE_SAFEOP = WRITE_SAFE, READ_ANY = READABLE, WRITE_ANY = WRITABLE. CoEObjectAccess is a same-value alias class of ObjAccess; from darra_ethercat.slave.coe import CoEObjectAccess also points to the same class.

Complete example​

SDO read/write​

from darra_ethercat import EtherCATMaster, EcState

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

slave = master[1]

# Read device information
vendor_id = slave.coe.sdo_read_value(0x1018, 1, dtype='u32')
product_code = slave.coe.sdo_read_value(0x1018, 2, dtype='u32')
if vendor_id is None or product_code is None:
print(f"Identity 读失败: {slave.coe.last_sdo_error}") # Identity read failed: {slave.coe.last_sdo_error}
raise SystemExit(1)
print(f"VendorID=0x{vendor_id:08X}, ProductCode=0x{product_code:08X}")

# Read the status word
status = slave.coe.sdo_read_value(0x6041, 0, dtype='u16')
if status is None:
print(f"SDO 失败: {slave.coe.last_sdo_error}") # SDO failed: {slave.coe.last_sdo_error}
raise SystemExit(1)
print(f"StatusWord = 0x{status:04X}")

# Write the control word
slave.coe.sdo_write_value(0x6040, 0, 0x0006, dtype='u16')

# Set the operating mode
slave.coe.sdo_write_value(0x6060, 0, 8, dtype='i8')

# Error handling
data = slave.coe.sdo_read(0x9999, 0)
if data is None:
error = slave.coe.last_sdo_error
print(f"SDO 错误: {error.name} - {error.describe()}") # SDO error: {error.name} - {error.describe()}

master.stop()

Object dictionary scan​

od = slave.coe.load_od_list()      # stable entry, returns None on failure
if od is None:
print(f"对象字典加载失败: {slave.coe.last_sdo_error}") # Failed to load the object dictionary: {slave.coe.last_sdo_error}
else:
for obj in od:
print(f"0x{obj.index:04X}: {obj.name}")
for entry in obj:
raw = slave.coe.sdo_read(obj.index, entry.subindex)
if raw is None:
print(f" [{entry.subindex}] {entry.name}: 读失败 {slave.coe.last_sdo_error}") # [{entry.subindex}] {entry.name}: read failed {slave.coe.last_sdo_error}
continue
print(f" [{entry.subindex}] {entry.name} = {raw.hex()}")

# Create a copy (structure copied; reads still use live SDO)
snapshot = od.copy()

EMCY history​

count = slave.emcy_count
history = slave.emcy_history # List[EmergencyMessage], oldest -> newest
for msg in history:
print(f"EMCY 0x{msg.error_code:04X}: {msg.get_error_description()}")
slave.clear_emcy()

CoE diagnostic history (0x10F3)​

The slave keeps runtime diagnostic messages in the 0x10F3 ring buffer. The SDK provides a per-message polling interface, so there is no need to fetch the whole history at once.

Difference from read_diagnostic_messages()
  • read_diagnostic_messages(slave.coe) — module-level function (from darra_ethercat.slave.coe import read_diagnostic_messages), fetches the whole 0x10F3 diagnostic history in one batch (reads one by one according to the message count declared in the slave's 0x10F3:00, with no fixed hard truncation) and returns List[DiagnosticMessage]; it is relatively expensive. The async version is read_diagnostic_messages_async(slave.coe, timeout_ms=None)
  • poll_has_new_diagnostic() + read_diagnostic_message(idx) — fetch only the single message that changed, suitable for periodic polling at runtime
Python-specific syntax sugar

The four steps "poll → read meta → read message → ack" can be consumed as a one-line stream with the async generator async for raw in slave.coe.diagnostic_stream(poll_ms=50):.

Prerequisite: diagnostic_stream is injected at import time by the syntax-sugar subpackage and does not exist under a standard import. You must first import darra_ethercat.sugar (import darra_ethercat alone is not enough), otherwise you get AttributeError.

poll_has_new_diagnostic()​

from darra_ethercat.slave.coe import DiagnosticPollResult

def poll_has_new_diagnostic(self) -> DiagnosticPollResult

Quickly polls the 0x10F3:04 NewMessagesAvailable flag to determine whether there are diagnostic messages that have not been read yet.

Return value (tri-state enum DiagnosticPollResult, same meaning and value as C# / Java / Rust; the Python keyword None cannot be a member name, so UPPER_SNAKE is used):

ValueSemanticsMeaning
DiagnosticPollResult.HAS_NEWNew messages availableShould keep fetching (recommended to follow immediately with read_diagnostic_meta() + read_diagnostic_message())
DiagnosticPollResult.NONENo new messagesIncludes the slave not supporting 0x10F3
DiagnosticPollResult.FAILEDCommunication failureThe underlying library does not support the capability / communication failed; this is different from "no new messages"; do not silently treat a failure as no messages (you can fall back to read_diagnostic_messages(slave.coe))

When judging, use the three branches is DiagnosticPollResult.HAS_NEW / is DiagnosticPollResult.NONE / is DiagnosticPollResult.FAILED; do not only test "not HAS_NEW", which mixes FAILED failures into "no messages".

Example:

from darra_ethercat.slave.coe import DiagnosticPollResult

rc = slave.coe.poll_has_new_diagnostic()
if rc is DiagnosticPollResult.HAS_NEW:
print("有新诊断消息") # New diagnostic message available
elif rc is DiagnosticPollResult.NONE:
pass # no new messages
else: # DiagnosticPollResult.FAILED: communication failure, not "no messages"
print("轮询失败,回退批量拉取") # Polling failed, falling back to batch fetch
read_diagnostic_messages(slave.coe)

read_diagnostic_meta()​

def read_diagnostic_meta(self) -> Optional[DiagMeta]

Reads the 0x10F3:01 / 02 / 03 / 05 metadata block (:04 is read separately by poll_has_new_diagnostic()) and returns a DiagMeta data class, or None on failure; when the slave does not implement 0x10F3 it also returns None, in which case use EMCY instead.

Related structures:

@dataclass
class DiagMeta:
max_messages: int = 0 # 0x10F3:01, slave diagnostic buffer capacity (usually <=250)
newest_message: int = 0 # 0x10F3:02, subindex of the newest message in 0x10F3
newest_acknowledged: int = 0 # 0x10F3:03, last acknowledged subindex
flags: int = 0 # 0x10F3:05, bit4 = 0 Overwrite / 1 Acknowledge, bit5 = Overrun
Meaning of the Flags bits

Per ETG.1020 v1.5.0 Table 49, flags (0x10F3:05) is defined as:

  • bit4 = diagnostic buffer mode: 0 = Overwrite / 1 = Acknowledge
  • bit5 = 1 means Overrun occurred (the ring buffer has overwritten unread messages)

How to read it: in Overwrite mode the slave keeps newest_acknowledged = 0 by specification; that 0 is a normal value and must not be read as "there are unacknowledged messages", nor may it be inferred from newest_message != newest_acknowledged. In that mode, whether an unread message exists can only be answered by 0x10F3:04 NewAvailable (poll_has_new_diagnostic()). Only in Acknowledge mode does newest_message != newest_acknowledged indicate unacknowledged messages.

Accessor: the Python DiagMeta exposes only the flags field and has no is_acknowledge_mode()-style accessor/property: test bool(meta.flags & 0x10) (0 = Overwrite, 1 = Acknowledge) and use bool(meta.flags & 0x20) for bit 5 Overrun (see ack_mode = bool(meta.flags & 0x10) below).

read_diagnostic_message()​

def read_diagnostic_message(self, msg_subidx: int,
buf_size: int = 1024) -> Optional[bytes]

Reads the raw Octet-Diagnosis bytes of the single message at 0x10F3:msg_subidx.

Parameters:

  • msg_subidx (int) — subindex range [6, 255] (ETG.1020)
  • buf_size (int) — receive buffer size in bytes, default 1024

Returns:

  • bytes | None — raw bytes (actual length); None on failure

acknowledge_diagnostic()​

def acknowledge_diagnostic(self, msg_subidx: int) -> bool

Writes 0x10F3:03 = msg_subidx to acknowledge that the message has been processed. In Acknowledge mode (flags bit4 = 1) the slave advances its acknowledged position accordingly; in Overwrite mode (bit4 = 0) this write carries no decision weight. The valid msg_subidx range is 6..255; passing 0 acknowledges all messages at once. The application layer should acknowledge promptly after processing a message, otherwise in Acknowledge mode newest_acknowledged does not advance, which may cause an Overrun.

Example: periodic polling listener

import time
from darra_ethercat.slave.coe import DiagnosticPollResult

running = True # controlled by your main loop

while running:
rc = slave.coe.poll_has_new_diagnostic()
if rc is DiagnosticPollResult.FAILED:
print("轮询失败(通信异常),稍后重试") # FAILED is not "no messages"; handle it separately
time.sleep(0.1)
continue
if rc is DiagnosticPollResult.NONE:
time.sleep(0.1) # 100 ms polling
continue

meta = slave.coe.read_diagnostic_meta()
if meta is None:
time.sleep(0.1)
continue

# Overrun and buffer mode
ack_mode = bool(meta.flags & 0x10) # bit4: 0 = Overwrite / 1 = Acknowledge
has_overrun = bool(meta.flags & 0x20) # bit5
if has_overrun:
print("警告: 诊断缓冲区溢出, 部分消息丢失") # Warning: diagnostics buffer overflow, some messages lost

if meta.newest_message < 6:
time.sleep(0.1)
continue
# 0x10F3:01 = message capacity N; message subindexes are fixed at 6..6+N-1 (that is 6..5+max_messages), wrapping back to 6
max_msgs = max(meta.max_messages, 1)
# In Overwrite mode newest_acknowledged stays 0 by specification, so start from the first message (6);
# only Acknowledge mode starts from acked+1
idx = meta.newest_acknowledged if (ack_mode and meta.newest_acknowledged >= 6) else 5
steps = 0
while idx != meta.newest_message and steps < max_msgs:
steps += 1
idx = idx + 1 if idx + 1 <= 5 + max_msgs else 6
raw = slave.coe.read_diagnostic_message(idx)
if raw:
print(f"[0x10F3:{idx:02X}] {raw.hex()}")
slave.coe.acknowledge_diagnostic(idx)

time.sleep(0.1) # 100 ms polling
Choosing between 0x10F3 and EMCY

The two mechanisms are independent and can be used at the same time:

  • To get fatal errors asynchronously pushed by the slave → the master.on_emergency callback; for history → slave.emcy_history
  • To actively poll historical diagnostic records → the 0x10F3 interface in this section