Skip to main content

Properties and state machine

NICs and scanning

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​

Function signature convention

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.

CategoryFunctionReturn typeRead/writeDescription
Network and linkGetLinkStatus(mi)uint8_tread-onlyNetwork link state (ec_link_state_t)
Network and linkGetNetworksPointer()void*read-onlyInternal pointer to the NIC list
Error codesGetSlaveALStatusCode(mi, si)uint16_tread-onlySlave AL Status Code error code
RuntimeGetSlaveState(mi, si)uint8_tread-onlyCurrent slave state (EC_STATE_*, see the state enum below)
RuntimeGetAggregatedState(mi)uint8_tread-onlySystem 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 clockget_master_dc_time(mi)int64_tread-onlyDC master clock time (ns)
Master clockget_reference_clock_slave(mi)uint16_tread-onlyReference-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.

CategoryFunctionReturn typeRead/writeDescription
Network and linkGetPhyLinkState(mi)uint32_tread-onlyBitmap: bit0 = primary port up, bit1 = secondary port up; 0xFFFF = not observable (runtime components not ready / master not created)
Network and linkGetPrimaryPhyLinkState(mi)int (ec_phy_link_state_t)read-onlyPrimary port physical link tri-state: -1 = unknown, 0 = down, 1 = up
Network and linkGetSecondaryPhyLinkState(mi)int (ec_phy_link_state_t)read-onlySecondary port physical link tri-state, same values
Network and linkSecondaryFrameLinkState(mi)int (ec_phy_link_state_t)read-onlySecondary 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
Unknown is not 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).

Entering SafeOp configures the sync policy automatically

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 */
}
C-specific syntactic sugar

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.

Return values are enum semantics

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.

Recommendation: events vs polling

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).

C-specific syntactic sugar

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 has no polling-only wait method

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 to timeout_ms for the master to reach the target state
  • SetSlaveStateWithTimeout(mi, si, state, timeout_ms) — switches and waits for a single slave
  • SetStateSequence(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 valueGetLastError()Meaning
>00All slaves written as requested
>00x20000011In 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
087The whole batch exceeds the 6553 ms cap, the entire batch is rejected and nothing is written
00Invalid master index / no slaves / write failure (an invalid index falls into the 0 bucket, it does not take 87)
  • 0 + 0x20000011 never 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 >0 the last-error is always 0, and 0x20000011 never appears (the PDI watchdog has no safety-floor branch).
note

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 → SlaveIdentityMismatch is raised again and the slave returns to the IDENT_REJECTED state

Parameters:

  • master_index (uint16_t) — master index
  • slave_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 in IDENT_REJECTED / FAILED
The event must arrive first

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);
Difference from Discovery (offline/online)
  • Discovery is_found=FALSE/TRUE — the slave lost power or its cable (identity still matches) → it recovers automatically and raises is_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) → call AcknowledgeSlaveReplacement manually

State machine transition rules​

Per ETG.1000.6 §6.4 / ETG.1020 Table 55:

CategoryTransitionDescription
LegalIP / PS / SO / PI / SP / OS / SI / OI / IB / BIOne level forward or backward
LegalSelf-transition to the same stateIdempotent, no error
IllegalLevel-skipping upgrades such as Init→SafeOp, PreOp→OPAdvance 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.

CategoryFunctionReturnsRead/writeUseRestrictions
AbortAbortNetwork()voidwrite-onlySets 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
AbortResetAbortNetwork()voidwrite-onlyClears the network-layer abort flag, preparing the next round of operationsClearing it before the old operation has really exited lets that operation keep blocking
AbortAbortScan()voidwrite-onlySets the scan abort flag so that ScanSlaveInfo returns immediatelyAffects scanning only; the state machine is untouched
AbortAbortMaster(mi)voidwrite-onlyAborts 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 0void only proves the abort request was issued; it does not mean the blocking loop has exited
Cycle controlPausePdoKeepRt(mi)BOOLwrite-onlyExplicitly 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 stopSafeStopMaster(mi)voidwrite-onlyControlled 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 aloneClosing a single master must pass that master's index
Safe stopDarraEcat_SafeStopAllMasters()voidwrite-onlyProcess-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:

ValueNameMeaning
0EC_ERROR_FRAME_LOSTFrame lost
1EC_ERROR_OUT_OF_ORDERFrame out of order
2EC_ERROR_CHECKSUMChecksum error
3EC_ERROR_TIMEOUTTimeout
4EC_ERROR_WKC_MISMATCHWorking counter mismatch
5EC_ERROR_LINK_LOSTLink 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.

