Skip to main content

SoE (Servo over EtherCAT)

The SoE protocol encapsulates the SERCOS servo communication protocol in the EtherCAT mailbox; it applies to SERCOS-compatible servo drives.

Accessed through slave.soe (the instance is created lazily and an object is always returned). Whether the slave supports SoE is judged with slave.soe.is_supported. That property produces only two conclusions: True supported / None unknown (no positive evidence or the read failed) — the SoE details in SII are reserved bytes, so this chain never produces False.​

SoE vs CoE

Most EtherCAT servo drives use the CoE + CiA 402 protocol 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.

Properties​

CategoryPropertyTypeRead/writeDescription
Capabilityis_supportedOptional[bool]read-onlyWhether the slave SII declares the SoE mailbox protocol (mbx_proto bit 4). Only produces True (positive evidence) / None (unknown); this chain does not produce False
Diagnosticslast_soe_errorOptional[SoEError]read-onlyMost recent SoE error code. In the current Python layer it is initialized to None; a read/write failure does not fill it in

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:

PrefixRangeDescription
S-x-xxxx0x0000 - 0x7FFFSERCOS standard parameters (common to all vendors)
P-x-xxxx0x8000 - 0xBFFFProduct-specific parameters
P-x-xxxx0xC000 - 0xFFFFVendor-defined parameters

Common standard IDNs (servo control):

IDNSERCOS nameDescriptionData type
S-0-0001 (0x0001)Cycle TimeCommunication cycle timeuint, us
S-0-0011 (0x000B)Class 1 DiagnosticsClass 1 diagnostic code (not a position value)uint16
S-0-0012 (0x000C)Class 2 DiagnosticsClass 2 diagnostic code (not a position value)uint16
S-0-0013 (0x000D)Velocity FeedbackActual velocityint, rpm
S-0-0014 (0x000E)Velocity CommandTarget velocityint, rpm
S-0-0016 (0x0010)AT ConfigInput mapping configuration listlist
S-0-0019 (0x0013)Drive StatusDrive status wordint
S-0-0024 (0x0018)MDT ConfigOutput mapping configuration listlist
S-0-0036 (0x0024)Max VelocityMaximum velocity limituint, rpm
S-0-0040 (0x0028)Homing VelocityHoming velocityuint, rpm
S-0-0047 (0x002F)Position CommandTarget positionint, inc
S-0-0051 (0x0033)Position Feedback 1Actual positionint, inc
S-0-0064 (0x0040)Drive Control WordDrive control wordint
S-0-0071 (0x0047)Drive Status WordDrive status wordint
S-0-0148 (0x0094)Homing CommandHoming procedure commandcommand

Element flags — reading different "layers" of an IDN:

FlagMeaning
0x01Data state
0x02Parameter name (string)
0x04Attribute (data type / length / permission bit field)
0x08Unit (string)
0x10Minimum value
0x20Maximum value
0x40Data value (default, most commonly used)
0x80Default value

SoEElementFlags bit flags​

SoEElementFlags is the 7-bit element bitmask (IntFlag) of the SoEHeader per ETG.1000.6 §5.11; multiple bits can be OR-combined to read / write several layers in one call.

from darra_ethercat.slave.soe import SoEElementFlags
FlagValueMeaning
NONE0x00None
DATA_STATUS0x01Data status word (valid/invalid/busy)
NAME0x02IDN name (string)
ATTRIBUTE0x04Attribute (type / length / decimal places, and so on)
UNIT0x08Unit string
MIN0x10Minimum value
MAX0x20Maximum value
VALUE0x40Operating data value (default, most commonly used)
DEFAULT0x80Default value

Example:

from darra_ethercat.slave.soe import SoEElementFlags

# read Name + Unit + Value in one call
flags = SoEElementFlags.NAME | SoEElementFlags.UNIT | SoEElementFlags.VALUE
data = slave.soe.read(0x0033, int(flags))

Constants with the same values are also attached to the SoE class: SoE.DATA=0x40 / SoE.NAME=0x02 / SoE.ATTRIBUTE=0x04 / SoE.UNIT=0x08 / SoE.MIN=0x10 / SoE.MAX=0x20 (also available on slave.soe).

SERCOS IDN encoding / decoding​

Module-level functions implemented with ETG.1020 standard bit arithmetic; they do not touch the bus and do not depend on a device connection:

encode_idn()​

def encode_idn(is_standard: bool, parameter_set: int, data_block: int) -> int

Encodes the (is_standard, set, block) triple into a 16-bit IDN.

  • is_standard=True → bit15=0 (S standard parameter)
  • is_standard=False → bit15=1 (P vendor parameter)
  • parameter_set takes 0..7 → bit14..12
  • data_block takes 0..0xFFF → bit11..0

Example:

from darra_ethercat.slave.soe import encode_idn

# S-0-0040 (Homing Velocity)
idn = encode_idn(True, 0, 40) # -> 0x0028

# P-1-0291 (data_block is an integer, 0x123 = decimal 291)
idn = encode_idn(False, 1, 0x123) # -> 0x9123

decode_idn()​

def decode_idn(idn: int) -> Tuple[bool, int, int]

