AoE (ADS over EtherCAT)
AoE carries ADS (Automation Device Specification) 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, PDO control and process data exchange do not need it; use it only when the device documentation explicitly provides ADS objects or an ADS state machine.
Accessed through slave.AoE. null when the slave does not support AoE.
Method overview
| Category | Method | Type | Read/write | Description |
|---|---|---|---|---|
| Data read/write | Read | byte[]? | read-only | Reads data of the given length by IndexGroup / IndexOffset |
| Write | bool | write-only | Writes data by IndexGroup / IndexOffset | |
| ReadWrite | byte[]? | read/write | Reads and writes within one ADS transaction (readLength=0 means a pure write, writeData=null means a pure read) | |
| ReadWriteWithStatus | tuple(bool, byte[]?) | read/write | Same as ReadWrite, but explicitly distinguishes "pure write succeeded" from "failure" | |
| Device information | ReadDeviceInfo | tuple(bool, byte, byte, ushort, string) | read-only | Reads the device name and version number |
| ReadState | tuple(bool, ushort, ushort) | read-only | Reads the ADS state and the device state | |
| State control | WriteControl | bool | write-only | Switches the slave ADS state |
| AoEInstance.GetAdsStateName | string | read-only | Converts an ADS state code to its name (static method) | |
| GetAdsStateDescription | string | read-only | Converts an ADS state code to its name (instance method, forwards to the static method) | |
| Data subscription | Subscribe | AoESubscription? | write-only | Registers a data-change notification for the given IndexGroup on the slave; returns null on failure |
| Unsubscribe | bool | write-only | Cancels one subscription | |
| UnsubscribeAll | void | write-only | Cancels all subscriptions | |
| DelNotification | bool | write-only | Deletes a device notification by handle (low-level) | |
| DelNotificationAsync | Task<bool> | write-only | Asynchronous version of DelNotification | |
| AoE configuration | SetConfig | bool | write-only | Sets the AoE routing (target/source AMS NetID and port) |
| GetConfig | tuple(bool, byte[], ushort, byte[], ushort) | read-only | Reads the current AoE routing configuration | |
| InitializeSlaveNetId | bool | write-only | Writes the master AMS NetID into the slave ADS routing table | |
| InitializeSlaveNetIdAsync | Task<bool> | write-only | Asynchronous version of InitializeSlaveNetId | |
| ADS IndexGroup | ReadCoEViaAoE | byte[]? | read-only | Reads a CoE object through IndexGroup 0xF302 |
| WriteCoEViaAoE | bool | write-only | Writes a CoE object through IndexGroup 0xF302 | |
| WriteCoEViaAoEAsync | Task<bool> | write-only | Asynchronous version of WriteCoEViaAoE | |
| ReadSoEViaAoE | byte[]? | read-only | Reads an SoE IDN through IndexGroup 0xF420 | |
| WriteSoEViaAoE | bool | write-only | Writes an SoE IDN through IndexGroup 0xF420 | |
| WriteSoEViaAoEAsync | Task<bool> | write-only | Asynchronous version of WriteSoEViaAoE | |
| Master requests | InitAllSlavesNetId | int | write-only | Dispatches NetID initialization to every AoE-capable slave of the whole master |
| SendFragmented | bool | write-only | Sends an ADS fragmented frame (low-level, packet number specified manually) | |
| RecvReassemble | tuple(bool, byte[]?) | read-only | Receives and reassembles a fragmented response (pairs with SendFragmented) | |
| SendCommand | tuple(bool, byte[]?) | read/write | Sends a raw ADS command to the given AMS port | |
| AddNotification | uint? | write-only | Registers a device notification handle directly (low-level) | |
| Error diagnostics | GetLastError | tuple(uint, ushort, ushort, ushort) | read-only | Reads the detailed error record (result / class / code / lastCommand) |
| ClearLastError | void | write-only | Clears the low-level LastError record | |
| PeekInvokeId | uint | read-only | Queries the current ADS InvokeId (for diagnostics) |
Data read/write and notification methods also have Async-suffixed versions; see "Master requests · Async variants".
Properties
| Category | Property | Type | Read/write | Description |
|---|---|---|---|---|
| Protocol capability | IsSupported | bool | read-only | Boolean view of AoESupport == true: true only when support is known, false when the result is unknown |
| AoESupport | bool? | read-only | Tri-state AoE capability: true = supported, false = mbx_proto was actually read and the bit is not set, null = unknown (read failed) | |
| IsSupportedKnown | bool | read-only | Whether the capability result is known; false = unknown (not the same as unsupported) | |
| ProtocolType | byte | read-only | Mailbox protocol type (AoE = 0x01) | |
| ProtocolName | string | read-only | Protocol name | |
| Errors and state | LastAoEError | AoEResultCode | read-only | ADS error code of the most recent AoE operation; NoError on success |
| LastAoEResult | AoEReadWriteResult | read-only | Full result of the most recent ReadWrite-family call (including the actual number of bytes read) | |
| LastStatus | MailboxStatus | read-only | Most recent mailbox status | |
| LastErrorCode | uint | read-only | Most recent error code (same source as LastAoEError, presented as uint) | |
| Statistics | Statistics | MailboxStatistics | read-only | Mailbox statistics snapshot (call ResetStatistics() to reset the counters) |
AoEResultCode enum
AoE/ADS result codes defined by ETG.1020 Table 16 and exposed through LastAoEError. Common values:
public enum AoEResultCode : uint
{
NoError = 0x00,
InternalError = 0x01,
NoRealTime = 0x02,
InsertMailboxError = 0x04,
TargetPortNotFound = 0x06,
TargetMachineNotFound = 0x07,
UnknownCommandId = 0x08,
InvalidAmsLength = 0x0E,
InvalidAmsNetId = 0x0F,
PortDisabled = 0x12,
AmsSyncTimeout = 0x15,
DeviceInvalidGroup = 0x0700,
DeviceInvalidOffset = 0x0701,
DeviceNotReady = 0x0705,
DeviceTimeout = 0x0712,
DeviceAccessDenied = 0x071C,
// see ETG.1020 Table 16 for further codes
}
AoEReadWriteResult struct
| Field | Type | Description |
|---|---|---|
| Success | bool | Whether the operation succeeded |
| Data | byte[]? | Response data (truncated to the actual length; when data is present, Data.Length == ActualBytesRead); null = no returned data: either a pure write succeeded (ActualBytesRead=0), or a variable-length response edge case (ActualBytesRead>0 but the data buffer is empty, in which case the length information is still kept and is not confused with a pure write) |
| ActualBytesRead | uint | Actual payload length of the slave response, which may be smaller than the requested readLength |
MailboxStatistics struct
| Field | Type | Description |
|---|---|---|
| TotalSent | ulong | Total transactions sent |
| TotalReceived | ulong | Total responses received (including error frames) |
| TotalTimeout | ulong | Total timeouts |
| TotalMailboxError | ulong | Total mailbox error frames received |
| TotalProtocolError | ulong | Total protocol errors |
| TotalCancelled | ulong | Total transactions cancelled |
| LastErrorCode | uint | Most recent error code (0 means none) |
| LastErrorTime | DateTime? | Time of the most recent error (UTC); null when there is no error |
| AverageLatencyUs | double | Average transaction latency (microseconds) |
AoESupport returns bool?: true = supported, false = SII mbx_proto was actually read and the bit is not set, null = not readable this time (the call failed). A failed read is no longer folded into false; to distinguish "confirmed unsupported" from "unknown", check AoESupport / IsSupportedKnown rather than IsSupported alone.
Except for InitAllSlavesNetId (default 1000000 microseconds), timeoutUs defaults to 500000 microseconds (0.5 seconds) on every method.
Data read/write
Read(uint indexGroup, uint indexOffset, uint length, int timeoutUs = 500_000)
public byte[]? Read(uint indexGroup, uint indexOffset, uint length, int timeoutUs = 500_000)
Reads ADS data.
Parameters:
indexGroup(uint) — index groupindexOffset(uint) — index offsetlength(uint) — read lengthtimeoutUs(int) — timeout (microseconds)
Return value:
byte[]?— the data read; returnsnullon failure
Write(uint indexGroup, uint indexOffset, byte[] data, int timeoutUs = 500_000)
public bool Write(uint indexGroup, uint indexOffset, byte[] data, int timeoutUs = 500_000)
Writes ADS data.
Parameters:
indexGroup(uint) — index groupindexOffset(uint) — index offsetdata(byte[]) — data to write (must not be null)timeoutUs(int) — timeout (microseconds)
Return value:
bool— returnstrueon success
Throws ArgumentException when data is null or an empty array.
ReadWrite(uint indexGroup, uint indexOffset, uint readLength, byte[]? writeData = null, int timeoutUs = 500_000)
public byte[]? ReadWrite(uint indexGroup, uint indexOffset, uint readLength, byte[]? writeData = null, int timeoutUs = 500_000)
Reads and writes data at the same time (the ADS ReadWrite command). readLength == 0 means a pure write, and writeData being null means read-only; when both are empty it throws ArgumentException. Large requests are fragmented automatically by the SDK when they exceed the mailbox capacity (ETG.1020 §9.3), so a single call is not limited by the mailbox capacity (128 to 512 bytes).
Parameters:
indexGroup(uint) — index groupindexOffset(uint) — index offsetreadLength(uint) — read lengthwriteData(byte[]?) — data to write (optional)timeoutUs(int) — timeout (microseconds)
Return value:
byte[]?— the data read; returnsnullon failure (useReadWriteWithStatuswhen "pure write succeeded" cannot be distinguished from "failure")
ReadWriteWithStatus(uint indexGroup, uint indexOffset, uint readLength, byte[]? writeData = null, int timeoutUs = 500_000)
public (bool success, byte[]? data) ReadWriteWithStatus(uint indexGroup, uint indexOffset, uint readLength, byte[]? writeData = null, int timeoutUs = 500_000)
Takes the same path as ReadWrite but returns an explicit success flag: success=true, data=null means the pure write succeeded; success=false, data=null means the operation failed, and the error code is available from LastAoEError.
Parameters:
indexGroup(uint) — index groupindexOffset(uint) — index offsetreadLength(uint) — read lengthwriteData(byte[]?) — data to write (optional)timeoutUs(int) — timeout (microseconds)
Return value:
success(bool) — whether the call succeededdata(byte[]?) — the data read
Related structures:
The actual number of bytes read (for a variable-length ETG.1020 response this can be smaller than the requested length) is available through LastAoEResult; see AoEReadWriteResult above.
Example:
byte[]? data = slave.AoE.ReadWrite(0xF302, 0x01, 256);
uint actual = slave.AoE.LastAoEResult.ActualBytesRead;
Device information
ReadDeviceInfo(int timeoutUs = 500_000)
public (bool success, byte majorVer, byte minorVer, ushort build, string deviceName) ReadDeviceInfo(int timeoutUs = 500_000)
Reads ADS device information.
Return value:
success(bool) — whether the call succeededmajorVer(byte) — major version numberminorVer(byte) — minor version numberbuild(ushort) — build numberdeviceName(string) — device name
ReadState(int timeoutUs = 500_000)
public (bool success, ushort adsState, ushort deviceState) ReadState(int timeoutUs = 500_000)
Reads the ADS state.
Return value:
success(bool) — whether the call succeededadsState(ushort) — ADS statedeviceState(ushort) — device state
Related structures:
ADS state values:
0—Invalid, invalid state1—Idle, idle2—Reset, reset3—Init, initialization4—Start, start5—Run, run6—Stop, stop7—SaveCfg, save configuration8—LoadCfg, load configuration9—PowerFailure, power failure10—PowerGood, power good11—Error, error12—Shutdown, shutdown13—Suspend, suspend14—Resume, resume15—Config, configuration16—ReConfig, reconfiguration
WriteControl(ushort adsState, ushort deviceState, byte[]? data = null, int timeoutUs = 500_000)
public bool WriteControl(ushort adsState, ushort deviceState, byte[]? data = null, int timeoutUs = 500_000)
Writes a control command (switches the device state).
Parameters:
adsState(ushort) — target ADS statedeviceState(ushort) — target device statedata(byte[]?) — additional data (optional)timeoutUs(int) — timeout (microseconds)
Return value:
bool— returnstrueon success
Example:
slave.AoE.WriteControl(5, 0); // switch to the Run state
AoEInstance.GetAdsStateName(ushort adsState)
public static string GetAdsStateName(ushort adsState)
Gets the ADS state name (unmapped values return a string of the form Unknown(n)).
Parameters:
adsState(ushort) — ADS state code
Return value:
string— state name
Example:
var (ok, adsState, deviceState) = slave.AoE.ReadState();
if (ok)
Console.WriteLine($"ADS 状态: {DarraEtherCAT.Slave.AoEInstance.GetAdsStateName(adsState)} ({adsState})"); // ADS state: {DarraEtherCAT.Slave.AoEInstance.GetAdsStateName(adsState)} ({adsState})
GetAdsStateDescription(ushort adsState)
public string GetAdsStateDescription(ushort adsState)
Instance entry point that turns an ADS state code into its name; it returns the same set of names as the static GetAdsStateName. Unmapped values return a string of the form Unknown(n).
Parameters:
adsState(ushort) — ADS state code
Return value:
string— state name
Example:
var (ok, adsState, deviceState) = slave.AoE.ReadState();
if (ok)
Console.WriteLine($"ADS 状态: {slave.AoE.GetAdsStateDescription(adsState)} ({adsState})"); // ADS state: {slave.AoE.GetAdsStateDescription(adsState)} ({adsState})
Data subscription
Subscribe(...)
public AoESubscription? Subscribe(
uint indexGroup, uint indexOffset, uint dataLength,
Action<AoENotificationEventArgs> callback,
AoETransmissionMode mode = DarraEtherCAT.Slave.AoETransmissionMode.OnChange,
int cycleTimeMs = 100)
Subscribes to data-change notifications. callback receives only the data-change events of this subscription.
Parameters:
indexGroup(uint) — index groupindexOffset(uint) — index offsetdataLength(uint) — data lengthcallback(Action<AoENotificationEventArgs>) — data-change callbackmode(AoETransmissionMode) — transmission mode (defaultOnChange)cycleTimeMs(int) — check cycle (milliseconds, default 100)
Return value:
AoESubscription?— the subscription object; returnsnullon failure
Related structures:
AoETransmissionMode
public enum AoETransmissionMode : uint
{
NoTransmission = 0, // no notification
Cyclic = 1, // cyclic notification - sent at the given cycle
OnChange = 2, // change notification - sent when the data changes
CyclicInDevice = 3, // cyclic notification generated in the device
OnChangeInDevice = 4 // change notification generated in the device
}
Unsubscribe(AoESubscription subscription)
public bool Unsubscribe(AoESubscription subscription)
Cancels a subscription. A return value of false means the subscription does not exist (it may already have been cancelled).
UnsubscribeAll()
public void UnsubscribeAll()
Cancels all subscriptions (including unregistering the notification handles on the device). Must be called before the master exits to avoid leaked handles on the device side.
DelNotification(uint notificationHandle, int timeoutUs = 500_000)
public bool DelNotification(uint notificationHandle, int timeoutUs = 500_000)
Deletes a slave device notification handle (ADS Command 0x07). Normal scenarios should use Unsubscribe / UnsubscribeAll; call this method only when you hold the raw handle and need to release it manually.
Parameters:
notificationHandle(uint) — handle returned by ADS AddNotificationtimeoutUs(int) — timeout (microseconds), default 500000
Return value:
bool— returnstrueon success
Example:
// low-level release path for a known handle
slave.AoE.DelNotification(handle);
DelNotificationAsync(uint notificationHandle, int timeoutUs = 500_000, CancellationToken cancellationToken = default)
public Task<bool> DelNotificationAsync(uint notificationHandle, int timeoutUs = 500_000, CancellationToken cancellationToken = default)
Asynchronous version of DelNotification, for releasing device notifications from UI / background threads.
Parameters:
notificationHandle(uint) — handle returned by ADS AddNotificationtimeoutUs(int) — timeout (microseconds), default 500000cancellationToken(CancellationToken) — cancellation token
Return value:
Task<bool>— returnstrueon success
Example:
await slave.AoE.DelNotificationAsync(handle, cancellationToken: ct);
AoE configuration
SetConfig(byte[] targetNetId, ushort targetPort, byte[] sourceNetId, ushort sourcePort)
public bool SetConfig(byte[] targetNetId, ushort targetPort, byte[] sourceNetId, ushort sourcePort)
Sets the AoE routing configuration (AMS NetID and port).
Parameters:
targetNetId(byte[]) — target AMS NetID (6 bytes)targetPort(ushort) — target AMS portsourceNetId(byte[]) — source AMS NetID (6 bytes)sourcePort(ushort) — source AMS port
Return value:
bool— returnstrueon success
Example:
byte[] targetNetId = { 5, 80, 187, 177, 1, 1 };
byte[] sourceNetId = { 192, 168, 1, 100, 1, 1 };
slave.AoE.SetConfig(targetNetId, 851, sourceNetId, 32768);
GetConfig()
public (bool success, byte[] targetNetId, ushort targetPort, byte[] sourceNetId, ushort sourcePort) GetConfig()
Reads the current AoE routing configuration (pairs with SetConfig).
Return value:
success(bool) — whether the call succeededtargetNetId(byte[]) — target AMS NetID (6 bytes, empty array on failure)targetPort(ushort) — target AMS portsourceNetId(byte[]) — source AMS NetID (6 bytes, empty array on failure)sourcePort(ushort) — source AMS port
Example:
var (ok, targetNetId, targetPort, sourceNetId, sourcePort) = slave.AoE.GetConfig();
InitializeSlaveNetId(byte[] netId, int timeoutUs = 500_000)
public bool InitializeSlaveNetId(byte[] netId, int timeoutUs = 500_000)
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 (writing to IndexGroup=1, IndexOffset=3). Throws ArgumentException when netId is not 6 bytes.
Parameters:
netId(byte[]) — 6-byte AMS Net IDtimeoutUs(int) — timeout (microseconds)
Return value:
bool— returnstrueon success
Example:
byte[] netId = { 5, 80, 187, 177, 1, 1 };
slave.AoE.InitializeSlaveNetId(netId);
InitializeSlaveNetIdAsync(byte[] netId, int timeoutUs = 500_000, CancellationToken cancellationToken = default)
public Task<bool> InitializeSlaveNetIdAsync(byte[] netId, int timeoutUs = 500_000, CancellationToken cancellationToken = default)
Asynchronous version of InitializeSlaveNetId, avoiding blocking the calling thread.
Parameters:
netId(byte[]) — 6-byte AMS Net IDtimeoutUs(int) — timeout (microseconds)cancellationToken(CancellationToken) — cancellation token
Return value:
Task<bool>— returnstrueon success
Example:
byte[] netId = { 5, 80, 187, 177, 1, 1 };
await slave.AoE.InitializeSlaveNetIdAsync(netId, cancellationToken: ct);
ADS IndexGroup read/write (not a general gateway)
Accesses the CoE/SoE objects that the slave already implements, through ADS IndexGroup (the ETG.1020 routing table). This is not a mailbox gateway, not SCADA and not symbolic name access. When the slave does not implement the corresponding IndexGroup, reads return null and writes return false. The CoE IndexOffset is encoded as (index << 16) | subindex; the SoE IndexOffset is the IDN number.
Related structures:
AoEMailboxRouting provides the routing IndexGroup constants:
public static class AoEMailboxRouting
{
public const uint CoEIndexGroup = 0xF302; // CoE routing
public const uint FoEReadIndexGroup = 0xF401; // FoE read request
public const uint FoEWriteIndexGroup = 0xF402; // FoE write request
public const uint FoEDataIndexGroup = 0xF404; // FoE data transfer
public const uint FoEAckIndexGroup = 0xF405; // FoE acknowledgement
public const uint SoEIndexGroup = 0xF420; // SoE routing
public const uint VoEIndexGroup = 0xF430; // VoE routing
}
ReadCoEViaAoE(ushort index, byte subindex, uint readLength, int timeoutUs = 500_000)
public byte[]? ReadCoEViaAoE(ushort index, byte subindex, uint readLength, int timeoutUs = 500_000)
Reads a CoE object through AoE routing (IndexGroup=0xF302).
Parameters:
index(ushort) — CoE object indexsubindex(byte) — CoE subindexreadLength(uint) — expected read lengthtimeoutUs(int) — timeout (microseconds)
Return value:
byte[]?— the data read; returnsnullon failure
Example:
// read CoE object 0x6041:0 (status word) through the AoE gateway
byte[]? data = slave.AoE.ReadCoEViaAoE(0x6041, 0, 2);
if (data != null)
{
ushort statusWord = BitConverter.ToUInt16(data, 0);
Console.WriteLine($"状态字: 0x{statusWord:X4}"); // Status word: 0x{statusWord:X4}
}
WriteCoEViaAoE(ushort index, byte subindex, byte[] data, int timeoutUs = 500_000)
public bool WriteCoEViaAoE(ushort index, byte subindex, byte[] data, int timeoutUs = 500_000)
Writes a CoE object through AoE routing (IndexGroup=0xF302).
Parameters:
index(ushort) — CoE object indexsubindex(byte) — CoE subindexdata(byte[]) — data to writetimeoutUs(int) — timeout (microseconds)
Return value:
bool— returnstrueon success
Example:
// write CoE object 0x6040:0 (control word) through the AoE gateway
slave.AoE.WriteCoEViaAoE(0x6040, 0, BitConverter.GetBytes((ushort)0x000F));
WriteCoEViaAoEAsync(ushort index, byte subindex, byte[] data, int timeoutUs = 500_000, CancellationToken cancellationToken = default)
public Task<bool> WriteCoEViaAoEAsync(ushort index, byte subindex, byte[] data, int timeoutUs = 500_000, CancellationToken cancellationToken = default)
Asynchronous version of WriteCoEViaAoE, suitable for remote CoE writes initiated from the UI main thread.
Parameters:
index(ushort) — CoE object indexsubindex(byte) — CoE subindexdata(byte[]) — data to writetimeoutUs(int) — timeout (microseconds)cancellationToken(CancellationToken) — cancellation token
Return value:
Task<bool>— returnstrueon success
Example:
await slave.AoE.WriteCoEViaAoEAsync(0x6040, 0,
BitConverter.GetBytes((ushort)0x000F), cancellationToken: ct);
ReadSoEViaAoE(uint idn, uint readLength, int timeoutUs = 500_000)
public byte[]? ReadSoEViaAoE(uint idn, uint readLength, int timeoutUs = 500_000)
Reads an SoE IDN through AoE routing (IndexGroup=0xF420).
Parameters:
idn(uint) — SoE IDN numberreadLength(uint) — expected read lengthtimeoutUs(int) — timeout (microseconds)
Return value:
byte[]?— the data read; returnsnullon failure
WriteSoEViaAoE(uint idn, byte[] data, int timeoutUs = 500_000)
public bool WriteSoEViaAoE(uint idn, byte[] data, int timeoutUs = 500_000)
Writes an SoE IDN through AoE routing (IndexGroup=0xF420).
Parameters:
idn(uint) — SoE IDN numberdata(byte[]) — data to writetimeoutUs(int) — timeout (microseconds)
Return value:
bool— returnstrueon success
WriteSoEViaAoEAsync(uint idn, byte[] data, int timeoutUs = 500_000, CancellationToken cancellationToken = default)
public Task<bool> WriteSoEViaAoEAsync(uint idn, byte[] data, int timeoutUs = 500_000, CancellationToken cancellationToken = default)
Asynchronous version of WriteSoEViaAoE, usable with await / CancellationToken.
Parameters:
idn(uint) — SoE IDN numberdata(byte[]) — data to writetimeoutUs(int) — timeout (microseconds)cancellationToken(CancellationToken) — cancellation token
Return value:
Task<bool>— returnstrueon success
Example:
await slave.AoE.WriteSoEViaAoEAsync(idn: 32,
BitConverter.GetBytes((uint)1500), cancellationToken: ct);
AoE subscription subsystem
The SDK entry point for ADS DeviceNotification (commands 0x06/0x07/0x08) is slave.AoE.Subscriptions. After subscribing, the device pushes data changes on its own; polling is no longer needed.
Subscriptions
public AoESubscriptionManager Subscriptions { get; }
Each slave instance has its own subscription manager, created lazily on first access. Subscriptions and notifications are isolated per master — a notification from slave N on master A never leaks to the same slave index on master B.
Subscribe(uint indexGroup, uint indexOffset, uint dataLength, AoETransmissionMode, int maxDelayMs, int cycleTimeMs)
public AoESubscription? Subscribe(uint indexGroup, uint indexOffset, uint dataLength,
AoETransmissionMode mode = DarraEtherCAT.Slave.AoETransmissionMode.OnChange,
int maxDelayMs = 100,
int cycleTimeMs = 100)
Creates and registers a new subscription. After successful registration the device pushes data changes; returns null on failure (and also raises the Error event).
Parameters:
indexGroup(uint) — ADS index groupindexOffset(uint) — ADS index offsetdataLength(uint) — data length (bytes)mode(AoETransmissionMode) — transmission modemaxDelayMs(int) — maximum delay (milliseconds), default 100cycleTimeMs(int) — cycle time (milliseconds), default 100
Return value:
AoESubscription?— the subscription object (withId/NotificationHandle/IsActive)
Unsubscribe(Guid id) / Unsubscribe(AoESubscription)
public bool Unsubscribe(Guid subscriptionId)
public bool Unsubscribe(AoESubscription subscription)
Cancels a single subscription and stops the data pushes of that subscription.
UnsubscribeAll() / GetActiveSubscriptions() / GetSubscription(Guid)
public void UnsubscribeAll()
public AoESubscription[] GetActiveSubscriptions()
public AoESubscription? GetSubscription(Guid subscriptionId)
Bulk management API. UnsubscribeAll must be called before the master exits to avoid leaked handles on the device side.
Subscription events
public event EventHandler<AoENotificationEventArgs>? DataNotification;
public event EventHandler<AoESubscriptionErrorEventArgs>? Error;
public event EventHandler<AoESubscription>? SubscriptionStateChanged;
Related structures:
public class AoENotificationEventArgs : EventArgs
{
public Guid SubscriptionId { get; }
public uint NotificationHandle { get; }
public ushort SlaveIndex { get; }
public uint IndexGroup { get; }
public uint IndexOffset { get; }
public byte[] Data { get; }
public DateTime Timestamp { get; }
public ulong DeviceTimestamp { get; } // in 100 ns units
}
public class AoESubscriptionErrorEventArgs : EventArgs
{
public Guid SubscriptionId { get; }
public string ErrorMessage { get; }
public Exception? Exception { get; }
public DateTime Timestamp { get; }
}
public class AoESubscription
{
public Guid Id { get; }
public uint NotificationHandle { get; }
public ushort SlaveIndex { get; }
public uint IndexGroup { get; }
public uint IndexOffset { get; }
public uint DataLength { get; }
public AoETransmissionMode TransmissionMode { get; }
public bool IsActive { get; }
public DateTime CreatedAt { get; }
public object? Tag { get; set; }
}
Subscription manager properties
public int SubscriptionCount { get; } // current number of subscriptions
public bool IsListenerRunning { get; } // whether this master's subscription listener is running
public int DefaultTimeoutMs { get; set; } // default timeout for subscription registration (default 500)
Example:
var sub = slave.AoE.Subscriptions.Subscribe(
indexGroup: 0xF021,
indexOffset: 0x1000,
dataLength: 4,
mode: DarraEtherCAT.Slave.AoETransmissionMode.OnChange,
maxDelayMs: 50,
cycleTimeMs: 100);
slave.AoE.Subscriptions.DataNotification += (s, e) =>
Console.WriteLine($"slave={e.SlaveIndex} data={BitConverter.ToInt32(e.Data,0)}");
slave.AoE.Subscriptions.Error += (s, e) =>
Console.WriteLine($"订阅错误: {e.ErrorMessage}"); // Subscription error: {e.ErrorMessage}
// release everything before exit
slave.AoE.Subscriptions.UnsubscribeAll();
AoE error handling
GetLastError()
public (uint resultCode, ushort errorClass, ushort errorLow, ushort lastCommand) GetLastError()
Reads the detailed error record of the most recent failed AoE operation.
Return value:
resultCode(uint) — the full 32-bit ADS Result CodeerrorClass(ushort) — high word (error class, for example 0x0700 = ADS device error)errorLow(ushort) — low word with the concrete error code (per ETG.1020 Table 16, convertible toAoEResultCode)lastCommand(ushort) — ADS command id of the most recent failure
When no error record can be found at the underlying layer, the failure code already held by this instance in LastAoEError is returned (all fields 0 when there is no failure record).
Related structures:
AoELastError is a structured representation of the same information (ResultCode / ErrorClass / ErrorCode / LastCommand / HasError / ResultCodeEnum / Message, where ResultCodeEnum matches the enum by the low word only). The current SDK has no public entry point that returns that instance directly; use GetLastError() and LastAoEError for error details.
ClearLastError()
public void ClearLastError()
Clears the underlying LastError record.
Master requests
InitAllSlavesNetId(byte[]? masterNetId = null, int timeoutUs = 1_000_000)
public int InitAllSlavesNetId(byte[]? masterNetId = null, int timeoutUs = 1_000_000)
Dispatches InitializeSlaveNetId to every AoE-capable slave (ETG.1020 §9.4, called during the PreOp stage). Note that this method acts on all AoE slaves of the whole master, not only the current slave.
Parameters:
masterNetId(byte[]?) — master AMS NetID (6 bytes);nulluses the default NetID (all 0)timeoutUs(int) — per-slave write timeout (microseconds), default 1000000
Return value:
int— number of slaves written successfully; a value below 0 means failure
SendFragmented(byte[] payload, ushort packetNumber, int timeoutUs = 500_000)
public bool SendFragmented(byte[] payload, ushort packetNumber, int timeoutUs = 500_000)
ADS Fragmentation send (ETG.1020 §9.3). payload must be a complete ADS request frame; when it exceeds a single mailbox capacity it is split into several fragments automatically and sent serially under the same packetNumber. High-level users normally call ReadWrite directly (splitting is automatic when the capacity is exceeded); use this method only when the packet number must be controlled manually. Receive the response with RecvReassemble.
Parameters:
payload(byte[]) — complete ADS request framepacketNumber(ushort) — packet number of this command (all fragments share the same number)timeoutUs(int) — timeout (microseconds)
Return value:
bool— returnstrueon success
RecvReassemble(uint bufferCapacity, ushort packetNumber, int timeoutUs = 500_000)
public (bool success, byte[]? data) RecvReassemble(uint bufferCapacity, ushort packetNumber, int timeoutUs = 500_000)
ADS Fragmentation receive and reassembly (pairs with SendFragmented).
Parameters:
bufferCapacity(uint) — preallocated buffer capacity (should be at least the complete response size)packetNumber(ushort) — packet number being awaited (fragments with another number are discarded)timeoutUs(int) — timeout (microseconds)
Return value:
success(bool) — whether the call succeededdata(byte[]?) — the reassembled data; returnsnullon failure
SendCommand(ushort targetPort, ushort commandId, byte[]? commandData = null, int timeoutUs = 500_000)
public (bool success, byte[]? responseData) SendCommand(ushort targetPort, ushort commandId, byte[]? commandData = null, int timeoutUs = 500_000)
Sends a raw ADS command to the given AMS port and returns the response data. Single-frame exchange: the command payload and the response must not exceed the slave mailbox capacity (usually 128 to 512 bytes); for larger data use ReadWrite / SendFragmented.
Parameters:
targetPort(ushort) — target AMS portcommandId(ushort) — ADS command IDcommandData(byte[]?) — command data (optional)timeoutUs(int) — timeout (microseconds)
Return value:
success(bool) — whether the call succeededresponseData(byte[]?) — response data (may benull: the call succeeded but there is no response data)
AddNotification(uint indexGroup, uint indexOffset, uint length, uint transMode, uint maxDelay, uint cycleTime, int timeoutUs = 500_000)
public uint? AddNotification(uint indexGroup, uint indexOffset, uint length,
uint transMode, uint maxDelay, uint cycleTime, int timeoutUs = 500_000)
Registers a notification handle directly with the device (ADS Command 0x06); returns null on failure. Subscriptions uses these methods; user code normally uses the higher-level Subscribe API and calls this method only in manual-management scenarios that hold a raw handle (pairs with DelNotification).
Parameters:
indexGroup(uint) — index groupindexOffset(uint) — index offsetlength(uint) — data lengthtransMode(uint) — transmission mode (1=Cyclic, 2=OnChange, 3=CyclicInDevice, 4=OnChangeInDevice, the same asAoETransmissionMode)maxDelay(uint) — maximum delay, in 100 ns unitscycleTime(uint) — cycle time, in 100 ns unitstimeoutUs(int) — timeout (microseconds)
Return value:
uint?— notification handle; returnsnullon failure
PeekInvokeId()
public uint PeekInvokeId()
Queries the current ADS InvokeId for request/response pairing diagnostics; normally it does not need to be called manually.
Return value:
uint— the current InvokeId (returns 0 when the query fails)
Async variants
Data read/write and notification methods provide Async versions with the Async suffix, most of them accepting an extra CancellationToken cancellationToken = default (SetConfig / GetConfig / ReadDeviceInfo / ReadState / SendFragmented and others have no asynchronous version):
Read—ReadAsyncWrite—WriteAsyncReadWrite—ReadWriteAsyncReadWriteWithStatus—ReadWriteWithStatusAsyncWriteControl—WriteControlAsyncAddNotification—AddNotificationAsyncDelNotification—DelNotificationAsyncReadCoEViaAoE—ReadCoEViaAoEAsyncWriteCoEViaAoE—WriteCoEViaAoEAsyncReadSoEViaAoE—ReadSoEViaAoEAsyncWriteSoEViaAoE—WriteSoEViaAoEAsyncInitializeSlaveNetId—InitializeSlaveNetIdAsync
Cancellation only affects completion of the caller's Task (it becomes cancelled immediately); the underlying call still runs to completion and its result is discarded.
Example:
var ct = new CancellationTokenSource(TimeSpan.FromSeconds(2)).Token;
byte[]? data = await slave.AoE.ReadCoEViaAoEAsync(0x6041, 0, 2, cancellationToken: ct);
Full example
if (slave.AoE != null)
{
// device information
var (ok, major, minor, build, name) = slave.AoE.ReadDeviceInfo();
if (ok)
Console.WriteLine($"设备: {name} v{major}.{minor}.{build}"); // Device: {name} v{major}.{minor}.{build}
// read IndexGroup data
byte[]? data = slave.AoE.Read(0x4020, 0, 4);
if (data != null)
Console.WriteLine($"读到的值: 0x{BitConverter.ToUInt32(data, 0):X8}"); // Value read: 0x{BitConverter.ToUInt32(data, 0):X8}
// write back to the same location
if (!slave.AoE.Write(0x4020, 0, BitConverter.GetBytes((uint)0x0006)))
Console.WriteLine("写入失败, 错误码: " + slave.AoE.LastAoEError); // Write failed, error code:
// ADS state
var (stateOk, adsState, deviceState) = slave.AoE.ReadState();
if (stateOk)
Console.WriteLine($"ADS 状态: {adsState}, 设备状态: {deviceState}"); // ADS state: {adsState}, device state: {deviceState}
// subscribe to changes, cancel before exit
var subscription = slave.AoE.Subscribe(0x4020, 0, 4, e =>
Console.WriteLine($"变化: 0x{BitConverter.ToUInt32(e.Data, 0):X8}")); // Change: 0x{BitConverter.ToUInt32(e.Data, 0):X8}
if (subscription != null)
slave.AoE.Unsubscribe(subscription);
}
Failures and handling
| Symptom | Cause | Handling |
|---|---|---|
| Read returns null, Write returns false | ADS returned a result code other than 0 | Read LastAoEError to confirm the cause, and check whether IndexGroup / IndexOffset exist in the slave object table |
| The call does not return for a long time or reports a timeout | The slave responds slowly, or the channel is occupied by another request | Pass a larger timeoutUs (in microseconds, default 500000 = 0.5 seconds) and confirm the slave has reached PreOp or a higher state |
| slave.AoE is null | The slave does not declare AoE support | Use CoE object access instead; to tell "confirmed unsupported" from "read failure", check AoESupport and IsSupportedKnown |
| Subscribe returns null | Notification registration failed | Check that IndexGroup and dataLength match the slave object, then shorten cycleTimeMs and retry |