Skip to main content

Properties and state machine

Initialization, NICs and the builder

Construction, NIC enumeration and scanning, and builder initialization (SetNetwork / SetENI / Validate / Build) are covered in Initialization. This page covers only properties, the state machine, start/stop, and runtime control.

Properties​

CategoryPropertyTypeRead/writeDescription
Basic informationMasterNumber()uint16_tRead-onlyMaster instance number
SlaveCount()intRead-onlyNumber of slaves detected on the network
IsInitialized()boolRead-onlyWhether the master has been initialized
IsDisposed()boolRead-onlyWhether the master has been disposed
IsRedundant()boolRead-onlyWhether redundancy mode is on
Network and linkLinkState()EcLinkStateRead-onlyNetwork link state
Error codeErrorCode()EcALStateRead-onlyError code reported automatically on a fault
ErrorCnt()uint32_tRead-onlyError count
DC and cycleDCtime()int64_tRead-onlyDC timestamp (nanoseconds)
LoopCycle() / LoopCycle(uint32_t)uint32_tRead/writePDO cycle time (nanoseconds)
RuntimeState()EcStateRead-onlyMaster EtherCAT state
RuntimeAggregatedState()EcStateRead-onlySystem aggregate state: the lowest base state across all real slaves plus the aggregated Error bit; returns None (unknown) when no slave takes part and never falls back to the master-state cache
WKC()uint16_tRead-onlyWorking counter (WKC)
ExpectedWKC()uint16_tRead-onlyExpected working counter
PrimaryWKC() / SecondaryWKC()uint16_tRead-onlyWKC of the primary / secondary NIC in redundancy mode
DCtime() / GetMasterDCTime()int64_tRead-onlyMaster DC timestamp (nanoseconds)
GetReferenceClockSlaveIndex()intRead-onlyReference clock slave index (0 = none)
GroupingDivider(group) / Divider(group, value)uint8_tRead/writeGroup cycle divider
ActiveGroupCount()uint8_tRead-onlyNumber of active groups
FilterThreshold() / FilterThreshold(value)uint32_tRead/writeLoss judgement filter threshold

Example:

using namespace darra;

EtherCATMaster master(dll);
master.SetNetwork("\\Device\\NPF_{...}");
master.Build();

printf("主站编号: %d\n", master.MasterNumber()); // Master number: %d
printf("从站数量: %d\n", master.SlaveCount()); // Slave count: %d
printf("链路状态: %d\n", static_cast<int>(master.LinkState())); // Link state: %d
printf("已初始化: %s\n", master.IsInitialized() ? "是" : "否"); // Initialized: %s (yes / no)

State machine management​

The EtherCAT state machine follows the standard sequence: INIT → PRE_OP → SAFE_OP → OP.

C++ offers 3 call forms:

FormSignaturePurpose
SynchronousEtherCATMaster::SetState(target, timeoutMs) -> boolBlocking switch; passing through the intermediate states and the timeout are handled internally
AsynchronousEtherCATMaster::SetStateAsync(target, timeoutMs) -> std::future<bool>Does not block the calling thread; take the result from future.get()
With error informationmaster_state::SetState(m, target, timeoutMs) -> StateResultRuns synchronously and returns {bool success; std::string message; EcState ActualState; int UnreachedSlaveCount; std::vector<SlaveStateIssue> UnreachedSlaves;}; on failure it carries the measured state and the per-slave AL code

SetState()​

bool SetState(EcState target, int timeoutMs = 10000) const;

Sets the master state (with a timeout). Internally it steps through the intermediate states INIT → PRE_OP → SAFE_OP → OP in the standard EtherCAT order, and applies the startup parameters and performs the MDP modular device configuration along the transition chain.