Splits a 16-bit IDN back into the (is_standard, parameter_set, data_block) triple.

Example:

from darra_ethercat.slave.soe import decode_idn

is_std, set_no, block = decode_idn(0x8000)
# is_std=False, set_no=0, block=0 (that is, P-0-0000)

try_parse_sercos_idn()​

def try_parse_sercos_idn(text: str) -> Optional[int]

Parses a SERCOS standard string ("S-0-0040" / "P-1-0123") into a 16-bit IDN; returns None on failure.

Example:

from darra_ethercat.slave.soe import try_parse_sercos_idn

idn = try_parse_sercos_idn("S-0-0040") # -> 0x0028
idn = try_parse_sercos_idn("invalid") # -> None

format_sercos_idn()​

def format_sercos_idn(idn: int) -> str

Formats a 16-bit IDN as an "S-x-xxxx" / "P-x-xxxx" string.

Example:

from darra_ethercat.slave.soe import format_sercos_idn

text = format_sercos_idn(0x0028) # -> "S-0-0040"
text = format_sercos_idn(0x9123) # -> "P-1-0291"

Basic read and write​

read()​

def read(self, idn: int, element_flags: int = 0x40) -> Optional[bytes]

Reads the raw bytes of an IDN parameter. Uses the timeout set at construction time (default 5000ms).

Example:

import struct

# read the communication cycle time (S-0-0001)
data = slave.soe.read(0x0001, 0x40)
if data is not None:
cycle_time = struct.unpack('<I', data)[0]
print(f"周期时间: {cycle_time} us") # Cycle time: {cycle_time} us

write()​

def write(self, idn: int, data: bytes, element_flags: int = 0x40) -> bool

Writes an IDN parameter. Uses the timeout set at construction time (default 5000ms).

Example:

import struct

# set the target position (S-0-0047)
position = struct.pack('<i', 100000)
success = slave.soe.write(0x002F, position)

SoEError enum​

SoE error codes (SERCOS standard). SoEError provides a describe() method to get a Chinese description.

from darra_ethercat.data.types import SoEError
NameValueDescription
NO_ERROR0x0000No error
NO_IDN0x1001No IDN
INVALID_ACCESS_TO_ELEMENT10x1009Invalid access to element 1
NO_NAME0x2001No name
NAME_TRANSMISSION_TOO_SHORT0x2002Name transmission too short
NAME_TRANSMISSION_TOO_LONG0x2003Name transmission too long
NAME_CANNOT_BE_CHANGED0x2004Name cannot be changed
NAME_WRITE_PROTECTED0x2005Name write-protected
ATTRIBUTE_TRANSMISSION_TOO_SHORT0x3002Attribute transmission too short
ATTRIBUTE_TRANSMISSION_TOO_LONG0x3003Attribute transmission too long
ATTRIBUTE_CANNOT_BE_CHANGED0x3004Attribute cannot be changed
ATTRIBUTE_WRITE_PROTECTED0x3005Attribute write-protected
NO_UNITS0x4001No units
UNIT_TRANSMISSION_TOO_SHORT0x4002Unit transmission too short
UNIT_TRANSMISSION_TOO_LONG0x4003Unit transmission too long
UNIT_CANNOT_BE_CHANGED0x4004Unit cannot be changed
UNIT_WRITE_PROTECTED0x4005Unit write-protected
NO_MINIMUM_INPUT_VALUE0x5001No minimum input value
MINIMUM_INPUT_VALUE_TRANSMISSION_TOO_SHORT0x5002Minimum input value transmission too short
MINIMUM_INPUT_VALUE_TRANSMISSION_TOO_LONG0x5003Minimum input value transmission too long
MINIMUM_INPUT_VALUE_CANNOT_BE_CHANGED0x5004Minimum input value cannot be changed
MINIMUM_INPUT_VALUE_WRITE_PROTECTED0x5005Minimum input value write-protected
NO_MAXIMUM_INPUT_VALUE0x6001No maximum input value
MAXIMUM_INPUT_VALUE_TRANSMISSION_TOO_SHORT0x6002Maximum input value transmission too short
MAXIMUM_INPUT_VALUE_TRANSMISSION_TOO_LONG0x6003Maximum input value transmission too long
MAXIMUM_INPUT_VALUE_CANNOT_BE_CHANGED0x6004Maximum input value cannot be changed
MAXIMUM_INPUT_VALUE_WRITE_PROTECTED0x6005Maximum input value write-protected
NO_OPERATION_DATA0x7001No operation data
OPERATION_DATA_TRANSMISSION_TOO_SHORT0x7002Operation data transmission too short
OPERATION_DATA_TRANSMISSION_TOO_LONG0x7003Operation data transmission too long
OPERATION_DATA_CANNOT_BE_CHANGED0x7004Operation data cannot be changed
OPERATION_DATA_WRITE_PROTECTED_BY_STATE0x7005Operation data write-protected by state
OPERATION_DATA_SMALLER_THAN_MINIMUM0x7006Operation data smaller than minimum
OPERATION_DATA_GREATER_THAN_MAXIMUM0x7007Operation data greater than maximum
INVALID_OPERATION_DATA_CONFIG_IDN_NOT_SUPPORTED0x7008Invalid operation data (configured IDN not supported)
OPERATION_DATA_WRITE_PROTECTED_BY_PASSWORD0x7009Operation data write-protected by password
OPERATION_DATA_CYCLICALLY_WRITE_PROTECTED0x700AOperation data cyclically write-protected
INVALID_INDIRECT_ADDRESSING0x700BInvalid indirect addressing
OPERATION_DATA_WRITE_PROTECTED_BY_SETTINGS0x700COperation data write-protected by settings
RESERVED0x700DReserved
PROCEDURE_COMMAND_ALREADY_ACTIVE0x7010Procedure command already active
PROCEDURE_COMMAND_NOT_INTERRUPTIBLE0x7011Procedure command not interruptible
PROCEDURE_COMMAND_NOT_EXECUTABLE_STATE0x7012Procedure command not executable (wrong state)
PROCEDURE_COMMAND_NOT_EXECUTABLE_INVALID_PARAMETERS0x7013Procedure command not executable (invalid parameters)
NO_DATA_STATE0x7014No data state
NO_DEFAULT_VALUE0x8001No default value
DEFAULT_VALUE_TRANSMISSION_TOO_LONG0x8002Default value transmission too long
DEFAULT_VALUE_TRANSMISSION_TOO_SHORT0x8003Default value transmission too short
DEFAULT_VALUE_CANNOT_BE_CHANGED0x8004Default value cannot be changed
DEFAULT_VALUE_WRITE_PROTECTED0x8005Default value write-protected
INVALID_DRIVE_NUMBER0x800AInvalid drive number
GENERAL_ERROR0x800BGeneral error
NO_ELEMENT_ADDRESSED0x800CNo element addressed
UNKNOWN0xFFFFUnknown error

