Skip to main content

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​

CategoryMethodTypeRead/writeDescription
Data read/writereadbyte[]read-onlyReads the given length of data by IndexGroup and IndexOffset; returns null on failure
Data read/writereadAsyncCompletableFuture<byte[]>read-onlyAsynchronous read; the future completes with AoEProtocolException on failure
Data read/writewritebooleanwrite-onlyWrites data by IndexGroup and IndexOffset
Data read/writewriteAsyncCompletableFuture<Boolean>write-onlyAsynchronous write; the future completes with AoEProtocolException on failure
Data read/writereadWritebyte[]read/writeReads and writes in one transaction (ADS ReadWrite); returns null on failure
Data read/writereadWriteAsyncCompletableFuture<byte[]>read/writeAsynchronous read/write; the future completes with AoEProtocolException on failure
Device informationreadDeviceInfoDeviceInforead-onlyReads the device name and version information
Device statusreadStateAdsStateread-onlyReads the current ADS state and device state
Device statusgetAdsStateDescriptionStringread-onlyStatic method; converts an ADS state code to a Chinese description
Device controlwriteControlbooleanwrite-onlySwitches the target ADS state and device state
Data subscriptionsubscribe(indexGroup, indexOffset, dataLength, callback, cycleTimeMs)intwrite-onlySubscribes to data changes on a cycle; returns the notification handle, or -1 on failure
Data subscriptionunsubscribebooleanwrite-onlyCancels the subscription of the specified handle
Data subscriptionunsubscribeAllvoidwrite-onlyCancels all subscriptions and clears the local handles
Data subscriptiongetActiveSubscriptionsint[]read-onlyList of handles of the currently active subscriptions
ADS commandssendCommandbyte[]read/writeSends a raw ADS command; normal reads, writes and subscriptions do not need it
Routing configurationsetConfigbooleanwrite-onlySets the target / source AMS NetID and port
Routing configurationinitializeSlaveNetIdbooleanwrite-onlyWrites the NetID into the slave ADS routing table during INIT→PreOp
Routing configurationgetConfigAoEConfigread-onlyReads the current AMS NetID and port configuration
Cross-protocol gatewayreadCoEViaAoE / writeCoEViaAoEbyte[] / booleanread/writeAccesses CoE objects through the AoE route (IndexGroup=0xF302)
Cross-protocol gatewayreadSoEViaAoE / writeSoEViaAoEbyte[] / booleanread/writeAccesses SoE IDNs through the AoE route (IndexGroup=0xF420)
CapabilityisSupportedbooleanread-onlyWhether the slave supports AoE; returns false when the capability is unknown
CapabilitysupportStateBooleanread-onlyTri-state capability: TRUE = supported, FALSE = confirmed unsupported, null = unknown
CapabilityisSupportKnownbooleanread-onlyWhether the capability verdict is known (supportState() != null)
Transaction statusgetLastStatusMailboxStatusread-onlyUnified status of the most recent mailbox transaction
Transaction statusgetLastErrorCodelongread-onlyMost recent protocol-layer error code (0 = no error)
StatisticsgetStatisticsMailboxStatisticsread-onlyMailbox statistics snapshot
StatisticsresetStatisticsvoidwrite-onlyResets the mailbox statistics counters

Interface details​

Default timeout

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 group
  • indexOffset (int) — index offset
  • length (int) — expected number of bytes to read; passing 0 means no data is read back in this call
  • timeoutUs (int) — timeout in microseconds; the overload without this parameter uses the default 500000

Returns:

  • byte[] — the data read; null means the transaction failed, or the transaction succeeded but no data was read back (length = 0). The two kinds of null can be told apart with getLastStatus(): a failure is TIMEOUT with getLastErrorCode() other than 0; the successful length = 0 path is SUCCESS with error code 0.

