SoE (Servo over EtherCAT)
SoE carries SERCOS servo parameters in the EtherCAT mailbox: parameters are addressed by a 16-bit IDN and can be read or written as raw bytes, or queried for their name and unit separately.
Most servo devices use CoE + CiA 402; SoE applies only to SERCOS-compatible servo devices (such as the Bosch Rexroth IndraDrive series), and a single slave cannot mix the two protocols.
Access it through slave.SoE. It is null when the slave does not support SoE.
Method overview
| Category | Method | Type | Read/write | Description |
|---|---|---|---|---|
| Protocol capability | IsSupported | bool | Read-only | bool view of SoESupport == true; true only when support is known |
| Protocol capability | SoESupport | bool? | Read-only | Tri-state capability: true = supported, false = confirmed not declared, null = unknown |
| Protocol capability | IsSupportedKnown | bool | Read-only | Whether the capability verdict is known; false = unknown (not the same as unsupported) |
| Parameter read/write | Read | byte[]? | Read-only | Reads the raw parameter bytes by IDN; returns null on failure |
| Parameter read/write | Write | bool | Write-only | Writes the raw parameter bytes by IDN; returns false on failure |
| Parameter read/write | ReadInt16 / ReadInt32 / ReadUInt16 / ReadUInt32 / ReadFloat / ReadDouble / ReadString | short? / int? / ushort? / uint? / float? / double? / string? | Read-only | Typed reads; return null on failure |
| Parameter read/write | WriteInt16 / WriteInt32 / WriteUInt16 / WriteUInt32 | bool | Write-only | Typed writes; return false on failure |
| Metadata | ReadName | string? | Read-only | Reads the IDN parameter name |
| Metadata | ReadUnit | string? | Read-only | Reads the IDN parameter unit |
| Metadata | ReadMinValue / ReadMaxValue / ReadDefaultValue | byte[]? | Read-only | Reads the parameter minimum / maximum / default value |
| Parameter information | GetAvailableIDNs | List<ushort> | Read-only | Lists every IDN the slave supports; throws SoEException if the query fails |
| Parameter information | GetParameterInfo | SoEParameter | Read-only | Reads the full parameter information for an IDN; throws SoEException if the query fails |
| Mapping | GetIDNMapping | ServoMappingInfo | Read-only | Reads the current drive AT/MDT mapping configuration |
| Mapping | GetAllDriveMappings | Dictionary<byte, ServoMappingInfo> | Read-only | Reads the mapping information of all drives (up to 8) |
| Procedure commands | ExecuteCommand | bool | Write-only | Executes a SERCOS procedure command and waits for it to complete |
| Procedure commands | ReadDataState | ushort? | Read-only | Reads the Data State element of an IDN |
| Procedure commands | WaitForProcedureDone | bool | Read-only | Polls until the procedure command completes |
| Notifications | NotificationReceived | Action<SoENotificationEventArgs> | Read-only | Fires when the value of a monitored IDN changes; the callback carries the IDN plus the old and new values |
| Notifications | EnableNotification | bool | Write-only | Enables change notification for an IDN; true = hardware notification enabled |
| Notifications | DisableNotification / DisableAllNotifications | void | Write-only | Disables one or all parameter change notifications |
| Notifications | PollNotifications | int | Read-only | Polls for parameter changes and raises the events; returns the number of changes |
| Notifications | GetMonitoredIDNs | List<ushort> | Read-only | Snapshot of the IDNs whose notification is currently enabled |
| Notifications | EmergencyReceived | Action<SoEEmergencyEventArgs> | Read-only | Fires when a Sercos Emergency (OpCode=6) is received |
| Async | ReadAsync / WriteAsync / the *Async variants of the typed reads and writes / GetAvailableIDNsAsync / GetParameterInfoAsync / EnableNotificationAsync / PollNotificationsAsync | Task<...> | Read/write | Asynchronous wrappers around the synchronous API; cancellation affects only the caller, see Async methods |
| Error codes | LastSoEError / LastStatus / LastErrorCode | SoEError? / MailboxStatus / uint | Read-only | Error code and mailbox transaction status of the most recent operation |
| Encoding helpers | SoEInstance.EncodeIdn / DecodeIdn / TryParseSercosIdn | ushort / tuple / bool | Read-only | Converts between IDN numbers and triples / SERCOS strings; pure bit arithmetic |
Protocol capability
| Category | Property | Type | Read/write | Description |
|---|---|---|---|---|
| Protocol capability | IsSupported | bool | Read-only | bool view of SoESupport == true: true only when support is known, false when the verdict is unknown |
| SoESupport | bool? | Read-only | Tri-state SoE capability: true = supported, false = mbx_proto was actually read and the bit is clear, null = unknown (read failed) | |
| IsSupportedKnown | bool | Read-only | Whether the capability verdict is known; false = unknown (not the same as unsupported) |
SoESupport returns bool?: true = supported, false = the SII mbx_proto word was actually read and the bit is clear, null = it could not be read on this call (the call failed). A read failure is no longer folded into false; to tell "confirmed unsupported" apart from "unknown", check SoESupport / IsSupportedKnown.
SERCOS IDN system
SoE addresses drive parameters through the IDN (Identification Number). Each IDN is a 16-bit number that stands 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 |
| — | 0xC000 – 0xFFFF | Vendor-defined parameters |
Common standard IDNs (servo control):
| IDN | SERCOS name | Description | Data type |
|---|---|---|---|
| S-0-0001 (0x0001) | Cycle Time | Communication cycle time | uint, µs |
| S-0-0011 (0x000B) | Position Feedback 1 | Actual position | int, inc |
| S-0-0012 (0x000C) | Position Command | Target position | int, inc |
| S-0-0013 (0x000D) | Velocity Feedback | Actual velocity | int, rpm |
| S-0-0014 (0x000E) | Velocity Command | Target velocity | int, rpm |
| S-0-0016 (0x0010) | AT Config | Input mapping configuration list | list |
| S-0-0019 (0x0013) | Drive Status | Drive status word | ushort |
| S-0-0024 (0x0018) | MDT Config | Output mapping configuration list | list |
| S-0-0036 (0x0024) | Max Velocity | Maximum velocity limit | uint, rpm |
| S-0-0040 (0x0028) | Homing Velocity | Homing velocity | uint, rpm |
| S-0-0064 (0x0040) | Drive Control Word | Drive control word | ushort |
| S-0-0071 (0x0047) | Drive Status Word | Drive status word | ushort |
Element flags — the different "layers" of reading an IDN:
| Flag | Meaning |
|---|---|
| 0x01 | Data state |
| 0x02 | Parameter name (string) |
| 0x04 | Attributes (data type / length / access bit field) |
| 0x08 | Unit (string) |
| 0x10 | Minimum value |
| 0x20 | Maximum value |
| 0x40 | Data value (default, most common) |
| 0x80 | Default value |
The SoEElementFlags enum overloads of Read / Write map to the members of the same name: DataStatus = 0x01, Name = 0x02, Attribute = 0x04, Unit = 0x08, Min = 0x10, Max = 0x20, Value = 0x40; combine them with a bitwise OR to read or write several elements at once. The default value 0x80 goes through the byte overload or ReadDefaultValue.
Basic read and write
Read(ushort idn, byte elementFlags = 0x40, int timeoutMs = 500)
public byte[]? Read(ushort idn, byte elementFlags = 0x40, int timeoutMs = 500)
public byte[]? Read(ushort idn, SoEElementFlags elementFlags, int timeoutMs = 500)
Reads the raw bytes of an IDN parameter. When the slave is not in PreOp / SafeOp / OP (the states in which the mailbox is available), the SDK switches to PreOp first and then reads; if the switch fails it returns null. The second overload takes the SoEElementFlags enum ([Flags], combinable with OR) instead of a bare byte, and elementFlags has no default value.
Parameters:
idn(ushort) — IDN numberelementFlags(byte) — element flags (default 0x40 = data value)timeoutMs(int) — timeout in milliseconds (default 500)
Return value:
byte[]?— the data read;nullon failure
Example:
// Read the communication cycle time (S-0-0001)
byte[]? data = slave.SoE.Read(0x0001, 0x40);
if (data != null)
{
uint cycleTime = BitConverter.ToUInt32(data, 0);
Console.WriteLine($"周期时间: {cycleTime} μs"); // Cycle time: {cycleTime} µs
}
Write(ushort idn, byte[] data, byte elementFlags = 0x40, int timeoutMs = 500)
public bool Write(ushort idn, byte[] data, byte elementFlags = 0x40, int timeoutMs = 500)
public bool Write(ushort idn, byte[] data, SoEElementFlags elementFlags, int timeoutMs = 500)
Writes an IDN parameter. When the slave is not in PreOp / SafeOp / OP, the SDK switches to PreOp first and then writes; if the switch fails it returns false. The second overload takes the SoEElementFlags enum instead of a bare byte, and elementFlags has no default value.
Parameters:
idn(ushort) — IDN numberdata(byte[]) — the data to writeelementFlags(byte) — element flags (default 0x40 = data value)timeoutMs(int) — timeout in milliseconds (default 500)
Return value:
bool—trueon success
Example:
// Set the target position (S-0-0012)
byte[] position = BitConverter.GetBytes(100000);
bool success = slave.SoE.Write(0x000C, position);
Typed reads
All methods share the same signature: ReadXxx(ushort idn, byte elementFlags = 0x40, int timeoutMs = 500)
| Category | Method | Type | Read/write | Description |
|---|---|---|---|---|
| Typed reads | ReadInt16 | short? | Read-only | Reads a 16-bit signed integer |
| ReadInt32 | int? | Read-only | Reads a 32-bit signed integer | |
| ReadUInt16 | ushort? | Read-only | Reads a 16-bit unsigned integer | |
| ReadUInt32 | uint? | Read-only | Reads a 32-bit unsigned integer | |
| ReadFloat | float? | Read-only | Reads a single-precision floating-point value | |
| ReadDouble | double? | Read-only | Reads a double-precision floating-point value | |
| ReadString | string? | Read-only | Reads a string |
Example:
// Read the actual position (S-0-0011)
int? actualPos = slave.SoE.ReadInt32(0x000B);
// Read the drive status word (S-0-0071)
ushort? status = slave.SoE.ReadUInt16(0x0047);
// Read the parameter name
string? name = slave.SoE.ReadString(0x000B, elementFlags: 0x02);
Typed writes
All methods share the same signature: WriteXxx(ushort idn, T value, byte elementFlags = 0x40, int timeoutMs = 500), returning bool.
| Category | Method | Type | Read/write | Description |
|---|---|---|---|---|
| Typed writes | WriteInt16 | short | Write-only | Writes a 16-bit signed integer |
| WriteInt32 | int | Write-only | Writes a 32-bit signed integer | |
| WriteUInt16 | ushort | Write-only | Writes a 16-bit unsigned integer | |
| WriteUInt32 | uint | Write-only | Writes a 32-bit unsigned integer |
Example:
// Set the target position (S-0-0012)
slave.SoE.WriteInt32(0x000C, 50000);
// Write the control word (S-0-0064)
slave.SoE.WriteUInt16(0x0040, 0x0006);
Metadata reads
ReadName(ushort idn, int timeoutMs = 500)
public string? ReadName(ushort idn, int timeoutMs = 500)
Reads the IDN parameter name (uses ElementFlag 0x02).
ReadUnit(ushort idn, int timeoutMs = 500)
public string? ReadUnit(ushort idn, int timeoutMs = 500)
Reads the IDN parameter unit (uses ElementFlag 0x08).
ReadMinValue / ReadMaxValue / ReadDefaultValue
public byte[]? ReadMinValue(ushort idn, int timeoutMs = 500)
public byte[]? ReadMaxValue(ushort idn, int timeoutMs = 500)
public byte[]? ReadDefaultValue(ushort idn, int timeoutMs = 500)
Reads the minimum (0x10), maximum (0x20) and default (0x80) value of an IDN parameter.
Example:
string? name = slave.SoE.ReadName(0x000B);
string? unit = slave.SoE.ReadUnit(0x000B);
byte[]? min = slave.SoE.ReadMinValue(0x000B);
byte[]? max = slave.SoE.ReadMaxValue(0x000B);
Console.WriteLine($"参数: {name} ({unit})"); // Parameter: {name} ({unit})
if (min != null && max != null)
Console.WriteLine($"范围: {BitConverter.ToInt32(min, 0)} - {BitConverter.ToInt32(max, 0)}"); // Range: {BitConverter.ToInt32(min, 0)} - {BitConverter.ToInt32(max, 0)}
Parameter information
GetAvailableIDNs(int timeoutMs = 5000)
public List<ushort> GetAvailableIDNs(int timeoutMs = 5000)
Gets the list of all IDNs supported by the slave. Throws SoEException when the read fails and does not return an empty list pretending success. An empty list means only that the slave reported 0 IDNs.
Return value:
List<ushort>— list of IDN numbers
GetParameterInfo(ushort idn, int timeoutMs = 5000)
public SoEParameter GetParameterInfo(ushort idn, int timeoutMs = 5000)
Gets the complete information of an IDN parameter (name, unit, attributes, current value, minimum / maximum value, and so on). Throws SoEException when the reads of all elements fail; it does not return an empty shell object.
Return value:
SoEParameter— contains the complete parameter information
Related structures:
public class SoEParameter
{
public ushort IDN { get; set; } // IDN number
public string Name { get; set; } // Parameter name
public string Unit { get; set; } // Unit
public SoEAttributes Attributes { get; set; } // Attributes (data type, length, etc.)
public byte[] Value { get; set; } // Current value
public byte[] DefaultValue { get; set; } // Default value
public byte[] MinValue { get; set; } // Minimum value
public byte[] MaxValue { get; set; } // Maximum value
public string SercosIDN { get; } // SERCOS IDN form (e.g. "S-0-0001", read-only derived)
public string Category { get; } // Category ("Standard" / "Product" / "Vendor", read-only derived)
public bool IsReadOnly { get; } // Whether the parameter is read-only (read-only derived)
public string AccessMode { get; } // Access mode ("RO" / "RW" / "RW*", read-only derived)
public string FormattedValue { get; } // Formatted current value (read-only derived)
public string FormattedDefaultValue { get; } // Formatted default value (read-only derived)
public string FormattedMinValue { get; } // Formatted minimum value (read-only derived)
public string FormattedMaxValue { get; } // Formatted maximum value (read-only derived)
}
public struct SoEAttributes
{
public ushort EvaluationFactor; // Evaluation factor
public byte Length; // Data length
public bool IsList; // Whether this is a list
public bool IsCommand; // Whether this is a command
public SoEDataType DataType; // Data type
public byte Decimals; // Number of decimal places
public bool WriteProtectedPreOp; // Write-protected in PreOp
public bool WriteProtectedSafeOp; // Write-protected in SafeOp
public bool WriteProtectedOp; // Write-protected in Op
}
public enum SoEDataType : byte
{
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 value
Parameter = 7 // Parameter
}
Example:
var param = slave.SoE.GetParameterInfo(0x000B);
Console.WriteLine($"IDN: {param.SercosIDN} - {param.Name}");
Console.WriteLine($"单位: {param.Unit}, 访问: {param.AccessMode}"); // Unit: {param.Unit}, access: {param.AccessMode}
Console.WriteLine($"当前值: {param.FormattedValue}"); // Current value: {param.FormattedValue}
Console.WriteLine($"范围: {param.FormattedMinValue} - {param.FormattedMaxValue}"); // Range: {param.FormattedMinValue} - {param.FormattedMaxValue}
AT/MDT mapping
SERCOS transfers cyclic data with AT (Acknowledge Telegram) and MDT (Master Data Telegram):
- 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 determines which IDN parameters are carried in the cyclic data frames.
GetIDNMapping(int timeoutMs = 5000)
public ServoMappingInfo GetIDNMapping(int timeoutMs = 5000)
Reads the current AT/MDT mapping configuration of the drive. Throws SoEException if the query fails.
Return value:
ServoMappingInfo— mapping information object
Related structures:
public class ServoMappingInfo
{
public List<ServoMappingEntry> ATMapping { get; set; } // AT (input) mapping list
public List<ServoMappingEntry> MDTMapping { get; set; } // MDT (output) mapping list
public int ATBitSize { get; set; } // Total AT bit count
public int MDTBitSize { get; set; } // Total MDT bit count
public int ATByteSize { get; } // Total AT byte count (read-only derived)
public int MDTByteSize { get; } // Total MDT byte count (read-only derived)
}
public class ServoMappingEntry
{
public ushort IDN { get; set; } // IDN number
public string Name { get; set; } // Parameter name
public int BitLength { get; set; } // Data length in bits
public int ByteLength { get; } // Data length in bytes (read-only derived)
}
GetAllDriveMappings(int timeoutMs = 5000)
public Dictionary<byte, ServoMappingInfo> GetAllDriveMappings(int timeoutMs = 5000)
Gets the mapping information of all drives (up to 8 drives are scanned).
Return value:
Dictionary<byte, ServoMappingInfo>— dictionary from drive number to mapping information
Procedure commands
ExecuteCommand(ushort idn, int timeoutMs = 5000, int pollIntervalMs = 50)
public bool ExecuteCommand(ushort idn, int timeoutMs = 5000, int pollIntervalMs = 50)
Executes an SoE procedure command (SERCOS Procedure Command). Writing bit0 of the DataState element (0x01) triggers the command, and the method then polls until it completes. Valid only for IDNs with IsCommand=true.
Parameters:
idn(ushort) — IDN number of the command to executetimeoutMs(int) — time to wait for the command to complete in milliseconds (default 5000)pollIntervalMs(int) — polling interval in milliseconds (default 50)
Return value:
bool—truewhen the command completes successfully,falseon timeout or failure
Example:
// Execute the homing command (S-0-0148)
bool success = slave.SoE.ExecuteCommand(0x0094);
if (success)
Console.WriteLine("回零完成"); // Homing complete
else
Console.WriteLine("回零超时或失败"); // Homing timed out or failed
// Custom timeout (long-running command)
bool ok = slave.SoE.ExecuteCommand(0x0094, timeoutMs: 30000, pollIntervalMs: 100);
ReadDataState(ushort idn, int timeoutMs = 500)
public ushort? ReadDataState(ushort idn, int timeoutMs = 500)
Reads the Data State element of an IDN (ElementFlag 0x01). Data State carries information such as the command state and data validity.
Parameters:
idn(ushort) — IDN numbertimeoutMs(int) — timeout in milliseconds (default 500)
Return value:
ushort?— 16-bit Data State value;nullon failure
Example:
// Read the Data State of the IDN
ushort? state = slave.SoE.ReadDataState(0x0094);
if (state != null)
{
bool commandActive = (state.Value & 0x01) != 0;
bool commandError = (state.Value & 0x02) != 0;
Console.WriteLine($"命令激活: {commandActive}, 命令错误: {commandError}"); // Command active: {commandActive}, command error: {commandError}
}
WaitForProcedureDone(ushort idn, int timeoutMs = 5000, int pollIntervalMs = 50)
public bool WaitForProcedureDone(ushort idn, int timeoutMs = 5000, int pollIntervalMs = 50)
Polls Data State until the procedure command completes (IEC 61800-7-204): bit0 = in progress (1 = still executing, 0 = complete), bit1 = error (returns false immediately when set), bit3 = interrupted (returns false when set). After triggering a command, ExecuteCommand waits for the same completion conditions; this method can also be used on its own for a command that is already running.
Async methods
Asynchronous wrappers around the synchronous API. Each method corresponds to the synchronous method of the same name (Read / Write / ReadInt16 ...) and has exactly the same return values and failure semantics; asynchrony only means that the call does not occupy the current thread, and cancellation is supported through CancellationToken.
public Task<byte[]?> ReadAsync(ushort idn, byte elementFlags = 0x40, int timeoutMs = 500, CancellationToken cancellationToken = default)
public Task<bool> WriteAsync(ushort idn, byte[] data, byte elementFlags = 0x40, int timeoutMs = 500, CancellationToken cancellationToken = default)
public Task<bool> ExecuteCommandAsync(ushort idn, int timeoutMs = 5000, int pollIntervalMs = 50, CancellationToken cancellationToken = default)
public Task<short?> ReadInt16Async(ushort idn, byte elementFlags = 0x40, int timeoutMs = 500, CancellationToken cancellationToken = default)
public Task<int?> ReadInt32Async(ushort idn, byte elementFlags = 0x40, int timeoutMs = 500, CancellationToken cancellationToken = default)
public Task<ushort?> ReadUInt16Async(ushort idn, byte elementFlags = 0x40, int timeoutMs = 500, CancellationToken cancellationToken = default)
public Task<uint?> ReadUInt32Async(ushort idn, byte elementFlags = 0x40, int timeoutMs = 500, CancellationToken cancellationToken = default)
public Task<bool> WriteInt16Async(ushort idn, short value, byte elementFlags = 0x40, int timeoutMs = 500, CancellationToken cancellationToken = default)
public Task<bool> WriteInt32Async(ushort idn, int value, byte elementFlags = 0x40, int timeoutMs = 500, CancellationToken cancellationToken = default)
public Task<bool> WriteUInt16Async(ushort idn, ushort value, byte elementFlags = 0x40, int timeoutMs = 500, CancellationToken cancellationToken = default)
public Task<bool> WriteUInt32Async(ushort idn, uint value, byte elementFlags = 0x40, int timeoutMs = 500, CancellationToken cancellationToken = default)
public Task<ushort?> ReadDataStateAsync(ushort idn, int timeoutMs = 500, CancellationToken cancellationToken = default)
public Task<List<ushort>> GetAvailableIDNsAsync(int timeoutMs = 5000, CancellationToken cancellationToken = default)
public Task<SoEParameter> GetParameterInfoAsync(ushort idn, int timeoutMs = 5000, CancellationToken cancellationToken = default)
public Task<byte[]?> ReadDefaultValueAsync(ushort idn, int timeoutMs = 500, CancellationToken cancellationToken = default)
public Task<string?> ReadNameAsync(ushort idn, int timeoutMs = 500, CancellationToken cancellationToken = default)
public Task<string?> ReadUnitAsync(ushort idn, int timeoutMs = 500, CancellationToken cancellationToken = default)
public Task<byte[]?> ReadMinValueAsync(ushort idn, int timeoutMs = 500, CancellationToken cancellationToken = default)
public Task<byte[]?> ReadMaxValueAsync(ushort idn, int timeoutMs = 500, CancellationToken cancellationToken = default)
public Task<string?> ReadStringAsync(ushort idn, byte elementFlags = 0x40, int timeoutMs = 500, CancellationToken cancellationToken = default)
public Task<float?> ReadFloatAsync(ushort idn, byte elementFlags = 0x40, int timeoutMs = 500, CancellationToken cancellationToken = default)
public Task<double?> ReadDoubleAsync(ushort idn, byte elementFlags = 0x40, int timeoutMs = 500, CancellationToken cancellationToken = default)
public Task<bool> EnableNotificationAsync(ushort idn, int timeoutMs = 500, CancellationToken cancellationToken = default)
public Task<int> PollNotificationsAsync(int timeoutMs = 200, CancellationToken cancellationToken = default)
- Cancellation affects only the caller: the
Taskcompletes withOperationCanceledException, the underlying synchronous call still runs to completion in the background, and its result is discarded and logged - A failed read returns
nulland a failed write returnsfalse, the same as the synchronous API; query failures fromGetAvailableIDNsAsync/GetParameterInfoAsyncsurface as aSoEExceptionthrown from theTask(the same as their synchronous versions) timeoutMs/pollIntervalMsare passed through unchanged to the corresponding synchronous method and mean the same thing
Example:
var soe = slave.SoE;
byte[]? status = await soe.ReadAsync(0x0047);
if (status != null && status.Length >= 2)
Console.WriteLine($"状态字: 0x{BitConverter.ToUInt16(status, 0):X4}"); // Status word: 0x{BitConverter.ToUInt16(status, 0):X4}
bool ok = await soe.WriteInt32Async(0x002F, 50000);
int changed = await soe.PollNotificationsAsync();
Parameter change notifications
SoE Notification monitors changes of IDN parameters on a SERCOS slave and notifies the application through the NotificationReceived event when a value changes. Notifications are delivered in one of two ways, transparent to the application layer, with the same event structure:
- Hardware notification: the SDK first tries to enable hardware notification on the slave side (writes the notification request S-0-0127, OpCode=5) and the slave pushes changes on its own
- Polling: when the slave does not support hardware notification the SDK falls back automatically, reading each monitored IDN and comparing it with the last recorded value, and raising the event when a change is found. This mode requires the application layer to call
PollNotifications()periodically; the latency of a change depends on the call frequency
NotificationReceived
public event Action<SoENotificationEventArgs>? NotificationReceived;
Fires when the value of a monitored IDN parameter changes. On the first notification OldValue may be null (the baseline has just been established and no previous value exists).
Related structures:
public class SoENotificationEventArgs : EventArgs
{
public ushort SlaveIndex { get; set; } // Slave index (1-based)
public byte DriveNumber { get; set; } // Drive number (used with multi-axis drives)
public ushort IDN { get; set; } // IDN number that changed
public SoEElementFlags ElementFlags { get; set; } // Element bitmask that triggered the notification
public byte[]? NewValue { get; set; } // Value after the change (null may mean the read failed)
public byte[]? OldValue { get; set; } // Value before the change (null on the first notification)
public string SercosIDN { get; } // SERCOS form, e.g. "S-0-0036" (read-only derived)
}
Example:
if (slave.SoE != null)
{
// Register the notification event
slave.SoE.NotificationReceived += (args) =>
{
Console.WriteLine($"参数变化: {args.SercosIDN} (IDN 0x{args.IDN:X4})"); // Parameter change: {args.SercosIDN} (IDN 0x{args.IDN:X4})
Console.WriteLine($" 旧值: {(args.OldValue != null ? BitConverter.ToString(args.OldValue) : "(首次)")}"); // old value: {(args.OldValue != null ? BitConverter.ToString(args.OldValue) : "(first)")}
Console.WriteLine($" 新值: {(args.NewValue != null ? BitConverter.ToString(args.NewValue) : "N/A")}"); // new value: {(args.NewValue != null ? BitConverter.ToString(args.NewValue) : "N/A")}
};
// Enable monitoring of the actual position (S-0-0011)
bool hwSupported = slave.SoE.EnableNotification(0x000B);
Console.WriteLine($"硬件通知: {(hwSupported ? "支持" : "回退到轮询")}"); // Hardware notification: {(hwSupported ? "supported" : "falling back to polling")}
// Enable monitoring of the drive status word (S-0-0071)
slave.SoE.EnableNotification(0x0047);
// Poll periodically from a timer
while (running)
{
int changed = slave.SoE.PollNotifications();
if (changed > 0)
Console.WriteLine($"检测到 {changed} 个参数变化"); // Detected {changed} parameter changes
Thread.Sleep(100);
}
// Stop monitoring
slave.SoE.DisableAllNotifications();
}
EnableNotification(ushort idn, int timeoutMs = 500)
public bool EnableNotification(ushort idn, int timeoutMs = 500)
Enables change notification for the given IDN. It first tries to enable hardware notification through S-0-0127 and adds the IDN to the polling list whether or not that succeeds.
Parameters:
idn(ushort) — IDN number to monitortimeoutMs(int) — timeout in milliseconds (default 500)
Return value:
bool—truemeans the slave confirmed hardware notification;falsemeans it fell back to polling mode
DisableNotification(ushort idn)
public void DisableNotification(ushort idn)
Disables change notification for the given IDN and removes it from the monitored list.
DisableAllNotifications()
public void DisableAllNotifications()
Disables all enabled notifications and clears the monitored list.
GetMonitoredIDNs()
public List<ushort> GetMonitoredIDNs()
Returns a snapshot of the IDNs currently being monitored (EnableNotification adds to it, DisableNotification / DisableAllNotifications remove from it). The returned value is a new copy of the list, so the caller can iterate it freely; the monitored list itself still changes as notifications are enabled and disabled.
Return value:
List<ushort>— the IDN numbers whose notification is enabled
PollNotifications(int timeoutMs = 200)
public int PollNotifications(int timeoutMs = 200)
Polls all monitored IDNs for parameter changes. Each current value is read and compared with the last recorded value, and the NotificationReceived event fires when a change is found. Suitable for periodic calls from a timer or a background thread.
Parameters:
timeoutMs(int) — timeout of each IDN read in milliseconds (default 200)
Return value:
int— number of IDNs whose value changed in this poll
Runtime asynchronous notifications (Notification / Emergency)
Besides the synchronous Read/Write API, SoE supports two kinds of notification that the slave pushes asynchronously; the SDK surfaces them as two events:
| Event | SERCOS OpCode | Purpose |
|---|---|---|
| NotificationReceived | 5 | IDN parameter value change notification (live-update monitoring) |
| EmergencyReceived | 6 | Drive Sercos Emergency (emergency stop / fault) |
Typical uses:
- Live servo parameter monitoring — after an HMI rewrites S-0-0036 Max Velocity, other monitoring endpoints receive the new value through Notification in real time
- Emergency stop monitoring — the drive pushes a hardware-level Emergency (overcurrent / overtemperature / encoder loss) and the application switches to its safe branch immediately
- Consistency across tuning endpoints — when several engineers tune parameters from different host applications, parameter changes can be broadcast to all listening endpoints
Subscribing to the events does not require the slave to be in OP; with the mailbox available in PreOp / SafeOp the events are received (consistent with mailbox availability). For the full event list see slave events.
EmergencyReceived
public event Action<SoEEmergencyEventArgs>? EmergencyReceived;
Fires when the drive pushes a Sercos Emergency (OpCode=6). Unlike the CoE EMCY message, the Sercos Emergency is specific to servo drives and its error codes follow the SERCOS definition (not CiA 301). Do not call blocking SDO/SoE reads or writes from inside the callback — requests pile up easily under a fault condition.
Related structures:
public class SoEEmergencyEventArgs : EventArgs
{
public ushort SlaveIndex { get; set; } // Source slave index (1-based)
public byte DriveNumber { get; set; } // Drive number (SoEHeader driveNo bit field, 3 bit)
public ushort ErrorCode { get; set; } // Sercos Emergency Error Code (2 bytes)
public DateTime Timestamp { get; set; } // Receive timestamp (UTC)
}
Threading contract
NotificationReceived / EmergencyReceived fire on the SDK callback thread, not on the UI thread. To update controls in a WinForms / WPF UI, switch back to the UI thread with Invoke / Dispatcher.Invoke:
// WinForms
slave.SoE.EmergencyReceived += (args) =>
{
if (mainForm.InvokeRequired)
mainForm.BeginInvoke(new Action(() => HandleEmergency(args)));
else
HandleEmergency(args);
};
Never block for long inside the callback (more than a few milliseconds), as that slows down SoE mailbox processing; move long-running work to Task.Run.
Example:
if (slave.SoE == null) return;
// 1. Subscribe to Notification (live parameter changes)
Action<SoENotificationEventArgs> onNotification = args =>
{
string newStr = args.NewValue != null ? BitConverter.ToString(args.NewValue) : "N/A";
string oldStr = args.OldValue != null ? BitConverter.ToString(args.OldValue) : "(首次)"; // (first)
Console.WriteLine(
$"[SoE Notify] 从站={args.SlaveIndex} 驱动器={args.DriveNumber} " + // [SoE Notify] slave={args.SlaveIndex} drive={args.DriveNumber}
$"{args.SercosIDN} (0x{args.IDN:X4}) Elements=0x{(byte)args.ElementFlags:X2} " +
$"旧=[{oldStr}] → 新=[{newStr}]"); // old=[{oldStr}] → new=[{newStr}]
};
// 2. Subscribe to Emergency (critical fault)
Action<SoEEmergencyEventArgs> onEmergency = args =>
{
Console.WriteLine(
$"[SoE EMCY] 从站={args.SlaveIndex} 驱动器={args.DriveNumber} " + // [SoE EMCY] slave={args.SlaveIndex} drive={args.DriveNumber}
$"ErrorCode=0x{args.ErrorCode:X4} @ {args.Timestamp:HH:mm:ss.fff}");
// Typical response: switch the UI to the fault branch and stop the motion axis
if (mainForm.InvokeRequired)
mainForm.BeginInvoke(new Action(() => mainForm.ShowEmergencyBanner(args.ErrorCode)));
};
slave.SoE.NotificationReceived += onNotification;
slave.SoE.EmergencyReceived += onEmergency;
// 3. Enable the IDNs to monitor (several are supported)
slave.SoE.EnableNotification(0x0024); // Max Velocity
slave.SoE.EnableNotification(0x0047); // Drive Status Word
// 4. Unsubscribe when the application exits to avoid dangling references
try
{
// ... application runs ...
}
finally
{
slave.SoE.DisableAllNotifications();
slave.SoE.NotificationReceived -= onNotification;
slave.SoE.EmergencyReceived -= onEmergency;
}
FSoE safety slave interface (slave.FSoE)
The members below live on slave.FSoE (FSoEInstance) and use the same safety frames and mailbox channel, so their entry points are listed here; for the safety protocol state machine, connection parameters and safety PDO semantics see FSoE.
| Category | Property | Type | Read/write | Description |
|---|---|---|---|---|
| Safety I/O | SafeInputFaulted | bool | Read-only | Whether the safety input refresh failed in the most recent PDO cycle. true = the read failed or threw; the instance still holds the stale data of the previous cycle, which must not be treated as newly acquired safety input |
| Safety I/O | SafeOutputFaulted | bool | Read-only | Whether the safety output commit failed in the most recent PDO cycle. true = the safety outputs were not written to the slave, and the upper layer must not treat them as issued |
| Safety I/O | SafeIoFaulted | bool | Read-only | Whether safety I/O is in a fault state (either the input refresh failed or the output commit failed). The safety application should apply its fail-safe logic for this cycle |
All three flags are maintained by the cycle pre-processing and post-processing and reset automatically after a successful refresh; no manual clearing is needed.
GetDeviceAddress(out ushort safetyAddress)
public bool GetDeviceAddress(out ushort safetyAddress)
Reads 0xF980:01 over SDO to obtain the safety address of the slave at call time. Every call actually sends a mailbox command, which is why this is a method rather than a property.
Parameters:
safetyAddress(out ushort) — safety address; 0 on failure
Return value:
bool— true = the read succeeded; false = the read failed or threw (the reason is logged)
GetModuleCommParam(ushort moduleNumber)
public byte[]? GetModuleCommParam(ushort moduleNumber)
Reads 0x9nn1 over SDO to get the communication parameters of an MDP module (nn is the module number); the value is read at call time and not cached.
Parameters:
moduleNumber(ushort) — module number
Return value:
byte[]?— the communication parameter bytes;nullwhen the read fails or the length is invalid (not an empty array)
GetModuleDiagnosis(ushort moduleNumber, out ushort connectionState, out ushort connectionDiagnosis)
public bool GetModuleDiagnosis(ushort moduleNumber, out ushort connectionState, out ushort connectionDiagnosis)
Reads 0xAnn0 over SDO to get the connection state and connection diagnosis of an MDP module.
Parameters:
moduleNumber(ushort) — module numberconnectionState(out ushort) — connection state; 0 on failureconnectionDiagnosis(out ushort) — connection diagnosis; 0 on failure
Return value:
bool— true = the read succeeded; false = the read failed or threw
FSoEPdoLayout.Create(int safeDataLength)
public static FSoEPdoLayout Create(int safeDataLength)
Builds the safety frame layout from the safety data length: the command byte offset, the safety data offset and length, the offset of each checksum segment, the Connection ID offset, and the trailing padding.
Parameters:
safeDataLength(int) — safety data length in bytes
Return value:
FSoEPdoLayout— frame layout instance;CrcSegmentCountis the number of checksum segments andTotalLengthis the total frame length
Related structures:
public sealed class FSoEPdoLayout
{
public int CommandOffset { get; set; } // Command byte offset
public int SafeDataOffset { get; set; } // Safety data start offset
public int SafeDataLength { get; set; } // Total length of the safety data (bytes)
public int PaddingBytes { get; set; } // Padding byte count of the last data segment
public int[] CrcOffsets { get; set; } // Offsets of each CRC section within the frame
public int ConnIdOffset { get; set; } // Connection ID offset
public int CrcSegmentCount { get; } // Number of CRC sections
public int TotalLength { get; } // Total frame length
}
Error handling
public SoEError? LastSoEError { get; } // Last SoE operation error code: null on success, the specific error code on failure
public MailboxStatus LastStatus { get; } // Unified status of the last mailbox transaction (Success / MailboxError, etc.)
public uint LastErrorCode { get; } // Same source as LastSoEError, presented as uint
Updated automatically after every Read / Write (including the typed reads and writes). A failed Read returns null and a failed Write returns false; LastSoEError then gives the specific reason (for example NoIDN = the IDN does not exist).
Queries such as GetAvailableIDNs / GetParameterInfo / GetIDNMapping throw SoEException when the query fails; they do not return an empty list / empty shell object pretending success:
public class SoEException : Exception { }
Related structures:
SoE operation error codes (SERCOS / ETG.1000.6 §5.11):
public enum SoEError : ushort
{
NoError = 0x0000,
NoIDN = 0x1001, // IDN does not exist
InvalidAccessToElement1 = 0x1009,
NoName = 0x2001,
NameTransmissionTooShort = 0x2002,
NameTransmissionTooLong = 0x2003,
NameCannotBeChanged = 0x2004,
NameWriteProtected = 0x2005,
AttributeTransmissionTooShort = 0x3002,
AttributeTransmissionTooLong = 0x3003,
AttributeCannotBeChanged = 0x3004,
AttributeWriteProtected = 0x3005,
NoUnits = 0x4001,
UnitTransmissionTooShort = 0x4002,
UnitTransmissionTooLong = 0x4003,
UnitCannotBeChanged = 0x4004,
UnitWriteProtected = 0x4005,
NoMinimumInputValue = 0x5001,
MinimumInputValueTransmissionTooShort = 0x5002,
MinimumInputValueTransmissionTooLong = 0x5003,
MinimumInputValueCannotBeChanged = 0x5004,
MinimumInputValueWriteProtected = 0x5005,
NoMaximumInputValue = 0x6001,
MaximumInputValueTransmissionTooShort = 0x6002,
MaximumInputValueTransmissionTooLong = 0x6003,
MaximumInputValueCannotBeChanged = 0x6004,
MaximumInputValueWriteProtected = 0x6005,
NoOperationData = 0x7001,
OperationDataTransmissionTooShort = 0x7002,
OperationDataTransmissionTooLong = 0x7003,
OperationDataCannotBeChanged = 0x7004,
OperationDataWriteProtectedByState = 0x7005,
OperationDataSmallerThanMinimum = 0x7006,
OperationDataGreaterThanMaximum = 0x7007,
InvalidOperationDataConfiguredIDNNotSupported = 0x7008,
OperationDataWriteProtectedByPassword = 0x7009,
OperationDataCyclicallyWriteProtected = 0x700A,
InvalidIndirectAddressing = 0x700B,
OperationDataWriteProtectedBySettings = 0x700C,
Reserved_700D = 0x700D,
ProcedureCommandAlreadyActive = 0x7010,
ProcedureCommandNotInterruptible = 0x7011,
ProcedureCommandNotExecutableState = 0x7012,
ProcedureCommandNotExecutableInvalidParameters = 0x7013,
NoDataState = 0x7014,
NoDefaultValue = 0x8001,
DefaultValueTransmissionTooLong = 0x8002,
DefaultValueTransmissionTooShort = 0x8003,
DefaultValueCannotBeChanged = 0x8004,
DefaultValueWriteProtected = 0x8005,
InvalidDriveNumber = 0x800A,
GeneralError = 0x800B,
NoElementAddressed = 0x800C,
Unknown = 0xFFFF
}
Example:
byte[]? data = slave.SoE.Read(0x000B);
if (data == null)
{
if (slave.SoE.LastSoEError == SoEError.NoIDN)
Console.WriteLine("IDN 不存在"); // IDN does not exist
else
Console.WriteLine($"SoE 读取失败: {slave.SoE.LastSoEError}"); // SoE read failed: {slave.SoE.LastSoEError}
}
IDN encoding helpers
The SDK provides a set of static helper methods that convert between a 16-bit IDN number and a (标准/厂商, 参数集, 数据块) triple or a SERCOS string. Bit layout: bit15 = 0 standard (S) / 1 vendor (P), bit14..12 = parameter set Set (0-7), bit11..0 = data block Block (0-4095).
| Category | Method | Return type | Read/write | Description |
|---|---|---|---|---|
| Encoding | EncodeIdn(bool isStandard, byte parameterSet, ushort dataBlock) | ushort | Read-only | Encodes a triple into a 16-bit IDN |
| Decoding | DecodeIdn(ushort idn) | (bool IsStandard, byte ParameterSet, ushort DataBlock) | Read-only | Decodes a 16-bit IDN into a triple |
| Parsing | TryParseSercosIdn(string text, out ushort idn) | bool | Read-only | Parses a SERCOS string (such as "S-0-0040" / "P-1-0123") into an IDN |
public static ushort EncodeIdn(bool isStandard, byte parameterSet, ushort dataBlock)
public static (bool IsStandard, byte ParameterSet, ushort DataBlock) DecodeIdn(ushort idn)
public static bool TryParseSercosIdn(string text, out ushort idn)
Example:
// Encode: standard IDN S-0-0040 (homing velocity)
ushort idn = DarraEtherCAT.Slave.SoEInstance.EncodeIdn(isStandard: true, parameterSet: 0, dataBlock: 40);
// Decode
var (isStd, set, block) = DarraEtherCAT.Slave.SoEInstance.DecodeIdn(idn);
Console.WriteLine($"标准={isStd}, 参数集={set}, 数据块={block}"); // standard={isStd}, parameter set={set}, data block={block}
// Parse from a string
if (DarraEtherCAT.Slave.SoEInstance.TryParseSercosIdn("S-0-0040", out ushort parsed))
{
byte[]? data = slave.SoE.Read(parsed);
}
These methods are pure bit arithmetic and do not access the slave, so they can be called without the slave being online.
Standard IDN constants
public static class StandardIDN
{
public const ushort IDNList = 0x0000; // IDN list (S-0-0000)
public const ushort CycleTime = 0x0001; // Communication cycle time (S-0-0001)
public const ushort SyncTime = 0x0002; // Synchronization timestamp T_scyc (S-0-0002)
public const ushort MdtToAtDelay = 0x0003; // MDT to AT interval T_mtsy (S-0-0003)
public const ushort ATConfig = 0x0010; // AT configuration - input mapping (S-0-0016)
public const ushort ProcedureCommandList = 0x0011;// List of Procedure Command IDNs (S-0-0017)
public const ushort MDTConfig = 0x0018; // MDT configuration - output mapping (S-0-0024)
public const ushort WritableIDNs = 0x0019; // Writable IDNs (S-0-0025)
public const ushort ConfigurationIDNs = 0x001A; // Configuration IDNs (S-0-0026)
public const ushort NotificationRequest = 0x007F; // Notification request (S-0-0127)
public const ushort PrimaryOperationMode = 0x0020;// Primary operation mode (S-0-0032)
public const ushort VelocityLoopKv = 0x002C; // Velocity loop proportional gain Kv (S-0-0044)
public const ushort PositionCommand = 0x002F; // Position command (S-0-0047)
public const ushort PositionFeedback = 0x0033; // Position feedback (S-0-0051)
public const ushort DiagnosticMessage = 0x005F; // Diagnostic message (S-0-0095)
public const ushort PositionLoopKv = 0x0064; // Position controller Kv (S-0-0100)
}
Full example
var slave = master.Slaves[0];
if (slave.SoE == null)
{
Console.WriteLine("该从站不支持 SoE"); // This slave does not support SoE
return;
}
// Read the communication cycle time (S-0-0001)
byte[]? cycleRaw = slave.SoE.Read(0x0001);
if (cycleRaw == null)
{
Console.WriteLine($"读取失败: {slave.SoE.LastSoEError}"); // Read failed: {slave.SoE.LastSoEError}
}
else
{
Console.WriteLine($"周期时间: {BitConverter.ToUInt32(cycleRaw, 0)} μs"); // Cycle time: {BitConverter.ToUInt32(cycleRaw, 0)} µs
}
// Write the target position (S-0-0047)
byte[] targetPosition = BitConverter.GetBytes(100000);
if (!slave.SoE.Write(0x002F, targetPosition))
{
Console.WriteLine($"写入失败: {slave.SoE.LastSoEError}"); // Write failed: {slave.SoE.LastSoEError}
}
// Read back the actual position (S-0-0051)
byte[]? actualRaw = slave.SoE.Read(0x0033);
if (actualRaw != null)
Console.WriteLine($"实际位置: {BitConverter.ToInt32(actualRaw, 0)}"); // Actual position: {BitConverter.ToInt32(actualRaw, 0)}
Parameter scan
if (slave.SoE != null)
{
var idns = slave.SoE.GetAvailableIDNs();
Console.WriteLine($"从站支持 {idns.Count} 个 IDN 参数\n"); // Slave supports {idns.Count} IDN parameters\n
foreach (var idn in idns.Take(10))
{
var info = slave.SoE.GetParameterInfo(idn);
Console.WriteLine($"{info.SercosIDN}: {info.Name} = {info.FormattedValue} {info.Unit} [{info.AccessMode}]");
}
}
Servo drive control
if (slave.SoE != null)
{
// 1. Read the drive status
ushort? statusWord = slave.SoE.ReadUInt16(0x0047);
Console.WriteLine($"状态字: 0x{statusWord:X4}"); // Status word: 0x{statusWord:X4}
// 2. Inspect the AT/MDT mapping (to learn the cyclic data layout)
var mapping = slave.SoE.GetIDNMapping();
Console.WriteLine($"\nAT 映射(输入 {mapping.ATByteSize} 字节):"); // \nAT mapping (input {mapping.ATByteSize} bytes):
foreach (var entry in mapping.ATMapping)
Console.WriteLine($" IDN 0x{entry.IDN:X4}: {entry.Name} ({entry.ByteLength}B)");
Console.WriteLine($"\nMDT 映射(输出 {mapping.MDTByteSize} 字节):"); // \nMDT mapping (output {mapping.MDTByteSize} bytes):
foreach (var entry in mapping.MDTMapping)
Console.WriteLine($" IDN 0x{entry.IDN:X4}: {entry.Name} ({entry.ByteLength}B)");
// 3. Write the control word to enable the drive (S-0-0064)
slave.SoE.WriteUInt16(0x0040, 0x0006);
// 4. Set the target position (S-0-0012)
slave.SoE.WriteInt32(0x000C, 50000);
// 5. Read the actual position (S-0-0011)
int? actualPos = slave.SoE.ReadInt32(0x000B);
Console.WriteLine($"\n实际位置: {actualPos} inc"); // \nActual position: {actualPos} inc
}
Failures and handling
| Symptom | Cause | Handling |
|---|---|---|
| Read returns null and the error code indicates a missing IDN | No IDN with that number exists on the slave | Use the IDN given in the device manual; first confirm whether the parameter belongs to the standard range or the vendor-defined range |
| Write returns false and the error code indicates write protection | The parameter is write-protected (by password, settings or access rights) | Confirm that the parameter can be written and, if needed, switch to an access level with write permission before writing |
| Read / Write fails and the error code indicates a timeout | The mailbox transaction timed out or the slave did not answer | Confirm that the slave mailbox is available and the state is normal, then retry; increase timeoutMs if the timeout persists |
| The operation is rejected and the error code indicates the state does not allow it | The parameter can only be written in a specific servo state | Wait until the servo reaches a state that allows this parameter, then write, avoiding the state transition window |