Example:

from darra_ethercat.data.types import SoEError

err = slave.soe.last_soe_error
if err is not None and err != SoEError.NO_ERROR:
print(f"SoE 错误: {err.name} (0x{err.value:04X}) - {err.describe()}") # SoE error: {err.name} (0x{err.value:04X}) - {err.describe()}

Typed read​

All method signatures are the same: read_xxx(idn, element_flags=0x40)

CategoryMethodTypeRead/writeDescription
Typed readread_int16Optional[int]read-onlyReads a 16-bit signed integer
read_int32Optional[int]read-onlyReads a 32-bit signed integer
read_uint16Optional[int]read-onlyReads a 16-bit unsigned integer
read_uint32Optional[int]read-onlyReads a 32-bit unsigned integer
read_floatOptional[float]read-onlyReads a single-precision floating-point number
read_doubleOptional[float]read-onlyReads a double-precision floating-point number
read_stringOptional[str]read-onlyReads a string

Example:

# read the actual position (S-0-0051)
actual_pos = slave.soe.read_int32(0x0033)

# read the drive status word (S-0-0071)
status = slave.soe.read_uint16(0x0047)

# read the parameter name
name = slave.soe.read_string(0x0033, element_flags=0x02)

Typed write​

All method signatures are the same: write_xxx(idn, value, element_flags=0x40), returning bool.

CategoryMethodTypeRead/writeDescription
Typed writewrite_int16intwrite-onlyWrites a 16-bit signed integer
write_int32intwrite-onlyWrites a 32-bit signed integer
write_uint16intwrite-onlyWrites a 16-bit unsigned integer
write_uint32intwrite-onlyWrites a 32-bit unsigned integer

Example:

# set the target position (S-0-0047)
slave.soe.write_int32(0x002F, 50000)

# write the control word (S-0-0064)
slave.soe.write_uint16(0x0040, 0x0006)

