CoE (CANopen over EtherCAT)
CoE provides SDO object dictionary access: reading and writing slave parameters, loading the object dictionary catalog, plus EMCY emergency messages and the 0x10F3 diagnostic history.
Access it through slave.CoE. It is null when the slave does not support CoE.
Recommended path
The object entry (ObjectEntry) is the final data read/write node. Read with TryGetBytes() (which distinguishes success from failure) or Bytes; to write, assign Bytes:
// Get an entry: object dictionary catalog → object → subentry
var entry = slave.CoE.ODList[0x6040].OEList[0];
// Read — check success or failure
if (entry.TryGetBytes(out byte[] data, out SDOError error))
ushort status = BitConverter.ToUInt16(data, 0);
else
Console.WriteLine($"读失败: {error}"); // Read failed: {error}
// Write — the only write path
entry.Bytes = BitConverter.GetBytes((ushort)0x0006);
When you do not want to depend on the object dictionary catalog, use SDORead / SDOWrite to read and write directly by index (see SDO read/write).
ObjectEntry.Bytes assignment, SDOWrite() and SDOWriteAsync() all go through the same write channel: state transitions and permission checks are performed automatically, and the behavior is identical. There is no write path that bypasses the state checks; an entry-level failure throws CoE_AccessDeniedException, and an SDO-level failure returns false.
Feature overview
| Category | Property | Type | Read/write | Description |
|---|---|---|---|---|
| Protocol capability | CoESupport | bool? | read-only | CoE capability tri-state: true = supported / false = confirmed unsupported / null = unknown |
| OD catalog | ODList | EcODList | read-only | The loaded object dictionary catalog |
| IsOdListLoaded | bool | read-only | Whether the catalog has been loaded | |
| IsODListLoading | bool | read-only | Whether the catalog is being loaded asynchronously | |
| Object entry | Index | byte | read-only | Subindex |
| ODIndex | ushort | read-only | Parent object index | |
| Name | string | read-only | Entry name | |
| DataType | EcDataType | read-only | Data type | |
| BitLength | uint | read-only | Bit length | |
| ObjAccess | CoEObjectAccess | read-only | Access permission flags | |
| CanRead | bool | read-only | Whether the entry is readable | |
| CanWrite | bool | read-only | Whether the entry is writable | |
| Bytes | byte[] | read/write | Raw byte access (the only write path) | |
| NotPresent | bool | read-only | The slave has confirmed that the entry does not exist | |
| EMCY | EmcyCount | int | read-only | Current number of records in the EMCY history |
| Statistics | Statistics | MailboxStatistics | read-only | Mailbox transaction statistics snapshot |
| Protocol access | CiA402 | CiA402 | read-only | Servo drive protocol helper |
| CiA401 | CiA401 | read-only | Generic IO module protocol helper |
| Category | Method | Type | Read/write | Description |
|---|---|---|---|---|
| SDO read/write | SDORead(ushort, byte, bool) | byte[] | read-only | Reads raw SDO bytes; returns null on failure |
| SDORead(..., out SdoReadResult, ...) | byte[] | read-only | As above, with the success/failure details filled in | |
| SDOWrite(ushort, byte, byte[], bool) | bool | write-only | Writes raw SDO bytes | |
| SDOWrite(..., out SdoWriteResult, ...) | bool | write-only | As above, with the success/failure details filled in | |
| LastSdoError | SDOError | read-only | Error code of the most recent SDO operation | |
| Async and batch | SDOReadAsync(ushort, byte, bool, int?, CancellationToken) | Task<byte[]?> | read-only | Asynchronous read; returns null on failure |
| SDOWriteAsync(ushort, byte, byte[], bool, int?, CancellationToken) | Task<bool> | write-only | Asynchronous write | |
| ReadMultipleAsync(entries, ct) | Task<Dictionary<(ushort, byte), byte[]>> | read-only | Batch serial read | |
| OD catalog | LoadODListAsync(ct, preferEsi) | Task<bool> | write-only | Loads the object dictionary catalog |
| LoadODMetadataAsync(ct) | Task<bool> | write-only | Loads the catalog structure only | |
| PeekOdList() | EcODList | read-only | Peeks at the loaded catalog without triggering a load | |
| ClearOdCache() | void | write-only | Clears the OD catalog and all caches | |
| OD descriptor | GetObjectDictionaryIndices(out CoeSdoInfoResult) | ushort[] | read-only | Reads the list of object indices |
| GetEntryDescription(ushort, byte, out CoeSdoInfoResult) | CoeEntryDescription | read-only | Reads a subindex description | |
| ParseCompleteAccessData(byte[], EcODList, ushort) | Dictionary<byte, byte[]> | read-only | Splits a CA block by subindex (static method, sends nothing on the bus) | |
| MDP / full-table refresh | RefreshMdpModuleValuesAsync(ct) | Task<bool> | write-only | Reads 0xF050 in a bounded background pass and publishes the value cache |
| BeginOdValueRefresh() | int | write-only | Queues a full OD value refresh and returns the number of queued requests | |
| Object entry | TryGetBytes(out byte[], out SDOError) | bool | read-only | Reads raw bytes and distinguishes success from failure |
| ResetNotPresent() | void | write-only | Clears the entry-not-present marker | |
| Value subscription | ValueChanged | event | read-only | Object value change event |
| SubscribeToObject(ushort, byte, TimeSpan) | bool | write-only | Registers cyclic polling | |
| UnsubscribeFromObject(ushort, byte) | void | write-only | Cancels the registration | |
| TryGetCachedValue(ushort, byte, out byte[]) | bool | read-only | Reads the value cache without bus traffic | |
| InvalidateMailboxValueCache(ushort, byte) | void | write-only | Invalidates the value cache of the given object | |
| EMCY | GetHistory(int) | EmcyHistory | read-only | Returns the most recent N EMCY history records |
| ClearHistory() | void | write-only | Clears the EMCY history | |
| Diagnostics | PollDiagnostic() | DiagnosticPollResult | read-only | Polls the 0x10F3 new-message flag |
| ReadDiagnosticMeta() | DiagMeta? | read-only | Reads the 0x10F3 metadata (including the Flags mode bit); null = communication failure or the slave does not support it — check for null first | |
| ReadDiagnosticMessages() | List<DiagnosticMessage> | read-only | Reads all diagnostic messages | |
| ReadDiagnosticMessage(byte, out uint, int) | byte[] | read-only | Reads a single named diagnostic message | |
| AcknowledgeDiagnostic(byte) | bool | write-only | Acknowledges a diagnostic message | |
| DiagnosticMessageReceived | event | read-only | New diagnostic message event | |
| Statistics | GetSdoStats() | CoeSdoStatsResult | read-only | Snapshot of the SDO request counters |
| ResetStatistics() | void | write-only | Resets the mailbox transaction statistics (called through IMailboxProtocol) |
true = CoE is supported; false = the slave has been confirmed not to declare CoE; null = not readable this time (unknown). When you need to distinguish "confirmed unsupported" from "unknown", test CoESupport itself; do not fold it into a bool.
Common SDOError values
The full member table (the complete CANopen / ETG.1020 Abort Code set) is not maintained on this site; the SDOError enum definition in the SDK is authoritative. Common values:
| Enum value | Value | Description |
|---|---|---|
| NoError | 0x00000000 | No error |
| UnsupportedAccess | 0x06010000 | Unsupported access type |
| WriteReadOnlyError | 0x06010002 | Attempt to write a read-only object |
| ObjectDoesNotExist | 0x06020000 | Object does not exist |
| SubindexDoesNotExist | 0x06090011 | Subindex does not exist |
| DataTypeMismatch | 0x06070010 | Data type mismatch |
| SDOProtocolTimeout | 0x05040000 | No communication response (WKC=0 / timeout / no mailbox reply); not "object does not exist" |
| GeneralError | 0x08000000 | The device really returned a general error; investigate further |
| DataTransferError | 0x08000020 | Data cannot be transferred or stored to the application (reported by the device) |
| LocalControlError | 0x08000021 | Data cannot be transferred or stored because of local control (reported by the device) |
| DeviceStateError | 0x08000022 | Data cannot be transferred or stored because of the present device state (reported by the device) |
| LocalRequestNotSent | 0x0D000001 | Request not sent (local reject): no frame went on the bus; not an abort code reported by the device |
Except for LocalRequestNotSent, these codes are not reported by a device. 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 |
|---|---|---|
| 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 |
These three have no enum member, so AbortCode carries the raw value; GetDescription() still returns a description.
Common EcDataType values
The full member table is not maintained on this site; the EcDataType enum definition in the SDK is authoritative (based on ETG.1000.6). Bytes is the uniform data carrier, and DataType determines how the application layer interprets those bytes; the SDK exposes only enum member names, not ETG protocol-name strings. Common values:
| Enum value | Value | Description |
|---|---|---|
| Boolean | 0x0001 | Boolean |
| Integer8 / Integer16 / Integer32 | 0x0002–0x0004 | Signed integers |
| Unsigned8 / Unsigned16 / Unsigned32 | 0x0005–0x0007 | Unsigned integers |
| Real32 / Real64 | 0x0008 / 0x0011 | Single / double precision floating point |
| VisibleString | 0x0009 | Single-byte ISO-8859-1 string |
| UnicodeString | 0x000B | UTF-16LE string |
| OctetString / Domain | 0x000A / 0x000F | Raw bytes |
Common CoEObjectAccess values
The full member table is not maintained on this site; the CoEObjectAccess flag enum definition in the SDK is authoritative. Common bits:
| Constant | Value | Description |
|---|---|---|
| ReadPreOp | 0x01 (Bit 0) | Readable in PreOp |
| ReadSafeOp | 0x02 (Bit 1) | Readable in SafeOp |
| ReadOp | 0x04 (Bit 2) | Readable in OP |
| WritePreOp | 0x08 (Bit 3) | Writable in PreOp |
| WriteSafeOp | 0x10 (Bit 4) | Writable in SafeOp |
| WriteOp | 0x20 (Bit 5) | Writable in OP |
There are also the combined values ReadAny / WriteAny / ReadWriteAll. CanRead / CanWrite are derived from these flags according to the current state.
SDO read/write
SDORead()
public byte[] SDORead(ushort index, byte subindex, bool completeAccess = false)
public byte[] SDORead(ushort index, byte subindex, out SdoReadResult detail, bool completeAccess = false)
Reads raw SDO bytes. A failure / WKC=0 returns null; always check for null before converting with BitConverter. When you need the abort code / WKC details, use the out SdoReadResult overload — it shares the same implementation as the basic overload, and detail.Ok matches the return value.
Parameters:
index(ushort) — object indexsubindex(byte) — subindexcompleteAccess(bool, defaultfalse) — whole-object accessdetail(out SdoReadResult) — success/failure details
Return value:
- Success:
byte[]. A length of 0 indicates "empty string succeeded" only for string objects such as0x1008/0x1009/0x100A - Failure / WKC=0:
null. No mailbox response is not "an empty object that succeeded" - A single read is capped at 64 KB; a response that exceeds the cap is returned as
null(failure)
Related structures: (out details)
SdoReadResult— Ok / Data (null on failure) / AbortCode (0 = none) / Error (= (SDOError)AbortCode) / Wkc / ExpectedWkc (SDO mailbox single-slave addressing = 1)
One SDORead is one SDO transaction; it does not silently retransmit after a timeout — a failure is returned as null. To verify "how many times it was actually sent", use the Requests / Retries deltas from GetSdoStats().
Example:
byte[] data = slave.CoE.SDORead(0x1000, 0);
if (data == null)
{
Console.WriteLine($"SDO 读取失败: {slave.CoE.LastSdoError}"); // SDO read failed: {slave.CoE.LastSdoError}
return;
}
uint typeValue = BitConverter.ToUInt32(data, 0);
SDOWrite()
public bool SDOWrite(ushort index, byte subindex, byte[] data, bool completeAccess = false)
public bool SDOWrite(ushort index, byte subindex, byte[] data, out SdoWriteResult detail, bool completeAccess = false)
Writes raw SDO bytes. It uses the same write channel as ObjectEntry.Bytes assignment (see Recommended path). A null or empty data array returns false directly; for the failure reason check LastSdoError; a master state transition in progress also returns false.
Related structures: (out details)
SdoWriteResult— Ok / AbortCode (0 = none) / Error (= (SDOError)AbortCode) / Wkc / ExpectedWkc
completeAccess parameter
false (the default) reads and writes a single entry by subindex; true reads and writes the whole object, and subindex must be 0 or 1, otherwise SDORead / SDOWrite throw ArgumentException (ETG.1000.6 §5.6.4), and a read does not hit the NotPresent negative cache. The bytes read for a whole object are packed tightly by subindex (SubIndex 0 is always 16 bits, BIT types are packed by bit, and the next non-BIT type starts at the next byte boundary); when you need to split them, parse them yourself using the OD type information, or use ParseCompleteAccessData() directly.
ParseCompleteAccessData()
public static Dictionary<byte, byte[]> ParseCompleteAccessData(byte[] caData, EcODList odList, ushort index)
Splits the whole-object byte block read with Complete Access by subindex (ETG.1020 §14.2). The layout comes from the ESI object dictionary matched to the slave's measured identity, which gives the bit offset and bit length of each subindex: SubIndex 0 is always 16 bits, BOOLEAN / BIT1..BIT8 are packed contiguously by bit, the next non-BIT type starts at a byte boundary, and ESI gap entries only take up space and produce no subindex.
Parameters: caData — the raw CA bytes; odList — supplies the master / slave index used to locate the ESI device; index — the object index.
Return value: Dictionary<byte, byte[]>, key = subindex number. It returns an empty table when caData is empty, odList is null, or the layout cannot be parsed — the caller should fall back to reading subindex by subindex. It is a pure computation and produces no bus traffic.
This is a static method on DarraEtherCAT.Slave.CoEInstance; call it through the type (it cannot be called through a slave.CoE instance).
LastSdoError
public SDOError LastSdoError { get; }
The error code of the most recent SDO operation. It is updated automatically after every SDORead / SDOWrite, and is SDOError.NoError on success.
SDOError.SDOProtocolTimeout (0x05040000)— WKC=0 / mailbox timeout / no communication response (the device sent no abort code). Retryable; not written to the NotPresent cache.SDOError.GeneralError (0x08000000)— the device really returned a general error without a reason; investigate. It is not treated as a missing object and is not written to the NotPresent cache.SDOError.LocalRequestNotSent (0x0D000001)— the request was not sent and no frame went on the bus (invalid arguments / slave index out of range / the slave does not support CoE / the mailbox is not ready). Fix the arguments or move to PreOp first; resending as-is will not succeed.- Only a real abort enters NotPresent (subsequent reads of the same index:sub return
nulldirectly and no SDO is sent):ObjectDoesNotExist (0x06020000),SubindexDoesNotExist (0x06090011),0x06090012. - An empty
byte[0]plusNoErroris an empty-string success, but only for0x1008/0x1009/0x100A; a 0-byte response for any other object is returned asnull(failure).
GetSdoStats()
public CoeSdoStatsResult GetSdoStats()
Snapshot of the accumulated SDO request counters for this slave (requests / retransmissions / timeouts). This is unrelated to the mailbox transaction statistics in Statistics. When Ok = false the counters stay 0; do not read that as "no request was sent". A Requests delta is the evidence that a request was really sent only once (retransmissions do not add 1).
Related structures:
CoeSdoStatsResult— Ok (whether the snapshot is trustworthy) / ReturnCode (0 = success) / Requests (number of newly issued SDO requests) / Retries (number of retransmissions) / Timeouts (cumulative number of timeouts)
Asynchronous SDO and batch reads
SDOReadAsync() / SDOWriteAsync()
public Task<byte[]?> SDOReadAsync(ushort index, byte subindex, bool completeAccess = false,
int? timeoutMs = null, CancellationToken cancellationToken = default)
public Task<bool> SDOWriteAsync(ushort index, byte subindex, byte[] data, bool completeAccess = false,
int? timeoutMs = null, CancellationToken cancellationToken = default)
CoE is the only asynchronous SDO entry point (there is no same-named asynchronous copy on Slave). The semantics match the synchronous versions: a failed read returns null, a failed write returns false (nothing is thrown upward). timeoutMs is the total wall-clock budget for this call (including queueing and throttle waits); when omitted, no budget is set; when given explicitly it must be ≥ 1, otherwise ArgumentOutOfRangeException is thrown.
data == null→ throwsArgumentNullException; an empty array → returnsfalse- NotPresent negative cache hit, or the master is shutting down or already shut down → throws
InvalidOperationException - Cancellation →
OperationCanceledException; values read through the asynchronous entry points are cached and can be read withTryGetCachedValue() - After cancellation / failure a write may still complete in the background — "failed" does not mean "not written"; when you need strong consistency, confirm with a read-back after the write
Example:
byte[]? sw = await slave.CoE.SDOReadAsync(0x6041, 0);
bool ok = await slave.CoE.SDOWriteAsync(0x607A, 0, BitConverter.GetBytes(100000));
ReadMultipleAsync()
public async Task<Dictionary<(ushort index, byte subindex), byte[]>> ReadMultipleAsync(
IEnumerable<(ushort index, byte subindex)> entries,
CancellationToken cancellationToken = default)
Batch SDO reads: one call reads multiple objects. Entries are read serially, not concurrently; a failed entry's value is null, and an exception on a single entry does not abort the whole batch.
Example:
var entries = new[] { ((ushort)0x1018, (byte)1), ((ushort)0x6041, (byte)0) };
var results = await slave.CoE.ReadMultipleAsync(entries, cancellationToken);
foreach (var (key, data) in results)
if (data != null)
Console.WriteLine($"0x{key.index:X4}:{key.subindex:X2} = {BitConverter.ToString(data)}");
For low-level asynchronous mailbox transaction semantics that send and receive complete mailbox frames directly, see Mailbox gateway.
Object dictionary
ODList / PeekOdList() / IsOdListLoaded
public EcODList ODList { get; }
public EcODList PeekOdList()
public bool IsOdListLoaded { get; }
Reading and peeking at the object dictionary catalog.
ODList— the loaded catalog; if it is not loaded and no load has ever been attempted, accessing it loads synchronously (which may block the calling thread); if a load was attempted and failed, it returnsnullPeekOdList()— read-only peek at the loaded catalog; returnsnullwhen it is not loaded, and never triggers a load or sends anything on the bus; anullresult only means "the catalog is not in memory", not that the slave lacks a particular objectIsOdListLoaded— instantaneous observation of whether the catalog is loaded, for diagnostics and display only
Related structures:
EcODList— Count;this[ushort index]gets anObjectDictionaryby object index; supports foreach (elements areKeyValuePair<ushort, ObjectDictionary>)ObjectDictionary— Index / Name / MaxSub;OEList(the subentry collection;this[byte subindex]gets anObjectEntry)
When subentry metadata has not been loaded (for example, only the object list was loaded in OP/SafeOp), accessing an OEList entry throws OdSubindexMetadataNotLoadedException (derived from KeyNotFoundException, so it can still be caught through the base class); see Failures and handling for how to handle it.
Related structures:
public sealed class OdSubindexMetadataNotLoadedException : KeyNotFoundException
{
public ushort ObjectIndex { get; } // Object index that triggered the exception (0x0000-0xFFFF)
public byte SubIndex { get; } // Subindex that triggered it
}
Once caught, locate the exact entry by ObjectIndex / SubIndex; do not parse the exception message text.
IsODListLoading
public bool IsODListLoading { get; }
Whether the object dictionary is being loaded asynchronously (for diagnostics). The load is driven in the background by LoadODListAsync() / LoadODMetadataAsync(), and while it runs the already loaded part can be enumerated directly. false only means no load is running at the moment; it does not mean the load succeeded — judge by IsOdListLoaded / PeekOdList().
LoadODListAsync()
public Task<bool> LoadODListAsync(CancellationToken ct = default, bool preferEsi = false)
Loads the object dictionary catalog asynchronously without blocking the calling thread. By default it really sends SDO Information; with preferEsi: true it first reads the ESI catalog bound to the slave (zero mailbox traffic), then falls back to SDO Information when there is no hit.
Parameters:
ct(CancellationToken) — cancellation tokenpreferEsi(bool, optional, defaultfalse) — prefer loading from ESI
Return value / behavior:
- Load succeeds (object count > 0) →
true; an empty dictionary does not count as success and returnsfalse - A load that just succeeded (within 2 seconds) reuses the previous result; no duplicate is started while one is in flight; the slave does not support CoE →
false - Cancellation: already cancelled at call time → throws
OperationCanceledException; cancelled midway → returnsfalse - After a failure or cancellation
ODListis no longer a usable catalog; callClearOdCache()and retry
LoadODMetadataAsync() / ClearOdCache()
public Task<bool> LoadODMetadataAsync(CancellationToken ct = default)
public void ClearOdCache()
LoadODMetadataAsync()— loads the catalog structure only (does not refresh all values and does not switch bus states).true= the catalog is usable (including a zero-traffic fast return when it has already been loaded);falseis not necessarily a failure — when a concurrent load is in flight this call is skipped, so judge byIsOdListLoaded/PeekOdList()ClearOdCache()— clears the OD catalog + load flag + SDO value cache + NotPresent cache. Call it after a hot-plug / firmware upgrade / topology change so that later accesses really send SDO probes again; the entry-level not-present markers need a separateResetNotPresent()call
GetObjectDictionaryIndices()
public ushort[] GetObjectDictionaryIndices(out CoeSdoInfoResult info)
Reads the list of object indices (SDO Info Service 0x01) and returns only the index array, which is much faster than LoadODListAsync. A failure returns an empty array — an empty array does not mean "the slave has no object dictionary"; always combine it with info.Ok. When you do not need the details, pass out _.
GetEntryDescription()
public CoeEntryDescription GetEntryDescription(ushort index, byte subindex, out CoeSdoInfoResult info)
Reads the description of a single subindex (SDO Info Service 0x05): DataType / BitLength / ObjectAccess / Name. It returns null when the subindex does not exist, the slave does not support SDO Info, or communication fails; check info for the reason.
Related structures:
CoeEntryDescription— Index / SubIndex / ValueInfo / DataType / BitLength / ObjectAccess (CoEObjectAccess) / NameCoeSdoInfoResult— Ok (the only success criterion) / AbortCode (the error code inside the device's SDO Info Error frame, 0 = not received) / Wkc (1 = success, 0 = failure)
AbortCode differs from 0 only when the device returned an Info Error frame; on a transport-level failure (timeout / WKC=0) it stays 0 and the failure is expressed by Wkc. Do not use AbortCode == 0 as a success test.
MDP module values and full OD refresh
RefreshMdpModuleValuesAsync()
public Task<bool> RefreshMdpModuleValuesAsync(CancellationToken ct = default)
After the OD structure is loaded, reads 0xF050 (detected module identities) in a bounded background pass and writes it into this instance's mailbox value cache — the same data consumed by TryGetCachedValue() and by the MDP support check, with no separate flag. It reads at most SubIndex 0 plus 32 ident entries; values already read hit the cache, and once a conclusion is available it does not read again.
Return value: true = the ESI / OD / value cache is already enough to conclude "MDP supported" or "no modules"; false = the value result is still unknown. false never means "there are no modules", and the caller must not use it to make a final hide decision or draw a page-level conclusion.
It is asynchronous and does not block the calling thread; it only queues reads of 0xF050 in the mailbox queue and neither changes bus states nor competes with SM2 PDO. Concurrent calls queue independently (there is no deduplication), so merge them yourself as needed. Throws ObjectDisposedException when the slave has been disposed.
BeginOdValueRefresh()
public int BeginOdValueRefresh()
Full OD value refresh: the structure is loaded by LoadODListAsync(), and this method queues every readable entry to the mailbox background service, which reads them entry by entry / whole object and publishes them to the value cache; the caller (including the GUI) must not send SDOs one by one itself.
0x1000-0x1FFFcommunication area / PDO mapping / SM assignment are read subindex by subindex, without Complete Access; a single failure does not mark the whole object as dead- Vendor-area VARs are read at
:00; RECORD / ARRAY go through Complete Access
Return value: the number of read requests queued this time; 0 = the OD is not loaded or the mailbox service is unavailable (in that case no read was queued).
Object entry
Bytes
public byte[] Bytes { get; set; }
Raw byte access, the uniform carrier for object entry data.
- Read: every access performs a live SDO read. A failed read (NotPresent hit / SDO abort / communication failure) collapses to
byte[0]and is indistinguishable from "the slave really returned an empty string" — useTryGetBytes()when you need to tell them apart. No read permission, or the current state does not allow reading → throwsCoE_AccessDeniedException. - Write: assignment performs the SDO write (the only write path, see Recommended path), with automatic state transitions and permission checks. Writing
nullor an empty array throwsArgumentException; a failed write (including a state transition failure or insufficient permission) throwsCoE_AccessDeniedException.
Related structures:
CoE_AccessDeniedException— Index / SubIndex / EntryName / IsReadOperation / ObjAccess. Thrown when an entry-level read or write is denied (no read/write permission, the current state does not allow that permission bit, or an SDO write requires at least PreOp); after catching it you can switch to a state that allows the operation and retry.
Example:
try
{
slave.CoE.ODList[0x1C12].OEList[0].Bytes = BitConverter.GetBytes((ushort)0);
}
catch (CoE_AccessDeniedException ex)
{
Console.WriteLine($"对象 0x{ex.Index:X4}:{ex.SubIndex:X2} 当前不可写"); // Object 0x{ex.Index:X4}:{ex.SubIndex:X2} is not writable right now
master.SetState(EcState.PreOp);
}
TryGetBytes()
public bool TryGetBytes(out byte[] data, out SDOError error)
Reads raw bytes without collapsing failures.
true— read succeeded (including an empty-string success):dataholds the bytes read (possibly an empty array) anderrorisSDOError.NoErrorfalse— read failed (NotPresent / abort / communication failure):datais an empty-array placeholder anderroris the failure code (for NotPresent it is the cached original abort code)
Note: on false, data.Length == 0, but Length == 0 must not be used as the failure test — rely on the return value and error. No read permission throws CoE_AccessDeniedException; that is not a "read failure".
NotPresent / ResetNotPresent()
public bool NotPresent { get; }
public void ResetNotPresent()
After a real abort (the object / subindex does not exist) is confirmed, the entry is marked NotPresent and no further SDO is sent for it. ResetNotPresent() clears the marker for this entry and allows it to be probed again next time (call it after a hot-plug / firmware upgrade).
Value subscription
ValueChanged
public event EventHandler<CoEValueChangedEventArgs> ValueChanged
Object value change event: only the (index, subIndex) pairs registered through SubscribeToObject() are polled cyclically, and a value is delivered only when the value read back differs from the previous one (unchanged values are not delivered); dispatch is asynchronous and does not block the mailbox thread. With no object registered the event never fires — for "what is the value now" use SDORead() or TryGetCachedValue().
Related structures:
CoEValueChangedEventArgs— SlaveIndex (source slave) / Index / SubIndex / OldValue / NewValue
SubscribeToObject() / UnsubscribeFromObject()
public bool SubscribeToObject(ushort index, byte subIndex, TimeSpan interval)
public void UnsubscribeFromObject(ushort index, byte subIndex)
Parameters:
index(ushort) — object index (0x1000throwsArgumentOutOfRangeException)subIndex(byte) — subindexinterval(TimeSpan) — polling interval, must be > 0
SubscribeToObject() returns false as-is and logs when the mailbox background service is unavailable, rather than silently claiming "subscribed but the event never arrives"; UnsubscribeFromObject() is a no-op for entries that are not registered and does not throw.
TryGetCachedValue()
public bool TryGetCachedValue(ushort index, byte subIndex, out byte[] data)
Reads the value cache published by the asynchronous entry points (a hit within the TTL is returned) and produces no SDO bus traffic at all. On a miss or when no cache exists, data is null and the method returns false; treat data as read-only and do not modify it in place.
InvalidateMailboxValueCache()
public void InvalidateMailboxValueCache(ushort idx, byte sub)
Invalidates the mailbox value cache of the given object so that the next read really sends an SDO (call it after a successful write, or when you refresh manually). It is lock-free and can be called from any thread: it only removes the cache key, does not wait for in-flight reads and does not interrupt an in-flight SDO; when the mailbox service has not started it is a no-op and does not throw.
EMCY emergency messages
CoE collects CiA 301 emergency messages (Emergency), and the CoE instance of each slave automatically collects that slave's EMCY history. The old interfaces GetEmergencyHistory() / ClearEmergencyHistory() / MaxEmcyHistorySize have been removed; use GetHistory() / ClearHistory() / EmcyCount instead.
GetHistory() / ClearHistory() / EmcyCount
public EmcyHistory GetHistory(int maxRecords = 64) // most recent maxRecords entries, oldest → newest
public void ClearHistory() // clears the history (and the event timestamps)
public int EmcyCount { get; } // current number of records in the history
Returns the most recent maxRecords entries from the ring history in chronological order (oldest → newest); Records[RecordCount - 1] is the newest entry. RecordCount is the number of entries returned this time (≤ maxRecords), and EmcyCount is the current total number of records in the history.
Related structures:
EmcyHistory— RecordCount (number of entries returned this time) / RecordsEmergencyMessage— ErrorCode (CiA 301 Table 24) / ErrorRegister (0x1001) / Data (5 vendor bytes) / SlaveIndex / Timestamp (the reading time for entries whose event timestamp cannot be matched);GetErrorDescription()returns the error category text (current error / temperature error, etc.)
Example:
var history = slave.CoE.GetHistory();
for (int i = 0; i < history.RecordCount; i++)
{
var msg = history.Records[i];
Console.WriteLine($"EMCY 0x{msg.ErrorCode:X4}: {msg.GetErrorDescription()} " +
$"寄存器=0x{msg.ErrorRegister:X2} 时间={msg.Timestamp:HH:mm:ss.fff}"); // register=0x{msg.ErrorRegister:X2} time={msg.Timestamp:HH:mm:ss.fff}
}
Console.WriteLine($"历史共 {slave.CoE.EmcyCount} 条"); // Total in history: {slave.CoE.EmcyCount}
slave.CoE.ClearHistory();
Diagnostic messages 0x10F3
CiA 301 / ETG.1020 §16 defines object 0x10F3 (Diagnosis History) as the standard channel through which a slave reports runtime faults, events and warnings. Unlike EMCY's "transient emergency messages", 0x10F3 is a ring buffer persisted in the slave: it can still be read after a device restart and reconnect, and is suitable for post-mortem analysis.
ReadDiagnosticMessages()
public List<DiagnosticMessage> ReadDiagnosticMessages()
Reads all 0x10F3 messages and returns the complete list read this time (without deduplication); new messages trigger the DiagnosticMessageReceived event (see Diagnostic events). A failed read / an insufficient count frame / a short frame is skipped (and logged), and the part already read is returned.
ReadDiagnosticMessage()
public byte[] ReadDiagnosticMessage(byte msgSubIndex, out uint abortCode, int bufferCapacity = 256)
Single diagnostic message primitive: reads only the 0x10F3:<msgSubIndex> record and returns the bytes as-is, without parsing and without triggering events; suited to reading a specific entry by name.
Parameters:
msgSubIndex(byte) — message subindex (6..255; the message body starts at subindex 6);< 6throwsArgumentOutOfRangeExceptionabortCode(out uint) — SDO abort code (0 = no error)bufferCapacity(int) — read buffer capacity (1..8192, default 256); messages longer than that are truncated to this capacity
Return value: the raw bytes of that message; null = communication failure or the subindex cannot be read; check abortCode for the reason.
Related structures:
DiagnosticMessage— SubIndex (6..n) / DiagCode (4-byte diagnostic code, vendor-defined) / Flags (severity / type; the bit definitions depend on the slave implementation, consult the ESI / manual) / TextIndex (0x1000 string table index) / RawData (8-byte header + variable parameters) / Timestamp (UTC) / SlaveIndex
Diagnostic polling and acknowledgement
PollDiagnostic()
public DiagnosticPollResult PollDiagnostic()
Fast polling of the 0x10F3:04 NewMessagesAvailable flag; it does not trigger a full history fetch and is suitable for high-frequency application-level polling.
Related structures:
DiagnosticPollResult.None(0) — no new messagesDiagnosticPollResult.HasNew(1) — new messages are available; continue fetching (ReadDiagnosticMessages())DiagnosticPollResult.Failed(-1) — communication failure or an abnormal return value; this is not "no new messages" — do not silently treat it as no messages
ReadDiagnosticMeta()
public DiagMeta? ReadDiagnosticMeta()
Reads the 0x10F3:01 / 02 / 03 / 05 metadata block (:04 is read separately by PollDiagnostic()); it uses the same atomic entry point as C++ / Java / Python / Rust.
Return value: DiagMeta? (nullable — the signature is public DiagMeta? ReadDiagnosticMeta()); null = communication failure or the slave does not support 0x10F3, so the caller must check for null before reading fields. It cannot be inferred from PollDiagnostic() returning None — the implementation normalizes "object not supported" to 0 as well, so use this method's null to tell capability apart.
DiagMeta structure:
| Member | Type | Access | Description |
|---|---|---|---|
MaxMessages | byte | read-only | 0x10F3:01 maximum number of message slots the slave supports (usually ≤ 250) |
NewestMessage | byte | read-only | 0x10F3:02 the subindex holding the newest message (6..255), not a "message count" |
NewestAcknowledged | byte | read-only | 0x10F3:03 newest acknowledged subindex |
Flags | ushort | read-only | 0x10F3:05 flags: bit4 = buffer mode (0 = Overwrite, 1 = Acknowledge), bit5 = Overrun |
The mode decides how to read NewestMessage / NewestAcknowledged (ETG.1020 Table 49):
Flagsbit4 = 0 → Overwrite mode:0x10F3:04 NewAvailablemeans "the newest message has not been read"; it alone answers "is there an unread message".NewestAcknowledgedstaying at 0 is the value the specification requires, so do not infer unacknowledged messages fromNewestMessage != NewestAcknowledged.Flagsbit4 = 1 → Acknowledge mode: only then doesNewestMessage != NewestAcknowledgedmean there are unacknowledged messages.- In both modes
Flagsbit5 = Overrun means the ring buffer has overwritten unread messages.
The C# DiagMeta exposes only the Flags field and has no IsAcknowledgeMode()-style accessor: test (meta.Flags & 0x0010) != 0 (0 = Overwrite, 1 = Acknowledge) and for bit5 use (meta.Flags & 0x0020) != 0 to test Overrun.
Example:
var meta = slave.CoE.ReadDiagnosticMeta();
if (meta == null) return; // 0x10F3 unsupported / read failed → fall back to EMCY monitoring
bool acknowledgeMode = (meta.Flags & 0x0010) != 0;
Console.WriteLine(
$"模式={(acknowledgeMode ? "Acknowledge" : "Overwrite")}, " + // mode={(acknowledgeMode ? "Acknowledge" : "Overwrite")},
$"最新消息子索引={meta.NewestMessage}, 已确认子索引={meta.NewestAcknowledged}, " + // newest message subindex={meta.NewestMessage}, acknowledged subindex={meta.NewestAcknowledged},
$"Overrun={((meta.Flags & 0x0020) != 0)}");
AcknowledgeDiagnostic()
public bool AcknowledgeDiagnostic(byte subIndex)
Writes 0x10F3:03 NewestAcknowledged to tell the slave that "all messages up to subIndex have been handled"; in Acknowledge mode (Flags bit4 = 1) the slave advances its acknowledged position accordingly, while in Overwrite mode (bit4 = 0) this object carries no decision weight. The valid range for subIndex is 6..255.
If a slave does not implement 0x10F3, the diagnostic interfaces read nothing and the application needs to fall back to EMCY monitoring (GetHistory()). In Overwrite mode, when the capacity is exceeded the oldest messages are overwritten and Overrun is set; on the first read it is recommended to read all unacknowledged messages in one go before acknowledging, so that none are missed.
Diagnostic events
DiagnosticMessageReceived
public event EventHandler<DiagnosticMessageEventArgs> DiagnosticMessageReceived
New diagnostic message event: fired when ReadDiagnosticMessages() finds new messages; repeated calls do not deliver the same message twice. DiagnosticMessageEventArgs.NewMessages is the list of messages newly added this time (after deduplication).
Full example — poll and consume the diagnostic history:
if (slave.CoE == null) return;
// 1. Subscribe to the event — e.NewMessages holds the messages added this time (deduplicated)
slave.CoE.DiagnosticMessageReceived += (sender, e) =>
{
foreach (var msg in e.NewMessages)
{
Console.WriteLine(
$"[从站 {msg.SlaveIndex}] 诊断 SubIndex={msg.SubIndex} " + // [Slave {msg.SlaveIndex}] diagnostics SubIndex={msg.SubIndex}
$"Code=0x{msg.DiagCode:X8} Flags=0x{msg.Flags:X4} " +
$"Text=0x{msg.TextIndex:X4} @ {msg.Timestamp:HH:mm:ss.fff}");
}
};
// 2. Application-level periodic polling (low frequency; a 1s interval is enough)
while (running)
{
if (slave.CoE.PollDiagnostic() == DiagnosticPollResult.HasNew)
{
// 3. Fetch the messages reported this time (the return value is the complete list read this time)
var messages = slave.CoE.ReadDiagnosticMessages();
byte newest = 0;
foreach (var msg in messages)
{
Console.WriteLine($" SubIndex={msg.SubIndex} Code=0x{msg.DiagCode:X8}");
if (msg.SubIndex > newest) newest = msg.SubIndex;
}
// 4. Handle and acknowledge
if (newest >= 6)
slave.CoE.AcknowledgeDiagnostic(newest);
}
Thread.Sleep(1000);
}
Mailbox statistics
Mailbox transactions share one status definition, MailboxStatus (the same definition is used by all seven protocols: CoE / FoE / SoE / AoE / EoE / VoE / FSoE):
MailboxStatus enum
public enum MailboxStatus
{
Pending = 0, // pending (not yet started, or in progress)
Success = 1, // completed successfully
Timeout = -1, // timeout (the peer did not respond within the allotted time)
Cancelled = -2, // cancelled
MailboxError = -3, // mailbox error frame (the peer returned MBX ERROR / Abort)
ProtoMismatch = -4, // response protocol type mismatch
// -5 reserved slot: this status never occurs (the mailbox Rx counter
// is an independent slave-send counter and has no pairing with the request Tx counter)
WkcFail = -6, // working counter (WKC) does not match the expectation
NoMemory = -7, // out of memory
InvalidArg = -8, // invalid argument
NotImplemented = -9, // not implemented / not supported
LinkDown = -10, // link down (frames fail immediately instead of timing out one by one); check the cable / NIC link status
NotSent = -11 // request never left locally (the frame never made it onto the wire: aborted / backing off / pool exhausted / channel closed / held by the kernel); not a slave timeout and not a slave rejection — there is no bus evidence at all, so it must not be used for slave-drop or link-health verdicts; callers treat it as retryable
}
Statistics / ResetStatistics()
public MailboxStatistics Statistics { get; }
void IMailboxProtocol.ResetStatistics(); // explicit interface implementation; not exposed on the CoE facade
Mailbox transaction statistics snapshot for this instance: every read returns the current snapshot, and when it cannot be obtained an empty snapshot is returned (all 0s — do not read that as "no traffic").
ResetStatistics() is called through IMailboxProtocol. It sets the status back to Pending only after the underlying reset really succeeds; a failed reset does not zero the counters — the status is explicitly set to MailboxError, and it never reports statistics that merely look correct:
((IMailboxProtocol)slave.CoE).ResetStatistics();
Related structures:
MailboxStatistics— TotalSent / TotalReceived / TotalTimeout / TotalMailboxError / TotalProtocolError (protocol type mismatch, WKC failure) / TotalCancelled / LastErrorCode (0 = none) / LastErrorTime (UTC, null when there is no error) / AverageLatencyUs (microseconds) / Empty (empty snapshot, all 0s)
Failures and handling
| Symptom | Cause | Handling |
|---|---|---|
| SDORead returns null and LastSdoError is SDOProtocolTimeout | WKC=0 / mailbox timeout, no reply received (not "object does not exist") | Check the link and slave state, then retry; use the out detail overload to inspect Wkc / AbortCode |
| SDORead returns null and AbortCode is 0x06020000 / 0x06090011 | The object / subindex really does not exist | Confirm the index against the OD / ESI; after a firmware change call ResetNotPresent() to probe again |
| Entry read/write throws CoE_AccessDeniedException | The entry has no read/write permission, or the current bus state does not allow that permission bit | Switch to a state that allows it (such as PreOp) and write again; do not write to read-only objects |
| Accessing an object entry throws OdSubindexMetadataNotLoadedException | Subindex metadata has not been loaded (for example, only the object list was loaded in OP/SafeOp) | Use GetEntryDescription() to get that entry's metadata, then go through SDOWrite / SDORead |
| Read/write throws InvalidOperationException | The object dictionary is not loaded or the load failed; a NotPresent cache hit on the asynchronous entry point, or the master is shut down | Call ClearOdCache() and then await LoadODListAsync() to retry; do not send more SDOs after the master shuts down |
| Asynchronous write returns false / still uncertain after cancellation | When a failure is concluded, the in-flight write may still complete ("failed" does not mean "not written") | When you need strong consistency, confirm with a read-back after the write |
| Some Timestamp values in GetHistory() are the reading time | Those entries cannot be matched to an event timestamp (records from before the process restarted, ring wrap-around, etc.) | Normal semantics; if you need exact event times, record them yourself when the event arrives |
| Diagnostic interfaces read nothing | The slave does not support 0x10F3, or communication failed | Fall back to EMCY monitoring (GetHistory()) |
| PollDiagnostic() returns Failed | The 0x10F3 poll failed at the communication level | Do not treat it as "no messages"; confirm the slave state and retry on the next cycle |
Full example
Iterate the object dictionary
bool loaded = await slave.CoE.LoadODListAsync();
if (!loaded)
{
Console.WriteLine($"对象字典加载失败: {slave.CoE.LastSdoError}"); // Object dictionary load failed: {slave.CoE.LastSdoError}
return;
}
foreach (var item in slave.CoE.ODList)
{
Console.WriteLine($"0x{item.Key:X4}: {item.Value.Name}");
foreach (var entry in item.Value.OEList)
{
byte[] raw = slave.CoE.SDORead(item.Key, entry.Index);
if (raw == null)
{
Console.WriteLine($" [{entry.Index}] {entry.Name}: 读失败 {slave.CoE.LastSdoError}"); // [{entry.Index}] {entry.Name}: read failed {slave.CoE.LastSdoError}
continue;
}
Console.WriteLine($" [{entry.Index}] {entry.Name}: {raw.Length} 字节"); // [{entry.Index}] {entry.Name}: {raw.Length} bytes
}
}