Parameters:

  • target (EcState) — target state
  • timeoutMs (int) — timeout in milliseconds, default 10000 (retained for compatibility; the core's global state timeout is what actually applies)

Returns:

  • bool — whether it succeeded

Example:

// Switch to the OP state
bool ok = master.SetState(EcState::OP);
if (!ok) {
printf("状态转换失败\n"); // State transition failed
}

Asynchronous variant: std::future<bool> SetStateAsync(EcState target, int timeoutMs = 10000) const; returns as soon as it is submitted without blocking the calling thread; take the result with future.get().

auto future = master.SetStateAsync(EcState::OP);
// ... other work can go here ...
bool ok2 = future.get();
Automatic sync configuration for SafeOp

When switching to EcState::SafeOp, the SDK follows the ETG standard and automatically configures the sync cycle counter threshold and the SyncManager sync type (FreeRun as the fallback) for non-DC slaves that support CoE, so the application layer does not have to hardcode them.

A write failure (the slave does not support it / the mailbox is busy) does not block the state change; the SDK only logs it and continues. If you need a custom sync policy, override it after SetState(SafeOp) through master.GetSlave(i).GetCoE().SDOWrite(...).

Automatic MDP configuration (2.5.x)

When switching to OP, module detection and the write of the configured module list (0xF030) are performed automatically for MDP modular devices (ETG.5001). MDP devices such as the GCAN-8200 do not need a manual call to MDP::AutoConfigureFromDetectedModules(), which avoids entering SafeOp with SM3 length=0 and reporting AL=0x001E.

master_state::SetState() (with error information)​

namespace darra { namespace ethercat { namespace master_state {

/// On a failed state transition, a snapshot of the slave that did not reach the target state
struct SlaveStateIssue {
uint16_t SlaveIndex = 0; // Slave index (1-based, always >= 1)
EcState State = EcState::None; // Measured raw state (base state in the low 4 bits + bit4 Error)
uint16_t AlStatusCode = 0; // AL Status Code (0 = no error; 0xFFFF = not read)
};

struct StateResult {
bool success = false;
std::string message;
EcState ActualState = EcState::None; // The master's measured state after the call (on failure = the state it really stopped in)
int UnreachedSlaveCount = 0; // Number of slaves that did not reach the target base state (0 on success)
std::vector<SlaveStateIssue> UnreachedSlaves; // Details of the stations that did not arrive (at most the first 32)
};

StateResult SetState(EtherCATMaster& m, EcState state, uint32_t timeoutMs = 10000);

} } }

A synchronous switch that carries an error description; it returns StateResult. Unlike earlier versions that only returned success / message, it now fills in the real state on both success and failure:

  • ActualState — the master state measured after the call returns; on failure this is the state it really stopped in.
  • UnreachedSlaveCount / UnreachedSlaves — after checking the target base state (the low 4 bits) slave by slave, it lists the index, measured state and AL Status Code of the slaves that did not arrive (first 32 entries at most).
  • message — on success it states that the state change succeeded; on failure it contains the target state, the measured state, the number of slaves that did not arrive and the first 8 slave entries (#站号(state=0x..,AL=0x....)), with an ESI attribution hint at the end. When the master is already in the target state the message says so, and ActualState is filled in as well.

Parameters:

  • m (EtherCATMaster&) — master instance
  • state (EcState) — target state
  • timeoutMs (uint32_t) — timeout in milliseconds, default 10000

Returns:

  • StateResult — { success, message, ActualState, UnreachedSlaveCount, UnreachedSlaves }

Asynchronous variant: SetStateWithErrorAsync(master, state) returns std::future<StateResult> with the same semantics and does not block the calling thread.

Example:

using namespace darra::ethercat;

auto r = master_state::SetState(master, EcState::OP);
if (!r.success) {
printf("状态切换失败: %s\n", r.message.c_str()); // State switch failed: %s
for (auto& issue : r.UnreachedSlaves) {
printf(" 从站 %u: state=0x%02X AL=0x%04X\n", // Slave %u: state=0x%02X AL=0x%04X
issue.SlaveIndex,
static_cast<unsigned>(issue.State),
issue.AlStatusCode);
}
}

WaitForState() (blocking wait, does not switch)​

namespace darra { namespace ethercat { namespace master_state {

bool WaitForState(const EtherCATMaster& m, EcState state,
uint32_t timeoutMs = 10000,
uint32_t pollIntervalMs = 50);

} } }

Blocks until the master reaches the given EtherCAT state without initiating the switch itself. It suits the case where another thread performs the switch and this thread only waits for the result.

Parameters:

  • m — master instance
  • state — target state (EcState::PreOp / SafeOp / OP and so on)
  • timeoutMs — timeout (milliseconds), default 10000
  • pollIntervalMs — polling interval (milliseconds), default 50

Returns:

  • bool — true means master.State() == state was observed before the timeout

Example:

using namespace darra::ethercat;

// Another thread is switching; this thread just waits for it to land
auto fut = master.SetStateAsync(EcState::OP);
if (master_state::WaitForState(master, EcState::OP, 5000)) {
master.Start();
} else {
printf("超时: 主站未能进入 OP\n"); // Timeout: the master did not reach OP
}
Which one to use
  • Wait synchronously for the result → SetState()
  • Start asynchronously + future.get() → SetStateAsync()
  • Need an error description → master_state::SetState()
  • Someone else switches, you only wait → master_state::WaitForState()

State steps and retry visibility​

When a state change fails, the whole sequence is not re-run: the SDK records the last confirmed starting state and runs only the remaining steps after it, writing one WARNING per failure. The entry points below can be called on their own so your own retry logic can reuse the same decision making.

CategoryMethodType or return typeRead/writeDescription
State steps and retryEtherCATMaster::UpgradeSteps()const EcState*Read-onlyAscending state chain PreOp → SafeOp → OP; returns a pointer to the first element of a 3-entry static array. Shared process-wide; do not free or modify it
EtherCATMaster::DowngradeSteps()const EcState*Read-onlyDescending state chain SafeOp → PreOp → Init, also a 3-entry static array
EtherCATMaster::BuildRemainingSteps(cur, target)std::vector<EcState>Read-onlyWorks out which state steps are still missing from the low 4 bits of cur and target: ascending for an upgrade, descending for a downgrade, and an empty vector when the target is already reached
ResumeRemainingSteps(target, perStepTimeoutMs)boolWrite-onlyResumes only the remaining steps after the confirmed state instead of re-running the whole sequence; one perStepTimeoutMs budget covers the whole resume, and it returns false as soon as the budget is exhausted or a step is not confirmed
AllSlavesAtTargetBaseState(target)boolRead-onlyReads the raw AL state slave by slave and returns true only when the low 4 bits of every slave equal the target base state; an empty slave list, any slave that cannot be read, or any slave outside the target base state gives false
DescribeUnreachedSlaves(target)std::stringRead-onlyLists the slaves that did not reach the target base state as #slave(0x base-state[,Error]), at most 16 entries, with any remainder summarised as +N slaves not listed
LogStateRetryFailure(attempt, elapsedMs, target, willRetry)voidWrite-onlyWrites one retry WARNING: which attempt this is, how long the segment took, the starting state and the target state, the list of unreached slaves, and whether what follows is a resume or an honest failure
  • Resume only the steps after the confirmed state: ResumeRemainingSteps reads State() first, derives the gap from the low 4 bits, and then issues the steps one by one; steps that already succeeded are not re-run.
  • When the starting state cannot be read (base state 0), or the start or the target is Boot (0x03), it does not guess the remaining steps: it writes a WARNING saying that retrying only the failed step is not possible and falls back to the whole-sequence state change entry point, rather than pretending that a single step was retried.
  • When the confirmed state already is the target, it does not resume step by step and leaves the recheck to the whole-sequence entry point.
  • The resume budget is per call: perStepTimeoutMs is the total budget for the whole resume, and the elapsed time is checked before each step starts. When the budget is exhausted it returns false at once, so the worst case never multiplies into steps × budget.
  • No read, no success: AllSlavesAtTargetBaseState requires a non-empty slave list, an AL state readable for every slave, and low 4 bits equal to the target base state; any slave that fails to read gives false. It looks only at the base-state bits, not at the bit4 Error flag, and it does not judge the AL Status Code.
  • DescribeUnreachedSlaves reads the same per-slave AL state source as the previous method: no slaves, all arrived and a read failure each return a fixed message.
  • attempt and elapsedMs of LogStateRetryFailure are passed in by the caller (the method does not time anything itself); willRetry only changes the closing wording (resume the failed steps / no retries left, fail honestly). The log level is always WARNING.

Example:

using namespace darra::ethercat;

// Take over and finish the run yourself: first see how many steps are left, then run the remainder
auto steps = EtherCATMaster::BuildRemainingSteps(master.State(), EcState::OP);
printf("还差 %zu 步\n", steps.size()); // %zu steps remaining

if (!master.ResumeRemainingSteps(EcState::OP, 15000)) {
printf("续跑未到 OP,未到站: %s\n", // Resume did not reach OP, slaves not reached: %s
master.DescribeUnreachedSlaves(EcState::OP).c_str());
}

Start and stop control​

Start() / Stop()​

bool Start() const;   // Start the PDO loop thread
bool Stop() const; // Stop the PDO loop thread

Returns: bool — whether it succeeded

Asynchronous variants: darra::sugar::StartAsync(master) / StopAsync(master) return std::future<bool> without blocking the calling thread (see sugar).

Example:

master.SetState(EcState::OP);
master.Start(); // Start the PDO loop

// ... running ...

master.Stop(); // Stop the PDO loop
// Or let the destructor Dispose() it automatically (no Stop read-back confirmation)

Lifetime and orderly shutdown (Close / Dispose / the destructor) are covered in Initialization § RAII lifetime.

Runtime control​

CategoryMethodType or return typeRead/writeDescription
Runtime controlEtherCATMaster::AbortMaster(master_index)voidWrite-onlyAborts the blocking loop (scan / wait) running on that master without freezing the other masters; 0 = all masters (the caller is responsible for the 0 case). The entry point returns void, which only proves the abort request was issued, not that the blocking loop has exited
master_state::PausePdoKeepRt(master)boolWrite-onlyPauses the cyclic PDO LRW while keeping the runtime RT session and the standalone frame transactions (for maintenance / reconfiguration). true = handled as paused (an idempotent success on a master that was already stopped); false = invalid master index or SDK not ready (fail-closed). It withdraws only the cyclic send permission; it does not touch the mailbox SM configuration and does not clear diagnostic counters
Instance countingEtherCATMaster::ActiveInstanceCount()intRead-onlyNumber of master instances in this process that are initialized and not yet released: incremented when Build succeeds or when the object is constructed with an explicit index, decremented on Dispose / destruction; only instances created through this wrapper and initialized successfully are counted
EtherCATMaster::GetActiveInstanceCount()intRead-onlyNumber of master slots currently occupied on the runtime side (slot 0 counts too when it is occupied). This is not the same quantity as the local ActiveInstanceCount; when the two disagree, take the runtime reading
EtherCATMaster::MaxInstanceCount(dll)intRead-onlyMaximum number of masters the runtime allows at the same time: the smaller of the SDK limit and the number of available real-time cores; returns 0 when no real-time core is available. The dll parameter is retained for source compatibility only and does not affect the value
Safe shutdownEtherCATMaster::EmergencyCleanup(dll)voidWrite-onlyEmergency close of the NIC handles of all masters, as a fallback for a crash / an imminent process exit: it does not depend on object state, does not wait for threads to exit, and reports neither success nor failure. This entry point does not check for active masters, and the runtime's internal state cannot be recovered after the call — do not call it in the middle of a session
Stop()boolWrite-onlyWhen stopping the PDO cycle, issues a CiA402 safe stop to the slaves of this master automatically (Shutdown 0x0006; deceleration is set by the 0x0105 Shutdown Option Code) without affecting other masters
Instance counting members are static

All three instance-counting entry points are static methods and do not depend on a particular object. ActiveInstanceCount() and GetActiveInstanceCount() have similar names but measure different things: the first is a local counter in the C++ layer, the second reads the number of occupied slots from the runtime. When you investigate slots that were not released cleanly, look at the latter.

Do not pause PDO during a state transition

master_state::PausePdoKeepRt() only withdraws the cyclic send permission. Calling it while Init / PreOp / SafeOp / OP transitions are in progress cuts the cyclic frames off, and the slave's SM2 watchdog then drops the slave out of OP. To pause, wait until the state is stable.

Abort only means the request was issued

The void return of AbortMaster() only says the abort request was issued; whether the scan / wait really exits has to be observed in the state that follows.

Several masters in one process

To shut down a single master, use only that master's Stop(). A safe stop of all masters freezes the axes running on the other masters as well.

Example:

#include "ethercat.hpp"
using namespace darra;

master.SetState(EcState::OP);
master.Start();

// ... running ...

// Maintenance window: once the state is stable, pause the cyclic frames first and only then change the configuration
if (!ethercat::master_state::PausePdoKeepRt(master)) {
printf("暂停未被受理:主站索引非法或 SDK 未就绪\n"); // Pause not accepted: invalid master index or the SDK is not ready
}

// Abort scans / waits still blocking on this master (other masters are unaffected)
EtherCATMaster::AbortMaster(master.MasterNumber());

Asynchronous operation state​

Every asynchronous EtherCAT operation (BuildAsync / SetStateAsync / scans / SDO and so on) is queued per master and executed one at a time, so the same master never hits the bus concurrently. This group of entry points observes the queue state and lets you shut the asynchronous layer down before touching the configuration.

CategoryMethodType or return typeRead/writeDescription
Asynchronous operation stateEtherCATMaster::IsAsyncOperationInProgress()boolRead-onlyWhether any asynchronous operation is still queued or running; waiting in the queue counts, an operation whose result already exists and that is only waiting for future.get() does not. For observation only — do not use it for synchronisation control
EtherCATMaster::RequestAsyncShutdown()voidWrite-onlySets the shutdown gate flag and wakes operations still blocked inside lower-level calls; asynchronous operations submitted afterwards end with OperationCanceled before they reach the lower level
  • RequestAsyncShutdown() is one-way: there is no entry point that clears the flag again. To keep using asynchronous operations after it, you must create the master instance again.
  • Close() / Dispose() already go through this step; call it explicitly only when you want to stop the asynchronous layer first and then change something else (swap the configuration, rebuild the master, wind down the process).
  • After the shutdown, an asynchronous call fails by having future.get() throw darra::ethercat::OperationCanceled (also visible in the darra namespace) rather than returning false; catch that type to tell cancellation by shutdown apart from a real failure.

Example:

#include "ethercat.hpp"
using namespace darra;

if (master.IsAsyncOperationInProgress()) {
printf("仍有异步操作在排队或执行\n"); // Asynchronous operations are still queued or running
}

// Actively stop the async layer: async operations submitted from now on end with OperationCanceled
master.RequestAsyncShutdown();

try {
bool ok = master.SetStateAsync(EcState::OP).get();
} catch (const ethercat::OperationCanceled& e) {
printf("异步操作被关闭流程取消: %s\n", e.what()); // Asynchronous operation cancelled by the shutdown flow: %s
}

Process data watchdog (batch)​

Applies the process data / PDI watchdog timeout to all slaves in one call. The entry points live in darra::ethercat::master_other (master/other.hpp, pulled in by ethercat.hpp):

namespace darra::ethercat::master_other {

struct BatchWatchdogResult {
int AppliedCount = 0; // Number of stations written successfully (0 = not a single one)
bool SomeRaisedToSafetyFloor = false; // Some station in this batch was raised by the safety lower bound (actual value != requested value)
bool RejectedOverRegisterLimit = false; // The whole batch is refused for exceeding the limit (AppliedCount is then always 0)
};

BatchWatchdogResult set_all_watchdog(EtherCATMaster& m, uint32_t timeout_ms);
BatchWatchdogResult set_all_pdi_watchdog(EtherCATMaster& m, uint32_t timeout_ms);

}

Parameters: timeout_ms (uint32_t) — timeout in milliseconds; 0 = disabled, maximum 6553ms.

Return value semantics (same basis as the C SDK batch watchdog):

  • AppliedCount = the number of slaves the lower layer wrote successfully; slaves written with the raised actual value after the safety floor lifted them also count, so AppliedCount > 0 does not mean every slave was written with the requested value.
  • SomeRaisedToSafetyFloor = true (lower-layer criterion: the number of successfully written slaves is >0 and GetLastError()==0x20000011) — in this batch some slaves had a requested value that was too low and were lifted to the safety floor (5000 ms for branch slaves / 400 ms for slaves with PDO on the ring) and written with the raised value; to read the actual milliseconds per slave, use GetWatchdogConfig() with wd_time_pd / 10 (wd_time_pdi / 10 for PDI).
  • RejectedOverRegisterLimit = true — the request exceeds the 6553 ms register limit (u16 × 0.1 ms), so the whole batch is rejected and nothing is written (AppliedCount is always 0); it is neither truncated nor silently changed to 6553.
  • Both flags false and AppliedCount == 0 — invalid master index / no slaves under the master / the write failed.
  • AppliedCount == -1 — the SDK state is unavailable and no lower-level call happened (both flags are false in that case); to tell the cases apart, take the return value of DarraEcat_ShellStatus().
  • set_all_pdi_watchdog has no safety floor lift, so SomeRaisedToSafetyFloor is always false.

Example:

using namespace darra::ethercat;

auto r = master_other::set_all_watchdog(master, 100);
if (r.RejectedOverRegisterLimit)
printf("整批超 6553ms 上限, 一个都没写\n"); // The whole batch exceeds the 6553ms cap, nothing was written
else if (r.SomeRaisedToSafetyFloor)
printf("写入 %d 站, 但有站被安全下限抬升, 实际值逐站读 GetWatchdogConfig\n", r.AppliedCount); // Wrote %d slaves, but some slaves were raised to the safety lower bound; read GetWatchdogConfig slave by slave for the actual values
else
printf("按请求写入 %d 站\n", r.AppliedCount); // Wrote %d slaves as requested

Slave access​

GetSlave(index)​

Slave& GetSlave(uint16_t index);

Returns a slave reference (1-based index). It is cached internally, so repeated calls return the same object.

Example:

auto& s = master.GetSlave(1);

// Chained access to the protocol interfaces
auto data = master.GetSlave(1).GetCoE().SDORead(0x1018, 0x01);

// Whole-frame PDO snapshot (on the hot path, map once into the real-time process image with InputsMapping / OutputsMapping)
std::vector<uint8_t> inFrame;
darra::SlavePDO::CopyInputFrame(dll, master.MasterNumber(), 1, inFrame);

GetSlaves()​

std::vector<uint16_t> GetSlaves() const;

Returns the list of all slave indices (1-based).

Slave iterator — EtherCATMaster supports range-based for loops over the slaves:

for (auto slave : master) {
printf("从站 %d: VID=0x%08X\n", slave.SlaveNum(), slave.VendorId()); // Slave %d: VID=0x%08X
}
C++-specific sugar

To use STL algorithms, auto v = darra::sugar::slaves(master); gives you a SlavesView exposing begin()/end()/size()/empty(), ready to pass straight to std::count_if / std::find_if.

Slave state / identity:

auto& s = master.GetSlave(1);
EcState state = s.State();
EcALState al = s.ErrorCode();
bool ok = s.SetState(EcState::OP, 5000);

printf("VID=0x%08X PID=0x%08X Rev=0x%08X SN=0x%08X 名称=%s 可选=%s\n", // VID=0x%08X PID=0x%08X Rev=0x%08X SN=0x%08X name=%s optional=%s
s.VendorId(), s.ProductId(), s.RevId(), s.SerialNumber(),
s.Name().c_str(), s.IsOptional() ? "是" : "否");

Scan lifecycle​

The scan phase occupies the NIC channel temporarily and the SDK closes it out when the scan ends. The two static entry points below confirm the cleanup result and tell you whether the scan snapshot you hold was still written by your own scan.

CategoryMethodType or return typeRead/writeDescription
Scan lifecycleEtherCATMaster::CloseScanNic()intWrite-onlyCloses out the temporary NIC channel occupied by the scan phase without touching masters that are still running; 1 = fully closed, 0 = something is still left after a bounded wait, or the runtime is not ready (tell the two apart with DarraEcat_ShellStatus(); do not treat it as success)
EtherCATMaster::GetScannedSlaveGeneration()intRead-onlyScan snapshot generation: even = the snapshot is stable, odd = it is being written. A normal scan advances it by exactly 2; take one reading before and one after reading the snapshot, and if the two differ the snapshot was rewritten in between and the result is void
  • When the SDK is not ready, GetScannedSlaveGeneration() returns 0 (even), but that is a generation with nothing to judge, not proof that the snapshot is stable; check DarraEcat_ShellStatus() first.
  • The correct way to read a scan result: record the generation once before reading and once after, and use the data only when the two are equal and even. Different values mean another scan wrote in between, so the whole snapshot must be read again — never splice the two halves together.
  • After a normal scan the flow does not need a manual CloseScanNic(); call it explicitly only when you suspect the channel held by a previous temporary scan was not released (starting a new master right afterwards, or a rescan on another NIC being refused), and judge from the return value whether something really is left.

Example:

// Read the scan snapshot: take the generation before and after, they must match and be even
int genBefore = EtherCATMaster::GetScannedSlaveGeneration();
if ((genBefore & 1) == 0) {
// ... read the slave list ...
int genAfter = EtherCATMaster::GetScannedSlaveGeneration();
if (genBefore != genAfter)
printf("读取期间快照被改写,结果作废\n"); // The snapshot was overwritten during the read, so the result is invalidated
}

// Targeted clean-up when a temporary scan channel is suspected of not being fully released
if (EtherCATMaster::CloseScanNic() != 1)
printf("扫描通道仍有残留,先查 DarraEcat_ShellStatus()\n"); // Residue remains in the scan channel, check DarraEcat_ShellStatus() first

Batch SDO list​

Reads the object dictionary lists of several slaves in one call, pipelined within the batch, so the total time is close to reading one slave instead of growing linearly with the number of slaves.

CategoryMethodType or return typeRead/writeDescription
Batch SDO listEtherCATMaster::GetMultiSlaveSDOList(slave_indices, count, results)intRead-onlyReads the object dictionary lists of several slaves in one call and writes each slave's result pointer into the results array supplied by the caller; returns the number of slaves read successfully. count allows 1 to 16
EtherCATMaster::FreeMultiSlaveSDOList(results, count)voidWrite-onlyFrees the per-slave object dictionary list memory blocks allocated by the previous method and clears the matching results entries; must be used as a pair with GetMultiSlaveSDOList

Parameters (GetMultiSlaveSDOList):

  • slave_indices (const uint16_t*) — array of slave indices, 1-based, at least count entries long
  • count (uint32_t) — number of slaves, allowed range 1..16; anything outside that returns 0 immediately
  • results (void**) — pointer array prepared by the caller with at least count entries; the function writes each slave's object dictionary list pointer into results[i], and entries stay nullptr when the read failed or the slave does not support CoE

Returns:

  • int — the number of slaves read successfully, not count. Map back by index to slave_indices; a nullptr in results[i] means that slave was not read.

Ownership:

  • The pointer array container is prepared by the caller; the SDK allocates only the per-slave object dictionary list memory blocks.
  • When done you must call FreeMultiSlaveSDOList(results, count) on the whole set; do not free it with FreeMemory / free, and do not free only part of it. After the call the matching entries are cleared, and reading them again is a dangling access.

Example:

const uint16_t slaves[] = {1, 2, 3};
void* odLists[3] = {};

int okCount = master.GetMultiSlaveSDOList(slaves, 3, odLists);
printf("成功读取 %d/%d 个从站\n", okCount, 3); // Read %d/%d slaves successfully

for (int i = 0; i < 3; ++i) {
if (!odLists[i]) continue; // This slave does not support CoE or the read failed
// odLists[i] is the pointer to that slave's object dictionary list memory block
}

master.FreeMultiSlaveSDOList(odLists, 3); // Released in pairs

PDO frame loss statistics​

The master-level GetPDOFrameLossStats(group) and the PDOFrameLossStats structure are defined in exactly one place, Master diagnostics - communication and performance statistics, and are obtained through master.GetDiagnostics().GetPDOFrameLossStats(group). For the raw events, subscribe to PDOFrameLoss.

Sub-object access​

// Get the diagnostics object
auto& diag = master.GetDiagnostics();

// Get the configuration object
auto& config = master.GetConfig();

// Get the event set
auto& events = master.Events();

PDO cycle and DC configuration​

master.LoopCycle() and master.GetConfig().LoopCycle() read and write the same PDO cycle (nanoseconds); master.ConfigureDC(sync0Ns, sync1Ns = 0) configures every DC slave of that master. Recommended values, phase and troubleshooting are in Configuration § LoopCycle and DC configuration.

DC propagation delay resolution​

This group answers only when and how often a propagation delay resolution initiated by the SDK succeeded; it takes no part in DC configuration itself.

CategoryMethodType or return typeRead/writeDescription
DC propagation delay resolutionEtherCATMaster::DcPropagationDelayResolvedAtUtc()std::optional<std::chrono::system_clock::time_point>Read-onlyTime (UTC) of the most recent propagation delay resolution in this process that the SDK triggered itself and that succeeded; empty = no such resolution was observed in this process
EtherCATMaster::DcPropagationDelayResolveCount()intRead-onlyNumber of successful resolutions from the same bookkeeping; it shares the source with the previous method and accumulates separately per master index
  • Scope of the bookkeeping: the resolutions the SDK initiates itself and that succeed — ConfigureDC configuring slaves (return value greater than 0), and successful master_other::update_propagation_delays and master_other::auto_calculate_dc_shift (return value not less than 0). Internal measurements taken during automatic startup are not counted.
  • The timestamp is the moment of bookkeeping, not the moment the physical measurement happened.
  • The bookkeeping does not distinguish a fresh measurement from reusing a result already obtained in the session (the runtime does not expose that distinction), so do not infer how often something was re-measured from the count.
  • The count is kept per master index inside the process and is not reset when a master is rebuilt on the same index; to count the resolutions of a particular session, use the difference between two readings.

Example:

if (auto at = master.DcPropagationDelayResolvedAtUtc()) {
auto secs = std::chrono::duration_cast<std::chrono::seconds>(
at->time_since_epoch()).count();
printf("最近一次传播延迟解析: %lld (UTC epoch 秒)\n", (long long)secs); // Last propagation delay resolve: %lld (UTC epoch seconds)
}
printf("累计成功解析 %d 次\n", master.DcPropagationDelayResolveCount()); // %d successful resolves so far

Master state change callback​

master.OnStateChanged(cb) is a convenience wrapper around master.Events().OnStateChanged(cb) (same dispatch path, multiple subscribers); the callback has the shape void(EcState oldState, EcState newState). The event list and the multi-subscriber semantics are in Events.

master.OnStateChanged([](EcState oldS, EcState newS) {
printf("主站状态: %s -> %s\n", // Master state: %s -> %s
EcStateFormat::Format(oldS).c_str(),
EcStateFormat::Format(newS).c_str());
});

Hot-plug self-recovery​

When a slave is power-cycled and reappears or is replaced, the SDK recognises the identity mismatch by itself and enters a protected state, so a wrong device is not taken into the control loop.

acknowledge_slave_replacement​

namespace darra { namespace ethercat { namespace master_other {

bool acknowledge_slave_replacement(EtherCATMaster& m, uint16_t slaveIndex);

} } }

Confirms that the slave replacement is complete and makes the EtherCAT identification state machine probe that slave again.

When to call: after subscribing to master.Events().OnSlaveIdentityMismatch(...) and receiving an identity mismatch alarm, and after the operator has checked or replaced the device, call this function so the SDK probes again.

Behaviour:

  • If the identity is corrected (the right device is back / a newer Revision of the same model) → it recovers automatically and fires the SlaveOnline event
  • If the identity still does not match → it fires SlaveIdentityMismatch again and returns to the IDENT_REJECTED state

Parameters:

  • m (EtherCATMaster&) — master reference
  • slaveIndex (uint16_t) — slave index (1-based, matching the configuration)

Returns:

  • bool — true = accepted and the FSM was reset; false = invalid parameter, or the slave is not currently in the IDENT_REJECTED / FAILED state (calling before the SlaveIdentityMismatch event arrives returns false)
The event must arrive first

Calling this function before the SlaveIdentityMismatch event has fired has no effect. While the slave is not in the protected state the SDK keeps probing normally and no manual confirmation is needed.

Example:

using namespace darra::ethercat;

master.Events().OnSlaveIdentityMismatch(
[&](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("从站 %u 身份不符: 期望 V=0x%08X, 实际 V=0x%08X\n", si, eV, aV); // Slave %u identity mismatch: expected V=0x%08X, actual V=0x%08X

// UI dialog: "Please check the device on slave N, put the correct model back and click confirm"
if (ShowReplacementDialog(si)) {
bool ok = master_other::acknowledge_slave_replacement(master, si);
if (!ok) {
printf("确认失败: 从站不在 IDENT_REJECTED 状态\n"); // Acknowledgement failed: the slave is not in the IDENT_REJECTED state
}
}
});
How this differs from SlaveOffline/SlaveOnline
  • SlaveOffline (the slave lost power / was disconnected, identity still matches) → recovers automatically and fires SlaveOnline
  • 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 acknowledge_slave_replacement manually

Startup configuration verification​

The final check before entering OP: master_state::VerifyStartupConfiguration(master) checks the link, the per-slave state, AL errors and configuration validity in one call; any failure is appended to issues and sets valid=false, so the application layer does not have to poll each item.

namespace darra::ethercat::master_state {
struct StartupVerifyResult {
bool valid = true;
int slaveCount = 0;
std::vector<std::string> issues;
};
StartupVerifyResult VerifyStartupConfiguration(EtherCATMaster& m);
}

Call it after Build() and before SetState(OP); after switching to SafeOp you can call it once more to check the PDO mapping (alarms about absent IsOptional slaves have to be filtered by the application).

auto r = darra::ethercat::master_state::VerifyStartupConfiguration(master);
if (!r.valid) {
for (auto& issue : r.issues) printf(" - %s\n", issue.c_str());
}

Exception types​

The SDK throws only when a failure cannot be expressed through a return value; the exception is a denied CoE access (see the table below), which is thrown separately as CoEAccessDeniedException according to its semantics. Most Slave and protocol methods report failure with std::optional / bool.

CategoryTypeThrown whenKey membersDescription
GeneralDarraExceptionConfiguration / initialization errors that cannot be expressed through a return value (for example an invalid configuration in EtherCATMaster_FromJson)code() / what()Derives from std::runtime_error, lives in darra::ethercat
CoE accessCoEAccessDeniedExceptionAn SDO read / write is judged access denied: the device returns 0x06010000 (read or write), 0x06010001 (reading a write-only object), 0x06010002 (writing a read-only object); or the object descriptor passed to the check explicitly carries no permission bit for that direction; or (read only) the descriptor is known and the current AL state does not allow itIndex() / SubIndex() / IsReadOperation() / ObjAccess() / what()Lives in the darra namespace; the device abort code wins over the local permission bits; the other abort codes do not throw and still go through last_sdo_error() / SDOReadDetail.abort_code

Example (writing a read-only object):

try {
coe.SDOWriteU16(0x6041, 0, 0x0006); // StatusWord (0x6041) is read-only
} catch (const darra::CoEAccessDeniedException& e) {
printf("访问拒绝: idx=0x%04X sub=%u (%s)\n", e.Index(), e.SubIndex(), e.what()); // Access denied: idx=0x%04X sub=%u (%s)
}

StatusWord is a read-only object, so writing it is judged access denied: the device returns 0x06010002, or the local check finds the descriptor explicitly carrying no write permission bit — either way it throws CoEAccessDeniedException.

When an SDO Abort Code throws

0x06010000 / 0x06010001 (read) / 0x06010002 (write) mean "access denied": SDORead / SDOWrite throw CoEAccessDeniedException directly. The other abort codes (object / subindex does not exist, value out of range, timeout and so on) do not throw; report them faithfully with coe.last_sdo_error() or SDOReadDetail.abort_code. When the device returns an access-denied abort code the device wins, and the local permission bits of the object descriptor never override it; only when there is no device abort code are the descriptor bits and the AL state consulted, and an incomplete (unknown) descriptor is always let through, with the slave's abort code as the source of truth.

Failure return conventions​

CategoryCallReturnsFailure testDescription
BuildBuild()boolfalseFor the reason see LastError(); for a structured result use the BuildResult version
Typed SDO readSDOReadU16 / SDOReadU32 and so onstd::optional<T>std::nulloptInsufficient length also counts as a failure
Raw byte readSDOReadstd::vector<uint8_t>an empty vector is not necessarily a failureA successful read of an empty string is empty too; tell the cases apart with last_sdo_error() or SDOReadDetail
Write operationsSDOWrite and so onboolfalseFor the reason see last_sdo_error()
Detail overloadsSDOReadDetail / SDOReadDetailAsyncoutput parameters ok / abort_code / wkcjudge by ok onlyabort_code == 0 only means the device returned no abort code; it is not a success flag

For SDORead / SDOWrite, "access denied" is the exception to the table above: when the device returns 0x06010000 / 0x06010001 / 0x06010002 it throws CoEAccessDeniedException instead of returning a value; see Exception types.

For error code meanings and on-site troubleshooting steps see Error codes and troubleshooting.

Complete example​

#include "ethercat.hpp"
#include <cstdio>

using namespace darra;

int main() {
try {
// Create and initialise the master (Builder pattern)
EtherCATMaster master(dll);
master.SetNetwork("\\Device\\NPF_{...}");
master.Build();

printf("发现 %d 个从站\n", master.SlaveCount()); // Found %d slaves

// Configure DC
master.ConfigureDC(1000000); // SYNC0 = 1ms

// Switch to OP
master.SetState(EcState::OP);
master.Start();

// Set the PDO callback (register with SetPDOCallbackSync)
master.Events().SetPDOCallbackSync([&](uint16_t mi) {
std::vector<uint8_t> inFrame;
darra::SlavePDO::CopyInputFrame(dll, master.MasterNumber(), 1, inFrame);
});

// Read a slave SDO
auto& s = master.GetSlave(1);
auto vendorId = s.GetCoE().SDOReadU32(0x1018, 0x01);
if (vendorId) {
printf("VendorID: 0x%08X\n", *vendorId);
}

// Run
printf("运行中... 按 Enter 停止\n"); // Running... press Enter to stop
getchar();

} catch (const ethercat::DarraException& e) {
printf("错误: %s\n", e.what()); // Error: %s
return -1;
}
return 0;
}