Skip to main content

CoE (CANopen over EtherCAT)

Quick start​

auto& coe = master.GetSlave(1).GetCoE();

// Read SDO (raw bytes) - a failure / WKC=0 returns an empty vector, so check for empty before memcpy
auto data = coe.SDORead(0x6041, 0);
if (data.empty()) {
auto err = coe.last_sdo_error();
printf("SDO 失败: 0x%08X\n", static_cast<uint32_t>(err)); // SDOProtocolTimeout != object does not exist
return;
}
uint16_t status_word;
std::memcpy(&status_word, data.data(), 2);
printf("StatusWord: 0x%04X\n", status_word);

// Write SDO (raw bytes)
uint16_t control_word = 0x0006;
if (!coe.SDOWrite(0x6040, 0,
reinterpret_cast<const uint8_t*>(&control_word),
sizeof(control_word)))
return;
SDORead returns an empty vector on failure / WKC=0

Do not memcpy an empty vector or parse it as uint32_t. last_sdo_error() == SDOError::SDOProtocolTimeout means the mailbox did not answer (WKC=0 / timeout); it is not "the object does not exist". Only a deterministic abort (unsupported access, object or subindex missing: ObjectDoesNotExist 0x06020000 / SubindexDoesNotExist 0x06090011 / 0x06090012) enters the NotPresent cache.

When the device returns an access-denied abort code (0x06010000 / read 0x06010001) the call throws darra::CoEAccessDeniedException instead of returning an empty vector; wrap SDO calls so the exception can be caught — see CoE access denied exception.

SDO read and write​

SDORead()​

std::vector<uint8_t> SDORead(uint16_t index, uint8_t subindex = 0,
bool completeAccess = false) const;

Read raw SDO bytes. On failure / WKC=0 it returns an empty vector. An empty success (an empty VISIBLE_STRING) is also an empty vector; tell the two apart with last_sdo_error(): NoError = the empty string was read successfully, SDOProtocolTimeout = WKC=0 / timeout. When the device returns an access-denied abort code (0x06010000 / read 0x06010001) it throws darra::CoEAccessDeniedException instead of returning an empty vector (see CoE access denied exception).

Parameters:

  • index (uint16_t) — object index, for example 0x6041.
  • subindex (uint8_t) — subindex, default 0.
  • completeAccess (bool) — default false (read only the given subindex); pass true for a Complete Access read of the whole object. In that case subindex may only be 0 or 1 (ETG.1000.6 Table 34 / ETG.1020 §14.2); when out of range the call fails immediately without sending a request (returns an empty vector, last_sdo_error() = GeneralError).
  • const member function: it does not change the OD list cache held by CoE, but it does refresh last_sdo_error().

Returns:

  • std::vector<uint8_t> — the raw bytes read on success; an empty vector on failure / WKC=0.
  • Access denied throws: when the device returns 0x06010000 (unsupported object access) or 0x06010001 (reading a write-only object) it throws darra::CoEAccessDeniedException and does not return an empty vector; the same is thrown when the NotPresent negative cache is hit and the cached code is one of these two. Every other failure still returns an empty vector — surround the call site with try/catch (see CoE access denied exception for an example).
  • A single read is capped at 64 KB: when the response data of an SDO read or of OD enumeration exceeds 64 KB it is returned as a failed read (empty std::vector, last_sdo_error() records it as-is); split oversized objects into several reads.
  • NotPresent negative cache: a deterministic abort (ObjectDoesNotExist / SubindexDoesNotExist / 0x06090012 and other codes the slave explicitly rejects and that would not succeed on retry) is recorded in the negative cache per (从站, index, subindex). Later SDORead calls for the same (index, subindex) do not touch the bus and short-circuit immediately: if the cached code is one of the access-denied codes (0x06010000 / 0x06010001) it throws, otherwise it returns an empty vector, and last_sdo_error() replays the cached abort. Call ResetNotPresentCache() after hot-plug / firmware update / topology change. completeAccess = true and SDOWrite do not use this cache.
  • Timing / state gate: no state gate is required (SDO can be sent from INIT onwards); when the slave mailbox is not up, the call returns an empty vector as a communication failure.
  • Thread safety: SDO calls to the same slave and reads of last_sdo_error() must run sequentially on the same thread; concurrent calls from several threads are not supported. To drive the mailbox from several threads, use Asynchronous SDO instead (it goes through the master serialization gate).

Example:

auto data = coe.SDORead(0x6041, 0);          // StatusWord
if (data.empty()) {
auto err = coe.last_sdo_error();
printf("SDO 读取失败: 0x%08X\n", static_cast<uint32_t>(err)); // SDO read failed: 0x%08X
return;
}
uint16_t status_word;
std::memcpy(&status_word, data.data(), 2);
Always check for emptiness
  • Access denied (0x06010000, read 0x06010001) is not an empty vector — it throws darra::CoEAccessDeniedException (see CoE access denied exception)
  • Do not memcpy the return value straight into a uint32_t
  • SDOError::GeneralError (0x08000000) is not "the object does not exist" and is not written to NotPresent
  • Only a deterministic abort enters NotPresent (unsupported access, object or subindex missing): ObjectDoesNotExist / SubindexDoesNotExist / 0x06090012

SDORead() detail overload​

std::vector<uint8_t> SDORead(uint16_t index, uint8_t subindex,
SDOReadDetail& detail,
bool completeAccess = false) const;

The returned data is unchanged; the out parameter detail additionally carries ok / data / abort_code / wkc. This is the only unambiguous success criterion — an empty vector can mean either failure or an empty string read successfully, whereas detail.ok is always a real value.

Parameters:

  • index (uint16_t) / subindex (uint8_t) — same as SDORead(); with completeAccess = true, subindex may only be 0 or 1.
  • detail (SDOReadDetail&) — out parameter, filled in the order ok / data / abort_code / wkc (the same order as the struct declaration).
  • completeAccess (bool) — default false.

Returns:

  • std::vector<uint8_t> — exactly the same semantics as the version without the out parameter (empty vector on failure).
  • detail.ok — the only success criterion; detail.data is empty on failure.
  • detail.abort_code (uint32_t) — the abort code returned by the device, passed through as-is: a value other than 0 is the abort code really returned by the device (or by the NotPresent negative cache); when the device sent no abort code (WKC=0 / timeout / a fallback entry point with no abort out parameter) the transport-layer SDOProtocolTimeout (0x05040000) is reported and 0x08000000 is never fabricated (it is 0 on an invalid parameter or when nothing was sent on the bus). Judge success by ok only; never treat abort_code == 0 as success. last_sdo_error() uses the same convention as abort_code.
  • detail.wkc (int) — the real working counter, 0 on the failure path; a NotPresent cache short-circuit produces no WKC (wkc=0), and when the runtime library is unavailable it is synthesised as 1/0 from ok.
  • Length cap: response data over 64 KB is returned as a failure (ok=false, data empty); split oversized objects into several reads.

Related structures:

struct SDOReadDetail {
bool ok; // Whether it succeeded (the only success criterion)
std::vector<uint8_t> data; // The data read (empty on failure)
uint32_t abort_code; // The Abort Code the device returned; 0 = the device sent no abort code, which does not mean success
int wkc; // Work counter (0 on the failure path)
};

struct SDOWriteDetail {
bool ok; // Whether it succeeded (the only success criterion)
uint32_t abort_code; // The Abort Code the device returned; 0 = the device sent no abort code, which does not mean success
int wkc; // Work counter (0 on the failure path)
};

ResetNotPresentCache() / ClearSdoCaches()​

void ResetNotPresentCache();   // Clear the NotPresent negative cache of (master, slave)
void ClearSdoCaches(); // Equivalent to ResetNotPresentCache (the C++ layer has no mailbox value cache)

Clear the NotPresent negative cache of this slave: after clearing, an (index, subindex) previously judged "the object does not exist" is sent as a real SDO again.

Parameters:

  • None. Both act only on the (master, slave) pair the current CoE instance belongs to; other slaves are not affected.

Returns:

  • void. There is no success / failure signal.

Example:

// After Hot-plug / firmware upgrade / topology change / degraded PreOp
coe.ResetNotPresentCache();

Notes:

  • Call it only after hot-plug / firmware update / topology change.
  • ClearSdoCaches() is an alias of ResetNotPresentCache(): the C++ header layer has no separate mailbox value cache, so both names clear the same table.

SDOWrite()​

bool SDOWrite(uint16_t index, uint8_t subindex,
const uint8_t* data, int dataLen,
bool completeAccess = false) const;

bool SDOWrite(uint16_t index, uint8_t subindex,
const std::vector<uint8_t>& data,
bool completeAccess = false) const;

Write SDO data. Both a raw pointer and a std::vector are supported. Returns true on success; false on failure, with the reason in last_sdo_error() (the abort code when the slave rejects the write, SDOProtocolTimeout (0x05040000) for a communication-level failure). When the device returns an access-denied abort code (0x06010000 / write 0x06010002) it throws darra::CoEAccessDeniedException instead of returning false (see CoE access denied exception).

Parameters:

  • index (uint16_t) — object index.
  • subindex (uint8_t) — subindex.
  • data — the raw bytes to write, typed const uint8_t* (together with dataLen) or const std::vector<uint8_t>& (the length is data.size()).
  • dataLen (int) — byte count for the pointer overload.
  • completeAccess (bool) — default false; true = Complete Access write of the whole object, in which case subindex may likewise only be 0 or 1; when out of range the call fails immediately without sending a request (returns false).
  • const member function; an abort from a failed write is not written to the NotPresent negative cache (only SDORead writes it).

Returns:

  • bool — true = write succeeded; false = failure.
  • When false is returned (any one of these fails the call): data is a null pointer, dataLen <= 0, or an empty std::vector (all three fail immediately without a bus request, last_sdo_error() = GeneralError); completeAccess = true and subindex is not 0 / 1; the slave returns an abort (last_sdo_error() = that abort code); a communication-level failure (last_sdo_error() = SDOProtocolTimeout).
  • Access denied throws: when the device returns 0x06010000 (unsupported object access) or 0x06010002 (writing a read-only object) it throws darra::CoEAccessDeniedException and does not return false; every other failure still returns false.
  • State gate: the write permission depends on the object's own obj_access bits (see ObjAccessFlags); prejudge it with ObjectEntry::CanWritePreOp() / CanWriteSafeOp() / CanWriteOp(). When the permission does not match, the slave returns an abort such as WriteReadOnlyError (0x06010002) / SubindexWriteError (0x06010003). 0x06010002 throws as access denied, while 0x06010003 is still reported by returning false.
  • Thread safety: the same constraint as SDORead() — SDO calls to the same slave must run sequentially.

