Skip to main content

AoE (ADS over EtherCAT)

AoE implements ADS (Automation Device Specification) over EtherCAT.

Get an AoE& reference with slave.GetAoE().​

Data read and write​

ReadWrite()​

std::vector<uint8_t> ReadWrite(uint32_t indexGroup, uint32_t indexOffset,
uint32_t readLength,
const uint8_t* writeData = nullptr,
uint32_t writeLength = 0,
int timeoutUs = 500000) const;

AoE read/write operation.

Read()​

std::vector<uint8_t> Read(uint32_t indexGroup, uint32_t indexOffset,
uint32_t length, int timeoutUs = 500000) const;

Write()​

bool Write(uint32_t indexGroup, uint32_t indexOffset,
const uint8_t* data, uint32_t dataLen,
int timeoutUs = 500000) const;

Example:

auto& aoe = master.GetSlave(1).GetAoE();

// Read data
auto data = aoe.Read(0x4020, 0, 4);
if (data.size() >= 4) {
uint32_t val;
std::memcpy(&val, data.data(), 4);
printf("值: 0x%08X\n", val); // Value: 0x%08X
}

Asynchronous API (std::future)​

Besides the synchronous Read / Write / ReadWrite calls, the C++ SDK provides 3 asynchronous std::future entry points. Internally std::async(std::launch::async) moves the synchronous call to a background thread so the main thread is not blocked.

ReadAsync()​

std::future<std::vector<uint8_t>> ReadAsync(uint32_t indexGroup, uint32_t indexOffset,
uint32_t length,
int timeoutUs = 500000) const;

Reads ADS data asynchronously. future.get() returns the read result, or an empty vector on failure.

WriteAsync()​

std::future<bool> WriteAsync(uint32_t indexGroup, uint32_t indexOffset,
std::vector<uint8_t> data,
int timeoutUs = 500000) const;

Writes ADS data asynchronously. data is captured by value, so the caller may destroy the source object immediately.

ReadWriteAsync()​

std::future<std::vector<uint8_t>> ReadWriteAsync(uint32_t indexGroup, uint32_t indexOffset,
uint32_t readLength,
std::vector<uint8_t> writeData,
int timeoutUs = 500000) const;

Runs an ADS Read+Write composite operation asynchronously.

Example (reading several ADS variables in parallel):

auto& aoe = master.GetSlave(1).GetAoE();

auto fa = aoe.ReadAsync(0x4020, 0, 4);
auto fb = aoe.ReadAsync(0x4021, 0, 4);

auto va = fa.get();
auto vb = fb.get();

Error codes​

ADS protocol error codes (ETG.1020 Table 16). enum class AoEResultCode : uint32_t is defined in slave/aoe.hpp and lists the standard values of the ADS header errorCode field (partial list):

enum class AoEResultCode : uint32_t {
NoError = 0x0000, // No error
InternalError = 0x0001, // Internal error
NoRealTime = 0x0002, // Not real time
InsertMailboxError = 0x0004, // Mailbox insert error
WrongReceiveHMsg = 0x0005, // Receive message handle error
TargetPortNotFound = 0x0006, // Target port not found
TargetMachineNotFound = 0x0007, // Target machine not found
UnknownCommandId = 0x0008, // Unknown command ID
BadTaskId = 0x0009, // Invalid task ID
NoIO = 0x000A, // No I/O
UnknownAmsCommand = 0x000B, // Unknown AMS command
PortNotConnected = 0x000D, // Port not connected
InvalidAmsLength = 0x000E, // Invalid AMS length
InvalidAmsNetId = 0x000F, // Invalid AMS NetID
PortDisabled = 0x0012, // Port disabled
PortAlreadyConnected = 0x0013, // Port connected
AmsSyncTimeout = 0x0015, // Synchronous wait timeout
InvalidAmsPort = 0x0018, // Invalid AMS port
NoMemory = 0x0019, // Out of memory
HostUnreachable = 0x001B, // Host unreachable
// ---- Device-level errors (0x07xx) ----
DeviceInvalidGroup = 0x0700, // Invalid index group
DeviceInvalidOffset = 0x0701, // Invalid index offset
DeviceInvalidAccess = 0x0702, // Invalid access
DeviceInvalidSize = 0x0703, // Invalid size
DeviceNotReady = 0x0705, // Device not ready
DeviceBusy = 0x0706, // Device busy
DeviceNotFound = 0x0708, // Device not found
DeviceSymbolNotFound = 0x070A, // Symbol not found
DeviceInvalidState = 0x070C, // Invalid state
DeviceTimeout = 0x0712, // Device timeout
DeviceAccessDenied = 0x071C, // Access denied
// ---- Client-level errors (0x074x / 0x075x) ----
ClientError = 0x0740, // Client error
ClientInvalidParam = 0x0741, // Invalid parameter
ClientInvokeTimeout = 0x0744, // Call timeout
ClientPortNotOpen = 0x0745, // Port not open
ClientQueueFull = 0x0750 // Queue full
};
The C++ AoE does not expose LastErrorCode()

