Initialization
Master index ≥1; 0 is always invalid. The underlying layer creates a master context only in the range from 1 to the maximum master count minus 1; passing 0 makes initialization return 0xFFFF (invalid index). With multiple masters, every API must be passed a valid index explicitly, and initialization must already have completed before the call.
Using a DENI file exported by the Darra configuration tool for initialization is strongly recommended. The DENI file contains the complete network configuration (ports, slaves, PDO mapping, DC settings and so on), which ensures the configuration is consistent and correct. Managing device hardware with a DENI file gives better compatibility and portability.
NICs and scanning
The main scan flow is organized in three layers: NIC selection → quick scan (batch / single-port) → full scan; cancel can interrupt at any time. A count-only full scan and the batch quick scan are described under Scan entry details below.
| Purpose | Entry point | Description |
|---|---|---|
| NIC selection | enumerate_network_info(is_redundant, need_slaves_num) | Enumerates the NICs that can serve as the primary port; use scan_status / slave_count() to decide which one really has slaves |
| Quick scan | EtherCATMaster::quick_slave_count(adapter) | Count only, no EEPROM read; the DENI / drop-down count uses this path |
| Full scan | scan_slaves(primary, secondary) | Reads EEPROM / topology slave by slave and returns a ScannedSlaveInfo list |
| Cancel | EtherCATMaster::abort_scan() | Interrupts the scan in progress when the user cancels or closes the window; can be called from any thread |
use darra_ethercat::{enumerate_network_info, scan_slaves, EtherCATMaster};
// 1) NIC selection: scan_status distinguishes "measured empty port" from "not measured"
let nics = enumerate_network_info(false, true)?;
let nic = nics.iter().find(|n| n.slave_count().unwrap_or(0) > 0); // None = the slave count cannot be read; treated as 0
if let Some(nic) = nic {
// 2) Quick scan: does not read EEPROM
let quick = EtherCATMaster::quick_slave_count(&nic.name)?;
// 3) Full scan: reads EEPROM and gets the slave list
let slaves = scan_slaves(&nic.name, None)?;
println!("快扫 {} 站, 完整扫描 {} 站", quick, slaves.len()); // Quick scan {} stations, full scan {} stations
}
// 4) Cancel: call from the UI / another thread
EtherCATMaster::abort_scan();
Besides the four entry points of the main flow, the scan surface has two supplementary members:
| Purpose | Entry point | Description |
|---|---|---|
| Batch quick scan | EtherCATMaster::quick_scan_adapters(names) | Produces one conclusion per port for a set of NIC names supplied by the caller (including the ring peer index and whether the port can serve as primary); read-only, does not take over the bus |
| Scan diagnostics | EtherCATMaster::last_scan_os_error() | Operating-system error code of the most recent full scan failing to open the NIC; 0 = nothing recorded |
The division of labour between enumerate_network_info() and quick_scan_adapters(): the former enumerates candidate NICs itself (answering "which ports on this machine can serve as primary"), while the latter does not enumerate at all — it only scans the names you give it (answering "what is the conclusion for each of these ports") and returns the whole batch of rows in one call.
Factory methods
EtherCATMaster::from_json_file()
pub fn from_json_file(path: &str) -> Result<Self>
Initializes the master in one step from a JSON configuration file (internally it performs network binding, configuration loading, state transition and startup in sequence).
from_json_file() parses JSON only — passing a DENI/ENI (XML) file returns DarraError::ConfigLoadFailed(-1). To load a DENI, use EtherCATMaster::builder().set_eni(...).
Parameters:
path(&str) — path to the JSON configuration file
Returns:
Result<Self>— on success, a started master instance; on failure, an error
Example:
use darra_ethercat::EtherCATMaster;
// Windows
let master = EtherCATMaster::from_json_file(r"C:\EtherCAT\config.json")?;
// Linux
let master = EtherCATMaster::from_json_file("/opt/ethercat/config.json")?;
println!("主站索引: {}, 从站数: {}", master.index(), master.slave_count()); // Master index: {}, slave count: {}
EtherCATMaster::from_json()
pub fn from_json(json_config: &str) -> Result<Self>
Initializes the master in one step from a JSON configuration string. Same as from_json_file(), but it takes the configuration string directly.
Parameters:
json_config(&str) — configuration string in JSON format
Returns:
Result<Self>— a started master instance
JSON configuration format:
{
"adapter": "\\Device\\NPF_{YOUR-GUID}",
"adapter_redundant": "",
"target_state": "OP",
"cycle_time_ns": 1000000
}
Example:
let config = r#"{"adapter": "\\Device\\NPF_{...}", "target_state": "OP"}"#;
let master = EtherCATMaster::from_json(config)?;
EtherCATMaster::new()
pub fn new() -> Result<Self>
Initializes a new master instance (manual configuration mode). The returned master index is assigned automatically by the SDK. You must call set_network() and set_state() manually to complete the configuration.
Returns:
Result<Self>— master instance
Example:
use darra_ethercat::{EtherCATMaster, EcState};
let mut master = EtherCATMaster::new()?;
master.set_network(r"\Device\NPF_{YOUR-GUID}", "")?;
master.set_state(EcState::Operational)?;
master.start();
EtherCATMaster::with_index()
pub fn with_index(master_index: u16) -> Result<Self>
Initializes the master instance at the specified index. Used in multi-instance management scenarios.
Parameters:
master_index(u16) — master index to use
Returns:
Result<Self>— master instance
Builder configuration
The product entry point is fluent configuration through EtherCATMaster::builder(). Network configuration goes through set_eni / load_config_json, and ESI goes through set_esi_file. utils::xml is pub(crate); there is no public save_xml / load_and_apply / apply_xml. Saving the configuration / startup snapshot uses a bounded wait inside the master self-healing window (second-level upper limit, short polling); on timeout it returns an error and does not hang for long.
After the fluent configuration is complete, build synchronously with build(); with the async-tokio feature, build_async(progress, cancel) is available (parameters Option<ProgressFn> / Option<CancelToken>, returns Result<BuildResult>), and the build can report progress and be cancelled.
set_eni()
pub fn set_eni(self, path: &str) -> Self
Sets the ENI/DENI configuration file path (takes effect at build()).
Parameters:
path(&str) — ENI/DENI configuration file path
Returns:
Self— the builder itself, so calls can be chained
Example:
let result = EtherCATMaster::builder()
.set_eni(r"C:\EtherCAT\MyProject.deni")
.build()?;
set_esi_file()
pub fn set_esi_file(self, path: &str) -> Self
set_esi_file() accepts an ESI file or a directory (distinguished automatically at build() via is_dir()); it can be called several times and takes effect at build().
Parameters:
path(&str) — ESI file path, or directory path
Returns:
Self— the builder itself, so calls can be chained
When a DENI is already used (set_eni), there is usually no need to load the ESI separately.
set_network()
pub fn set_network(self, primary: &str, redundant: Option<&str>) -> Self
Sets the primary port and the optional redundant port (takes effect at build()).
Parameters:
primary(&str) — device path of the primary portredundant(Option<&str>) — redundant port; passNonewhen there is no redundancy
Returns:
Self— the builder itself, so calls can be chained
set_eni() and set_network() are two mutually independent settings; the order of the chained calls does not change the result. build() always applies the configuration file first (selecting and binding the NIC per the port declaration in the file), then binds the port given to set_network() — when both are set, the set_network() port is what gets bound in the end. DENI content such as slaves / PDO / DC is always preserved.
enable_auto_startup()
pub fn enable_auto_startup(self) -> Self
At build time, slaves that do not yet have startup parameters are configured automatically. Slaves that already have startup parameters from the ENI/DENI are skipped.
Builder preflight checks
validate()
pub fn validate(&self) -> ValidationResult
Validates whether the current configuration is reasonable before calling build(). It does not perform actual initialization; it only checks the configuration parameters.
Returns:
pub struct ValidationResult {
pub is_valid: bool, // whether the configuration is valid
pub errors: Vec<String>, // error message list (empty means no errors)
}
Example:
let builder = EtherCATMaster::builder()
.set_eni("config.deni");
let result = builder.validate();
if !result.is_valid {
for err in &result.errors {
println!("配置错误: {}", err); // Configuration error: {}
}
} else {
let build_result = builder.build()?;
}
Resource release (RAII)
EtherCATMaster implements the Drop trait and automatically performs Stop + Dispose to release resources when it goes out of scope.
{
let mut master = EtherCATMaster::new()?;
master.set_network(adapter, "")?;
master.set_state(EcState::Operational)?;
master.start();
// ... use the master
} // master goes out of scope; Stop + Dispose run automatically
dispose() / dispose_async()
pub fn dispose(&mut self)
// async-tokio feature:
pub async fn dispose_async(&mut self) -> Result<()>
Releases the master resources manually (without waiting for Drop). After the call the master no longer owns the resources, and a later Drop does not release them twice. dispose_async() has the same semantics; it goes through the asynchronous serial gate and can be awaited. If the release fails it honestly returns Err and does not falsely report that resources were released.
Multi-instance management
Each master instance manages an independent EtherCAT bus and uses a different NIC. Creating a new instance takes effect immediately and needs no restart.
- Each instance must use a different NIC — the same NIC cannot be used by several instances at once; the SDK detects and blocks duplicate binding automatically
- CPU cores are assigned automatically — each instance automatically occupies a different CPU core; no manual setting is needed
- Mailbox Gateway ports shift automatically — each instance is assigned a different port number automatically
- Logs are shared — all instances share the same logging system without conflict
Scan entry details
Complete description of the scan entry points, including the count-only full scan, the batch quick scan and abort reset; for the order NIC selection / quick scan / full scan / cancel, see NICs and scanning.
enumerate_network_info()
pub fn enumerate_network_info(is_redundant: bool, need_slaves_num: bool) -> Result<Vec<EnumeratedNetworkInfo>>
Uses the SDK's own NIC enumeration (the result can be passed to set_network directly); with need_slaves_num=true it also returns the slave count and scan conclusion for each port.
pub struct EnumeratedNetworkInfo {
pub name: String,
pub description: String,
pub slave_num: i16, // slave count; when not measured / occupied by a master read scan_status, and do not treat 0 as an empty bus
pub redundant_slave_num: i16, // redundancy pair conclusion (ring pair path WKC), not a slave count; do not subtract it from slave_num to infer the branch slave count
pub bound_protocol: i16,
pub scan_status: NicScanStatus, // classification of this scan's conclusion (see the table below)
}
pub enum NicScanStatus {
NotMeasured, // not measured this time (did not take part in the scan / the NIC could not be opened) — this is not 0 slaves
IdleNoSlave, // measured empty port: the scan ran and there really are 0 slaves
Found, // measured with slaves
OccupiedByMaster, // a local master occupies this NIC; the scan is skipped by design (a fact, not a failure)
}
impl EnumeratedNetworkInfo {
pub fn occupied_by_master(&self) -> bool; // whether the scan was skipped because a local master occupies it
pub fn slave_count(&self) -> Option<i32>; // None when not measured; 0 is not used as a stand-in
}
| Category | Member | Type | R/W | Description |
|---|---|---|---|---|
| Scan conclusion | scan_status | NicScanStatus | Read-only | Classification of this scan's conclusion for the NIC; when slave_num == 0 it distinguishes "measured empty port" from "not measured" |
| Scan conclusion | occupied_by_master() | bool | Read-only | Equivalent to scan_status == NicScanStatus::OccupiedByMaster; an occupied port was not rescanned, which does not mean the bus has no slaves |
| Slave count | slave_count() | Option<i32> | Read-only | Holds the real slave count only; None when not measured, and scan_status gives the reason |
When a master has already established a link, the NIC it is using cannot be taken over by a scan again. The SDK skips that port by design and marks it
NicScanStatus::OccupiedByMaster. Such ports are not rescanned: slave_num being 0 only means
"not measured" and does not mean the bus is empty (slave_count() returns None for negative values); to get its slave count, read the
slave_count() of that master instance (the snapshot of the master currently using this NIC).
When polling, use scan_status to distinguish the three kinds of 「0」: IdleNoSlave (truly empty port) /
OccupiedByMaster (skipped because occupied) / NotMeasured (not measured).
quick_slave_count()
pub fn quick_slave_count(adapter: &str) -> Result<i32>
Fast slave count (does not read EEPROM). The DENI / drop-down count uses this path. To get slave details, use scan_slaves(). The count must not be discarded as 0.
Parameters:
adapter(&str) — network adapter name
Returns:
Result<i32>— detected slave count
quick_scan_adapters()
pub fn quick_scan_adapters(names: &[&str]) -> Result<Vec<QuickScanRow>>
Performs one read-only quick scan over a set of NIC names and returns one conclusion row per port in the order given. It does not take over the bus, changes no slave state, and needs no existing master instance.
Division of labour with enumerate_network_info(): enumerate_network_info() enumerates candidate NICs itself (answering "which ports on this machine can serve as primary"); quick_scan_adapters() does not enumerate — it only scans the names you give it (answering "what is the conclusion for each of these ports") and returns the whole batch of rows in one call.
Non-Windows platforms do not provide the quick-scan aggregation yet: each row honestly returns QuickScanState::OtherFailure with slave_count as None, and never passes itself off as 「0 slaves」.
Parameters:
names(&[&str]) — list of NIC names to scan; the returned rows correspond to it one-to-one
Returns:
Result<Vec<QuickScanRow>>— one row per port; the slave count isNonewhen not measured, andNonemust not be treated as 0 slaves
Related structures:
pub struct QuickScanRow {
pub state: QuickScanState, // Outcome classification for this port
pub peer_index: Option<u16>, // Index in names of the NIC on the other side of the ring; None = single port / no peer
pub native_code: i32, // Underlying raw code, for diagnostics (e.g. >=1 measured stations / 0 empty port / -2 not measured / -3 busy)
pub slave_count: Option<i32>, // Measured station count; None = not measured or the master is busy (never passed off a known count)
}
pub enum QuickScanState {
HasSlaves, // There are slaves
EmptyPort, // Measured empty port
MasterOccupied, // This station's master occupies the NIC, skipped by design
NotMeasured, // Not measured
NotScanned, // Not scanned
NotPrimaryCapable, // Not physically wired / empty name, cannot be used as the primary port
Interrupted, // Aborted by the scan
OtherFailure, // Other failure
Unrecognized(i16), // Unclassified
}
Errors:
namesempty →Err(DarraError::InvalidParameter(...))- A name contains an embedded null byte →
Err(DarraError::InvalidParameter(...)) - The batch exceeds the size limit, or this quick scan is rejected →
Err(DarraError::InvalidParameter(...))(the message carries the return code)
Example:
use darra_ethercat::EtherCATMaster;
let names = [r"\Device\NPF_{NIC-A}", r"\Device\NPF_{NIC-B}"];
let rows = EtherCATMaster::quick_scan_adapters(&names)?;
for (i, row) in rows.iter().enumerate() {
println!("口 {i}: {:?}, 站数 {:?}", row.state, row.slave_count); // Port {i}: {:?}, station count {:?}
}
scan_slave_count() / scan_slave_count_redundant()
pub fn scan_slave_count(adapter: &str) -> Result<i32>
pub fn scan_slave_count_redundant(primary: &str, secondary: &str) -> Result<i32>
Returns only the slave count after a full scan (which reads EEPROM); use it when per-slave details are not needed, and use scan_slaves() when you need the list. Both are associated functions and need no existing master instance.
Parameters:
adapter(&str) — network adapter nameprimary(&str) /secondary(&str) — primary / secondary port of the redundancy ring; an emptysecondary= single-port scan
Returns:
Result<i32>— slave count.Ok(0)= the scan ran to completion and the bus really has no slaves, a normal conclusion rather than a failure.
Errors:
- Underlying negative codes are passed through as-is via
DarraError::NetworkFailed(code):-1failed to open the NIC,-2the topology write transaction was rejected,-3the scan is closing (retry shortly); other negative codes are preserved as they are. - A NIC name containing a null byte returns
Err(DarraError::InvalidParameter(...)).
quick_slave_count() does not read EEPROM and only aims at speed; scan_slave_count() / scan_slave_count_redundant() are full scans (they read EEPROM), take longer, and produce the same conclusion as scan_slaves().
scan_slaves()
pub fn scan_slaves(primary: &str, secondary: Option<&str>) -> Result<Vec<ScannedSlaveInfo>>
Performs a full scan and returns the slave list (single-port / redundancy alike). When the count is valid the list must not be empty: while scan details are not ready, a "slave N" placeholder keeps the count.
With the async-tokio feature there is also EtherCATMaster::scan_async(adapter, secondary, cancel): an asynchronous version of the same scan that can be awaited and takes an Option<CancelToken> to cancel.
Parameters:
primary(&str) — primary network adapter namesecondary(Option<&str>) — redundant network adapter name;Noneor an empty string = single-port scan
Returns:
Result<Vec<ScannedSlaveInfo>>— slave list. AnOkemptyVec= empty bus: the scan completed normally and the bus really has no slaves, so it is not a failure.
Errors:
Err(DarraError::NetworkFailed(...))when the scan cannot start;Err(DarraError::InvalidParameter(...))whenprimaryis empty / contains a null byte.
Related structures:
pub struct ScannedSlaveInfo {
pub index: u16, // slave index (1-based)
pub vendor_id: u32, // vendor ID
pub product_code: u32, // product code
pub revision: u32, // revision number
pub serial: u32, // serial number
pub name: String, // device name
pub config_addr: u16, // configuration address
pub alias_addr: u16, // alias address
pub parent_index: u16, // parent slave index (0 = the master is the parent node)
pub topology: u8, // configuration-time structure classification snapshot : 0=NoLink / 1=endpoint / 2=line / 3=branch / 4=cross; not the connection count measured in this cycle
pub active_ports: u8, // active port bitmap
pub entry_port: u8, // entry port
pub parent_port: u8, // port number on the parent slave
pub physical_type: u8, // physical port type
}
Outcome classification:
pub enum ScanOutcome {
Success(i32), // scan completed, value = slave count (0 = truly empty bus)
OpenFailed, // opening the NIC failed / invalid parameter
TopologyXactRefused, // the topology write transaction was rejected; this scan round is incomplete
ScanClosing, // the scan is closing; retry shortly
Unknown(i32), // unclassified failure (raw value kept; -1208 takes this branch)
}
impl ScanOutcome {
pub fn is_success(self) -> bool; // whether the scan completed normally (then 0 slaves = truly empty bus)
pub fn is_unknown(self) -> bool; // whether it is an unclassified failure
}
-1208 (zero responses and the linear bus has been wired as a ring) shows up on ScanOutcome as Unknown(-1208) (not a named variant); failure_reason_of(-1208) decodes to ScanFailureReason::TopologyLoop — this is a wiring verdict; the remedy = leave the OUT port of the last slave unconnected again, the opposite of OpenLinkDown (-1205, cable not connected).
When a DENI file is used, the scan result from the set_network() stage is matched and verified against the configuration in the DENI automatically. The matching policy is controlled by config.scan_revision_match (RevisionID is ignored by default). If the network topology does not match the DENI, set_state() returns a detailed error message.
abort_scan()
pub fn abort_scan()
Aborts all scan operations in progress (static method). Use it to interrupt a blocking network scan quickly when closing a window or cancelling an operation.
Example:
use std::thread;
// scan in a background thread
let handle = thread::spawn(|| {
darra_ethercat::scan_slaves(r"\Device\NPF_{...}", None)
});
// the user clicks cancel
EtherCATMaster::abort_scan();
let _ = handle.join();
reset_scan_abort()
pub fn reset_scan_abort()
Clears the scan-abort flag left behind by abort_scan(). The abort interrupts only the current scan round; the flag stays set, so call this to reset it before the next scan, otherwise the new scan is interrupted by the same flag immediately.
Returns: nothing.
If the abort flag belongs to another scan round that is still running, this clear is rejected (the cancellation is kept), so one mistaken call cannot void someone else's cancel request.
Example:
// Cancel the current scan -> reset the flag -> start the next round
EtherCATMaster::abort_scan();
EtherCATMaster::reset_scan_abort();
let count: i32 = EtherCATMaster::quick_slave_count(r"\Device\NPF_{...}")?;
last_scan_os_error()
pub fn last_scan_os_error() -> i32
The operating-system error code left by the most recent full scan (scan_slave_count() / scan_slaves()); it has a value only when opening the NIC failed. 0 = no NIC-open error was recorded this round. It is a raw operating-system code, not the SDK's closed error enum, so do not interpret it through the DarraError branches; for the scan outcome classification see ScanOutcome.
Returns:
i32— operating-system error code;0= nothing recorded (a successful scan of an empty bus, the scan closing, and a rejected topology write transaction can all be 0)
Note: the value is recorded by the thread that started the scan, so it is meaningful only when read right after the scan returns; do not read it across threads to judge another thread's round.
Full example
Using a DENI/JSON file (recommended)
The example below uses the JSON path. A DENI file is XML; load it with set_eni().
use darra_ethercat::EtherCATMaster;
let master = EtherCATMaster::from_json_file(r"C:\EtherCAT\MyProject.json")?;
println!("主站索引: {}, 从站数: {}", master.index(), master.slave_count()); // Master index: {}, slave count: {}
// master is released automatically when it goes out of scope
Scanning NICs dynamically
use darra_ethercat::{enumerate_network_info, EtherCATMaster, EcState};
let nics = enumerate_network_info(false, true)?;
let target = nics.iter().find(|n| n.slave_count().unwrap_or(0) > 0); // None = the slave count cannot be read; treated as 0
if let Some(nic) = target {
let mut master = EtherCATMaster::new()?;
master.set_network(&nic.name, "")?;
master.set_state(EcState::Operational)?;
master.start();
}
Redundancy mode
use darra_ethercat::{enumerate_network_info, EtherCATMaster, EcState};
let adapters = enumerate_network_info(true, false)?;
let mut master = EtherCATMaster::new()?;
master.set_network(&adapters[0].name, &adapters[1].name)?;
// once the two NICs are wired, redundancy is enabled automatically by topology detection + RedProcessdata; there is no manual switch.
master.set_state(EcState::Operational)?;
master.start();
Multiple instances (independent buses per NIC)
use darra_ethercat::{enumerate_network_info, EtherCATMaster, EcState};
let adapters = enumerate_network_info(false, false)?;
// instance 1 — bind the first NIC
let mut master1 = EtherCATMaster::new()?;
master1.set_network(&adapters[0].name, "")?;
master1.set_state(EcState::Operational)?;
master1.start();
// instance 2 — bind the second NIC (takes effect immediately, no restart needed)
let mut master2 = EtherCATMaster::new()?;
master2.set_network(&adapters[1].name, "")?;
master2.set_state(EcState::Operational)?;
master2.start();
// each instance runs independently and does not interfere with the others
master1.events().on_pdo_cyclic_sync(|_| { /* PDO cycle handling for bus 1 */ });
master2.events().on_pdo_cyclic_sync(|_| { /* PDO cycle handling for bus 2 */ });
// the NIC and port are returned automatically on release
drop(master2); // after release, adapters[1] can be used by a new instance
Multi-instance resource allocation:
- NIC — each instance uses a different NIC
- CPU core — each instance is automatically assigned a different dedicated core
- Mailbox port — each instance is automatically assigned an incrementing port number
- Worker threads — independent for each instance