Example:

uint16_t control_word = 0x0006;
if (!coe.SDOWrite(0x6040, 0,
reinterpret_cast<const uint8_t*>(&control_word),
sizeof(control_word))) {
printf("写失败: 0x%08X\n", static_cast<uint32_t>(coe.last_sdo_error())); // Write failed: 0x%08X
return;
}

// std::vector version
std::vector<uint8_t> payload = {0x06, 0x00};
if (!coe.SDOWrite(0x6040, 0, payload))
return;

SDOWrite() detail overload​

bool SDOWrite(uint16_t index, uint8_t subindex,
const uint8_t* data, int dataLen,
SDOWriteDetail& detail,
bool completeAccess = false) const;

bool SDOWrite(uint16_t index, uint8_t subindex,
const std::vector<uint8_t>& data,
SDOWriteDetail& detail,
bool completeAccess = false) const;

The return value matches the version without the out parameter (true on success); detail additionally carries ok / abort_code / wkc.

Parameters:

  • index (uint16_t) / subindex (uint8_t) / data / dataLen — same as SDOWrite().
  • detail (SDOWriteDetail&) — out parameter, filled in the order ok / abort_code / wkc (the same order as the struct declaration).
  • completeAccess (bool) — default false.

Returns:

  • bool — true = success, the same value as detail.ok; false = failure.
  • detail.abort_code (uint32_t) — the abort code returned by the device, passed through as-is: a value other than 0 is the real abort code; when the device sent no abort code (WKC=0 / timeout / a fallback entry point with no abort out parameter) it reports SDOProtocolTimeout (0x05040000); an invalid parameter or a call not dispatched to the bus stays 0. Success is judged from ok alone.
  • detail.wkc (int) — the working counter; when the runtime library is unavailable it is synthesised as 1/0 from ok.

SDO negative cache​

The runtime library performs the NotPresent short-circuit in SDORead() automatically: a deterministic abort (explicitly rejected by the slave, would not succeed on retry) is written to the negative cache (the first write wins), and later reads with the same key short-circuit without touching the bus. The "object does not exist / subindex does not exist" family of aborts is handled as one class. Callers do not need to maintain their own "object does not exist" list.

GeneralError / SDOProtocolTimeout do not enter the cache

SDOError::SDOProtocolTimeout (0x05040000, the device sent no abort code) and SDOError::GeneralError (0x08000000, the device really returned a general error) are not "the object does not exist"; neither is written to the negative cache, so a single glitch does not permanently short-circuit that object.

Clear the slave's negative cache manually only after hot-plug / firmware update / topology change:

coe.ResetNotPresentCache();   // Equivalent to ClearSdoCaches()

Typed SDO read and write​

Reads return std::optional and std::nullopt on failure; writes return bool. All are const member functions and take no completeAccess parameter (the typed interface reads and writes single subindexes only; for a whole-object read use completeAccess on SDORead() / SDOWrite()).

Full signatures — reads:

std::optional<uint8_t>   SDOReadU8   (uint16_t idx, uint8_t sub = 0) const;
std::optional<uint16_t> SDOReadU16 (uint16_t idx, uint8_t sub = 0) const;
std::optional<uint32_t> SDOReadU32 (uint16_t idx, uint8_t sub = 0) const;
std::optional<uint64_t> SDOReadU64 (uint16_t idx, uint8_t sub = 0) const;
std::optional<int16_t> SDOReadI16 (uint16_t idx, uint8_t sub = 0) const;
std::optional<int32_t> SDOReadI32 (uint16_t idx, uint8_t sub = 0) const;
std::optional<float> SDOReadFloat (uint16_t idx, uint8_t sub = 0) const;
std::optional<double> SDOReadDouble(uint16_t idx, uint8_t sub = 0) const;
std::optional<std::string> SDOReadString(uint16_t idx, uint8_t sub = 0) const;

Full signatures — writes:

bool SDOWriteU8   (uint16_t idx, uint8_t sub, uint8_t   val) const;
bool SDOWriteU16 (uint16_t idx, uint8_t sub, uint16_t val) const;
bool SDOWriteU32 (uint16_t idx, uint8_t sub, uint32_t val) const;
bool SDOWriteU64 (uint16_t idx, uint8_t sub, uint64_t val) const;
bool SDOWriteI16 (uint16_t idx, uint8_t sub, int16_t val) const;
bool SDOWriteI32 (uint16_t idx, uint8_t sub, int32_t val) const;
bool SDOWriteFloat (uint16_t idx, uint8_t sub, float val) const;
bool SDOWriteDouble(uint16_t idx, uint8_t sub, double val) const;

Parameters:

  • idx (uint16_t) — object index; sub (uint8_t) — subindex, default 0.
  • val — the value to write, its type matching the method name; numeric values are packed little-endian per ETG.
  • For reads, the std::optional holds a value only when the data is long enough.

Returns:

  • Read std::optional<T> — std::nullopt on failure; insufficient data length (for example a U16 read that returned only 1 byte) also returns std::nullopt.
  • Write bool — true on success, false on failure (the value could not be put into the buffer / the underlying SDOWrite failed).
  • The failure reason always comes from last_sdo_error(), with the same semantics as SDORead() / SDOWrite().
  • Empty-data ambiguity: SDOReadString also returns std::nullopt for empty data (including an empty string read successfully), which cannot be told apart from a read failure; use SDOReadDetail when you need to tell them apart.
CategoryMethodTypeRead/writeDescription
Typed readSDOReadU8 / U16 / U32 / U64std::optional<integer>read-onlyUnsigned 8 / 16 / 32 / 64 bit
Typed readSDOReadI16 / I32std::optional<integer>read-onlySigned 16 / 32 bit
Typed readSDOReadFloat / Doublestd::optional<floating point>read-only32 / 64-bit floating point
Typed readSDOReadStringstd::optional<std::string>read-onlyString, decoded by its OD type
Typed writeSDOWriteU8 / U16 / U32 / U64boolwrite-onlyWrites uint8_t … uint64_t, returns false on failure
Typed writeSDOWriteI16 / I32boolwrite-onlyWrites int16_t / int32_t, returns false on failure
Typed writeSDOWriteFloat / Doubleboolwrite-onlyWrites float / double, returns false on failure

SDOReadString decodes by the object's own OD data type: the type comes from the loaded OD table (VISIBLE_STRING / OCTET_STRING use single-byte ISO-8859-1, UNICODE_STRING uses UTF-16LE with surrogate pairs emitted as UTF-8), and the byte-level conversion is done by the runtime library. When the OD provides no string type for that entry, the raw bytes are kept (with the trailing \0 removed) and the encoding is not guessed.

Example:

auto& coe = master.GetSlave(1).GetCoE();

auto sw = coe.SDOReadU16(0x6041, 0); // std::optional<uint16_t>
auto pos = coe.SDOReadI32(0x6064, 0); // std::optional<int32_t>
auto name = coe.SDOReadString(0x1008, 0); // std::optional<std::string>
if (sw) printf("StatusWord: 0x%04X\n", *sw);
if (pos) printf("位置: %d\n", *pos); // Position: %d

if (!coe.SDOWriteU16(0x6040, 0, 0x0006)) // ControlWord
return;
if (!coe.SDOWriteU8 (0x6060, 0, 8)) // Mode of operation CSP
return;

Properties​

CategoryPropertyTypeRead/writeDescription
Diagnosticslast_sdo_error()SDOErrorread-onlyError code of the most recent SDO operation
Diagnosticslast_od_error()const std::string&read-onlyReason of the most recent OD load failure (empty = no failure)
Diagnosticslast_od_abort()uint16_tread-onlyDevice abort code of the most recent SDO Information read; 0 = the device returned no abort code (does not mean success)
Diagnosticslast_od_wkc()uint16_tread-onlyInnermost mailbox transaction WKC of the most recent SDO Information read (1 = success, 0 = failure / not executed)
StatisticsGetSdoStats(SdoStats&)boolread-onlyReads the accumulated SDO request statistics snapshot for this slave; false = the read failed (the out parameter is zeroed)
Instance infoDll()dll_t&read-onlyReference to the SDK context
Instance infoMasterIndex()uint16_tread-onlyMaster number
Instance infoSlaveIndex()uint16_tread-onlySlave index

Dll() / MasterIndex() / SlaveIndex() can be fed straight into the slave_emcy free functions described below.

last_sdo_error()​

SDOError last_sdo_error() const;
Naming: the C++ method is snake_case last_sdo_error()

The C++ SDK method is last_sdo_error() (snake_case) and returns the SDOError enumeration (note that all three letters of SDO are upper case).

Error code of the most recent SDO operation. When SDORead() / SDOWrite() fails, this method gives the SDO abort code. After a successful operation it resets to SDOError::NoError automatically.

GeneralError is not "the object does not exist"
  • SDOError::SDOProtocolTimeout (0x05040000) — WKC=0 / mailbox timeout / no answer (the device sent no abort code). Retryable; it is not treated as a missing object and is not written to NotPresent.
  • Only a deterministic abort enters NotPresent (unsupported access, object or subindex missing): ObjectDoesNotExist (0x06020000), SubindexDoesNotExist (0x06090011), 0x06090012.

When it is overwritten:

  • SDORead() / SDOWrite() / the typed SDOReadU8, SDOReadU16, SDOReadU32, SDOReadI16, SDOReadI32, SDOReadFloat, SDOReadString (and the matching SDOWriteU8 family for writes) refresh it before they return
  • success → it becomes SDOError::NoError
  • failure → it becomes the matching SDO abort code (degraded to SDOError::SDOProtocolTimeout when there is no abort code)
  • each slave's CoE holds its own copy; they do not overwrite each other
  • read it immediately after the call: the next SDO call to the same slave overwrites it, and concurrent reads from several threads are not supported — SDO calls and last_sdo_error() reads must run sequentially on the same thread

Example:

auto data = coe.SDORead(0x6041, 0);
if (data.empty()) {
auto error = coe.last_sdo_error();
printf("SDO 读取失败: 0x%08X\n", static_cast<uint32_t>(error)); // SDO read failed: 0x%08X
}

last_od_error() / last_od_abort() / last_od_wkc()​