slave.soe is itself a SoEAdvanced instance (a subclass of SoE), so the wider typed series read_i8 / read_i16 / read_i32 / read_i64 / read_u8 / read_u16 / read_u32 / read_u64 / read_f32 / read_f64 and the corresponding write_* methods are directly available, plus read_string(idn, element_flags=0x40, timeout_ms=500, encoding='utf-8') / write_string(idn, value, element_flags=0x40, timeout_ms=500, encoding='utf-8'); all unpack in a fixed little-endian format. read_i* / read_u* / read_f* and the corresponding write_* have no element_flags parameter. write_int16 / write_int32 / write_uint16 / write_uint32 / write_float / write_double take (idn, value, element_flags=0x40, timeout_ms=500) (aligned with C#; element_flags is actually passed through), so the simple call write_int16(idn, value) is unchanged. SoEAdvanced does not need to be, and cannot be, constructed manually (construction requires an internal runtime library object). There are also asyncio variants read_async / write_async / execute_command_async / poll_notifications_async / get_parameter_info_async and so on, with the same semantics as the synchronous versions.

write_typed_async()​

async def write_typed_async(self, idn: int, value: Any, fmt: str,
timeout_ms: Optional[int] = None) -> bool

Packs the value with a struct format string and writes it to the IDN; this is the asynchronous variant of write(): the blocking mailbox round trip runs on the SoE-dedicated thread pool and does not occupy the event loop. Only an await differs from the synchronous form; the packed bytes and element bits are exactly the same.

Parameters:

  • idn (int) — IDN number
  • value (Any) — value to write; its type must match fmt
  • fmt (str) — struct format string, such as '<i' (32-bit signed), '<H' (16-bit unsigned), '<f' (single precision); the < prefix means little-endian, matching the byte order of SERCOS data; without a prefix the value is packed with the running machine's byte order and alignment
  • timeout_ms (int, optional) — upper bound for the await wait in milliseconds; the default None means no limit, and 0 also means no limit

Returns:

  • bool — True the write succeeded; False the slave rejected the write or the mailbox failed
Three easily overlooked constraints
  • The Value element (0x40) is always written; this method takes no element parameter. To write elements such as Name / Attribute / Default, use the synchronous write()
  • timeout_ms only cuts the await short; the background thread still finishes this read/write (the thread cannot be interrupted). After a timeout, do not resend immediately on the same IDN
  • A mismatch between fmt and value raises struct.error; that is a caller parameter error, not a False return

Example:

import asyncio

async def main():
# target position (S-0-0047), 32-bit signed little-endian
ok = await slave.soe.write_typed_async(0x002F, 50000, '<i')
print("写入成功" if ok else "写入失败") # Write succeeded / write failed

asyncio.run(main())

The read direction is served by read_typed_async(idn, fmt, timeout_ms=None), with the same format string syntax.

Metadata read​

def read_name(self, idn: int) -> Optional[str]
def read_unit(self, idn: int) -> Optional[str]
def read_attributes(self, idn: int) -> Optional[int]
def read_min_value(self, idn: int) -> Optional[bytes]
def read_max_value(self, idn: int) -> Optional[bytes]
def read_default_value(self, idn: int) -> Optional[bytes]
def read_min_max(self, idn: int) -> Optional[Tuple[bytes, bytes]]

read_attributes() returns the raw attribute bit field (int); decode it into decode_soe_attributes() with the module-level SoEAttributes:

from darra_ethercat.slave.soe import decode_soe_attributes

raw = slave.soe.read_attributes(0x000B)
if raw is not None:
attrs = decode_soe_attributes(raw)
print(f"类型: {attrs.data_type.name}, 访问: {attrs.access_mode}") # Type: {attrs.data_type.name}, access: {attrs.access_mode}

Example:

name = slave.soe.read_name(0x000B)
unit = slave.soe.read_unit(0x000B)
min_val = slave.soe.read_min_value(0x000B)
max_val = slave.soe.read_max_value(0x000B)

print(f"参数: {name} ({unit})") # Parameter: {name} ({unit})
if min_val and max_val:
print(f"范围: {struct.unpack('<i', min_val)[0]} - {struct.unpack('<i', max_val)[0]}") # Range: {struct.unpack('<i', min_val)[0]} - {struct.unpack('<i', max_val)[0]}

Parameter information​

get_available_idns()​

def get_available_idns(self) -> List[int]

Gets the list of all IDNs supported by the slave.

read_idn_list()​

def read_idn_list(self) -> Optional[List[int]]

Reads the IDN list declared by the slave (S-0-0000), that is, every parameter number supported by this axis. get_available_idns() is a wrapper around this method: when the read fails it returns an empty list rather than None.

Returns:

  • List[int] — list of IDN numbers (raw 16-bit numbers, not formatted)
  • None — the read failed, the slave has no IDN list, or the list is empty
This discovers parameters; it does not read parameter values

The list gives numbers only; read the name / unit / current value one by one with get_parameter_info(). Display a number in the "S-0-0040" form with format_sercos_idn().

Example:

from darra_ethercat.slave.soe import format_sercos_idn

idns = slave.soe.read_idn_list()
if idns is None:
print("从站未返回 IDN 列表") # The slave returned no IDN list
else:
for idn in idns[:10]:
print(f"0x{idn:04X} {format_sercos_idn(idn)}")

get_parameter_info()​

def get_parameter_info(self, idn: int, timeout_ms: int = 5000) -> SoEParameter

Gets the complete information of an IDN parameter (name, unit, attributes, current value, minimum/maximum value, default value) and returns a SoEParameter rich object (with sercos_idn / category). If any item fails to read, the corresponding field is left empty; no exception is thrown.

SoEParameter class (returned only by SoEAdvanced.get_parameter_info):

class SoEParameter:
idn: int # IDN number
name: str # parameter name
unit: str # unit
attributes: SoEAttributes # attributes (data type, length, etc.)
value: bytes # current value
default_value: bytes # default value
min_value: bytes # minimum value
max_value: bytes # maximum value

@property
def sercos_idn(self) -> str # SERCOS IDN format (for example "S-0-0001")
@property
def category(self) -> str # category ("Standard" / "Product" / "Vendor")

Read-only and access permissions live on attributes (param.attributes.is_read_only / param.attributes.access_mode); to format a value by data type use format_byte_array():

from darra_ethercat.slave.soe import format_byte_array

print(format_byte_array(param.value, param.attributes))

SoEAttributes structure:

class SoEAttributes:
evaluation_factor: int # evaluation factor
length: int # length code (2-bit raw value from attribute bits 16-17, 0..3, not a byte count)
is_list: bool # whether it is a list
is_command: bool # whether it is a command
data_type: SoEDataType # data type
decimals: int # number of decimal places
write_protected_preop: bool # write-protected in PreOp state
write_protected_safeop: bool # write-protected in SafeOp state
write_protected_op: bool # write-protected in Op state

@property
def is_read_only(self) -> bool # read-only when write-protected in all three states
@property
def access_mode(self) -> str # "RO" / "RW" / "RW*"

SoEDataType enum:

class SoEDataType(IntEnum):
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
Parameter = 7 # parameter

Example:

from darra_ethercat.slave.soe import format_byte_array

param = slave.soe.get_parameter_info(0x0033)
print(f"IDN: {param.sercos_idn} - {param.name}")
print(f"单位: {param.unit}, 访问: {param.attributes.access_mode}") # Unit: {param.unit}, access: {param.attributes.access_mode}
print(f"当前值: {format_byte_array(param.value, param.attributes)}") # Current value: {format_byte_array(param.value, param.attributes)}
print(f"范围: {format_byte_array(param.min_value, param.attributes)} - {format_byte_array(param.max_value, param.attributes)}") # Range: {format_byte_array(param.min_value, param.attributes)} - {format_byte_array(param.max_value, param.attributes)}

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, and so on)
  • MDT = cyclic outputs from master to slave (target position, target velocity, control word, and so on)