Throws:

  • Runtime exceptions propagate unchanged (the transaction status is recorded as TIMEOUT or MAILBOX_ERROR at the same time); they are never swallowed into null, 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 with AoEProtocolException — including the successful length = 0 path (an empty read-back is likewise judged as a failure). For a pure write use write, not readAsync(..., 0, ...).
  • Exceptions inside the future are wrapped once by CompletableFuture: exceptionally / whenComplete receive a CompletionException with the real cause in ex.getCause(); get() reports it in the cause of an ExecutionException.

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 group
  • indexOffset (int) — index offset
  • data (byte[]) — the data to write; null or length 0 is a call error and returns false immediately without starting a transaction
  • timeoutUs (int) — timeout in microseconds

Returns:

  • boolean — true when the write succeeds, false on failure. With empty data getLastStatus() = INVALID_ARG and getLastErrorCode() = CLIENT_INVALID_PARAM (0x0741); when the transaction fails, getLastStatus() = TIMEOUT and getLastErrorCode() 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> — always Boolean.TRUE on success (a failure does not end with false; the future completes exceptionally instead).

Throws:

  • When the write fails (including data being null or an empty array), the future completes with AoEProtocolException.

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 group
  • indexOffset (int) — index offset
  • readLength (int) — read length; 0 = pure write
  • writeData (byte[]) — the data to write; may be null (= read-only)
  • timeoutUs (int) — timeout in microseconds

Returns:

  • byte[] — the data read back; null means the transaction failed, or the transaction succeeded without reading data back (readLength = 0). Distinguish them as in read.

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 with AoEProtocolException (including the successful readLength = 0 path).

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 failure Success = false, the remaining fields keep their defaults (DeviceName is an empty string), and the transaction status is available from getLastStatus().

Throws:

  • Runtime exceptions propagate unchanged; they are not swallowed into Success = false with 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)
}
FieldTypeMeaning
SuccessbooleanWhether this read succeeded
MajorVerbyteMajor version number
MinorVerbyteMinor version number
BuildshortBuild number
DeviceNameStringDevice 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 failure Success = false and AdsState / DeviceState are 0.

Throws:

  • Runtime exceptions propagate unchanged; they are not swallowed into Success = false with 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 code
  • deviceState (short) — target device state
  • data (byte[]) — additional data; null may be passed (sent as empty data — unlike write, this is not judged as a call error)
  • timeoutUs (int) — timeout in microseconds

Returns:

  • boolean — true on success; false on failure, with getLastStatus() = TIMEOUT and getLastErrorCode() 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 from readState().AdsState)

Returns:

  • String — the Chinese description; a state code that is not covered returns 未知状态 (n) (n is the value passed in).
State codeReturned textState codeReturned text
0invalid8load configuration
1idle9shutdown
2reset10suspend
3initialization11reconfigure
4start15error
5runOther未知状态 (n)
6stop
7save 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 group
  • indexOffset (int) — index offset
  • dataLength (int) — length of the data carried by each notification
  • callback (NotificationCallback) — data change callback
  • cycleTimeMs (int) — check period in milliseconds; the allowed range is 0 to 214748 (that is Integer.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); -1 on failure, in which case getLastStatus() / getLastErrorCode() give the reason.

Throws:

  • IllegalArgumentException — cycleTimeMs is negative or greater than 214748. 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);
}
ParameterTypeMeaning
slaveshortSlave index
handleintSubscription handle of this notification
databyte[]The data after the change
timestamplongTimestamp 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 by subscribe

Returns:

  • boolean — true when the cancel succeeds on the slave side; false on 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 which subscribe returned.

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 port
  • commandId (short) — ADS command ID
  • commandData (byte[]) — command data; null may be passed (sent as empty data)
  • timeoutUs (int) — timeout in microseconds

Returns:

  • byte[] — the response data; null means the command failed, or the command was accepted with no reply. On failure getLastStatus() = TIMEOUT and getLastErrorCode() is other than 0; with an empty reply getLastStatus() = 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 bytes
  • targetPort (short) — target AMS port
  • sourceNetId (byte[]) — source AMS NetID, which must be exactly 6 bytes
  • sourcePort (short) — source AMS port

Returns:

  • boolean — true on success; false on failure.

Throws:

  • IllegalArgumentException — either NetID is null, 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 NetID
  • timeoutUs (int) — timeout in microseconds

