Skip to main content

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​

CategoryMethodTypeRead/writeDescription
Data read/writeReadbyte[]?read-onlyReads data of the given length by IndexGroup / IndexOffset
Writeboolwrite-onlyWrites data by IndexGroup / IndexOffset
ReadWritebyte[]?read/writeReads and writes within one ADS transaction (readLength=0 means a pure write, writeData=null means a pure read)
ReadWriteWithStatustuple(bool, byte[]?)read/writeSame as ReadWrite, but explicitly distinguishes "pure write succeeded" from "failure"
Device informationReadDeviceInfotuple(bool, byte, byte, ushort, string)read-onlyReads the device name and version number
ReadStatetuple(bool, ushort, ushort)read-onlyReads the ADS state and the device state
State controlWriteControlboolwrite-onlySwitches the slave ADS state
AoEInstance.GetAdsStateNamestringread-onlyConverts an ADS state code to its name (static method)
GetAdsStateDescriptionstringread-onlyConverts an ADS state code to its name (instance method, forwards to the static method)
Data subscriptionSubscribeAoESubscription?write-onlyRegisters a data-change notification for the given IndexGroup on the slave; returns null on failure
Unsubscribeboolwrite-onlyCancels one subscription
UnsubscribeAllvoidwrite-onlyCancels all subscriptions
DelNotificationboolwrite-onlyDeletes a device notification by handle (low-level)
DelNotificationAsyncTask<bool>write-onlyAsynchronous version of DelNotification
AoE configurationSetConfigboolwrite-onlySets the AoE routing (target/source AMS NetID and port)
GetConfigtuple(bool, byte[], ushort, byte[], ushort)read-onlyReads the current AoE routing configuration
InitializeSlaveNetIdboolwrite-onlyWrites the master AMS NetID into the slave ADS routing table
InitializeSlaveNetIdAsyncTask<bool>write-onlyAsynchronous version of InitializeSlaveNetId
ADS IndexGroupReadCoEViaAoEbyte[]?read-onlyReads a CoE object through IndexGroup 0xF302
WriteCoEViaAoEboolwrite-onlyWrites a CoE object through IndexGroup 0xF302
WriteCoEViaAoEAsyncTask<bool>write-onlyAsynchronous version of WriteCoEViaAoE
ReadSoEViaAoEbyte[]?read-onlyReads an SoE IDN through IndexGroup 0xF420
WriteSoEViaAoEboolwrite-onlyWrites an SoE IDN through IndexGroup 0xF420
WriteSoEViaAoEAsyncTask<bool>write-onlyAsynchronous version of WriteSoEViaAoE
Master requestsInitAllSlavesNetIdintwrite-onlyDispatches NetID initialization to every AoE-capable slave of the whole master
SendFragmentedboolwrite-onlySends an ADS fragmented frame (low-level, packet number specified manually)
RecvReassembletuple(bool, byte[]?)read-onlyReceives and reassembles a fragmented response (pairs with SendFragmented)
SendCommandtuple(bool, byte[]?)read/writeSends a raw ADS command to the given AMS port
AddNotificationuint?write-onlyRegisters a device notification handle directly (low-level)
Error diagnosticsGetLastErrortuple(uint, ushort, ushort, ushort)read-onlyReads the detailed error record (result / class / code / lastCommand)
ClearLastErrorvoidwrite-onlyClears the low-level LastError record
PeekInvokeIduintread-onlyQueries the current ADS InvokeId (for diagnostics)

Data read/write and notification methods also have Async-suffixed versions; see "Master requests · Async variants".

Properties​