const std::string& last_od_error() const;   // Empty = no failure
uint16_t last_od_abort() const; // Device abort code; 0 = the device sent no abort code
uint16_t last_od_wkc() const; // Result of the innermost mailbox transaction; 1=success, 0=failure/not executed

LoadODList() / LoadODListAsync() / LoadObjectDictionary() / GetObjectDescription() / GetEntryDescription() / TryLoadFromEsi() leave these three values behind when they fail:

  • last_od_error() — a human-readable failure reason, used to tell "the device has no CoE / SDO Info is not supported", "no ESI identity matched", "the mailbox is not up" and "the SDK is not ready" apart; cleared on success.
  • last_od_abort() / last_od_wkc() — the real abort code and WKC of the SDO Information exchange. abort == 0 means the device returned no abort code (timeout / protocol failure and so on) and does not mean success; success is judged by the entry point's return value only.
  • Multi-transaction interfaces (the segmented OD list plus per-subindex descriptions) take the worst result: when the object list succeeds but one subentry description fails, wkc is recorded as 0 and the first real abort code is kept; later successes do not mask an earlier failure.

Example:

auto* od = coe.LoadODList();
if (!od) {
printf("OD 加载失败: %s (abort=0x%04X, wkc=%u)\n", // OD load failed: %s (abort=0x%04X, wkc=%u)
coe.last_od_error().c_str(),
coe.last_od_abort(), coe.last_od_wkc());
}

SDO request statistics​

struct SdoStats {
uint32_t requests = 0; ///< Number of SDO requests sent
uint32_t retries = 0; ///< Automatic resend count after a timeout
uint32_t timeouts = 0; ///< Mailbox timeout count
};

bool GetSdoStats(SdoStats& out) const;

Read the accumulated SDO statistics snapshot of this slave.

Parameters:

  • out (SdoStats&) — output snapshot; its contents are zeroed before the call

Returns / failure semantics:

  • true = the read succeeded and out holds the snapshot
  • false = the runtime library is not ready / the runtime call failed; out has been zeroed and must not be read as "0 requests"
  • counters accumulate per slave and are zeroed when the runtime context is initialized / closed

Typical use — proving "exactly one request":

CoE::SdoStats before, after;
if (!coe.GetSdoStats(before)) {
/* Statistics unavailable: can only judge UNPROVEN, never manufacture a false green*/
}
/* ... make one asynchronous SDO call ...*/
if (coe.GetSdoStats(after) &&
(after.requests - before.requests) == 1u &&
(after.retries - before.retries) == 0u) {
/* Proves this call sent exactly one request*/
}

Comparing the number of completion callbacks cannot tell a silent resend after a runtime timeout apart; the requests increment is the criterion for "really sent only once".

SDOError enumeration​

SDO operation error codes (CANopen standard / ETG.1020). Declared as enum class SDOError : uint32_t; it can be compared directly with == against the return value of last_sdo_error(), and static_cast<uint32_t>() prints the raw code.

CategoryNameValueRead/writeDescription
No errorNoError0x00000000read-onlyNo error
ProtocolToggleBitNotChanged0x05030000read-onlyToggle bit not changed
ProtocolSDOProtocolTimeout0x05040000read-onlySDO protocol timeout
ProtocolInvalidCommandSpecifier0x05040001read-onlyInvalid command specifier
ProtocolInvalidBlockSize0x05040002read-onlyInvalid block size
ProtocolInvalidSequenceNumber0x05040003read-onlyInvalid sequence number
ProtocolCrcError0x05040004read-onlyCRC check error
ProtocolOutOfMemory0x05040005read-onlyOut of memory
AccessUnsupportedAccess0x06010000read-onlyUnsupported access
AccessReadWriteOnlyError0x06010001read-onlyAttempted read of a write-only object
AccessWriteReadOnlyError0x06010002read-onlyAttempted write to a read-only object
AccessSubindexWriteError0x06010003read-onlyThe subindex is not writable
AccessCompleteAccessNotSupported0x06010004read-onlyComplete Access not supported
ObjectObjectLengthExceeded0x06010005read-onlyObject length exceeded
ObjectObjectMappedToRxPDO0x06010006read-onlyThe object is mapped to RxPDO
ObjectObjectDoesNotExist0x06020000read-onlyObject does not exist (deterministic failure, enters the NotPresent negative cache)
PDO mappingCannotBeMappedToPDO0x06040041read-onlyCannot be mapped to a PDO
PDO mappingExceedsPDOLength0x06040042read-onlyExceeds the PDO length
PDO mappingParameterIncompatibility0x06040043read-onlyParameter incompatibility
PDO mappingInternalIncompatibility0x06040047read-onlyInternal incompatibility
HardwareHardwareAccessError0x06060000read-onlyHardware access error
TypeDataTypeMismatch0x06070010read-onlyData type mismatch
TypeDataTypeTooHigh0x06070012read-onlyData type length too high
TypeDataTypeTooLow0x06070013read-onlyData type length too low
SubindexSubindexDoesNotExist0x06090011read-onlySubindex does not exist (deterministic failure, enters the NotPresent negative cache)
ValueValueRangeExceeded0x06090030read-onlyValue out of range
ValueValueTooHigh0x06090031read-onlyValue too high
ValueValueTooLow0x06090032read-onlyValue too low
ValueModuleIdentListMismatch0x06090033read-onlyModule list mismatch
ValueMaxLessThanMin0x06090036read-onlyMaximum less than minimum
ValueResourceNotAvailable0x060A0023read-onlyResource not available
CommunicationSDOProtocolTimeout0x05040000read-onlyThe device sent no abort code (WKC=0 / mailbox timeout / no answer); does not enter NotPresent
CommunicationGeneralError0x08000000read-onlyGeneral error (the device really returned this code; does not enter NotPresent)
Device sideDataTransferError0x08000020read-onlyData cannot be transferred or stored to the application (reported by the device)
Device sideLocalControlError0x08000021read-onlyData cannot be transferred or stored because of local control (reported by the device)
Device sideDeviceStateError0x08000022read-onlyData cannot be transferred or stored because of the present device state (reported by the device)
Device sideDictionaryError0x08000023read-onlyDictionary error
UnknownUnknownError0xFFFFFFFFread-onlyUnknown error
0x0D0000xx are master-side codes, not slave abort codes

These four codes are not reported by a slave. They only appear when the request did not complete and the device returned no abort frame. Seeing one means there is nothing to look up in the object dictionary.

CodeMeaningWhat to do
0x0D000001Request not sent (invalid arguments, slave index out of range, the slave does not support CoE, the mailbox is not ready) — no frame went on the busFix the arguments, or move the slave to PreOp first; resending as-is will not succeed
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

SDOError has no enum member for these four codes; print the raw value with static_cast<uint32_t>(). The codes a device reports — 0x08000020 / 0x08000021 / 0x08000022 — differ both in value and in meaning.

What to do for common codes:

CategoryEnumValueRead/writeAction
No errorNoError0x00000000read-onlyNormal
Communication / deviceSDOProtocolTimeout / GeneralError0x05040000 / 0x08000000read-only0x05040000 = timeout or no mailbox answer (the device sent no abort code): retry once; if it still fails, report it as a communication fault. 0x08000000 = the device really returned a general error without a reason: investigate. Neither is a missing object
AccessReadWriteOnlyError / WriteReadOnlyError0x06010001 / 0x06010002read-onlyWrong direction: change the direction of the call
Object missingObjectDoesNotExist0x06020000read-onlyCheck the ESI / OD to confirm the index; deterministic failure, stop retrying
Subindex missingSubindexDoesNotExist0x06090011read-onlyCheck by subindex. 0x06090012 has no matching enum member; print the raw code
Unsupported accessUnsupportedAccess0x06010000read-onlyChange state or use PDO instead
Invalid valueValueRangeExceeded / ValueTooHigh / ValueTooLow0x06090030 / 31 / 32read-onlyCorrect it against the OD limits
Type mismatchDataTypeMismatch / DataTypeTooHigh / DataTypeTooLow0x06070010 / 12 / 13read-onlyPick the matching SDORead* / SDOWrite* for the object type
Already mappedObjectMappedToRxPDO / CannotBeMappedToPDO / ExceedsPDOLength0x06010006 / 0x06040041 / 0x06040042read-onlyRelease it in the PDO mapping first
UnknownUnknownError0xFFFFFFFFread-onlyPrint the raw code and log it

Getting a description for an abort code:

const char* darra::ethercat::statics::sdo_error_description(uint32_t code);

Codes not in the table fall back to the "unknown Abort Code" form produced by the runtime library. English text is not available at present; do not build your own lookup table in the application.

Returns:

  • const char* — the Chinese description text; pass static_cast<uint32_t>(coe.last_sdo_error()).

Example:

if (data.empty())
printf("%s (0x%08X)\n",
darra::ethercat::statics::sdo_error_description(
static_cast<uint32_t>(coe.last_sdo_error())),
static_cast<uint32_t>(coe.last_sdo_error()));

CoE access denied exception​

namespace darra {
class CoEAccessDeniedException : public std::runtime_error {
public:
CoEAccessDeniedException(uint16_t index, uint8_t sub, const std::string& name,
bool isRead, uint16_t objAccess);

uint16_t Index() const; // Object index
uint8_t SubIndex() const; // Subindex
bool IsReadOperation() const; // true = read, false = write
uint16_t ObjAccess() const; // Object access bits used in the judgement
// what(): inherited from std::runtime_error, contains the full reason
};
}

SDORead() / SDOWrite() (including the detail overloads) throw this exception when the access is judged denied; they do not return an empty vector / false.

When it is thrown — device abort codes:

  • 0x06010000 (unsupported object access) — both read and write.
  • 0x06010001 (attempt to read a write-only object) — read only.
  • 0x06010002 (attempt to write a read-only object) — write only.

Any other abort code (object / subindex does not exist, value out of range, data type mismatch, timeout, and so on) does not throw; failure is still expressed through the return value. When the read path hits the NotPresent negative cache and the cached code is exactly one of the access-denied codes above, it throws as well, with the same semantics as the first on-line failure.

Device abort codes win: once abort_code != 0 the verdict comes from the device abort code alone; the permission bits of the local object descriptor cannot override it.