The mapping configuration determines which IDN parameters are included in the cyclic data frame.

get_idn_mapping()​

def get_idn_mapping(self, timeout_ms: int = 5000) -> ServoMappingInfo

Reads the current drive AT/MDT mapping configuration.

Returns:

  • ServoMappingInfo — mapping information object

ServoMappingInfo class:

class ServoMappingInfo:
at_mapping: List[ServoMappingEntry] # AT (input) mapping list
mdt_mapping: List[ServoMappingEntry] # MDT (output) mapping list
at_bit_size: int # total AT bit count
mdt_bit_size: int # total MDT bit count

@property
def at_byte_size(self) -> int # total AT byte count (bit count rounded up to bytes)
@property
def mdt_byte_size(self) -> int # total MDT byte count

ServoMappingEntry class:

class ServoMappingEntry:
idn: int # IDN number
name: str # parameter name
bit_length: int # data length (bits)

@property
def byte_length(self) -> int # data length (bytes, derived from bit_length)

get_all_drive_mappings()​

def get_all_drive_mappings(self, timeout_ms: int = 5000) -> Dict[int, ServoMappingInfo]

Reads mappings one drive number at a time for drive numbers 0..7 (each drive number is read through a separate session). Only drives whose mapping was really read are returned: drives that failed to read / did not respond / have no mapping are absent; no empty mapping is fabricated.

Returns:

  • Dict[int, ServoMappingInfo] — dictionary from drive number to mapping information
Mapping queries are available directly on slave.soe

The AT/MDT mapping queries are methods of slave.soe itself; use them only when the IDN cyclic data layout needs to be scanned. Ordinary IDN read/write / procedure commands go through read / write / execute_command.

mapping = slave.soe.get_idn_mapping()
print(f"AT 映射(输入 {mapping.at_byte_size} 字节):") # AT mapping (input {mapping.at_byte_size} bytes):
for entry in mapping.at_mapping:
print(f" IDN 0x{entry.idn:04X}: {entry.name} ({entry.byte_length}B)")

print(f"MDT 映射(输出 {mapping.mdt_byte_size} 字节):") # MDT mapping (output {mapping.mdt_byte_size} bytes):
for entry in mapping.mdt_mapping:
print(f" IDN 0x{entry.idn:04X}: {entry.name} ({entry.byte_length}B)")

Procedure commands​

execute_command()​

def execute_command(self, idn: int, timeout_ms: int = 5000, poll_interval_ms: int = 50) -> bool

Executes an SoE procedure command (SERCOS Procedure Command).

Example:

# execute the homing command (S-0-0148)
success = slave.soe.execute_command(0x0094)
if success:
print("回零完成") # Homing complete

# custom timeout (long-running command)
ok = slave.soe.execute_command(0x0094, timeout_ms=30000, poll_interval_ms=100)

read_data_state()​

def read_data_state(self, idn: int) -> Optional[int]

Reads the Data State element of an IDN (ElementFlag 0x01). Data State contains the command status, data validity and other information.

Parameters:

  • idn (int) — IDN number

Returns:

  • int | None — Data State value (uint16), None on failure

Example:

# read the Data State of the IDN
state = slave.soe.read_data_state(0x0094)
if state is not None:
command_active = (state & 0x01) != 0
command_error = (state & 0x02) != 0
print(f"命令激活: {command_active}, 命令错误: {command_error}") # command active: {command_active}, command error: {command_error}

Parameter change notifications​

The SoE Notification feature monitors changes of IDN parameters on a SERCOS slave. When a parameter value changes, the application is notified through a callback.

Implementation mechanism:

  1. Hardware notification: attempt to enable hardware notification on the slave by writing S-0-0127 (notification request IDN)
  2. Polling detection: if the slave does not support hardware notification, fall back to polling mode automatically
Notification API on slave.soe

slave.soe (a SoEAdvanced instance) provides the complete notification surface: instance-level polling (enable_notification / poll_notifications) and callback registration (on_notification) are all on the same object.