CategoryPropertyTypeRead/writeDescription
Protocol capabilityIsSupportedboolread-onlyBoolean view of AoESupport == true: true only when support is known, false when the result is unknown
AoESupportbool?read-onlyTri-state AoE capability: true = supported, false = mbx_proto was actually read and the bit is not set, null = unknown (read failed)
IsSupportedKnownboolread-onlyWhether the capability result is known; false = unknown (not the same as unsupported)
ProtocolTypebyteread-onlyMailbox protocol type (AoE = 0x01)
ProtocolNamestringread-onlyProtocol name
Errors and stateLastAoEErrorAoEResultCoderead-onlyADS error code of the most recent AoE operation; NoError on success
LastAoEResultAoEReadWriteResultread-onlyFull result of the most recent ReadWrite-family call (including the actual number of bytes read)
LastStatusMailboxStatusread-onlyMost recent mailbox status
LastErrorCodeuintread-onlyMost recent error code (same source as LastAoEError, presented as uint)
StatisticsStatisticsMailboxStatisticsread-onlyMailbox 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
FieldTypeDescription
SuccessboolWhether the operation succeeded
Databyte[]?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)
ActualBytesReaduintActual payload length of the slave response, which may be smaller than the requested readLength
MailboxStatistics struct
FieldTypeDescription
TotalSentulongTotal transactions sent
TotalReceivedulongTotal responses received (including error frames)
TotalTimeoutulongTotal timeouts
TotalMailboxErrorulongTotal mailbox error frames received
TotalProtocolErrorulongTotal protocol errors
TotalCancelledulongTotal transactions cancelled
LastErrorCodeuintMost recent error code (0 means none)
LastErrorTimeDateTime?Time of the most recent error (UTC); null when there is no error
AverageLatencyUsdoubleAverage transaction latency (microseconds)
Tri-state capability

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 group
  • indexOffset (uint) — index offset
  • length (uint) — read length
  • timeoutUs (int) — timeout (microseconds)

Return value:

  • byte[]? — the data read; returns null on 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 group
  • indexOffset (uint) — index offset
  • data (byte[]) — data to write (must not be null)
  • timeoutUs (int) — timeout (microseconds)

Return value:

  • bool — returns true on 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 group
  • indexOffset (uint) — index offset
  • readLength (uint) — read length
  • writeData (byte[]?) — data to write (optional)
  • timeoutUs (int) — timeout (microseconds)

