CoE (CANopen over EtherCAT)
Get the CoE& reference through slave.GetCoE(). When the slave does not support CoE, the related methods return an empty value or false.
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;
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 example0x6041.subindex(uint8_t) — subindex, default0.completeAccess(bool) — defaultfalse(read only the given subindex); passtruefor a Complete Access read of the whole object. In that casesubindexmay only be0or1(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).constmember function: it does not change the OD list cache held byCoE, but it does refreshlast_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) or0x06010001(reading a write-only object) it throwsdarra::CoEAccessDeniedExceptionand 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 withtry/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/0x06090012and other codes the slave explicitly rejects and that would not succeed on retry) is recorded in the negative cache per(从站, index, subindex). LaterSDOReadcalls 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, andlast_sdo_error()replays the cached abort. CallResetNotPresentCache()after hot-plug / firmware update / topology change.completeAccess = trueandSDOWritedo 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);
- Access denied (
0x06010000, read0x06010001) is not an empty vector — it throwsdarra::CoEAccessDeniedException(see CoE access denied exception) - Do not
memcpythe return value straight into auint32_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 asSDORead(); withcompleteAccess = true,subindexmay only be0or1.detail(SDOReadDetail&) — out parameter, filled in the orderok/data/abort_code/wkc(the same order as the struct declaration).completeAccess(bool) — defaultfalse.
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.datais 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-layerSDOProtocolTimeout (0x05040000)is reported and0x08000000is never fabricated (it is0on an invalid parameter or when nothing was sent on the bus). Judge success byokonly; never treatabort_code == 0as success.last_sdo_error()uses the same convention asabort_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 fromok.- Length cap: response data over 64 KB is returned as a failure (
ok=false,dataempty); 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
CoEinstance 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 ofResetNotPresentCache(): 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, typedconst uint8_t*(together withdataLen) orconst std::vector<uint8_t>&(the length isdata.size()).dataLen(int) — byte count for the pointer overload.completeAccess(bool) — defaultfalse;true= Complete Access write of the whole object, in which casesubindexmay likewise only be0or1; when out of range the call fails immediately without sending a request (returnsfalse).constmember function; an abort from a failed write is not written to the NotPresent negative cache (onlySDOReadwrites it).
Returns:
bool—true= write succeeded;false= failure.- When
falseis returned (any one of these fails the call):datais a null pointer,dataLen <= 0, or an emptystd::vector(all three fail immediately without a bus request,last_sdo_error()=GeneralError);completeAccess = trueandsubindexis not0/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) or0x06010002(writing a read-only object) it throwsdarra::CoEAccessDeniedExceptionand does not returnfalse; every other failure still returnsfalse. - State gate: the write permission depends on the object's own
obj_accessbits (seeObjAccessFlags); prejudge it withObjectEntry::CanWritePreOp()/CanWriteSafeOp()/CanWriteOp(). When the permission does not match, the slave returns an abort such asWriteReadOnlyError (0x06010002)/SubindexWriteError (0x06010003).0x06010002throws as access denied, while0x06010003is still reported by returningfalse. - 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 asSDOWrite().detail(SDOWriteDetail&) — out parameter, filled in the orderok/abort_code/wkc(the same order as the struct declaration).completeAccess(bool) — defaultfalse.
Returns:
bool—true= success, the same value asdetail.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 reportsSDOProtocolTimeout (0x05040000); an invalid parameter or a call not dispatched to the bus stays0. Success is judged fromokalone.detail.wkc(int) — the working counter; when the runtime library is unavailable it is synthesised as 1/0 fromok.
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.
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, default0.val— the value to write, its type matching the method name; numeric values are packed little-endian per ETG.- For reads, the
std::optionalholds a value only when the data is long enough.
Returns:
- Read
std::optional<T>—std::nullopton failure; insufficient data length (for example aU16read that returned only 1 byte) also returnsstd::nullopt. - Write
bool—trueon success,falseon failure (the value could not be put into the buffer / the underlyingSDOWritefailed). - The failure reason always comes from
last_sdo_error(), with the same semantics asSDORead()/SDOWrite(). - Empty-data ambiguity:
SDOReadStringalso returnsstd::nulloptfor empty data (including an empty string read successfully), which cannot be told apart from a read failure; useSDOReadDetailwhen you need to tell them apart.
| Category | Method | Type | Read/write | Description |
|---|---|---|---|---|
| Typed read | SDOReadU8 / U16 / U32 / U64 | std::optional<integer> | read-only | Unsigned 8 / 16 / 32 / 64 bit |
| Typed read | SDOReadI16 / I32 | std::optional<integer> | read-only | Signed 16 / 32 bit |
| Typed read | SDOReadFloat / Double | std::optional<floating point> | read-only | 32 / 64-bit floating point |
| Typed read | SDOReadString | std::optional<std::string> | read-only | String, decoded by its OD type |
| Typed write | SDOWriteU8 / U16 / U32 / U64 | bool | write-only | Writes uint8_t … uint64_t, returns false on failure |
| Typed write | SDOWriteI16 / I32 | bool | write-only | Writes int16_t / int32_t, returns false on failure |
| Typed write | SDOWriteFloat / Double | bool | write-only | Writes 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
| Category | Property | Type | Read/write | Description |
|---|---|---|---|---|
| Diagnostics | last_sdo_error() | SDOError | read-only | Error code of the most recent SDO operation |
| Diagnostics | last_od_error() | const std::string& | read-only | Reason of the most recent OD load failure (empty = no failure) |
| Diagnostics | last_od_abort() | uint16_t | read-only | Device abort code of the most recent SDO Information read; 0 = the device returned no abort code (does not mean success) |
| Diagnostics | last_od_wkc() | uint16_t | read-only | Innermost mailbox transaction WKC of the most recent SDO Information read (1 = success, 0 = failure / not executed) |
| Statistics | GetSdoStats(SdoStats&) | bool | read-only | Reads the accumulated SDO request statistics snapshot for this slave; false = the read failed (the out parameter is zeroed) |
| Instance info | Dll() | dll_t& | read-only | Reference to the SDK context |
| Instance info | MasterIndex() | uint16_t | read-only | Master number |
| Instance info | SlaveIndex() | uint16_t | read-only | Slave index |
Dll() / MasterIndex() / SlaveIndex() can be fed straight into the slave_emcy free functions described below.
last_sdo_error()
SDOError last_sdo_error() const;
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 typedSDOReadU8,SDOReadU16,SDOReadU32,SDOReadI16,SDOReadI32,SDOReadFloat,SDOReadString(and the matchingSDOWriteU8family for writes) refresh it before they return- success → it becomes
SDOError::NoError - failure → it becomes the matching SDO abort code (degraded to
SDOError::SDOProtocolTimeoutwhen there is no abort code) - each slave's
CoEholds 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 == 0means 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,
wkcis 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 andoutholds the snapshotfalse= the runtime library is not ready / the runtime call failed;outhas 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.
| Category | Name | Value | Read/write | Description |
|---|---|---|---|---|
| No error | NoError | 0x00000000 | read-only | No error |
| Protocol | ToggleBitNotChanged | 0x05030000 | read-only | Toggle bit not changed |
| Protocol | SDOProtocolTimeout | 0x05040000 | read-only | SDO protocol timeout |
| Protocol | InvalidCommandSpecifier | 0x05040001 | read-only | Invalid command specifier |
| Protocol | InvalidBlockSize | 0x05040002 | read-only | Invalid block size |
| Protocol | InvalidSequenceNumber | 0x05040003 | read-only | Invalid sequence number |
| Protocol | CrcError | 0x05040004 | read-only | CRC check error |
| Protocol | OutOfMemory | 0x05040005 | read-only | Out of memory |
| Access | UnsupportedAccess | 0x06010000 | read-only | Unsupported access |
| Access | ReadWriteOnlyError | 0x06010001 | read-only | Attempted read of a write-only object |
| Access | WriteReadOnlyError | 0x06010002 | read-only | Attempted write to a read-only object |
| Access | SubindexWriteError | 0x06010003 | read-only | The subindex is not writable |
| Access | CompleteAccessNotSupported | 0x06010004 | read-only | Complete Access not supported |
| Object | ObjectLengthExceeded | 0x06010005 | read-only | Object length exceeded |
| Object | ObjectMappedToRxPDO | 0x06010006 | read-only | The object is mapped to RxPDO |
| Object | ObjectDoesNotExist | 0x06020000 | read-only | Object does not exist (deterministic failure, enters the NotPresent negative cache) |
| PDO mapping | CannotBeMappedToPDO | 0x06040041 | read-only | Cannot be mapped to a PDO |
| PDO mapping | ExceedsPDOLength | 0x06040042 | read-only | Exceeds the PDO length |
| PDO mapping | ParameterIncompatibility | 0x06040043 | read-only | Parameter incompatibility |
| PDO mapping | InternalIncompatibility | 0x06040047 | read-only | Internal incompatibility |
| Hardware | HardwareAccessError | 0x06060000 | read-only | Hardware access error |
| Type | DataTypeMismatch | 0x06070010 | read-only | Data type mismatch |
| Type | DataTypeTooHigh | 0x06070012 | read-only | Data type length too high |
| Type | DataTypeTooLow | 0x06070013 | read-only | Data type length too low |
| Subindex | SubindexDoesNotExist | 0x06090011 | read-only | Subindex does not exist (deterministic failure, enters the NotPresent negative cache) |
| Value | ValueRangeExceeded | 0x06090030 | read-only | Value out of range |
| Value | ValueTooHigh | 0x06090031 | read-only | Value too high |
| Value | ValueTooLow | 0x06090032 | read-only | Value too low |
| Value | ModuleIdentListMismatch | 0x06090033 | read-only | Module list mismatch |
| Value | MaxLessThanMin | 0x06090036 | read-only | Maximum less than minimum |
| Value | ResourceNotAvailable | 0x060A0023 | read-only | Resource not available |
| Communication | SDOProtocolTimeout | 0x05040000 | read-only | The device sent no abort code (WKC=0 / mailbox timeout / no answer); does not enter NotPresent |
| Communication | GeneralError | 0x08000000 | read-only | General error (the device really returned this code; does not enter NotPresent) |
| Device side | DataTransferError | 0x08000020 | read-only | Data cannot be transferred or stored to the application (reported by the device) |
| Device side | LocalControlError | 0x08000021 | read-only | Data cannot be transferred or stored because of local control (reported by the device) |
| Device side | DeviceStateError | 0x08000022 | read-only | Data cannot be transferred or stored because of the present device state (reported by the device) |
| Device side | DictionaryError | 0x08000023 | read-only | Dictionary error |
| Unknown | UnknownError | 0xFFFFFFFF | read-only | Unknown error |
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.
| Code | Meaning | What to do |
|---|---|---|
| 0x0D000001 | Request 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 bus | Fix the arguments, or move the slave to PreOp first; resending as-is will not succeed |
| 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 |
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:
| Category | Enum | Value | Read/write | Action |
|---|---|---|---|---|
| No error | NoError | 0x00000000 | read-only | Normal |
| Communication / device | SDOProtocolTimeout / GeneralError | 0x05040000 / 0x08000000 | read-only | 0x05040000 = 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 |
| Access | ReadWriteOnlyError / WriteReadOnlyError | 0x06010001 / 0x06010002 | read-only | Wrong direction: change the direction of the call |
| Object missing | ObjectDoesNotExist | 0x06020000 | read-only | Check the ESI / OD to confirm the index; deterministic failure, stop retrying |
| Subindex missing | SubindexDoesNotExist | 0x06090011 | read-only | Check by subindex. 0x06090012 has no matching enum member; print the raw code |
| Unsupported access | UnsupportedAccess | 0x06010000 | read-only | Change state or use PDO instead |
| Invalid value | ValueRangeExceeded / ValueTooHigh / ValueTooLow | 0x06090030 / 31 / 32 | read-only | Correct it against the OD limits |
| Type mismatch | DataTypeMismatch / DataTypeTooHigh / DataTypeTooLow | 0x06070010 / 12 / 13 | read-only | Pick the matching SDORead* / SDOWrite* for the object type |
| Already mapped | ObjectMappedToRxPDO / CannotBeMappedToPDO / ExceedsPDOLength | 0x06010006 / 0x06040041 / 0x06040042 | read-only | Release it in the PDO mapping first |
| Unknown | UnknownError | 0xFFFFFFFF | read-only | Print 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; passstatic_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
ObjectEntryavailable) → allow; the device abort code stays the source of truth. - Reads require
obj_accessto contain theREAD_ANYbit, writes requireWRITE_ANY; a missing bit means access denied. - Reads also look at the AL state: Init / SafeOp accept
READ_PREOPorREAD_SAFEOP, PreOp accepts onlyREAD_PREOP, OP requiresREAD_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 aCoEAccessVerdict. Use it when you only want the verdict and do not want to deal with an exception.ThrowIfCoEAccessDenied(...)— the only throw site: it callsEvaluateCoEAccessinternally and throws only whendenied == 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, callEvaluateCoEAccess(...)with your ownObjectEntry*and the currentEcState.
Reading the exception information:
Index()/SubIndex()— the object index / subindex that failed.IsReadOperation()—truefor a read,falsefor a write.ObjAccess()— the object access permission bits used in the decision;0when 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 indexsub(uint8_t) — subindexmsg(const std::string&) — the complete error message text as-is (it becomes the wholee.what())isRead(bool) — true for a read, false for a write; only fills theIsReadOperation()field, it does not affect thewhat()textobjAccess(uint16_t) — the object access permission bit field; only fills theObjAccess()field, it does not affect thewhat()text
Returns:
CoEAccessDeniedException— a copy of the exception object, ready tothrow
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);
}
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.
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:
| Category | Field/method | Type | Read/write | Description |
|---|---|---|---|---|
| EcODList | full_list | std::vector<ObjectDictionary> | read-only | All objects (directly iterable) |
| EcODList | Count() | int | read-only | Number of objects |
| EcODList | Get(uint16_t idx) | const ObjectDictionary* | read-only | Get by index; returns nullptr when not found |
| EcODList | Get(const std::string& key) | const ObjectDictionary* | read-only | Get by name; returns nullptr when not found |
| EcODList | GetByPosition(int pos) | const ObjectDictionary* | read-only | Get by position; returns nullptr when out of range |
| EcODList | ContainsKey(uint16_t idx) | bool | read-only | Checks whether the index exists |
| EcODList | ContainsKey(const std::string& key) | bool | read-only | Checks whether the name exists |
| EcODList | Copy() | EcODList | read-only | Creates a copy |
ObjectDictionary fields and methods:
| Category | Field/method | Type | Read/write | Description |
|---|---|---|---|---|
| ObjectDictionary | index | uint16_t | read-only | Object index |
| ObjectDictionary | name | std::string | read-only | Object name |
| ObjectDictionary | datatype | uint16_t | read-only | Data type (raw EcDataType value) |
| ObjectDictionary | object_code | uint8_t | read-only | Object code (0x07=VAR / 0x08=ARRAY / 0x09=RECORD) |
| ObjectDictionary | max_sub | uint8_t | read-only | Maximum subindex |
| ObjectDictionary | esi_default_text | std::string | read-only | Display text of the ESI object-level default value |
| ObjectDictionary | entries | std::vector<ObjectEntry> | read-only | Subindex entries |
| ObjectDictionary | Count() | int | read-only | Number of subindexes |
| ObjectDictionary | IsVar() | bool | read-only | Whether it is a VAR type |
| ObjectDictionary | IsArray() | bool | read-only | Whether it is an ARRAY type |
| ObjectDictionary | IsRecord() | bool | read-only | Whether it is a RECORD type |
| ObjectDictionary | Get(uint8_t sub) | const ObjectEntry* | read-only | Get the entry by subindex; returns nullptr when not found |
| ObjectDictionary | Get(const std::string& key) | const ObjectEntry* | read-only | Get the entry by name; returns nullptr when not found |
| ObjectDictionary | GetByPosition(int pos) | const ObjectEntry* | read-only | Get the entry by position; returns nullptr when out of range |
| ObjectDictionary | ContainsKey(uint8_t sub) | bool | read-only | Checks whether the subindex exists |
| ObjectDictionary | ContainsKey(const std::string& key) | bool | read-only | Checks whether the name exists |
| ObjectDictionary | Copy() | ObjectDictionary | read-only | Creates a copy |
ObjectEntry fields and methods:
| Category | Field/method | Type | Read/write | Description |
|---|---|---|---|---|
| ObjectEntry | od_index | uint16_t | read-only | Parent object index |
| ObjectEntry | sub_index | uint8_t | read-only | Subindex |
| ObjectEntry | name | std::string | read-only | Entry name |
| ObjectEntry | data_type | uint16_t | read-only | Data type (raw EcDataType value) |
| ObjectEntry | bit_length | uint16_t | read-only | Bit length |
| ObjectEntry | obj_access | uint16_t | read-only | Access permission bits (see ObjAccessFlags) |
| ObjectEntry | esi_default_text | std::string | read-only | Display text of the ESI DefaultData |
| ObjectEntry | ByteLength() | int | read-only | Byte length = (bit_length + 7) / 8 |
| ObjectEntry | Datatype() | uint16_t | read-only | Data type (same value as data_type) |
| ObjectEntry | CanRead() | bool | read-only | Whether it is readable (decided from the access permission bits; the current master state is not considered) |
| ObjectEntry | CanWrite() | bool | read-only | Whether it is writable (decided from the access permission bits; the current master state is not considered) |
| ObjectEntry | IsReadOnly() | bool | read-only | Whether it is read-only (readable and not writable) |
| ObjectEntry | CanWritePreOp() | bool | read-only | Writable in PreOP |
| ObjectEntry | CanWriteSafeOp() | bool | read-only | Writable in SafeOP (including PreOP) |
| ObjectEntry | CanWriteOp() | bool | read-only | Writable in OP (true when writable in any phase) |
| ObjectEntry | AccessDescription() | std::string | read-only | Access description (for example 读写(PreOP,SafeOP,OP可写) (SDK output, = read/write (writable in PreOP, SafeOP, OP)) / 只读 (SDK output, = read-only) / 无权限 (SDK output, = no access)) |
| ObjectEntry | ToString() | std::string | read-only | Of 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) — defaultfalse.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::nulloptuses the XML cached bySetEsiXml(); an explicitly passed emptystring_viewmeans "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 byCoE; the caller must not free / delete it);nullptron 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 (
nullptrif not ready) and does not start a second load. - State gate: no state gate is required; in OP / SafeOp,
preferEsi = falsereally pulls the subindexes and puts noticeable load on the mailbox, so for value refreshes useLoadODAsyncfrom 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());
}
}
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 ofObjectEntry::obj_access.
Returns:
boolpredicates —true= that permission bit holds. Only the permission bits are examined, not the current master state; for per-state decisions useObjectEntry::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 example0x1C12(member version only).ca_data— the raw bytes read by Complete Access, typedconst std::vector<uint8_t>&.start_subindex(uint8_t) —0= the blob starts with SubIndex 0 (2 bytes);1= it starts at SubIndex 1. Default0.od(const ObjectDictionary&) — the OD entry of the matching object; its OE list must be loaded (staticversion 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;
BOOLEANandBIT1..BIT8are 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 atbit_offset % 8. - When an empty map is returned:
ca_datais empty,od.entriesis empty (staticversion), 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; checkd.okand whetherca_datais 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.constmember function; the same thread-safety constraint asSDORead().
Returns:
std::vector<SDOReadResult>— in the same order asentries, one result per item.- A failed item does not stop the following entries; when
successisfalse,datais 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.
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 useSDOReadDetailAsync. Access denied does not go through the empty vector: when the device returns0x06010000/0x06010001, thedarra::CoEAccessDeniedExceptionthrown on the background thread is rethrown unchanged at.get(), with the same semantics as the synchronous version (the same applies to the detail variantSDOReadDetailAsync).SDOWriteAsync(...).get()returnsfalseon failure; whendatais empty it returnsfalsedirectly without sending a request. When the device returns0x06010000/0x06010002,.get()throwsdarra::CoEAccessDeniedException(the same applies to the detail variantSDOWriteDetailAsync).- On cancellation (
CancelToken).get()throwsOperationCanceled.
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:
| Category | Property | Type | Read/write | Description |
|---|---|---|---|---|
| Batch | SDOBatchAsync(master, slaveIndex, SdoRequest list, CancelToken) | std::future<SdoBatchResult> | read-write | Mixed reads and writes run inside one gate; a failed item does not stop the following ones |
| Batch | SDOBatchReadAsync(master, slaveIndex, SdoAddr list, CancelToken) | std::future<SdoBatchResult> | read-only | Batch read |
| Batch | SDOBatchWriteAsync(master, slaveIndex, SdoWriteItem list, CancelToken) | std::future<SdoBatchResult> | write-only | Batch write; items with empty data are recorded as failures |
| Whole table | LoadODAsync(master, slaveIndex, CancelToken) | std::future<LoadODResult> | read-only | Pulls 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_codeare 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 byokonly. In a batch write, an item whosedatais empty is never sent on the bus at all, so itsabort_codestays 0.LoadODResult::wkctakes 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_okistrueonly when every item succeeded; the failure reason is inreason(an empty batch / a batch containing a failed item is nevertrue).LoadODResult::okistrueonly when objects with names were really obtained; an empty table, a fake index table (most object names of the form0x....) or a slave mailbox that is not up are allfalse, with the reason inreason. In OP / SafeOp,loaded_entries=false(the subindexes are not pulled, to avoid crowding SM2); for value refreshes callSDOBatchReadAsyncseparately.
Device profile detection
GetDeviceProfile()
uint16_t GetDeviceProfile() const;
Read the device profile number.
Parameters:
- None.
constmember function.
Returns:
uint16_t— the lower 16 bits of object0x1000(Device Type).- When
0is returned: the read of0x1000failed, the data is shorter than 4 bytes, or no 32-bit value can be extracted.0is 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()equals402/401respectively. When the profile is unavailable (returns0) both arefalse.
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_emcyfree 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
CoEinstance 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. constmember 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 returnstrue, 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
0x1003in 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 indexerror_code(uint16_t) — EMCY error codeerror_register(uint8_t) — error registerdata(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.
| Category | Name | Value | Read/write | Description |
|---|---|---|---|---|
| Untyped | NONE | 0x0000 | read-only | Untyped |
| Boolean | BOOLEAN | 0x0001 | read-only | Boolean (bool) |
| Signed | INTEGER8 | 0x0002 | read-only | Signed 8-bit (int8_t) |
| Signed | INTEGER16 | 0x0003 | read-only | Signed 16-bit (int16_t) |
| Signed | INTEGER32 | 0x0004 | read-only | Signed 32-bit (int32_t) |
| Unsigned | UNSIGNED8 | 0x0005 | read-only | Unsigned 8-bit (uint8_t) |
| Unsigned | UNSIGNED16 | 0x0006 | read-only | Unsigned 16-bit (uint16_t) |
| Unsigned | UNSIGNED32 | 0x0007 | read-only | Unsigned 32-bit (uint32_t) |
| Floating point | REAL32 | 0x0008 | read-only | Single-precision floating point (float) |
| String | VISIBLE_STRING | 0x0009 | read-only | Visible string (std::string) |
| String | OCTET_STRING | 0x000A | read-only | Byte array (std::vector<uint8_t>) |
| String | UNICODE_STRING | 0x000B | read-only | Unicode string (std::string) |
| Time | TIME_OF_DAY | 0x000C | read-only | Time (as raw bytes) |
| Time | TIME_DIFF | 0x000D | read-only | Time difference (as raw bytes) |
| Other | DOMAIN | 0x000F | read-only | Raw data (std::vector<uint8_t>) |
| Signed | INTEGER24 | 0x0010 | read-only | Signed 24-bit (as raw bytes) |
| Floating point | REAL64 | 0x0011 | read-only | Double-precision floating point (double) |
| Signed | INTEGER40 | 0x0012 | read-only | Signed 40-bit (as raw bytes) |
| Signed | INTEGER48 | 0x0013 | read-only | Signed 48-bit (as raw bytes) |
| Signed | INTEGER56 | 0x0014 | read-only | Signed 56-bit (as raw bytes) |
| Signed | INTEGER64 | 0x0015 | read-only | Signed 64-bit (int64_t) |
| Unsigned | UNSIGNED24 | 0x0016 | read-only | Unsigned 24-bit (as raw bytes) |
| Unsigned | UNSIGNED40 | 0x0018 | read-only | Unsigned 40-bit (as raw bytes) |
| Unsigned | UNSIGNED48 | 0x0019 | read-only | Unsigned 48-bit (as raw bytes) |
| Unsigned | UNSIGNED56 | 0x001A | read-only | Unsigned 56-bit (as raw bytes) |
| Unsigned | UNSIGNED64 | 0x001B | read-only | Unsigned 64-bit (uint64_t) |
| Bit | BIT1 | 0x0030 | read-only | 1 bit |
| Bit | BIT2 | 0x0031 | read-only | 2 bit |
| Bit | BIT3 | 0x0032 | read-only | 3 bit |
| Bit | BIT4 | 0x0033 | read-only | 4 bit |
| Bit | BIT5 | 0x0034 | read-only | 5 bit |
| Bit | BIT6 | 0x0035 | read-only | 6 bit |
| Bit | BIT7 | 0x0036 | read-only | 7 bit |
| Bit | BIT8 | 0x0037 | read-only | 8 bit |
| Unknown | UNKNOWN | 0xFFFF | read-only | A 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 ofObjectEntry::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 fromdata_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.
constmember function; it reads the count from0x10F3:00and 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);
}
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)
};
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 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 messageDiagnosticPollResult::None— no new message (including the normalized result for slaves that do not support0x10F3)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::nullopton failure (including an unsupported runtime), with the specific error inLastDiagAbortCode().
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, usually6..255(seeDiagMeta::newestMessage).bufSize(size_t) — receive buffer capacity, default1024(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 inLastDiagAbortCode().- 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 inLastDiagAbortCode().
LastDiagAbortCode()
uint32_t LastDiagAbortCode() const;
Parameters:
- None.
constmember function.
Returns:
uint32_t— the SDO Abort Code of the most recent call to the 4 diagnostic APIs above;0means 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);
}
}
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'snewestAcknowledged; do not callReadDiagnosticMessages()again to pull repeatedly
ETG.1020 §16 Table 65; ETG.1510 §6.2 Diagnosis history.