CategoryFunctionReturn typeRead/writeDescription
Status querySoftRealtimeQuery(mi, out)BOOLread-onlyFills ec_srt_status_t; TRUE = filled, which does not mean enabled
ec_srt_policy_probe(mi)intread-onlyReads the DARRA_ECAT_SRT policy only: 0 = auto, 1 = off, 2 = on; a failed query is treated as auto
Thread-level applySoftRealtimeApply(mi)BOOLwrite-onlyBinds the PDO thread to a reserved core + thread base priority 31; does not change the process priority class
SoftRealtimeApplyAuto(mi)BOOLwrite-onlySame action as SoftRealtimeApply, with the policy handled inside the runtime
SoftRealtimeEnsure(mi)BOOLwrite-onlyAlias for SoftRealtimeApply
Process-level applySoftRealtimeEnable()BOOLwrite-onlyStrict mode: sets the whole process to the REALTIME priority class, affecting every thread in the host process
SoftRealtimeEnsureProcess()BOOLwrite-onlyAlias for SoftRealtimeEnable
DisableSoftRealtimeDisable()voidwrite-onlyClears all master registrations; restores only the process real-time class set by this SDK
Compatibility entrySoftRealtimeOptIn()BOOLread-onlyOld-signature compatibility; does not change scheduling state, and a constant TRUE only means "no opt-in needed"
PollingSoftRealtimePoll(mi)BOOLread-onlyTRUE = 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.

CategoryFunctionReturn typeRead/writeDescription
InstanceGetMaxMasterInstances()intread-onlyMaximum number of master instances = min(SDK limit, number of usable isolated cores)
GetActiveInstanceCount()intread-onlyNumber of currently active master instances (occupied slots, not the limit)
CPU affinityGetAvailableCpuCores()intread-onlyNumber of processors available on this machine (including cores that are not reserved)
SetMasterCpuAffinity(mi, cpu_core)BOOLwrite-onlySets the baseline CPU core for this master's thread group
SetProcessCpuAffinity(cpu_core)BOOLwrite-onlyBinds the whole process to a single core (0..N-1), affecting every thread in the process
SetPDOThreadCpuAffinity(mi, cpu_core)BOOLwrite-onlyRegisters the target core for the PDO thread; applied immediately while running, and at Start when not running
GetPDOThreadCpuAffinity(mi)intread-onlyReturns the registered value (configuration side), -1 = not configured; not the core actually bound
GetPDOThreadCpuEffectiveCore(mi)intread-onlyReturns the actually bound core (reads the real thread mask); -1 for unbound / multi-core mask / thread not started / unreadable
Configuration is not measurement

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.

CategoryFunctionReturn typeRead/writeDescription
Real-time transportIsWdkAvailable(mi)BOOLread-onlyWhether the real-time transport component is available (loaded and ready)
GetWdkMode(mi)BOOLread-onlyTRUE = currently using real-time transport
SetWdkMode(mi, enable)BOOLwrite-onlyEnables / disables real-time transport mode; returns FALSE when unavailable or the arguments are invalid
StartWdkRT(mi, cycle_us, cpu_index)BOOLwrite-onlyStarts 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)BOOLwrite-onlyStops the real-time core and releases the isolated core
TimingGetTimingMode(mi)uint32_tread-onlyCycle 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)intread-onlySleeps 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.

CategoryFunctionReturn typeRead/writeDescription
Scan closeCloseScanNic()intwrite-onlyCloses 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()voidwrite-onlyClears 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 abortResetAbortMaster(mi)voidwrite-onlyResets 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()voidwrite-onlyEmergency 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 snapshotGetScannedSlaveGeneration()intread-onlyScan 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
Do not use the emergency close in the middle of a session

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).

CategoryFunctionReturn typeRead/writeDescription
DC capabilityDebugSlaveHasDC(mi, si)voidwrite-onlyDebug 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 timeGetSlaveDCReceiveTimeB(mi, si)int32_tread-onlyDC receive time of port B (nanoseconds)
GetSlaveDCReceiveTimeC(mi, si)int32_tread-onlyDC receive time of port C (nanoseconds)
GetSlaveDCReceiveTimeD(mi, si)int32_tread-onlyDC 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.