enable_notification()​

def enable_notification(self, idn: int, timeout_ms: int = 500) -> bool

Enables parameter change notification for the specified IDN. It first tries to enable hardware notification through S-0-0127; regardless of success, the IDN is added to the polling monitor list (and the current value is recorded as the baseline).

Returns:

  • bool — True means the slave confirmed hardware notification support; False means it fell back to polling mode

disable_notification()​

def disable_notification(self, idn: int)

Disables parameter change notification for the specified IDN.

disable_all_notifications()​

def disable_all_notifications(self)

Disables all enabled notifications and clears the monitor list.

poll_notifications()​

def poll_notifications(self, timeout_ms: int = 200) -> int

Polls all monitored IDNs for parameter changes (the read timeout for each IDN is timeout_ms). When a change is found, the baseline is updated and the callbacks registered through on_notification() are fired for each change.

Returns:

  • int — number of IDNs whose change was detected in this poll

on_notification()​

def on_notification(self, callback: Callable[[SoENotificationEventArgs], None]) -> None

Registers a change callback. Multiple callbacks can be registered; an exception thrown by one callback does not affect the others.

remove_notification()​

def remove_notification(self, callback: Callable[[SoENotificationEventArgs], None]) -> None

Unregisters a change callback registered with on_notification(); use it in pairs with registration. A callback that was never registered is silently ignored and no exception is thrown; registering the same callback several times keeps a single copy, so one unregister call removes them all.

Parameters:

  • callback — the callback to remove; it must be the same callable object that was registered
Stops the callback only, not the monitoring

This method does not change the monitor list: IDNs already enabled with enable_notification() keep being polled by poll_notifications(), they simply stop firing callbacks. To stop the monitoring as well, use disable_notification() / disable_all_notifications().

Example:

def on_change(ev):
print(f"IDN 0x{ev.idn:04X} 变化") # IDN 0x{ev.idn:04X} changed

slave.soe.on_notification(on_change)

# Unregister when it is no longer needed
slave.soe.remove_notification(on_change)

get_monitored_idns() / monitored_idns()​

def get_monitored_idns(self) -> List[int]
def monitored_idns(self) -> List[int] # same-name method, called with parentheses

Both entry points return the same monitored IDN list.

SoENotificationEventArgs​

class SoENotificationEventArgs:
slave_index: int # slave index
drive_number: int # drive number
idn: int # changed IDN number
element_flags: int # Element flag (0x40=Value / 0x02=Name ...)
new_value: Optional[bytes] # new value
old_value: Optional[bytes] # old value

@property
def sercos_idn(self) -> str # formatted SERCOS IDN name (for example "S-0-0127")

Example:

if slave.soe.is_supported:
# enable monitoring of the actual position (S-0-0051)
slave.soe.enable_notification(0x0033)

# enable monitoring of the drive status word (S-0-0071)
slave.soe.enable_notification(0x0047)

# the callback receives SoENotificationEventArgs
def on_change(ev):
print(f"参数变化: IDN 0x{ev.idn:04X}") # Parameter change: IDN 0x{ev.idn:04X}
if ev.old_value is not None:
print(f" 旧值: {ev.old_value.hex()}") # Old value: {ev.old_value.hex()}
if ev.new_value is not None:
print(f" 新值: {ev.new_value.hex()}") # New value: {ev.new_value.hex()}

slave.soe.on_notification(on_change)
changed = slave.soe.poll_notifications()
if changed > 0:
print(f"检测到 {changed} 个参数变化") # Detected {changed} parameter changes

# show the monitored IDN
print(f"监控列表: {slave.soe.get_monitored_idns()}") # Monitoring list: {slave.soe.get_monitored_idns()}

# stop monitoring
slave.soe.disable_all_notifications()

Global Notification / Emergency dispatcher​

In addition to the instance-level polling notifications and slave.soe callback of on_notification() described above, the SDK also provides a global single-instance dispatcher that listens to SoE Notification (OpCode=5) and SoE Emergency (OpCode=6) events from all slaves in one place.

The dispatcher fires synchronously in the mailbox receive thread; multiple Python callbacks run in registration order.

Use cases
  • Global logging: one callback records parameter changes of all SoE slaves in one place
  • Emergency alarm system: report in one place when a SERCOS drive sends a fatal error frame (OpCode=6)
  • Multi-slave scenarios: avoid registering a callback repeatedly for each slave.soe instance

SoENotificationEventArgs​

The global dispatcher reuses the same SoENotificationEventArgs type from "Parameter change notifications"; it is filled as follows when dispatched:

class SoENotificationEventArgs:
slave_index: int # slave index (the real value in the callback)
drive_number: int # drive number (multi-axis devices)
idn: int # IDN number
element_flags: int # Element flag (0x40=Value / 0x02=Name / 0x04=Attribute ...)
new_value: Optional[bytes] # new value (buffered copy during the callback)
old_value: Optional[bytes] # always None on the global path (old-value tracking is provided only by SoEAdvanced.poll_notifications)

@property
def sercos_idn(self) -> str # "S-0-0127" format

SoEEmergencyEventArgs​

