AoE (ADS over EtherCAT)
The AoE protocol implements ADS (Automation Device Specification) over EtherCAT communication.
Get an AoEInstance through slave.aoe() — the method returns the AoEInstance directly (not an Option); use aoe.aoe_support() to determine whether AoE is really supported.
The read and write methods (read() / write()) use a fixed default timeout internally (500 ms); use read_with_timeout() or read_write() when a custom timeout is needed.
Protocol capability detection
pub fn aoe_support(&self) -> Option<bool>
pub fn is_support_known(&self) -> bool
pub fn is_supported(&self) -> bool
AoE has no dedicated details bit in the SII General Category, only the mailbox protocol bit word (mbx_proto bit0). On the ESI exact-match fast path that word is hard-coded to CoE (0x0004), so bit0 = 0 cannot prove lack of support — it only yields a positive conclusion.
Some(true)— bit0 is set, supportedNone— unknown (there is no authoritative negative evidence, so it cannot be folded into false)
is_supported() is the bool view: true only for Some(true). When you need to distinguish "unknown" from "not supported", use is_support_known() or read aoe_support() directly.
Data read and write
read()
pub fn read(&self, index_group: u32, index_offset: u32, length: u32) -> Result<Option<Vec<u8>>>
Reads ADS data (using the internal default timeout of 500 ms).
Parameters:
index_group(u32) — index groupindex_offset(u32) — index offsetlength(u32) — read length
Returns:
Result<Option<Vec<u8>>>— the data read; returnsOk(None)when there is no data
Example:
let aoe = slave.aoe();
if let Some(status) = aoe.read(0x4020, 0, 4)? {
let value = u32::from_le_bytes(status[0..4].try_into()?);
println!("状态值: 0x{:08X}", value); // Status value: 0x{:08X}
}
read_with_timeout()
pub fn read_with_timeout(&self, index_group: u32, index_offset: u32,
length: u32, timeout_us: i32) -> Result<Option<Vec<u8>>>
Reads ADS data (with the specified timeout).
write()
pub fn write(&self, index_group: u32, index_offset: u32, data: &[u8]) -> Result<()>
Writes ADS data (using the internal default timeout of 500 ms).
Parameters:
index_group(u32) — index groupindex_offset(u32) — index offsetdata(&[u8]) — data to write
Returns:
Result<()>— success or error
Example:
aoe.write(0x4020, 0, &0x0006u32.to_le_bytes())?;
read_write()
pub fn read_write(&self, index_group: u32, index_offset: u32, read_length: u32,
write_data: Option<&[u8]>, timeout_us: i32) -> Result<Option<Vec<u8>>>
Reads and writes data in one operation (the ADS ReadWrite command).
Parameters:
index_group(u32) — index groupindex_offset(u32) — index offsetread_length(u32) — read length; 0 means a pure writewrite_data(Option<&[u8]>) — data to write; empty means a pure readtimeout_us(i32) — timeout in microseconds
Returns:
Result<Option<Vec<u8>>>— the data read
read_write_ex()
pub fn read_write_ex(
&self,
index_group: u32,
index_offset: u32,
read_length: u32,
write_data: Option<&[u8]>,
timeout_us: i32,
) -> Result<Option<Vec<u8>>>
The ADS ReadWrite variant that reports the actual length: the returned Vec is as long as the bytes the device actually read back, not the requested read_length. The difference from read_write() is that it requires read_length > 0 (at most 10 MiB), so it cannot be used as a pure write — use write() for a pure write and read() / read_with_timeout() for a pure read.
Parameters:
index_group(u32) — index groupindex_offset(u32) — index offsetread_length(u32) — number of bytes to read back; must be> 0and no more than 10 MiBwrite_data(Option<&[u8]>) — data to write;Nonemeans no writetimeout_us(i32) — timeout in microseconds
Returns:
Ok(Some(Vec<u8>))— the transaction succeeded and the device read data back; the length is the actual number of bytes readOk(None)— the transaction succeeded but no data was read back (actual length 0)Err(DarraError::AoeFailed)—read_lengthis 0 or above 10 MiB / the total request size exceeds the single-mailbox capacity (this method does not fragment; use the fragmented send and receive for oversized payloads) / the transaction with the slave failed
Example:
// Write 4 bytes and read back up to 64 bytes; the Vec length is the length the device actually returned
let reply = aoe.read_write_ex(0x4020, 0, 64, Some(&0x0006u32.to_le_bytes()), 500_000)?;
if let Some(bytes) = reply {
println!("实际回读 {} 字节", bytes.len()); // Actually read back {} bytes
}
Fragmented send and receive
When one ADS request or response exceeds the single-mailbox capacity, split it into several fragments with the ETG.1020 §9.3 fragmentation mechanism (command 0x0902) and send and receive them serially. The two methods are used as a pair; packet_number is specified by the caller and shared across the fragments — incrementing it per command is recommended, and the receiving side filters fragments by this number.
Fragmentation condition: the payload is split only when it exceeds "slave mailbox length minus fragment header length"; the first 16 bytes of the complete request (NetID + Port) are reused by the fragment header and are not counted as fragment payload. Sending and receiving both block inside the call and are bounded by the same overall timeout budget.
send_fragmented()
pub fn send_fragmented(&self, payload: &[u8], packet_number: u16, timeout_us: i32) -> Result<()>
Parameters:
payload(&[u8]) — the complete AoE request (32-byte AoE header + ADS body); the length must be ≥ 32, otherwise it returnsErrpacket_number(u16) — fragment number of this command, shared by the fragmentstimeout_us(i32) — the total budget for the whole send (microseconds; 1 second when<= 0), not the timeout of each fragment; the transfer is aborted once the budget is exceeded
Returns:
Ok(())— all fragments were sent successfullyErr(DarraError::AoeFailed)— the payload is too short / the slave cannot send mailboxes in its current state (for example during initialization) / any fragment failed to send / the total budget was exceeded
recv_reassemble()
pub fn recv_reassemble(&self, out_capacity: usize, packet_number: u16, timeout_us: i32) -> Result<Vec<u8>>
Parameters:
out_capacity(usize) — reassembly buffer capacity; must be> 0: passing0returnsErr(DarraError::InvalidParameter)directly, while passing1..31makes the lower layer returnErr(DarraError::AoeFailed)for insufficient capacitypacket_number(u16) — accept only fragments with this number; fragments with any other number are droppedtimeout_us(i32) — timeout for waiting and reassembly (microseconds; 1 second when<= 0)
Returns:
Ok(Vec<u8>)— the reassembled AoE response; the length is the actual number of reassembled bytes (truncated to the actual length, notout_capacity)Err(DarraError::AoeFailed)— timeout / fragment number or order mismatch / the reassembled result exceedsout_capacity/ the slave cannot receive mailboxes in its current state
Example:
let payload = build_request(); // Complete AoE request, at least 32 bytes
aoe.send_fragmented(&payload, 7, 500_000)?;
let reply = aoe.recv_reassemble(64 * 1024, 7, 500_000)?;
println!("重组收到 {} 字节", reply.len()); // Received {} bytes after reassembly
Device information
read_device_info()
pub fn read_device_info(&self) -> Result<(u8, u8, u16, String)>
Reads the ADS device information (using the internal default timeout). The method returns a tuple, not a struct.
Returns:
Result<(u8, u8, u16, String)>—(major_version, minor_version, build, device_name)
Example:
let (major, minor, build, name) = aoe.read_device_info()?;
println!("设备: {} v{}.{}.{}", name, major, minor, build); // Device: {} v{}.{}.{}
read_state()
pub fn read_state(&self) -> Result<(u16, u16)>
Reads the ADS state (using the internal default timeout). The method takes no parameters and returns a tuple.
Returns:
Result<(u16, u16)>—(ads_state, device_state)tuple
Meaning of the ADS state values (standard ADS state codes): 0=Invalid 1=Idle 2=Reset 3=Init 4=Start 5=Run 6=Stop 7=SaveConfig 8=LoadConfig 9=PowerFailure 10=PowerGood 11=Error 12=Shutdown 13=Suspend 14=Resume 15=Config 16=Reconfig.
Use the associated function AoEInstance::ads_state_name(ads_state) to get the state name.
Example:
let (ads_state, device_state) = aoe.read_state()?;
println!("ADS 状态: {} ({}), 设备状态: {}", // ADS state: {} ({}), device state: {}
AoEInstance::ads_state_name(ads_state), ads_state, device_state);
write_control()
pub fn write_control(&self, ads_state: u16, device_state: u16,
data: Option<&[u8]>) -> Result<()>
Writes a control command (switching the device state, using the internal default timeout).
Parameters:
ads_state(u16) — target ADS statedevice_state(u16) — target device statedata(Option<&[u8]>) — additional data (optional)
Returns:
Result<()>— success or error
Example:
aoe.write_control(5, 0, None)?; // switch to the Run state
send_command()
pub fn send_command(&self, target_port: u16, command_id: u16,
command_data: Option<&[u8]>, timeout_us: i32) -> Result<(bool, Option<Vec<u8>>)>
Sends a custom AoE command to the target port and returns whether it was accepted together with optional response data.
Parameters:
target_port(u16) — target portcommand_id(u16) — command IDcommand_data(Option<&[u8]>) — command data (optional)timeout_us(i32) — timeout (microseconds)
Returns:
Result<(bool, Option<Vec<u8>>)>— (accepted, response data)
ads_state_name()
pub fn ads_state_name(ads_state: u16) -> &'static str
Gets the ADS state name.
Data subscription
AoEInstance itself provides the low-level add_notification() / del_notification(), but AoeSubscriptionManager is recommended for registering and unregistering multiple subscriptions and for automatic cleanup on Drop. The subscription transfer mode enum is AoeTransMode (there is no AoETransmissionMode type).
add_notification() / del_notification()
pub fn add_notification(
&self,
index_group: u32,
index_offset: u32,
length: u32,
trans_mode: u32,
max_delay: u32,
cycle_time: u32,
) -> Result<u32>
pub fn del_notification(&self, handle: u32) -> Result<()>
add_notification() registers an ADS device notification and returns a notification handle (u32); del_notification() unregisters it by handle. trans_mode takes the numeric value of AoeTransMode (AoeTransMode::OnChange as u32 and so on). Callback registration and dispatch are managed centrally by AoeSubscriptionManager (which owns the AOENotificationCallback); for day-to-day use, prefer the manager directly.
AoE configuration
set_config()
pub fn set_config(&self, target_net_id: &[u8; 6], target_port: u16,
source_net_id: &[u8; 6], source_port: u16) -> Result<()>
Sets the AoE routing configuration (AMS NetID and ports).
Example:
aoe.set_config(&[5, 80, 187, 177, 1, 1], 851,
&[192, 168, 1, 100, 1, 1], 32768)?;
config()
pub fn config(&self) -> Result<([u8; 6], u16, [u8; 6], u16)>
Gets the AoE routing configuration and returns the (target_net_id, target_port, source_net_id, source_port) tuple.
initialize_slave_net_id()
pub fn initialize_slave_net_id(&self, net_id: &[u8; 6]) -> Result<()>
Initializes the slave AoE Net ID (ETG.1020 §9.4). Call it during the INIT→PreOp state transition.
Example:
aoe.initialize_slave_net_id(&[5, 80, 187, 177, 1, 1])?;
init_slave_net_id()
pub fn init_slave_net_id(&self, master_net_id: Option<&[u8; 6]>, timeout_us: i32) -> Result<i32>
It belongs to the same ETG.1020 §9.4 NetID write as initialize_slave_net_id() (IndexGroup=1, IndexOffset=3); the scope, the NetID source and the return value are what differ:
| Item | initialize_slave_net_id() | init_slave_net_id() |
|---|---|---|
| Scope | The single slave the current AoEInstance refers to | Every AoE-capable slave under this master, written one by one |
| NetID source | Required &[u8; 6] | Option: Some uses the given bits, None writes all 0s (so the master can overwrite it later) |
| Return value | Result<()> | Result<i32>: number of slaves written successfully |
| Timeout | Fixed 500 ms | timeout_us (microseconds, applied per slave) |
Parameters:
master_net_id(Option<&[u8; 6]>) — master NetID;Nonewrites all 0stimeout_us(i32) — write timeout for each slave (microseconds)
Returns:
Ok(n)— number of slaves written successfully (n >= 0;0means no slave accepted this write)Err(DarraError::AoeFailed)— the master index is invalid or the master is not initialized (the lower layer returns a negative value)
During the write a temporary route is formed from "master NetID + slave station address"; the previous routing configuration is restored as soon as the write completes, so NetID / Port values set by the application layer are not affected.
Cross-protocol gateway
AoE routing provides access to other mailbox protocols (ETG.1020) and supports transparent forwarding for CoE and SoE.
read_coe_via_aoe()
pub fn read_coe_via_aoe(&self, index: u16, subindex: u8,
read_length: u32) -> Result<Option<Vec<u8>>>
Reads a CoE object through AoE routing (IndexGroup=0xF302, IndexOffset=(index << 16) | subindex).
write_coe_via_aoe()
pub fn write_coe_via_aoe(&self, index: u16, subindex: u8,
data: &[u8]) -> Result<()>
Writes a CoE object through AoE routing (IndexGroup=0xF302).
read_soe_via_aoe()
pub fn read_soe_via_aoe(&self, idn: u32, read_length: u32) -> Result<Option<Vec<u8>>>
Reads a SoE IDN through AoE routing (IndexGroup=0xF420, IndexOffset=the IDN number).
write_soe_via_aoe()
pub fn write_soe_via_aoe(&self, idn: u32, data: &[u8]) -> Result<()>
Writes a SoE IDN through AoE routing (IndexGroup=0xF420).
Example:
// Read CoE object 0x6041:0 (status word) through AoE
if let Some(data) = aoe.read_coe_via_aoe(0x6041, 0, 2)? {
let status = u16::from_le_bytes(data[0..2].try_into()?);
println!("状态字: 0x{:04X}", status); // Status word: 0x{:04X}
}
// Write CoE object 0x6040:0 (control word) through AoE
aoe.write_coe_via_aoe(0x6040, 0, &0x000Fu16.to_le_bytes())?;
// Read a SoE IDN through AoE
if let Some(idn_data) = aoe.read_soe_via_aoe(32, 4)? {
println!("IDN 32: {:?}", idn_data);
}
Message diagnostics
Two diagnostic entry points: one reads the InvokeId of the most recent request (to check that a response is paired), the other clears the most recent error record of this slave.
peek_invoke_id()
pub fn peek_invoke_id(&self) -> u32
Returns the InvokeId used by the most recent AoE request of this master and this slave, for response comparison and troubleshooting.
- Returns
u32— the InvokeId of the most recent request;0when the master / slave index is invalid or the slave has not yet sent an AoE request - Read-only: it sends no message and changes no state
clear_last_error()
pub fn clear_last_error(&self)
Clears the most recent AoE error record of this slave (the one last_error() reads); it returns nothing and has no failure branch. Use it to clear old errors before an operation so that a failure from the previous round is not misread as the result of the current one.
aoe.clear_last_error();
// Then check whether last_error() shows a new error record
Error codes
AoEResultCode enum
ADS over EtherCAT standard error codes (ETG.1020 Table 16). #[repr(u32)]; the values follow the ETG.1020 Table 16 definition: high byte = error class (0x0700 = ADS device, 0x0740 = client), low byte = the specific error code.
The read and write methods of AoEInstance return Err(DarraError::AoeFailed) when ADS fails; AoEResultCode is the specific sub-code of the ADS protocol layer, matched from the raw numeric value with AoEResultCode::from_u32(code).
#[repr(u32)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AoEResultCode {
NoError = 0x0000,
InternalError = 0x0001,
NoRealTime = 0x0002,
AllocationLockedMemoryError = 0x0003,
InsertMailboxError = 0x0004,
WrongReceiveHMsg = 0x0005,
TargetPortNotFound = 0x0006,
TargetMachineNotFound = 0x0007,
UnknownCommandId = 0x0008,
BadTaskId = 0x0009,
NoIO = 0x000A,
UnknownAmsCommand = 0x000B,
Win32Error = 0x000C,
PortNotConnected = 0x000D,
InvalidAmsLength = 0x000E,
InvalidAmsNetId = 0x000F,
LowInstLevel = 0x0010,
NoDebugAvailable = 0x0011,
PortDisabled = 0x0012,
PortAlreadyConnected = 0x0013,
AmsSyncWin32Error = 0x0014,
AmsSyncTimeout = 0x0015,
AmsSyncAmsError = 0x0016,
AmsSyncNoIndexMap = 0x0017,
InvalidAmsPort = 0x0018,
NoMemory = 0x0019,
TcpSendError = 0x001A,
HostUnreachable = 0x001B,
InvalidAmsFragment = 0x001C,
WsaServiceNotStarted = 0x274D,
DeviceInvalidGroup = 0x0700,
DeviceInvalidOffset = 0x0701,
DeviceInvalidAccess = 0x0702,
DeviceInvalidSize = 0x0703,
DeviceInvalidData = 0x0704,
DeviceNotReady = 0x0705,
DeviceBusy = 0x0706,
DeviceInvalidContext = 0x0707,
DeviceNotFound = 0x0708,
DeviceAlreadyExists = 0x0709,
DeviceSymbolNotFound = 0x070A,
DeviceSymbolVersionInvalid = 0x070B,
DeviceInvalidState = 0x070C,
DeviceTimeout = 0x0712,
DeviceNoInterfaceQuery = 0x0713,
DeviceInvalidInterface = 0x0714,
DeviceInvalidClassId = 0x0715,
DeviceInvalidObjectId = 0x0716,
DevicePending = 0x0717,
DeviceAborted = 0x0718,
DeviceWarning = 0x0719,
DeviceInvalidArrayIndex = 0x071A,
DeviceSymbolNotActive = 0x071B,
DeviceAccessDenied = 0x071C,
ClientError = 0x0740,
ClientInvalidParam = 0x0741,
ClientListEmpty = 0x0742,
ClientVarAlreadyInUse = 0x0743,
ClientInvokeTimeout = 0x0744,
ClientPortNotOpen = 0x0745,
ClientNotStarted = 0x0746,
ClientQueueFull = 0x0750,
}
impl AoEResultCode {
/// Match the enum from a raw u32 value (returns None when unmatched)
pub fn from_u32(code: u32) -> Option<Self>;
/// Numeric value
pub fn value(self) -> u32;
}
Example:
if let Err(e) = aoe.read(0x4020, 0, 4) {
eprintln!("AoE 失败: {:?}", e); // DarraError::AoeFailed
}
// Raw ADS Result codes pulled from errors returned by the runtime can be compared against the enum
if let Some(code) = AoEResultCode::from_u32(0x0705) {
println!("ADS 错误: {:?}", code); // DeviceNotReady
}
Mailbox protocol common interface (MailboxProtocol)
AoEInstance implements the unified mailbox protocol interface, so it can share one set of protocol management and statistics code with CoE / FoE / SoE / EoE instances. These two methods come from the trait, so bring it into scope before calling:
use darra_ethercat::abstractions::MailboxProtocol;
| Method | Returns | Description |
|---|---|---|
| protocol_type() | u8 | Mailbox protocol type; AoE is fixed at 0x01 (under the same interface EoE=0x02 / CoE=0x03 / FoE=0x04 / SoE=0x05) |
| protocol_name() | &'static str | Protocol name; AoE is fixed at "AoE" |
Both are constant queries: no side effects and no mailbox transaction. The same trait also provides is_supported() / last_status() / statistics() / reset_statistics() for a uniform query of protocol support and mailbox statistics.
Asynchronous read and write
The round trip of an ADS message is usually 1 ms to a few tens of ms, so asynchronous concurrency is recommended when reading and writing several variables. The SDK offers two paths:
- std::thread dual track — no tokio dependency; use the associated functions
AoEInstance::read_blocking()/write_blocking(), which return aJoinHandle; suits scenarios that do not want to pull in an async runtime. - tokio async — enabling the
async-tokiofeature exposesread_async()/write_async(), which can be.awaited inside anasync fnand run concurrently withtokio::join!.
read_async() / write_async() (tokio)
pub async fn read_async(
&self,
index_group: u32,
index_offset: u32,
length: u32,
) -> Result<Option<Vec<u8>>>
pub async fn write_async(
&self,
index_group: u32,
index_offset: u32,
data: Vec<u8>,
) -> Result<()>
Available after enabling the async-tokio feature. Internally it dispatches to the blocking thread pool with tokio::task::spawn_blocking and never starves the tokio scheduler. read_async returns Result<Option<Vec<u8>>> exactly like the synchronous read(); write_async takes an owned data: Vec<u8>.
Example:
use tokio::join;
let (a, b, c) = join!(
aoe.read_async(0x4020, 0, 4),
aoe.read_async(0x4020, 4, 4),
aoe.read_async(0x4020, 8, 4),
);
let (a, b, c) = (a?, b?, c?);
println!("并发读取完成: {:?} {:?} {:?}", a, b, c); // Concurrent read complete: {:?} {:?} {:?}
read_blocking() / write_blocking()
// associated function (not a method); master_index / slave_index are passed explicitly
pub fn read_blocking(
master_index: u16,
slave_index: u16,
index_group: u32,
index_offset: u32,
length: u32,
) -> std::thread::JoinHandle<Result<Option<Vec<u8>>>>
pub fn write_blocking(
master_index: u16,
slave_index: u16,
index_group: u32,
index_offset: u32,
data: Vec<u8>,
) -> std::thread::JoinHandle<Result<()>>
A blocking plus background-thread version that does not depend on tokio. These are associated functions on AoEInstance; the master/slave indices are passed directly and the caller waits with join().
Example:
let h1 = AoEInstance::read_blocking(master.index(), 1, 0x4020, 0, 4);
let h2 = AoEInstance::read_blocking(master.index(), 1, 0x4020, 4, 4);
// Err from join = the background thread panicked; surface it as an error instead of swallowing it
let a = match h1.join() {
Ok(r) => r?,
Err(p) => return Err(darra_ethercat::DarraError::Other(format!("读线程异常退出: {p}"))), // Read thread exited abnormally: {p}
};
let b = match h2.join() {
Ok(r) => r?,
Err(p) => return Err(darra_ethercat::DarraError::Other(format!("读线程异常退出: {p}"))), // Read thread exited abnormally: {p}
};
If the project already pulls in tokio, use read_async/write_async; otherwise use read_blocking/write_blocking.
Complete example
Data read and write
let aoe = slave.aoe();
if aoe.aoe_support() != Some(true) {
return Ok(());
}
// Read data (read takes 3 parameters, uses the internal default timeout; returns Result<Option<Vec<u8>>>)
if let Some(status) = aoe.read(0x4020, 0, 4)? {
let value = u32::from_le_bytes(status[0..4].try_into()?);
println!("状态: 0x{:08X}", value); // Status: 0x{:08X}
}
// Write data (write takes 3 parameters)
aoe.write(0x4020, 0, &0x0006u32.to_le_bytes())?;
// Device information (read_device_info takes no parameters and returns a tuple)
let (major, minor, build, name) = aoe.read_device_info()?;
println!("设备: {} v{}.{}.{}", name, major, minor, build); // Device: {} v{}.{}.{}
Cross-protocol gateway
let aoe = slave.aoe();
if aoe.aoe_support() != Some(true) {
return Ok(());
}
// Read a CoE object through AoE
if let Some(data) = aoe.read_coe_via_aoe(0x6041, 0, 2)? {
let status = u16::from_le_bytes(data[0..2].try_into()?);
println!("状态字: 0x{:04X}", status); // Status word: 0x{:04X}
}
// Write a CoE object through AoE
aoe.write_coe_via_aoe(0x6040, 0, &0x000Fu16.to_le_bytes())?;
// Read and write SoE IDNs through AoE
if let Some(idn_data) = aoe.read_soe_via_aoe(32, 4)? {
println!("IDN 32: {:?}", idn_data);
}
aoe.write_soe_via_aoe(32, &[0x01, 0x00, 0x00, 0x00])?;
Cross-protocol gateway API
Four methods that read and write CoE / SoE objects directly over the AoE mailbox routing defined by the ETG.1020 standard IndexGroups. They do not use the slave CoE mailbox channel, which suits gateway-type devices whose master protocol is AoE.
read_coe_via_aoe / write_coe_via_aoe
pub fn read_coe_via_aoe(&self, index: u16, subindex: u8, read_length: u32) -> Result<Option<Vec<u8>>>
pub fn write_coe_via_aoe(&self, index: u16, subindex: u8, data: &[u8]) -> Result<()>
IndexGroup = 0xF302, IndexOffset = (index << 16) | subindex, default timeout 500 ms.
read_soe_via_aoe / write_soe_via_aoe
pub fn read_soe_via_aoe(&self, idn: u32, read_length: u32) -> Result<Option<Vec<u8>>>
pub fn write_soe_via_aoe(&self, idn: u32, data: &[u8]) -> Result<()>
IndexGroup = 0xF420, IndexOffset = idn.
initialize_slave_net_id
pub fn initialize_slave_net_id(&self, net_id: &[u8; 6]) -> Result<()>
ETG.1020 §9.4: writes the local Net ID into the slave ADS routing table (IndexGroup=1, IndexOffset=3) during the IP→PreOp state transition. It must be called once before AoE communication is bound.
AoE subscription manager
[AoeSubscriptionManager] wraps registration / unregistration of multiple subscriptions and automatic cleanup on Drop; internally it indexes subscriptions in a HashMap by string key.
Creation and registration
pub fn new(master_index: u16) -> Self
pub fn subscribe<T>(
&mut self,
name: impl Into<String>,
config: AoeSubscription,
callback: AOENotificationCallback,
user_data: std::sync::Arc<T>,
) -> Result<u32>
where
T: Send + Sync + 'static,
The callback is a bare function pointer type (not wrapped in Some(...)):
pub type AOENotificationCallback = extern "C" fn(
master_index: u16, slave: u16, handle: u32, timestamp: u64,
data: *const u8, data_size: u32, user_data: *mut std::ffi::c_void,
);
name is globally unique within the manager; if a subscription with the same name already exists, it returns Err. config is built with AoeSubscription::on_change or AoeSubscription::cyclic. The returned Result<u32> is the subscription handle id.
user_data is a generic Arc<T> (T: Send + Sync + 'static) held as a strong reference by the manager; no raw pointer parameter is taken: the referenced object stays valid for the whole lifetime of the subscription and can never have been released by the caller when the callback fires; inside the callback, recover &T with user_data as *const T. The unregistration order rules out dangling: the notification is unregistered first (no further callbacks), then the Arc is released.
Unregistration
pub fn unsubscribe(&mut self, name: &str) -> Result<()>
pub fn unsubscribe_all(&mut self)
unsubscribe performs a two-step unregistration through AOEUnregisterNotification + AOEDelNotification; unsubscribe_all is called automatically by Drop and can also be invoked manually to clear everything.
Queries
pub fn has_subscription(&self, name: &str) -> bool
pub fn subscription_count(&self) -> usize
pub fn subscription_names(&self) -> Vec<&str>
pub fn active_subscriptions(&self) -> Vec<&str>
pub fn subscription_config(&self, name: &str) -> Option<&AoeSubscription>
pub fn subscription_handle(&self, name: &str) -> Option<u32>
active_subscriptions and subscription_names are equivalent in the current implementation and can be used interchangeably.
AoeSubscription
pub struct AoeSubscription {
pub slave_index: u16,
pub index_group: u32,
pub index_offset: u32,
pub length: u32,
pub trans_mode: AoeTransMode,
pub max_delay_us: u32,
pub cycle_time_us: u32,
pub timeout_us: i32,
}
#[repr(u32)]
pub enum AoeTransMode {
NoTransmission = 0,
Cyclic = 1,
OnChange = 2,
CyclicInDevice = 3,
OnChangeInDevice = 4,
}
Constructors:
AoeSubscription::on_change(slave, ig, io, length, timeout_us)
AoeSubscription::cyclic(slave, ig, io, length, cycle_time_us, timeout_us)
Complete example
use darra_ethercat::slave::aoe::{AoeSubscriptionManager, AoeSubscription};
use std::sync::Arc;
// Context carried by the callback: the manager holds a strong reference for the lifetime of the subscription
struct NotifyCtx {
tag: String,
}
let mut mgr = AoeSubscriptionManager::new(master.index());
// The callback signature must match AOENotificationCallback (bare function pointer, no Some(...) wrapper)
extern "C" fn on_data(
_master_index: u16, slave: u16, _handle: u32, _timestamp: u64,
data: *const u8, data_size: u32, user_data: *mut std::ffi::c_void,
) {
// Recover &NotifyCtx with user_data as *const T — it stays valid for the whole lifetime of the subscription
let ctx = unsafe { &*(user_data as *const NotifyCtx) };
let bytes = unsafe { std::slice::from_raw_parts(data, data_size as usize) };
println!("[{}] Slave {} 通知 {} 字节: {:?}", ctx.tag, slave, data_size, bytes); // [{}] Slave {} notification {} bytes: {:?}
}
let cfg = AoeSubscription::on_change(slave.index(), 0x4020, 0, 4, 500_000);
let sub_id = mgr.subscribe(
"driver_status", cfg, on_data,
Arc::new(NotifyCtx { tag: "driver_status".to_string() }),
)?;
println!("订阅 id: {}", sub_id); // Subscription id: {}
println!("订阅数: {}", mgr.subscription_count()); // Subscription count: {}
println!("活跃订阅: {:?}", mgr.active_subscriptions()); // Active subscriptions: {:?}
// unsubscribe_all can be called explicitly before exit (Drop calls it too)
mgr.unsubscribe_all();