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))
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, default0complete_access(bool) — whether to use complete access, defaultFalse. The 3rd positional parameter, it can be written assdo_read(0x1018, 0, True). WhenTrue,subindexmay only be0or1; larger subindexes fail immediately and send no request (returnsNone,last_sdo_error=SDO_PROTOCOL_TIMEOUT)detail(bool) — keyword-only parameter (after*in the signature), it must be written asdetail=True; passing it positionally raisesTypeError
Returns:
bytes | None— the bytes read; failure / WKC=0 returnsNone- with
detail=Trueit returnsSdoReadResult, 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 succeededdata(bytes | None) — data on success (an empty object isb''),Noneon failureabort_code(int) — slave abort code; if it failed without an abort code,0x05040000(SDO_PROTOCOL_TIMEOUT)wkc(int) — working counter of this SDO transaction;<= 0means 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}")
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 indexsubindex(int) — subindexdtype(str) — data type:'u8','u16','u32','u64','i8','i16','i32','i64'; an unsupported dtype raisesValueError
Returns:
int | None— the parsed value, orNoneif the SDO read fails; when the response bytes are short,\x00is 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 indexsubindex(int) — subindex, required (no default)data(bytes) — the byte data to write; an emptydatareturnsFalseimmediately as failurecomplete_access(bool) — whether to use complete access, defaultFalse, the 4th positional parameter. WhenTrue,subindexmay only be0or1(larger values fail immediately and returnFalse)detail(bool) — keyword-only parameter, it must be written asdetail=True
Returns:
bool— whether the write succeeded (whendetail=False)- with
detail=Trueit returnsSdoWriteResult, 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 indexsubindex(int) — subindexvalue(int) — the numeric value to writedtype(str) — data type:'u8','u16','u32','u64','i8','i16','i32','i64'; an unsupported dtype raisesValueError
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 failureabort_codeis the abort code, orSDO_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}
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 readcancel_event(asyncio.Event, optional) — once set, the remaining reads are aborted andCancelledErroris raised
Returns:
dict—{(index, subindex): bytes 或 None}; entries whose read failed have the valueNone
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) — theslave.coeinstance, first positional parameterindex/subindex(int) — object index / subindex (subindexis required, no default)complete_access(bool) — complete access, defaultFalsetimeout_ms(int | None) — timeout in milliseconds, defaultNonemeans no timeout is set
Returns / exceptions:
sdo_read_async— returnsbyteson success; returnsNoneon SDO failure (including WKC=0), the error code is still taken fromcoe.last_sdo_errorsdo_write_async—Trueon success,Falseon failureasyncio.TimeoutError— not completed withintimeout_msasyncio.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))
master.sdo_read_async / Slave.sdo_read_asyncThis 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). Thecanceltoken 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
cancelhas no effect, and a WARNING is logged first.
Returns / exceptions:
- read success returns
bytes, failure returnsNone(same semantics as the synchronoussdo_read); write successTrue/ failureFalse sdo_write_asyncwithdata=NoneraisesValueErrorasyncio.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) — defaultTrue, waits for the tasks already submitted to the pool to finish before returning;Falsereturns immediately and the tasks keep running in the background until they finish
Returns:
None
*_async entry pointsThe 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
| Category | Property | Type | Read/write | Description |
|---|---|---|---|---|
| Diagnostics | last_sdo_error | SDOError | read-only | Error code of the last SDO operation (an enum view; codes outside the table are folded to UNKNOWN_ERROR, never fabricated as GENERAL_ERROR) |
| Diagnostics | last_sdo_abort_code | int | read-only | The 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) |
| Capability | is_supported | Optional[bool] | read-only | Whether the slave supports the CoE mailbox; True / False are definite conclusions, a failed read returns None (unknown) and is not folded into True / False |
| Protocol | protocol_type | int | read-only | CoE mailbox protocol type code |
| Protocol | protocol_name | str | read-only | Always returns "CoE" |
| Statistics | statistics | MailboxStatistics | read-only | Snapshot 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 fromlast_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;Truereturns a detailedSdoStats(ok, requests, retries, timeouts)snapshot
Returns:
detail=False→tuple[int, int, int] | None; returnsNoneon failuredetail=True→SdoStats(namedtuple:ok/requests/retries/timeouts); on failureok=Falseand the counters are 0
Failure semantics:
- underlying library unavailable / returns failure →
ok=False(Nonein 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.
| Method | Default return | detail=True return |
|---|---|---|
load_object_dictionary(*, detail=False) | List[ObjectDictionary] | None | OdListResult(ok, od_list, abort_code, wkc) |
get_object_description(index, *, detail=False) | ObjectDictionary | None | OdObjectResult(ok, od, abort_code, wkc) |
get_entry_description(index, subindex, *, detail=False) | ObjectEntry | None | OdEntryResult(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}")
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) —0reads the RxPDO assignment table (0x1C12),1reads the TxPDO assignment table (0x1C13); any other value raisesValueErrormax_count(int) — maximum number of entries to enumerate, default 16; allowed range 1..256, out of range raisesValueError
Returns (tri-state):
List[int]— read succeeded; the PDO indexes in assignment order, no longer thanmax_count, empty slots (0) are not returned[]— read succeeded and no PDO is assignedNone— 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—directionis not 0/1, ormax_countis 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_countis the current number of entries;emcy_historyreturns 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_emergencycallback (parameters are master_index / slave_index / error_code / error_reg / b1 / w1 / w2); when you need history still readslave.emcy_history - the callback's
b1 / w1 / w2are the 5 bytes of vendor data in the EMCY frame:data = [b1, w1 低字节, w1 高字节, w2 低字节, w2 高字节], the same source asEmergencyMessage.data;error_regonly 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 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) — defaultTrue, consult the ESI directory first;Falsesends 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
| Member | Type | Description |
|---|---|---|
loaded | bool | Whether it has been loaded successfully |
count / len(od) | int | Number of objects |
od[index] | ObjectDictionary | Get an object by OD index; raises KeyError if absent |
od["Name"] | ObjectDictionary | Get by object name (case-insensitive); raises KeyError if absent |
index in od | bool | Whether the index / name exists |
keys() | List[int] | All OD indexes (sorted) |
get(index, default=None) | ObjectDictionary | None | Safe lookup by int index, does not raise (name strings are not supported) |
items() | Iterator[Tuple[int, ObjectDictionary]] | (索引, 对象) iteration |
load(prefer_esi=True) | bool | Clears and reloads; returns whether it succeeded |
load_async(prefer_esi=True) | threading.Thread | None | Background thread load; returns None if a load is already in progress |
load_awaitable(timeout_ms=None, prefer_esi=True) | await → bool | asyncio version of the load; timeout raises asyncio.TimeoutError |
is_loading | bool | Whether a background load is in progress |
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).
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
| Category | Property | Type | Read/write | Description |
|---|---|---|---|---|
| Object dictionary | index | int | read-only | Object index |
| Object dictionary | name | str | read-only | Object name |
| Object dictionary | data_type / datatype | int | read-only | Raw data type value (not the EcDataType enum) |
| Object dictionary | object_code | int | read-only | Object code (7=VAR / 8=ARRAY / 9=RECORD) |
| Object dictionary | count / len(od) | int | read-only | Number of subindex entries |
| Object dictionary | is_var / is_array / is_record | bool | read-only | Whether the object code is 7 / 8 / 9 |
| Object dictionary | oe_list | OEDictionary | read-only | Subindex container (dictionary-like access) |
| Object dictionary | EsiDefaultText | str | read-only | ESI 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]— raisesKeyErrorif the subindex or name is absent; probe withinorcontains_key()firstread_all()— readsentry.bytesone by one, subindexes whose read fails are skipped (they do not appear in the result); returns{}if all failsdo_write()— returnsFalsewhendatais 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-bitread_u16()/write_u16(v)— unsigned 16-bitread_u32()/write_u32(v)— unsigned 32-bitread_u64()/write_u64(v)— unsigned 64-bitread_i8()/write_i8(v)— signed 8-bitread_i16()/write_i16(v)— signed 16-bitread_i32()/write_i32(v)— signed 32-bitread_i64()/write_i64(v)— signed 64-bitread_f32()/write_f32(v)— 32-bit floating pointread_f64()/write_f64(v)— 64-bit floating pointread_string(encoding=None)/write_string(v, encoding=None)— strings. The defaultencoding=Noneselects character semantics from the object OD data type:VISIBLE_STRING/OCTET_STRINGuse single-byte ISO-8859-1,UNICODE_STRINGuses UTF-16LE code units (all through the underlyingec_str_decode/ec_str_encode); whenencodingis given explicitly, the raw bytes are decoded with that encoding (old behavior, no terminator padding)read_typed()— parses automatically according to the data typeget_value(target_type=None)— converts to the target type after reading
Return value semantics:
read_*()— returns the numeric value on success; returnsNoneif the SDO read fails; when the response bytes are short,\x00is appended at the tail (little-endian padding of the high bytes) before parsingwrite_*()— returnsbool; returnsFalseif the SDO write failsread_string()— by default decodes through the underlying character decoder according to the OD type (returnsNoneon failure / non-string types); with an explicitencodingit strips the trailing\x00and decodes witherrors='replace', and returnsNoneif the read failsread_typed()— fixed-width types are parsed perdata_type; string types go throughread_string(); the rest (variable-length / out-of-table types) return the rawbytes; returnsNoneif the read failsget_value(target_type)— whentarget_typeisNoneit is the same asread_typed(); returnsNoneif 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 raisesasyncio.TimeoutError
ObjectEntry properties
| Category | Property | Type | Read/write | Description |
|---|---|---|---|---|
| Object entry | od_index / ODIndex | int | read-only | Object dictionary index |
| Object entry | subindex | int | read-only | Subindex |
| Object entry | index | int | read-only | Subindex (an alias of subindex, not the OD index) |
| Object entry | name | str | read-only | Name |
| Object entry | data_type / Datatype / DataType | EcDataType | read-only | Data type |
| Object entry | bit_length | int | read-only | Bit length |
| Object entry | byte_length | int | read-only | Byte length (bit_length rounded up to bytes) |
| Object entry | obj_access / ObjAccess | ObjAccess | read-only | Access permission flags |
| Object entry | can_read | bool | read-only | Whether it has any read permission |
| Object entry | can_write | bool | read-only | Whether it has any write permission |
| Object entry | is_read_only | bool | read-only | Readable and not writable |
| Object entry | can_write_pre_op | bool | read-only | Writable in PreOP |
| Object entry | can_write_safe_op | bool | read-only | Writable in PreOP / SafeOP |
| Object entry | can_write_op | bool | read-only | Writable in any state (same as can_write) |
| Object entry | access_description | str | read-only | Permission description text (Chinese) |
| Object entry | EsiDefaultText / esi_default_text | str | read-only | ESI pre-filled default display text |
| Object entry | not_present | bool | read-only | This subindex has been judged absent (NotPresent) |
entry.index is the subindexentry.index is equivalent to entry.subindex. For the OD index use entry.od_index (alias ODIndex).
bytes raw byte read/write:
| Operation | Behavior |
|---|---|
Read entry.bytes | first 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 = value | an 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 indexsub_index(int) — subindexentry_name(str) — object entry nameis_read_operation(bool) —True= read operation,False= write operationobj_access(int) — raw access permission bits (flag definitions seeObjAccess)
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 indexsub_index(int) — subindexcustom_message(str) — custom exception message; it is also written to theentry_namefield (this classmethod does not accept a separate object name argument)is_read_operation(bool) —Truemeans a read operation,Falsemeans a write operationobj_access(int) — raw access permission bits
Returns:
CoE_AccessDeniedException— the exception instance, raised by the caller withraise
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
| Name | Value | Description |
|---|---|---|
| NO_ERROR | 0x00000000 | No error |
| TOGGLE_BIT_NOT_CHANGED | 0x05030000 | Toggle bit not changed |
| SDO_PROTOCOL_TIMEOUT | 0x05040000 | SDO protocol timeout |
| INVALID_COMMAND_SPECIFIER | 0x05040001 | Invalid command specifier |
| INVALID_BLOCK_SIZE | 0x05040002 | Invalid block size (CiA 301 block transfer) |
| INVALID_SEQUENCE_NUMBER | 0x05040003 | Invalid block sequence number (CiA 301 block transfer) |
| CRC_ERROR | 0x05040004 | CRC check error (CiA 301 block transfer) |
| OUT_OF_MEMORY | 0x05040005 | Out of memory |
| UNSUPPORTED_ACCESS | 0x06010000 | Unsupported access |
| READ_WRITE_ONLY_ERROR | 0x06010001 | Attempt to read a write-only object |
| WRITE_READ_ONLY_ERROR | 0x06010002 | Attempt to write a read-only object |
| SUBINDEX_WRITE_ERROR | 0x06010003 | Writing to the subindex is not allowed |
| COMPLETE_ACCESS_NOT_SUPPORTED | 0x06010004 | Complete access not supported |
| OBJECT_LENGTH_EXCEEDED | 0x06010005 | Object length exceeded |
| OBJECT_MAPPED_TO_RXPDO | 0x06010006 | Object already mapped to RxPDO |
| OBJECT_DOES_NOT_EXIST | 0x06020000 | Object does not exist |
| CANNOT_BE_MAPPED_TO_PDO | 0x06040041 | Cannot be mapped to PDO |
| EXCEEDS_PDO_LENGTH | 0x06040042 | Exceeds the PDO length |
| PARAMETER_INCOMPATIBILITY | 0x06040043 | Parameter incompatibility |
| INTERNAL_INCOMPATIBILITY | 0x06040047 | Internal incompatibility |
| HARDWARE_ACCESS_ERROR | 0x06060000 | Hardware access error |
| DATA_TYPE_MISMATCH | 0x06070010 | Data type mismatch |
| DATA_TYPE_TOO_HIGH | 0x06070012 | Data type length too large |
| DATA_TYPE_TOO_LOW | 0x06070013 | Data type length too small |
| SUBINDEX_DOES_NOT_EXIST | 0x06090011 | Subindex does not exist |
| SUBINDEX_DOES_NOT_EXIST_FOR_OBJECT | 0x06090012 | Subindex does not exist (object variant) |
| VALUE_RANGE_EXCEEDED | 0x06090030 | Value out of range |
| VALUE_TOO_HIGH | 0x06090031 | Value too high |
| VALUE_TOO_LOW | 0x06090032 | Value too low |
| MODULE_IDENT_LIST_MISMATCH | 0x06090033 | Module list mismatch |
| MAX_LESS_THAN_MIN | 0x06090036 | Maximum less than minimum |
| RESOURCE_NOT_AVAILABLE | 0x060A0023 | Resource not available (SDO connection) |
| GENERAL_ERROR | 0x08000000 | A "general error" really returned by the device (out-of-table codes are not folded into this entry; see UNKNOWN_ERROR) |
| DATA_TRANSFER_ERROR | 0x08000020 | Data cannot be transferred or stored to the application (reported by the device) |
| LOCAL_CONTROL_ERROR | 0x08000021 | Data cannot be transferred or stored because of local control (reported by the device) |
| DEVICE_STATE_ERROR | 0x08000022 | Data cannot be transferred or stored because of the present device state (reported by the device) |
| DICTIONARY_ERROR | 0x08000023 | Dictionary error |
| LOCAL_REQUEST_NOT_SENT | 0x0D000001 | Request not sent (local reject): no frame went on the bus; not an abort code reported by the device |
| UNKNOWN_ERROR | 0xFFFFFFFF | Unknown error: out-of-table abort codes not covered by the SDK code table land here; the original code is in last_sdo_abort_code |
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.
| Code | Meaning | What to do |
|---|---|---|
| 0x0D000002 | Frame transmitted, but no device counted it | Check whether that slave's mailbox is rejecting or full, and check the receive path |
| 0x0D000003 | Mailbox layer error (the peer returned a mailbox Error frame) | Check the mailbox SM configuration and the request length |
| 0x0D000004 | Transport 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 value | Value | Python type | Description |
|---|---|---|---|
| NONE | 0x0000 | bytes | Untyped (raw bytes) |
| BOOLEAN | 0x0001 | bool | Boolean |
| INTEGER8 | 0x0002 | int | int8 |
| INTEGER16 | 0x0003 | int | int16 |
| INTEGER32 | 0x0004 | int | int32 |
| UNSIGNED8 | 0x0005 | int | uint8 |
| UNSIGNED16 | 0x0006 | int | uint16 |
| UNSIGNED32 | 0x0007 | int | uint32 |
| REAL32 | 0x0008 | float | Single-precision floating point |
| VISIBLE_STRING | 0x0009 | str | ASCII string |
| OCTET_STRING | 0x000A | bytes | Byte string |
| UNICODE_STRING | 0x000B | str | Unicode string |
| TIME_OF_DAY | 0x000C | bytes | Time (raw bytes) |
| TIME_DIFFERENCE | 0x000D | bytes | Time difference (raw bytes; old alias TIME_DIFF) |
| DOMAIN | 0x000F | bytes | Raw data |
| REAL64 | 0x0011 | float | Double-precision floating point |
| INTEGER64 | 0x0015 | int | int64 |
| UNSIGNED64 | 0x001B | int | uint64 |
| UNKNOWN | 0xFFFF | bytes | Sentinel 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; returns0when it cannot be determined (NONE, variable-length string types /DOMAIN,BIT1–BIT8, out-of-table codesGUID/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 returnNone
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 isdarra_ethercat.utils.value_codec.type_name(dt); the static wrapper isProtocolCodes.pdo_data_type_name(dt)(requiresProtocolCodes.set_dll(dll)first, seedarra_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_STRINGin 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))
| Flag | Value | Description |
|---|---|---|
| NONE | 0x0000 | No permission |
| READ_PRE | 0x0001 | Readable in PreOp |
| READ_SAFE | 0x0002 | Readable in SafeOp |
| READ_OP | 0x0004 | Readable in OP |
| WRITE_PRE | 0x0008 | Writable in PreOp |
| WRITE_SAFE | 0x0010 | Writable in SafeOp |
| WRITE_OP | 0x0020 | Writable in OP |
| MAPPABLE | 0x0040 | Can be mapped to PDO |
| BACKUP | 0x0080 | Backup parameter (stored in EEPROM) |
| SETTINGS | 0x0100 | Configuration parameter |
| READABLE | 0x0007 | Readable in all states (= READ_PRE | READ_SAFE | READ_OP) |
| WRITABLE | 0x0038 | Writable in all states (= WRITE_PRE | WRITE_SAFE | WRITE_OP) |
| READ_WRITE_ALL | 0x003F | Readable 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.
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's0x10F3:00, with no fixed hard truncation) and returnsList[DiagnosticMessage]; it is relatively expensive. The async version isread_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
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):
| Value | Semantics | Meaning |
|---|---|---|
DiagnosticPollResult.HAS_NEW | New messages available | Should keep fetching (recommended to follow immediately with read_diagnostic_meta() + read_diagnostic_message()) |
DiagnosticPollResult.NONE | No new messages | Includes the slave not supporting 0x10F3 |
DiagnosticPollResult.FAILED | Communication failure | The 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
Per ETG.1020 v1.5.0 Table 49, flags (0x10F3:05) is defined as:
bit4= diagnostic buffer mode: 0 = Overwrite / 1 = Acknowledgebit5= 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);Noneon 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
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_emergencycallback; for history →slave.emcy_history - To actively poll historical diagnostic records → the
0x10F3interface in this section