SERCOS Emergency frame (OpCode=6) arguments: a fatal error pushed asynchronously by the slave:

class SoEEmergencyEventArgs:
slave_index: int # slave index
drive_number: int # drive number
error_code: int # Sercos Emergency Error Code (uint16)
timestamp: datetime # receive time (UTC)

Register / remove callbacks​

from darra_ethercat.slave.soe import (
add_soe_notification_callback,
remove_soe_notification_callback,
add_soe_emergency_callback,
remove_soe_emergency_callback,
)

def add_soe_notification_callback(
callback: Callable[[SoENotificationEventArgs], None]
) -> None

def remove_soe_notification_callback(
callback: Callable[[SoENotificationEventArgs], None]
) -> None

def add_soe_emergency_callback(
callback: Callable[[SoEEmergencyEventArgs], None]
) -> None

def remove_soe_emergency_callback(
callback: Callable[[SoEEmergencyEventArgs], None]
) -> None

Example — global Notification listener:

from darra_ethercat.slave.soe import add_soe_notification_callback

def on_notif(e):
print(f"Slave {e.slave_index} "
f"IDN {e.sercos_idn} (0x{e.idn:04X}) "
f"element=0x{e.element_flags:02X} 变化") # element=0x{e.element_flags:02X} changed
if e.new_value:
print(f" new = {e.new_value.hex()}")

add_soe_notification_callback(on_notif)

Example — Emergency alarm:

from darra_ethercat.slave.soe import add_soe_emergency_callback

def on_emcy(e):
print(f"[EMCY] Slave {e.slave_index} drive={e.drive_number} "
f"error=0x{e.error_code:04X} at {e.timestamp:%H:%M:%S.%f}")

add_soe_emergency_callback(on_emcy)

add_notification_callback()​

from darra_ethercat.slave.soe import add_notification_callback

def add_notification_callback(
callback: Callable[[SoENotificationEventArgs], None]) -> None

An alias of add_soe_notification_callback(); it registers into the same global Notification listener list, so mixing the two names does not dispatch twice. It is also attached to SoE as a static method, so slave.soe.add_notification_callback(cb) is equivalent to the module-level call.

Parameters:

  • callback — callback function fn(SoENotificationEventArgs); registering the same function repeatedly keeps a single copy

Raises:

  • Raised when the underlying callback registration fails. A listener is recorded only when registration really succeeded, so "recorded but never notified" cannot happen

Example:

from darra_ethercat.slave.soe import add_notification_callback

def on_notif(e):
print(f"Slave {e.slave_index} IDN {e.sercos_idn} 变化") # Slave {e.slave_index} IDN {e.sercos_idn} changed

add_notification_callback(on_notif)

SoE.remove_notification_callback()​

@staticmethod
def remove_notification_callback(
callback: Callable[[SoENotificationEventArgs], None]) -> None

An alias of remove_soe_notification_callback(); it removes the callback from the global Notification list. A callback that was never registered is silently ignored and no exception is thrown.

The entry points are SoE.remove_notification_callback() or slave.soe.remove_notification_callback(); there is no function of that name at module level — from darra_ethercat.slave.soe import remove_notification_callback raises ImportError, so use remove_soe_notification_callback() for module-level removal.

Parameters:

  • callback — the callback to remove; it must be the same callable object that was registered

Example:

from darra_ethercat.slave.soe import remove_soe_notification_callback

def on_notif(e):
print(f"Slave {e.slave_index} IDN {e.sercos_idn} 变化") # Slave {e.slave_index} IDN {e.sercos_idn} changed

# Removal at module level; equivalent to slave.soe.remove_notification_callback(on_notif)
remove_soe_notification_callback(on_notif)
Callback threading model

Python callbacks execute synchronously in the mailbox receive thread:

  1. Do not block for long — return quickly, otherwise subsequent SoE mailboxes are processed with delay
  2. Accessing Tk / WinForms / Qt controls requires cross-thread dispatch — use queue.Queue or the framework's after/invoke to hop to the main thread
  3. Exceptions are swallowed by the SDK — make sure the callback catches exceptions and logs them itself
import queue

ui_queue: queue.Queue = queue.Queue()

def on_emcy(e):
try:
ui_queue.put_nowait(("emcy", e))
except queue.Full:
pass # UI is slow, drop it

Standard reference: IEC 61800-7-204 (SERCOS over EtherCAT) §Service Channel Communication.

Standard IDN constants​

The constants class is nested inside SoEAdvanced and accessed through slave.soe.StandardIDN:

class SoEAdvanced:
class StandardIDN:
IDN_LIST = 0x0000 # IDN list (S-0-0000)
CYCLE_TIME = 0x0001 # communication cycle time (S-0-0001)
AT_CONFIG = 0x0010 # AT configuration - input mapping (S-0-0016)
MDT_CONFIG = 0x0018 # MDT configuration - output mapping (S-0-0024)
NOTIFICATION_REQUEST = 0x007F # notification request (S-0-0127)
cycle = slave.soe.read_uint32(slave.soe.StandardIDN.CYCLE_TIME)

ServoDriveManager bulk parameter management​