The AoE class does not provide LastErrorCode() / GetLastError() members. On failure, C++ Read / Write / ReadWrite only return an empty vector or false; no AoE error code is cached separately. The AoEResultCode enum is provided as a reference when parsing the ADS header errorCode field.

Example:

auto data = aoe.Read(0x4020, 0, 4);
if (data.empty()) {
// In C++ an AoE failure only returns an empty vector, there is no separate LastErrorCode() entry point
printf("ADS 读取失败 (超时 / 设备未响应)\n"); // ADS read failed (timeout / device not responding)
}

Device information​

ReadDeviceInfo()​

std::tuple<bool, uint8_t, uint8_t, uint16_t, std::string>
ReadDeviceInfo(int timeoutUs = 500000) const;

Reads ADS device information. Returns the {success, major, minor, build, name} tuple.

Example:

auto& aoe = master.GetSlave(1).GetAoE();

auto [ok, major, minor, build, name] = aoe.ReadDeviceInfo();
if (ok)
printf("设备: %s v%d.%d.%d\n", name.c_str(), major, minor, build); // Device: %s v%d.%d.%d

ADS state​

ReadState()​

std::tuple<bool, uint16_t, uint16_t> ReadState(int timeoutUs = 500000) const;

Reads the ADS state. Returns the {success, adsState, deviceState} tuple.

WriteControl()​

bool WriteControl(uint16_t adsState, uint16_t deviceState,
const uint8_t* data = nullptr, int dataLen = 0,
int timeoutUs = 500000) const;

Writes an ADS control command.

Example:

auto& aoe = master.GetSlave(1).GetAoE();

auto [ok, ads, dev] = aoe.ReadState();
if (ok) {
printf("ADS 状态: %s, 设备状态: %d\n", // ADS state: %s, device state: %d
AoE::GetAdsStateName(ads).c_str(), dev);
}

// Switch to the Run state
aoe.WriteControl(5, 0); // ADS_STATE_RUN = 5

Command sending​

SendCommand()​

std::tuple<bool, std::vector<uint8_t>>
SendCommand(uint16_t targetPort, uint16_t commandId,
const uint8_t* cmdData = nullptr, uint32_t cmdSize = 0,
int timeoutUs = 500000) const;

Sends an AoE command and receives the response.

Data subscription​

CategoryMethodTypeAccessDescription
NotificationGetNotificationCountsize_tread-onlyNumber of notifications received since creation; it only increases, and unsubscribing does not lower it
NotificationActiveSubscriptionCountsize_tread-onlyNumber of active subscriptions, counted in real time from the registered notification handles
NotificationSubscribeNotificationuint32_twrite-onlySubscribes to device notifications directly on the AoE instance and returns a notification handle; returns 0 on failure
NotificationUnsubscribeNotificationboolwrite-onlyCancels a subscription by notification handle; returns false when the handle is unknown or cleanup fails
ValidationValidatePayloadboolread-onlyStatic helper: checks that the pointer is not null, that the length covers at least the 16-byte notification header, and that the header length field does not exceed the remaining bytes; it does not inspect payload content
Subscription managementSubscriptionsconst reference to the subscription tableread-onlyLocal subscription table mapping subscription ID to subscription information
Subscription managementDtorRemoveAllFailureCountuint32_tread-onlyProcess-wide cumulative count: number of times removing all subscriptions at destruction failed
Subscription managementUnsubscribeAllFailureCountuint32_tread-onlyPer-instance cumulative count: number of UnsubscribeAll failures
Do not confuse the two counters

GetNotificationCount() is "how many notifications have been received in total"; ActiveSubscriptionCount() is "how many subscriptions are registered right now". Unsubscribing lowers the subscription count but not the cumulative receive count; there is no conversion between the two.

Subscribe()​

Use the AoESubscriptionManager class to manage the subscription lifetime; it cleans up automatically at destruction.

int Subscribe(uint32_t indexGroup, uint32_t indexOffset, uint32_t dataLength,
AoETransmissionMode mode, uint32_t maxDelay, uint32_t cycleTimeMs,
std::function<void(uint32_t, uint32_t, uint32_t,
const uint8_t*, uint32_t)> callback);

Subscribes to data change notifications.

SubscribeNotification versus Subscribe

AoE::SubscribeNotification(...) is another entry point for the same subscription semantics, attached directly to the AoE instance: its parameters are (ams_addr, index_group, index_offset, length, cycle_ms, subscriber, timeoutUs); it returns the notification handle allocated by the device (0 means failure), and UnsubscribeNotification(handle) cancels by handle. Subscribe(...) goes through AoESubscriptionManager and manages subscriptions by local subscription ID. The two handle systems are not interchangeable; do not mix them.

