Initialization and construction
Master indexes are ≥1; 0 is always invalid. With multiple masters, every API call must pass a valid index explicitly, and initialization must already be complete before the call.
Initializing from the DENI file exported by the Darra configuration tool is strongly recommended. The DENI file carries the complete network configuration (NIC, slaves, PDO mapping, DC settings and so on) and keeps that configuration consistent and correct.
NICs and scanning
The public scan surface is organized in three layers: NIC selection → quick scan (single-port) → full scan; cancel can interrupt at any time.
| Use | Entry point | Description |
|---|---|---|
| NIC selection | statics::GetNetworkInfo | Enumerates the NICs that can serve as the primary port; judge a candidate with ScanStatus / BoundProtocol |
| Quick scan | statics::QuickSlaveCount | Does not read the EEPROM, reports the count only; DENI / drop-down counts use this path. C++ has no batch quick-scan wrapper: the per-port verdicts come from the caller looping over the NICs (the raw C DarraEcat_QuickScanAdapters can also be used directly) |
| Full scan | statics::ScanSlaves | Reads the EEPROM / topology slave by slave, returns a list of ScannedSlaveInfo |
| Cancel | statics::AbortScan | Interrupts a running scan when a window closes or an operation is cancelled |
using namespace darra::ethercat;
// 1) Select a NIC
auto nics = statics::GetNetworkInfo(dll, /*need_slave_count=*/true);
for (const auto& nic : nics) {
if (nic.ScanStatus != NicScanStatus::Found) continue;
// 2) Quick scan
int quick = statics::QuickSlaveCount(dll, nic.Name);
// 3) Full scan
statics::ScanOutcome outcome;
int code = 0;
auto slaves = statics::ScanSlaves(dll, nic.Name, "", outcome, code);
printf("%s: 快扫 %d 站,完整扫描 %zu 站\n", // %s: quick scan %d slaves, full scan %zu slaves
nic.Description.c_str(), quick, slaves.size());
break;
}
// 4) Cancel
statics::AbortScan(dll);
Constructor
EtherCATMaster(dll)
explicit EtherCATMaster(dll_t& dll);
Creates a master instance. SetNetwork() and Build() must then be called to complete initialization.
Example:
using namespace darra;
EtherCATMaster master(dll);
Builder pattern initialization (recommended)
EtherCATMaster supports the chained Builder pattern: configure it with SetNetwork, SetENI and EnableAutoStartup, then call Build to complete initialization.
EtherCATMaster master(dll);
bool ok = master.SetNetwork("\\Device\\NPF_{...}")
.SetENI("C:/EtherCAT/config.deni")
.Build();
SetNetwork()
EtherCATMaster& SetNetwork(const std::string& primary, const std::string& redundant = "");
Sets the primary NIC and the optional redundant NIC. Returns a reference to itself so calls can be chained.
SetENI()
EtherCATMaster& SetENI(const std::string& path);
Registers the path of the ENI / DENI configuration file. Build() reads the file and hands it to master_other::load_config_json. Returns a reference to itself so calls can be chained.
The runtime loading paths for product DENI/ENI: SetENI / master_other::load_config_json. LoadEniFile is the offline structure read for standard ENI; LoadDeniFile parses only the legacy offline format and does not read product DENI. Configuration-saving / whole-package loading entry points are not user APIs; do not call them.
load_config_json()
int darra::ethercat::master_other::load_config_json(
EtherCATMaster& m, const std::string& json);
The configuration engine. Accepts JSON or DENI/ENI XML text. SetENI + Build() go through this entry point internally. A return value < 0 means failure.
Example:
int rc = darra::ethercat::master_other::load_config_json(master, xmlText);
if (rc < 0) return -1;
EnableAutoStartup()
EtherCATMaster& EnableAutoStartup();
Marks that slaves must be configured automatically. Returns a reference to itself so calls can be chained.
When an ENI / DENI file is used, this method is usually not needed. Slaves that already have startup parameters are skipped entirely; they are neither overwritten nor completed. The method only affects slaves that are not configured (PDO / DC / startup parameters are generated automatically from the ESI / MDP / SM).
MasterBuilder::Build() performs the automatic configuration while building; EtherCATMaster::Build() does not consume this flag at present. When automatic configuration is needed, use MasterBuilder instead, or call master_other::auto_configure_sm(m, 0) manually.
SetEsiFiles()
MasterBuilder& SetEsiFiles(const std::string& path);
Hand the ESI file or directory to the builder with SetEsiFiles(); Build() then loads it synchronously and completes slave binding. When a DENI file is already in use, passing it is usually unnecessary.
Validate()
ValidationResult Validate() const;
A pre-Build configuration check; it does not perform actual initialization. Returns the validation result, containing whether it passed and the list of errors.
Related structure:
struct ValidationResult {
bool IsValid; // Whether verification passed
std::vector<std::string> Errors; // Verification error list (empty on success)
};
Example:
auto result = master.Validate();
if (!result.IsValid) {
for (auto& err : result.Errors) printf("验证错误: %s\n", err.c_str()); // Validation error: %s
return -1;
}
master.Build();
Build()
bool Build();
Builds and initializes the master. Returns a bool indicating success. After a failure, read LastError() for the reason (driver not installed / not bound / the previous instance not released, and so on).
LastError() is a raw low-level code; do not branch on the number. Use the two helper entry points IsLastErrorTransient() (transient not-ready, retry later) and IsLastErrorBindingMissing() (the NIC is not bound / the driver is not loaded; rebind through the official installation flow, then retry). Failures on the stop / release path are reported separately through LastStopError() / StopFailureCount(), which do not overwrite LastError().
Four driver-instance LastError values can come back with 170 (device busy): 30 = RT real-time channels exhausted; 2 = the instance is still held by a live handle; 23 = the NIC is occupied by another master instance; 22 = the polling thread failed to start/rebuild. In addition, 20 = driver network initialization failure (the underlying NTSTATUS is passed through as-is) and 31 = the admission quota was exhausted, set by the polling thread after StartRT succeeded — neither of these is a 170 reply.
Async variants: darra::ethercat::BuildAsync(master) (optional progress callback / cancel token) returns std::future<bool>, BuildResultAsync(master) returns std::future<BuildResult>, and darra::sugar::BuildAsync(master) is the reduced form without a callback. None of them block the calling thread.
Example:
EtherCATMaster master(dll);
bool ok = master.SetNetwork("\\Device\\NPF_{...}")
.SetENI("C:/EtherCAT/config.deni")
.EnableAutoStartup()
.Build();
Static factory methods
EtherCATMaster_FromJson()
namespace darra::ethercat {
EtherCATMaster EtherCATMaster_FromJson(dll_t& dll, const std::string& json_config);
}
Initializes in one step from a JSON configuration string. Throws DarraException on failure.
EtherCATMaster_FromJsonFile()
namespace darra::ethercat {
EtherCATMaster EtherCATMaster_FromJsonFile(dll_t& dll, const std::string& path);
}
Initializes in one step from a JSON file. Throws DarraException on failure.
InitializeSpecificMaster()
static std::optional<EtherCATMaster> InitializeSpecificMaster(dll_t& dll, uint16_t masterIndex);
Initializes the master with the given index. Unlike Build(), this method specifies the master index instead of allocating one automatically (0 is not allowed). Returns std::nullopt on failure.
Standalone MasterBuilder class
namespace darra::ethercat {
class MasterBuilder {
public:
explicit MasterBuilder(dll_t& dll);
MasterBuilder& SetNetwork(const std::string& primary, const std::string& secondary = "");
MasterBuilder& SetENI(const std::string& path);
MasterBuilder& SetEsiFiles(const std::string& path);
MasterBuilder& EnableAutoStartup();
MasterBuilder& SetRevisionMatch(ScanRevisionMatchMode mode);
BuildResult Build();
};
}
A standalone builder that returns a BuildResult structure.
Related structure:
struct BuildResult {
bool Success; // Whether it succeeded
std::string Message; // Descriptive message
uint16_t MasterIndex; // A valid index on success, 0xFFFF on failure
};
Example:
using namespace darra::ethercat;
auto result = MasterBuilder(dll)
.SetNetwork("\\Device\\NPF_{...}")
.SetENI("config.deni")
.Build();
if (result.Success) printf("主站索引: %d\n", result.MasterIndex); // Master index: %d
RAII lifetime
EtherCATMaster follows RAII: Build() creates the master and the destructor releases it automatically. There is no need to call Dispose() manually.
{
EtherCATMaster master(dll);
master.SetNetwork("\\Device\\NPF_{...}");
master.Build();
master.SetState(EcState::OP);
master.Start();
} // Leave the scope, the destructor Disposes automatically
Dispose()
void Dispose();
Releases the master resources manually. The destructor calls it automatically, so a manual call is usually unnecessary.
Close() (free function)
namespace darra::ethercat {
void Close(EtherCATMaster& m);
}
Orderly shutdown: first StopChecked(2000) to confirm the PDO cycle has stopped, then Dispose(). Destroying the object directly skips Stop; reclaiming while the PDO cycle is still running can trigger a NIC release conflict. A stop failure inside Close does not throw a second exception; it is recorded in LastStopError() / StopFailureCount(). Calling Close again on a master that is already Disposed is a no-op.
darra::ethercat::Close(master); // Stop -> Dispose
Move semantics
EtherCATMaster supports move construction but forbids copying, which keeps resource ownership unique.
EtherCATMaster master1(dll);
EtherCATMaster master2 = std::move(master1);
// master1 is now invalid, master2 owns the resources
Container storage:
auto master = std::make_unique<EtherCATMaster>(dll);
master->SetNetwork("\\Device\\NPF_{...}");
master->Build();
Multiple instances
Each EtherCATMaster instance manages its own EtherCAT bus on a different NIC. Creating a new instance needs no restart; it takes effect immediately.
- Every instance must use a different NIC — one NIC cannot be used by several instances at the same time
- CPU cores are assigned automatically — each instance occupies different CPU cores
- Mailbox Gateway ports are offset automatically — each instance is assigned a different port number
- All instances share the same logging system
Scan entry points in detail
Full description of the four entry points; for the order (NIC selection / quick scan / full scan / cancel) see NICs and scanning.
By default only physical wired ports bound to the real-time driver are listed. Virtual NICs, WiFi and TAP do not appear. USB wired NICs such as ASIX are kept as physical wired ports. Do not treat an unbound port as a primary-port candidate (see BoundProtocol).
statics::GetNetworkInfo()
namespace darra::ethercat::statics {
std::vector<NetworkInfo> GetNetworkInfo(dll_t& dll, bool need_slave_count = false);
}
Gets the NIC list (the main entry point for NIC selection). With need_slave_count=true it also fills SlaveCount and ScanStatus for every port. An empty list means enumeration ran to completion but no NIC is available; a failed enumeration throws DarraException and is never folded into an empty list.
Related structure:
struct NetworkInfo {
std::string Name; // pcap adapter name (pass to SetNetwork / ScanSlaves)
std::string Description; // NIC description
std::string MacAddress; // MAC address (aa:bb:cc:dd:ee:ff)
int SlaveCount = 0; // Number of slaves scanned (valid only when need_slave_count=true); 0 when it was not measured
int BoundProtocol = 0; // Whether the real-time driver is bound (1=bound, 0=not bound)
NicScanStatus ScanStatus = NicScanStatus::NotMeasured; // Outcome classification of this scan
bool OccupiedByMaster() const; // Whether the scan was skipped because this station's master occupies the NIC (a fact, not a failure)
};
enum class NicScanStatus {
NotMeasured, // Not measured this round (not part of the scan / could not open the NIC) - not 0 slaves
IdleNoSlave, // Measured empty port: it was scanned and really has 0 slaves
Found, // Measured with slaves
OccupiedByMaster, // This station's master occupies the NIC, so the scan is skipped by design (a fact, not a failure)
};
| Category | Member | Type | Read/write | Description |
|---|---|---|---|---|
| Scan verdict | ScanStatus | NicScanStatus | read-only | Verdict classification for this NIC in this scan; when SlaveCount == 0 it tells a measured idle port from "not measured" |
| Scan verdict | OccupiedByMaster() | bool | read-only | Equivalent to ScanStatus == NicScanStatus::OccupiedByMaster; an occupied port was not scanned again, which does not mean the bus has no slaves |
| Slave count | SlaveCount | int | read-only | Holds the real slave count only; it is 0 when nothing was measured — see ScanStatus for the reason |
While a master is linked, the NIC it is using may not be bound again by a scan. The SDK skips that port by design and marks it
NicScanStatus::OccupiedByMaster. Such a port is not scanned again: SlaveCount == 0 only means
"not measured", not that the bus is empty; to get its slave count, read SlaveCount() on that master instance.
When polling, use ScanStatus to tell the three kinds of 0 apart: IdleNoSlave (genuinely idle port) /
OccupiedByMaster (skipped because occupied) / NotMeasured (nothing measured).
The slave count alone cannot distinguish "measured: no slaves" from "nothing measured on this port this round". When a verdict matters, read ScanStatus: only NicScanStatus::IdleNoSlave is a measured idle port; OccupiedByMaster / NotMeasured both mean nothing was measured, so 0 alone cannot establish that the bus is empty.
Example:
using namespace darra::ethercat;
auto adapters = statics::GetNetworkInfo(dll, /*need_slave_count=*/true);
for (const auto& a : adapters)
printf("%s: %d 个从站 (status=%d)\n", // %s: %d slaves (status=%d)
a.Description.c_str(), a.SlaveCount, static_cast<int>(a.ScanStatus));
statics::QuickSlaveCount()
namespace darra::ethercat::statics {
int QuickSlaveCount(dll_t& dll, const std::string& adapter);
}
Fast probe of the slave count on one NIC (does not read the EEPROM); DENI / drop-down counts use this path. A return >= 0 = slave count (0 = measured idle port); a negative value is a reason code / failure, not a slave count, and must not be read as 0 slaves. For a per-port verdict use GetNetworkInfo(need_slave_count=true); to select slaves use ScanSlaves().
statics::ScanSlaves()
namespace darra::ethercat::statics {
// Three parameters: throws ScanException on failure, returns the list on success
std::vector<ScannedSlaveInfo> ScanSlaves(
dll_t& dll, const std::string& primary, const std::string& secondary = "");
// Five parameters: no exception, also gives the outcome classification
std::vector<ScannedSlaveInfo> ScanSlaves(
dll_t& dll, const std::string& primary, const std::string& secondary,
ScanOutcome& outcome, int& native_code);
}
A standalone scan that does not create a master. An empty list means the scan completed normally and the bus genuinely has no slaves; failures are classified through ScanOutcome (Success / OpenFailed / TopologyXactRefused / ScanClosing / named card-open reasons OpenAccessDenied..OpenBadMedia(-1201..-1206)/ topology verdict TopologyLoop(-1208)) and are never folded into an empty list. The three-parameter overload throws ScanException on failure.
using namespace darra::ethercat;
statics::ScanOutcome outcome;
int native_code = 0;
auto slaves = statics::ScanSlaves(dll, primary, "", outcome, native_code);
if (outcome == statics::ScanOutcome::Success) {
// The scan ran to completion; an empty slaves list means an empty bus, not a failure
}
Async variant: darra::ethercat::ScanAsync(dll, primary, secondary, token) returns std::future<std::vector<statics::ScannedSlaveInfo>> and does not block the calling thread; several ScanAsync calls in one process are serialized automatically.
statics::AbortScan()
namespace darra::ethercat::statics {
bool AbortScan(dll_t& dll);
}
Aborts all scans in progress. A return of true only means the request was issued on a ready SDK; it does not mean the scan has stopped. false = the SDK is not ready and the request was not issued.
The abort flag is sticky: statics::ScanSlaves does not reset it automatically, so after a cancel you must first call statics::ResetScanAbort(dll) to scan again (it also returns bool; false = not ready, request not issued). When an async ScanAsync is cancelled with a CancelToken, the SDK performs "abort → take effect → reset" itself, so neither entry point needs to be called manually.
Example:
// User clicked cancel / closed the window
statics::AbortScan(dll);
Full example
#include "ethercat.hpp"
using namespace darra;
using namespace darra::ethercat;
int main() {
try {
EtherCATMaster master(dll);
master.SetENI("C:/EtherCAT/MyProject.deni").Build();
master.SetState(EcState::OP);
master.Start();
printf("主站 %d: %d 个从站\n", master.MasterNumber(), master.SlaveCount()); // Master %d: %d slaves
getchar();
} catch (const DarraException& e) {
printf("错误: %s\n", e.what()); // Error: %s
return -1;
}
return 0;
}