AoE (ADS over EtherCAT)
Accessed through slave.aoe (created lazily, always returns an object). Whether a slave supports AoE is queried with slave.aoe.is_supported: that property only returns True (positive evidence in the mailbox protocol bits) or None (unknown) and never produces False, so it cannot be used to decide "confirmed unsupported".
AoE carries ADS commands over EtherCAT. It reads and writes slave data by IndexGroup / IndexOffset, reads device information and the ADS state, and subscribes to data changes. Normal scanning and PDO process data do not go through it; use it only when the device documentation explicitly provides ADS objects or an ADS state machine.
Method overview
| Category | Method | Type | Read/write | Description |
|---|---|---|---|---|
| Device information | read_device_info | dict or None | read-only | Reads the version number; returns the three keys major / minor / build. The current version does not include the device name |
| read_state | tuple or None | read-only | Reads the ADS state and the device state | |
| State control | write_control | bool | write-only | Switches the slave ADS state |
| get_ads_state_description | str | read-only | Module-level function; converts an ADS state code into a Chinese description | |
| Data read/write | read_write | bytes or None | read/write | Reads by IndexGroup / IndexOffset; leaving the write argument empty makes it a pure read |
| write | bool | write-only | Writes data by IndexGroup / IndexOffset | |
| send_command | bytes or None | read/write | Sends an arbitrary ADS command and retrieves the response data | |
| Notification | add_notification | int or None | write-only | Registers an ADS data notification and returns the notification handle |
| del_notification | bool | write-only | Deletes a notification by handle | |
| Routing configuration | set_config | bool | write-only | Sets the AoE routing (target / source NetID and port) |
| get_config | dict or None | read-only | Reads the current AoE routing configuration | |
| Cross-protocol gateway | read_coe_via_aoe / write_coe_via_aoe | bytes or bool | read/write | Reads and writes CoE objects through the AoE routing |
| read_soe_via_aoe / write_soe_via_aoe | bytes or bool | read/write | Reads and writes SoE IDNs through the AoE routing | |
| initialize_slave_net_id | bool | write-only | Writes the 6-byte AMS Net ID into the slave ADS routing table | |
| Data subscription | AoESubscriptionManager.subscribe | str or None | read/write | Subscribes to data changes and returns the subscription ID; slave.aoe itself has no subscription method |
| AoESubscriptionManager.unsubscribe | bool | write-only | Cancels a subscription by subscription ID | |
| AoESubscriptionManager.unsubscribe_all | int | write-only | Cancels all subscriptions and returns the number of successful cancellations | |
| Async | read_async / write_async / read_write_async | bytes or bool | read/write | Module-level asyncio wrappers that do not block the event loop |
| subscribe_async / unsubscribe_async | str or None / bool | read/write | Asynchronous versions of subscription management |
Properties
| Category | Property | Type | Read/write | Description |
|---|---|---|---|---|
| Capability | is_supported | bool or None | read-only | True = positive evidence in the mailbox protocol bits; None = unknown. This path never produces False |
Device information
read_device_info()
def read_device_info(self) -> Optional[dict]
Reads the ADS device information.
Returns:
dict | None— device information dictionary; returnsNoneon failure. The keys aremajor/minor/build, all integers. The current version does not return the device namename, so do not readinfo['name']
{
'major': int, # major version number
'minor': int, # minor version number
'build': int, # build number
}
Example:
info = slave.aoe.read_device_info()
if info is not None:
print(f"版本: v{info['major']}.{info['minor']}.{info['build']}") # Version: v{info['major']}.{info['minor']}.{info['build']}
read_state()
def read_state(self) -> Optional[Tuple[int, int]]
Reads the ADS state and returns an (ads_state, device_state) tuple; returns None on failure. ads_state is an integer state code (there is no dedicated enum class) and can be turned into a readable string with the module-level function get_ads_state_description().
ADS state codes (integers):
ads_state is a raw integer with the values listed below (the SDK provides the get_ads_state_description mapping):
0— invalid1— idle2— reset3— initialization4— start5— run6— stop7— save configuration8— load configuration9— shutdown10— suspend11— reconfiguration15— error
Example:
result = slave.aoe.read_state()
if result is not None:
ads_state, device_state = result
print(f"ADS 状态: {ads_state}, 设备状态: {device_state}") # ADS state: {ads_state}, device state: {device_state}
write_control()
def write_control(self, ads_state: int, device_state: int,
data: bytes = b'') -> bool
Writes a control command (switches the device state).
get_ads_state_description()
from darra_ethercat.slave.aoe import get_ads_state_description
def get_ads_state_description(ads_state: int) -> str
Gets the ADS state name (a module-level function, not an AoE method).
Example:
from darra_ethercat.slave.aoe import get_ads_state_description
result = slave.aoe.read_state()
if result:
ads_state, device_state = result
name = get_ads_state_description(ads_state)
print(f"ADS 状态: {name} ({ads_state})") # ADS state: {name} ({ads_state})
Data read/write
read_writeAoE has no separate read() method. For a pure ADS read, call read_write(index_group, index_offset, read_length) and leave write_data empty; for a pure write, use write().
read_write() — pure-read usage
# pure read: write_data left empty
data = slave.aoe.read_write(0x4020, 0, 4)
if data is not None and len(data) >= 4:
import struct
value = struct.unpack('<I', data)[0]
print(f"状态值: 0x{value:08X}") # Status value: 0x{value:08X}
write()
def write(self, index_group: int, index_offset: int,
data: bytes) -> bool
Writes ADS data.
Parameters:
index_group(int) — index groupindex_offset(int) — index offsetdata(bytes) — data to write
Returns:
bool— returnsTrueon success
Example:
import struct
slave.aoe.write(0x4020, 0, struct.pack('<I', 0x0006))
read_write()
def read_write(self, index_group: int, index_offset: int,
read_length: int, write_data: bytes = b'') -> Optional[bytes]
ADS read/write operation (reads and writes data at the same time).
Example:
# read data
data = slave.aoe.read_write(0x4020, 0, 4)
if data is not None and len(data) >= 4:
import struct
value = struct.unpack('<I', data)[0]
print(f"值: 0x{value:08X}") # Value: 0x{value:08X}
# write data (read_length=0 means write only)
slave.aoe.read_write(0x4020, 0, 0, struct.pack('<I', 0x0006))
send_command()
def send_command(self, target_port: int, command_id: int,
command_data: bytes = b'') -> Optional[bytes]
Sends an AoE command and receives the response.
Parameters:
target_port(int) — target AMS portcommand_id(int) — ADS command IDcommand_data(bytes) — command data
Returns:
bytes | None— response data; returnsNoneon failure
AoEResultCode enum
Standard result error codes for ADS / AoE operations (ETG.1020 Table 16). The values follow the ETG.1020 Table 16 definitions; the high byte usually indicates the error class (0x0700 ADS device, 0x0740 ADS client).
from darra_ethercat.slave.aoe import AoEResultCode
| Name | Value | Description |
|---|---|---|
| NO_ERROR | 0x0000 | No error |
| INTERNAL_ERROR | 0x0001 | Internal error |
| NO_REALTIME | 0x0002 | No real-time context |
| ALLOCATION_LOCKED_MEMORY_ERROR | 0x0003 | Failed to allocate locked memory |
| INSERT_MAILBOX_ERROR | 0x0004 | Mailbox full |
| WRONG_RECEIVE_HMSG | 0x0005 | Command ID mismatch |
| TARGET_PORT_NOT_FOUND | 0x0006 | Target AMS port not found |
| TARGET_MACHINE_NOT_FOUND | 0x0007 | Target device not found |
| UNKNOWN_COMMAND_ID | 0x0008 | Unknown command ID |
| BAD_TASK_ID | 0x0009 | Invalid task ID |
| NO_IO | 0x000A | No IO channel |
| UNKNOWN_AMS_COMMAND | 0x000B | Unknown AMS command |
| WIN32_ERROR | 0x000C | Win32 error |
| PORT_NOT_CONNECTED | 0x000D | Port not connected |
| INVALID_AMS_LENGTH | 0x000E | Invalid AMS length |
| INVALID_AMS_NET_ID | 0x000F | Invalid AMS Net ID |
| AMS_SYNC_TIMEOUT | 0x0015 | AMS synchronization timeout |
| HOST_UNREACHABLE | 0x001B | Host unreachable |
| WSA_SERVICE_NOT_STARTED | 0x274D | Device service not started |
| DEVICE_INVALID_GROUP | 0x0700 | Invalid IndexGroup on the device |
| DEVICE_INVALID_OFFSET | 0x0701 | Invalid IndexOffset on the device |
| DEVICE_INVALID_ACCESS | 0x0702 | Invalid access on the device |
| DEVICE_INVALID_SIZE | 0x0703 | Invalid data size on the device |
| DEVICE_NOT_READY | 0x0705 | Device not ready |
| DEVICE_BUSY | 0x0706 | Device busy |
| DEVICE_NOT_FOUND | 0x0708 | Device does not exist |
| DEVICE_INVALID_STATE | 0x070C | Invalid device state |
| DEVICE_TIMEOUT | 0x0712 | Device timeout |
| DEVICE_ACCESS_DENIED | 0x071C | Device access denied |
| CLIENT_INVALID_PARAM | 0x0741 | Invalid client parameter |
| CLIENT_INVOKE_TIMEOUT | 0x0744 | Client invocation timeout |
| CLIENT_PORT_NOT_OPEN | 0x0745 | Client port not open |
The table lists only the common entries.
Example:
from darra_ethercat.slave.aoe import AoEResultCode
result = slave.aoe.read_state()
if result is None:
# when read_device_info / read_write / write and similar return None
# compare AoEResultCode to understand what the failure means
print(f"AoE 失败, 错误码可能为 {AoEResultCode.DEVICE_NOT_READY.name}") # AoE failed, error code may be {AoEResultCode.DEVICE_NOT_READY.name}
AoE notification
add_notification()
def add_notification(self, index_group: int, index_offset: int,
length: int, trans_mode: int = 0,
max_delay: int = 0, cycle_time: int = 0) -> Optional[int]
Adds an ADS notification and returns the notification handle.
Parameters:
index_group(int) — index groupindex_offset(int) — index offsetlength(int) — data lengthtrans_mode(int) — transmission mode (0-4, seeAoETransmissionMode)max_delay(int) — maximum delay (in 100 ns units)cycle_time(int) — cycle time (in 100 ns units)
Returns:
int | None— notification handle; returnsNoneon failure
max_delay_ms / cycle_time_ms of AoESubscriptionManager.subscribe are in milliseconds; internally they are multiplied by 10000 to convert to the 100 ns units of this interface.
del_notification()
def del_notification(self, handle: int) -> bool
Deletes an ADS notification.
Returns:
bool— returnsTrueon success
The SDK provides the AoESubscriptionManager class, which wraps the subscription management functions:
from darra_ethercat import AoESubscriptionManager
mgr = AoESubscriptionManager(slave.aoe)
sub_id = mgr.subscribe(0x4020, 0, 4, callback=on_data_changed)
mgr.unsubscribe(sub_id)
mgr.unsubscribe_all()
Routing configuration
set_config()
def set_config(self, target_net_id: bytes, target_port: int,
source_net_id: bytes, source_port: int) -> bool
Sets the AoE routing configuration. The NetID is 6 bytes.
get_config()
def get_config(self) -> Optional[dict]
Gets the AoE routing configuration and returns a dictionary:
{
'target_net_id': bytes, # target NetID (6 bytes)
'target_port': int, # target port
'source_net_id': bytes, # source NetID (6 bytes)
'source_port': int, # source port
}
Cross-protocol gateway
Accesses other mailbox protocols through the AoE routing (ETG.1020); it supports transparent forwarding of the CoE and SoE protocols.
read_coe_via_aoe()
def read_coe_via_aoe(self, index: int, subindex: int,
read_length: int) -> Optional[bytes]
Reads a CoE object through the AoE routing (IndexGroup=0xF302, IndexOffset=(index << 16) | (subindex & 0xFF)).
Parameters:
index(int) — CoE object indexsubindex(int) — CoE subindexread_length(int) — expected read length
Returns:
bytes | None— the data read; returnsNoneon failure
write_coe_via_aoe()
def write_coe_via_aoe(self, index: int, subindex: int,
data: bytes) -> bool
Writes a CoE object through the AoE routing (IndexGroup=0xF302).
read_soe_via_aoe()
def read_soe_via_aoe(self, idn: int, read_length: int) -> Optional[bytes]
Reads an SoE IDN through the AoE routing (IndexGroup=0xF420, IndexOffset=IDN number).
write_soe_via_aoe()
def write_soe_via_aoe(self, idn: int, data: bytes) -> bool
Writes an SoE IDN through the AoE routing (IndexGroup=0xF420).
Example:
# read CoE object 0x6041:0 (status word) through AoE
data = slave.aoe.read_coe_via_aoe(0x6041, 0, 2)
if data is not None:
import struct
status_word = struct.unpack('<H', data)[0]
print(f"状态字: 0x{status_word:04X}") # Status word: 0x{status_word:04X}
# write CoE object 0x6040:0 (control word) through AoE
slave.aoe.write_coe_via_aoe(0x6040, 0, struct.pack('<H', 0x000F))
# read an SoE IDN through AoE
idn_data = slave.aoe.read_soe_via_aoe(32, 4)
initialize_slave_net_id()
def initialize_slave_net_id(self, net_id: bytes) -> bool
Initializes the slave AoE Net ID (ETG.1020 §9.4). Call it during the INIT→PreOp state transition; it writes the Net ID into the slave ADS routing table (IndexGroup=1, IndexOffset=3).
Parameters:
net_id(bytes) — 6-byte AMS Net ID
Returns:
bool— returnsTrueon success
Throws:
ValueError— the Net ID is not 6 bytes
Example:
slave.aoe.initialize_slave_net_id(bytes([5, 80, 187, 177, 1, 1]))
Advanced subscription management
The AoESubscriptionManager class wraps the full subscription management functionality and manages subscriptions by ID. slave.aoe itself has no subscription method, so you must construct the manager yourself:
from darra_ethercat import AoESubscriptionManager
mgr = AoESubscriptionManager(slave.aoe)
subscribe() / unsubscribe() / unsubscribe_all()
def subscribe(self, index_group: int, index_offset: int, length: int,
trans_mode: int = AoETransmissionMode.ON_CHANGE,
max_delay_ms: int = 0, cycle_time_ms: int = 100,
callback: Optional[Callable[[bytes], None]] = None
) -> Optional[str]
def unsubscribe(self, subscription_id: str) -> bool
def unsubscribe_by_handle(self, handle: int) -> bool
def unsubscribe_all(self) -> int
subscribe() registers a data-change notification and returns the subscription ID (a UUID string) on success, or None on failure. The callback signature is callback(data: bytes) and may be None. unsubscribe() cancels by subscription ID (recommended); unsubscribe_by_handle() cancels by notification handle (for compatibility with older usage). Both remove the registration and notify the slave, and return False when the handle / ID does not exist. unsubscribe_all() cancels all subscriptions and returns the number of successful cancellations.
AoETransmissionMode
class AoETransmissionMode(IntEnum):
NO_TRANSMISSION = 0 # no notification
CYCLIC = 1 # cyclic notification - sent at the given cycle
ON_CHANGE = 2 # change notification - sent when the data changes
CYCLIC_IN_DEVICE = 3 # cyclic notification generated on the device
ON_CHANGE_IN_DEVICE = 4 # change notification generated on the device
AoESubscription
@dataclass
class AoESubscription:
handle: int # notification handle
slave_index: int # slave index
index_group: int # index group
index_offset: int # index offset
length: int # data length
callback: Optional[Callable] # callback function
subscription_id: str # unique subscription ID (UUID)
trans_mode: int # transmission mode
is_active: bool # whether the subscription is active
tag: object # arbitrary tag (default None)
Example:
from darra_ethercat import AoESubscriptionManager
from darra_ethercat.slave import AoETransmissionMode
mgr = AoESubscriptionManager(slave.aoe)
# subscribe to data-change notifications
sub_id = mgr.subscribe(
index_group=0x4020, index_offset=0, length=4,
trans_mode=AoETransmissionMode.ON_CHANGE,
cycle_time_ms=100,
callback=lambda data: print(f"数据变化: {data.hex()}") # Data change: {data.hex()}
)
# get the list of active subscriptions
active = mgr.get_active_subscriptions()
print(f"活跃订阅数: {mgr.active_count}") # Active subscription count: {mgr.active_count}
# cancel by ID
mgr.unsubscribe(sub_id)
# cancel all subscriptions
mgr.unsubscribe_all()
Subscription manager properties
| Category | Property | Type | Read/write | Description |
|---|---|---|---|---|
| Subscription management | active_count | int | read-only | Current number of active subscriptions |
| all_handles | list[int] | read-only | List of all active notification handles |
Query subscriptions by handle / ID
def get_subscription(self, handle: int) -> Optional[AoESubscription]
def get_subscription_by_id(self, subscription_id: str) -> Optional[AoESubscription]
def unsubscribe_by_handle(self, handle: int) -> bool
def get_active_subscriptions(self) -> List[AoESubscription]
get_subscription() keeps the older handle-style lookup; get_subscription_by_id() is recommended for new code (a UUID does not collide with handles that have already been deleted). get_active_subscriptions() returns a copy of the list of currently active subscriptions.
sub = mgr.get_subscription_by_id(sub_id)
if sub and sub.is_active:
print(f"订阅 slave={sub.slave_index} group=0x{sub.index_group:08X}") # Subscribed slave={sub.slave_index} group=0x{sub.index_group:08X}
Asynchronous subscription and read/write (asyncio)
An AoE mailbox round trip usually takes 10-50 ms, and a synchronous call blocks the event loop. The asynchronous versions run on a dedicated thread pool and do not block the event loop.
subscribe_async() / unsubscribe_async() / unsubscribe_all_async()
async def subscribe_async(self, index_group: int, index_offset: int,
length: int,
trans_mode: int = AoETransmissionMode.ON_CHANGE,
max_delay_ms: int = 0, cycle_time_ms: int = 100,
callback: Optional[Callable[[bytes], None]] = None,
timeout_ms: Optional[int] = None) -> Optional[str]
async def unsubscribe_async(self, subscription_id: str,
timeout_ms: Optional[int] = None) -> bool
async def unsubscribe_all_async(self,
timeout_ms: Optional[int] = None) -> int
Asynchronous versions of subscribe / unsubscribe. When timeout_ms fires, asyncio.TimeoutError is raised, but the background thread still runs the single synchronous call to completion.
import asyncio
from darra_ethercat import AoESubscriptionManager
from darra_ethercat.slave import AoETransmissionMode
async def main():
mgr = AoESubscriptionManager(slave.aoe)
sub_id = await mgr.subscribe_async(
index_group=0x4020, index_offset=0, length=4,
trans_mode=AoETransmissionMode.ON_CHANGE,
callback=lambda data: print(f"通知: {data.hex()}"), # Notification: {data.hex()}
timeout_ms=2000,
)
if sub_id is None:
print("订阅失败") # Subscription failed
return
await asyncio.sleep(10)
await mgr.unsubscribe_async(sub_id)
asyncio.run(main())
read_async() / write_async() / read_write_async()
from darra_ethercat.slave.aoe import read_async, write_async, read_write_async
async def main():
data = await read_async(slave.aoe, 0x4020, 0, 4, timeout_ms=500)
if data is not None:
print(f"值: {data.hex()}") # Value: {data.hex()}
await write_async(slave.aoe, 0x4020, 0, b'\x06\x00\x00\x00',
timeout_ms=500)
read_write_async() calls the underlying read_write first (read and write in one mailbox round trip); when that is unavailable it falls back to write_async followed by read_async.
shutdown_aoe_async_executor()
from darra_ethercat.slave.aoe import shutdown_aoe_async_executor
shutdown_aoe_async_executor(wait=True)
Shuts down the thread pool dedicated to the AoE protocol before the process exits, either waiting for (wait=True) or not waiting for the submitted tasks to finish.
Full example
Data read/write
# is_supported is only ever True or None; None = unknown, still worth trying, do not treat it as "unsupported"
if slave.aoe.is_supported is not False:
import struct
# device information (the current version has no device name)
info = slave.aoe.read_device_info()
if info is not None:
print(f"版本: v{info['major']}.{info['minor']}.{info['build']}") # Version: v{info['major']}.{info['minor']}.{info['build']}
# state
from darra_ethercat.slave.aoe import get_ads_state_description
result = slave.aoe.read_state()
if result:
ads_state, device_state = result
name = get_ads_state_description(ads_state)
print(f"ADS 状态: {name} ({ads_state}), 设备状态: {device_state}") # ADS state: {name} ({ads_state}), device state: {device_state}
# read data (a pure read goes through read_write with write_data left empty)
data = slave.aoe.read_write(0x4020, 0, 4)
if data is not None and len(data) >= 4:
print(f"值: 0x{struct.unpack('<I', data)[0]:08X}") # Value: 0x{struct.unpack('<I', data)[0]:08X}
# write data
slave.aoe.write(0x4020, 0, struct.pack('<I', 0x0006))
# switch the device state
slave.aoe.write_control(5, 0) # switch to the Run state
Data subscription
from darra_ethercat import AoESubscriptionManager
from darra_ethercat.slave import AoETransmissionMode
if slave.aoe.is_supported is not False:
mgr = AoESubscriptionManager(slave.aoe)
sub_id = mgr.subscribe(
index_group=0x4020, index_offset=0, length=4,
trans_mode=AoETransmissionMode.ON_CHANGE,
cycle_time_ms=100,
callback=lambda data: print(f"数据变化: {data.hex()}") # Data change: {data.hex()}
)
import time
time.sleep(10)
mgr.unsubscribe_all()
Cross-protocol gateway
if slave.aoe.is_supported is not False:
import struct
# read CoE object 0x6041:0 (status word) through AoE
data = slave.aoe.read_coe_via_aoe(0x6041, 0, 2)
if data is not None:
status_word = struct.unpack('<H', data)[0]
print(f"状态字: 0x{status_word:04X}") # Status word: 0x{status_word:04X}
# write CoE object 0x6040:0 (control word) through AoE
slave.aoe.write_coe_via_aoe(0x6040, 0, struct.pack('<H', 0x000F))
# read an SoE IDN through AoE
idn_data = slave.aoe.read_soe_via_aoe(32, 4)
if idn_data is not None:
print(f"IDN 32 值: {struct.unpack('<I', idn_data)[0]}") # IDN 32 value: {struct.unpack('<I', idn_data)[0]}
Failures and handling
| Symptom | Cause | Handling |
|---|---|---|
| Read returns None while the slave is still running | ADS returned a result code other than 0 (the object does not exist, access is denied, or the device is busy); compare AoEResultCode to understand the failure | Check IndexGroup / IndexOffset and the length, shorten the read length and retry |
| The call fails after a long time without returning | Mailbox timeout (the slave is busy or the mailbox is not ready) | Reduce the call frequency, confirm the slave has reached a communicable state and retry |
| Every call fails and is_supported is None | The slave may not support AoE, or the mailbox protocol bits cannot be read (None only means unknown) | Use CoE / SoE to read the same object; retrying will not solve it |