Returns:

  • boolean — true on success; false on failure.

Throws:

  • IllegalArgumentException — netId is null, 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 failure Success = 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 into Success = false and an error log entry, with getLastStatus() / 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
}
FieldTypeMeaning
SuccessbooleanWhether this read succeeded
TargetNetIdbyte[]Target AMS NetID (6 bytes)
TargetPortshortTarget AMS port
SourceNetIdbyte[]Source AMS NetID (6 bytes)
SourcePortshortSource 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 index
  • subindex (int) — CoE subindex
  • readLength (int) — expected read length
  • timeoutUs (int) — timeout in microseconds

Returns:

  • byte[] — the data read; null means 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 index
  • subindex (int) — CoE subindex
  • data (byte[]) — the data to write; null or an empty array returns false directly (same as write)
  • timeoutUs (int) — timeout in microseconds

Returns:

  • boolean — true on success; false on 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 number
  • readLength (int) — expected read length
  • timeoutUs (int) — timeout in microseconds

Returns:

  • byte[] — the data read; null means 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 number
  • data (byte[]) — the data to write; null or an empty array returns false directly (same as write)
  • timeoutUs (int) — timeout in microseconds

Returns:

  • boolean — true on success; false on 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).

MethodTypeDescription
isSupported()booleanReturns true only when support is confirmed; returns false when the capability is unknown (fail-closed) — unknown is not the same as unsupported
supportState()BooleanTri-state: TRUE = supported; null = unknown; AoE has no details field in SII that could serve as contrary evidence, so FALSE is never returned
isSupportKnown()booleanWhether 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.

MethodTypeDescription
getLastStatus()MailboxStatusUnified status of the most recent transaction
getLastErrorCode()longMost 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 successfully
  • TIMEOUT — the peer did not respond within the timeout
  • CANCELLED — cancelled
  • MAILBOX_ERROR — mailbox error frame or protocol-layer abort
  • PROTO_MISMATCH / WKC_FAIL — response protocol type / working counter mismatch
  • NO_MEMORY / INVALID_ARG / NOT_IMPLEMENTED — out of memory / invalid argument / not implemented
  • LINK_DOWN — link down (frames fail immediately instead of timing out one by one); check the cable / NIC link status
  • NOT_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:

FieldTypeDescription
totalSentlongTotal transactions sent
totalReceivedlongTotal responses received (including error frames)
totalTimeoutlongTotal timeouts
totalMailboxErrorlongTotal mailbox error frames
totalProtocolErrorlongTotal protocol errors (protocol type / working counter mismatch)
totalCancelledlongTotal cancelled transactions
lastErrorCodelongMost recent error code (0 = none)
lastErrorTimeInstantTime of the most recent error (UTC, null when there is no error)
averageLatencyUsdoubleAverage 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
}
MethodTypeDescription
getValue()intThe ADS result code of the enum constant (read-only)
fromValue(int code)AoEResultCodeStatic 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​

SymptomCauseHandling
read returns null, or write returns falseThe ADS transaction failed (the slave rejected it or the mailbox timed out); read also returns null when the transaction succeeds with readLength = 0Confirm the slave state with readState first, then check the IndexGroup, the IndexOffset and the read length
A call does not return for a long timeThe slave did not answer within the default timeoutSwitch to the overload with timeoutUs and widen it appropriately
isSupported is falseThe slave does not support AoEDo not keep calling; use a protocol that the slave supports
subscribe returns -1Subscription resources are exhausted or the slave rejected the requestReduce 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_ARGThe data passed in is null or an empty arrayPass non-empty data; this is a call error, not a bus fault
setConfig / initializeSlaveNetId throw IllegalArgumentExceptionThe AMS NetID is not exactly 6 bytesMake it 6 bytes; the SDK does not zero-pad or truncate
The future of an asynchronous method completes exceptionallyThe synchronous read/write returned null / falseRead the AoEProtocolException message in exceptionally / get; readAsync with length = 0 behaves the same way
getLastStatus() is always PENDINGNo transaction has been started yetPerform one read or write first; resetStatistics() also resets the status to PENDING