Slave properties and methods
Accessed through master[n] or master.slave(n) (1-based index).
Properties
| Category | Property | Type | Read/write | Description |
|---|---|---|---|---|
| Basic identification | slave_num | int | read-only | Slave index (1-based) |
| name | str | read-only | Slave group name (group_name, the ESI GroupType name) | |
| drive_name | str | read-only | Device name (the ESI device name when ESI matching succeeds, otherwise the SII EEPROM name) | |
| Device information | vendor_id | int | read-only | Manufacturer ID (read from the SII EEPROM) |
| vendor_name | str | read-only | Manufacturer name. The current version always returns an empty string (the read interface always writes empty), so it cannot be used to determine the vendor name | |
| product_id | int | read-only | Product ID | |
| rev_id | int | read-only | Revision number | |
| serial_number | int | read-only | Serial number (native runtime identity snapshot); 0 has three meanings — not read / real value 0 / read failed; use slave.try_get_serial_number() for the real value (see SII identity area and true serial number) | |
| has_mdp | bool | read-only | Whether the modular device profile is supported (ETG.5001) | |
| block_lrw | bool | read-only | LRW logical read/write blocking flag | |
| device_emulation | bool | read-only | Whether this is a Device Emulation device | |
| device_emulation_flag | bool | read-only | Alias of device_emulation (the same test) | |
| Address | config_addr | int | read-only | Physical configuration address |
| alias_address | int | read-only | Alias address | |
| Status | state | EcState | read-only | The slave's basic state (the low 4 bits of AL Status); it drops the Error bit: 0x14/0x18 are shown as SAFE_OP/OP. To judge errors use has_error / state_raw / status |
| state_raw | int | read-only | Raw byte 0-255 of AL Status (0x0130), with bit4 (Error) preserved; a read failure returns the 0 sentinel | |
| state_live_read | LiveRead | read-only | Live state read (forces one real read) plus four-state trust; value is the raw AL Status byte (low 4 bits = base state, bit4 = Error), usable as the current state only when is_valid. Use state / state_raw for the cached view | |
| state_live | Optional[EcState] | read-only | Convenience entry point for state_live_read: gives a value only when VALID, otherwise None. None = there is no trustworthy current state, which is not the same thing as EcState.NONE (value 0) | |
| state_raw_live | Optional[int] | read-only | Raw live state byte 0-255 (including the bit4 Error bit); None when untrusted | |
| has_error | bool | read-only | state_raw & 0x10: whether the slave is currently in an error state | |
| status | EcState | read-only | Full state view (same semantics as C# (EcState)raw): 0x14/0x18 are both representable; base_state takes the low 4 bits, format() produces SafeOp+Error / OP+Error | |
| error_code | EcALState | read-only | Error code (real read: the full 16-bit ALstatuscode in the slave structure; reads the polled cache while in OP and refreshes with one live frame otherwise; not the mirror high byte of diagnostics.al_status_mirror.al_status_code; al_status_code is an alias of it; codes outside the table return an instance carrying the original code, not folded to UNKNOWN) | |
| al_status_code_raw | int | read-only | Lossless raw AL Status Code 0-65535; a read failure returns 0xFFFF (the EcALState.UNKNOWN sentinel) | |
| al_status_code_live_read | LiveRead | read-only | Live AL Status Code (lossless 16-bit) plus four-state trust. When the slave is lost / not responding native returns 0; this entry point judges it STALE; 0 is not "no error" | |
| al_status_code_live | Optional[EcALState] | read-only | Gives a value only when VALID, otherwise None (not NO_ERROR); out-of-table codes are returned carrying the raw code | |
| al_status_code_raw_live | Optional[int] | read-only | Live AL code lossless raw value 0-65535; None when untrusted (never returns 0 to pass as "no error") | |
| is_lost | Optional[bool] | read-only | Whether the slave has been judged lost (three states: True = judged lost / False = not judged lost / None = read failure; None does not mean online) | |
| liveness | SlaveLivenessState | read-only | Liveness three-state: ALIVE = confirmed alive / LOST = confirmed offline / UNKNOWN = insufficient evidence. is_lost only answers "is it confirmed lost"; use this property to tell "insufficient evidence" | |
| offline_reason | SlaveOfflineReason | read-only | Offline reason classification: RealOffline = truly offline / Unreachable = not confirmed by the server — the server/probe did not see it, but the process data proves it is still contributing (not a confirmed offline) / Unknown = insufficient evidence | |
| has_entered_operational | bool | read-only | Whether it has ever successfully entered OP during this run (event-latched; falls back to the current-cycle state when the event surface is not ready) | |
| dropped_from_operational | bool | read-only | Whether it "entered OP but is not in OP now" (dropped out of OP at runtime) | |
| out_of_op_duration_ms | Optional[int] | read-only | Monotonic duration the slave has continuously been out of OP (ms); None = no provable start of the out-of-OP period. System clock changes do not affect this value | |
| out_of_op_duration | Optional[datetime.timedelta] | read-only | How long it has continuously been out of OP; None has the same meaning as above | |
| out_of_op_since_utc | Optional[datetime] | read-only | Start of the out-of-OP period (UTC, derived from "current UTC - monotonic duration"); None has the same meaning as above | |
| input_data_validity | PdoInputValidity | read-only | Four-state validity of the input process data: VALID = this cycle's data is valid; DEGRADED = this cycle has no full evidence (the group's inputs are incomplete for this cycle; on a single dropped frame / WKC=0 the data is the previous valid frame (last-good); when some slaves are missing, the input bytes of the absent slave and everything downstream may be the process-image initial values established at startup, do not treat it as definitely trustworthy); STALE = cannot be used as the current value; UNKNOWN = no evidence. Use this property to decide "can this frame of data be used"; use is_lost to decide "has the slave been confirmed offline" | |
| needs_reconfig | bool | read-only | Whether startup parameters and configuration need to be replayed after hot-plug | |
| Topology | link_count | int | read-only | Measured link count for the current sample: 1..4 = measured number of connections, -1 = unknown or invalid argument (a 0 placeholder from an unread DLSTAT also counts as unknown); unknown does not mean offline |
| topology_type | Optional[int] | read-only | Configuration-time topology structure classification snapshot: 0 = NoLink / 1 = EndPoint / 2 = Line / 3 = Fork / 4 = Cross; None = unavailable (None ≠ 0, 0 is a valid "no link"); unplugging a cable does not change it, and it is not a per-sample measurement | |
| parent_index | int | read-only | Parent slave index (1-based), 0 = the parent node is the master; a read failure or an invalid index returns 0xFFFF | |
| parent_station | int | read-only | Parent slave index (1-based; the name is historical, it is actually an index, not a station address; 0 = the parent node is the master, a read failure or an invalid index returns 0xFFFF) | |
| parent_port | int | read-only | Parent port number: 0..3, -1 = unknown or invalid argument; unknown does not mean P0 | |
| p1_foldback_only | int | read-only | P1 fold-back reachability: 1 = reachable only through the fold-back window, 0 = not a branch slave or not calibrated, -1 = unavailable (invalid master / slave index or read failure) | |
| entry_port | int | read-only | Entry port number | |
| active_ports | int | read-only | Active port bitmask | |
| physical_type | int | read-only | Physical port type | |
| child_count | int | read-only | Number of child modules | |
| PDO data | ibits / obits | int | read-only | Input/output data bit count |
| ibytes / obytes | int | read-only | Input/output data byte count | |
| ioffset / ooffset | int | read-only | Input/output offset in the process image | |
| istartbit / ostartbit | int | read-only | Input/output start bit | |
| ESI/configuration | has_esi | bool | read-only | Whether slave identity information was read. The current version only checks vendor_id != 0; it does not mean an ESI file was actually loaded and parsed |
| esi_version | str | read-only | ESI version. The current version always returns an empty string (the SII EEPROM cannot provide this field directly) | |
| EEPROM | eep_8byte_addressing | bool | read-only | EEPROM addressing mode (True = 8-byte, False = 4-byte) |
| eep_pdi | int | read-only | Physical device interface (PDI) type | |
| ebus_current | int | read-only | E-bus current consumption (mA) | |
| Mailbox | mbx_proto | int | read-only | Supported mailbox protocol bitmask (ECT_MBXPROT_*: AoE=0x01, EoE=0x02, CoE=0x04, FoE=0x08, SoE=0x10, VoE=0x20) |
| mbx_length | int | read-only | Mailbox send buffer size | |
| mbx_read_length | int | read-only | Mailbox receive buffer size | |
| mbx_read_offset / mbx_write_offset | int | read-only | Mailbox read/write offset | |
| mbx_count | int | read-only | Mailbox protocol counter | |
| Protocol details | coe_details | int | read-only | CoE protocol feature flags (EcCoEDetails bitmask) |
| eoe_details | int | read-only | EoE protocol feature flags (EcEoEDetails bitmask) | |
| foe_details | int | read-only | FoE protocol details (from the SII EEPROM) | |
| soe_details | int | read-only | SoE protocol details (from the SII EEPROM) | |
| FMMU | fmmu0_function | int | read-only | FMMU0 function type: 0 = unused, 1 = output, 2 = input, 3 = SM status (taken from the Function byte of the SII FMMU section; it is a type code, not a bitmask) |
| fmmu1_function | int | read-only | FMMU1 function type | |
| fmmu2_function | int | read-only | FMMU2 function type | |
| fmmu3_function | int | read-only | FMMU3 function type | |
| DC | has_dc | Optional[bool] | read-only | Whether DC is supported: True / False is an ESC hardware bit conclusion; a read failure returns None (unknown) |
| dc_active | int | read-only | Committed 0x0980 AssignActivate value (0 = not enabled, non-0 = DC-active). Non-0 does not mean armed or synchronized: check sync0_armed for arming and sync_window.in_sync for synchronization | |
| dc_cycle0 | int | read-only | SYNC0 cycle (ns) | |
| dc_cycle1 | int | read-only | SYNC1 cycle (ns) | |
| dc_shift | int | read-only | Phase shift (ns) | |
| dc_next | int | read-only | Index of the next slave in the DC chain | |
| dc_previous | int | read-only | Index of the previous slave in the DC chain | |
| dc_receive_time_a | int | read-only | Port A receive time (ns) | |
| dc_receive_time_b | int | read-only | Port B receive time (ns) | |
| dc_receive_time_c | int | read-only | Port C receive time (ns) | |
| dc_receive_time_d | int | read-only | Port D receive time (ns) | |
| propagation_delay | int | read-only | Propagation delay of the frame from the master to this slave (ns) | |
| pdelay | int | read-only | Propagation delay (ns), an alias of propagation_delay | |
| Topology extensions | children | List[Slave] | read-only | List of child slaves (used with child_count to navigate the topology tree) |
| supports_frame_repeat | bool | read/write | Whether frame repeat is supported (ETG.1500 5.4.3) | |
| Redundancy | redundancy_activated | bool | read-only | Redundancy activated (master ring mode is DUAL or DEGRADED) = the same master-level criterion master.redundancy_ring_mode >= RingMode.DUAL; always False for linear / end fold-back topologies, not an independent per-slave conclusion |
| primary_link_broken | bool | read-only | Whether the primary link is broken | |
| secondary_link_broken | bool | read-only | Whether the redundant link is broken | |
| Runtime diagnostics | emcy_count | int | read-only | Number of EMCY emergency messages |
| emcy_history | List[EmergencyMessage] | read-only | EMCY history (up to the most recent 256 entries, in chronological order oldest → newest; each entry is a read-only EmergencyMessage snapshot accessed through properties) | |
| link_quality | int | read-only | Link quality (0-100%, -1 = unknown) | |
| sync_window_status | dict | None | read-only | Sync window status (keys diff_ns / max_diff_ns / min_diff_ns / in_sync / out_of_sync_count); a read failure returns None | |
| Configuration | group | int | read/write | Slave group number (0-7; 0 = unassigned, automatically placed in group 1 before mapping; 1-7 are valid PDO groups; must be set before SAFE_OP) |
| is_optional | bool | read/write | Optional slave flag: when absent it does not affect the WKC check and does not raise a group offline alarm (must be set before OP) | |
| op_only | bool | read-only | Whether the OpOnly flag is set | |
| op_only_flag | bool | read-only | Alias of op_only (the same test) | |
| esm_timeouts | Optional[SlaveEsmTimeouts] | read/write | ESM state transition timeout configuration (ms); None on a read failure, throws RuntimeError on a write failure |
EcTopologyType / EcPortType enumeration values
class EcTopologyType(IntEnum):
NO_LINK = 0 # No link
END_POINT = 1 # Endpoint
LINE = 2 # Intermediate node (linear topology)
FORK = 3 # Fork point
CROSS = 4 # Cross point
class EcPortType(IntEnum):
NOT_USED = 0 # Not used
MII = 1 # MII
EBUS = 2 # EBUS
EBUS_ENHANCED = 3 # EBUS enhanced
MailboxType constants
Type codes in the mailbox header (not the mbx_proto bitmask; mbx_proto uses the ECT_MBXPROT_* bits).
class MailboxType(IntEnum):
ERROR_MAILBOX = 0x00 # Error mailbox
ADS_OVER_ETHERCAT = 0x01 # AoE
ETHERNET_OVER_ETHERCAT = 0x02 # EoE
CANOPEN_OVER_ETHERCAT = 0x03 # CoE
FILE_OVER_ETHERCAT = 0x04 # FoE
SERVO_OVER_ETHERCAT = 0x05 # SoE
VENDOR_OVER_ETHERCAT = 0x0F # VoE
EcCoEDetails constants
class EcCoEDetails(IntFlag):
NONE = 0x00
SDO = 0x01 # SDO supported
SDO_INFO = 0x02 # SDO Info supported
PDO_ASSIGN = 0x04 # PDO Assign supported
PDO_CONFIG = 0x08 # PDO Config supported
STARTUP = 0x10 # Startup supported
COMPLETE_ACCESS = 0x20 # Complete Access supported
EcEoEDetails constants
class EcEoEDetails(IntFlag):
NONE = 0x00
SEND_FRAME = 0x01 # Frame sending supported
RECEIVE_FRAME = 0x02 # Frame receiving supported
SET_IP_PARAM = 0x04 # Setting IP parameters supported
GET_IP_PARAM = 0x08 # Getting IP parameters supported
SlaveEsmTimeouts fields
ESM state transition timeout configuration; every entry is in milliseconds.
| Field | Type | Description |
|---|---|---|
| ip | int | Init → PreOp |
| ps | int | PreOp → SafeOp |
| so | int | SafeOp → OP |
| os | int | OP → SafeOp |
| sp | int | SafeOp → PreOp |
| pi | int | PreOp → Init |
| bi | int | Any state → Boot |
| ib | int | Boot → Init |
The identity tuple (vendor / product / revision / serial) is returned as a dict by the main SDK and cannot be hashed or unpacked. Wrapping it in the SlaveIdentityKey frozen dataclass makes it usable as a dict key / set element plus tuple unpacking. It is provided by the syntax-sugar subpackage, and you must first import darra_ethercat.sugar in your code (or from darra_ethercat.sugar import SlaveIdentityKey): vendor, product, rev, serial = SlaveIdentityKey.from_slave(slave).
Sub-objects
| Category | Property | Type | Read/write | Description |
|---|---|---|---|---|
| Data and events | pdo | SlavePdo | read-only | PDO data accessor |
| events | SlaveEvents | read-only | Slave-level events | |
| diagnostics | SlaveDiagnostics | read-only | Diagnostics accessor | |
| startup | StartupParameterList | read-only | Startup parameter list | |
| Protocol instances | coe | CoE | read-only | CANopen over EtherCAT (created lazily; use coe.is_supported to determine support) |
| soe | SoE | read-only | Servo over EtherCAT (created lazily; check support with soe.is_supported) | |
| foe | FoE | read-only | File over EtherCAT (created lazily; check support with foe.is_supported) | |
| eoe | EoE | read-only | Ethernet over EtherCAT (created lazily; check support with eoe.is_supported) | |
| aoe | AoE | read-only | ADS over EtherCAT (created lazily; check support with aoe.is_supported) | |
| voe | VoE | read-only | Vendor over EtherCAT (created lazily; check support with voe.is_supported) | |
| fsoe | FSoE | read-only | Functional Safety over EtherCAT (created lazily; check support with fsoe.is_supported) | |
| cia402 | CiA402 | read-only | CiA 402 drive (created lazily) | |
| cia401 | CiA401 | read-only | CiA 401 I/O module (created lazily) | |
| mdp | MdpDiscovery | None | read-only | MDP modular device; None when the slave does not support MDP | |
| dc_config | DcConfig | read-only | DC synchronization configuration and diagnostics |
is_supported returns Optional[bool], but not every protocol ever returns False:
coe/eoe/foe:True= supported,False= confirmed unsupported by a real SII read,None= unknown.aoe/voe/soe/fsoe: this chain only producesTrue/None(None= no positive evidence or a read failure; it is not folded into "confirmed unsupported").
On slave.eoe (the base EoE) it is a property; on EoEAdvanced it is a method that takes an explicit mailbox protocol bit field, and it also returns tri-state (EoEAdvanced currently has no public entry point that returns an instance, see EoE). Do not use if x.is_supported: to treat "unknown" as "unsupported" or "supported"; when you need to distinguish, test with is True / is False / is None separately.
Enum descriptions
How to get an enum description depends on the enum:
EcState: use.namefor the symbolic name (such as"OP") and.format()for a readable string (such as"SafeOp+Error").EcALState/SDOError/EcPortType/EcTopologyTypeand so on: use.describe()for the Chinese description.ModeCiA402/StateCiA402/RedundancyState: use.descriptionfor the Chinese description.
state = slave.state
desc = state.name # "OP"
# CiA402 is accessed through slave.cia402 (created lazily, always returns an instance)
cia = master[1].cia402
state = cia.state_drive # Drive state (StateCiA402)
Hardware information queries
FMMU / SyncManager reads and configuration are performed item by item:
- FMMU function type: the
fmmu0_functiontofmmu3_functionproperties (0 = unused, 1 = output, 2 = input, 3 = SM status) - FMMU mapping write:
configure_fmmu(fmmu_index, logical_addr, length, logical_start_bit=0, logical_end_bit=7, physical_addr=0, physical_start_bit=0, fmmu_type=0, enable=True)— returnsbool - SyncManager configuration:
configure_sync_manager(sm_index, start_addr, length, sm_type=0, enable=True)—sm_typeis 0 = unused / 1 = mailbox output / 2 = mailbox input / 3 = process data output / 4 = process data input; returnsbool - Output SM enable/disable:
enable_output_sync_manager()/disable_output_sync_manager()— returnbool - Type constants:
darra_ethercat.data.types/EcFmmuTypeinEcSyncManagerType
There is no bulk array query member on the Python side (no interface exists that returns all FMMU / SyncManager configuration or type arrays at once; calling one raises AttributeError). For register-level detail of each SM, read it directly with read_register, or walk the SII categories through slave.sii.
Diagnostics
Slave diagnostics (communication error rate, redundancy state, DC synchronization) are accessed through slave.diagnostics.
PdoInputValidity — input data validity
slave.input_data_validity answers "can this frame of input data be used as the current value", which is a different fact from "has the slave been confirmed offline" (slave.is_lost).
| Value | What you see | Recommended use |
|---|---|---|
VALID | This cycle's PDO exchange was complete; the input image is the current value | Use normally |
DEGRADED | This cycle has no full evidence: the group's inputs are incomplete for this cycle. On a single dropped frame / WKC=0 the data is the previous valid frame (last-good); when some slaves are missing, the input bytes of the absent slave and everything downstream may be the process-image initial values established at startup, not the last valid value | Do not treat this as "the data is definitely trustworthy": either wait for recovery, or cross-check is_lost / offline_reason / input_data_validity to see which slaves are untrustworthy. It turns STALE only after N full cycles without recovery (N is computed from the group cycle and the slave watchdog) |
STALE | The input image cannot be used as the current value (WKC short / no frame this cycle / slave lost / exchange stalled) | Do not use as a live value; take the safe fallback |
UNKNOWN | No evidence (no input PDO / group expectation not established / never exchanged / read failed) | Unknown is not valid; treat it as unavailable |
A read failure / out-of-range index / an older runtime without this capability returns UNKNOWN (fail-closed).
Note: the native-side comment still says "three-state / degradation pending", which is stale text awaiting sync in the native domain; the public SDK contract is the four states in this section.
diagnostics.stale_input_countcounts only slaves confirmedSTALE; it does not count whileDEGRADEDapplies.
Diagnostics mirror (thin read)
The per-slave diagnostics properties live on slave.diagnostics (Python convention: use properties, not get_xxx() methods), and most of them are thin reads of the per-slave diagnostics cache: each access reads the live state directly, sends and receives no frames (zero frames), performs no second-level caching, and what you read is the bus reality at that moment, with no manual refresh needed. The exception is al_status_mirror: it is a cache sampled while the master is in OP, not the live truth at read time (see below). When communication fails they honestly return UNKNOWN / raw=0 instead of making something up.
diagnostics.wc_contributed(WcContribution) — this slave's contribution state to the working counter (WKC) in the current cyclediagnostics.al_status_mirror(SlaveAlStatusMirror) — AL status mirror (contains al_state / has_error / al_status_code;al_status_codeis the mirror's high byte (the low 8 bits of the AL Status Code, present only when the Error bit is set and the code is non-0; codes ≥0x0100 are truncated, so it only covers 0-255); for the full 16-bit code read the ESC register withread_register(0x0134, 2)). This value is a cache refreshed by the master only while it is in OP; it is not the live truth at read time. When the master is not currently in OP (or no sample has been taken yet) the getter returns 0 = not sampled / unknown; only a non-0 value is a trustworthy sample. Once the master leaves OP the sampler stops and the cache keeps its last sample, so this property no longer claims realtime behaviour.diagnostics.mailbox_health(EcMailboxHealth) — mailbox health of this slave (UNKNOWN/HEALTHY/DEGRADED)diagnostics.is_free_run_demoted(bool) — whether this slave was forced to fall back from DC to FreeRundiagnostics.health_degraded_count(int | None) — consecutive accumulated count of mailbox half-failures on this slave (approximately seconds); a read failure returns Nonediagnostics.recover_mailbox_health()(bool) — manually trigger mailbox half-failure repair (usually repaired automatically)
WcContribution enumeration values (WKC contribution state)
class WcContribution(IntEnum):
NOT_CONTRIBUTED = 0x00 # This slave is not contributing WKC right now (slave loss / no response)
CONTRIBUTED = 0x01 # This slave contributes WKC normally (responds on the bus)
UNKNOWN = 0xFF # Not filled in / not mapped by the SDK — honestly unknown, not treated as no contribution
EcMailboxHealth enumeration values (mailbox health)
class EcMailboxHealth(IntEnum):
UNKNOWN = 0 # No mailbox / not in OP — mailbox health is meaningless here
HEALTHY = 1 # In OP and the mailbox is usable
DEGRADED = 2 # In OP but the mailbox half-fails (CoE/SDO may block)
WKC contribution semantics
slave.diagnostics.wc_contributed reflects whether this slave is really responding right now:
CONTRIBUTED— this slave contributes its working counter (WKC) normally, meaning that when the aggregate WKC is complete (actual == expected, that is, the master-leveldiagnostics_info.wc_deficit == 0), the per-slave byte-by-byte comparison is "full" for every slave.NOT_CONTRIBUTED— this slave is not contributing WKC right now (suspected slave loss / hot-plug recovery in progress). This is not a master fault; once the slave is repaired the state naturally returns toCONTRIBUTED.UNKNOWN— not filled in / not mapped by the SDK, exposed honestly, never made up as "contributed".
This property only "reflects bus reality as it is" and takes part in no WKC tampering / accommodation logic. The per-slave contribution bit is the per-station breakdown of the aggregate WKC deficit (expected - actual): a deficit greater than 0 means some slave is not contributing right now, which should raise an alarm and diagnostics; do not lower expected and do not stop OP.
Example:
from darra_ethercat.data.types import WcContribution, EcMailboxHealth
for slave in master:
if slave.diagnostics.wc_contributed == WcContribution.NOT_CONTRIBUTED:
al = slave.diagnostics.al_status_mirror
print(f"从站 {slave.slave_num} 此刻未贡献 WKC(疑似掉站),AL Code=0x{al.al_status_code:04X}") # Slave {slave.slave_num} is not contributing WKC at the moment (suspected slave loss), AL Code=0x{al.al_status_code:04X}
if slave.diagnostics.mailbox_health == EcMailboxHealth.DEGRADED:
print(f"从站 {slave.slave_num} 在 OP 但邮箱半失效, 已持续 {slave.diagnostics.health_degraded_count}s") # Slave {slave.slave_num} is in OP but the mailbox is partially failing, for {slave.diagnostics.health_degraded_count}s so far
EMCY emergencies
Per-slave EMCY records live on Slave (not on slave.coe), and their only source is the underlying ring buffer:
emcy_count(int) — number of emergency messagesemcy_history(List[EmergencyMessage]) — emergency history (up to the most recent 256 entries, in chronological order oldest → newest). Each entry is a read-onlyEmergencyMessagesnapshot accessed through properties:rec.error_code/rec.error_register/rec.data/rec.slave_index/rec.timestamp_msclear_emcy()— clear the emergency history
for rec in slave.emcy_history:
print(f"从站 {rec.slave_index} EMCY 0x{rec.error_code:04X} " # Slave {rec.slave_index} EMCY 0x{rec.error_code:04X}
f"reg=0x{rec.error_register:02X} t={rec.timestamp_ms}ms")
slave.clear_emcy()
Link quality / port error counters / sync window
link_quality(int) — link quality (0-100%, -1 = unknown)read_port_error_counters()(dict | None) — port error counters; returns{'rx_error': [4], 'invalid_frame': [4], 'lost_link': [4]}(one entry per port); returns None on failurereset_port_error_counters()(bool) — zero the port error counterssync_window_status(dict | None) — sync window status (keysdiff_ns/max_diff_ns/min_diff_ns/in_sync/out_of_sync_count); returns None on failurereset_sync_stats()— reset the sync window statistics
Port error counter exception: read_port_error_counters() really reads ESC registers 0x0300-0x0313 (3 FPRD operations), so it sends frames on the bus; do not put it in a high-frequency loop. It returns None on a read failure. The remaining diagnostic items (WKC contribution / AL status mirror / mailbox health / link quality / sync window / EMCY) are all thin reads of the per-slave diagnostics cache and send no frames.
port_error_stats()
def port_error_stats(self)
Get a read-only pointer to the underlying port error statistics structure of this slave.
Returns:
int— structure address (pointing at the underlying static cache); returnsNonewhen the pointer is empty- The structure holds 4 ports × 4 counter groups: receive error / invalid frame / lost link / forwarded receive error, 4 bytes each
Notes:
- What you get back is a pointer, not a
dict, so copy the data out according to the structure you declared yourself; the same static cache is overwritten by later reads, so you must copy it immediately and must not keep the address until the next sample. - It sends no bus frames; it reads a statistics cache that the underlying layer already maintains.
port_error_stats() only gives you an address, which suits scenarios where you already hold the matching structure definition and need the forwarded receive error counters. In ordinary scenarios use read_port_error_counters(): it returns {'rx_error': [4], 'invalid_frame': [4], 'lost_link': [4]} directly and returns None on failure.
Example:
ptr = slave.port_error_stats()
if ptr:
print(f"端口统计结构地址: 0x{ptr:X}") # Port statistics struct address: 0x{ptr:X}
ESI methods
set_esi_file(esi_file_name)
def set_esi_file(esi_file_name: str) -> bool
Set the ESI file used by the slave.
Returns:
bool— whether the call succeeded
slave.config_by_esi() and slave.configure_from_esi() always raise NotImplementedError (the old implementation returned fake success; it now raises explicitly). ESI parsing is done inside the underlying library, and the Python public surface does not provide a slave.esi / EsiLoader query entry point; just hand the ESI path to master.set_eni() / master.set_esi_file() / master.set_esi_files(). Automatic configuration of SM physical parameters goes through master.auto_configure_sm(slave_index).
Process data watchdog
set_watchdog(timeout_ms)
def set_watchdog(timeout_ms: int) -> bool
Set the slave process data watchdog timeout. The slave raises a watchdog error (ALStatusCode 0x001B, SYNC_MANAGER_WATCHDOG) when it receives no process data frame within the timeout.
Parameters:
timeout_ms(int) — timeout in milliseconds; 0 = disabled; the pre-checked range is0..6553(the watchdog counter register is u16 × 0.1ms), and anything out of range throws immediately, with no truncation and no clamping
Return value and exceptions (three states reported honestly):
True— the value actually written equals the requested value and the register write succeeded- Throws
WatchdogTimeoutError(aValueErrorsubclass) withactual_msset toNone— the request exceeds the 6553ms register limit, so it was rejected and no register was written; the current value stays unchanged - Throws
WatchdogTimeoutErrorwithactual_msholding a value — the value was raised to the safe minimum and written (5000ms for branch slaves / 400ms for PDO slaves on a ring; required by the topology protocol, because writing it as requested would cause false slave loss). The register now holdsactual_ms, not the requested value. If the actual value cannot be read after raising it,actual_msisNoneand the exception message explains why False— the register write failed / the index is invalid (the underlying layer gives no specific error code); the value is unchanged
Example:
from darra_ethercat import WatchdogTimeoutError
try:
ok = slave.set_watchdog(100)
print("已按请求写入" if ok else "寄存器写失败 / 索引无效") # Written as requested / register write failed or index invalid
except WatchdogTimeoutError as e:
if e.actual_ms is None:
print(f"请求被拒绝,未写入:{e}") # Request rejected, nothing written: {e}
else:
print(f"被安全下限抬升并写入,实际 {e.actual_ms} ms") # Raised to the safety lower limit and written; actual value {e.actual_ms} ms
Call this in SafeOp or OP state.
set_pdi_watchdog(timeout_ms)
def set_pdi_watchdog(timeout_ms: int) -> bool
Set the slave PDI watchdog timeout. The PDI watchdog monitors whether the slave's local application (microcontroller firmware) is running normally.
Parameters:
timeout_ms(int) — timeout in milliseconds; 0 = disabled; the pre-checked range is0..6553; anything out of range throws immediately
Return value and exceptions (same semantics as set_watchdog):
True— written as requested- Throws
WatchdogTimeoutErrorwithactual_msset toNone— above the 6553ms register limit; rejected and not written False— the register write failed / the index is invalid
PDI has no safe minimum, so the "raised and then written" branch never occurs (actual_ms is None only on rejection).
Example:
slave.set_pdi_watchdog(100) # 100ms timeout
slave.set_pdi_watchdog(0) # Disable the PDI watchdog
watchdog_config
@property
def watchdog_config(self) -> Optional[dict]
Read the slave's current watchdog configuration. A return value of None means the read failed.
Returns:
Optional[dict]— watchdog configuration dictionary with the following keys:divider(int) — watchdog dividerpdi_timeout(int) — PDI watchdog timeout value (in divider units)pd_timeout(int) — process data watchdog timeout value (in divider units)
Example:
config = slave.watchdog_config
if config is not None:
print(f"PD超时: {config['pd_timeout']} × {config['divider'] * 0.04}µs") # PD timeout: {config['pd_timeout']} × {config['divider'] * 0.04}µs
watchdog_status
@property
def watchdog_status(self) -> Optional[dict]
Read the slave watchdog runtime status. A return value of None means the whole call failed (read failure).
On a successful call, the dictionary determines validity valid_maskfield by field** from the returned valid bit set **; it no longer infers a read failure from 0x0440 == 0xFF:
- The corresponding
valid_maskbit is 1 → the field is the real register value (it can be 0) - The corresponding bit is 0 → that register read failed this time and the field returns
None(it is not "really read 0")
The status key in the dictionary comes from bit0 of ESC register 0x0440: 0 = the watchdog has overflowed / expired, 1 = the watchdog is normal or not enabled; bits other than bit0 are reserved. 0x0442 / 0x0443 are watchdog overflow counters (write 0 to reset, reading does not clear them) and are not the same thing as the status bit in 0x0440.
Returns:
Optional[dict]— watchdog status dictionary with the following keys:status(int | None) — watchdog status value (0x0440bit0: 0 = overflowed/expired, 1 = normal or not enabled);Noneon a read failurecounter(int | None) — watchdog counter0x0442(accumulated expiration count);Noneon a read failuredivider(int | None) — current divider value0x0400;Noneon a read failurepd_timeout(int | None) — current process data watchdog timeout value0x0420;Noneon a read failurecounter_pdi(int | None) — PDI watchdog overflow counter0x0443;Noneon a read failurevalid_mask(int) — the valid bit set of this read (status=0x0001 / counter=0x0002 / divider=0x0004 / time_pd=0x0008 / counter_pdi=0x0010)
Example:
status = slave.watchdog_status
if status is None:
print("看门狗状态读取失败") # Failed to read watchdog status
elif status['status'] is None:
print("0x0440 本次未读到(未知),不按健康处理") # 0x0440 was not read this time (unknown); not treated as healthy
elif (status['status'] & 0x01) == 0:
print(f"看门狗触发! 计数={status['counter']}") # Watchdog triggered! Count={status['counter']}
else:
print(f"看门狗正常, valid_mask=0x{status['valid_mask']:04X}") # Watchdog OK, valid_mask=0x{status['valid_mask']:04X}
State transitions
set_state(state, timeout_ms=5000)
def set_state(state: EcState, timeout_ms: int = 5000) -> bool
Set the EtherCAT state of a single slave (with a timeout). Use this for manual recovery or to move one slave to a specified state; for a network-wide state machine use master.set_state().
Parameters:
state(EcState) — target statetimeout_ms(int) — timeout in milliseconds, default5000
Returns:
bool— whether the call succeeded
State transitions follow the EtherCAT standard state machine flow, and the protocol layer handles intermediate states automatically. For example, switching from INIT to OP passes through PreOp → SafeOp → OP automatically.
Example:
# Manually recover a single slave to OP
if slave.state != EcState.OP:
slave.set_state(EcState.OP)
# Switch the slave to Init (reset)
slave.set_state(EcState.INIT, timeout_ms=5000)
Hot-plug and reconfiguration
When a slave has been powered off and plugged back in or replaced and then re-enters PreOp, the underlying layer sets needs_reconfig to indicate that the startup parameters and configuration of that slave need to be replayed:
needs_reconfig— read-only flag,True= configuration is waiting to be replayed,False= nothing to replayclear_reconfig_flag()— clear the flag manually
When the flag is True, the PreOp reconfiguration callback registered by the SDK automatically replays the startup parameters of the IP / PS / SO transitions at both the Before / After timings, then clears the flag. You only need to clear it manually when you have completed the reconfiguration yourself and do not want the SDK to replay it again.
clear_reconfig_flag()
def clear_reconfig_flag(self)
Clear the reconfiguration flag of this slave. It returns no value.
Once the flag is cleared, the next PreOp reconfiguration callback no longer replays startup parameters automatically for this slave.
Example:
if slave.needs_reconfig:
slave.apply_startup_params() # replay itself (default IP + After)
slave.clear_reconfig_flag()
Real-time status queries
slave.state / slave.error_code are adaptive read sources: during stable OP operation they read the cache maintained by the cycle health check (zero frames); when not in OP (INIT / PreOp / SafeOp / hot-plug) or when the cache is not filled, they first refresh in real time once before returning, so you cannot treat them as "pure cache values that are always zero-frame". When you need a forced live read for "right now", use the properties below (they really send one frame and compete for the port lock; read them only when confirming a state transition or locating a fault):
| Property | Returns | Description |
|---|---|---|
state_live_read | LiveRead | Live state read + four-state trust; value is the raw AL Status byte (including the bit4 Error bit) |
state_live | Optional[EcState] | Gives a value only when VALID, otherwise None; None != EcState.NONE |
state_raw_live | Optional[int] | Live raw byte; None when untrusted |
al_status_code_live_read | LiveRead | Live AL code (lossless 16-bit) + four-state trust |
al_status_code_live | Optional[EcALState] | Gives a value only when VALID, otherwise None (not NO_ERROR) |
al_status_code_raw_live | Optional[int] | Live lossless raw code; None when untrusted |
LiveRead and the four trust states
Only a value that passes is_valid (that is, validity == VALID) may be used as the current value; the other three states must never be taken as "this is how it is right now".
| Value | Meaning | Usable as the current value |
|---|---|---|
UNKNOWN(0) | No usable read (call failed / old library missing the entry point / invalid handle) | No. Unknown != normal |
VALID(1) | This measurement produced a result usable as the current value | Yes |
STALE(2) | A value was obtained, but it is confirmed not current (the lower layer uses 0 as a placeholder when the slave is lost / not responding) | No, this is a residual value |
DEGRADED(3) | A value was obtained, but only partial evidence is available (liveness state / probe unreadable or unknown) | Not as confirmation |
Live state criterion: 0 / 0xFF / low 4 bits are 0 -> UNKNOWN; otherwise -> VALID.
Live AL code criteria:
| Verdict | Trigger | value |
|---|---|---|
UNKNOWN | The call failed, or it returned 0xFFFF (the unavailable sentinel) | 0xFFFF |
DEGRADED | The liveness state / probe read failed | Raw code |
STALE | is_lost is true, or the probe confirms no response | Raw code (residual) |
DEGRADED | Probe evidence is insufficient (unknown) | Raw code |
VALID | is_lost is False and the probe confirms the slave is online | Raw code |
The lower layer returns 0 for a lost / non-responding slave; that 0 is the "no data" placeholder, not "no error". al_status_code_live_read uses the liveness state and probe evidence to file it as STALE; the convenience entry points give None in that case. Never read 0 / None as "the device confirmed no fault".
The view semantics of slave.state and slave.error_code must be kept clear: state gives only the base state (it drops the Error bit), while error_code / al_status_code are enum views (codes outside the table carry the original code); for a lossless integer use state_raw / al_status_code_raw, and for a "readable state with the Error bit" use slave.status.format(). On a read failure state_raw / al_status_code_raw return the 0 / 0xFFFF sentinels respectively — do not treat them as the device's real value.
The AL mirror (diagnostics.al_status_mirror) holds only the low 8 bits of the code, so codes ≥ 0x0100 are truncated; for the complete 16-bit code use al_status_code_raw or al_status_code_live_read.
ESC register access (advanced)
Read and write slave ESC (EtherCAT Slave Controller) registers directly, for fault diagnostics, custom ESC operations and register-level debugging. General register reads and writes do not automatically fall back to the secondary NIC port or broadcast (that capability exists only in write_dl_port()).
You do not need to call this during normal SDK use — state transitions / PDO / mailbox flows configure the registers automatically. This API is for in-depth diagnostics and special scenarios (for example reading error counters, forcing a port policy, or debugging when an ESI burn-in does not take effect).
Register definitions are in ETG.1000.4 §6 / ETG.1000.6 §5 (public standards), for example:
| Register | Description |
|---|---|
| 0x0000 | Type / Revision / Build (device type) |
| 0x0030 | AL Control (master initiates a state request) |
| 0x0130 | AL Status (current slave state) |
| 0x0134 | AL Status Code (error code) |
| 0x0300-0x0313 | Port 0-3 error counters (RX Error / Invalid Frame / Lost Link) |
| 0x0400-0x043F | Watchdog configuration (divider / PDI timeout / PD timeout) |
| 0x0440-0x0443 | SM watchdog status / overflow counters: 0x0440 bit0 (0 = overflowed/expired, 1 = normal or not enabled; 0xFF = read failure/unknown); 0x0442/0x0443 reset on write 0, reading does not clear |
read_register(addr, length)
def read_register(self, addr: int, length: int) -> Optional[bytes]
Read a slave ESC register (FPRD).
Parameters:
addr(int) — register address (for example0x0130= AL Status)length(int) — number of bytes to read (1 / 2 / 4 and so on)
Returns:
Optional[bytes]— returns the byte data on success; returnsNoneon failure (slave offline / timeout)
write_register(addr, data)
def write_register(self, addr: int, data: bytes) -> bool
Write a slave ESC register (FPWR).
Parameters:
addr(int) — register addressdata(bytes) — data to write
Returns:
bool— returnsTrueon success
Example:
slave = master[1] # 1-based index, the 1st slave
# Read AL Status (0x0130, 2 bytes)
data = slave.read_register(0x0130, 2)
if data:
state = int.from_bytes(data, 'little')
print(f"AL Status = 0x{state:04X} (state={state & 0x0F}, err={(state & 0x10) != 0})")
# Read AL Status Code (0x0134, error code)
code_bytes = slave.read_register(0x0134, 2)
if code_bytes:
code = int.from_bytes(code_bytes, 'little')
print(f"AL Status Code = 0x{code:04X}")
# Write AL Control = 0x04 (request SafeOp)
slave.write_register(0x0030, bytes([0x04, 0x00]))
EEPROM (SII) access
Read and write the slave SII EEPROM (Slave Information Interface, ETG.1000.6 §6). The EEPROM stores device identity and configuration information such as vendor_id / product_code / revision_no / serial_no / SyncManager / FMMU / PDO mapping / Strings. The SDK already reads it automatically at configuration time, so applications generally do not need direct access.
Use EEPROM writes with care — a wrong write can corrupt the slave identity information and, in the worst case, permanently brick the slave, requiring the vendor's tool to recover. Use it only in the following scenarios:
- Burning an alias address (ESC
0x0012) - Repairing factory data that was overwritten by mistake
- Vendor-authorized firmware / parameter burning
EEPROM writes require the slave to be in Init / PreOp state; writes are rejected in OP state.
EEPROM size is usually 1 KB - 16 KB (word-addressed, 1 word = 2 byte). The first 8 words hold basic vendor information, followed by the category linked list (Strings / General / FMMU / SyncM / TxPdo / RxPdo / DC / End=0xFFFF).
read_eeprom(byte_offset, byte_length)
def read_eeprom(self, byte_offset: int, byte_length: int) -> bytes
Read a byte region of the slave SII EEPROM (looping by word). The SDK handles BUSY polling and word alignment automatically; applications should prefer this high-level API.
Parameters:
byte_offset(int) — starting byte offset (an odd offset is aligned down to the word boundary and the corresponding byte is taken)byte_length(int) — number of bytes to read (an even value is recommended; for an odd value the low byte is taken at the end)
Returns:
bytes—byte_lengthbytes of data; returns emptyb""on failure or invalid arguments
write_eeprom(byte_offset, data)
def write_eeprom(self, byte_offset: int, data: bytes) -> bool
Write a byte region of the slave SII EEPROM (looping by word). Both byte_offset and len(data) must be even.
Parameters:
byte_offset(int) — starting byte offset (must be even)data(bytes) — bytes to write (the length must be even)
Returns:
bool— returnsTruewhen every word was written successfully
Example:
slave = master[1] # 1-based index, the 1st slave
# Read vendor_id (EEPROM byte offset 0x10, length 4)
data = slave.read_eeprom(0x10, 4)
if len(data) == 4:
vendor_id = int.from_bytes(data, 'little')
print(f"VendorID = 0x{vendor_id:08X}")
# Read the first 16 header bytes (including PDIControl / StationAlias and so on)
header = slave.read_eeprom(0, 16)
print(f"EEPROM 头部: {header.hex()}") # EEPROM header: {header.hex()}
# Write the alias section (consecutive words starting at EEPROM byte offset 0x08)
# The slave must be in Init/PreOp state
if slave.state == EcState.INIT:
ok = all([
slave.write_eeprom(0x08, bytes([0x01, 0x00])), # alias = 1 (word 0x04)
slave.write_eeprom(0x0A, bytes([0x00, 0x00])), # Reserved field (word 0x05)
])
For byte-range access use read_eeprom / write_eeprom; for category-level access use slave.sii (below). For identity and similar values, see the wrapped properties in the property table above.
slave.sii — tri-state category reads
slave.sii (SiiAccessor) is the Category-level SII entry point: it locates / reads any category through the ETG.1000.6 category chain and parses the General Category into a struct. read_eeprom / write_eeprom are byte-range access; the two complement each other.
class SiiReadStatus(IntEnum):
OK = 0 # Read succeeded
NOT_FOUND = 1 # The chain is readable and really has no such category (a normal result, not an error)
READ_FAILED = 2 # SII cannot be read; must not be treated as "does not exist"
class SiiReadResult(NamedTuple):
status: SiiReadStatus
value: Optional[object] # A real value only when OK
def try_find_category(self, cat: int) -> SiiReadResult
def try_read_category(self, cat: int, max_bytes: int = 4096) -> SiiReadResult
def try_get_general_info(self) -> SiiReadResult
def try_read_identity(self) -> SiiReadResult # value = SiiIdentityInfo
def try_read_serial_number(self) -> SiiReadResult # value = int
Shape of value when OK:
try_find_category→(byte_offset, byte_size)try_read_category→bytes(length 0 is a valid empty segment and returnsb"")try_get_general_info→SiiGeneralInfotry_read_identity→SiiIdentityInfotry_read_serial_number→int(the true 32-bit serial number, possibly 0)
Attribution rules (the tri-state, aligned case by case):
SIIEnumerateCategoriesreturns a negative value (even the SII context cannot be obtained) →READ_FAILED- The category is present on the chain but locating it failed →
READ_FAILED(being on the chain means it does not "not exist") - The category chain is readable and does not contain the category →
NOT_FOUND(a normal result) - Locating succeeded →
OK try_read_category: locate first (same attribution), return that status directly when it is notOK; if locating succeeded but the data cannot be read →READ_FAILED(no partial data)try_get_general_info: on a failed read, iftry_find_category(30)isNOT_FOUND→NOT_FOUND, otherwiseREAD_FAILED
find_category() / read_category() / get_general_info() use None to mean both "really does not exist" and "read failed";
the two are the same shape in the old signatures. Use the tri-state try_* entries to tell them apart; the old entries keep their return shape and behavior.
Example:
from darra_ethercat.slave.core import SiiReadStatus
sii = slave.sii
r = sii.try_find_category(30) # General Category
if r.status is SiiReadStatus.OK:
offset, size = r.value
print(f"General @0x{offset:X} ({size} 字节)") # General @0x{offset:X} ({size} bytes)
elif r.status is SiiReadStatus.NOT_FOUND:
print("该从站没有 General 分类") # This slave has no General category
else:
print("SII 读不出来(不是'不存在')") # SII could not be read (this is not the same as 'not present')
data = sii.try_read_category(10) # Strings Category
if data.status is SiiReadStatus.OK:
print(f"Strings 共 {len(data.value)} 字节") # Strings total {len(data.value)} bytes
info = sii.try_get_general_info()
if info.status is SiiReadStatus.OK:
print(f"设备名索引={info.value.name_idx}") # Device name index={info.value.name_idx}
SII identity area and true serial number
The identity area is a fixed ESC area (ETG.1000.6: word 0x0008..0x000F) and does not go through the category chain, so try_read_identity / try_read_serial_number only ever produce OK / READ_FAILED and never NOT_FOUND.
| word | Field | Description |
|---|---|---|
| 0x0008 / 0x0009 | vendor_id | V (Vendor ID) |
| 0x000A / 0x000B | product_code | P (Product Code) |
| 0x000C / 0x000D | revision_no | R (Revision No) |
| 0x000E / 0x000F | serial_no | Serial (serial number) |
Each item is assembled into 32 bits with the low word first (low | high << 16), matching the EEPROM direct-read convention.
from darra_ethercat.slave.core import SiiReadStatus
ident = slave.sii.try_read_identity()
if ident.status is SiiReadStatus.OK:
i = ident.value
print(f"V=0x{i.vendor_id:08X} P=0x{i.product_code:08X} "
f"R=0x{i.revision_no:08X} Serial={i.serial_no}")
serial = slave.sii.try_read_serial_number()
if serial.status is SiiReadStatus.OK:
print(f"序列号真值 = {serial.value}") # May be 0: the real value is 0
A failed read is never folded to 0: if any of the 8 identity words cannot be read the result is READ_FAILED (value is None). An incomplete identity area means no partial data is delivered, and it is not passed off as "the device wrote no identity". READ_FAILED and "the real value is 0" are two different things and callers must handle them separately.
The three meanings of serial number 0
slave.serial_number is a native runtime identity snapshot, and 0 can mean any of three things:
| Case | Meaning | Correct way to read it |
|---|---|---|
| Not read | Cold configuration only reads the SER word for slaves that miss the ESI; slaves that hit the ESI keep 0 | slave.try_get_serial_number() |
| Real value 0 | The serial number declared in the device's SII really is 0 | slave.try_get_serial_number() returns 0 (not None) |
| Read failed | The SII cannot be read | slave.try_get_serial_number() returns None |
slave.try_get_serial_number() -> Optional[int] order: (a) the native snapshot is non-0 → return it directly without touching the EEPROM; (b) the snapshot is 0 → read SII word 0x000E..0x000F live.
- Returns
int= the real value (possibly0) - Returns
None= cannot be read (not equal to 0 — unknown is never folded to 0) - While the snapshot is 0, every call really reads the EEPROM; callers that need it frequently should cache it themselves
sn = slave.try_get_serial_number()
if sn is None:
... # Cannot be read — unknown; do not treat it as serial 0
else:
print(f"序列号 = {sn}") # sn may be 0; that is the value the device declares
DL Port control
Read and write the ESC DL Port Control register (0x0101) directly, for port fault injection tests and manual diagnostics of redundancy / ring topologies.
You do not need to call this during normal operation. Most users should diagnose port state by subscribing to the slave_port_link_changed event and reading the port error counters. Use it only when you need to actively simulate a port fault (testing redundancy switching) or investigate a specific port problem.
The ESC has 4 physical ports P0 / P1 / P2 / P3; the bit definitions of the DL Port Control register are as follows:
| DLPORT value | Behavior |
|---|---|
| 0x00 | Auto — all ports managed automatically by the ESC (default) |
| 0x03 | Close P0 |
| 0x0C | Close P1 |
| 0x30 | Close P2 |
| 0xC0 | Close P3 |
Only write_dl_port() automatically switches to the secondary NIC port / broadcast write-back when a port is unavailable: after P0 is closed it can still write back. write_register / read_register have no fallback; after P0 is closed, access through them does not automatically switch to the secondary port or broadcast.
- The dedicated
slave.write_dl_port(value)/slave.read_dl_port()methods: writes have a three-level fallback (primary → secondary → broadcast APWR); reads go through the primary port only and have no secondary fallback; on failure they returnFalse/Nonerespectively. - The general register read/write
write_register(addr, data)/read_register(addr, length)hit0x0101directly: the register location is the same, but they send a single frame with no fallback, so they are not equivalent to the dedicated methods. When P0 is normal both produce the same result; after P0 is closed,write_dl_portmay still succeed whilewrite_registerfails (neither path has a fallback on the read side).
write_dl_port() / read_dl_port() are for debugging / port fault injection. When the runtime library does not export the corresponding debug symbol, they return False / None respectively (no exception), so do not read that as "the register write definitely failed". For production code that needs to read or write 0x0101, use write_register(0x0101, ...) / read_register(0x0101, 1); the cost is losing the write fallback of write_dl_port (the read side never had a fallback).
Write the DL Port Control register (0x0101):
# See the table above for value (0-255)
ok = slave.write_dl_port(value) # Dedicated method with port fallback
ok = slave.write_register(0x0101, bytes([value])) # General register write, single frame, no fallback
Read the current DL Port Control register value:
dlport = slave.read_dl_port() # Dedicated method; returns None on a read failure
data = slave.read_register(0x0101, 1) # General register read, single frame, no fallback
dlport = data[0] if data else 0
Example:
# Simulate a P1 port fault (test redundancy switching)
ok = slave.write_register(0x0101, bytes([0x0C]))
print(f"关闭 P1: {'成功' if ok else '失败'}") # Closing P1: {'success' if ok else 'failure'}
# Read back to confirm
data = slave.read_register(0x0101, 1)
dlport = data[0] if data else 0
print(f"当前 DLPORT = 0x{dlport:02X}") # Current DLPORT = 0x{dlport:02X}
# Restore after the fault is cleared
slave.write_register(0x0101, bytes([0x00])) # Restore Auto
After closing a port, watch master.events.add_slave_port_link_changed() and master.diagnostics_info.break_point to verify that redundancy switching takes effect.
Startup configuration
The "whether to write PDO Assignment / PDO Configuration" and "whether Complete Access is supported" settings of the Startup configuration are fields in the ENI/DENI configuration file and are not exposed as slave object properties. The Startup interface on the slave object only has the startup parameter list.
Automatic startup (ENI/DENI and MDP)
Startup fields declared in the ENI/DENI configuration file take effect when the configuration is loaded and do not need to be sent slave by slave; modular devices (MDP) and SM physical parameters are orchestrated automatically by the master — call master.enable_auto_startup() during chained initialization, and it executes at build().
Configuration source declaration (StartupAutoConfig)
The declaration interface on darra_ethercat.slave.startup.StartupAutoConfig (not on the slave object): it only records the declaration "the configuration came from ENI or DENI" and is not responsible for loading files — loading ENI / DENI still goes through their respective configuration loading entry points. The class is defined in the darra_ethercat.slave.startup module, and ConfigSource is exported by both the package root and darra_ethercat.data.
class ConfigSource(IntEnum):
UNKNOWN = 0 # Undeclared (instance default; must not be written explicitly)
ENI = 1 # Configuration came from ENI (standard ETG.2100 network configuration XML)
DENI = 2 # Configuration came from DENI (Darra extended network configuration, an ENI superset)
class StartupAutoConfig:
def set_config_source(self, source) -> None
def set_config_source_eni(self) -> None # Equivalent to set_config_source(ConfigSource.ENI)
def set_config_source_deni(self) -> None # Equivalent to set_config_source(ConfigSource.DENI)
@property
def config_source(self) -> str
@property
def has_executed(self) -> bool
| Category | Property | Type | Read/write | Description |
|---|---|---|---|---|
| Configuration source | set_config_source(source) | None | write-only | Declares the configuration source; accepts ConfigSource.ENI / ConfigSource.DENI as well as the equivalent strings "ENI" / "DENI"; UNKNOWN, out-of-range values and unrecognized strings raise ValueError |
| set_config_source_eni() | None | write-only | Forwarder to set_config_source(ConfigSource.ENI), kept for compatibility | |
| set_config_source_deni() | None | write-only | Forwarder to set_config_source(ConfigSource.DENI), kept for compatibility | |
| config_source | str | read-only | Reads back the declared source: "ENI" / "DENI"; an empty string "" when nothing has been declared (still returns str, no enum read-back) | |
| Execution status | has_executed | bool | read-only | Whether automatic configuration has been executed; default False |
Write and read-back:
set_config_source(ConfigSource.ENI)→config_sourcereads back"ENI"and setshas_executedtoTrueat the same timeset_config_source(ConfigSource.DENI)→config_sourcereads back"DENI"and likewise setshas_executed = True- May be called repeatedly: a later declaration overwrites the previous one (ENI ↔ DENI switching is supported) and is read back through
config_source ConfigSource.UNKNOWN, out-of-range values and unrecognized strings all raiseValueError— "undeclared" is the instance default, and writing it explicitly would be fabricating a source- Defaults: after creating a new instance,
config_sourceis""andhas_executedisFalse - They only change the declaration field on this instance; they do not load files, read the slave or write to the slave, and issue no bus operation
from darra_ethercat import ConfigSource
# auto = the StartupAutoConfig instance you hold
auto.set_config_source(ConfigSource.DENI)
print(auto.config_source) # "DENI"
print(auto.has_executed) # True — declaring a source sets the flag as well
auto.set_config_source("ENI") # The equivalent string is accepted too
print(auto.config_source) # "ENI"
native does not record the ENI / DENI source per slave — it only records two things per slave: "explicitly planned (explicit_replace)" and "merged ESI defaults (esi_installed)". config_source is the declaration value kept on the SDK side: it reads back whatever the caller declared. Actually loading configuration still goes through the master's set_eni / load_config_* path.
has_executed only means "has been declared as having executed automatic configuration"; it is not a read-back of the slave's actual running state. Declaring a source sets it to True at the same time so upper layers can tell whether the configuration is already in place (the SDK has no auto-startup executor today; whether to skip is the caller's decision). Startup fields declared in the ENI/DENI still take effect when the configuration is loaded (see the previous section), and this interface does not change the loading behavior.
Managing startup parameters manually (slave.startup)
StartupParameterList methods (accessed through slave.startup):
add(index, sub_index, data, transition=StartupTransition.IP, priority=0, write_timing=None, complete_access=False, description="")— creates and adds a startup parameter from explicit fields, returns the createdStartupParameteradd_parameter(param)— adds an already createdStartupParameterobjectremove(param)— removes the specifiedStartupParameterobject, returnsboolclear()— clears all startup parameters, returns a result code (int)apply_all(slave)— applies all startup parameters to the slave, returns the number successfully applied (int)
add() takes explicit fields and constructs a StartupParameter; add_parameter() takes an already constructed StartupParameter object.
Example:
from darra_ethercat import StartupParameter
from darra_ethercat.data.types import StartupTransition
# First approach: add() with explicit arguments
slave.startup.add(
index=0x1C12,
sub_index=0,
data=bytes([0]),
transition=StartupTransition.PS,
priority=10,
)
# Second approach: construct a StartupParameter object first, then call add_parameter()
param = StartupParameter(
index=0x1C13,
sub_index=0,
data=bytes([0]),
transition=StartupTransition.PS,
priority=10,
)
slave.startup.add_parameter(param)
Related structures:
IP— Init → PreOp, default AfterTransitionPS— PreOp → SafeOp, default BeforeTransitionSO— SafeOp → Op, default BeforeTransitionOS— Op → SafeOp, default AfterTransitionSP— SafeOp → PreOp, default AfterTransitionPI— PreOp → Init, default BeforeTransition
startup_param_count
@property
def startup_param_count(self) -> int
Number of startup parameters registered for this slave.
Returns:
int— number of registered startup parameters; when the master / slave index is invalid or the slave is not initialized it returns a negative error code (never folded into 0)
Example:
count = slave.startup_param_count
if count < 0:
print("启动参数数量读取失败") # Failed to read the startup parameter count
else:
print(f"已登记 {count} 条启动参数") # {count} startup parameters registered
apply_startup_params(transition=TRANS_IP, timing=TIMING_AFTER)
def apply_startup_params(self, transition: int = TRANS_IP,
timing: int = TIMING_AFTER) -> int
Send the startup parameters registered for this slave to the slave, selected by state transition phase and write timing.
Parameters:
transition(int) — state transition phase:TRANS_IP=0 (Init→PreOp) /TRANS_PS=1 /TRANS_SO=2 /TRANS_OS=3 /TRANS_SP=4 /TRANS_PI=5, defaultTRANS_IPtiming(int) — write timing:TIMING_BEFORE=0 /TIMING_AFTER=1, defaultTIMING_AFTER
Returns:
int— number of startup parameters successfully applied this time0— nothing was applied for the current sample (this phase has no parameters waiting to be sent, or this call was deferred; it does not mean the phase is complete)- A negative number — failure error code (invalid master / slave index, not initialized, SDO write failure and so on); a failure is never folded into 0
Notes:
- Only entries whose registered phase and timing match are sent.
- Normal state transitions apply startup parameters automatically through the master; call this directly only when you manage startup parameters manually.
Example:
from darra_ethercat import TRANS_PS, TIMING_BEFORE
applied = slave.apply_startup_params(TRANS_PS, TIMING_BEFORE)
if applied < 0:
print(f"启动参数下发失败, 错误码 {applied}") # Failed to send the startup parameters, error code {applied}
else:
print(f"本次应用 {applied} 条") # {applied} applied this time
clear_startup_params()
def clear_startup_params(self) -> int
Clear all startup parameters registered for this slave.
Returns:
int—0= success; a negative number = error code (invalid master / slave index, not initialized)
Notes:
- An empty queue after clearing still counts as a complete replacement, and startup parameters are not filled back in automatically from the ESI afterwards.
- Only the registration table is cleared; parameter values already written to the slave are not withdrawn. To restore the slave, send them again or restart the slave.
Example:
rc = slave.clear_startup_params()
if rc == 0:
print("启动参数已清空") # Startup parameters cleared
Identity verification and domain information
The slave's domain information is read through public properties: the identity returns a dictionary and the rest are ordinary Python values.
Reading and verifying identity
identity = slave.identity
# {'vendor_id': 0x00000002, 'product_code': 0x0000000A,
# 'revision_no': 0x00010000, 'serial_no': 0x00001234}
from darra_ethercat import SlaveIdentity
expected = SlaveIdentity(
vendor_id=0x00000002,
product_code=0x0000000A,
revision_no=0x00010000,
serial_no=0x00001234,
)
ok = slave.verify_identity(expected, check_revision=True, check_serial=False)
slave.identityreturnsNoneon a read failure (slave offline / not ready); do not treat that as an all-0 identity.verify_identitychecks the revision number by default and not the serial number; withcheck_serial=Truethe serial number is also compared.
Common domain properties
| Category | Public property | Type | Read/write | Description |
|---|---|---|---|---|
| Groups | slave.group | int | read/write | Group the slave belongs to; a failed write throws RuntimeError |
| Optionality | slave.optional | bool | read/write | Whether the slave is optional (is_optional is the equivalent entry point) |
| Device information | slave.name | str | read-only | Slave group name (EEPROM group_name, the ESI GroupType name) |
| Topology | slave.active_ports | int | read-only | Active port bitmap |
| slave.parent_index | int | read-only | Parent slave index | |
| slave.parent_station | int | read-only | Parent slave index (historical name; it is actually the index, 0 = master) | |
| DC | slave.propagation_delay | int | read-only | Propagation delay (ns) |
| slave.dc_active | int | read-only | AssignActivate value, 0 = disabled | |
| Mailbox | slave.mbx_proto | int | read-only | Supported mailbox protocol bitmap |
| slave.mbx_count | int | read-only | Mailbox link-layer protocol counter |
Each mailbox protocol's is_supported (such as coe.is_supported) combines the slave.mbx_proto protocol bits (positive evidence) with the SII General details (negative authority); protocols without a negative authority field only return True / None and are never folded into False.