Parameters:

  • indexGroup (uint32_t) — index group
  • indexOffset (uint32_t) — index offset
  • dataLength (uint32_t) — data length
  • mode (AoETransmissionMode) — transmission mode (no default value; OnChange is common)
  • maxDelay (uint32_t) — maximum delay (milliseconds)
  • cycleTimeMs (uint32_t) — check cycle (milliseconds)
  • callback — data change callback

Returns:

  • int — subscription ID, or -1 on failure

AoETransmissionMode​

enum class AoETransmissionMode : uint32_t {
NoTransmission = 0, // No notification
Cyclic = 1, // Cyclic notification - sent at the specified period
OnChange = 2, // Change notification - sent when data changes
CyclicInDevice = 3, // Device-side cyclic notification
OnChangeInDevice = 4 // Device-side change notification
};

Example:

AoESubscriptionManager subMgr(dll, masterIndex, slaveIndex);

auto subId = subMgr.Subscribe(0x4020, 0, 4,
AoETransmissionMode::OnChange, 0, 100,
[](uint32_t handle, uint32_t ig, uint32_t io,
const uint8_t* data, uint32_t size) {
printf("数据变化: handle=%u, size=%u\n", handle, size); // Data change: handle=%u, size=%u
});

Unsubscribe()​

bool Unsubscribe(int subscriptionId);

Cancels the specified subscription.

UnsubscribeNotification(notification_handle) is the corresponding entry point on the AoE instance that cancels by notification handle.

UnsubscribeAll()​

bool UnsubscribeAll();

Cancels all subscriptions and reports whether all of them succeeded.

ActiveCount()​

int ActiveCount() const;

Returns the number of active subscriptions.

Example:

AoESubscriptionManager subMgr(dll, masterIndex, slaveIndex);

// Add a subscription
int subId = subMgr.Subscribe(0x4020, 0, 4,
AoETransmissionMode::OnChange, 0, 100,
[](uint32_t handle, uint32_t ig, uint32_t io,
const uint8_t* data, uint32_t size) {
printf("数据变化: handle=%u, size=%u\n", handle, size); // Data change: handle=%u, size=%u
});

printf("活跃订阅: %d\n", subMgr.ActiveCount()); // Active subscriptions: %d

// Remove a subscription
subMgr.Unsubscribe(subId);

// Remove all subscriptions
subMgr.UnsubscribeAll();

Low-level API (AddNotification / DelNotification)​

std::optional<uint32_t> AddNotification(
uint32_t indexGroup, uint32_t indexOffset, uint32_t length,
uint32_t transMode, uint32_t maxDelay, uint32_t cycleTime,
int timeoutUs = 500000) const;

bool DelNotification(uint32_t handle, int timeoutUs = 500000) const;

Adds/removes an ADS data change notification (low-level API; AoESubscriptionManager is recommended).

AoE configuration​

SetConfig()​

bool SetConfig(const uint8_t targetNetId[6], uint16_t targetPort,
const uint8_t sourceNetId[6], uint16_t sourcePort) const;

Sets the AoE routing configuration (AMS NetID and ports).

Parameters:

  • targetNetId (const uint8_t[6]) — target AMS NetID (6 bytes)
  • targetPort (uint16_t) — target AMS port
  • sourceNetId (const uint8_t[6]) — source AMS NetID (6 bytes)
  • sourcePort (uint16_t) — source AMS port

Returns:

  • bool — true on success

Example:

uint8_t targetNetId[] = { 5, 80, 187, 177, 1, 1 };
uint8_t sourceNetId[] = { 192, 168, 1, 100, 1, 1 };
aoe.SetConfig(targetNetId, 851, sourceNetId, 32768);

GetConfig()​

std::tuple<bool, std::array<uint8_t, 6>, uint16_t,
std::array<uint8_t, 6>, uint16_t>
GetConfig() const;

Gets the AoE routing configuration. Returns the {success, targetNetId, targetPort, sourceNetId, sourcePort} tuple.

InitializeSlaveNetId()​

bool InitializeSlaveNetId(const uint8_t netId[6],
int timeoutUs = 500000) const;

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.

Parameters:

  • netId (const uint8_t[6]) — 6-byte AMS Net ID
  • timeoutUs (int) — timeout (microseconds)

Returns:

  • bool — true on success

Example:

uint8_t netId[] = { 5, 80, 187, 177, 1, 1 };
aoe.InitializeSlaveNetId(netId);

Cross-protocol gateway​

Access other mailbox protocols through AoE routing (ETG.1020); CoE and SoE are forwarded transparently.

ReadCoEViaAoE()​

std::vector<uint8_t> ReadCoEViaAoE(uint16_t index, uint8_t subindex,
uint32_t readLength,
int timeoutUs = 500000) const;

