Properties and state machine
NIC enumeration and scanning (NIC selection / quick scan / full scan / cancel) are covered in Initialization § NICs and scanning. This page covers properties, the state machine and runtime control only.
Properties
Except for a few process-level functions, the first parameter of a C API function is master_index.
The table below omits that parameter from the signatures; a full call looks like GetLinkStatus(master). GetNetworksPointer() is a process-level function and takes no master_index.
| Category | Function | Return type | Read/write | Description |
|---|---|---|---|---|
| Network and link | GetLinkStatus(mi) | uint8_t | read-only | Network link state (ec_link_state_t) |
| Network and link | GetNetworksPointer() | void* | read-only | Internal pointer to the NIC list |
| Error codes | GetSlaveALStatusCode(mi, si) | uint16_t | read-only | Slave AL Status Code error code |
| Runtime | GetSlaveState(mi, si) | uint8_t | read-only | Current slave state (EC_STATE_*, see the state enum below) |
| Runtime | GetAggregatedState(mi) | uint8_t | read-only | System aggregate state: the lowest base state across all real slaves plus the aggregated Error bit; returns 0 (unknown) when no slave takes part and never falls back to the master-state cache |
| Master clock | get_master_dc_time(mi) | int64_t | read-only | DC master clock time (ns) |
| Master clock | get_reference_clock_slave(mi) | uint16_t | read-only | Reference-clock slave index |
For slave grouping (slaves per group / active groups / expected WKC per group / lost frames per group) see Slave grouping.
EtherCAT state enum:
typedef enum {
EC_STATE_NONE = 0x00, /* no state / unknown */
EC_STATE_INIT = 0x01, /* Init state */
EC_STATE_PRE_OP = 0x02, /* Pre-Operational */
EC_STATE_BOOT = 0x03, /* Boot state (firmware update) */
EC_STATE_SAFE_OP = 0x04, /* Safe-Operational */
EC_STATE_OPERATIONAL = 0x08, /* Operational */
EC_STATE_ACK = 0x10, /* error acknowledge bit */
EC_STATE_ERROR = 0x10 /* error state flag */
} ec_state_t;
typedef enum {
EC_LINK_DOWN = 0, /* confirmed down: both configured ports are explicitly DOWN */
EC_LINK_UP = 1, /* link OK (both the primary and the redundant NIC are connected) */
EC_LINK_PRIMARY_ONLY = 3, /* primary NIC only connected */
EC_LINK_SECONDARY_ONLY = 4, /* redundant NIC only connected */
EC_LINK_UNKNOWN = 5 /* unknown: not initialized / real-time process image not observable / PHY has not reported yet */
} ec_link_state_t;
EC_LINK_DOWN only means "confirmed down"; when the physical link cannot be read the call returns EC_LINK_UNKNOWN, which does not mean disconnected — show it as "unknown" rather than "link down".
Physical link tri-state
GetLinkStatus() describes the state of the whole link / redundancy combination; the entry points below look at a single physical port, and all of them can express "unknown". They can be read while the link is down and do not depend on a scan or on the OP state.
| Category | Function | Return type | Read/write | Description |
|---|---|---|---|---|
| Network and link | GetPhyLinkState(mi) | uint32_t | read-only | Bitmap: bit0 = primary port up, bit1 = secondary port up; 0xFFFF = not observable (runtime components not ready / master not created) |
| Network and link | GetPrimaryPhyLinkState(mi) | int (ec_phy_link_state_t) | read-only | Primary port physical link tri-state: -1 = unknown, 0 = down, 1 = up |
| Network and link | GetSecondaryPhyLinkState(mi) | int (ec_phy_link_state_t) | read-only | Secondary port physical link tri-state, same values |
| Network and link | SecondaryFrameLinkState(mi) | int (ec_phy_link_state_t) | read-only | Secondary port frame-level link: whether the redundancy loop-back frame actually arrives; when the peer does not forward, the port is physically up but frame-level down |
A value of -1 from the tri-state functions means not observable (the real-time driver is not installed properly / the real-time process image is unavailable / the master has not been created); it must be treated as neither 0 (down) nor 1 (up). To decide "the link is really down" you must compare explicitly against EC_PHY_LINK_DOWN(0); do not use a truthiness test — both -1 and 1 are true, which reads "unknown" as "up". The bitmap form (GetPhyLinkState) and the per-port tri-state form (GetPrimaryPhyLinkState / GetSecondaryPhyLinkState / SecondaryFrameLinkState) coexist; do not substitute one for the other.
State machine management
SetState()
BOOL SetState(uint16_t master_index, int state);
BOOL SetStateWithTimeout(uint16_t master_index, int state, uint32_t timeout_ms);
BOOL SetSlaveStateWithTimeout(uint16_t master_index, uint16_t slave_index,
int state, uint32_t timeout_ms);
Switches the master and all slaves to the target state (walking the ETG state-machine chain and crossing several levels in one call). SetSlaveStateWithTimeout switches a single slave only. The SDK retries up to 3 times automatically on occasional hardware glitches (waiting 1.5 s after each failure), so the application does not need to wrap its own retry logic.
When you need to submit asynchronously, use darra_set_state_async(gate, mi, state, timeout_ms, ...): attach it to the gate created by darra_async_gate_create() and it queues serially, returns as soon as it is submitted, and reports the result and progress through callbacks (at any moment only one operation per master talks to the bus).
When switching to EC_STATE_SAFE_OP, the SDK configures the sync cycle counter threshold and the SyncManager sync type for non-DC slaves per the ETG standard (falling back to FreeRun), so that missing default values on some drives do not stall SafeOp. SetStateSequence / SetStateWithStartup do the same automatically. A slave that does not support the relevant configuration is skipped silently; a custom sync policy should be applied after switching to SafeOp.
SetStateSequence()
BOOL SetStateSequence(uint16_t master_index, int target_state, uint32_t timeout_ms);
BOOL SetStateWithStartup(uint16_t master_index, int target_state, uint32_t timeout_ms);
SetStateSequence performs a chained automatic state transition (Init → PreOp → SafeOp → OP) and applies the startup parameters automatically. This is the recommended function. SetStateWithStartup performs a single-step state transition and applies the Before/After startup parameters automatically.
Example:
uint16_t master = Initialize();
SetNetwork(master, adapter, "");
if (!SetStateSequence(master, EC_STATE_OPERATIONAL, 10000)) {
printf("状态转换失败\n"); /* State transition failed */
}
A failed state change needs the cleanup path; in C you can use EC_TRY(SetStateSequence(mi, EC_STATE_OPERATIONAL, 5000)) instead of the if-not-return boilerplate: a failure jumps to goto fail automatically, and EC_AUTO_DISPOSE hands release to the enclosing scope.
Stop()
BOOL Stop(uint16_t master_index);
BOOL Start(uint16_t master_index);
Stop() stops the PDO cycle thread and switches the master back to the PRE_OP state. Start() starts the PDO cycle (call it after SafeOp/OP). Both return whether they succeeded. To interrupt a blocking state change, see Runtime emergency control below.
GetMasterState() / GetSlaveState()
void* GetMasterState(uint16_t master_index);
uint8_t GetSlaveState(uint16_t master_index, uint16_t slave_index);
uint8_t GetLinkStatus(uint16_t master_index);
uint16_t GetSlaveALStatusCode(uint16_t master_index, uint16_t slave_index);
GetMasterState() returns a pointer to the current master state value as void* (no need to free); cast it to uint8_t* and read the first byte for the aggregate state (EC_STATE_*). GetSlaveState() returns the current state of a single slave. GetSlaveALStatusCode() returns the slave AL Status Code error code.
The value returned by GetSlaveState() corresponds to the EC_STATE_* state enum (EC_STATE_INIT / EC_STATE_PRE_OP / EC_STATE_SAFE_OP / EC_STATE_OPERATIONAL / EC_STATE_BOOT). C carries it as an integer; interpret it as an enum value, not as a bare number.
Prefer subscribing to RegisterSlaveStateChangeCallbackAsync; the SDK pushes state changes as they happen. Poll with GetMasterState yourself only for UI refresh / simple demos (an interval of ≥ 100 ms is recommended; do not put it inside a PDO callback).
To poll all slave states, C can use EC_FOREACH_SLAVE(mi, i) { ... } for a compact loop: the macro calls ec_foreach_slave_count_(mi) once and caches the result as the loop bound, so it does not hit the SDK on every iteration.
Waiting and timeouts for state transitions
The C SDK does not provide a polling-only method that waits without switching states, and the headers do not declare one, so it cannot be called.
In the C SDK the waiting and timeout of a state transition is handled by the timeout-taking state functions themselves:
SetStateWithTimeout(mi, state, timeout_ms)— switches and waits up totimeout_msfor the master to reach the target stateSetSlaveStateWithTimeout(mi, si, state, timeout_ms)— switches and waits for a single slaveSetStateSequence(mi, target, timeout_ms)— chained switch with waiting
They already pick a fallback timeout per ESI / configuration / ETG.1020, so a separate "wait-only" function is not needed. If you really need pure polling, write your own loop over GetSlaveState() / GetMasterState().
Process data watchdog
int SetAllSlaveWatchdog(uint16_t master_index, uint32_t timeout_ms);
int SetAllSlavePdiWatchdog(uint16_t master_index, uint32_t timeout_ms);
Sets the process data watchdog / PDI watchdog timeout for all slaves in one call (milliseconds, 0 = disabled, maximum 6553 ms).
Return value (the number of slaves written successfully, not a boolean): it must be judged together with GetLastError() (same thread, read immediately after the call):
| Return value | GetLastError() | Meaning |
|---|---|---|
>0 | 0 | All slaves written as requested |
>0 | 0x20000011 | In this batch some slaves were raised to a safety floor (5000 ms for branch slaves / 400 ms for PDO slaves on the ring); the actual value != the requested value, so this is not "everything applied as requested"; per slave, use GetSlaveWatchdogConfig() to read wd_time_pd / 10 for the actual milliseconds |
0 | 87 | The whole batch exceeds the 6553 ms cap, the entire batch is rejected and nothing is written |
0 | 0 | Invalid master index / no slaves / write failure (an invalid index falls into the 0 bucket, it does not take 87) |
0+0x20000011never happens; a slave that was raised to the safety floor and written with the actual value still counts toward the success count.- When the SDK is not ready (the runtime is not loaded, so no call is issued) the call returns -1 and last-error is pinned to 0, so it cannot be confused with the 0 / >0 buckets.
- PDI batch: with
>0the last-error is always0, and0x20000011never appears (the PDI watchdog has no safety-floor branch).
For the watchdog configuration of a single slave use SetSlaveWatchdog().
Example:
int count = SetAllSlaveWatchdog(master, 100);
printf("已设置 %d 个从站看门狗超时为 100ms\n", count); /* Set the watchdog timeout to 100ms on %d slaves */
Hot-plug self-recovery
When a slave is powered off and replugged, or replaced, the SDK detects the identity mismatch automatically and enters a protected state, so a wrong device is never pulled into the control cycle by mistake.
AcknowledgeSlaveReplacement()
BOOL AcknowledgeSlaveReplacement(uint16_t master_index, uint16_t slave_index);
Confirms that the slave replacement is finished and triggers the EtherCAT identification state machine to probe that slave again.
When to call: subscribe to RegisterSlaveIdentityMismatchCallback; once the identity-mismatch alarm arrives and the operator has finished checking or replacing the device, call this method so the SDK probes again.
Behavior:
- If the identity is now correct (the right device is back / the same model with a newer revision) → it recovers automatically and raises the slave discovery event
- If the identity still does not match →
SlaveIdentityMismatchis raised again and the slave returns to theIDENT_REJECTEDstate
Parameters:
master_index(uint16_t) — master indexslave_index(uint16_t) — slave index (1-based, matching the configuration)
Return value:
BOOL—TRUE= accepted and the FSM reset;FALSE= invalid parameter, or the slave is not currently inIDENT_REJECTED/FAILED
Calling this method before the SlaveIdentityMismatch event fires has no effect. While the slave has not entered the protected state the SDK keeps probing normally, so no manual confirmation is needed.
Example:
static void on_identity_mismatch(uint16_t mi, uint16_t si,
uint32_t ev, uint32_t ep, uint32_t er,
uint32_t av, uint32_t ap, uint32_t ar)
{
printf("从站 %d 身份不符 (期望 Vendor=0x%08X, 实际 Vendor=0x%08X)\n", /* Slave %d identity mismatch (expected Vendor=0x%08X, actual Vendor=0x%08X) */
si, ev, av);
if (show_replacement_dialog(si)) {
BOOL ok = AcknowledgeSlaveReplacement(mi, si);
if (!ok)
printf("确认失败: 从站不在 IDENT_REJECTED 状态\n"); /* Confirmation failed: the slave is not in the IDENT_REJECTED state */
}
}
RegisterSlaveIdentityMismatchCallback(on_identity_mismatch);
- Discovery
is_found=FALSE/TRUE— the slave lost power or its cable (identity still matches) → it recovers automatically and raisesis_found=TRUE SlaveIdentityMismatch— the slave identity changed (wrong device, i.e. Vendor + Product do not match the configuration; the revision is not part of the identity check) → callAcknowledgeSlaveReplacementmanually
State machine transition rules
Per ETG.1000.6 §6.4 / ETG.1020 Table 55:
| Category | Transition | Description |
|---|---|---|
| Legal | IP / PS / SO / PI / SP / OS / SI / OI / IB / BI | One level forward or backward |
| Legal | Self-transition to the same state | Idempotent, no error |
| Illegal | Level-skipping upgrades such as Init→SafeOp, PreOp→OP | Advance one level at a time |
SetStateWithTimeout / SetStateSequence already fall back to the recommended timeouts, so applications normally do not compute timeouts themselves. For the classification of AL Status Codes and troubleshooting advice see Diagnostics.
Runtime emergency control
The abort / pause / safe-stop entry points used at runtime. Lifecycle actions such as releasing a master and FreeMemory are covered in Initialization § Resource release.
| Category | Function | Returns | Read/write | Use | Restrictions |
|---|---|---|---|---|---|
| Abort | AbortNetwork() | void | write-only | Sets the abort flag so that blocking SetState* / GetNetworkInfo / ScanSlaveInfo calls return immediately; callable from any thread (UI cancel button) | Interrupts blocking calls only; it does not stop the PDO cycle |
| Abort | ResetAbortNetwork() | void | write-only | Clears the network-layer abort flag, preparing the next round of operations | Clearing it before the old operation has really exited lets that operation keep blocking |
| Abort | AbortScan() | void | write-only | Sets the scan abort flag so that ScanSlaveInfo returns immediately | Affects scanning only; the state machine is untouched |
| Abort | AbortMaster(mi) | void | write-only | Aborts a blocking loop (scan / wait) on the given master without freezing other masters; mi = 0 means "all masters", and the caller is responsible for guarding that 0 | void only proves the abort request was issued; it does not mean the blocking loop has exited |
| Cycle control | PausePdoKeepRt(mi) | BOOL | write-only | Explicitly pauses the PDO cyclic LRW while keeping the real-time session and independent frame transactions; TRUE = handled as paused (an idempotent success for a master that was already stopped) | Do not call it during a state transition: the cyclic frame must keep running, and pausing lets the slaves' SM2 watchdog drop them out of OP; FALSE = invalid master index or SDK not ready (fail-closed) |
| Safe stop | SafeStopMaster(mi) | void | write-only | Controlled stop of a single master: sends the CiA 402 Shutdown 0x0006 only to the slaves of this master (the deceleration behaviour is set by the 0x0105 Shutdown Option Code) and leaves other masters alone | Closing a single master must pass that master's index |
| Safe stop | DarraEcat_SafeStopAllMasters() | void | write-only | Process-level safe shutdown: all masters receive the safe stop together (a process-level entry point with no short-name wrapper) | With several masters running, do not use it to close one master |
Example:
/* GUI cancel button */
void on_cancel_clicked(void) {
AbortNetwork(); /* make a blocking SetState return immediately */
AbortScan(); /* make ScanSlaveInfo return immediately */
}
Startup configuration validation
BOOL VerifyAllSlaveIdentities(uint16_t master_index,
ec_slave_identity_t* expected, uint32_t slave_count,
BOOL check_revision, BOOL check_serial,
uint64_t* mismatch_mask);
int ec_validate_config(uint16_t master_index);
VerifyAllSlaveIdentities — validates the identity of the whole network in one call (Vendor / ProductCode / optional Revision / optional Serial); returns TRUE when everything matches. mismatch_mask marks mismatching slaves by bit position (slave_index 1..64 maps to bit0..63). Combine it with SetSlaveOptional to allow a device swap at certain positions.
ec_validate_config — a pre-Build check: network configuration / slave-to-group mapping / PDO sizes / watchdog parameters and so on. Returns the number of configuration problems (0 = configuration OK).
Error types
The communication-layer error type enum ec_error_type_t:
| Value | Name | Meaning |
|---|---|---|
| 0 | EC_ERROR_FRAME_LOST | Frame lost |
| 1 | EC_ERROR_OUT_OF_ORDER | Frame out of order |
| 2 | EC_ERROR_CHECKSUM | Checksum error |
| 3 | EC_ERROR_TIMEOUT | Timeout |
| 4 | EC_ERROR_WKC_MISMATCH | Working counter mismatch |
| 5 | EC_ERROR_LINK_LOST | Link lost |
For SDO failure reasons see ec_sdo_typed_status_t (see CoE); for the classification and troubleshooting of AL Status Codes see Diagnostics; for on-site handling of other error codes see Error codes and troubleshooting.
Soft real-time scheduling
Soft real-time scheduling entry points for the Windows user-mode PDO thread. By default only the PDO thread is promoted (bound to a reserved core + thread base priority 31) and the process priority class is not changed; failures are always a no-op with a reason text.
| Category | Function | Return type | Read/write | Description |
|---|---|---|---|---|
| Status query | SoftRealtimeQuery(mi, out) | BOOL | read-only | Fills ec_srt_status_t; TRUE = filled, which does not mean enabled |
| ec_srt_policy_probe(mi) | int | read-only | Reads the DARRA_ECAT_SRT policy only: 0 = auto, 1 = off, 2 = on; a failed query is treated as auto | |
| Thread-level apply | SoftRealtimeApply(mi) | BOOL | write-only | Binds the PDO thread to a reserved core + thread base priority 31; does not change the process priority class |
| SoftRealtimeApplyAuto(mi) | BOOL | write-only | Same action as SoftRealtimeApply, with the policy handled inside the runtime | |
| SoftRealtimeEnsure(mi) | BOOL | write-only | Alias for SoftRealtimeApply | |
| Process-level apply | SoftRealtimeEnable() | BOOL | write-only | Strict mode: sets the whole process to the REALTIME priority class, affecting every thread in the host process |
| SoftRealtimeEnsureProcess() | BOOL | write-only | Alias for SoftRealtimeEnable | |
| Disable | SoftRealtimeDisable() | void | write-only | Clears all master registrations; restores only the process real-time class set by this SDK |
| Compatibility entry | SoftRealtimeOptIn() | BOOL | read-only | Old-signature compatibility; does not change scheduling state, and a constant TRUE only means "no opt-in needed" |
| Polling | SoftRealtimePoll(mi) | BOOL | read-only | TRUE = nothing left to retry; FALSE = still worth waiting (a failed query also returns FALSE) |
Full semantics and examples are on Soft real-time scheduling; the mode enum, status structure and environment policy are on the same page.
Instances and CPU affinity
mi is the master index. cpu_core is a system core number, -1 means not configured (a core is chosen automatically per the CPU contract), and any other out-of-range value returns FALSE as-is.
| Category | Function | Return type | Read/write | Description |
|---|---|---|---|---|
| Instance | GetMaxMasterInstances() | int | read-only | Maximum number of master instances = min(SDK limit, number of usable isolated cores) |
| GetActiveInstanceCount() | int | read-only | Number of currently active master instances (occupied slots, not the limit) | |
| CPU affinity | GetAvailableCpuCores() | int | read-only | Number of processors available on this machine (including cores that are not reserved) |
| SetMasterCpuAffinity(mi, cpu_core) | BOOL | write-only | Sets the baseline CPU core for this master's thread group | |
| SetProcessCpuAffinity(cpu_core) | BOOL | write-only | Binds the whole process to a single core (0..N-1), affecting every thread in the process | |
| SetPDOThreadCpuAffinity(mi, cpu_core) | BOOL | write-only | Registers the target core for the PDO thread; applied immediately while running, and at Start when not running | |
| GetPDOThreadCpuAffinity(mi) | int | read-only | Returns the registered value (configuration side), -1 = not configured; not the core actually bound | |
| GetPDOThreadCpuEffectiveCore(mi) | int | read-only | Returns the actually bound core (reads the real thread mask); -1 for unbound / multi-core mask / thread not started / unreadable |
GetPDOThreadCpuAffinity answers "what the user set", while GetPDOThreadCpuEffectiveCore answers "which core the thread is actually bound to". Use the latter to decide whether the binding really took effect.
Real-time mode and timing
Entry points to query and start or stop the real-time transport and the cycle timing modes.
| Category | Function | Return type | Read/write | Description |
|---|---|---|---|---|
| Real-time transport | IsWdkAvailable(mi) | BOOL | read-only | Whether the real-time transport component is available (loaded and ready) |
| GetWdkMode(mi) | BOOL | read-only | TRUE = currently using real-time transport | |
| SetWdkMode(mi, enable) | BOOL | write-only | Enables / disables real-time transport mode; returns FALSE when unavailable or the arguments are invalid | |
| StartWdkRT(mi, cycle_us, cpu_index) | BOOL | write-only | Starts the real-time core (high-resolution timer + core isolation); cycle_us is the cycle in microseconds, cpu_index is the isolated core number | |
| StopWdkRT(mi) | BOOL | write-only | Stops the real-time core and releases the isolated core | |
| Timing | GetTimingMode(mi) | uint32_t | read-only | Cycle timing mode: 0=unknown, 1=hardware timer, 2=software (QPC), 3=degraded, 4=RT ready (driver loaded, timer not started), 5=RT start failed |
| DarraValidateTimerAccuracy(expected_usec, tolerance_usec) | int | read-only | Sleeps for expected_usec and measures the elapsed time: 0 = within tolerance, 1 = too short, 2 = too long; a blocking probe that does not change configuration |
GetTimingMode returns the timing mode enum, not the cycle time; for cycle configuration see Configuration § SetMasterLoopCycleTime.
Scanning and runtime emergency control
The paired entry points for closing scan sessions and "cancel". For the general interruption of blocking calls (AbortNetwork / ResetAbortNetwork / AbortScan / AbortMaster / PausePdoKeepRt) see Runtime emergency control above.
| Category | Function | Return type | Read/write | Description |
|---|---|---|---|---|
| Scan close | CloseScanNic() | int | write-only | Closes the temporary scan owner in a targeted way; 1 = all closed, 0 = something remains after a bounded wait (reported as-is, no false success); does not touch an active master |
| ResetScanAbort() | void | write-only | Clears the scan abort flag; it is a no-op when the abort flag belongs to another in-flight scan session, and does not clear beyond its authority | |
| Emergency and abort | ResetAbortMaster(mi) | void | write-only | Resets the abort bit set by AbortMaster (0 = all masters); only reclaims what that entry point produced, does not touch the Stop/Close intent and does not weaken the process-level abort latch |
| EmergencyCloseNics() | void | write-only | Emergency close of all master NICs, the last resort before the process exits; it closes everything including active masters, and the library's internal state cannot be recovered after the call | |
| Scan snapshot | GetScannedSlaveGeneration() | int | read-only | Scan result snapshot generation: even = stable snapshot, odd = being written; compare once before and once after reading the snapshot, and a mismatch means "stale"; returns -1 when not ready |
EmergencyCloseNics is only for when the process is about to exit. To close temporary scan resources mid-session, always use CloseScanNic; otherwise the real-time channel of the active master is torn down as well.
Slave DC receive time and hardware capabilities
Debug helpers for a slave's DC capability and per-port receive-time readings. The parameters are the master index and the slave index (1-based).
| Category | Function | Return type | Read/write | Description |
|---|---|---|---|---|
| DC capability | DebugSlaveHasDC(mi, si) | void | write-only | Debug helper: re-reads the slave's ESC capability register to probe the DC capability read path; no return value and no effect on bus data. Implemented in debug builds only; a no-op in release builds |
| DC receive time | GetSlaveDCReceiveTimeB(mi, si) | int32_t | read-only | DC receive time of port B (nanoseconds) |
| GetSlaveDCReceiveTimeC(mi, si) | int32_t | read-only | DC receive time of port C (nanoseconds) | |
| GetSlaveDCReceiveTimeD(mi, si) | int32_t | read-only | DC receive time of port D (nanoseconds) |
The port A entry point is the existing GetSlaveDCReceiveTimeA, in the same group of read-only properties as B / C / D; for slave-level DC configuration and criteria see Slave DC.