CoE (CANopen over EtherCAT)
Access through slave.coe(). Sub-objects are created lazily and always return an instance (never null).
Quick start
CoE uses SDO to read and write the object dictionary by index / subindex; cyclic process data goes through PDO and is not covered here.
import com.darra.ethercat.slave.CoE;
import com.darra.ethercat.data.EtherCATTypes.SDOError;
CoE coe = slave.coe();
// Raw byte read — the result object carries ok / data / abortCode / wkc; no exception is thrown
CoE.SdoReadResult read = coe.sdoRead((short) 0x6041, (byte) 0);
if (!read.ok) {
System.out.printf("SDO 失败: abort=0x%08X wkc=%d%n", read.abortCode, read.wkc); // SDO failed: abort=0x%08X wkc=%d%n
return;
}
int statusWord = (read.data[0] & 0xFF) | ((read.data[1] & 0xFF) << 8);
boolean ok = coe.sdoWrite((short) 0x6040, (byte) 0, new byte[]{0x06, 0x00}).ok;
// Typed read — returns SdoTypedResult; judge by ok
CoE.SdoTypedResult<Short> status = coe.sdoReadInt16((short) 0x6041, (byte) 0);
if (!status.ok) return;
CoE.SdoTypedResult<Integer> position = coe.sdoReadInt32((short) 0x6064, (byte) 0);
CoE.SdoTypedResult<String> name = coe.sdoReadString((short) 0x1008, (byte) 0);
// Typed write — also returns SdoTypedResult (value is always null)
coe.sdoWriteInt16((short) 0x6040, (byte) 0, (short) 0x0006);
coe.sdoWriteInt32((short) 0x607A, (byte) 0, 100000);
The index parameter type is short and the subindex is byte; Java does not narrow int literals to short automatically, so you must add the (short) / (byte) casts as shown above.
getLastSdoError()sdoRead / sdoWrite / the typed methods each return their own result object; on failure ok=false and abortCode holds the device's raw value. getLastSdoError() is an instance-level shared cache, so with concurrent SDO traffic it only reflects "the last one" and cannot be used to attribute a specific call. SDO_PROTOCOL_TIMEOUT (0x05040000) means the mailbox did not come back (WKC=0 / timeout), not "object does not exist"; only deterministic aborts such as a missing object / subindex are classified as NotPresent.
SDO read
sdoRead(short index, byte subIndex)
public CoE.SdoReadResult sdoRead(short index, byte subIndex)
public CoE.SdoReadResult sdoRead(short index, byte subIndex, boolean completeAccess)
Reads raw SDO byte data. The entire result is carried in the returned object; it does not throw and does not return null.
Related structures:
public static class SdoReadResult {
public boolean ok; // true = this read succeeded
public byte[] data; // data read; null on failure, byte[0] when an empty string was read successfully
public int abortCode; // raw SDO Abort value from the device (0 = no abort)
public int wkc; // underlying working counter; 0 = timeout / no response
}
When ok=false, data=null. On a communication-level failure where the underlying layer gives no abort, abortCode is filled with SDO_PROTOCOL_TIMEOUT (0x05040000), so a 0 is never read as "success with no abort reason"; an abort actually returned by the device (including codes outside the table) is passed through unchanged.
Complete Access: with completeAccess=true, reads all subindices of the object in one transfer (ETG.1000.6); data is the packed raw bytes, which parseCompleteAccessData(...) can split; Complete Access reads are not affected by the NotPresent read memory.
Returns:
CoE.SdoReadResult— transfer result + raw bytes + abort code + WKC- The length of a single read result is limited by the underlying buffer; the SDK additionally applies a defensive
size <= 0 || size > 10 MBcheck and returns failure when it triggers (ok=false,abortCode=SDO_PROTOCOL_TIMEOUT)
Typed reads
public CoE.SdoTypedResult<Byte> sdoReadInt8(short index, byte subIndex)
public CoE.SdoTypedResult<Short> sdoReadInt16(short index, byte subIndex)
public CoE.SdoTypedResult<Integer> sdoReadInt32(short index, byte subIndex)
public CoE.SdoTypedResult<Long> sdoReadInt64(short index, byte subIndex)
public CoE.SdoTypedResult<Integer> sdoReadUInt8(short index, byte subIndex)
public CoE.SdoTypedResult<Integer> sdoReadUInt16(short index, byte subIndex)
public CoE.SdoTypedResult<Long> sdoReadUInt32(short index, byte subIndex)
public CoE.SdoTypedResult<Long> sdoReadUInt64(short index, byte subIndex)
public CoE.SdoTypedResult<Float> sdoReadFloat(short index, byte subIndex)
public CoE.SdoTypedResult<Double> sdoReadDouble(short index, byte subIndex)
public CoE.SdoTypedResult<String> sdoReadString(short index, byte subIndex)
All typed reads return CoE.SdoTypedResult<T> instead of a bare wrapper type. ok = the transfer succeeded and decoding to the target type succeeded; take the value from result.value.
Payload types: UInt8 is carried in Integer (0..255), UInt16 in Integer, and UInt32 / UInt64 in Long. UInt64 is the raw 64 bits: values above Long.MAX_VALUE appear negative, the same convention as asUInt64 for PDO.
Decode failure = transfer succeeded but the length is short: ok=false, abortCode=0, and rawBytes keeps the bytes actually read, which is how you tell a device abort from a type mismatch.
Strings: sdoReadString decodes according to the OD data type of the object: VISIBLE_STRING / OCTET_STRING use single-byte ISO-8859-1, UNICODE_STRING uses UTF-16LE; the byte-level conversion is done by the underlying layer. The mode first checks the loaded OD table and, on a miss, sends one Entry Description to obtain the authoritative type; if neither yields it, it truthfully returns ok=false (it does not guess a single encoding). When the read succeeds but the object is empty, value="" and ok=true (distinguishable from the transfer failure ok=false).
SdoTypedResult
public static class SdoTypedResult<T> {
public boolean ok; // read: both transfer and decode succeeded; write: the write succeeded
public T value; // decoded value; null on failure (always null for writes)
public int abortCode; // raw SDO Abort value (0 = no abort; codes outside the table are passed through unchanged)
public int wkc; // underlying working counter (0 = timeout / no response)
public byte[] rawBytes; // raw bytes read / encoded bytes written; null when there is no data on failure
}
Each call holds its own result object and does not rely on instance-shared state such as getLastSdoError(), so it can be used directly for per-call decisions in concurrent read/write scenarios.
SDO write
sdoWrite(short index, byte subIndex, byte[] data)
public CoE.SdoWriteResult sdoWrite(short index, byte subIndex, byte[] data)
public CoE.SdoWriteResult sdoWrite(short index, byte subIndex, byte[] data, boolean completeAccess)
Writes raw SDO byte data. The result is carried in the returned object; it does not throw.
Related structures:
public static class SdoWriteResult {
public boolean ok; // true = the write succeeded
public int abortCode; // raw SDO Abort value from the device (0 = no abort)
public int wkc; // underlying working counter; 0 = timeout / no response
}
If data is null or has length 0, the call returns ok=false and abortCode=GENERAL_ERROR directly without sending a bus frame. A failed write does not enter the read cache (the object may still be readable). If the underlying layer reports success but carries an abort other than 0, it is treated as a failure (the device's value wins). On failure abortCode is the device's raw value; on a communication-level failure without an abort it is filled with SDO_PROTOCOL_TIMEOUT (0x05040000).
Complete Access: with completeAccess=true, writes all subindices of the object in one transfer; data must be packed according to the ETG.1000.6 rules.
Asynchronous SDO read/write
public CompletableFuture<CoE.SdoReadResult> sdoReadAsync(short index, byte subIndex)
public CompletableFuture<CoE.SdoReadResult> sdoReadAsync(short index, byte subIndex, boolean completeAccess)
public CompletableFuture<CoE.SdoWriteResult> sdoWriteAsync(short index, byte subIndex, byte[] data)
public CompletableFuture<CoE.SdoWriteResult> sdoWriteAsync(short index, byte subIndex, byte[] data, boolean completeAccess)
Reads and writes SDO asynchronously; the caller gets a future immediately and the current thread is not blocked.
- Execution model: strictly serialized with build / setState / other SDO calls on the same master and never accesses the mailbox concurrently; the caller gets a
CompletableFutureimmediately and the current thread is not blocked. - Failure semantics (same as the synchronous version): completes normally with an
ok=falseresult object, with the abort code in theabortCodefield and no exception thrown. Only a master close / a callercancel(true)completes exceptionally withCancellationException. - Cancellation: cancellation aborts only the blocking call of this master and then resets; it does not affect other masters.
Example:
CoE coe = slave.coe();
coe.sdoReadAsync((short) 0x6041, (byte) 0)
.thenAccept(r -> {
if (!r.ok) {
System.err.printf("SDO 失败 abort=0x%08X wkc=%d%n", r.abortCode, r.wkc); // SDO failed abort=0x%08X wkc=%d%n
return;
}
if (r.data.length < 2) return; // a successful but empty object is byte[0]
System.out.printf("状态字: 0x%04X%n", // Status word: 0x%04X%n
(r.data[0] & 0xFF) | ((r.data[1] & 0xFF) << 8));
});
Typed writes
public CoE.SdoTypedResult<Void> sdoWriteInt16 (short index, byte subIndex, short value)
public CoE.SdoTypedResult<Void> sdoWriteInt32 (short index, byte subIndex, int value)
public CoE.SdoTypedResult<Void> sdoWriteInt64 (short index, byte subIndex, long value)
public CoE.SdoTypedResult<Void> sdoWriteUInt16(short index, byte subIndex, int value)
public CoE.SdoTypedResult<Void> sdoWriteUInt32(short index, byte subIndex, long value)
public CoE.SdoTypedResult<Void> sdoWriteUInt64(short index, byte subIndex, long value)
public CoE.SdoTypedResult<Void> sdoWriteFloat (short index, byte subIndex, float value)
public CoE.SdoTypedResult<Void> sdoWriteDouble(short index, byte subIndex, double value)
public CoE.SdoTypedResult<Void> sdoWriteByte (short index, byte subIndex, byte value)
All of them return CoE.SdoTypedResult<Void>: ok is the write result, abortCode is the device's raw value, wkc is the transaction result, rawBytes holds the encoded bytes submitted by this call, and value is always null. There is no sdoWriteInt8; use sdoWriteByte for 8-bit writes. UInt16 is carried in int, and UInt32 / UInt64 in long.
NotPresent read memory
For a read request that the slave has explicitly rejected and that would never succeed on retry, the SDK remembers the conclusion: identical read requests afterward fail directly without using the bus, and getLastSdoError() reflects that conclusion. Only the read path uses this memory; the write path neither consults nor updates it, and Complete Access reads do not use it.
After hot-plug / firmware upgrade / topology change you must call resetNotPresentCache(), otherwise a newly attached object with the same index is blocked by the old conclusion; switching slaves or refreshing the list does not require clearing it.
public static boolean isDeterministicSdoAbort(long abortCode) // whether this failure is certain to repeat
public void resetNotPresentCache() // clears the read memory of this slave
public void clearSdoCaches() // equivalent to resetNotPresentCache()
if (CoE.isDeterministicSdoAbort(coe.getLastSdoError().value)) {
coe.resetNotPresentCache(); // re-probe after a topology change
}
Batch read
readMultipleAsync(List<int[]> entries)
public CompletableFuture<Map<Long, byte[]>> readMultipleAsync(List<int[]> entries)
Batch SDO read — reads multiple objects asynchronously in one call. Suited to scenarios that need several SDOs at once, avoiding blocking calls one by one.
Parameters:
entries(List<int[]>) — the list of (index, subindex) pairs to read; each element is anint[2]
Returns:
CompletableFuture<Map<Long, byte[]>>— result map (LinkedHashMap, in the same order asentries), where the key is the((index & 0xFFFF) << 8) | (subindex & 0xFF)encoding (long) and the value is the data; when a single entry fails, that key's value isnulland the other entries are unaffected
Batch reads are strictly serialized with build / setState / other SDO calls on the same master. When a single entry fails, that key's value is null and a WARNING is logged (with the abort code and wkc), so a failure never becomes a silent item that cannot be traced.
Example:
CoE coe = slave.coe();
List<int[]> entries = new ArrayList<>();
entries.add(new int[]{0x6041, 0}); // StatusWord
entries.add(new int[]{0x6064, 0}); // ActualPosition
entries.add(new int[]{0x1008, 0}); // DeviceName
Map<Long, byte[]> results = coe.readMultipleAsync(entries).get();
for (Map.Entry<Long, byte[]> e : results.entrySet()) {
long key = e.getKey();
int index = (int) ((key >> 8) & 0xFFFF);
int sub = (int) (key & 0xFF);
System.out.printf("0x%04X:%d = %s%n", index, sub,
e.getValue() != null ? e.getValue().length + " bytes" : "失败"); // Failed
}
Properties
| Category | Property | Type | Read/write | Description |
|---|---|---|---|---|
| Error codes | getLastSdoError() | SDOError | read-only | Error code of the last SDO operation (enum view) |
| Error codes | getLastSdoAbortCode() | long | read-only | Raw 32-bit abort code returned verbatim by the device on the last SDO failure (0 = the device returned no abort code) |
getLastSdoError()
public SDOError getLastSdoError()
Error code of the last SDO operation (CANopen Abort Code, ETG.1020). It is cached by the SDK after each sdoRead* / sdoWrite* call: on success → SDOError.NO_ERROR, on failure → the specific Abort enum. It can be used as a secondary reading after a result object reports ok=false.
getLastSdoError() is a shared cache on the CoE instance, not thread-local. When SDO requests run concurrently on the same slave, it only reflects "the last" operation. To determine the failure reason for this call, read the result object: SdoReadResult.abortCode / SdoWriteResult.abortCode / SdoTypedResult.abortCode.
SDOError is an enum with the full name com.darra.ethercat.data.EtherCATTypes.SDOError; take the raw numeric value with error.value (long) and look it up by value with SDOError.fromValue(long) (an unknown value returns SDOError.UNKNOWN_ERROR).
getLastSdoAbortCode()
public long getLastSdoAbortCode()
The 32-bit abort code returned verbatim by the device on the last SDO failure (& 0xFFFFFFFF, already restored to unsigned). It serves a different purpose from getLastSdoError():
getLastSdoError()is the enum view and only lists codes inside the ETG.1020 table; out-of-table codes always fall toUNKNOWN_ERROR(0xFFFFFFFF) — the same value as "no abort code was obtained";getLastSdoAbortCode()gives the device's real raw value: out-of-table codes (vendor codes such as the0xAnnn:18returned by ETG.1510) come back as-is and are never folded into 0xFFFFFFFF.
0 means the device returned no abort code (timeout / no frame sent locally / no failure yet) — 0 is not a legal abort code. This is likewise an instance-level shared cache; to judge per call, read the result object's abortCode.
CoE.SdoReadResult r = coe.sdoRead((short) 0x6000, (byte) 0x01);
if (!r.ok) {
long raw = coe.getLastSdoAbortCode();
if (raw == 0) {
System.out.println("设备没回中止码(超时 / 未发帧)"); // The device returned no abort code (timeout / frame never sent)
} else if (coe.getLastSdoError() == SDOError.UNKNOWN_ERROR) {
System.out.printf("表外中止码: 0x%08X%n", raw); // The enum cannot hold it; the raw value lives here
}
}
GENERAL_ERROR / SDO_PROTOCOL_TIMEOUT are not "object does not exist"SDOError.SDO_PROTOCOL_TIMEOUT (0x05040000)— WKC=0 / mailbox timeout / no communication response (the device returned no abort code). Retryable; do not treat it as a missing object, and it is not written to NotPresent.SDOError.GENERAL_ERROR (0x08000000)— the device really returned a "general error" but gave no reason; investigate it. Also not classified as NotPresent.- Only deterministic aborts are classified as NotPresent: failures that are certain to fail on retry, such as a missing object or subindex.
Example:
CoE.SdoReadResult r = coe.sdoRead((short) 0x6041, (byte) 0);
if (!r.ok) {
SDOError error = coe.getLastSdoError(); // secondary reading only
System.out.printf("SDO 读取失败: abort=0x%08X wkc=%d%s%n", // SDO read failed: abort=0x%08X wkc=%d%s%n
r.abortCode, r.wkc, error.name());
if ((r.abortCode & 0xFFFFFFFFL) == SDOError.SDO_PROTOCOL_TIMEOUT.value)
System.out.println("WKC=0 / 超时,不是对象不存在"); // WKC=0 / timeout, not a nonexistent object
}
SDO request statistics
| Category | Method | Type | Read/write | Description |
|---|---|---|---|---|
| Statistics | getSdoStats() | CoE.SdoStats | read-only | Reads a per-slave snapshot of cumulative SDO requests / retransmissions / timeouts; the counters are not trustworthy when ok=false |
getSdoStats()
public CoE.SdoStats getSdoStats()
Reads the cumulative SDO statistics snapshot of this slave.
Returns: CoE.SdoStats
public static class SdoStats {
public boolean ok; // true = snapshot reliable (the call returned 0); false = unavailable / invalid parameter or state
public int nativeStatus; // call result code: 0 = success
public long requests; // number of newly issued logical SDO requests (a timeout retransmission does not add 1)
public long retries; // number of retransmissions
public long timeouts; // cumulative number of timeouts
}
The three counters are raw unsigned 32-bit values carried losslessly in long (0..4294967295); no inference is made.
Failure semantics:
- When the older runtime library does not support it / the call returns a value other than 0 / the call throws,
ok = false,nativeStatusrecords the result code, and the counters stay 0 but do not represent the real values - Counters are accounted per
(主站, 从站); they are cleared on master Close / context re-initialization and do not accumulate across sessions
Typical usage:
CoE.SdoStats before = coe.getSdoStats();
coe.sdoReadAsync((short) 0x6041, (byte) 0).get();
CoE.SdoStats after = coe.getSdoStats();
boolean sentOnce = before.ok && after.ok
&& (after.requests - before.requests) == 1
&& (after.retries - before.retries) == 0;
Mailbox statistics
CoE implements the unified IMailboxProtocol interface and provides mailbox transaction statistics.
| Category | Method | Type | Read/write | Description |
|---|---|---|---|---|
| Protocol identity | getProtocolType() | byte | read-only | Protocol type constant (CoE=0x03) |
| getProtocolName() | String | read-only | Protocol name ("CoE") | |
| isSupported() | boolean | read-only | Whether the slave supports this protocol; returns false when the capability is unknown (fail-closed) | |
| supportState() | Boolean | read-only | Capability tri-state: TRUE=supported, FALSE=confirmed not supported, null=unknown | |
| isSupportKnown() | boolean | read-only | Whether the capability conclusion is known (supportState() != null) | |
| Transaction status | getLastStatus() | MailboxStatus | read-only | Unified status of the most recent mailbox transaction |
| getLastErrorCode() | long | read-only | Protocol-layer error code of the most recent transaction (0=no error) | |
| Statistics | getStatistics() | MailboxStatistics | read-only | Mailbox statistics snapshot |
| resetStatistics() | void | write-only | Resets the mailbox statistics counters |
isSupported() reads the CoE bit of mbx_proto in SII; it returns true only when support is confirmed, and when the underlying call throws (capability unknown) it returns false and logs a WARNING instead of falling back to true. To distinguish "unknown" from "confirmed not supported", use supportState() (a Boolean tri-state) or isSupportKnown(). getLastErrorCode() returns that SDO abort code when lastSdoError != NO_ERROR, otherwise it returns the mailbox-layer error code.
Boolean state = coe.supportState();
if (state == null) {
System.out.println("CoE 能力未知(读不到 mbx_proto),既不是支持也不是不支持"); // CoE capability unknown (mbx_proto could not be read), neither supported nor unsupported
} else if (state) {
// confirmed supported
}
MailboxStatistics structure (immutable snapshot):
| Field | Type | Description |
|---|---|---|
| totalSent | long | Total number of transactions sent |
| totalReceived | long | Total number of responses received (including error frames) |
| totalTimeout | long | Total number of timeouts |
| totalMailboxError | long | Total number of mailbox error frames (MBX ERROR / SDO Abort, etc.) |
| totalProtocolError | long | Total number of protocol errors (protocol type / WKC mismatch) |
| totalCancelled | long | Total number of cancelled transactions |
| lastErrorCode | long | Most recent error code (0=none) |
| lastErrorTime | Instant | Time of the most recent error (UTC; null when there is no error) |
| averageLatencyUs | double | Average transaction latency (microseconds) |
Example:
CoE coe = slave.coe();
// Run a batch of SDO operations ...
coe.sdoRead((short) 0x6041, (byte) 0);
// Query the mailbox statistics
MailboxStatistics stats = coe.getStatistics();
System.out.printf("CoE 邮箱: 发送=%d, 接收=%d, 超时=%d, 平均延迟=%.1fus%n", // CoE mailbox: sent=%d, received=%d, timeouts=%d, average latency=%.1fus%n
stats.totalSent, stats.totalReceived, stats.totalTimeout, stats.averageLatencyUs);
// Check the status of the most recent transaction
if (coe.getLastStatus() != MailboxStatus.SUCCESS) {
System.out.printf("最近事务异常: %s (code=0x%X)%n", // Last transaction exception: %s (code=0x%X)%n
coe.getLastStatus(), coe.getLastErrorCode());
}
// Reset the statistics
coe.resetStatistics();
MailboxStatus enum
Unified status codes for mailbox transactions (shared by all mailbox protocols and mapped one-to-one to the underlying mailbox status codes).
| Name | Value | Description |
|---|---|---|
| PENDING | 0 | Pending (the transaction has not started or is still in progress) |
| SUCCESS | 1 | Completed successfully |
| TIMEOUT | -1 | Timeout (the peer did not respond within the specified time) |
| CANCELLED | -2 | Cancelled |
| MAILBOX_ERROR | -3 | Mailbox error frame (MBX ERROR or protocol-layer Abort) |
| PROTO_MISMATCH | -4 | Response protocol type mismatch |
| WKC_FAIL | -6 | The underlying working counter (WKC) does not match the expected value |
| NO_MEMORY | -7 | Out of memory |
| INVALID_ARG | -8 | Invalid argument |
| NOT_IMPLEMENTED | -9 | Not implemented / not supported |
| LINK_DOWN | -10 | Link down (frames fail immediately instead of timing out one by one); check the cable / NIC link status |
| NOT_SENT | -11 | Request never left the local host (frame never reached the wire: aborted / backoff / pool exhausted / channel closed / held by the kernel); not a slave timeout and not a slave rejection — carries no bus evidence, must not be used for slave-drop or health verdicts; callers treat it as retryable |
SDOError enum
Error codes for SDO operations (CANopen standard / ETG.1020).
| Name | Value | Description |
|---|---|---|
| NO_ERROR | 0x00000000 | No error |
| TOGGLE_BIT_NOT_CHANGED | 0x05030000 | Toggle bit did not change |
| SDO_PROTOCOL_TIMEOUT | 0x05040000 | SDO protocol timeout |
| INVALID_COMMAND_SPECIFIER | 0x05040001 | Invalid command specifier |
| INVALID_BLOCK_SIZE | 0x05040002 | Invalid block size in block transfer mode |
| INVALID_SEQUENCE_NUMBER | 0x05040003 | Invalid sequence number in block transfer mode |
| CRC_ERROR | 0x05040004 | CRC error (block transfer mode only) |
| OUT_OF_MEMORY | 0x05040005 | Out of memory |
| UNSUPPORTED_ACCESS | 0x06010000 | Unsupported access |
| READ_WRITE_ONLY_ERROR | 0x06010001 | Attempt to read a write-only object |
| WRITE_READ_ONLY_ERROR | 0x06010002 | Attempt to write a read-only object |
| SUBINDEX_WRITE_ERROR | 0x06010003 | The subindex does not allow writing |
| COMPLETE_ACCESS_NOT_SUPPORTED | 0x06010004 | Complete Access not supported |
| OBJECT_LENGTH_EXCEEDED | 0x06010005 | Object length exceeded |
| OBJECT_MAPPED_TO_RXPDO | 0x06010006 | Object is already mapped to an RxPDO |
| OBJECT_DOES_NOT_EXIST | 0x06020000 | Object does not exist |
| CANNOT_BE_MAPPED_TO_PDO | 0x06040041 | Cannot be mapped to PDO |
| EXCEEDS_PDO_LENGTH | 0x06040042 | Exceeds the PDO length |
| PARAMETER_INCOMPATIBILITY | 0x06040043 | Parameter incompatibility |
| INTERNAL_INCOMPATIBILITY | 0x06040047 | Internal incompatibility |
| HARDWARE_ACCESS_ERROR | 0x06060000 | Hardware access error |
| DATA_TYPE_MISMATCH | 0x06070010 | Data type mismatch |
| DATA_TYPE_TOO_HIGH | 0x06070012 | Data type length too high |
| DATA_TYPE_TOO_LOW | 0x06070013 | Data type length too low |
| SUBINDEX_DOES_NOT_EXIST | 0x06090011 | Subindex does not exist |
| VALUE_RANGE_EXCEEDED | 0x06090030 | Value out of range |
| VALUE_TOO_HIGH | 0x06090031 | Value too high |
| VALUE_TOO_LOW | 0x06090032 | Value too low |
| MODULE_IDENT_LIST_MISMATCH | 0x06090033 | Module list mismatch |
| MAX_LESS_THAN_MIN | 0x06090036 | Maximum is less than minimum |
| RESOURCE_NOT_AVAILABLE | 0x060A0023 | Resource not available (SDO connection) |
| GENERAL_ERROR | 0x08000000 | General error |
| DATA_TRANSFER_ERROR | 0x08000020 | Data cannot be transferred or stored to the application (reported by the device) |
| LOCAL_CONTROL_ERROR | 0x08000021 | Data cannot be transferred or stored because of local control (reported by the device) |
| DEVICE_STATE_ERROR | 0x08000022 | Data cannot be transferred or stored because of the present device state (reported by the device) |
| DICTIONARY_ERROR | 0x08000023 | Dictionary error |
| LOCAL_REQUEST_NOT_SENT | 0x0D000001 | Request not sent (local reject): no frame went on the bus; not an abort code reported by the device |
| UNKNOWN_ERROR | 0xFFFFFFFF | Unknown error |
Apart from LOCAL_REQUEST_NOT_SENT, these codes are not reported by a device. They only appear when the request did not complete and the device returned no abort frame. 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 |
The codes a device reports — 0x08000020 / 0x08000021 / 0x08000022 — differ from these in both value and meaning.
ProtocolCodes.sdoAbortDescription(long) returns Chinese text; an English SDO Abort description is not currently provided. For classification and advice there are also sdoAbortCategory(long) / sdoAbortIsRetryable(long) / sdoAbortHint(long).
Look up conclusions and advice by abort code (com.darra.ethercat.statics.ProtocolCodes, all static methods):
| Category | Method | Returns | Read/write | Description |
|---|---|---|---|---|
| Description | sdoAbortDescription(long) | String | read-only | Chinese description |
| Classification | sdoAbortCategory(long) | int | read-only | 0 = access / 1 = parameter / 2 = object / 3 = data, etc. |
| Determination | sdoAbortIsRetryable(long) | boolean | read-only | true = transient error, may be retried |
| Action | sdoAbortHint(long) | String | read-only | Handling advice |
CoE.SdoReadResult r = coe.sdoRead((short) 0x6041, (byte) 0);
if (!r.ok) {
long abort = r.abortCode & 0xFFFFFFFFL;
System.out.printf("%s / %s%n",
ProtocolCodes.sdoAbortDescription(abort), ProtocolCodes.sdoAbortHint(abort));
if (ProtocolCodes.sdoAbortIsRetryable(abort)) { /* retry once */ }
}
Only transient failures such as a timeout / the mailbox not coming back are worth retrying once; do not rebuild the master for them. A deterministic abort (missing object, write to a read-only object, etc.) will not succeed on retry — fix the index or the access direction instead.
EcDataType enum
com.darra.ethercat.data.EcDataType. EtherCAT data type enum (based on ETG.1000.6 / CiA 301), mapped one-to-one to the codes in ObjectEntry.DataType (short).
| Enum value | Code | Description |
|---|---|---|
| NONE | 0x0000 | No type |
| BOOLEAN | 0x0001 | Boolean (1 bit) |
| INTEGER8 | 0x0002 | Signed 8-bit |
| INTEGER16 | 0x0003 | Signed 16-bit |
| INTEGER24 | 0x0010 | Signed 24-bit |
| INTEGER32 | 0x0004 | Signed 32-bit |
| INTEGER40 | 0x0012 | Signed 40-bit |
| INTEGER48 | 0x0013 | Signed 48-bit |
| INTEGER56 | 0x0014 | Signed 56-bit |
| INTEGER64 | 0x0015 | Signed 64-bit |
| UNSIGNED8 | 0x0005 | Unsigned 8-bit |
| UNSIGNED16 | 0x0006 | Unsigned 16-bit |
| UNSIGNED24 | 0x0016 | Unsigned 24-bit |
| UNSIGNED32 | 0x0007 | Unsigned 32-bit |
| UNSIGNED40 | 0x0018 | Unsigned 40-bit |
| UNSIGNED48 | 0x0019 | Unsigned 48-bit |
| UNSIGNED56 | 0x001A | Unsigned 56-bit |
| UNSIGNED64 | 0x001B | Unsigned 64-bit |
| REAL32 | 0x0008 | 32-bit IEEE 754 single precision |
| REAL64 | 0x0011 | 64-bit IEEE 754 double precision |
| VISIBLE_STRING | 0x0009 | Visible string (ASCII) |
| OCTET_STRING | 0x000A | Octet string |
| UNICODE_STRING | 0x000B | Unicode string |
| TIME_OF_DAY | 0x000C | Time of day |
| TIME_DIFFERENCE | 0x000D | Time difference |
| DOMAIN | 0x000F | Domain data (any length) |
| PDO_COMM_PARAM | 0x0020 | PDO communication parameter record |
| PDO_MAPPING | 0x0021 | PDO mapping parameter record |
| IDENTITY | 0x0023 | Identity object record |
| COMMAND_PAR | 0x0025 | Command object record |
| BIT1 … BIT8 | 0x0030 … 0x0037 | Bit sequence (1~8 bits) |
| UNKNOWN | 0xFFFF | Unrecognized code |
Methods:
getCode()(int) — gets the data type codeEcDataType.fromCode(int code)(static) — looks up by code; an unknown value returnsUNKNOWN(note that it is a different member fromNONE)byteSize()(int) — byte size of fixed-width types (bit width rounded up); variable-length types, record types (PDO_COMM_PARAM/PDO_MAPPING/IDENTITY/COMMAND_PAR) and codes outside the table return-1isInteger()/isFloat()/isString()(boolean) — type classification
Example:
EcDataType dt = EcDataType.fromCode(entry.DataType & 0xFFFF);
if (dt.isInteger() && dt.byteSize() > 0)
System.out.printf("%s: %d 字节%n", dt, dt.byteSize()); // %s: %d bytes%n
Protocol name:
- The authoritative protocol name is returned by
ProtocolCodes.pdoDataTypeName(int)and is a canonical uppercase name such asINT8/UINT16/REAL32/VISIBLE_STRING/BIT1/UNKNOWN. - This name is used for protocol determination, bit-width calculation, PDO encoding/decoding and cross-language semantic comparison, and it is the final display name; the Java side provides no other display alias.
- The
INTEGER8/REAL32/VISIBLE_STRINGentries in the "Enum value" column above are Java enum member names, not the authoritative protocol name strings.
ObjAccessFlags access flags
Object access permission flags (the constants live on CoE.ObjAccessFlags).
| Constant | Value | Description |
|---|---|---|
| NONE | 0x00 | No access permission |
| READ_PRE | 0x01 | Readable in PreOp |
| READ_SAFE | 0x02 | Readable in SafeOp |
| READ_OP | 0x04 | Readable in OP |
| WRITE_PRE | 0x08 | Writable in PreOp |
| WRITE_SAFE | 0x10 | Writable in SafeOp |
| WRITE_OP | 0x20 | Writable in OP |
| MAPPABLE | 0x40 | Mappable to PDO |
| BACKUP | 0x80 | Backup parameter |
| SETTINGS | 0x100 | Configuration parameter |
Combined constants: READ_ANY = 0x07, WRITE_ANY = 0x38.
Object dictionary
oDList()
public Map<Short, List<ObjectEntry>> oDList()
Gets the complete object dictionary of the slave, grouped by OD index. Internally it triggers loadODList() first; when loading fails it returns an empty Map (not null).
Related structures:
public class ObjectEntry {
public final short ODIndex; // object index
public final byte SubIndex; // subindex
public final String Name; // name
public final short DataType; // data type (see the EcDataType enum)
public final int BitLength; // bit length
public final int ObjAccess; // access permission flags (see the CoE.ObjAccessFlags constants)
}
Static helper methods (CoE.ObjAccessFlags):
ObjAccessFlags.canRead(int access)(boolean) — whether readable (anyREAD_ANYbit set)ObjAccessFlags.canWrite(int access)(boolean) — whether writable (anyWRITE_ANYbit set)ObjAccessFlags.canWritePreOp(int access)(boolean) — whether writable in PreOPObjAccessFlags.canWriteSafeOp(int access)(boolean) — whether writable in SafeOP (including PreOP inheritance)ObjAccessFlags.canWriteOp(int access)(boolean) — whether writable in OP (including PreOP / SafeOP inheritance)ObjAccessFlags.getAccessDescription(int access)(String) — gets the Chinese access permission description
ObjectEntry instance methods:
| Method | Returns | Description |
|---|---|---|
| getByteLength() | int | byte count with the bit length rounded up |
| getDatatype() | short | data type code (same as the DataType field) |
| canRead() / canWrite() | boolean | determined from this entry's ObjAccess |
| (no instance method) | — | Per-state write permissions only have static entry points ObjAccessFlags.canWritePreOp(entry.ObjAccess) / canWriteSafeOp(...) / canWriteOp(...); ObjectEntry does not provide instance methods with these names |
| isReadOnly() | boolean | canRead() && !canWrite() |
| (no instance method) | — | The permission description goes through the static entry point ObjAccessFlags.getAccessDescription(entry.ObjAccess) |
| getBytes() | byte[] | reads raw bytes |
| setBytes(byte[]) | void | writes raw bytes |
| getValue(Class<T>) | T | typed read |
| readInt8() / readInt16() / readInt32() / readFloat() / readString() | the corresponding wrapper type | convenience shorthand for getValue(...) |
| toString() | String | format like OE(0x6041:00 Statusword 只读) |
getBytes() semantics (different from sdoRead, important):
- When
!canRead(), it throwsCoEAccessDeniedExceptionand sends no bus frame. - When the underlying
sdoReadfails, it folds tonew byte[0]— the caller cannot distinguish "read failed" from "genuinely empty object" from the return value. To distinguish them, usesdoRead(index, subIndex)and check the result object'sok, or checkgetLastSdoError()after the read. - The Java side has no "with success flag" counterpart such as
tryGetBytes.
setBytes(byte[]) semantics:
dataisnullor has length 0 → throwsIllegalArgumentException("写入数据不能为空")(SDK output, = write data must not be empty).!canWrite()→ throwsCoEAccessDeniedException: whenObjAccesshas no write bit it is intercepted before any frame is sent, so no bus frame goes out.- An underlying write failure is split by the same criterion (the only implementation on the Java side =
CoE.isAccessDeniedAbort(int, boolean)): the descriptor permission-bit branch aligns with the Flags branch of C#ObjectEntry.CheckWriteAccess, and the device-abort branch with step ① of Cec_coe_classify_access_denied/ C++EvaluateCoEAccess(C#ObjectEntrytakes no abort argument and does not implement that branch):- The device's SDO abort explicitly refuses —
0x06010000(unsupported object access) /0x06010002(write to a read-only object) → throwsCoEAccessDeniedException, with a message like对象条目 0x6041:00 写被拒绝: 设备 SDO Abort 0x06010002 (WRITE_READ_ONLY_ERROR); here the frame has already been sent and the conclusion comes from the slave. - Everything else — transfer timeout
0x05040000, object does not exist0x06020000, subindex does not exist0x06090011, type mismatch0x06070010, locally not sent0x0D000001, and the write direction of0x06010001→ throwsCoEAbortException, with the native abort code inabortCode. These failures only mean this transfer did not succeed; they do not mean the device refused access permission.
- The device's SDO abort explicitly refuses —
- A single write call throws only once: the exception type is the conclusion, so there is no need to read
getLastSdoError()to guess the cause.
getValue(Class<T>) semantics:
- Supported types:
Byte/byte,Short/short,Integer/int,Long/long,Float/float,Double/double,String,byte[]. - Internally it calls
getBytes()first, so when!canRead()it throwsCoEAccessDeniedException. - If the byte count is less than the type width, the type is unsupported, or decoding fails → returns
null. Integer: ≥ 4 bytes decodes as int32, otherwise ≥ 2 bytes decodes as uint16;Long: ≥ 8 bytes decodes as int64, otherwise ≥ 4 bytes decodes as uint32.String: the mode is determined by this entry's ownDataType(VISIBLE_STRING/OCTET_STRING= single-byte ISO-8859-1,UNICODE_STRING= UTF-16LE), and the byte-level decoding is done by the underlying layer. If the type is not a string / the code is unknown → returnsnullwithout guessing an encoding.
Example (read/write by entry):
CoE.EntryDescriptionResult oe = coe.getEntryDescription((short) 0x6041, (byte) 0);
CoE.ObjectEntry entry = oe.ok ? oe.value : null;
if (entry != null && entry.canRead()) {
byte[] raw = entry.getBytes(); // failure folds to byte[0]
if (raw.length == 0 && coe.getLastSdoError() != SDOError.NO_ERROR) {
System.out.printf("读取失败: %s%n", coe.getLastSdoError()); // Read failed: %s%n
}
Short value = entry.readInt16(); // failure / insufficient length → null
}
Example:
Map<Short, List<CoE.ObjectEntry>> od = coe.oDList();
for (Map.Entry<Short, List<CoE.ObjectEntry>> entry : od.entrySet()) {
List<CoE.ObjectEntry> subEntries = entry.getValue();
if (!subEntries.isEmpty()) {
CoE.ObjectEntry first = subEntries.get(0);
System.out.printf("0x%04X: %s%n", entry.getKey() & 0xFFFF, first.Name);
// Check the access permissions
for (CoE.ObjectEntry sub : subEntries) {
boolean readable = CoE.ObjAccessFlags.canRead(sub.ObjAccess);
boolean writable = CoE.ObjAccessFlags.canWrite(sub.ObjAccess);
System.out.printf(" [%d] %s (R=%b, W=%b)%n",
sub.SubIndex, sub.Name, readable, writable);
}
}
}
Object dictionary tree structure
loadODList()
public EcODList loadODList()
public EcODList loadODList(boolean preferEsi)
Loads the complete object dictionary tree structure (synchronous).
loadODList()=loadODList(false): really issues SDO Information (does not use ESI / the preloaded cache).loadODList(true): checks the bound ESI directory first (only names + subindices, 0 mailbox traffic) and falls back to SDO Information on a miss; on a hit it then reads the mandatory objects of the communication area 0x1000–0x1FFF (0x1000 / 0x1001 / 0x1018).
The first call reads from the slave; repeated calls within 2 seconds reuse the previous result, and an earlier cache is also reused directly when the structure is complete.
Returns: EcODList; returns null when loading fails or 0 objects are found (an empty table is not treated as success).
loadODListAsync()
public CompletableFuture<EcODList> loadODListAsync()
public CompletableFuture<EcODList> loadODListAsync(boolean preferEsi)
Loads the object dictionary asynchronously. The no-argument version is equivalent to loadODListAsync(false) (really issues SDO Information).
Behavior:
- Loading already in progress (single-flight) → does not start a second one and returns the same future for the same load; every caller gets the real result of that same load, so "loading" is never mistaken for "loaded but no data"
- An empty dictionary is not success: when 0 objects are found the future completes with
null; do not treatgetCount()==0as a successful load preferEsi=false(default): fully loads the subindex entries of every objectpreferEsi=true: 0 mailbox traffic on an ESI hit; when falling back to SDO on an ESI miss, subindices are loaded one by one only in PreOp, while in OP / SafeOp only object-level information (name, etc.) is taken and each object description is not scanned
EcODList methods:
getCount()(int) — number of objectsget(short index)(ObjectDictionary) — gets by OD index; throwsNoSuchElementExceptionwhen it does not exist (not returning null)get(int index)(ObjectDictionary) — matches by OD index first and, on a miss, fetches by positional index; throwsNoSuchElementExceptionwhen neither existsget(String key)(ObjectDictionary) — gets by name or index string; throwsNoSuchElementExceptionwhen it does not exist- Parsing rules:
"0x6041"as hexadecimal; a string of length ≤ 4 (such as"6041") is also parsed as hexadecimal; a longer all-digit string as decimal; anything else is matched by name (case-insensitive)
- Parsing rules:
containsKey(short)/containsKey(String)(boolean) — checks whether the index / name existsgetFullList()(List<ObjectDictionary>) — immutable complete listiterator()— implementsIterable<ObjectDictionary>and can be used directly in for-eachcopy()(EcODList) — deep-copies a cached instance
ObjectDictionary fields/methods:
| Field | Type | Description |
|---|---|---|
| Index | short | object index |
| Name | String | object name |
| Datatype | short | data type code (EcDataType enum) |
| ObjectCode | byte | object type (0x07=VAR, 0x08=ARRAY, 0x09=RECORD) |
| MaxSub | byte | maximum subindex |
getCount()(int) — number of subindex entriesgetOEList()(OEDictionary) — collection of subindex entries (Iterable<ObjectEntry>)get(byte)/get(int)/get(String)(ObjectEntry) — gets an entry by subindex number / name; throwsNoSuchElementExceptionwhen it does not existcontainsKey(byte)/containsKey(String)(boolean) — checks whether the subindex / name existsisVar()/isArray()/isRecord()(boolean) — determined fromObjectCodereadAll()(Map<Byte, byte[]>) — iterates all subindices callinggetBytes()on each; entries whose individual read fails are skipped and logged as WARNING (no exception is thrown and they are not silently swallowed), and thebyte[0]folded out of a failure never enters the resultsdoWrite(byte subIndex, byte[] data)(boolean) — convenience write of one subindex of this object; returnsfalsewhendataisnull/ emptycopy()(ObjectDictionary) — cached copy
OEDictionary methods:
getCount()(int) — number of entriesget(byte)/get(int)(ObjectEntry) — gets by subindex number; throwsNoSuchElementExceptionwhen it does not existget(String)(ObjectEntry) — gets by name or index string; throwsNoSuchElementExceptionwhen it does not existcontainsKey(byte)/containsKey(String)(boolean)getByPosition(int)(ObjectEntry) — gets by list position; throwsIndexOutOfBoundsExceptionwhen out of rangeiterator()— can be used directly in for-each
Example:
CoE.EcODList odList = coe.loadODList();
if (odList == null || odList.getCount() == 0) {
System.out.printf("对象字典加载失败: %s%n", coe.getLastSdoError()); // Object dictionary load failed: %s%n
return;
}
for (CoE.ObjectDictionary od : odList) {
System.out.printf("0x%04X: %s (子索引=%d)%n", // 0x%04X: %s (subindex=%d)%n
od.Index & 0xFFFF, od.Name, od.getCount());
}
Helper methods:
isODListLoading()(boolean) — whether the object dictionary is being loaded asynchronouslygetODList()(EcODList) — gets the loaded OD list (returnsnullif not loaded)getCount()(int) — number of loaded objectscontainsKey(short index)/containsKey(String key)(boolean) — checks whether the given index / name existsgetSlaveIndex()(short) — gets the slave index
Reading the object dictionary directly through SDO Information
The following methods pull the OD tree directly from the slave in real time through the CoE SDO Information Service and do not reuse the loadODList() cache. They suit scenarios that need real-time OD metadata.
The old signatures that returned List<ObjectDictionary> / ObjectDictionary / ObjectEntry directly have been removed; they now return result objects carrying ok / abortCode / wkc, and the values are taken from result.objects / result.value.
loadObjectDictionary()
public CoE.OdListResult loadObjectDictionary()
Loads the complete object dictionary directly through the SDO Information Service (pulling the OD index + details from the slave in real time on every call).
Related structures:
public static class OdListResult {
public boolean ok; // true = a parseable object list was obtained
public List<ObjectDictionary> objects; // object list; null on failure (an empty list = ok=true + empty list)
public int abortCode; // device SDO Info ErrorCode (0 = the device did not return an Info Error)
public int wkc; // innermost mailbox transaction result: 1=success, 0=failure/not executed
}
When ok=false, objects=null, so a failure is never disguised as an empty table. abortCode comes from the SDO Info Error frame returned by the device (the raw 16-bit value; codes outside the table are passed through unchanged); transport-layer failures do not fabricate an abort code. wkc is the result of the most recent / innermost mailbox transaction, taking the worst one across multiple transactions.
getObjectDescription(short index)
public CoE.ObjectDescriptionResult getObjectDescription(short index)
Reads the description of a single object (SDO Info Service 0x03).
public static class ObjectDescriptionResult {
public boolean ok; // true = the object description was read
public ObjectDictionary value; // metadata (without subentries); null on failure
public int abortCode; // device SDO Info ErrorCode (0 = no Info Error returned)
public int wkc; // 1=success, 0=failure/not executed
}
value contains Index / Name / Datatype / ObjectCode / MaxSub.
Example:
CoE.ObjectDescriptionResult desc = coe.getObjectDescription((short) 0x6041);
if (desc.ok)
System.out.printf("%s type=0x%04X subs=%d%n",
desc.value.Name, desc.value.Datatype & 0xFFFF, desc.value.MaxSub & 0xFF);
else
System.out.printf("读取失败: abort=0x%04X wkc=%d%n", desc.abortCode, desc.wkc); // Read failed: abort=0x%04X wkc=%d%n
getEntryDescription(short index, byte subindex)
public CoE.EntryDescriptionResult getEntryDescription(short index, byte subindex)
Reads the description of a single subindex (SDO Info Service 0x05).
public static class EntryDescriptionResult {
public boolean ok; // true = the subentry description was read
public ObjectEntry value; // subentry description; null on failure
public int abortCode; // device SDO Info ErrorCode (0 = no Info Error returned)
public int wkc; // 1=success, 0=failure/not executed
}
value contains DataType / BitLength / ObjAccess / Name.
Example:
CoE.EntryDescriptionResult entry = coe.getEntryDescription((short) 0x1A00, (byte) 1);
if (entry.ok)
System.out.printf("sub1: %s, bits=%d%n", entry.value.Name, entry.value.BitLength);
Device profile
getDeviceProfile()
public int getDeviceProfile()
Reads the device profile number (the low 16 bits of 0x1000 Device Type). For example, a CiA 402 servo returns 402 and a CiA 401 I/O module returns 401. Returns 0 when the read fails.
getCiA402() / getCiA401()
public Object getCiA402()
public Object getCiA401()
When getDeviceProfile() matches 402 / 401, returns the current CoE instance (which can keep operating on CiA objects with SDO), otherwise returns null. The declared return type is Object, so you must cast before using CoE methods:
Object o = coe.getCiA402();
if (o instanceof CoE) {
CoE asCoE = (CoE) o; // only then can you call asCoE.sdoRead(...)
}
Day to day, use slave.cia402() / slave.cia401() directly (see slave properties and methods). Corresponding protocol pages: CiA 402 / CiA 401.
Complete Access data parsing
parseCompleteAccessData(byte[] caData, ObjectDictionary od)
public static Map<Integer, byte[]> parseCompleteAccessData(byte[] caData, ObjectDictionary od)
Splits the packed raw bytes read by sdoRead(..., completeAccess=true) by subindex (ETG.1000.6 §5.6.2). Rules: SubIndex 0 is always padded to 16 bits (2 bytes); bit types (BOOLEAN and BIT1..BIT8) are packed contiguously, and the next non-bit type starts at the next byte boundary.
Parameters:
caData(byte[]) — raw bytes read by Complete Accessod(ObjectDictionary) — the corresponding object dictionary entry (its OE list must already be loaded)
Returns:
Map<Integer, byte[]>— byte arrays split by subindex (key = the actual subindex number, not the positional index)- returns an empty Map when
caDataisnull/ empty, orodisnull/ has no subindex entries - when a subindex is out of range in
caData, that subindex does not appear in the result (no exception is thrown)
Diagnostic messages
readDiagnosticMessages()
public List<DiagnosticMessage> readDiagnosticMessages()
Reads the 0x10F3 diagnostic history messages (ETG.1510). It first reads 0x10F3:00 as the message count, then reads subindices 1..N in order, reading message by message according to the count declared by the device with no truncation (the count is a uint8, up to 255 messages); suited to offline diagnostics or a snapshot at a fault site.
When reading fails or the count cannot be read, it returns an empty list (failures are logged as ERROR and not thrown to the caller) — an empty list can mean either "no messages" or "read failed"; when you need to distinguish them, use the incremental primitives below and check for DiagnosticPollResult.Failed returned by pollHasNewDiagnostic() ("not read", which is not the same as "no new messages").
readDiagnosticMessages() fills fields in message byte order: the first 4 bytes go into DiagCode, the next 2 into Flags, and the next 2 into TextIndex, which does not match the semantics of these three field names. When you need semantic values, parse RawData (the raw 0x10F3 message bytes) yourself and do not rely directly on DiagCode / Flags / TextIndex. This mismatch is pending correction.
Note: this method and readDiagnosticMessage(int, int) below use different subindex ranges (1..N for this method, 6..255 for the incremental primitive); do not mix results from the same scan.
Related structures:
public static class DiagnosticMessage {
public final byte SubIndex; // subindex
public final int DiagCode; // diagnostic code
public final short Flags; // flags
public final short TextIndex; // text index
public final byte[] RawData; // raw data
}
New diagnostic history API (0x10F3)
Based on the ETG.1020 §16 definition, this implements incremental polling access to the diagnostic history through four lightweight operations — "is there a new message / metadata / single message / acknowledge processed" — which suits high-frequency runtime monitoring better than scanning many records at once with readDiagnosticMessages().
readDiagnosticMessages()— scans the diagnostic history once per call (up to 255 records); suited to offline analysis and fault-site dumpspollHasNewDiagnostic+readDiagnosticMeta+readDiagnosticMessage+acknowledgeDiagnostic— polling + on-demand reads + per-record acknowledgement; suited to runtime monitoring and ring buffer management
pollHasNewDiagnostic()
public DiagnosticPollResult pollHasNewDiagnostic()
Quickly polls the 0x10F3:04 NewAvailable flag. It does not read the full history when there are no new messages, which suits high-frequency polling at 1~10 Hz.
Returns: the DiagnosticPollResult tri-state enum (not a bare int):
DiagnosticPollResult.HasNew— there is a new diagnostic message (overwrite mode) or an unacknowledged message (acknowledge mode)DiagnosticPollResult.None— no new messages (including the case where the slave does not support 0x10F3; the underlying layer groups abort 0x06020000 into this bucket)DiagnosticPollResult.Failed— communication failure / not read (timeout / WKC=0 / call exception)
The tri-state cannot be collapsed: Failed means "not read", not "no new messages" — do not treat Failed as None and keep running.
DiagnosticPollResult enum
public enum DiagnosticPollResult {
HasNew(1), // there is a new message / an unacknowledged message
None(0), // no new messages (including a slave that does not support 0x10F3)
Failed(-1); // communication failure / not read
public int getValue(); // stable encoding 1 / 0 / -1
public static DiagnosticPollResult fromNative(int v); // anything other than 1/0/-1 maps to Failed
}
getValue() is only a stable encoding (1 / 0 / -1) of the same value as the underlying return value; for day-to-day decisions, compare the enum variants directly.
readDiagnosticMeta()
public DiagMeta readDiagnosticMeta()
Reads the 0x10F3 metadata (MaxMessages / NewestMessage / NewestAcknowledged / Flags).
Returns:
DiagMeta— metadata object; returnsnullon communication failure
DiagMeta
public static class DiagMeta {
public int maxMessages; // 0x10F3:01 maximum number of messages supported by the slave
public int newestMessage; // 0x10F3:02 subindex of the newest message
public int newestAcknowledged; // 0x10F3:03 newest subindex acknowledged by the user
public int flags; // 0x10F3:05 bit4 = 0 Overwrite / 1 Acknowledge, bit5 = Overrun
}
Per ETG.1020 v1.5.0 Table 49, flags (0x10F3:05) is defined as:
bit4= diagnostic buffer mode: 0 = Overwrite / 1 = Acknowledgebit5= 1 means Overrun occurred (the ring buffer has overwritten unread messages)
How to read it: in Overwrite mode the slave keeps 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: the Java 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.
readDiagnosticMessage(int msgIdx, int bufSize)
public byte[] readDiagnosticMessage(int msgIdx, int bufSize)
Reads the raw bytes of the diagnostic message at the given subindex (6..255).
Parameters:
msgIdx(int) — message subindex (6..255)bufSize(int) — receive buffer size in bytes, valid range 1..8192
Returns:
byte[]— the bytes actually read (length = the amount actually written); returnsnullon communication failure- returns
byte[0](notnull) when the read succeeds with length 0
Throws:
- a
bufSizeoutside 1..8192 throwsIllegalArgumentExceptionand never silently falls back to a default
acknowledgeDiagnostic(int msgIdx)
public boolean acknowledgeDiagnostic(int msgIdx)
Acknowledges that messages up to the given subindex have been processed. In Acknowledge mode (flags bit4 = 1) the slave advances its acknowledged position and clears messages <= msgIdx; in Overwrite mode (bit4 = 0) this write carries no decision weight.
Parameters:
msgIdx(int) — the last subindex to acknowledge
Returns:
boolean— returnstrueon success
Complete example (runtime polling):
CoE coe = slave.coe();
// 1. Query the buffer mode
CoE.DiagMeta meta = coe.readDiagnosticMeta();
if (meta == null) return;
boolean isAckMode = ((meta.flags >> 4) & 0x01) != 0;
boolean overrun = ((meta.flags >> 5) & 0x01) != 0;
System.out.printf("MaxMsg=%d, AckMode=%b, Overrun=%b%n",
meta.maxMessages, isAckMode, overrun);
// 2. Poll periodically (for example, once every 100 ms)
DiagnosticPollResult poll = coe.pollHasNewDiagnostic();
if (poll == DiagnosticPollResult.Failed) {
// Not read ≠ no new messages: log it / retry next cycle; do not treat it as "no diagnostics" and keep running
return;
}
if (poll == DiagnosticPollResult.HasNew) {
CoE.DiagMeta m2 = coe.readDiagnosticMeta();
if (m2 != null) {
// In Overwrite mode newestAcknowledged stays 0 by specification and is not a read cursor;
// only Acknowledge mode starts from acked+1
int first = ((m2.flags >> 4) & 0x01) != 0 ? m2.newestAcknowledged + 1 : 6;
for (int idx = first; idx <= m2.newestMessage; idx++) {
byte[] raw = coe.readDiagnosticMessage(idx, 256);
if (raw != null && raw.length >= 8) {
int diagCode = (raw[0] & 0xFF) | ((raw[1] & 0xFF) << 8)
| ((raw[2] & 0xFF) << 16) | ((raw[3] & 0xFF) << 24);
System.out.printf("Diag[%d]: code=0x%08X, %d 字节%n", // Diag[%d]: code=0x%08X, %d bytes%n
idx, diagCode, raw.length);
}
}
coe.acknowledgeDiagnostic(m2.newestMessage);
}
}
readDiagnosticMessages() returns List<CoE.DiagnosticMessage>, which can be used directly with .stream(). com.darra.ethercat.sugar.DiagnosticStream provides static factories: diagnostics(slave) / diagnosticsByCode(slave, int) / diagnosticsBySeverity(slave, short) / latestDiagnostics(slave, int); on the EMCY side there are emergencies(slave) / emergenciesByCode(...) / emergenciesByRegister(...) / recentEmergencies(...).
Access permissions
ObjAccessFlags
Provides static methods for object access permission checks (the constants and static methods all live on CoE.ObjAccessFlags):
canRead(int access)— whether readablecanWrite(int access)— whether writablecanWritePreOp(int access)— whether writable in PreOPcanWriteSafeOp(int access)— whether writable in SafeOP (including PreOP inheritance)canWriteOp(int access)— whether writable in OP (including PreOP / SafeOP inheritance)getAccessDescription(int access)— gets the Chinese access permission description
isAccessDeniedAbort(int abortCode, boolean isRead)
public static boolean isAccessDeniedAbort(int abortCode, boolean isRead)
Determines whether an SDO Abort means the device explicitly refused this access (a pure function that does not touch native code and can be unit-tested offline). This is the only implementation of that criterion in the Java SDK, corresponding to the device branch of C ec_coe_classify_access_denied and step ① of C++ EvaluateCoEAccess: 0x06010000 counts as a refusal for both read and write; 0x06010001 counts as a refusal for read only; 0x06010002 counts as a refusal for write only. Other aborts (0x05040000 timeout / 0x06020000 object does not exist / 0x06070010 type mismatch / 0x08000000 generic, etc.) are not access denials.
abortCode(int) — the SDO Abort code the device returned unchanged (0 = the device returned no abort code)isRead(boolean) —true= read operation,false= write operation- returns
boolean—true= the device explicitly refused this access
Emergencies
getEmergencyHistory()
public List<EmergencyMessage> getEmergencyHistory() // full history (up to 256 records), oldest → newest; returns an empty list on failure
Gets the emergency history. Returns the entire history recorded so far (ring capacity 256 records, overwriting the oldest when full) in time order, oldest → newest. On failure (no EMCY records / read exception) it returns an empty list without throwing — an empty list can mean either "no EMCY" or "read failed" (a read failure is logged as ERROR).
clearEmergencyHistory()
public void clearEmergencyHistory()
Clears the emergency history.
Related structures:
public static class EmergencyMessage {
public final short ErrorCode; // error code
public final byte ErrorRegister; // error register
public final byte[] Data; // additional data
public final short SlaveIndex; // slave index
public final long Timestamp; // timestamp
}
Example:
List<CoE.EmergencyMessage> history = coe.getEmergencyHistory();
for (CoE.EmergencyMessage msg : history) {
System.out.println(msg);
}
coe.clearEmergencyHistory();
To get the message in the same cycle a fault occurs, subscribe with slave events: slave.events().addEmergencyListener((errorCode, errorReg, b1, w1, w2) -> ...). The Chinese description of an error code is available from ProtocolCodes.emcyDescription(int). This history is the master-side emergency record and is not the same data as the error history in slave object dictionary 0x1003.
CoEEmcyRecorder
CoEEmcy.CoEEmcyRecorder is an in-process ring recorder for emergency messages: the caller feeds the messages in itself (tests / offline replay); the default capacity is 256 records and it is thread-safe. It neither reads nor affects the master's emergency message history — use getEmergencyHistory() when you need the master history. Both the constructor and the capacity setter require a minimum of 1; a value below 1 throws IllegalArgumentException.
The type is marked deprecated (@Deprecated); new code should use getEmergencyHistory() / clearEmergencyHistory(). The recorder itself still compiles and runs, so existing code can keep using it.
public static class CoEEmcyRecorder {
public CoEEmcyRecorder(int slaveIndex)
public CoEEmcyRecorder(int slaveIndex, int maxHistorySize)
}
| Category | Method | Type/Returns | Read/write | Description |
|---|---|---|---|---|
| Record | recordEmergency | void | call | Builds one message from the error code, error register and vendor bytes and adds it to the ring |
| Query | getHistory | List<EmergencyMessage> | call | Returns a copy of the history, oldest → newest |
| Capacity | maxHistorySize | int | call | Reads the current maximum history capacity |
| Capacity | maxHistorySize(int) | void | call | Sets the maximum capacity (minimum 1); shrinking it trims the oldest records |
recordEmergency(int errorCode, int errorReg, int b1, int w1, int w2)
public void recordEmergency(int errorCode, int errorReg, int b1, int w1, int w2)
Builds and records one emergency message from raw fields. errorCode keeps the low 16 bits and errorReg the low 8 bits; b1 occupies 1 byte, w1 / w2 occupy 2 bytes each in little-endian order, and together they form the 5 bytes of vendor data. The timestamp is the moment of recording.
Parameters:
errorCode(int) — emergency error code (CiA 301)errorReg(int) — error register (object0x1001)b1(int) — vendor-specific bytew1(int) — vendor-specific word 1w2(int) — vendor-specific word 2
Returns: none (void). When the record is full, the oldest one is overwritten.
getHistory()
public List<EmergencyMessage> getHistory()
Returns a copy of the current records (a new list), oldest → newest. Modifying the returned list does not affect the recorder.
Returns:
List<EmergencyMessage>— a copy of the history; an empty list when nothing is recorded
maxHistorySize()
public int maxHistorySize()
public void maxHistorySize(int value)
Reads or sets the maximum history capacity. Setting a smaller capacity trims the oldest records immediately until the number of records no longer exceeds the new capacity.
Parameters:
value(int) — the new capacity, minimum 1; a value below 1 throwsIllegalArgumentException
Returns:
- the no-argument version returns
int— the current maximum capacity - the version with an argument returns nothing (
void)
Example:
CoEEmcy.CoEEmcyRecorder recorder = new CoEEmcy.CoEEmcyRecorder(slave.SlaveNum, 64);
recorder.recordEmergency(0x2310, 0x01, 0x00, 0x0000, 0x0000);
List<CoEEmcy.EmergencyMessage> history = recorder.getHistory();
System.out.printf("记录 %d 条, 容量 %d%n", history.size(), recorder.maxHistorySize()); // %d records, capacity %d%n
recorder.maxHistorySize(16); // Keeps only the last 16 entries
Exception types
CoEAccessDeniedException
public static class CoEAccessDeniedException extends RuntimeException {
public final int Index; // object index
public final int SubIndex; // subindex
public final String EntryName; // entry name
public final boolean IsReadOperation; // true=read, false=write
public final int ObjAccess; // access permission flags
}
Thrown when CoE object access is denied. Two sources:
- Local interception on the SDK side:
ObjectEntry.getBytes()/setBytes(...)throws whenObjAccesslacks the permission bit for that direction; it is intercepted before any frame is sent, so no bus frame goes out. - Explicit device refusal:
ObjectEntry.setBytes(...)throws when the underlying write fails and the device abort is0x06010000(unsupported object access) or0x06010002(write to a read-only object); the message carries the device abort code. Here the frame has already been sent and the conclusion comes from the slave.
The descriptor permission-bit branch of the criterion aligns with C# ObjectEntry.CheckWriteAccess, and the device-abort branch with step ① of C ec_coe_classify_access_denied / C++ EvaluateCoEAccess (C# ObjectEntry takes no abort argument and does not implement that branch); the only implementation on the Java side is CoE.isAccessDeniedAbort(int, boolean). Other abort codes (timeout 0x05040000 / object does not exist 0x06020000 / type mismatch 0x06070010 etc.) are not access denial and go to CoEAbortException.
Example:
try {
CoE.EntryDescriptionResult oe = coe.getEntryDescription((short) 0x1C12, (byte) 0);
// oe.value.setBytes(...) throws when permissions are insufficient
} catch (CoE.CoEAccessDeniedException ex) {
System.out.printf("对象 0x%04X:%02X (%s) 当前不可访问%n", // Object 0x%04X:%02X (%s) is currently inaccessible%n
ex.Index, ex.SubIndex, ex.EntryName);
}
createWithCustomMessage(int index, int subIndex, String customMessage, boolean isReadOperation, int objAccess)
public static CoEAccessDeniedException createWithCustomMessage(
int index, int subIndex, String customMessage,
boolean isReadOperation, int objAccess)
Static factory: creates an access-denied exception with custom message text. Compared with the instances thrown normally, only getMessage() and EntryName differ — both use customMessage; Index / SubIndex / IsReadOperation / ObjAccess are still stored as passed in. Use it when business context should go into the exception while callers still handle it as the same type.
Parameters:
index(int) — object indexsubIndex(int) — subindexcustomMessage(String) — custom exception message, also written intoEntryNameisReadOperation(boolean) —true= read operation,false= write operationobjAccess(int) — access permission flags (anObjAccessFlagsvalue)
Returns:
CoEAccessDeniedException— the newly created exception instance (this method only creates it and does not throw)
Example:
try {
// Wrap a failed business pre-check into the same exception type with a custom message
throw CoE.CoEAccessDeniedException.createWithCustomMessage(
0x6040, 0, "驱动器未使能, 禁止写控制字", false, 0x00); // (SDK output, = drive not enabled, writing the control word is forbidden)
} catch (CoE.CoEAccessDeniedException ex) {
System.out.println(ex.getMessage()); // The drive is not enabled; writing the control word is forbidden
System.out.println(ex.EntryName); // The drive is not enabled; writing the control word is forbidden
}
CoEAbortException
public static class CoEAbortException extends RuntimeException {
public final int slaveIndex; // slave index
public final long abortCode; // SDO Abort code
}
Thrown by the convenience write entry point with no return value ObjectEntry.setBytes(byte[]) when the underlying write fails and that failure is not a "device refuses access"; it carries the raw abortCode and the slave index (typically: transfer timeout 0x05040000, object does not exist 0x06020000, subindex does not exist 0x06090011, type mismatch 0x06070010, frame not sent locally 0x0D000001). The calls with a return value, sdoRead / sdoWrite (asynchronous included), do not throw this exception: a failure completes normally with an ok=false result object and the abort code is read from the result's abortCode; only cancellation / master close completes exceptionally with CancellationException.
Complete example
Traversing the object dictionary
CoE coe = slave.coe();
// Traverse with the tree structure (an empty dictionary is not success)
CoE.EcODList odList = coe.loadODList();
if (odList == null || odList.getCount() == 0) {
System.out.printf("对象字典加载失败: %s%n", coe.getLastSdoError()); // Object dictionary load failed: %s%n
return;
}
for (CoE.ObjectDictionary od : odList) {
System.out.printf("0x%04X: %s (子索引=%d)%n", // 0x%04X: %s (subindex=%d)%n
od.Index & 0xFFFF, od.Name, od.getCount());
// Iterate the subindices
for (CoE.ObjectEntry entry : od.getOEList()) {
boolean readable = CoE.ObjAccessFlags.canRead(entry.ObjAccess);
boolean writable = CoE.ObjAccessFlags.canWrite(entry.ObjAccess);
String accessDesc = CoE.ObjAccessFlags.getAccessDescription(entry.ObjAccess);
System.out.printf(" [%d] %s (类型=0x%04X, 位长=%d, %s)%n", // [%d] %s (type=0x%04X, bit length=%d, %s)%n
entry.SubIndex, entry.Name, entry.DataType, entry.BitLength, accessDesc);
}
}
// Access by index — get(...) throws NoSuchElementException when not found; check existence with containsKey first
if (odList.containsKey((short) 0x6040)) {
CoE.ObjectDictionary controlWord = odList.get((short) 0x6040);
System.out.println("控制字: " + controlWord.Name); // Control word:
// Batch-read all subindex data (failed entries are skipped)
Map<Byte, byte[]> allData = controlWord.readAll();
for (Map.Entry<Byte, byte[]> e : allData.entrySet()) {
System.out.printf(" 子索引 %d: %d 字节%n", e.getKey(), e.getValue().length); // Subindex %d: %d bytes%n
}
}
// Access by name
if (odList.containsKey("Device Type")) {
CoE.ObjectDictionary devType = odList.get("Device Type");
System.out.printf("Device Type: 0x%04X%n", devType.Index & 0xFFFF);
}