AoE (ADS over EtherCAT)
Accessed through slave.aoe(). The sub-object is created lazily and always returns an instance (never null); check whether the slave supports AoE with slave.aoe().isSupported(), and treat an unknown capability as unsupported.
Reads and writes the slave ADS data area by IndexGroup and IndexOffset, reads device information and the ADS state, and can subscribe to data changes on a cycle.
Method overview
| Category | Method | Type | Read/write | Description |
|---|---|---|---|---|
| Data read/write | read | byte[] | read-only | Reads the given length of data by IndexGroup and IndexOffset; returns null on failure |
| Data read/write | readAsync | CompletableFuture<byte[]> | read-only | Asynchronous read; the future completes with AoEProtocolException on failure |
| Data read/write | write | boolean | write-only | Writes data by IndexGroup and IndexOffset |
| Data read/write | writeAsync | CompletableFuture<Boolean> | write-only | Asynchronous write; the future completes with AoEProtocolException on failure |
| Data read/write | readWrite | byte[] | read/write | Reads and writes in one transaction (ADS ReadWrite); returns null on failure |
| Data read/write | readWriteAsync | CompletableFuture<byte[]> | read/write | Asynchronous read/write; the future completes with AoEProtocolException on failure |
| Device information | readDeviceInfo | DeviceInfo | read-only | Reads the device name and version information |
| Device status | readState | AdsState | read-only | Reads the current ADS state and device state |
| Device status | getAdsStateDescription | String | read-only | Static method; converts an ADS state code to a Chinese description |
| Device control | writeControl | boolean | write-only | Switches the target ADS state and device state |
| Data subscription | subscribe(indexGroup, indexOffset, dataLength, callback, cycleTimeMs) | int | write-only | Subscribes to data changes on a cycle; returns the notification handle, or -1 on failure |
| Data subscription | unsubscribe | boolean | write-only | Cancels the subscription of the specified handle |
| Data subscription | unsubscribeAll | void | write-only | Cancels all subscriptions and clears the local handles |
| Data subscription | getActiveSubscriptions | int[] | read-only | List of handles of the currently active subscriptions |
| ADS commands | sendCommand | byte[] | read/write | Sends a raw ADS command; normal reads, writes and subscriptions do not need it |
| Routing configuration | setConfig | boolean | write-only | Sets the target / source AMS NetID and port |
| Routing configuration | initializeSlaveNetId | boolean | write-only | Writes the NetID into the slave ADS routing table during INIT→PreOp |
| Routing configuration | getConfig | AoEConfig | read-only | Reads the current AMS NetID and port configuration |
| Cross-protocol gateway | readCoEViaAoE / writeCoEViaAoE | byte[] / boolean | read/write | Accesses CoE objects through the AoE route (IndexGroup=0xF302) |
| Cross-protocol gateway | readSoEViaAoE / writeSoEViaAoE | byte[] / boolean | read/write | Accesses SoE IDNs through the AoE route (IndexGroup=0xF420) |
| Capability | isSupported | boolean | read-only | Whether the slave supports AoE; returns false when the capability is unknown |
| Capability | supportState | Boolean | read-only | Tri-state capability: TRUE = supported, FALSE = confirmed unsupported, null = unknown |
| Capability | isSupportKnown | boolean | read-only | Whether the capability verdict is known (supportState() != null) |
| Transaction status | getLastStatus | MailboxStatus | read-only | Unified status of the most recent mailbox transaction |
| Transaction status | getLastErrorCode | long | read-only | Most recent protocol-layer error code (0 = no error) |
| Statistics | getStatistics | MailboxStatistics | read-only | Mailbox statistics snapshot |
| Statistics | resetStatistics | void | write-only | Resets the mailbox statistics counters |
Interface details
Overloads without a timeoutUs parameter use a fixed default timeout of 500000 microseconds (0.5 seconds). That default is a fixed constant and is not exposed as a public property; use the overload that takes timeoutUs when a custom timeout is needed. subscribe / unsubscribe / unsubscribeAll / setConfig / getConfig have no timeoutUs overload.
read(int indexGroup, int indexOffset, int length, int timeoutUs)
public byte[] read(int indexGroup, int indexOffset, int length, int timeoutUs)
public byte[] read(int indexGroup, int indexOffset, int length) // default timeout
Reads the given length of data by IndexGroup and IndexOffset (writes no data).
Parameters:
indexGroup(int) — index groupindexOffset(int) — index offsetlength(int) — expected number of bytes to read; passing0means no data is read back in this calltimeoutUs(int) — timeout in microseconds; the overload without this parameter uses the default 500000
Returns:
byte[]— the data read;nullmeans the transaction failed, or the transaction succeeded but no data was read back (length = 0). The two kinds ofnullcan be told apart withgetLastStatus(): a failure isTIMEOUTwithgetLastErrorCode()other than 0; the successfullength = 0path isSUCCESSwith error code 0.
Throws:
- Runtime exceptions propagate unchanged (the transaction status is recorded as
TIMEOUTorMAILBOX_ERRORat the same time); they are never swallowed intonull, which would make the caller mistake the failure for absent data.
Example:
byte[] status = slave.aoe().read(0x4020, 0, 4);
if (status != null) {
int value = (status[0] & 0xFF) | ((status[1] & 0xFF) << 8)
| ((status[2] & 0xFF) << 16) | ((status[3] & 0xFF) << 24);
System.out.printf("状态值: 0x%08X%n", value); // Status value: 0x%08X%n
}
readAsync(int indexGroup, int indexOffset, int length, int timeoutUs)
public CompletableFuture<byte[]> readAsync(int indexGroup, int indexOffset, int length, int timeoutUs)
public CompletableFuture<byte[]> readAsync(int indexGroup, int indexOffset, int length)
Asynchronously reads ADS data; the task runs on defaultExecutor() (default ForkJoinPool.commonPool(), which a subclass can override with a custom thread pool).
Parameters: Same as read.
Returns:
CompletableFuture<byte[]>— the data read, available when the future completes.
Throws:
- When the synchronous read returns
null, the future completes withAoEProtocolException— including the successfullength = 0path (an empty read-back is likewise judged as a failure). For a pure write usewrite, notreadAsync(..., 0, ...). - Exceptions inside the future are wrapped once by
CompletableFuture:exceptionally/whenCompletereceive aCompletionExceptionwith the real cause inex.getCause();get()reports it in the cause of anExecutionException.
Example:
slave.aoe().readAsync(0x4020, 0, 4)
.thenAccept(data -> System.out.printf("状态长度: %d%n", data.length)) // Status length: %d%n
.exceptionally(ex -> { System.err.println("失败: " + ex.getMessage()); return null; }); // Failed:
write(int indexGroup, int indexOffset, byte[] data, int timeoutUs)
public boolean write(int indexGroup, int indexOffset, byte[] data, int timeoutUs)
public boolean write(int indexGroup, int indexOffset, byte[] data) // default timeout
Writes data by IndexGroup and IndexOffset (an ADS ReadWrite with read length 0).
Parameters:
indexGroup(int) — index groupindexOffset(int) — index offsetdata(byte[]) — the data to write;nullor length 0 is a call error and returnsfalseimmediately without starting a transactiontimeoutUs(int) — timeout in microseconds
Returns:
boolean—truewhen the write succeeds,falseon failure. With empty datagetLastStatus()=INVALID_ARGandgetLastErrorCode()=CLIENT_INVALID_PARAM(0x0741); when the transaction fails,getLastStatus()=TIMEOUTandgetLastErrorCode()is other than 0.
Throws:
- Runtime exceptions propagate unchanged (the transaction status is recorded at the same time) and are not swallowed into
false.
Example:
byte[] data = { 0x06, 0x00, 0x00, 0x00 };
slave.aoe().write(0x4020, 0, data);
writeAsync(int indexGroup, int indexOffset, byte[] data, int timeoutUs)
public CompletableFuture<Boolean> writeAsync(int indexGroup, int indexOffset, byte[] data, int timeoutUs)
public CompletableFuture<Boolean> writeAsync(int indexGroup, int indexOffset, byte[] data)
Asynchronously writes ADS data; the task runs on defaultExecutor().
Parameters: Same as write.
Returns:
CompletableFuture<Boolean>— alwaysBoolean.TRUEon success (a failure does not end withfalse; the future completes exceptionally instead).
Throws:
- When the write fails (including
databeingnullor an empty array), the future completes withAoEProtocolException.
readWrite(int indexGroup, int indexOffset, int readLength, byte[] writeData, int timeoutUs)
public byte[] readWrite(int indexGroup, int indexOffset, int readLength, byte[] writeData, int timeoutUs)
Reads and writes in a single ADS ReadWrite transaction. Only the overload with timeoutUs exists; to use the default timeout, pass 500000 explicitly.
Parameters:
indexGroup(int) — index groupindexOffset(int) — index offsetreadLength(int) — read length;0= pure writewriteData(byte[]) — the data to write; may benull(= read-only)timeoutUs(int) — timeout in microseconds
Returns:
byte[]— the data read back;nullmeans the transaction failed, or the transaction succeeded without reading data back (readLength = 0). Distinguish them as inread.
Throws:
- Runtime exceptions propagate unchanged.
readWriteAsync(int indexGroup, int indexOffset, int readLength, byte[] writeData, int timeoutUs)
public CompletableFuture<byte[]> readWriteAsync(int indexGroup, int indexOffset, int readLength,
byte[] writeData, int timeoutUs)
Asynchronous ADS ReadWrite; the task runs on defaultExecutor(). Again only the overload with timeoutUs exists.
Parameters: Same as readWrite.
Returns:
CompletableFuture<byte[]>— the data read back, available when the future completes.
Throws:
- When the synchronous read/write returns
null, the future completes withAoEProtocolException(including the successfulreadLength = 0path).
readDeviceInfo(int timeoutUs)
public DeviceInfo readDeviceInfo(int timeoutUs)
public DeviceInfo readDeviceInfo()
Reads the ADS device information (ReadDeviceInfo command).
Parameters:
timeoutUs(int) — timeout in microseconds; the overload without this parameter uses the default 500000
Returns:
DeviceInfo— the device information object; on failureSuccess = false, the remaining fields keep their defaults (DeviceNameis an empty string), and the transaction status is available fromgetLastStatus().
Throws:
- Runtime exceptions propagate unchanged; they are not swallowed into
Success = falsewith no error code left behind.
Related structures:
DeviceInfo
public static class DeviceInfo {
public boolean Success; // whether the call succeeded
public byte MajorVer; // major version number
public byte MinorVer; // minor version number
public short Build; // build number
public String DeviceName = ""; // device name (leading and trailing whitespace already removed)
}
| Field | Type | Meaning |
|---|---|---|
| Success | boolean | Whether this read succeeded |
| MajorVer | byte | Major version number |
| MinorVer | byte | Minor version number |
| Build | short | Build number |
| DeviceName | String | Device name with leading and trailing whitespace removed; an empty string on failure |
Example:
AoE.DeviceInfo info = slave.aoe().readDeviceInfo();
if (info.Success)
System.out.printf("设备: %s v%d.%d.%d%n", // Device: %s v%d.%d.%d%n
info.DeviceName, info.MajorVer, info.MinorVer, info.Build);
readState(int timeoutUs)
public AdsState readState(int timeoutUs)
public AdsState readState()
Reads the current ADS state and device state (ReadState command).
Parameters:
timeoutUs(int) — timeout in microseconds; the overload without this parameter uses the default 500000
Returns:
AdsState— the ADS state object; on failureSuccess = falseandAdsState/DeviceStateare 0.
Throws:
- Runtime exceptions propagate unchanged; they are not swallowed into
Success = falsewith no error code left behind.
Related structures:
AdsState
public static class AdsState {
public boolean Success; // whether the call succeeded
public short AdsState; // ADS state code
public short DeviceState; // device state
}
Get the state code text with getAdsStateDescription(state.AdsState).
Example:
AoE.AdsState state = slave.aoe().readState();
if (state.Success)
System.out.println("ADS 状态: " + AoE.getAdsStateDescription(state.AdsState)); // ADS state:
writeControl(short adsState, short deviceState, byte[] data, int timeoutUs)
public boolean writeControl(short adsState, short deviceState, byte[] data, int timeoutUs)
public boolean writeControl(short adsState, short deviceState) // default timeout, no additional data
Writes a control command that switches the target ADS state and device state (WriteControl command).
Parameters:
adsState(short) — target ADS state codedeviceState(short) — target device statedata(byte[]) — additional data;nullmay be passed (sent as empty data — unlikewrite, this is not judged as a call error)timeoutUs(int) — timeout in microseconds
Returns:
boolean—trueon success;falseon failure, withgetLastStatus()=TIMEOUTandgetLastErrorCode()other than 0.
Throws:
- Runtime exceptions propagate unchanged.
Example:
slave.aoe().writeControl((short) 5, (short) 0); // Switch to the Run state
getAdsStateDescription(int adsState)
public static String getAdsStateDescription(int adsState)
Static method: converts an ADS state code to a Chinese description text.
Parameters:
adsState(int) — ADS state code (usually taken fromreadState().AdsState)
Returns:
String— the Chinese description; a state code that is not covered returns未知状态 (n)(nis the value passed in).
| State code | Returned text | State code | Returned text |
|---|---|---|---|
| 0 | invalid | 8 | load configuration |
| 1 | idle | 9 | shutdown |
| 2 | reset | 10 | suspend |
| 3 | initialization | 11 | reconfigure |
| 4 | start | 15 | error |
| 5 | run | Other | 未知状态 (n) |
| 6 | stop | ||
| 7 | save configuration |
The returned Chinese text for 9 / 10 / 11 / 15 does not match the ADS standard definitions of those state codes (PowerFailure / PowerGood / Error / Config); when the device state must be interpreted by the standard, use the numeric value returned by readState().
subscribe(int indexGroup, int indexOffset, int dataLength, NotificationCallback callback, int cycleTimeMs)
public int subscribe(int indexGroup, int indexOffset, int dataLength,
NotificationCallback callback, int cycleTimeMs)
Subscribes to data change notifications: the data is checked once per cycleTimeMs period, and the callback fires only when the data changes (reported as OnChange).
Parameters:
indexGroup(int) — index groupindexOffset(int) — index offsetdataLength(int) — length of the data carried by each notificationcallback(NotificationCallback) — data change callbackcycleTimeMs(int) — check period in milliseconds; the allowed range is0to214748(that isInteger.MAX_VALUE / 10000, because the value must still fit in 32 bits after conversion to 100 ns units)
Returns:
int— the notification handle (a positive integer);-1on failure, in which casegetLastStatus()/getLastErrorCode()give the reason.
Throws:
IllegalArgumentException—cycleTimeMsis negative or greater than214748. An out-of-range cycle parameter throws first; it does not return-1.
Related structures:
NotificationCallback
@FunctionalInterface
public interface NotificationCallback {
void onNotification(short slave, int handle, byte[] data, long timestamp);
}
| Parameter | Type | Meaning |
|---|---|---|
| slave | short | Slave index |
| handle | int | Subscription handle of this notification |
| data | byte[] | The data after the change |
| timestamp | long | Timestamp carried by the notification |
Example:
int handle = slave.aoe().subscribe(0x4020, 0, 4, (slaveNo, h, data, ts) -> {
int value = (data[0] & 0xFF) | ((data[1] & 0xFF) << 8)
| ((data[2] & 0xFF) << 16) | ((data[3] & 0xFF) << 24);
System.out.printf("数据变化: 0x%08X%n", value); // Data change: 0x%08X%n
}, 100);
unsubscribe(int handle)
public boolean unsubscribe(int handle)
Cancels the specified subscription. The local handle record is removed first regardless of whether the cancel succeeded on the slave side; to retry, call it again with the same handle.
Parameters:
handle(int) — the notification handle returned bysubscribe
Returns:
boolean—truewhen the cancel succeeds on the slave side;falseon failure (getLastStatus()=MAILBOX_ERROR)
Throws:
- Runtime exceptions propagate unchanged.
unsubscribeAll()
public void unsubscribeAll()
Cancels all subscriptions. They are cancelled one by one; a single failure does not interrupt the remaining cleanup, but the failure is written to the error log and getLastStatus() is set to MAILBOX_ERROR; once the call returns, getActiveSubscriptions() is an empty array.
getActiveSubscriptions()
public int[] getActiveSubscriptions()
Returns:
int[]— array of the handles of the currently active subscriptions; an empty array when there are none. The order is not guaranteed and is unrelated to the order in whichsubscribereturned.
sendCommand(short targetPort, short commandId, byte[] commandData, int timeoutUs)
public byte[] sendCommand(short targetPort, short commandId, byte[] commandData, int timeoutUs)
Sends a raw ADS command (advanced API; for normal reads and writes, state and subscriptions use read / write / readState / subscribe). There is no default-timeout overload.
Parameters:
targetPort(short) — target AMS portcommandId(short) — ADS command IDcommandData(byte[]) — command data;nullmay be passed (sent as empty data)timeoutUs(int) — timeout in microseconds
Returns:
byte[]— the response data;nullmeans the command failed, or the command was accepted with no reply. On failuregetLastStatus()=TIMEOUTandgetLastErrorCode()is other than 0; with an empty replygetLastStatus()=SUCCESS.
Throws:
- Runtime exceptions propagate unchanged; they are not swallowed into
null.
setConfig(byte[] targetNetId, short targetPort, byte[] sourceNetId, short sourcePort)
public boolean setConfig(byte[] targetNetId, short targetPort, byte[] sourceNetId, short sourcePort)
Sets the AoE routing configuration (target / source AMS NetID and port). An AMS NetID is always 6 bytes and is not zero-padded or truncated: a wrong length is rejected outright.
Parameters:
targetNetId(byte[]) — target AMS NetID, which must be exactly 6 bytestargetPort(short) — target AMS portsourceNetId(byte[]) — source AMS NetID, which must be exactly 6 bytessourcePort(short) — source AMS port
Returns:
boolean—trueon success;falseon failure.
Throws:
IllegalArgumentException— either NetID isnull, or its length is not 6.
Runtime exceptions thrown during configuration are not propagated; they turn into a false return and an error log entry, with getLastStatus() / getLastErrorCode() recorded accordingly.
Example:
byte[] targetNetId = { 5, 80, (byte)187, (byte)177, 1, 1 };
byte[] sourceNetId = { (byte)192, (byte)168, 1, 100, 1, 1 };
slave.aoe().setConfig(targetNetId, (short) 851, sourceNetId, (short) 32768);
initializeSlaveNetId(byte[] netId, int timeoutUs)
public boolean initializeSlaveNetId(byte[] netId, int timeoutUs)
public boolean initializeSlaveNetId(byte[] netId) // default timeout
Initializes the slave AoE NetID (ETG.1020 §9.4): call it during the INIT→PreOp state transition to write the NetID into the slave ADS routing table.
Parameters:
netId(byte[]) — the 6-byte AMS NetIDtimeoutUs(int) — timeout in microseconds
Returns:
boolean—trueon success;falseon failure.
Throws:
IllegalArgumentException—netIdisnull, or its length is not 6.
Example:
byte[] netId = { 5, 80, (byte)187, (byte)177, 1, 1 };
slave.aoe().initializeSlaveNetId(netId);
getConfig()
public AoEConfig getConfig()
Reads the current AoE routing configuration.
Returns:
AoEConfig— the configuration information; on failureSuccess = false, the NetIDs stay at 6 bytes of all 0 and the ports are 0. Runtime exceptions thrown during the read are not propagated; they turn intoSuccess = falseand an error log entry, withgetLastStatus()/getLastErrorCode()recorded accordingly.
Related structures:
AoEConfig
public static class AoEConfig {
public boolean Success; // whether the call succeeded
public byte[] TargetNetId = new byte[6]; // target AMS NetID (6 bytes)
public short TargetPort; // target AMS port
public byte[] SourceNetId = new byte[6]; // source AMS NetID (6 bytes)
public short SourcePort; // source AMS port
}
| Field | Type | Meaning |
|---|---|---|
| Success | boolean | Whether this read succeeded |
| TargetNetId | byte[] | Target AMS NetID (6 bytes) |
| TargetPort | short | Target AMS port |
| SourceNetId | byte[] | Source AMS NetID (6 bytes) |
| SourcePort | short | Source AMS port |
readCoEViaAoE(int index, int subindex, int readLength, int timeoutUs)
public byte[] readCoEViaAoE(int index, int subindex, int readLength, int timeoutUs)
public byte[] readCoEViaAoE(int index, int subindex, int readLength) // default timeout
Reads a CoE object through the AoE route (IndexGroup = COE_INDEX_GROUP, that is 0xF302), with IndexOffset encoded as (index << 16) | (subindex & 0xFF).
Parameters:
index(int) — CoE object indexsubindex(int) — CoE subindexreadLength(int) — expected read lengthtimeoutUs(int) — timeout in microseconds
Returns:
byte[]— the data read;nullmeans the transaction failed, or the transaction succeeded without reading data back (readLength = 0).
Example:
// Read CoE object 0x6041:0 (status word) through the AoE gateway
byte[] data = slave.aoe().readCoEViaAoE(0x6041, 0, 2);
if (data != null) {
int statusWord = (data[0] & 0xFF) | ((data[1] & 0xFF) << 8);
System.out.printf("状态字: 0x%04X%n", statusWord); // Status word: 0x%04X%n
}
writeCoEViaAoE(int index, int subindex, byte[] data, int timeoutUs)
public boolean writeCoEViaAoE(int index, int subindex, byte[] data, int timeoutUs)
public boolean writeCoEViaAoE(int index, int subindex, byte[] data) // default timeout
Writes a CoE object through the AoE route (IndexGroup = 0xF302), with the IndexOffset encoded as in readCoEViaAoE.
Parameters:
index(int) — CoE object indexsubindex(int) — CoE subindexdata(byte[]) — the data to write;nullor an empty array returnsfalsedirectly (same aswrite)timeoutUs(int) — timeout in microseconds
Returns:
boolean—trueon success;falseon failure.
Example:
// Write CoE object 0x6040:0 (control word) through the AoE gateway
byte[] ctrlWord = { 0x0F, 0x00 };
slave.aoe().writeCoEViaAoE(0x6040, 0, ctrlWord);
readSoEViaAoE(int idn, int readLength, int timeoutUs)
public byte[] readSoEViaAoE(int idn, int readLength, int timeoutUs)
public byte[] readSoEViaAoE(int idn, int readLength) // default timeout
Reads an SoE IDN through the AoE route (IndexGroup = SOE_INDEX_GROUP, that is 0xF420), with IndexOffset = the IDN number.
Parameters:
idn(int) — SoE IDN numberreadLength(int) — expected read lengthtimeoutUs(int) — timeout in microseconds
Returns:
byte[]— the data read;nullmeans the transaction failed, or the transaction succeeded without reading data back (readLength = 0).
writeSoEViaAoE(int idn, byte[] data, int timeoutUs)
public boolean writeSoEViaAoE(int idn, byte[] data, int timeoutUs)
public boolean writeSoEViaAoE(int idn, byte[] data) // default timeout
Writes an SoE IDN through the AoE route (IndexGroup = 0xF420), with IndexOffset = the IDN number.
Parameters:
idn(int) — SoE IDN numberdata(byte[]) — the data to write;nullor an empty array returnsfalsedirectly (same aswrite)timeoutUs(int) — timeout in microseconds
Returns:
boolean—trueon success;falseon failure.
Routing IndexGroup constants
public static final int COE_INDEX_GROUP = 0xF302; // CoE over AoE routing
public static final int SOE_INDEX_GROUP = 0xF420; // SoE over AoE routing
readCoEViaAoE / writeCoEViaAoE use COE_INDEX_GROUP with the IndexOffset encoded as (index << 16) | (subindex & 0xFF) (the subindex occupies only the low 8 bits); readSoEViaAoE / writeSoEViaAoE use SOE_INDEX_GROUP with IndexOffset = the IDN number. When calling readWrite / write directly instead of the convenience methods, fill IndexGroup and IndexOffset with the same encoding.
isSupported() / supportState() / isSupportKnown()
public boolean isSupported()
public Boolean supportState()
public boolean isSupportKnown()
Slave AoE capability check (AoE implements the unified IMailboxProtocol interface).
| Method | Type | Description |
|---|---|---|
| isSupported() | boolean | Returns true only when support is confirmed; returns false when the capability is unknown (fail-closed) — unknown is not the same as unsupported |
| supportState() | Boolean | Tri-state: TRUE = supported; null = unknown; AoE has no details field in SII that could serve as contrary evidence, so FALSE is never returned |
| isSupportKnown() | boolean | Whether the capability verdict is known; equivalent to supportState() != null |
The slave object also exposes the two entry points supportsAoE() / aoeSupportState() with the same semantics; see Slave API.
Boolean state = slave.aoe().supportState();
if (state == null) {
System.out.println("AoE 能力未知:既不能说支持,也不能说不支持"); // AoE capability unknown: neither supported nor unsupported can be claimed
} else if (state) {
System.out.println("从站声明支持 AoE"); // Slave declares AoE support
}
getLastStatus() / getLastErrorCode()
public MailboxStatus getLastStatus()
public long getLastErrorCode()
Status and error code of the most recent mailbox transaction, used to break failures that return null / false / -1 down to a specific cause. Both are updated when any transaction ends (success or failure); the initial status of a new instance is PENDING.
| Method | Type | Description |
|---|---|---|
| getLastStatus() | MailboxStatus | Unified status of the most recent transaction |
| getLastErrorCode() | long | Most recent protocol-layer error code; 0 = no error. Always non-zero on failure: 1 when no specific code was provided |
MailboxStatus (com.darra.ethercat.abstractions) values:
PENDING— the transaction has not been started or is still in progress (initial value)SUCCESS— completed successfullyTIMEOUT— the peer did not respond within the timeoutCANCELLED— cancelledMAILBOX_ERROR— mailbox error frame or protocol-layer abortPROTO_MISMATCH/WKC_FAIL— response protocol type / working counter mismatchNO_MEMORY/INVALID_ARG/NOT_IMPLEMENTED— out of memory / invalid argument / not implementedLINK_DOWN— link down (frames fail immediately instead of timing out one by one); check the cable / NIC link statusNOT_SENT— 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
byte[] data = slave.aoe().read(0x4020, 0, 4);
if (data == null) {
System.out.printf("读取失败: %s (code=0x%X)%n", // Read failed: %s (code=0x%X)%n
slave.aoe().getLastStatus(), slave.aoe().getLastErrorCode());
}
getStatistics() / resetStatistics()
public MailboxStatistics getStatistics()
public void resetStatistics()
Mailbox statistics snapshot and statistics reset. When statistics are unavailable a snapshot of all 0s is returned and no exception is thrown. Besides zeroing the counters, resetStatistics() also resets getLastStatus() to PENDING and getLastErrorCode() to 0.
MailboxStatistics (com.darra.ethercat.abstractions) is an immutable snapshot:
| Field | Type | Description |
|---|---|---|
| totalSent | long | Total transactions sent |
| totalReceived | long | Total responses received (including error frames) |
| totalTimeout | long | Total timeouts |
| totalMailboxError | long | Total mailbox error frames |
| totalProtocolError | long | Total protocol errors (protocol type / working counter mismatch) |
| totalCancelled | long | Total 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) |
MailboxStatistics stats = slave.aoe().getStatistics();
System.out.printf("AoE 邮箱: 发送=%d, 接收=%d, 超时=%d, 平均延迟=%.1fus%n", // AoE mailbox: sent=%d, received=%d, timeouts=%d, average latency=%.1fus%n
stats.totalSent, stats.totalReceived, stats.totalTimeout, stats.averageLatencyUs);
slave.aoe().resetStatistics();
AoEResultCode
The AoE / ADS result codes defined by ETG.1020 Table 16, with values identical to the standard: the high byte is the error class (0x0700 = ADS device error, 0x0740 = client error) and the low byte is the specific error code. The enum has 62 constants:
public enum AoEResultCode {
NO_ERROR(0x0000), // no error
INTERNAL_ERROR(0x0001), // internal error
NO_REALTIME(0x0002), // no real time
ALLOCATION_LOCKED_MEMORY_ERROR(0x0003), // allocation of locked memory error
INSERT_MAILBOX_ERROR(0x0004), // mailbox full
WRONG_RECEIVE_HMSG(0x0005), // wrong command ID
TARGET_PORT_NOT_FOUND(0x0006), // target port not found
TARGET_MACHINE_NOT_FOUND(0x0007), // target machine not found
UNKNOWN_COMMAND_ID(0x0008), // unknown command ID
BAD_TASK_ID(0x0009), // invalid task ID
NO_IO(0x000A), // no IO
UNKNOWN_AMS_COMMAND(0x000B), // unknown AMS command
WIN32_ERROR(0x000C), // system error
PORT_NOT_CONNECTED(0x000D), // port not connected
INVALID_AMS_LENGTH(0x000E), // invalid AMS length
INVALID_AMS_NET_ID(0x000F), // invalid AMS NetID
LOW_INST_LEVEL(0x0010), // low installation level
NO_DEBUG_AVAILABLE(0x0011), // no debugging available
PORT_DISABLED(0x0012), // port disabled
PORT_ALREADY_CONNECTED(0x0013), // port already connected
AMS_SYNC_WIN32_ERROR(0x0014), // AMS sync system error
AMS_SYNC_TIMEOUT(0x0015), // AMS sync timeout
AMS_SYNC_AMS_ERROR(0x0016), // AMS sync AMS error
AMS_SYNC_NO_INDEX_MAP(0x0017), // AMS sync no index map
INVALID_AMS_PORT(0x0018), // invalid AMS port
NO_MEMORY(0x0019), // no memory
TCP_SEND_ERROR(0x001A), // send error
HOST_UNREACHABLE(0x001B), // host unreachable
INVALID_AMS_FRAGMENT(0x001C), // invalid AMS fragment
WSA_SERVICE_NOT_STARTED(0x274D), // service not started
DEVICE_INVALID_GROUP(0x0700), // device invalid group
DEVICE_INVALID_OFFSET(0x0701), // device invalid offset
DEVICE_INVALID_ACCESS(0x0702), // device invalid access
DEVICE_INVALID_SIZE(0x0703), // device invalid size
DEVICE_INVALID_DATA(0x0704), // device invalid data
DEVICE_NOT_READY(0x0705), // device not ready
DEVICE_BUSY(0x0706), // device busy
DEVICE_INVALID_CONTEXT(0x0707), // device invalid context
DEVICE_NOT_FOUND(0x0708), // device not found
DEVICE_ALREADY_EXISTS(0x0709), // device already exists
DEVICE_SYMBOL_NOT_FOUND(0x070A), // device symbol not found
DEVICE_SYMBOL_VERSION_INVALID(0x070B), // device symbol version invalid
DEVICE_INVALID_STATE(0x070C), // device invalid state
DEVICE_TIMEOUT(0x0712), // device timeout
DEVICE_NO_INTERFACE_QUERY(0x0713), // device no interface query
DEVICE_INVALID_INTERFACE(0x0714), // device invalid interface
DEVICE_INVALID_CLASS_ID(0x0715), // device invalid class ID
DEVICE_INVALID_OBJECT_ID(0x0716), // device invalid object ID
DEVICE_PENDING(0x0717), // device pending
DEVICE_ABORTED(0x0718), // device aborted
DEVICE_WARNING(0x0719), // device warning
DEVICE_INVALID_ARRAY_INDEX(0x071A), // device invalid array index
DEVICE_SYMBOL_NOT_ACTIVE(0x071B), // device symbol not active
DEVICE_ACCESS_DENIED(0x071C), // device access denied
CLIENT_ERROR(0x0740), // client error
CLIENT_INVALID_PARAM(0x0741), // client invalid parameter
CLIENT_LIST_EMPTY(0x0742), // client list empty
CLIENT_VAR_ALREADY_IN_USE(0x0743), // client variable already in use
CLIENT_INVOKE_TIMEOUT(0x0744), // client invoke timeout
CLIENT_PORT_NOT_OPEN(0x0745), // client port not open
CLIENT_NOT_STARTED(0x0746), // client not started
CLIENT_QUEUE_FULL(0x0750); // client queue full
}
| Method | Type | Description |
|---|---|---|
| getValue() | int | The ADS result code of the enum constant (read-only) |
| fromValue(int code) | AoEResultCode | Static reverse lookup: matches the enum constant by value and returns null when nothing matches |
AoEResultCode rc = AoEResultCode.fromValue((int) slave.aoe().getLastErrorCode());
System.out.println(rc == null ? "未收录的结果码" : rc.name()); // Result code not in the table
AoEProtocolException
When an AoE asynchronous method (readAsync / writeAsync / readWriteAsync) fails, the returned CompletableFuture completes with this exception.
public static class AoEProtocolException extends RuntimeException {
public AoEProtocolException(String message);
public AoEProtocolException(String message, Throwable cause);
}
It is a subclass of RuntimeException, but it is never thrown by the synchronous methods; in asynchronous scenarios it is wrapped once by CompletableFuture (exceptionally / whenComplete receive a CompletionException, get() receives an ExecutionException), with the real cause in getCause().
Example:
slave.aoe().readAsync(0x4020, 0, 4)
.thenAccept(data -> System.out.printf("长度: %d%n", data.length)) // Length: %d%n
.exceptionally(ex -> {
if (ex.getCause() instanceof AoE.AoEProtocolException)
System.err.println("AoE 读取失败: " + ex.getCause().getMessage()); // AoE read failed:
return null;
});
Notification listening
The AoE notification listener thread is independent per master: one thread per master, which distributes the data change callbacks pushed by the slaves to that master's subscribers. The listener thread can be started explicitly and is also brought up on demand when the first subscription is registered; isNotificationListening() reports whether it is currently running.
isNotificationListening()
public boolean isNotificationListening()
Reports whether the notification listener thread of the master this instance belongs to is running. A read-only query: it neither starts nor changes the listening state.
Returns:
boolean—true= the listener thread of that master is running;false= it has not been started yet, or the listening state cannot be obtained at the moment (a failed query is treated as not running)
Example:
AoE aoe = slave.aoe();
// The first subscription starts the listener thread on demand
int handle = aoe.subscribe(0x4020, 0, 4, (s, h, data, ts) -> {
System.out.printf("从站 %d 通知: %d 字节%n", s, data.length); // Slave %d notification: %d bytes%n
}, 100);
if (aoe.isNotificationListening()) {
System.out.println("AoE 通知监听已就绪"); // AoE notification listener is ready
}
Full example
AoE aoe = slave.aoe();
if (!aoe.isSupported()) {
System.out.println("从站不支持 AoE"); // Slave does not support AoE
return;
}
// Read the device information
AoE.DeviceInfo info = aoe.readDeviceInfo();
if (info.Success)
System.out.printf("设备: %s v%d.%d.%d%n", // Device: %s v%d.%d.%d%n
info.DeviceName, info.MajorVer, info.MinorVer, info.Build);
// Read 4 bytes by IndexGroup / IndexOffset
byte[] data = aoe.read(0x4020, 0, 4);
if (data != null) {
int value = (data[0] & 0xFF) | ((data[1] & 0xFF) << 8)
| ((data[2] & 0xFF) << 16) | ((data[3] & 0xFF) << 24);
System.out.printf("数据: 0x%08X%n", value); // Data: 0x%08X%n
}
// Write back to the same location
boolean ok = aoe.write(0x4020, 0, new byte[] { 0x06, 0x00, 0x00, 0x00 });
System.out.println(ok ? "写入成功" : "写入失败"); // Write succeeded / write failed
// Read the ADS state
AoE.AdsState state = aoe.readState();
if (state.Success)
System.out.println("ADS 状态码: " + state.AdsState); // ADS state code:
Data subscription
AoE aoe = slave.aoe();
int handle = aoe.subscribe(0x4020, 0, 4, (slaveNo, h, data, ts) -> {
System.out.println("数据变化"); // Data change
}, 100);
Thread.sleep(10000);
aoe.unsubscribeAll();
Cross-protocol gateway
AoE aoe = slave.aoe();
// Read a CoE object through AoE
byte[] statusWord = aoe.readCoEViaAoE(0x6041, 0, 2);
if (statusWord != null) {
int value = (statusWord[0] & 0xFF) | ((statusWord[1] & 0xFF) << 8);
System.out.printf("状态字: 0x%04X%n", value); // Status word: 0x%04X%n
}
// Write a CoE object through AoE
byte[] ctrlWord = { 0x0F, 0x00 };
aoe.writeCoEViaAoE(0x6040, 0, ctrlWord);
// Read an SoE IDN through AoE
byte[] idnData = aoe.readSoEViaAoE(32, 4);
if (idnData != null) {
int value = (idnData[0] & 0xFF) | ((idnData[1] & 0xFF) << 8)
| ((idnData[2] & 0xFF) << 16) | ((idnData[3] & 0xFF) << 24);
System.out.printf("IDN 32 值: %d%n", value); // IDN 32 value: %d%n
}
Failures and handling
| Symptom | Cause | Handling |
|---|---|---|
| read returns null, or write returns false | The ADS transaction failed (the slave rejected it or the mailbox timed out); read also returns null when the transaction succeeds with readLength = 0 | Confirm the slave state with readState first, then check the IndexGroup, the IndexOffset and the read length |
| A call does not return for a long time | The slave did not answer within the default timeout | Switch to the overload with timeoutUs and widen it appropriately |
| isSupported is false | The slave does not support AoE | Do not keep calling; use a protocol that the slave supports |
| subscribe returns -1 | Subscription resources are exhausted or the slave rejected the request | Reduce concurrent subscriptions and check the data length; an out-of-range cycle parameter (negative / beyond the 32-bit conversion range) throws IllegalArgumentException first, it does not return -1 |
| write / writeCoEViaAoE / writeSoEViaAoE return false immediately and getLastStatus() is INVALID_ARG | The data passed in is null or an empty array | Pass non-empty data; this is a call error, not a bus fault |
| setConfig / initializeSlaveNetId throw IllegalArgumentException | The AMS NetID is not exactly 6 bytes | Make it 6 bytes; the SDK does not zero-pad or truncate |
| The future of an asynchronous method completes exceptionally | The synchronous read/write returned null / false | Read the AoEProtocolException message in exceptionally / get; readAsync with length = 0 behaves the same way |
| getLastStatus() is always PENDING | No transaction has been started yet | Perform one read or write first; resetStatistics() also resets the status to PENDING |