Reads a CoE object through AoE routing (IndexGroup=0xF302, IndexOffset=(index << 16) | subindex).

Parameters:

  • index (uint16_t) — CoE object index
  • subindex (uint8_t) — CoE subindex
  • readLength (uint32_t) — expected read length
  • timeoutUs (int) — timeout (microseconds)

Returns:

  • std::vector<uint8_t> — the data read; empty on failure

WriteCoEViaAoE()​

bool WriteCoEViaAoE(uint16_t index, uint8_t subindex,
const uint8_t* data, uint32_t dataLen,
int timeoutUs = 500000) const;

Writes a CoE object through AoE routing (IndexGroup=0xF302).

Parameters:

  • index (uint16_t) — CoE object index
  • subindex (uint8_t) — CoE subindex
  • data (const uint8_t*) — data to write
  • dataLen (uint32_t) — data length
  • timeoutUs (int) — timeout (microseconds)

Returns:

  • bool — true on success

ReadSoEViaAoE()​

std::vector<uint8_t> ReadSoEViaAoE(uint32_t idn, uint32_t readLength,
int timeoutUs = 500000) const;

Reads an SoE IDN through AoE routing (IndexGroup=0xF420, IndexOffset=the IDN number).

WriteSoEViaAoE()​

bool WriteSoEViaAoE(uint32_t idn, const uint8_t* data, uint32_t dataLen,
int timeoutUs = 500000) const;

Writes an SoE IDN through AoE routing (IndexGroup=0xF420).

Full examples​

Data read and write​

auto& aoe = master.GetSlave(1).GetAoE();

// Read data
auto status = aoe.Read(0x4020, 0, 4);
if (status.size() >= 4) {
uint32_t val;
std::memcpy(&val, status.data(), 4);
printf("状态: 0x%08X\n", val); // State: 0x%08X
}

// Write data
uint32_t writeVal = 0x0006;
aoe.Write(0x4020, 0, reinterpret_cast<const uint8_t*>(&writeVal), 4);

// Device information
auto [ok, major, minor, build, name] = aoe.ReadDeviceInfo();
if (ok)
printf("设备: %s v%d.%d.%d\n", name.c_str(), major, minor, build); // Device: %s v%d.%d.%d

Data subscription​

AoESubscriptionManager subMgr(dll, masterIndex, slaveIndex);

auto subId = subMgr.Subscribe(0x4020, 0, 4,
AoETransmissionMode::OnChange, 0, 100,
[](uint32_t handle, uint32_t ig, uint32_t io,
const uint8_t* data, uint32_t size) {
printf("数据变化, handle=%u\n", handle); // Data change, handle=%u
});

// ... running ...

subMgr.UnsubscribeAll();

Cross-protocol gateway​

auto& aoe = master.GetSlave(1).GetAoE();

// Read a CoE object over AoE
auto statusWord = aoe.ReadCoEViaAoE(0x6041, 0, 2);
if (statusWord.size() >= 2) {
uint16_t val;
std::memcpy(&val, statusWord.data(), 2);
printf("状态字: 0x%04X\n", val); // Status word: 0x%04X
}

// Write a CoE object over AoE
uint16_t ctrlWord = 0x000F;
aoe.WriteCoEViaAoE(0x6040, 0, reinterpret_cast<const uint8_t*>(&ctrlWord), 2);

// Read a SoE IDN over AoE
auto idnData = aoe.ReadSoEViaAoE(32, 4);
if (idnData.size() >= 4) {
uint32_t idnVal;
std::memcpy(&idnVal, idnData.data(), 4);
printf("IDN 32 值: %u\n", idnVal); // IDN 32 value: %u
}

End-to-end flow​

#include "ethercat.hpp"
using namespace darra;

int main() {
EtherCATMaster master(dll);
master.SetNetwork("\\Device\\NPF_{...}")
.SetENI("config.deni")
.Build();
master.SetState(EcState::OP);
master.Start();

auto& aoe = master.GetSlave(1).GetAoE();

// Device information
auto [infoOk, major, minor, build, name] = aoe.ReadDeviceInfo();
if (infoOk)
printf("设备: %s v%d.%d.%d\n", name.c_str(), major, minor, build); // Device: %s v%d.%d.%d

// ADS state
auto [stateOk, ads, dev] = aoe.ReadState();
if (stateOk)
printf("ADS=%s, 设备=%d\n", AoE::GetAdsStateName(ads).c_str(), dev); // ADS=%s, device=%d

// Read data
auto data = aoe.Read(0x4020, 0, 4);
if (data.size() >= 4) {
uint32_t val;
std::memcpy(&val, data.data(), 4);
printf("值: 0x%08X\n", val); // Value: 0x%08X
}

getchar();
return 0;
}