Return value:

  • byte[]? — the data read; returns null on failure (use ReadWriteWithStatus when "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 group
  • indexOffset (uint) — index offset
  • readLength (uint) — read length
  • writeData (byte[]?) — data to write (optional)
  • timeoutUs (int) — timeout (microseconds)

Return value:

  • success (bool) — whether the call succeeded
  • data (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 succeeded
  • majorVer (byte) — major version number
  • minorVer (byte) — minor version number
  • build (ushort) — build number
  • deviceName (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 succeeded
  • adsState (ushort) — ADS state
  • deviceState (ushort) — device state

Related structures:

ADS state values:

  • 0 — Invalid, invalid state
  • 1 — Idle, idle
  • 2 — Reset, reset
  • 3 — Init, initialization
  • 4 — Start, start
  • 5 — Run, run
  • 6 — Stop, stop
  • 7 — SaveCfg, save configuration
  • 8 — LoadCfg, load configuration
  • 9 — PowerFailure, power failure
  • 10 — PowerGood, power good
  • 11 — Error, error
  • 12 — Shutdown, shutdown
  • 13 — Suspend, suspend
  • 14 — Resume, resume
  • 15 — Config, configuration
  • 16 — 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 state
  • deviceState (ushort) — target device state
  • data (byte[]?) — additional data (optional)
  • timeoutUs (int) — timeout (microseconds)

Return value:

  • bool — returns true on 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 group
  • indexOffset (uint) — index offset
  • dataLength (uint) — data length
  • callback (Action<AoENotificationEventArgs>) — data-change callback
  • mode (AoETransmissionMode) — transmission mode (default OnChange)
  • cycleTimeMs (int) — check cycle (milliseconds, default 100)

Return value:

  • AoESubscription? — the subscription object; returns null on 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 AddNotification
  • timeoutUs (int) — timeout (microseconds), default 500000

Return value:

  • bool — returns true on 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 AddNotification
  • timeoutUs (int) — timeout (microseconds), default 500000
  • cancellationToken (CancellationToken) — cancellation token

Return value:

  • Task<bool> — returns true on 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 port
  • sourceNetId (byte[]) — source AMS NetID (6 bytes)
  • sourcePort (ushort) — source AMS port

Return value:

  • bool — returns true on 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 succeeded
  • targetNetId (byte[]) — target AMS NetID (6 bytes, empty array on failure)
  • targetPort (ushort) — target AMS port
  • sourceNetId (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 ID
  • timeoutUs (int) — timeout (microseconds)

Return value:

  • bool — returns true on 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 ID
  • timeoutUs (int) — timeout (microseconds)
  • cancellationToken (CancellationToken) — cancellation token

Return value:

  • Task<bool> — returns true on 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 index
  • subindex (byte) — CoE subindex
  • readLength (uint) — expected read length
  • timeoutUs (int) — timeout (microseconds)

Return value:

  • byte[]? — the data read; returns null on 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 index
  • subindex (byte) — CoE subindex
  • data (byte[]) — data to write
  • timeoutUs (int) — timeout (microseconds)

Return value:

  • bool — returns true on 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 index
  • subindex (byte) — CoE subindex
  • data (byte[]) — data to write
  • timeoutUs (int) — timeout (microseconds)
  • cancellationToken (CancellationToken) — cancellation token

Return value:

  • Task<bool> — returns true on 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 number
  • readLength (uint) — expected read length
  • timeoutUs (int) — timeout (microseconds)

Return value:

  • byte[]? — the data read; returns null on 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 number
  • data (byte[]) — data to write
  • timeoutUs (int) — timeout (microseconds)

Return value:

  • bool — returns true on 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 number
  • data (byte[]) — data to write
  • timeoutUs (int) — timeout (microseconds)
  • cancellationToken (CancellationToken) — cancellation token

Return value:

  • Task<bool> — returns true on 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 group
  • indexOffset (uint) — ADS index offset
  • dataLength (uint) — data length (bytes)
  • mode (AoETransmissionMode) — transmission mode
  • maxDelayMs (int) — maximum delay (milliseconds), default 100
  • cycleTimeMs (int) — cycle time (milliseconds), default 100

Return value:

  • AoESubscription? — the subscription object (with Id / 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 Code
  • errorClass (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 to AoEResultCode)
  • 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); null uses 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 frame
  • packetNumber (ushort) — packet number of this command (all fragments share the same number)
  • timeoutUs (int) — timeout (microseconds)

Return value:

  • bool — returns true on 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 succeeded
  • data (byte[]?) — the reassembled data; returns null on 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 port
  • commandId (ushort) — ADS command ID
  • commandData (byte[]?) — command data (optional)
  • timeoutUs (int) — timeout (microseconds)

Return value:

  • success (bool) — whether the call succeeded
  • responseData (byte[]?) — response data (may be null: 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 group
  • indexOffset (uint) — index offset
  • length (uint) — data length
  • transMode (uint) — transmission mode (1=Cyclic, 2=OnChange, 3=CyclicInDevice, 4=OnChangeInDevice, the same as AoETransmissionMode)
  • maxDelay (uint) — maximum delay, in 100 ns units
  • cycleTime (uint) — cycle time, in 100 ns units
  • timeoutUs (int) — timeout (microseconds)

Return value:

  • uint? — notification handle; returns null on 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 — ReadAsync
  • Write — WriteAsync
  • ReadWrite — ReadWriteAsync
  • ReadWriteWithStatus — ReadWriteWithStatusAsync
  • WriteControl — WriteControlAsync
  • AddNotification — AddNotificationAsync
  • DelNotification — DelNotificationAsync
  • ReadCoEViaAoE — ReadCoEViaAoEAsync
  • WriteCoEViaAoE — WriteCoEViaAoEAsync
  • ReadSoEViaAoE — ReadSoEViaAoEAsync
  • WriteSoEViaAoE — WriteSoEViaAoEAsync
  • InitializeSlaveNetId — 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​

SymptomCauseHandling
Read returns null, Write returns falseADS returned a result code other than 0Read 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 timeoutThe slave responds slowly, or the channel is occupied by another requestPass a larger timeoutUs (in microseconds, default 500000 = 0.5 seconds) and confirm the slave has reached PreOp or a higher state
slave.AoE is nullThe slave does not declare AoE supportUse CoE object access instead; to tell "confirmed unsupported" from "read failure", check AoESupport and IsSupportedKnown
Subscribe returns nullNotification registration failedCheck that IndexGroup and dataLength match the slave object, then shorten cycleTimeMs and retry