ServoDriveManager (darra_ethercat.slave.soe) reads and writes parameters in bulk over a standard IDN subset. Pass slave.soe as soe_instance at construction to perform the actual read/write; when no instance is provided, read_parameter only returns a parameter object with default names, and write_parameter raises RuntimeError. The class constant ServoDriveManager.STANDARD_IDNS is the built-in standard IDN subset.

from darra_ethercat.slave.soe import ServoDriveManager

mgr = ServoDriveManager(master.master_index, slave.slave_num,
drive_number=0, soe_instance=slave.soe)

params = mgr.read_all_parameters() # iterate STANDARD_IDNS, skipping items that fail to read
param = mgr.read_parameter(0x0033) # -> SoEParameter
ok = mgr.write_parameter(0x002F, struct.pack('<i', 50000))
CategoryMethodTypeRead/writeDescription
Bulk readread_all_parametersList[SoEParameter]read-onlyIterates the STANDARD_IDNS standard subset, skipping items that fail to read
Parameter readread_parameterSoEParameterread-onlyReads the metadata and current value of a single IDN (when no instance is provided, only default names are filled in)
get_parameter_infoSoEParameterread-onlyAlias of read_parameter
Parameter writewrite_parameterboolwrite-onlyRaises ValueError when value is empty; raises RuntimeError when soe_instance is not provided

Complete examples​

Parameter scan​

if slave.soe.is_supported:
idns = slave.soe.get_available_idns()
print(f"从站支持 {len(idns)} 个 IDN 参数\n") # The slave supports {len(idns)} IDN parameters\n

for idn in idns[:10]:
# get_parameter_info returns SoEParameter
info = slave.soe.get_parameter_info(idn)
print(f"IDN 0x{info.idn:04X}: {info.name} ({info.unit})")

Servo drive control​

if slave.soe.is_supported:
# 1. read the drive status
status_word = slave.soe.read_uint16(0x0047)
print(f"状态字: 0x{status_word:04X}") # Status word: 0x{status_word:04X}

# 2. view the AT/MDT mapping (to understand the cyclic data layout)
mapping = slave.soe.get_idn_mapping()

print(f"\nAT 映射(输入 {mapping.at_byte_size} 字节):") # \nAT mapping (input {mapping.at_byte_size} bytes):
for entry in mapping.at_mapping:
print(f" IDN 0x{entry.idn:04X}: {entry.name} ({entry.byte_length}B)")

print(f"\nMDT 映射(输出 {mapping.mdt_byte_size} 字节):") # \nMDT mapping (output {mapping.mdt_byte_size} bytes):
for entry in mapping.mdt_mapping:
print(f" IDN 0x{entry.idn:04X}: {entry.name} ({entry.byte_length}B)")

# 3. write the control word to enable the drive (S-0-0064)
slave.soe.write_uint16(0x0040, 0x0006)

# 4. set the target position (S-0-0047)
slave.soe.write_int32(0x002F, 50000)

# 5. read the actual position (S-0-0051)
actual_pos = slave.soe.read_int32(0x0033)
print(f"\n实际位置: {actual_pos} inc") # \nActual position: {actual_pos} inc

Failures and handling​

SymptomCauseHandling
read returns NoneThe IDN does not exist, or this axis does not support this parameterConfirm the IDN with read_name first, then use the parameter number from the servo manual
write returns False (parameter read-only or write-protected)The parameter is read-only, or protected by a password or settingsSwitch to a writable parameter; to unlock, remove write protection according to the servo manual
Read/write fails after a long period without responseMailbox communication timeout (default 5 seconds)Confirm the slave is reachable and retry; do not perform long blocking read/write inside a cycle callback
write returns False (not allowed by the current servo state)The current servo state does not allow changing this parameterStop the drive or switch to the parameter configuration state first, then write
execute_command returns FalseThe command reports an error (Data State bit1), or it timed out before completionCheck the command state with read_data_state; retry with a longer timeout_ms, or confirm the command preconditions in the servo manual
enable_notification returns FalseThe slave does not support hardware notificationIt has already fallen back to local polling; keep using poll_notifications as usual

shutdown_soe_async_executor()​

from darra_ethercat.slave.soe import shutdown_soe_async_executor

def shutdown_soe_async_executor(wait: bool = True) -> None

Shuts down the SoE asynchronous thread pool. read_async / write_async / read_typed_async / write_typed_async / get_parameter_info_async / execute_command_async / poll_notifications_async share this thread pool; it is created lazily on the first asynchronous method call, and this function releases it before the program exits.

Parameters:

  • wait (bool) — True (the default) waits for asynchronous reads and writes already submitted to finish before shutting down; False returns immediately and unfinished tasks are not guaranteed to finish
Lifecycle

Idempotent; repeated calls have no side effects. Calling an asynchronous method after shutdown lazily creates a new thread pool, so this function is only for cleanup before exit; it is not a switch that disables asynchronous operation.

Example:

import asyncio
from darra_ethercat.slave.soe import shutdown_soe_async_executor

async def main():
position = await slave.soe.read_typed_async(0x0033, '<i')
print(f"实际位置: {position}") # Actual position: {position}

try:
asyncio.run(main())
finally:
shutdown_soe_async_executor()