SoE (Servo over EtherCAT)
The SoE protocol carries the SERCOS servo communication protocol inside the EtherCAT mailbox; it is meant for SERCOS-compatible servo drives.
Get the SoE& reference through slave.GetSoE().
Most EtherCAT servo drives use the CoE + CiA 402 stack. SoE is only for SERCOS-compatible drives (such as the Bosch Rexroth IndraDrive series). The two cannot be mixed — which one a slave supports depends on the hardware.
S-0-0011 (IDN 0x000B) and S-0-0012 (IDN 0x000C) are Class 1 / Class 2 diagnostic codes (UINT16), not position values. For position feedback use S-0-0051 (IDN 0x0033), for the position command use S-0-0047 (IDN 0x002F); reading a diagnostic code as a 32-bit position gives a value with no physical meaning. The position read back is signed; the zero point and scaling are set by the drive's scaling parameters, the SDK does no conversion.
Method overview
| Category | Method | Type | Read/write | Description |
|---|---|---|---|---|
| Parameter read/write | Read | byte array | read-only | Reads the raw parameter bytes for an IDN; returns an empty array on failure |
| Parameter read/write | Write | bool | write-only | Writes raw parameter bytes for an IDN; returns false on failure |
| Typed read | ReadInt16 / ReadInt32 / ReadUInt16 / ReadUInt32 / ReadFloat / ReadDouble / ReadString | std::optional | read-only | Reads the data value by type (little-endian decode); returns empty on failure |
| Typed write | WriteInt16 / WriteInt32 / WriteUInt16 / WriteUInt32 / WriteFloat / WriteDouble / WriteString | bool | write-only | Writes the data value by type (little-endian encode); returns false on failure |
| Metadata | ReadName | string or empty | read-only | Reads the IDN parameter name; returns empty when it cannot be read |
| Metadata | ReadUnit | string or empty | read-only | Reads the IDN parameter unit; returns empty when it cannot be read |
| Metadata | ReadAttributes / WriteAttribute | SoEAttributes or empty / bool | read-only / write-only | Reads and writes the IDN attribute bit field |
| Metadata | ReadMinValue / ReadMaxValue / ReadDefaultValue | byte array | read-only | Reads the minimum / maximum / default value |
| Metadata | ReadDataState | optional uint16 | read-only | Reads the data state word (Element 0x01) |
| Parameter information | GetAvailableIDNs | IDN list | read-only | Lists every IDN the slave supports |
| Parameter information | GetParameterInfo | SoEParameter | read-only | Retrieves name/unit/attributes/current value/min/max/default in one call |
| Parameter information | FormatValueWithAttributes | string | read-only | Static helper: formats raw bytes into readable text according to the data type |
| Mapping | GetIDNMapping | ServoMappingInfo | read-only | Reads the current drive AT/MDT mapping configuration |
| Mapping | GetAllDriveMappings | mapping dictionary | read-only | Walks the 8 drive slots and collects the mappings |
| Procedure command | ExecuteCommand | bool | read/write | Triggers a procedure command and polls until it completes or errors |
| Notification monitoring | EnableNotification | bool | write | Turns on value-change monitoring for the given IDN; false means only local polling is possible, after which use PollNotifications to fetch the changes |
| Notification monitoring | DisableNotification / DisableAllNotifications | bool | write-only | A real unsubscribe (including the hardware unsubscribe); failed items are kept for retry |
| Notification monitoring | NotifyCancelFailureCount | uint32_t | read-only | Running count of failed hardware unsubscribes (S-0-0127 written with 0) |
| Notification monitoring | PollNotifications | event list | read-only | Polls the monitored IDNs and returns the change events from this poll |
| Notification monitoring | GetMonitoredIDNs | IDN list | read-only | The IDNs currently being monitored |
| Error query | GetLastSoEError | enum or empty | read-only | Failure reason of the most recent Read / Write |
| Error query | GetLastSoEErrorCode | optional SoEErrorCode | read-only | ETG.5003 advanced error code field |
| Error query | SetLastSoEErrorCode | void | write-only | Writes the ETG.5003 advanced error code field |
| Error query | ClearLastSoEErrorCode | void | write-only | Clears the ETG.5003 advanced error code field |
The SERCOS IDN system
SoE addresses drive parameters through an IDN (Identification Number). Each IDN is a 16-bit number standing for one parameter (position, velocity, control word and so on).
IDN naming rules:
| Prefix | Range | Description |
|---|---|---|
| S-x-xxxx | 0x0000 – 0x7FFF | SERCOS standard parameters (common to all vendors) |
| P-x-xxxx | 0x8000 – 0xBFFF | Product-specific parameters |
| P-x-xxxx | 0xC000 – 0xFFFF | Vendor-defined parameters |
Common standard IDNs (servo control related; for the semantics of the remaining IDNs refer to the device manual):
| IDN | SERCOS name | Description | Data type |
|---|---|---|---|
| S-0-0001 (0x0001) | Cycle Time | Communication cycle time | uint, us, read-only |
| S-0-0047 (0x002F) | Position Command | Position command value | int, inc |
| S-0-0051 (0x0033) | Position Feedback 1 | Position feedback value | int, inc |
| S-0-0064 (0x0040) | Drive Control Word | Drive control word | ushort |
| S-0-0071 (0x0047) | Drive Status Word | Drive status word | ushort, read-only |
Element flags — reading different "layers" of an IDN:
| Flag | Meaning |
|---|---|
| 0x01 | Data state |
| 0x02 | Parameter name (string) |
| 0x04 | Attributes (data type/length/access-rights bit field) |
| 0x08 | Unit (string) |
| 0x10 | Minimum value |
| 0x20 | Maximum value |
| 0x40 | Data value (default, most commonly used) |
| 0x80 | Default value |
SoEElementFlags
The C++ wrapper represents the Element Flags bit mask with enum class SoEElementFlags : uint8_t. It provides operator| / operator& overloads and an explicit ToByte() conversion, so it can be passed straight to Read(idn, flags) / Write(idn, ..., flags) in place of a bare uint8_t.
enum class SoEElementFlags : uint8_t {
None = 0x00,
DataStatus = 0x01, // Data status word (valid/invalid/busy)
Name = 0x02, // IDN name string
Attribute = 0x04, // Data attributes (type, length, floating-point precision and so on)
Unit = 0x08, // Unit string
Min = 0x10, // Minimum value
Max = 0x20, // Maximum value
Value = 0x40, // Operational data value (most common, the default)
Default = 0x80 // Default value
};
inline constexpr SoEElementFlags operator|(SoEElementFlags, SoEElementFlags);
inline constexpr SoEElementFlags operator&(SoEElementFlags, SoEElementFlags);
inline constexpr uint8_t ToByte (SoEElementFlags);
Example:
using darra::ethercat::SoEElementFlags;
// Take Value + Unit together
auto flags = SoEElementFlags::Value | SoEElementFlags::Unit;
auto raw = soe.Read(0x0033, ToByte(flags));
SoEIdnTriple / EncodeIdn / DecodeIdn
ETG.6220 splits the 16-bit IDN into 3 fields: is_standard (S/P), parameter_set (0..7), data_block (0..0x0FFF). The SDK provides two helper functions for decoding / assembling plus a triple struct, which makes cross-vendor IDN string conversion easier (for example "S-0-0051" → 0x0033).
struct SoEIdnTriple {
bool is_standard; // true = S- standard, false = P- product/vendor
uint8_t parameter_set; // 0..7
uint16_t data_block; // 0..0x0FFF
};
inline uint16_t EncodeIdn(bool is_standard, uint8_t parameter_set, uint16_t data_block);
inline SoEIdnTriple DecodeIdn(uint16_t idn);
EncodeIdn(...)— triple → 16-bit IDN (S-0-0051→0x0033)DecodeIdn(idn)— 16-bit IDN → triple (for printing / validation)
The SDK also provides conversion between SERCOS IDN strings and 16-bit numbers:
// "S-0-0040" / "P-1-0123" string -> 16-bit IDN; returns false for a malformed format
inline bool TryParseSercosIdn(const std::string& text, uint16_t& idn_out);
// 16-bit IDN -> "S-x-xxxx" / "P-x-xxxx" string
inline std::string FormatSercosIdn(uint16_t idn);
Example:
using darra::ethercat::EncodeIdn;
using darra::ethercat::DecodeIdn;
using darra::ethercat::TryParseSercosIdn;
using darra::ethercat::FormatSercosIdn;
// "S-0-0051" position feedback value -> 0x0033
uint16_t idn = EncodeIdn(/*is_standard*/ true, /*set*/ 0, /*block*/ 51);
auto t = DecodeIdn(idn);
printf("%s-%u-%04u\n", t.is_standard ? "S" : "P", t.parameter_set, t.data_block);
// Output: S-0-0051
// String conversions
uint16_t parsed = 0;
if (TryParseSercosIdn("S-0-0040", parsed))
printf("%s -> 0x%04X\n", FormatSercosIdn(parsed).c_str(), parsed);
Basic read and write
Read()
std::vector<uint8_t> Read(uint16_t idn, uint8_t elementFlags = 0x40,
int timeoutMs = 500) const;
Reads the raw bytes of an IDN parameter. Returns an empty vector on failure. The default elementFlags of 0x40 means the data value. Multi-byte values are stored little-endian in ETG wire order; for an empty vector you must also tell "read failed" apart from "this element has no operation data" with GetLastSoEError().
Parameters:
idn(uint16_t) — IDN numberelementFlags(uint8_t) — element flags (default 0x40 = data value)timeoutMs(int) — timeout (milliseconds)
Returns:
std::vector<uint8_t>— the data read; an empty vector on failure
Example:
// Read the communication cycle time (S-0-0001). The return value is ETG little-endian byte order
auto data = soe.Read(0x0001, 0x40);
if (data.size() >= 4) {
uint32_t cycleTime = static_cast<uint32_t>(data[0])
| (static_cast<uint32_t>(data[1]) << 8)
| (static_cast<uint32_t>(data[2]) << 16)
| (static_cast<uint32_t>(data[3]) << 24);
printf("周期时间: %u μs\n", cycleTime); // Cycle time: %u µs
}
Write()
bool Write(uint16_t idn, const void* data, int dataLen,
uint8_t elementFlags = 0x40, int timeoutMs = 500) const;
Writes an IDN parameter.
Parameters:
idn(uint16_t) — IDN numberdata(const void*) — pointer to the data to writedataLen(int) — data length (bytes)elementFlags(uint8_t) — element flags (default 0x40 = data value)timeoutMs(int) — timeout (milliseconds)
Returns:
bool—trueon success
Example:
auto& soe = master.GetSlave(1).GetSoE();
// Read the position feedback (S-0-0051), decoded manually in little-endian byte order
auto pos_data = soe.Read(0x0033);
if (pos_data.size() >= 4) {
int32_t pos = static_cast<int32_t>(
static_cast<uint32_t>(pos_data[0])
| (static_cast<uint32_t>(pos_data[1]) << 8)
| (static_cast<uint32_t>(pos_data[2]) << 16)
| (static_cast<uint32_t>(pos_data[3]) << 24));
printf("位置反馈: %d\n", pos); // Position feedback: %d
}
// Write the control word (S-0-0064)
uint16_t cw = 0x0006;
soe.Write(0x0040, &cw, sizeof(cw));
Typed reads
All typed read methods share the same signature: parameters (uint16_t idn, int timeoutMs = 500), returning the matching std::optional<T>.
| Category | Method | Type | Read/write | Description |
|---|---|---|---|---|
| Typed read | ReadInt16() | std::optional<int16_t> | read-only | Reads a 16-bit signed integer |
| ReadInt32() | std::optional<int32_t> | read-only | Reads a 32-bit signed integer | |
| ReadUInt16() | std::optional<uint16_t> | read-only | Reads a 16-bit unsigned integer | |
| ReadUInt32() | std::optional<uint32_t> | read-only | Reads a 32-bit unsigned integer | |
| ReadFloat() | std::optional<float> | read-only | Reads a single-precision float | |
| ReadDouble() | std::optional<double> | read-only | Reads a double-precision float | |
| ReadString() | std::optional<std::string> | read-only | Reads a string |
Example:
auto& soe = master.GetSlave(1).GetSoE();
// Read the position feedback (S-0-0051). A failed read is nullopt, not 0
auto actualPos = soe.ReadInt32(0x0033);
if (actualPos) printf("位置反馈: %d\n", *actualPos); // Position feedback: %d
else printf("位置读取失败\n"); // Position read failed
// Read the drive status word (S-0-0071)
auto status = soe.ReadUInt16(0x0047);
if (status) printf("状态字: 0x%04X\n", *status); // Status word: 0x%04X
// Read the parameter name (use ReadName to read a name, not ReadString)
auto name = soe.ReadName(0x0033);
if (name) printf("参数名: %s\n", name->c_str()); // Parameter name: %s
Typed writes
All typed write methods share the same signature: parameters (uint16_t idn, T value, int timeoutMs = 500), returning bool.
| Category | Method | Type | Read/write | Description |
|---|---|---|---|---|
| Typed write | WriteInt16() | int16_t | write-only | Writes a 16-bit signed integer |
| WriteInt32() | int32_t | write-only | Writes a 32-bit signed integer | |
| WriteUInt16() | uint16_t | write-only | Writes a 16-bit unsigned integer | |
| WriteUInt32() | uint32_t | write-only | Writes a 32-bit unsigned integer | |
| WriteFloat() | float | write-only | Writes a single-precision float | |
| WriteDouble() | double | write-only | Writes a double-precision float | |
| WriteString() | const std::string& | write-only | Writes a string |
Example:
auto& soe = master.GetSlave(1).GetSoE();
// Set the position command (S-0-0047)
soe.WriteInt32(0x002F, 50000);
// Write the control word (S-0-0064)
soe.WriteUInt16(0x0040, 0x0006);
Reading metadata
ReadName()
std::optional<std::string> ReadName(uint16_t idn, int timeoutMs = 500) const;
Reads the IDN parameter name (Element 0x02). Returns empty when it cannot be read.
Parameters:
idn(uint16_t) — IDN numbertimeoutMs(int) — timeout (milliseconds, default 500)
Returns:
std::optional<std::string>— the parameter name;std::nulloptwhen it cannot be read
ReadUnit()
std::optional<std::string> ReadUnit(uint16_t idn, int timeoutMs = 500) const;
Reads the IDN parameter unit (Element 0x08). Returns empty when it cannot be read.
Parameters:
idn(uint16_t) — IDN numbertimeoutMs(int) — timeout (milliseconds, default 500)
Returns:
std::optional<std::string>— the parameter unit;std::nulloptwhen it cannot be read
ReadAttributes()
std::optional<SoEAttributes> ReadAttributes(uint16_t idn, int timeoutMs = 500) const;
Reads the IDN parameter attributes (data type, length, access-rights bit field and so on).
Parameters:
idn(uint16_t) — IDN numbertimeoutMs(int) — timeout (milliseconds, default 500)
Returns:
std::optional<SoEAttributes>— the attribute object;std::nullopton failure
WriteAttribute()
bool WriteAttribute(uint16_t idn, uint32_t attrValue, int timeoutMs = 500) const;
Writes the attribute bit field for an IDN (Element 0x04); the 32 bits are assembled little-endian in ETG order. For the attribute bit field layout see the decode convention of SoEAttributes.
Parameters:
idn(uint16_t) — IDN numberattrValue(uint32_t) — the raw 32-bit attribute bit fieldtimeoutMs(int) — timeout (milliseconds, default 500)
Returns:
bool—trueon success,falseon failure
ReadMinValue / ReadMaxValue / ReadDefaultValue
std::vector<uint8_t> ReadMinValue(uint16_t idn, int timeoutMs = 500) const;
std::vector<uint8_t> ReadMaxValue(uint16_t idn, int timeoutMs = 500) const;
std::vector<uint8_t> ReadDefaultValue(uint16_t idn, int timeoutMs = 500) const;
Reads the minimum (0x10), maximum (0x20) and default (0x80) value of an IDN parameter. Returns an empty array on failure. ReadMin() / ReadMax() are convenience aliases for the minimum / maximum value (the same data), ReadIDNList() is equivalent to GetAvailableIDNs().
Parameters:
idn(uint16_t) — IDN numbertimeoutMs(int) — timeout (milliseconds, default 500)
Returns:
std::vector<uint8_t>— the raw element bytes; an empty array on failure
Example:
auto& soe = master.GetSlave(1).GetSoE();
auto name = soe.ReadName(0x0033);
auto unit = soe.ReadUnit(0x0033);
auto attrs = soe.ReadAttributes(0x0033);
auto minVal = soe.ReadMinValue(0x0033);
auto maxVal = soe.ReadMaxValue(0x0033);
if (name) printf("参数: %s", name->c_str()); // Parameter: %s
if (unit) printf(" (%s)", unit->c_str());
printf("\n");
if (attrs) {
printf("数据类型: %d, 列表=%s, 命令=%s\n", // Data type: %d, list=%s, command=%s
static_cast<int>(attrs->DataType),
attrs->IsList ? "是" : "否",
attrs->IsCommand ? "是" : "否");
}
if (minVal.size() >= 4 && maxVal.size() >= 4) {
auto le32 = [](const std::vector<uint8_t>& d) {
return static_cast<int32_t>(
static_cast<uint32_t>(d[0]) | (static_cast<uint32_t>(d[1]) << 8)
| (static_cast<uint32_t>(d[2]) << 16) | (static_cast<uint32_t>(d[3]) << 24));
};
printf("范围: %d - %d\n", le32(minVal), le32(maxVal)); // Range: %d - %d
}
Parameter information
GetAvailableIDNs()
std::vector<uint16_t> GetAvailableIDNs(int timeoutMs = 5000) const;
Gets the list of every IDN the slave supports.
Parameters:
timeoutMs(int) — timeout (milliseconds, default 5000)
Returns:
std::vector<uint16_t>— the list of IDN numbers
GetParameterInfo()
SoEParameter GetParameterInfo(uint16_t idn, int timeoutMs = 5000) const;
Gets the complete information of an IDN parameter (name, unit, attributes, current value, minimum/maximum value and so on).
Parameters:
idn(uint16_t) — IDN numbertimeoutMs(int) — timeout (milliseconds, default 5000)
Returns:
SoEParameter— the complete parameter information
Related structures:
struct SoEParameter {
uint16_t IDN; // IDN number
std::string Name; // Parameter name
std::string Unit; // Unit
SoEAttributes Attributes; // Attributes (data type, length and so on)
std::vector<uint8_t> Value; // Current value
std::vector<uint8_t> DefaultValue; // Default value
std::vector<uint8_t> MinValue; // Minimum value
std::vector<uint8_t> MaxValue; // Maximum value
std::string Category() const; // Category ("Standard" / "Product" / "Vendor")
std::string SercosIDN() const; // SERCOS IDN format (e.g. "S-0-0001")
bool IsReadOnly() const; // Whether it is read-only
std::string AccessMode() const; // Access rights ("RO" / "RW" / "RW*")
std::string FormattedValue() const; // Formatted current value
std::string FormattedMinValue() const; // Formatted minimum value
std::string FormattedMaxValue() const; // Formatted maximum value
std::string FormattedDefaultValue() const; // Formatted default value
};
struct SoEAttributes {
uint16_t EvaluationFactor; // Rating factor
uint8_t Length; // Data length
bool IsList; // Whether it is a list
bool IsCommand; // Whether it is a command
SoEDataType DataType; // Data type
uint8_t Decimals; // Decimal places
bool WriteProtectedPreOp; // Write protection in PreOp state
bool WriteProtectedSafeOp; // Write protection in SafeOp state
bool WriteProtectedOp; // Write protection in Op state
std::string AccessMode() const; // Access rights string ("RO", "RW", "RW*")
};
enum class SoEDataType : uint8_t {
Binary = 0, // Binary
UInt = 1, // Unsigned integer
Int = 2, // Signed integer
Hexadecimal = 3, // Hexadecimal
String = 4, // String
IDN = 5, // IDN reference
Float = 6, // Floating-point number
Parameter = 7 // Parameter
};
Example:
auto& soe = master.GetSlave(1).GetSoE();
auto param = soe.GetParameterInfo(0x0033);
printf("IDN: %s - %s\n", param.SercosIDN().c_str(), param.Name.c_str());
printf("单位: %s, 访问: %s\n", param.Unit.c_str(), param.AccessMode().c_str()); // Unit: %s, access: %s
printf("当前值: %s\n", param.FormattedValue().c_str()); // Current value: %s
printf("范围: %s - %s\n", param.FormattedMinValue().c_str(), param.FormattedMaxValue().c_str()); // Range: %s - %s
FormatValueWithAttributes()
static std::string FormatValueWithAttributes(const std::vector<uint8_t>& data,
const SoEAttributes& attr);
Static helper method: decodes the raw bytes into readable text according to attr.DataType; multi-byte numeric values are always decoded little-endian in ETG wire order, independent of the host byte order.
Parameters:
data(const std::vector<uint8_t>&) — raw bytes, usuallySoEParameter'sValue/DefaultValue/MinValue/MaxValueattr(const SoEAttributes&) — the parameter attributes, deciding which data type to interpret by
Returns:
std::string— the formatted text; returnsN/Awhendatais empty
Formatting rules:
- Binary — space-separated uppercase hexadecimal byte string
- UInt / Int — decoded to decimal from 1 / 2 / 4 / 8 bytes little-endian; signed types are interpreted as two's complement
- Hexadecimal — outputs uppercase hexadecimal with a 0x prefix when the data is no more than 4 bytes
- String — the text after stripping the trailing NUL
- Float — 4 / 8 bytes little-endian IEEE754, 6 decimal places kept
- IDN — outputs
IDN 0xXXXX - Other types or a failed decode — falls back to a hexadecimal byte string
Example:
auto param = soe.GetParameterInfo(0x0033);
std::string text = SoEParameter::FormatValueWithAttributes(param.Value, param.Attributes);
printf("%s = %s\n", param.SercosIDN().c_str(), text.c_str());
AT/MDT mapping
SERCOS uses AT (Acknowledge Telegram) and MDT (Master Data Telegram) to transfer cyclic data:
- AT = cyclic inputs from slave to master (actual position, actual velocity, status word …)
- MDT = cyclic outputs from master to slave (target position, target velocity, control word …)
The mapping configuration decides which IDN parameters are included in the cyclic data frame.
GetIDNMapping()
SoE::ServoMappingInfo GetIDNMapping(int timeoutMs = 5000) const;
Reads the current drive's AT/MDT mapping configuration. The return types ServoMappingInfo / ServoMappingEntry are nested structures of the SoE class.
Parameters:
timeoutMs(int) — timeout (milliseconds, default 5000)
Returns:
SoE::ServoMappingInfo— the mapping information object
Related structures (nested types of SoE):
struct SoE::ServoMappingEntry {
uint16_t IDN; // IDN number
std::string Name; // Parameter name
int BitLength; // Data length (bits)
int ByteLength() const; // Data length (bytes)
};
struct SoE::ServoMappingInfo {
std::vector<ServoMappingEntry> ATMapping; // AT (input) mapping list
std::vector<ServoMappingEntry> MDTMapping; // MDT (output) mapping list
int ATBitSize; // AT total bits
int MDTBitSize; // MDT total bits
bool ATValid; // Whether the AT configuration was actually read
bool MDTValid; // Whether the MDT configuration was actually read
int ATByteSize() const; // AT total bytes
int MDTByteSize() const; // MDT total bytes
};
ATValid / MDTValid being false means the mapping configuration for that direction was not read (the read failed or the slave does not support it); the matching bit count then stays 0 — 0 bits does not mean 0 bits measured, so check these two flags before trusting the size. Each entry's bit length is derived from the Length in its attributes (0 = 16 bits, 1 = 32 bits, 2 = 64 bits, 3 = cannot be determined, recorded as 0).
GetAllDriveMappings()
std::map<uint8_t, SoE::ServoMappingInfo> GetAllDriveMappings(int timeoutMs = 5000) const;
Gets the mapping information for all drives (up to 8 drives are scanned). Slots with no drive or no response are normal cases; they are skipped and do not enter the result.
Parameters:
timeoutMs(int) — read timeout per drive (milliseconds, default 5000)
Returns:
std::map<uint8_t, SoE::ServoMappingInfo>— dictionary from drive number to mapping information
Parameter change notification
The SoE Notification feature lets you monitor SERCOS slave IDN parameters for changes. When it is enabled, the SDK writes S-0-0127 (notification request) to ask the slave for a hardware notification; whether or not that request succeeds, the IDN enters the local monitor list, where PollNotifications() polls the current value and compares it with the last recorded value, returning a change event when a change is found.
Thread safety: the monitor list is driven by the caller's thread (EnableNotification / PollNotifications and so on); concurrent calls on the same SoE instance from multiple threads must be serialized by the caller.
EnableNotification()
bool EnableNotification(uint16_t idn, int timeoutMs = 500);
Enables parameter change notification for the given IDN. It first tries to enable the hardware notification through S-0-0127; whether or not that succeeds, the IDN is added to the polling monitor list (with the current value as the comparison baseline).
Parameters:
idn(uint16_t) — the IDN number to monitortimeoutMs(int) — timeout (milliseconds, default 500)
Returns:
bool—truemeans the slave confirmed hardware notification support;falsemeans it fell back to polling mode
DisableNotification()
bool DisableNotification(uint16_t idn, int timeoutMs = 500);
Disables parameter change notification for the given IDN. true = the local monitor was removed (for an IDN whose hardware notification was enabled, S-0-0127 is also written to unsubscribe); false = the hardware unsubscribe failed, and that item stays in the monitor list for retry.
A failed hardware unsubscribe is counted in NotifyCancelFailureCount(); the local monitor table is left alone, so DisableNotification() can be called again later to retry.
DisableAllNotifications()
bool DisableAllNotifications(int timeoutMs = 500);
Disables all enabled notifications, each with a real unsubscribe. true = all removed; false = at least one hardware unsubscribe failed, and the failed items stay in the monitor list for retry.
PollNotifications()
std::vector<SoENotificationEventArgs> PollNotifications(int timeoutMs = 200);
Polls all monitored IDNs for parameter changes. It reads the current value of each in turn and compares it with the last recorded value, returning the list of change events when a change is found. Suited to a periodic call from a timer or a background thread.
Parameters:
timeoutMs(int) — read timeout per IDN (milliseconds, default 200)
Returns:
std::vector<SoENotificationEventArgs>— the list of change events detected by this poll
GetMonitoredIDNs()
std::vector<uint16_t> GetMonitoredIDNs() const;
Gets the list of IDNs currently being monitored.
SoENotificationEventArgs
struct SoENotificationEventArgs {
uint16_t SlaveIndex; // Slave index
uint8_t DriveNumber; // Drive number
uint16_t IDN; // Number of the IDN that changed
std::vector<uint8_t> NewValue; // New value
std::vector<uint8_t> OldValue; // Old value
std::string SercosIDN() const; // Formatted SERCOS IDN name (e.g. "S-0-0127")
std::string ToString() const; // Formatted event description
};
Example:
auto& soe = master.GetSlave(1).GetSoE();
// Enable monitoring the position feedback (S-0-0051)
bool hwSupported = soe.EnableNotification(0x0033);
printf("硬件通知: %s\n", hwSupported ? "支持" : "回退到轮询"); // Hardware notification: %s (supported / falling back to polling)
// Enable monitoring the drive status word (S-0-0071)
soe.EnableNotification(0x0047);
// Poll to detect changes
while (running) {
auto changes = soe.PollNotifications();
for (auto& c : changes) {
printf("参数变化: %s (IDN 0x%04X)\n", c.SercosIDN().c_str(), c.IDN); // Parameter change: %s (IDN 0x%04X)
printf(" 旧值: %s\n", FormatByteArray(c.OldValue).c_str()); // Old value: %s
printf(" 新值: %s\n", FormatByteArray(c.NewValue).c_str()); // New value: %s
}
std::this_thread::sleep_for(std::chrono::milliseconds(100));
}
// View the monitored IDNs
auto monitored = soe.GetMonitoredIDNs();
printf("正在监控 %zu 个 IDN\n", monitored.size()); // Monitoring %zu IDNs
// Stop monitoring
soe.DisableAllNotifications();
Procedure commands
ExecuteCommand()
bool ExecuteCommand(uint16_t idn, int timeoutMs = 5000, int pollIntervalMs = 50) const;
Executes an SoE procedure command (SERCOS Procedure Command). It triggers command execution by writing bit0 of the DataState element (0x01), then polls until the command completes.
Parameters:
idn(uint16_t) — the IDN number of the command to executetimeoutMs(int) — timeout for waiting until the command completes (milliseconds, default 5000)pollIntervalMs(int) — polling interval (milliseconds, default 50)
Returns:
bool—truewhen the command completed successfully,falseon timeout or failure
Example:
auto& soe = master.GetSlave(1).GetSoE();
// Execute a process command defined by the device manual (such as a homing command)
bool success = soe.ExecuteCommand(0x0094);
if (success)
printf("命令完成\n"); // Command completed
else
printf("命令超时或失败\n"); // Command timed out or failed
// Custom timeout (for long-running commands)
bool ok = soe.ExecuteCommand(0x0094, 30000, 100);
ExecuteCommand() overload with drive number
bool ExecuteCommand(uint16_t idn, uint8_t driveNo, uint8_t elementFlags,
int timeoutMs = 5000, int pollIntervalMs = 50) const;
The same command flow, additionally specifying the drive number and the element flags (state reads and writes use elementFlags combined with 0x01).
Parameters:
idn(uint16_t) — the IDN number of the command to executedriveNo(uint8_t) — drive number (multi-axis slave)elementFlags(uint8_t) — element flags (combined automatically with the 0x01 data state)timeoutMs(int) — timeout for waiting until the command completes (milliseconds, default 5000)pollIntervalMs(int) — polling interval (milliseconds, default 50)
Returns:
bool—truewhen the command completed successfully;falsewhen a status bit reports an error or on timeout
ReadDataState()
std::optional<uint16_t> ReadDataState(uint16_t idn, int timeoutMs = 500) const;
Reads the Data State element of an IDN (Element 0x01). bit0 = procedure command requested / in progress, bit1 = command error; ExecuteCommand() judges completion and failure by these two bits.
Parameters:
idn(uint16_t) — IDN numbertimeoutMs(int) — timeout (milliseconds, default 500)
Returns:
std::optional<uint16_t>— the Data State value;std::nullopton failure
Example:
auto& soe = master.GetSlave(1).GetSoE();
// Read the Data State of an IDN
auto state = soe.ReadDataState(0x0094);
if (state) {
bool commandActive = (*state & 0x01) != 0;
bool commandError = (*state & 0x02) != 0;
printf("命令激活: %s, 命令错误: %s\n", // Command active: %s, command error: %s
commandActive ? "是" : "否",
commandError ? "是" : "否");
}
Standard IDN constants
struct StandardIDN {
static constexpr uint16_t IDNList = 0x0000; // IDN list (S-0-0000)
static constexpr uint16_t CycleTime = 0x0001; // Communication cycle time (S-0-0001)
static constexpr uint16_t ATConfig = 0x0010; // AT configuration - input mapping (S-0-0016)
static constexpr uint16_t MDTConfig = 0x0018; // MDT configuration - output mapping (S-0-0024)
static constexpr uint16_t NotificationRequest = 0x007F; // Notification request (S-0-0127)
};
Accessed through SoE::StandardIDN::CycleTime and so on.
Complete example
Parameter scan
#include "ethercat.hpp"
using namespace darra;
auto& soe = master.GetSlave(1).GetSoE();
// Get all supported IDNs
auto idns = soe.GetAvailableIDNs();
printf("从站支持 %zu 个 IDN 参数\n\n", idns.size()); // Slave supports %zu IDN parameters
int limit = std::min<int>(static_cast<int>(idns.size()), 10);
for (int i = 0; i < limit; ++i) {
auto info = soe.GetParameterInfo(idns[i]);
printf("%s: %s = %s %s [%s]\n",
info.SercosIDN().c_str(),
info.Name.c_str(),
info.FormattedValue().c_str(),
info.Unit.c_str(),
info.AccessMode().c_str());
}
Servo drive control
#include "ethercat.hpp"
using namespace darra;
int main() {
darra::ethercat::dll_t dll;
EtherCATMaster master(dll);
master.SetNetwork("\\Device\\NPF_{...}")
.SetENI("config.deni")
.Build();
master.SetState(EcState::OP);
master.Start();
auto& soe = master.GetSlave(1).GetSoE();
// 1. Read the drive status
auto statusWord = soe.ReadUInt16(0x0047);
if (statusWord)
printf("状态字: 0x%04X\n", *statusWord); // Status word: 0x%04X
// 2. Inspect the AT/MDT mapping (to understand the cyclic data layout)
auto mapping = soe.GetIDNMapping();
if (mapping.ATValid) {
printf("\nAT 映射(输入 %d 字节):\n", mapping.ATByteSize()); // AT mapping (input %d bytes):
for (auto& entry : mapping.ATMapping)
printf(" IDN 0x%04X: %s (%dB)\n", entry.IDN, entry.Name.c_str(), entry.ByteLength());
}
if (mapping.MDTValid) {
printf("\nMDT 映射(输出 %d 字节):\n", mapping.MDTByteSize()); // MDT mapping (output %d bytes):
for (auto& entry : mapping.MDTMapping)
printf(" IDN 0x%04X: %s (%dB)\n", entry.IDN, entry.Name.c_str(), entry.ByteLength());
}
// 3. Write the control word to enable the drive (S-0-0064)
soe.WriteUInt16(0x0040, 0x0006);
// 4. Set the position command (S-0-0047)
soe.WriteInt32(0x002F, 50000);
// 5. Read the position feedback (S-0-0051)
auto actualPos = soe.ReadInt32(0x0033);
if (actualPos)
printf("\n位置反馈: %d inc\n", *actualPos); // Position feedback: %d inc
getchar();
return 0;
}
Parameter change notification callbacks
Besides the PollNotifications() polling approach, the SDK also provides a std::function-based callback registration mechanism. Parameter change (IDN Notification) events are detected by the runtime's background thread, and when they fire the callbacks run in a background thread context — if a callback needs to touch the UI or shared state, it must lock or post to the main thread itself.
The C++ SDK does not provide SoEEmergencyEvent / AddEmergencyCallback / RemoveEmergencyCallback / EmergencyCount. SERCOS OpCode=6 online actually means Slave Info (not Emergency as in older material); the runtime merges it into the notification channel. To receive such slave reports, subscribe to SoENotificationEvent. If another language SDK keeps an Emergency event, that is a surface difference on that language's side, not a C++ capability.
The SoE class has no AddNotificationCallback member method.
The SoE notification callback on the DLL side is a single global callback; multiple SoE instances share the same event stream, routed centrally by the darra::ethercat::SoERuntimeEvents singleton. Usage:
auto& evt = SoERuntimeEvents::Instance();
evt.Bind(dll); // Call once after loading the DLL and before the first subscription
size_t h = evt.AddNotificationCallback(cb); // Returns the subscription handle
// evt.RemoveNotificationCallback(h); evt.Clear();
SoENotificationEvent
struct SoENotificationEvent {
int slaveIndex; // Slave index (1-based)
uint8_t driveNumber; // Drive number
uint8_t elementFlags; // Element flags (0x40 = data value)
uint16_t idn; // The IDN that changed
std::vector<uint8_t> newValue; // Raw bytes of the new value
std::chrono::system_clock::time_point timestamp; // Event timestamp
};
SoERuntimeEvents::AddNotificationCallback()
class SoERuntimeEvents {
public:
using NotificationCallback = std::function<void(const SoENotificationEvent&)>;
static SoERuntimeEvents& Instance(); // Global singleton
void Bind(dll_t& dll); // Bind the DLL (call once before the first subscription)
size_t AddNotificationCallback(NotificationCallback cb); // Returns the subscription handle
void RemoveNotificationCallback(size_t handle);
void Clear(); // Clears only this layer's dispatch list (the DLL side keeps its registrations)
void Unregister(); // Clear + unregister the callback from the DLL (before exiting the process / resetting the event stream)
size_t NotificationCount() const; // Current notification subscription count
};
Clear()— only clears this layer'sstd::functiondispatch list; the callback registration on the DLL side stays in place.Unregister()— clears the dispatch list and removes the callback registration from the DLL. Call it before process exit / resetting the event stream so the registration is removed cleanly.
Registers a parameter change callback. It can be called several times to register several callbacks; all callbacks fire in registration order. Callbacks run on the runtime's background notification thread.
Example (C++17 lambda):
using darra::ethercat::SoERuntimeEvents;
auto& evt = SoERuntimeEvents::Instance();
evt.Bind(dll); // Call once after loading the DLL and before the first subscription
// Parameter change callback
evt.AddNotificationCallback([](const SoENotificationEvent& e) {
std::cout << "[" << std::chrono::duration_cast<std::chrono::milliseconds>(
e.timestamp.time_since_epoch()).count()
<< "ms] IDN 0x" << std::hex << e.idn
<< " 变化 (从站 " << std::dec << e.slaveIndex // changed (slave
<< " 驱动 " << (int)e.driveNumber << ")\n"; // drive
});
// Enable monitoring the target IDN (hardware notification is enabled by the SoE instance's EnableNotification)
auto& soe = master.GetSlave(1).GetSoE();
soe.EnableNotification(0x0047); // Drive status word
soe.EnableNotification(0x0033); // Position feedback
AddNotificationCallbackreturns a subscription handle; useRemoveNotificationCallback(handle)to remove a single callback, orClear()to clear them all- Callbacks run on a background thread; when touching the UI or non-thread-safe containers, use
std::mutex/PostMessage/Invokeyourself - Avoid blocking inside a callback (such as file IO or synchronous IO), so the notification thread is not slowed down
ETG.6220 §7 SoE Notification; SERCOS II standard §2.10 Diagnostic data.
Error queries
GetLastSoEError()
std::optional<SoEError> GetLastSoEError() const;
Reads the failure reason of the most recent Read() / Write(); for the error code values see the SoEError enum (SDK header data/types.hpp).
Returns:
std::optional<SoEError>—std::nullopt= the most recent operation succeeded;NoOperationData= what was read is empty operation data;Unknown= communication failure / write failure
Example:
auto data = soe.Read(0x0033);
if (data.empty()) {
if (auto err = soe.GetLastSoEError())
printf("读取失败: 0x%04X\n", static_cast<uint16_t>(*err)); // Read failed: 0x%04X
}
Members of the same family: GetLastSoEErrorCode() reads the ETG.5003 advanced error code (the SoEErrorCode enum); it is a field independent of the basic SoEError and the two never overwrite each other; SetLastSoEErrorCode(code) writes that field, ClearLastSoEErrorCode() clears it. The SDK itself never fills in the advanced error code, so a value can only be read if the caller set it explicitly.
SetLastSoEErrorCode()
void SetLastSoEErrorCode(SoEErrorCode code);
Writes the ETG.5003 advanced error code field, which GetLastSoEErrorCode() then reads back. It does not affect the basic error code maintained by GetLastSoEError().
Parameters:
code(SoEErrorCode) — the advanced error code to record; for the values see theSoEErrorCodeenum indata/types.hpp
Example:
soe.SetLastSoEErrorCode(SoEErrorCode::NoIDN);
if (auto code = soe.GetLastSoEErrorCode())
printf("高级错误码: 0x%04X\n", static_cast<uint16_t>(*code)); // Advanced error code: 0x%04X
soe.ClearLastSoEErrorCode();
Failures and handling
| Symptom | Cause | Action |
|---|---|---|
| Read returns an empty array | The IDN number does not exist on that slave | Switch to an IDN given in the device manual; first confirm whether the parameter belongs to the standard segment or the vendor-defined segment |
| Write returns false | The parameter is write-protected (password or access-level restriction) | Confirm the parameter allows writing; if necessary, switch to an access level with write permission and write again |
| Read / Write fails and takes noticeably longer | Mailbox transaction timeout, or the slave did not answer | Confirm the slave mailbox is available and the state is normal, then retry, or increase timeoutMs |
| Write is rejected | The parameter can only be written in a specific servo state | Wait until the servo enters the state that allows this parameter, then write, avoiding the state-transition window |