Local decision rules when there is no device abort code (the descriptor comes from the object dictionary, the state is the slave's current AL state):

  • Descriptor unknown (no ObjectEntry available) → allow; the device abort code stays the source of truth.
  • Reads require obj_access to contain the READ_ANY bit, writes require WRITE_ANY; a missing bit means access denied.
  • Reads also look at the AL state: Init / SafeOp accept READ_PREOP or READ_SAFEOP, PreOp accepts only READ_PREOP, OP requires READ_ANY; an unknown state is allowed, other known states such as Boot are denied.
  • A state mismatch on a write is not treated as access denied (it means "change state first"), so it does not throw.

The single decision and throw point:

namespace darra {
enum class CoEAccessReason : uint32_t { None = 0, Device = 1, Flags = 2, State = 3 };

struct CoEAccessVerdict {
bool denied = false; // Whether it is access denied
CoEAccessReason reason = CoEAccessReason::None; // Device / Flags / State
uint32_t abort_code = 0; // Device abort code used in the judgement (0 = the device sent none)
std::string message; // Reason for the refusal (empty when denied == false)
};

CoEAccessVerdict EvaluateCoEAccess(uint16_t index, uint8_t subIndex, bool isRead,
const ObjectEntry* entry, EcState state,
uint32_t abortCode);

void ThrowIfCoEAccessDenied(uint16_t index, uint8_t subIndex, bool isRead,
const ObjectEntry* entry, EcState state,
uint32_t abortCode);
}
  • EvaluateCoEAccess(...) — the only decision function; a pure function (no bus access, no runtime library calls), returns a CoEAccessVerdict. Use it when you only want the verdict and do not want to deal with an exception.
  • ThrowIfCoEAccessDenied(...) — the only throw site: it calls EvaluateCoEAccess internally and throws only when denied == true.
  • The SDK's own SDO read/write paths call the decision without an object descriptor (entry = nullptr) and without the slave state (EcState::None), so on that path only a device abort code can trigger a throw; to pre-judge by descriptor / AL state, call EvaluateCoEAccess(...) with your own ObjectEntry* and the current EcState.

Reading the exception information:

  • Index() / SubIndex() — the object index / subindex that failed.
  • IsReadOperation() — true for a read, false for a write.
  • ObjAccess() — the object access permission bits used in the decision; 0 when the descriptor is unknown.
  • what() — the complete reason in Chinese, including the device abort code or the permission-bit explanation.

Example (catch the exception so it does not reach the top of the call stack):

try {
auto data = coe.SDORead(0x6041, 0);
if (data.empty()) { /* Ordinary failure: see last_sdo_error()*/ }
} catch (const darra::CoEAccessDeniedException& e) {
printf("访问被拒: 0x%04X:%02X (%s) obj_access=0x%04X: %s\n", // Access denied: 0x%04X:%02X (%s) obj_access=0x%04X: %s
e.Index(), e.SubIndex(),
e.IsReadOperation() ? "读" : "写", e.ObjAccess(), e.what());
}

The async path has the same semantics: SDOReadAsync(...).get() / SDOWriteAsync(...).get() and their detail variants rethrow the same exception from the background thread at the .get() site (the serial gate only queues, it never swallows exceptions), so wrapping try/catch around .get() is enough.

CoEAccessDeniedException.CreateWithCustomMessage()​

static CoEAccessDeniedException CreateWithCustomMessage(
uint16_t index, uint8_t sub, const std::string& msg,
bool isRead, uint16_t objAccess);

Builds an “access denied” exception in which msg is the whole what(): it is handed unchanged to std::runtime_error, with no index template appended, no object name substituted and no extra wrapping. Index() / SubIndex() / IsReadOperation() / ObjAccess() are still filled from the parameters — the structured fields and the message text are fully decoupled, and the caller owns the whole text.

How this differs from the public constructor CoEAccessDeniedException(index, sub, name, isRead, objAccess): the public constructor assembles what() from a fixed Chinese template (对象条目 0x<index>:<sub> (<name>) 不支持读取/写入操作。访问权限: <描述> (SDK output, = object entry 0x<index>:<sub> (<name>) does not support read/write. Access: <description>), where name only fills the object-name slot); this method is the “message already built” entry point and msg becomes what() directly. Use the public constructor when you want the SDK’s fixed wording; use this method when you already have the complete error text.

Parameters:

  • index (uint16_t) — CoE object index
  • sub (uint8_t) — subindex
  • msg (const std::string&) — the complete error message text as-is (it becomes the whole e.what())
  • isRead (bool) — true for a read, false for a write; only fills the IsReadOperation() field, it does not affect the what() text
  • objAccess (uint16_t) — the object access permission bit field; only fills the ObjAccess() field, it does not affect the what() text

Returns:

  • CoEAccessDeniedException — a copy of the exception object, ready to throw

Example (the whole sentence is assembled by the caller; msg becomes what() verbatim):

if (!ObjAccessFlags::CanRead(entry.obj_access)) {
char msg[192];
std::snprintf(msg, sizeof(msg),
"对象条目 0x%04X:%02X (%s) 不支持读取操作。访问权限: %s", // (SDK output, = object entry 0x%04X:%02X (%s) does not support read. Access: %s)
static_cast<unsigned>(entry.od_index),
static_cast<unsigned>(entry.sub_index),
entry.name.c_str(),
ObjAccessFlags::GetAccessDescription(entry.obj_access).c_str());
throw CoEAccessDeniedException::CreateWithCustomMessage(
entry.od_index, entry.sub_index, msg, true, entry.obj_access);
}
When to use it

This method only builds the exception; it does not judge or throw by itself — the SDK decides with ThrowIfCoEAccessDenied(...) inside SDORead() / SDOWrite() and throws there (see CoE access denied exception). Use this method to throw for yourself when the application layer already holds the complete error text (assemble the whole sentence first); when you only have the index and subindex and can accept the SDK’s fixed wording (template plus object name), call the constructor CoEAccessDeniedException(index, sub, name, isRead, objAccess) directly.

2026-11-19 fix

The old implementation stuffed the caller’s custom text into the “object name” slot and wrapped it a second time in the fixed template, producing a what() shaped like 对象条目 0x....:.. (<整句错误>) 不支持写入操作。... (SDK output, = object entry 0x....:.. (<full error message>) does not support write operations. ...) — doubly wrapped and semantically wrong. That behaviour was a bug and has been changed so that msg goes straight through to std::runtime_error (internally via the PrebuiltMessage constructor that marks the message as already formed). After the fix what() no longer carries the index prefix or the permission description: read the Index() / SubIndex() / ObjAccess() fields when you need them, or splice them into msg yourself.

Object dictionary​

The OD is carried by a three-level structure: EcODList (the object list) → ObjectDictionary (a single object) → ObjectEntry (a subentry). All three levels are plain data structures and can be walked directly with a range-based for loop.

EcODList fields and methods:

CategoryField/methodTypeRead/writeDescription
EcODListfull_liststd::vector<ObjectDictionary>read-onlyAll objects (directly iterable)
EcODListCount()intread-onlyNumber of objects
EcODListGet(uint16_t idx)const ObjectDictionary*read-onlyGet by index; returns nullptr when not found
EcODListGet(const std::string& key)const ObjectDictionary*read-onlyGet by name; returns nullptr when not found
EcODListGetByPosition(int pos)const ObjectDictionary*read-onlyGet by position; returns nullptr when out of range
EcODListContainsKey(uint16_t idx)boolread-onlyChecks whether the index exists
EcODListContainsKey(const std::string& key)boolread-onlyChecks whether the name exists
EcODListCopy()EcODListread-onlyCreates a copy

ObjectDictionary fields and methods:

CategoryField/methodTypeRead/writeDescription
ObjectDictionaryindexuint16_tread-onlyObject index
ObjectDictionarynamestd::stringread-onlyObject name
ObjectDictionarydatatypeuint16_tread-onlyData type (raw EcDataType value)
ObjectDictionaryobject_codeuint8_tread-onlyObject code (0x07=VAR / 0x08=ARRAY / 0x09=RECORD)
ObjectDictionarymax_subuint8_tread-onlyMaximum subindex
ObjectDictionaryesi_default_textstd::stringread-onlyDisplay text of the ESI object-level default value
ObjectDictionaryentriesstd::vector<ObjectEntry>read-onlySubindex entries
ObjectDictionaryCount()intread-onlyNumber of subindexes
ObjectDictionaryIsVar()boolread-onlyWhether it is a VAR type
ObjectDictionaryIsArray()boolread-onlyWhether it is an ARRAY type
ObjectDictionaryIsRecord()boolread-onlyWhether it is a RECORD type
ObjectDictionaryGet(uint8_t sub)const ObjectEntry*read-onlyGet the entry by subindex; returns nullptr when not found
ObjectDictionaryGet(const std::string& key)const ObjectEntry*read-onlyGet the entry by name; returns nullptr when not found
ObjectDictionaryGetByPosition(int pos)const ObjectEntry*read-onlyGet the entry by position; returns nullptr when out of range
ObjectDictionaryContainsKey(uint8_t sub)boolread-onlyChecks whether the subindex exists
ObjectDictionaryContainsKey(const std::string& key)boolread-onlyChecks whether the name exists
ObjectDictionaryCopy()ObjectDictionaryread-onlyCreates a copy

ObjectEntry fields and methods:

CategoryField/methodTypeRead/writeDescription
ObjectEntryod_indexuint16_tread-onlyParent object index
ObjectEntrysub_indexuint8_tread-onlySubindex
ObjectEntrynamestd::stringread-onlyEntry name
ObjectEntrydata_typeuint16_tread-onlyData type (raw EcDataType value)
ObjectEntrybit_lengthuint16_tread-onlyBit length
ObjectEntryobj_accessuint16_tread-onlyAccess permission bits (see ObjAccessFlags)
ObjectEntryesi_default_textstd::stringread-onlyDisplay text of the ESI DefaultData
ObjectEntryByteLength()intread-onlyByte length = (bit_length + 7) / 8
ObjectEntryDatatype()uint16_tread-onlyData type (same value as data_type)
ObjectEntryCanRead()boolread-onlyWhether it is readable (decided from the access permission bits; the current master state is not considered)
ObjectEntryCanWrite()boolread-onlyWhether it is writable (decided from the access permission bits; the current master state is not considered)
ObjectEntryIsReadOnly()boolread-onlyWhether it is read-only (readable and not writable)
ObjectEntryCanWritePreOp()boolread-onlyWritable in PreOP
ObjectEntryCanWriteSafeOp()boolread-onlyWritable in SafeOP (including PreOP)
ObjectEntryCanWriteOp()boolread-onlyWritable in OP (true when writable in any phase)
ObjectEntryAccessDescription()std::stringread-onlyAccess description (for example 读写(PreOP,SafeOP,OP可写) (SDK output, = read/write (writable in PreOP, SafeOP, OP)) / 只读 (SDK output, = read-only) / 无权限 (SDK output, = no access))
ObjectEntryToString()std::stringread-onlyOf the form OD[0x6041:0] StatusWord

LoadOD()​

EcODList* LoadOD(bool preferEsi = false,
std::optional<std::string_view> esiXml = std::nullopt);

Load the object dictionary (the complete OD tree). This is the real entry point for OD loading; LoadODList() is an alias for it.

Parameters:

  • preferEsi (bool) — default false.
    • false: a full load over real SDO Information, including the subindex entries (OE) of every object.
    • true: try ESI first (0 mailbox traffic). The ESI text passed in or bound beforehand is parsed by the runtime library first (identical content is parsed only once), then the device is selected by this slave's real identity (SII VendorId / ProductCode / RevisionNo) inside that file's Device range (an exact Revision match wins, then the same vendor/model); the first unrelated device in the file is never substituted. If nothing matches, the call fails. When the ESI does not match, it falls back to SDO Information but takes the object list only and does not pull the subindex entries.
  • esiXml (std::optional<std::string_view>) — std::nullopt uses the XML cached by SetEsiXml(); an explicitly passed empty string_view means "do not use ESI this time"; non-empty text is the ESI to parse for this call.

Returns:

  • EcODList* — on success, a pointer to the internal cache (owned by CoE; the caller must not free / delete it); nullptr on failure. An empty table is not success.
  • The real reason for a failure is in last_od_error() / last_od_abort() / last_od_wkc() (they tell "no CoE / SDO Info not supported", "no ESI identity matched", "mailbox not up" and "SDK not ready" apart).
  • Cache reuse: a previous load is reused — when both the object list and the subindexes are complete it returns immediately; with the object list only it is also reused for 2 seconds, to avoid hammering the mailbox.
  • Concurrency: while a load is already in progress, a new call returns the current cache pointer directly (nullptr if not ready) and does not start a second load.
  • State gate: no state gate is required; in OP / SafeOp, preferEsi = false really pulls the subindexes and puts noticeable load on the mailbox, so for value refreshes use LoadODAsync from Asynchronous SDO instead.

LoadODList()​

EcODList* LoadODList(bool preferEsi = false,
std::optional<std::string_view> esiXml = std::nullopt);

An alias of LoadOD(); parameters, return value and failure semantics are identical. Both names are kept for compatibility with existing call sites.

LoadODListAsync()​

std::future<EcODList*> LoadODListAsync(bool preferEsi = false,
std::optional<std::string_view> esiXml = std::nullopt);

Asynchronous version: the parameters and failure semantics are as above, and .get() still yields the internal cache pointer (nullptr on failure). While a load is already in progress, a new call returns a future whose .get() == nullptr and does not start a second load.

Related queries:

bool       IsODListLoading() const;                        // Whether it is currently loading
EcODList* GetODList() const; // The loaded cache (nullptr when not loaded)
int Count() const; // Number of objects loaded (0 when nothing is loaded)
bool ContainsKey(uint16_t idx) const; // Whether that index is in the loaded cache
bool ContainsKey(const std::string& key) const; // Whether that name is in the loaded cache

ESI binding​

void             SetEsiXml(std::string_view xml);  // Bind the ESI XML (used by preferEsi)
bool HasEsiXml() const; // Whether it is bound
std::string_view EsiXml() const; // Get the bound XML
bool TryLoadFromEsi(std::string_view esiXml); // Read the ESI directly to build the OD table

TryLoadFromEsi(esiXml) returns false on failure; the caller should fall back to SDO Information. The text passed in is parsed by the runtime library (identical content is parsed only once), and the OD table is built only after the device has been selected by this slave's identity inside the Device ranges recorded in the document (an exact Revision match wins, then the same vendor/model; an unrelated device is never substituted). When nothing matches or parsing fails, the reason is written to last_od_error(). Default value data (esi_default_text) is inlined for the first 64 bytes only (a runtime library limit); default values longer than 64 bytes are shown as their first 64 bytes.

Traversal example​

auto& coe = master.GetSlave(1).GetCoE();

// Load the object dictionary list (really sends SDO Information)
// An empty dictionary is not success: a null pointer or Count()==0 is a failure (WKC=0 does not count as loaded)
EcODList* odList = coe.LoadODList();
if (!odList || odList->Count() == 0) {
printf("对象字典加载失败: %s (abort=0x%04X wkc=%u)\n", // Object dictionary load failed: %s (abort=0x%04X wkc=%u)
coe.last_od_error().c_str(), coe.last_od_abort(), coe.last_od_wkc());
return;
}
printf("对象数量: %d\n", odList->Count()); // Object count: %d

// Asynchronous load
auto future = coe.LoadODListAsync();
EcODList* result = future.get();
if (!result || result->Count() == 0) {
printf("异步加载失败\n"); // Asynchronous load failed
return;
}

Range-based for loops are supported:

auto* odList = coe.LoadODList();
if (!odList || odList->Count() == 0) {
printf("对象字典加载失败: %s (abort=0x%04X wkc=%u)\n", // Object dictionary load failed: %s (abort=0x%04X wkc=%u)
coe.last_od_error().c_str(), coe.last_od_abort(), coe.last_od_wkc());
return;
}
for (auto& od : *odList) {
printf("0x%04X %s (子索引数=%d)\n", od.index, od.name.c_str(), od.Count()); // 0x%04X %s (subindex count=%d)
for (auto& entry : od.entries) {
printf(" [%d] %s (类型=0x%04X, %d位, %s)\n", // [%d] %s (type=0x%04X, %d bits, %s)
entry.sub_index, entry.name.c_str(),
entry.data_type, entry.bit_length,
entry.AccessDescription().c_str());
}
}
Where esi_default_text comes from under ESI

Under the ESI path (LoadODList(preferEsi=true) / TryLoadFromEsi), esi_default_text is generated from the loaded ESI's default values, and the default data is inlined for the first 64 bytes only (a runtime library limit); default values longer than 64 bytes are shown as their first 64 bytes, not as the complete default value.

ObjAccessFlags​

ObjectEntry::obj_access holds the ETG.1000.6 access permission bits. Compare them against the bit constants directly, or use the static predicates.

Constants:

struct ObjAccessFlags {
static constexpr uint16_t NONE = 0x0000; // No permission
static constexpr uint16_t READ_PRE = 0x0001; // Readable in PreOp
static constexpr uint16_t READ_SAFE = 0x0002; // Readable in SafeOP
static constexpr uint16_t READ_OP = 0x0004; // Readable in OP
static constexpr uint16_t WRITE_PRE = 0x0008; // Writable in PreOp
static constexpr uint16_t WRITE_SAFE = 0x0010; // Writable in SafeOP
static constexpr uint16_t WRITE_OP = 0x0020; // Writable in OP
static constexpr uint16_t MAPPABLE = 0x0040; // Can be mapped into RxPDO
static constexpr uint16_t BACKUP = 0x0080; // Backup parameters
static constexpr uint16_t SETTINGS = 0x0100; // Configuration parameters
static constexpr uint16_t READ_ANY = READ_PRE | READ_SAFE | READ_OP; // 0x0007
static constexpr uint16_t WRITE_ANY = WRITE_PRE | WRITE_SAFE | WRITE_OP; // 0x0038
};

Static predicates (every parameter is uint16_t access):

static bool        CanRead (uint16_t access);            // (access & READ_ANY)  != 0
static bool CanWrite(uint16_t access); // (access & WRITE_ANY) != 0
static bool CanWritePreOp (uint16_t access); // (access & WRITE_PRE) != 0
static bool CanWriteSafeOp(uint16_t access); // (access & (WRITE_PRE | WRITE_SAFE)) != 0, includes PreOP
static bool CanWriteOp (uint16_t access); // (access & WRITE_ANY) != 0, true if writable at any point
static bool IsReadOnly (uint16_t access); // CanRead && !CanWrite
static std::string GetAccessDescription(uint16_t access);

Parameters:

  • access (uint16_t) — the raw bit value of ObjectEntry::obj_access.

Returns:

  • bool predicates — true = that permission bit holds. Only the permission bits are examined, not the current master state; for per-state decisions use ObjectEntry::CanWritePreOp() / CanWriteSafeOp() / CanWriteOp().
  • GetAccessDescription — a human-readable description, for example 读写(PreOP,SafeOP,OP可写) (SDK output, = read/write (writable in PreOP, SafeOP, OP)) / 只读 (SDK output, = read-only) / 无权限 (SDK output, = no access).

Example:

const ObjectEntry* e = od->Get(0);
if (e && ObjAccessFlags::CanRead(e->obj_access))
printf("%s -> %s\n", e->ToString().c_str(), e->AccessDescription().c_str());

Do not compare access bits by hand: use ObjectEntry::CanRead() / CanWrite() / CanWriteOp() and the like, or the ObjAccessFlags static functions above.

Single object / single entry descriptions​

std::vector<ObjectDictionary>     LoadObjectDictionary();                  // Really sends SDO Information every time; returns an empty vector on failure
std::optional<ObjectDictionary> GetObjectDescription(uint16_t index); // Object-level fields only, entries is empty
std::optional<ObjectEntry> GetEntryDescription(uint16_t index, uint8_t subindex);

All three fetch live and do not write the LoadODList() cache; on failure they return empty / std::nullopt, and the real reason (including the device abort code and WKC) is in last_od_error() / last_od_abort() / last_od_wkc().

Read and write by entry​

std::vector<uint8_t> ReadEntryBytes (uint16_t odIndex, uint8_t subIndex) const;   // = SDORead
bool WriteEntryBytes(uint16_t odIndex, uint8_t subIndex,
const std::vector<uint8_t>& data) const; // = SDOWrite

std::map<uint8_t, std::vector<uint8_t>> ReadAll(uint16_t odIndex) const;

ReadAll reads every subindex in the loaded OD's entries and returns 子索引 → 数据. Both read failures and empty-string successes are skipped (only items with !data.empty() are collected); when you need to tell them apart, read entry by entry with SDOReadDetail. When odIndex is not in the cache it returns an empty map.

Complete Access data splitting​

// Preferred: the version with slave context (looks up the loaded ESI layout by this slave's measured identity)
std::map<uint8_t, std::vector<uint8_t>>
ParseCompleteAccessData(uint16_t index,
const std::vector<uint8_t>& ca_data,
uint8_t start_subindex = 0) const;

// Compatibility version: pure OD version, with no master / slave context
static std::map<uint8_t, std::vector<uint8_t>>
ParseCompleteAccessData(const std::vector<uint8_t>& ca_data,
const ObjectDictionary& od);

Split the whole-object bytes read by SDORead(index, 0, true) into 子索引 → 字节. With a slave context, use the member version that takes index: it looks the layout up in the loaded ESI object dictionary by this slave's measured identity, and returns an empty map when it cannot find one (the layout is not guessed). The static version is a compatibility entry point with the same rules.

Parameters:

  • index (uint16_t) — CoE object index, for example 0x1C12 (member version only).
  • ca_data — the raw bytes read by Complete Access, typed const std::vector<uint8_t>&.
  • start_subindex (uint8_t) — 0 = the blob starts with SubIndex 0 (2 bytes); 1 = it starts at SubIndex 1. Default 0.
  • od (const ObjectDictionary&) — the OD entry of the matching object; its OE list must be loaded (static version only).

Returns:

  • std::map<uint8_t, std::vector<uint8_t>> — 实际子索引号 → 字节.
  • Splitting rules (ETG.1000.6 §5.6.2 / ETG.1020 §14.2): SubIndex 0 is always taken as 2 bytes; BOOLEAN and BIT1..BIT8 are packed contiguously as bit types, and the next non-bit type starts on a new byte boundary; when a bit type does not start on a byte boundary, the bytes actually covered are returned (it may span two bytes) — if you need the value, start the bit width at bit_offset % 8.
  • When an empty map is returned: ca_data is empty, od.entries is empty (static version), the SDK is not ready, or the layout cannot be found / the type is unknown / the data is truncated. An empty map does not mean the object has no subindexes; check d.ok and whether ca_data is non-empty first.

Example:

auto* odList = coe.LoadODList();
auto* od = odList ? odList->Get(0x1C13) : nullptr;
if (od) {
SDOReadDetail d;
auto raw = coe.SDORead(0x1C13, 0, d, true); // Complete Access + details
if (d.ok) {
for (auto& kv : coe.ParseCompleteAccessData(0x1C13, raw, 0))
printf(" sub %u: %zu 字节\n", kv.first, kv.second.size()); // sub %u: %zu bytes
}
}

Batch SDO reads​

ReadMultiple()​

std::vector<SDOReadResult> ReadMultiple(const std::vector<SDOReadEntry>& entries) const;

Batch SDO read — read several objects in one call. Synchronous; the entries are read one after another. success is derived from !data.empty(), so an empty string read successfully is also judged a failure; when you need exact success/failure, read entry by entry with SDOReadDetail.

Parameters:

  • entries (const std::vector<SDOReadEntry>&) — the list of (index, subindex) pairs to read.
  • const member function; the same thread-safety constraint as SDORead().

Returns:

  • std::vector<SDOReadResult> — in the same order as entries, one result per item.
  • A failed item does not stop the following entries; when success is false, data is empty.
  • The order is synchronous, one entry at a time on the bus, so the time grows linearly with the number of entries.

Related structures:

struct SDOReadEntry {
uint16_t index; // Object index
uint8_t subindex; // Subindex
};

struct SDOReadResult {
uint16_t index; // Object index
uint8_t subindex; // Subindex
bool success; // Whether it succeeded
std::vector<uint8_t> data; // The data read (empty on failure)
};

Example:

auto& coe = master.GetSlave(1).GetCoE();

// Batch-read several objects
std::vector<CoE::SDOReadEntry> entries = {
{0x1018, 1}, // VendorID
{0x1018, 2}, // ProductCode
{0x6041, 0}, // StatusWord
{0x6064, 0}, // ActualPosition
};

auto results = coe.ReadMultiple(entries);
for (auto& r : results) {
if (r.success)
printf("0x%04X:%02X 读取成功 (%zu 字节)\n", r.index, r.subindex, r.data.size()); // 0x%04X:%02X read OK (%zu bytes)
else
printf("0x%04X:%02X 读取失败\n", r.index, r.subindex); // 0x%04X:%02X read failed
}

ReadMultipleAsync()​

std::future<std::vector<SDOReadResult>> ReadMultipleAsync(
const std::vector<SDOReadEntry>& entries) const;

Asynchronous version of the batch SDO read; it runs on a background thread and does not block the calling thread.

Does not go through the master serialization gate

ReadMultipleAsync only starts another thread that runs the synchronous ReadMultiple; it does not go through the master serialization gate, so it hits the mailbox at the same time as SDO calls / state changes on other threads. For guaranteed serialization use SDOBatchReadAsync from Asynchronous SDO.

Example:

auto future = coe.ReadMultipleAsync(entries);
// ... do other work ...
auto results = future.get(); // Wait for completion

Asynchronous SDO​

The asynchronous versions are free functions in the darra::ethercat namespace (not CoE members) and take the parent EtherCATMaster& plus the slave index explicitly. They run on a background thread queued through the parent master's serialization gate, strictly serial with other SDO calls / Build / SetState on the same master, so they never hit the mailbox concurrently. The master must stay alive until future.get() returns.

// Read
std::future<std::vector<uint8_t>> SDOReadAsync(
EtherCATMaster& master, uint16_t slaveIndex,
uint16_t index, uint8_t subindex, bool completeAccess = false,
CancelToken token = CancelToken{});

// Read (Slave& convenience overload)
std::future<std::vector<uint8_t>> SDOReadAsync(
EtherCATMaster& master, const darra::Slave& slave,
uint16_t index, uint8_t subindex, bool completeAccess = false,
CancelToken token = CancelToken{});

// Write
std::future<bool> SDOWriteAsync(
EtherCATMaster& master, uint16_t slaveIndex,
uint16_t index, uint8_t subindex, std::vector<uint8_t> data,
bool completeAccess = false, CancelToken token = CancelToken{});

// Write (Slave& convenience overload)
std::future<bool> SDOWriteAsync(
EtherCATMaster& master, const darra::Slave& slave,
uint16_t index, uint8_t subindex, std::vector<uint8_t> data,
bool completeAccess = false, CancelToken token = CancelToken{});

Failure semantics:

  • SDOReadAsync(...).get() returns an empty vector on failure — an empty vector cannot tell "empty string read successfully" from "failure"; to judge success honestly use SDOReadDetailAsync. Access denied does not go through the empty vector: when the device returns 0x06010000 / 0x06010001, the darra::CoEAccessDeniedException thrown on the background thread is rethrown unchanged at .get(), with the same semantics as the synchronous version (the same applies to the detail variant SDOReadDetailAsync).
  • SDOWriteAsync(...).get() returns false on failure; when data is empty it returns false directly without sending a request. When the device returns 0x06010000 / 0x06010002, .get() throws darra::CoEAccessDeniedException (the same applies to the detail variant SDOWriteDetailAsync).
  • On cancellation (CancelToken) .get() throws OperationCanceled.

Versions with details:

std::future<SDOReadDetail> SDOReadDetailAsync(
EtherCATMaster& master, uint16_t slaveIndex,
uint16_t index, uint8_t subindex, bool completeAccess = false,
CancelToken token = CancelToken{});

std::future<SDOWriteDetail> SDOWriteDetailAsync(
EtherCATMaster& master, uint16_t slaveIndex,
uint16_t index, uint8_t subindex, std::vector<uint8_t> data,
bool completeAccess = false, CancelToken token = CancelToken{});

Both also have const darra::Slave& overloads. An empty string read successfully = ok=true + empty data + abort_code=0; a failure = ok=false, with abort_code / wkc as-is.

Cancellation token: a default-constructed CancelToken never cancels; when cancellation is needed, use CancelToken::Create() and call Cancel() to cancel.

Minimal example:

#include "ethercat.hpp"
using namespace darra;
using namespace darra::ethercat;

auto token = CancelToken::Create();
auto fut = SDOReadAsync(master, 1, 0x6041, 0, false, token);
// ... do other work meanwhile, without blocking ...
auto data = fut.get(); // Cancellation throws OperationCanceled
if (data.size() >= 2) {
uint16_t statusWord;
std::memcpy(&statusWord, data.data(), 2);
}

// Use the detailed version when you need an honest pass/fail
auto d = SDOReadDetailAsync(master, 1, 0x6041, 0).get();
if (!d.ok) printf("SDO 失败, abort=0x%08X\n", d.abort_code); // SDO failed, abort=0x%08X

Batch / whole-table asynchronous calls:

CategoryPropertyTypeRead/writeDescription
BatchSDOBatchAsync(master, slaveIndex, SdoRequest list, CancelToken)std::future<SdoBatchResult>read-writeMixed reads and writes run inside one gate; a failed item does not stop the following ones
BatchSDOBatchReadAsync(master, slaveIndex, SdoAddr list, CancelToken)std::future<SdoBatchResult>read-onlyBatch read
BatchSDOBatchWriteAsync(master, slaveIndex, SdoWriteItem list, CancelToken)std::future<SdoBatchResult>write-onlyBatch write; items with empty data are recorded as failures
Whole tableLoadODAsync(master, slaveIndex, CancelToken)std::future<LoadODResult>read-onlyPulls the OD over real SDO Information in OP, without changing state

The first three also have const darra::Slave& overloads. Related structures:

enum class SdoKind : uint8_t { Read = 0, Write = 1 };

struct SdoRequest {
SdoKind kind = SdoKind::Read;
uint16_t index = 0;
uint8_t subindex = 0;
bool complete_access = false;
std::vector<uint8_t> data; // Write only
};

struct SdoAddr { uint16_t index; uint8_t subindex; bool complete_access; };
struct SdoWriteItem { uint16_t index; uint8_t subindex; std::vector<uint8_t> data; bool complete_access; };

struct SdoItemResult {
bool ok; SdoKind kind; uint16_t index; uint8_t subindex;
std::vector<uint8_t> data; uint32_t abort_code; int wkc;
};

struct SdoBatchResult {
bool all_ok; int succeeded; int failed;
std::vector<SdoItemResult> items; std::string reason;
};

struct LoadODResult {
bool ok; EcODList list; EcState master_state; EcState slave_state;
int object_count; bool loaded_entries;
uint16_t abort_code; // SDO Information device abort code (0 = the device sent no abort code, which does not mean success)
uint16_t wkc; // Result of the innermost mailbox transaction (1=success, 0=failure/not executed); the worst is taken across transactions
std::string reason;
};
  • SdoItemResult::abort_code / LoadODResult::abort_code are both passed through as-is: 0 = the device returned no abort code (invalid parameter / never sent on the bus / communication timeout) and does not mean success; judge success by ok only. In a batch write, an item whose data is empty is never sent on the bus at all, so its abort_code stays 0.
  • LoadODResult::wkc takes the worst result over multiple transactions (the OD list plus per-subindex descriptions): when the list succeeds but one subentry description fails, it records 0 and keeps the first real abort code.
  • SdoBatchResult::all_ok is true only when every item succeeded; the failure reason is in reason (an empty batch / a batch containing a failed item is never true).
  • LoadODResult::ok is true only when objects with names were really obtained; an empty table, a fake index table (most object names of the form 0x....) or a slave mailbox that is not up are all false, with the reason in reason. In OP / SafeOp, loaded_entries=false (the subindexes are not pulled, to avoid crowding SM2); for value refreshes call SDOBatchReadAsync separately.

Device profile detection​

GetDeviceProfile()​

uint16_t GetDeviceProfile() const;

Read the device profile number.

Parameters:

  • None. const member function.

Returns:

  • uint16_t — the lower 16 bits of object 0x1000 (Device Type).
  • When 0 is returned: the read of 0x1000 failed, the data is shorter than 4 bytes, or no 32-bit value can be extracted. 0 is not a valid profile number, so it can be treated directly as "unavailable".

IsCiA402() / IsCiA401()​

bool IsCiA402() const;   // Whether it is a CiA 402 servo drive
bool IsCiA401() const; // Whether it is a CiA 401 I/O module

Parameters:

  • None.

Returns:

  • bool — true = GetDeviceProfile() equals 402 / 401 respectively. When the profile is unavailable (returns 0) both are false.

Example:

uint16_t profile = coe.GetDeviceProfile();
if (coe.IsCiA402()) printf("CiA 402 伺服\n"); // CiA 402 servo
else if (coe.IsCiA401()) printf("CiA 401 I/O\n");
else printf("其它 profile = %u\n", profile); // Other profile = %u

Emergency message history​

CoE offers two sets of interfaces for reading EMCY, and both read the same data:

  • CoE::GetEmergencyHistory() / ClearEmergencyHistory() — project every record into a CiA 301 8-byte EMCY frame and return it.
  • darra::ethercat::slave_emcy free functions — return the structured records directly (including timestamp / slave index / error register).

Both read the master-side live receive ring (at most 256 records per slave, in time order, oldest → newest); they trigger no SDO traffic and do not read object 0x1003 in the slave's object dictionary.

GetEmergencyHistory()​

std::vector<std::vector<uint8_t>> GetEmergencyHistory() const;

Return the EMCY records currently in the ring, each one an 8-byte raw payload.

Parameters:

  • None. Acts on the (master, slave) pair the current CoE instance belongs to.

Returns:

  • std::vector<std::vector<uint8_t>> — 8 bytes per item: [0..1] Error Code (little-endian), [2] Error Register, [3..7] vendor-specific bytes (matching the EMCY payload of CiA 301 DS301 §7.2.8.1).
  • Returned in time order (oldest → newest), at most 256 records per slave.
  • An empty vector is ambiguous: "nothing was read this time" and "there really are no records" return the same thing, so do not conclude from it that "an emergency message was never reported". To tell them apart, check slave_emcy::emcy_count() first.
  • const member function; it does not change the ring contents.

Example:

for (auto& frame : coe.GetEmergencyHistory()) {
if (frame.size() >= 3) {
uint16_t err_code;
std::memcpy(&err_code, frame.data(), 2);
printf("EMCY 错误码=0x%04X 寄存器=0x%02X\n", err_code, frame[2]); // EMCY error code=0x%04X register=0x%02X
}
}

ClearEmergencyHistory()​

bool ClearEmergencyHistory() const;

Clear this slave's EMCY receive ring.

Parameters:

  • None.

Returns:

  • bool — always returns true, which only means "the clear request was issued". The underlying clear has no failure return value, so there is no decidable success / failure signal here.
  • It does not mean object 0x1003 in the slave's object dictionary was cleared as well; this interface does not touch the slave side.

Example:

coe.ClearEmergencyHistory();   // Clear this station's receive ring only

slave_emcy free functions​

namespace darra::ethercat::slave_emcy {
int emcy_count(dll_t& dll, uint16_t mi, uint16_t si);
std::vector<ec_emcy_record_t>
emcy_history(dll_t& dll, uint16_t mi, uint16_t si);
void clear_emcy(dll_t& dll, uint16_t mi, uint16_t si);
}

Read the same live EMCY ring buffer and return structured records. No extra SDO traffic is generated.

Parameters:

  • dll (dll_t&) — the SDK context (CoE::Dll() can be used directly).
  • mi (uint16_t) — master number (CoE::MasterIndex()).
  • si (uint16_t) — slave index (CoE::SlaveIndex()).

Returns:

  • emcy_count (int) — the number of records currently in the ring (0..256).
  • emcy_history (std::vector<ec_emcy_record_t>) — the record array, in time order (oldest → newest), at most 256 records per slave. When an empty vector is returned, "nothing was read this time" and "there really are no records" are the same outcome, so it cannot be taken as "an emergency message was never reported".
  • clear_emcy (void) — clears the ring of that slave.

ec_emcy_record_t fields:

  • timestamp_ms (uint32_t) — capture timestamp (milliseconds)
  • slave_index (uint16_t) — slave index
  • error_code (uint16_t) — EMCY error code
  • error_register (uint8_t) — error register
  • data (uint8_t[5]) — vendor-specific bytes

Example (slave_emcy — structured records):

using namespace darra::ethercat;
int n = slave_emcy::emcy_count(dll, mi, si);
printf("EMCY 记录数: %d\n", n); // EMCY record count: %d
auto records = slave_emcy::emcy_history(dll, mi, si);
for (auto& r : records) {
printf("EMCY t=%u ms slave=%u code=0x%04X reg=0x%02X\n",
r.timestamp_ms, r.slave_index, r.error_code, r.error_register);
}
slave_emcy::clear_emcy(dll, mi, si);

EcDataType enumeration​

EtherCAT data type identifiers used in the CoE object dictionary, declared as enum class EcDataType : uint16_t. ObjectDictionary::datatype / ObjectEntry::data_type hold its raw value.

CategoryNameValueRead/writeDescription
UntypedNONE0x0000read-onlyUntyped
BooleanBOOLEAN0x0001read-onlyBoolean (bool)
SignedINTEGER80x0002read-onlySigned 8-bit (int8_t)
SignedINTEGER160x0003read-onlySigned 16-bit (int16_t)
SignedINTEGER320x0004read-onlySigned 32-bit (int32_t)
UnsignedUNSIGNED80x0005read-onlyUnsigned 8-bit (uint8_t)
UnsignedUNSIGNED160x0006read-onlyUnsigned 16-bit (uint16_t)
UnsignedUNSIGNED320x0007read-onlyUnsigned 32-bit (uint32_t)
Floating pointREAL320x0008read-onlySingle-precision floating point (float)
StringVISIBLE_STRING0x0009read-onlyVisible string (std::string)
StringOCTET_STRING0x000Aread-onlyByte array (std::vector<uint8_t>)
StringUNICODE_STRING0x000Bread-onlyUnicode string (std::string)
TimeTIME_OF_DAY0x000Cread-onlyTime (as raw bytes)
TimeTIME_DIFF0x000Dread-onlyTime difference (as raw bytes)
OtherDOMAIN0x000Fread-onlyRaw data (std::vector<uint8_t>)
SignedINTEGER240x0010read-onlySigned 24-bit (as raw bytes)
Floating pointREAL640x0011read-onlyDouble-precision floating point (double)
SignedINTEGER400x0012read-onlySigned 40-bit (as raw bytes)
SignedINTEGER480x0013read-onlySigned 48-bit (as raw bytes)
SignedINTEGER560x0014read-onlySigned 56-bit (as raw bytes)
SignedINTEGER640x0015read-onlySigned 64-bit (int64_t)
UnsignedUNSIGNED240x0016read-onlyUnsigned 24-bit (as raw bytes)
UnsignedUNSIGNED400x0018read-onlyUnsigned 40-bit (as raw bytes)
UnsignedUNSIGNED480x0019read-onlyUnsigned 48-bit (as raw bytes)
UnsignedUNSIGNED560x001Aread-onlyUnsigned 56-bit (as raw bytes)
UnsignedUNSIGNED640x001Bread-onlyUnsigned 64-bit (uint64_t)
BitBIT10x0030read-only1 bit
BitBIT20x0031read-only2 bit
BitBIT30x0032read-only3 bit
BitBIT40x0033read-only4 bit
BitBIT50x0034read-only5 bit
BitBIT60x0035read-only6 bit
BitBIT70x0036read-only7 bit
BitBIT80x0037read-only8 bit
UnknownUNKNOWN0xFFFFread-onlyA code that cannot be parsed / is not recognised (a different thing from NONE's "untyped")

Getting the type name text:

const char* darra::ethercat::statics::data_type_description(uint16_t dt);  // Protocol's official name
const char* darra::ethercat::statics::data_type_short_name (uint16_t dt); // Display alias

Parameters:

  • dt (uint16_t) — the raw value of ObjectEntry::data_type.

Returns:

  • data_type_description — the canonical upper-case name (such as INT8 / UINT16 / REAL32 / VISIBLE_STRING / BIT1 / UNKNOWN). When the type cannot be determined it returns an Unknown text that includes the raw value, not the enum name UNKNOWN.
  • data_type_short_name — a short display alias (int8 / float / string / byte[] / bool / double), for the UI only; it takes no part in protocol decisions, bit-width calculation, PDO encoding or decoding, or cross-language semantic comparison. The alias table lists common types only; types not listed / unknown fall back to the canonical name from data_type_description.
  • The INTEGER8 / REAL32 / VISIBLE_STRING in the table above are C++ enum member names, not the strings returned by data_type_description; do not mix the two.

Example:

for (auto& entry : od->entries)
printf("[%u] %s 类型=%s (0x%04X) %d 位\n", // [%u] %s type=%s (0x%04X) %d bits
entry.sub_index, entry.name.c_str(),
darra::ethercat::statics::data_type_description(entry.data_type),
entry.data_type, entry.bit_length);

Complete example​

#include "ethercat.hpp"
using namespace darra;

int main() {
darra::ethercat::dll_t dll; // SDK context (RAII)
EtherCATMaster master(dll);
if (!master.SetNetwork("\\Device\\NPF_{...}").Build())
return 1;
if (!master.SetState(EcState::OP) || !master.Start())
return 1;

auto& coe = master.GetSlave(1).GetCoE();

// Read the Identity Object
auto vid = coe.SDOReadU32(0x1018, 1);
auto pid = coe.SDOReadU32(0x1018, 2);
if (vid && pid)
printf("VID=0x%08X PID=0x%08X\n", *vid, *pid);

// Read the StatusWord
auto sw = coe.SDOReadU16(0x6041, 0);
if (sw) printf("StatusWord: 0x%04X\n", *sw);

// Write the ControlWord
if (!coe.SDOWriteU16(0x6040, 0, 0x0006))
return 1;

// Set the mode of operation to CSP
if (!coe.SDOWriteU8(0x6060, 0, 8))
return 1;

// Read the PDO mapping in Complete Access mode
auto pdo_map = coe.SDORead(0x1C12, 0, true);
if (!pdo_map.empty())
printf("PDO 映射数据: %zu 字节\n", pdo_map.size()); // PDO mapping data: %zu bytes

// Read the device name
auto name = coe.SDOReadString(0x1008, 0);
if (name) printf("设备名称: %s\n", name->c_str()); // Device name: %s

return 0;
}

Diagnostic messages (0x10F3, ETG.1510 / ETG.1020 §16)​

A slave keeps a diagnostic message buffer under object 0x10F3. There are two ways to use it (do not mix them):

  • ReadDiagnosticMessages() — pulls up to 20 messages from the current buffer in one call (an SDO read per subindex); new and old are not distinguished, which suits offline "export all diagnostics" scenarios.
  • The lightweight polling set PollHasNewDiagnostic() / ReadDiagnosticMeta() / ReadDiagnosticMessage() / AcknowledgeDiagnostic() — first check whether there is a new message, then fetch the metadata, fetch one message by number, and acknowledge it after handling. This suits 24/7 live monitoring and avoids repeated reads and buffer overflow.

Once you use the lightweight API, AcknowledgeDiagnostic() advances the slave's newestAcknowledged; do not call ReadDiagnosticMessages() again to pull repeatedly. When the current runtime does not support the lightweight polling interface, every lightweight call returns false / nullopt / -1 quietly without throwing; the failure reason is available from LastDiagAbortCode().

ReadDiagnosticMessages()​

std::vector<DiagnosticMessage> ReadDiagnosticMessages() const;

Read the 0x10F3 diagnostic history and return the list of DiagnosticMessage (at most 20 entries). Returns an empty vector when the slave does not support it or has no messages yet.

Parameters:

  • None. const member function; it reads the count from 0x10F3:00 and then reads each entry over SDO.

Returns:

  • std::vector<DiagnosticMessage> — at most 20 entries; an empty vector when the slave does not support it or has no messages yet.
  • It shares the mailbox with other SDO reads and writes; do not call it from a high-rate PDO thread.

Related structures:

struct DiagnosticMessage {
uint8_t sub_index; // Subindex
uint32_t diag_code; // Diagnostic code (ETG.1020 Table 65)
uint16_t flags; // Flag bits
uint16_t text_index; // Text index
std::vector<uint8_t> raw_data; // Raw bytes (including the header above + parameters)
};

Example:

auto& coe = master.GetSlave(1).GetCoE();
auto messages = coe.ReadDiagnosticMessages();
for (auto& msg : messages) {
printf("[Sub=%u] 诊断码: 0x%08X, Flags: 0x%04X, TextIdx: 0x%04X\n", // [Sub=%u] diagnostic code: 0x%08X, Flags: 0x%04X, TextIdx: 0x%04X
msg.sub_index, msg.diag_code, msg.flags, msg.text_index);
}
Standard basis

ETG.1020 §16 diagnostic history object; CANopen CiA 301 DS301 §7.5.3.

DiagMeta structure​

struct DiagMeta {
uint8_t maxMessages; // 0x10F3:01 maximum number of messages in the buffer
uint8_t newestMessage; // 0x10F3:02 subindex of the newest message; 0 = no message
uint8_t newestAcknowledged; // 0x10F3:03 newest acknowledged subindex (the spec keeps it 0 in Overwrite mode)
uint16_t flags; // 0x10F3:05 bit4 = 0 Overwrite / 1 Acknowledge, bit5 = Overrun

bool isAcknowledgeMode() const; // Bit4=1 is Acknowledge mode, false is Overwrite mode
bool hasOverrun() const; // Bit5 (the ring buffer has overwritten an unread message)
};
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 newestAcknowledged = 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 newestMessage != newestAcknowledged. In that mode, whether an unread message exists can only be answered by 0x10F3:04 NewAvailable (PollHasNewDiagnostic()). Only in Acknowledge mode does newestMessage != newestAcknowledged indicate unacknowledged messages.

Accessor: this language provides DiagMeta::isAcknowledgeMode() (equivalent to (flags & 0x0010) != 0; 0 = Overwrite, 1 = Acknowledge) and DiagMeta::hasOverrun() ((flags & 0x0020) != 0), so no manual bit mask is needed.

PollHasNewDiagnostic()​

DiagnosticPollResult PollHasNewDiagnostic();

Lightweight polling of the 0x10F3:04 NewAvailable flag (ETG.1020 §16.2); it does not read the full history, so it suits periodic checks.

Returns:

  • DiagnosticPollResult::HasNew — there is a new diagnostic message
  • DiagnosticPollResult::None — no new message (including the normalized result for slaves that do not support 0x10F3)
  • DiagnosticPollResult::Failed — communication failure (entry point unavailable / native returned -1 / unexpected value). "Could not ask" is not "none"; do not treat it as no message

ReadDiagnosticMeta()​

std::optional<DiagMeta> ReadDiagnosticMeta();

Read the 0x10F3:01..05 metadata.

Parameters:

  • None.

Returns:

  • std::optional<DiagMeta> — the metadata on success; std::nullopt on failure (including an unsupported runtime), with the specific error in LastDiagAbortCode().

ReadDiagnosticMessage()​

std::vector<uint8_t> ReadDiagnosticMessage(uint8_t msgIdx, size_t bufSize = 1024);

Read the bytes of the diagnostic message with the given number.

Parameters:

  • msgIdx (uint8_t) — message subindex, usually 6..255 (see DiagMeta::newestMessage).
  • bufSize (size_t) — receive buffer capacity, default 1024 (the value recommended by ETG.1020).

Returns:

  • std::vector<uint8_t> — the message bytes trimmed to their actual length; an empty vector on failure, with the specific error in LastDiagAbortCode().
  • The first 8 bytes of the message body are a header: [0..3] diagnostic code, [4..5] flags, [6..7] text index; the parameters follow.

AcknowledgeDiagnostic()​

bool AcknowledgeDiagnostic(uint8_t msgIdx);

Write msgIdx to 0x10F3:03. In Acknowledge mode (DiagMeta::isAcknowledgeMode() = true) the slave advances its acknowledged position accordingly and clears that message and everything before it; in Overwrite mode this write carries no decision weight (the slave keeps newestAcknowledged = 0 by specification).

Parameters:

  • msgIdx (uint8_t) — the number of the message that has been handled.

Returns:

  • bool — true = acknowledgement succeeded; false = the communication failed or the runtime does not support it, with the specific error in LastDiagAbortCode().

LastDiagAbortCode()​

uint32_t LastDiagAbortCode() const;

Parameters:

  • None. const member function.

Returns:

  • uint32_t — the SDO Abort Code of the most recent call to the 4 diagnostic APIs above; 0 means no error (or the device returned no abort code).

End-to-end example​

#include <thread>
#include <chrono>
#include <cstring>

auto& coe = master.GetSlave(1).GetCoE();

while (running) {
const DiagnosticPollResult poll = coe.PollHasNewDiagnostic();
if (poll == DiagnosticPollResult::Failed) {
printf("轮询失败 (通信异常), 稍后重试\n"); // Failed != no new message
std::this_thread::sleep_for(std::chrono::milliseconds(100));
continue;
}
if (poll == DiagnosticPollResult::None) {
std::this_thread::sleep_for(std::chrono::milliseconds(100));
continue;
}

auto meta = coe.ReadDiagnosticMeta();
if (!meta) {
printf("读元数据失败, AbortCode=0x%08X\n", coe.LastDiagAbortCode()); // Reading the metadata failed, AbortCode=0x%08X
std::this_thread::sleep_for(std::chrono::milliseconds(100));
continue;
}

if (meta->hasOverrun()) {
printf("[警告] 诊断历史溢出, 部分旧消息丢失\n"); // [Warning] diagnostic history overflow, some old messages lost
}

if (meta->newestMessage < 6) { // 0 = no message ever
std::this_thread::sleep_for(std::chrono::milliseconds(100));
continue;
}

// In Overwrite mode newestAcknowledged is always 0 (the spec value) and must not be treated as a read position;
// Only Acknowledge mode starts from acked+1
const uint8_t first = meta->isAcknowledgeMode()
? static_cast<uint8_t>(meta->newestAcknowledged + 1)
: static_cast<uint8_t>(6);
for (uint8_t i = first;
i != static_cast<uint8_t>(meta->newestMessage + 1); ++i) {
auto bytes = coe.ReadDiagnosticMessage(i);
if (bytes.size() < 8) continue;

uint32_t diagCode;
uint16_t flags, textIdx;
std::memcpy(&diagCode, bytes.data(), 4);
std::memcpy(&flags, bytes.data() + 4, 2);
std::memcpy(&textIdx, bytes.data() + 6, 2);

printf("Diag[%u] code=0x%08X flags=0x%04X textIdx=0x%04X\n",
i, diagCode, flags, textIdx);

coe.AcknowledgeDiagnostic(i);
}
}
Choosing between this and ReadDiagnosticMessages()
  • ReadDiagnosticMessages() — pulls up to 20 messages at once, new and old are not distinguished, suits offline export
  • The 4 lightweight APIs — incremental polling plus per-message acknowledgement, suits 24/7 live monitoring and avoids repeated reads and buffer overflow
  • Do not mix them. Once you use the lightweight API, AcknowledgeDiagnostic() advances the slave's newestAcknowledged; do not call ReadDiagnosticMessages() again to pull repeatedly
Reference

ETG.1020 §16 Table 65; ETG.1510 §6.2 Diagnosis history.