Skip to main content

Initialization

Master indices start at 1

Master indices are ≥1; 0 is always invalid. The SDK creates a master context only for a valid index. With several masters, every API call must pass a valid index explicitly, and initialization must already be complete before the call.

Recommended approach

Initialize from a DENI file exported by the Darra configuration tool.
The DENI file carries the complete network configuration (NIC, slaves, PDO mapping, DC settings and so on), which keeps the configuration consistent and correct.
Managing device hardware with DENI files gives better compatibility across setups.

Constructors​

DarraEtherCAT()​

public DarraEtherCAT()

Parameterless constructor and the entry point to the fluent API. Configure it with SetENI() or SetNetwork(), then call Build() to initialize.

Example:

var master = new DarraEtherCAT()
.SetENI(@"C:\EtherCAT\MyProject.deni")
.Build()
.Master;

if (master == null)
{
Console.WriteLine("初始化失败"); // Initialization failed
return;
}

master.SetState(EcState.OP);

Fluent configuration​

SetENI(string eniPath)​

public DarraEtherCAT SetENI(string eniPath)

Load a DENI/ENI configuration file (deferred configuration, applied at build time). Build() hands the file contents to the SDK's unified configuration engine; the C# API does not expose a method of the same name.

Parameters:

  • eniPath (string) — DENI or ENI configuration file path

Example:

var master = new DarraEtherCAT()
.SetENI(@"C:\EtherCAT\MyProject.deni");

SetNetwork(NetworkInfo primary, NetworkInfo? redundant = null)​

public DarraEtherCAT SetNetwork(NetworkInfo primary, NetworkInfo? redundant = null)

Set the primary NIC and an optional redundant NIC from network interface objects (deferred configuration, applied at build time).

Parameters:

  • primary (NetworkInfo) — primary NIC information
  • redundant (NetworkInfo?) — redundant NIC information (optional)

SetNetwork(string primaryName, string? redundantName = null)​

public DarraEtherCAT SetNetwork(string primaryName, string? redundantName = null)

Set the primary NIC and an optional redundant NIC by NIC name (deferred configuration, resolved at build time).

Parameters:

  • primaryName (string) — primary NIC name or description
  • redundantName (string?) — redundant NIC name or description (optional)

Example:

var master = new DarraEtherCAT()
.SetNetwork("以太网 1"); // Ethernet 1

SetEsiFile(string filePath)​

public DarraEtherCAT SetEsiFile(string filePath)

Load a single ESI file (deferred configuration, applied at build time). Can be called several times.

note

When you use a DENI file, you usually do not need to load ESI files separately.

SetEsiFiles(string path)​

public DarraEtherCAT SetEsiFiles(string path)

Load a directory of ESI files (deferred configuration, applied at build time). Can be called several times.

EnableAutoStartup()​

public DarraEtherCAT EnableAutoStartup()

Mark the instance for automatic slave configuration (performed at build time).

note

When you use an ENI/DENI file, you usually do not need to call this method. Slaves that already have startup parameters are skipped completely; they are neither overwritten nor extended. This method applies only to slaves that are not configured (PDO/DC/startup parameters are generated automatically from ESI/MDP/SM).

Chained-call override rules

SetENI and SetNetwork can both set the NIC. When both are used, the method called later overrides the earlier conflicting configuration:

// SetENI comes later → the NIC configuration in the ENI file is used
var master = new DarraEtherCAT()
.SetNetwork("以太网 1") // Ethernet 1
.SetENI(@"C:\config.deni") // ← the NIC from the ENI overrides SetNetwork
.Build()
.Master;
// SetNetwork comes later → the NIC from SetNetwork overrides the ENI
var master = new DarraEtherCAT()
.SetENI(@"C:\config.deni")
.SetNetwork("以太网 1") // ← overrides the NIC in the ENI
.Build()
.Master;

Slave configuration, PDO mapping, DC settings and so on in an ENI/DENI file are always preserved; only the NIC configuration is subject to the override rules. EnableAutoStartup() applies only to slaves that are not configured; slaves already configured by the ENI/DENI file are skipped completely.

DisableAutoStartup()​

public DarraEtherCAT DisableAutoStartup()

Turn automatic configuration off explicitly. By default the first SetState enables AutoStartup automatically; this method cancels that automatic enablement (for ENI/DENI-only or test setups). Like EnableAutoStartup(), call it before Build(), and it also supports chained calls.

Example:

var master = new DarraEtherCAT()
.SetENI("config.deni")
.DisableAutoStartup()
.Build()
.Master;

Build​

Build()​

public BuildResult Build()

Build and initialize the master (terminal method). BuildResult converts implicitly to DarraEtherCAT? (the instance on success, null on failure) and also supports tuple deconstruction into (success, message). On failure the instance has already been released.

Recommended usage — chain the calls and test the result against null:

var master = new DarraEtherCAT()
.SetENI(@"C:\EtherCAT\config.deni")
.Build()
.Master;

if (master == null) return; // initialization failed
master.SetState(EcState.OP);

Extended usage — deconstruct the tuple when you need the detailed error message:

var master = new DarraEtherCAT()
.SetENI(@"C:\EtherCAT\config.deni");

var (success, message) = master.Build();
if (!success)
{
Console.WriteLine($"初始化失败: {message}"); // Initialization failed: {message}
return;
}
Console.WriteLine(message); // "Master initialised OK, N slaves scanned"

Async variant: BuildAsync(IProgress<string>? progress = null, CancellationToken cancellationToken = default) returns Task<BuildResult> and runs the same build sequence (connect → scan → configure) with progress callbacks and cancellation. Failure semantics match Build() (the instance has already been released); read result.Success / result.Message for the outcome.

LastError causes behind a 170 (device busy) init failure

Four driver-instance LastError values can come back with 170: 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. The Build() failure message already splits these causes automatically; the caller does not have to guess.

Validate()​

public ValidationResult Validate()

Pre-build configuration check; it does not perform the actual build. It checks that the ENI file exists, the master instance limit, and similar conditions.

Return value:

  • ValidationResult — contains the IsValid (bool) and Errors (IReadOnlyList<string>) properties

Example:

var master = new DarraEtherCAT().SetENI("config.deni");
var result = master.Validate();
if (!result.IsValid)
{
foreach (var error in result.Errors)
Console.WriteLine($"配置错误: {error}"); // Configuration error: {error}
return;
}
master.Build();

VerifyStartupConfiguration(bool strictMode = false)​

public StartupConfigurationVerifier.VerificationResult VerifyStartupConfiguration(bool strictMode = false)

Compare the loaded ENI configuration with the slave identities actually found by the scan, per ETG.1500 §5.5.2, and return a per-slave match report. When no XML configuration is loaded it returns Success=true directly. This is an initialization-time configuration check, usually called after Build().

Parameters:

  • strictMode (bool) — strict mode: also checks RevisionNo and SerialNo; default false (checks VendorId / ProductCode only)

Return value:

  • VerificationResult — four fields: Success / Errors / Warnings / SlaveDetails

Example:

var result = master.VerifyStartupConfiguration(strictMode: false);
if (!result.Success)
foreach (var err in result.Errors) Console.WriteLine(err);

Resource release​

Close()​

public void Close()

Close the master and clear the in-memory data, then stop the master and background data acquisition. Shutdown has an overall time limit, so it never hangs indefinitely.

Dispose()​

public void Dispose()

Release master resources and close the network connection. Implements the IDisposable interface.

CloseAsync() / DisposeAsync()​

public static Task CloseAsync(this DarraEtherCAT master, CancellationToken ct = default)
public static Task DisposeAsync(this DarraEtherCAT master, CancellationToken ct = default)

Async extensions of Close() / Dispose(): they run on a thread-pool thread and do not block the calling thread; ct is checked for cancellation before execution starts. Use them when a GUI closes a window so the UI does not freeze.

Example:

await master.CloseAsync();

NICs and scanning​

The public scan surface is organized in three layers: adapter selection → quick scan (batch / single-port) → full scan; cancel can interrupt at any time:

StepEntry pointWhat it does
SelectGetNetworkAdapters()Enumerates NIC identity / capability / binding / occupancy / link, optionally with a per-port slave count
Quick scanQuickScan()One verdict per candidate port: has slaves / empty / occupied / not measured / failed
Quick scan (single-port)QuickSlaveCount()Single-port shortcut of QuickScan() (internal quick-probe primitive, not a separate entry): count only, no EEPROM read
Full scanStandardScan()Reads EEPROM / topology per slave and returns the list of slaves that can be used; ScanAsync is its asynchronous form, not a third mode
CancelAbortScan()Aborts the scan in progress
The level of aggregation differs by language
  • Batch quick scan available: C# QuickScan(), Rust quick_scan_adapters(), native C public header DarraEcat_QuickScanAdapters().
  • Single-port quick scan only: C++ statics::QuickSlaveCount(), Python quick_slave_count(), Java NetworkInfo.quickSlaveCount() — collect per-port verdicts by looping over adapters.
  • Full scan has a matching entry in every language: C# StandardScan() / ScanSlaves(), C ScanSlaveInfo() / ScanSlaveInfoEx(), C++ statics::ScanSlaves(), Rust scan_slaves(), Python scan_slaves(), Java NetworkInfo.scanSlaves(); cancel goes through AbortScan everywhere.
  • Additional read-only members (they do not change the three layers above): C# additionally has QuickFindRedundantPairBatch (redundant pairing; returns an accumulated WKC total, not a slave count) and GetRingSlaveCount (ring slave count from the most recent topology calibration); the native C public header additionally has ReadSlaveInfo.

Adapter selection: GetNetworkAdapters(bool includeSlaveCount = false)​

public static NetworkAdapterInfo[] GetNetworkAdapters(bool includeSlaveCount = false)

One call returns the complete adapter list: NIC identity / capability / binding / occupancy / link, optionally with a per-port slave count. It is meant for building an adapter-selection UI; no extra API calls are needed to fill in fields.

Parameters:

  • includeSlaveCount (bool, default false) —
    • false: enumerate NICs only, without touching the bus. SlaveCount = 0, ScanStatus = NotMeasured (not measured, not an empty port).
    • true: quick-scan and count each port; the results are in SlaveCount + ScanStatus. The scan occupies the NIC temporarily and empty ports take longer; the following Build() / SetNetwork() takes over automatically, so no manual handling is needed.

Return value: NetworkAdapterInfo[] — an empty array (not null) when there are no NICs; if enumeration fails as a whole it throws InvalidOperationException (the inner exception is preserved) and never disguises a failed read as "no NICs". List order = ports usable as an EtherCAT main port first → more slaves first → link Up first.

NetworkAdapterInfo (category: NIC / diagnostics; access: all read-only):

CategoryMemberTypeAccessDescription
IdentityIndexintRead-onlyOrdinal after sorting (from 0), matching the list order; not guaranteed stable across calls
IdentityNamestringRead-onlypcap device name \Device\NPF_{GUID}, pass it to SetNetwork / StandardScan
IdentityDescriptionstringRead-onlyAdapter description (human-readable); may be empty
IdentityMacstringRead-onlyMAC address aa:bb:cc:dd:ee:ff; empty string when unavailable, see Error for the reason
IdentityDevicePathstringRead-onlyDevice path (same value as Name)
IdentityGuidstringRead-onlyBare NIC GUID (lowercase, no braces); empty string when unavailable
CapabilityEtherCatCapableboolRead-onlyWhether it can serve as an EtherCAT main port (physical wired 802.3 and not virtual / wireless / blocklisted); a missing protocol binding does not affect this field
BindingBoundProtocolboolRead-onlyWhether the real-time environment is configured (read-only; configuration is done by the official installer)
LinkLinkStatusOperationalStatusRead-onlyUp / Down / Unknown; Unknown = the system did not report it, do not treat it as online
OccupancyUsedByAnotherInstanceboolRead-onlyWhether another master instance in this process is using it
OccupancyOwnerMasterNumberushortRead-onlyMaster number of the owner; 0 when unused
ScanSlaveCountintRead-onlyMeaningful only with includeSlaveCount: true; read it together with ScanStatus (0 may be an empty port or may mean nothing was measured)
ScanScanStatusNicScanStatusRead-onlyFound / IdleNoSlave = measured; NotMeasured = not measured; OccupiedByMaster = occupied by a master and skipped by design (not a failure)
FailureErrorstringRead-onlyWhy this row cannot be used directly / which field could not be read; empty string = no error. Fields that cannot be read are never disguised as 0

Scan verdict classification NicScanStatus (category: scanning; read-only):

public enum NicScanStatus
{
NotMeasured, // not measured this round (not scanned / could not open the NIC) — not a 0-slave result
IdleNoSlave, // measured empty port: it was scanned and really has 0 slaves
Found, // measured with slaves
OccupiedByMaster, // a local master occupies this NIC, so the scan skips it by design (a fact, not a failure)
}

GetNetworkAdapters() lists all enumerable NICs with capability / binding / occupancy flags. It is read-only and does not write binding state.

Example:

var adapters = DarraEtherCAT.GetNetworkAdapters(includeSlaveCount: true);
foreach (var a in adapters)
{
if (!a.EtherCatCapable) continue;
string slaves = a.ScanStatus == NicScanStatus.Found ? $"{a.SlaveCount} 站"
: a.ScanStatus == NicScanStatus.IdleNoSlave ? "空口" // empty port (no slaves)
: "未测量"; // not measured
Console.WriteLine($"#{a.Index} {a.Description} [{a.LinkStatus}] {slaves}");
}

Quick scan: QuickScan(string[]? adapters = null)​

public static List<NicQuickScanRow> QuickScan(string[]? adapters = null)

One call returns the whole quick-scan table: one verdict per candidate port (measured with slaves / measured empty / skipped because a master occupies it / not measured / not selected / unsupported / aborted / failed). It answers only "does this port have slaves, and if not, why" and does not restate NIC properties.

Parameters:

  • adapters (string[]?) — scan only these ports (matched by NetworkAdapterInfo.Name, case-insensitive); null = scan every port usable as a main port; an empty array = scan none.

Return value: List<NicQuickScanRow> — an empty list (not null) when there are no NICs. If enumeration or the quick scan fails as a whole it throws InvalidOperationException (the inner exception is preserved) and never disguises a failed read as "no NICs".

NicScanState (category: scanning; read-only):

ValueNameSlaveCountMeaning
0HasSlaves≥ 1Measured with slaves
1EmptyBus0Measured empty port: it was scanned and really has 0 slaves
2OccupiedByMasternullA local master occupies this port, so the scan skips it by design (a fact, not a failure)
3NotMeasurednullNot measured (could not open the NIC / not part of this round); the reason is not broken down further
4NotScannednullThe adapters parameter did not select this port, so it was not scanned
5UnsupportednullThis port cannot serve as an EtherCAT main port, so it was not scanned
6AbortednullThe user called AbortScan() and aborted this round of scanning
7FailednullOther underlying negative code; the original value is in NativeCode

NicQuickScanRow (category: scanning; access: all read-only):

CategoryMemberTypeAccessDescription
IdentityNamestringRead-onlypcap device name \Device\NPF_{GUID}
VerdictStateNicScanStateRead-onlyVerdict for this round; when there is no number, this explains why
CountSlaveCountint?Read-onlynull = not measured; 0 = measured empty port. The two are strictly distinguished
PairingPeerIndexintRead-onlyIndex in the list returned by this call of the peer redundant ring port; -1 = single port / unpaired / not completed this round. When paired they point at each other: rows[rows[i].PeerIndex].PeerIndex == i
DiagnosticsNativeCodeintRead-onlyRaw code returned by the SDK: measured slave count / 0 (empty port) / -2 (not measured) / -3 (master-occupied); on a whole-round failure, the return code of the round
ResultOutcomeScanOutcomeRead-onlyEnum view of the native code, decoded with the quick-scan-specific table: >= 1 -> Success, 0 -> EmptyBus, -2 -> QuickScanNotMeasured, -3 -> QuickScanOccupiedByMaster; unclassified negative codes keep their raw value. A port that was not scanned does not mean an empty port - always use State
Not measured ≠ 0 slaves

SlaveCount == null only means not measured (occupied / not selected / unsupported / aborted / failed); it does not mean the bus is empty. To decide that a port is empty you must see State == NicScanState.EmptyBus. PeerIndex is meaningful only within the list returned by this call and is invalid across calls.

Example:

foreach (var row in DarraEtherCAT.QuickScan())
{
if (row.State == NicScanState.HasSlaves)
Console.WriteLine($"{row.Name}: {row.SlaveCount} 站, 对端口 #{row.PeerIndex}"); // {row.Name}: {row.SlaveCount} slaves, peer port #{row.PeerIndex}
else if (row.State != NicScanState.NotScanned && row.State != NicScanState.Unsupported)
Console.WriteLine($"{row.Name}: {row.State}(无站数结论, 底层码 {row.NativeCode})"); // {row.Name}: {row.State} (no slave count conclusion, native code {row.NativeCode})
}
Single-port quick count QuickSlaveCount(string adapterName)
public static int QuickSlaveCount(string adapterName)

Probe the slave count of a single NIC only (no EEPROM read); the DENI / drop-down count uses this path. It returns >= 0 = slave count (0 = measured empty port); a negative code is not a slave count — it is a native failure code and shares the same encoding as ScanSlaves: -1 opening the card / scan failed, -2 topology write transaction refused (this round's scan is incomplete), -3 scan is closing out (retry shortly); unclassified negative codes are returned as-is.

When the port is occupied by a master already running on this machine, this method returns the slave count that master knows (a non-negative snapshot) and does not report "occupied" as a negative code.

Do not read the negative codes here as the -2 not measured / -3 occupied by a master from the QuickScan() rows above — that encoding belongs only to NicQuickScanRow.NativeCode / Outcome; the two encodings must not be mixed. For a per-port verdict table and redundant pairing use QuickScan(); to select slaves use StandardScan().

Full scan: StandardScan(string adapter, string? secondary, out ScanOutcome outcome)​

public static List<ScannedSlaveInfo> StandardScan(string adapter, string? secondary,
out ScanOutcome outcome)

Standard (full) scan plus an outcome classification, for callers that want the scan and the verdict in one step. The scan reports an outcome in this order:

  • NIC name empty / port not in the list → ScanOutcome.AdapterNotFound (bus untouched)
  • Scan completed with exactly 0 slaves → ScanOutcome.EmptyBus (measured empty port, not a failure)
  • Enumeration itself failed / unclassified failure → ScanOutcome.Failed (not disguised as "adapter not found")
  • User called AbortScan() → ScanOutcome.Aborted
  • Underlying negative code → OpenFailed / TopologyXactRefused / ScanBusy / named NIC-open reason codes (-1201..-1206: OpenAccessDenied / OpenOccupied / OpenNotReady / OpenNicNotFound / OpenLinkDown / OpenBadMedia) / topology verdict TopologyLoop (-1208) / Failed (other unclassified negative codes)

Parameters:

  • adapter (string) — pcap device name of the primary NIC (of the form \Device\NPF_{GUID})
  • secondary (string?) — secondary NIC of the redundant ring; pass null for a single-port scan
  • outcome (out ScanOutcome) — outcome classification for this round

Return value:

  • List<ScannedSlaveInfo> — list of slave details. An empty list = the scan completed and the bus really has no slaves (ScanOutcome.EmptyBus, a normal outcome, not a failure); on scan failure the list is empty, see outcome for the reason.

Related structures:

public class ScannedSlaveInfo
{
// Basic identity
public int Index { get; } // slave index (1-based)
public string Name { get; } // device name
public uint VendorID { get; } // vendor ID
public uint ProductCode { get; } // product code
public uint RevisionNumber { get; } // revision number
public uint SerialNumber { get; } // serial number

// Addresses
public ushort ConfigAddr { get; } // configured address
public ushort AliasAddr { get; } // alias address

// Topology information
public ushort ParentIndex { get; } // parent slave index (0=the master is the parent)
public byte Topology { get; } // configuration-time structure classification snapshot : 0=NoLink / 1=endpoint / 2=line / 3=branch / 4=crossing; not the measured connection count of this cycle
public byte ActivePorts { get; } // active port bitmap
public byte EntryPort { get; } // entry port
public byte ParentPort { get; } // port number on the parent slave
public byte PhysicalType { get; } // physical port type

// Computed properties
public bool IsCoupler { get; } // whether it is a coupler
public string DeviceType { get; } // device type name (identified from vendor ID + product code; "未知设备" (SDK output, = unknown device) when it cannot be identified)
public int Depth { get; } // topology depth

// Physical port types
public int GetPortType(int port); // ports 0-3: 0 = not implemented / 1 = not configured / 2 = EBUS / 3 = MII; out of range returns -1
public int EntryPortType { get; } // physical type of the entry port, equal to GetPortType(EntryPort)
public int ParentPortType { get; } // physical type of the port on the parent slave that connects this device; -1 when there is no parent
public static string GetPortTypeString(int portType); // -1 = unknown / 0 = N/A / 1 = NC / 2 = EBUS / 3 = MII

// Formatted output
public string VendorIDHex { get; } // "0x..."
public string ProductCodeHex { get; } // "0x..."
public string RevisionNumberHex { get; } // "0x..."
public string ConfigAddrHex { get; } // "0x..."
public string AliasAddrHex { get; } // "0x..."
}

The port type value domain is fixed to 0 (not implemented) / 1 (not configured) / 2 (EBUS) / 3 (MII); -1 means unknown — an out-of-range port number, or a parent port that is the sentinel for "no parent slave", always returns -1 and never substitutes 0 for "not implemented". GetPortTypeString turns those values into display text and returns ? (原始值: n) (SDK output, = ? (original value: n)) for an unrecognised raw value.

Outcome classification:

public enum ScanOutcome
{
// ---- scan executed / decidable on the SDK side ----
Success = 0, // scan completed (possibly 0 slaves; the returned list length is the slave count)
AdapterNotFound = 1, // NIC name empty / port not in the list (bus untouched)
EmptyBus = 2, // StandardScan's refined classification for 0 slaves (scan completed, really 0 slaves, not a failure)
Aborted = 3, // the user called AbortScan() to abort this round
Failed = 4, // other unclassified failure
QuickScanNotMeasured = 5, // native quick-scan -2: genuinely not measured (open failed / not part of this round)
QuickScanOccupiedByMaster = 6, // native quick-scan -3: occupied by a local master, the scan skips it by design

// ---- underlying negative codes (the value is the underlying return code) ----
OpenFailed = -1, // could not open the NIC / invalid argument
TopologyXactRefused = -2, // topology write transaction refused, this round of scanning is incomplete
ScanBusy = -3, // the scan is winding down (previous round not drained), try again shortly
OpenAccessDenied = -1201, // driver security gate refused (Win32 5 ACCESS_DENIED)
OpenOccupied = -1202, // port occupied (Win32 170 BUSY)
OpenNotReady = -1203, // driver or NIC not ready (Win32 21 NOT_READY)
OpenNicNotFound = -1204, // card not in the driver NIC pool (Win32 1168/2/3)
OpenLinkDown = -1205, // port link down
OpenBadMedia = -1206, // not a wired-medium NIC, cannot be the EtherCAT primary port

TopologyLoop = -1208, // zero replies and a linear bus wired as a ring: remove the ring

ScanClosing = -3, // legacy alias of ScanBusy (same value)
}

ScanOutcome.Success only means the scan completed (possibly 0 slaves); EmptyBus is the refined classification StandardScan gives for 0 slaves. Decide an empty port by EmptyBus, not by Success alone.

Example:

var slaves = DarraEtherCAT.StandardScan(@"\Device\NPF_{...}", null, out var outcome);
switch (outcome)
{
case ScanOutcome.Success:
Console.WriteLine($"扫描完成: {slaves.Count} 个从站"); // Scan complete: {slaves.Count} slaves
break;
case ScanOutcome.EmptyBus:
Console.WriteLine("扫描完成,总线上没有从站"); // Scan complete, no slaves on the bus
break;
case ScanOutcome.AdapterNotFound:
Console.WriteLine("网卡名称为空或清单里没有这个口"); // NIC name is empty, or this port is not in the list
break;
default:
Console.WriteLine($"扫描失败: {outcome}"); // Scan failed: {outcome}
break;
}

Direct scan: ScanSlaves(string adapterName, string? secondaryAdapter = null)​

public static List<ScannedSlaveInfo> ScanSlaves(string adapterName, string? secondaryAdapter = null)
public static List<ScannedSlaveInfo> ScanSlaves(string adapterName, string? secondaryAdapter,
out ScanOutcome outcome)
public static List<ScannedSlaveInfo> ScanSlaves(string adapterName, string? secondaryAdapter,
out ScanOutcome outcome, out int nativeCode)

The raw entry point of the full scan: it scans topology and EEPROMs and returns the list of slaves that can be used. StandardScan in the full scan section above adds four SDK-side verdicts (AdapterNotFound / EmptyBus / Aborted / Failed) on top of it, so prefer StandardScan when "a scan plus one outcome code" is all you need; use this method when you need the raw return code of the scan interface itself.

Parameters:

  • adapterName (string) — pcap device name of the primary NIC; an empty value throws ArgumentException
  • secondaryAdapter (string?) — secondary NIC of the redundant ring; pass null for a single-port scan
  • outcome (out ScanOutcome) — outcome classification for this round
  • nativeCode (out int) — raw return code of the scan interface itself: >= 0 = slave count for this round (0 = empty bus, a normal outcome), < 0 = failure / winding-down code; an unclassified negative code is passed through unchanged, never flattened to -1

Return value:

  • List<ScannedSlaveInfo> — list of slaves. An empty list does not mean failure: it may be a measured empty port or a failed round, so always judge it together with outcome

Each round resets the scan error properties first, so a round that returns early before scanning never carries over the previous round's error code. On -3 (the scan is winding down) it neither retries nor reports "no slaves found"; it returns ScanOutcome.ScanBusy as it is, and the caller tells the user to try again shortly.

Example:

var slaves = DarraEtherCAT.ScanSlaves(adapterName, null, out var outcome, out int rawCode);
if (outcome != ScanOutcome.Success)
Console.WriteLine($"扫描未成功: {outcome}(原始码 {rawCode})"); // Scan did not succeed: {outcome} (raw code {rawCode})
else
Console.WriteLine($"扫描完成: {slaves.Count} 个从站"); // Scan complete: {slaves.Count} slaves

Async scan: ScanAsync(string adapterName, string? secondaryAdapter = null, CancellationToken cancellationToken = default)​

public static Task<List<ScannedSlaveInfo>> ScanAsync(
string adapterName, string? secondaryAdapter = null, CancellationToken cancellationToken = default)

The async form of the full scan: the scan runs on a background thread, await does not block the caller, and it returns the slave list (without the ScanOutcome classification). The cancellation token aborts the scan; concurrent ScanAsync calls in one process are serialized by the SDK automatically, so several scans do not compete for the same cache. An empty adapter name throws ArgumentException.

Example:

var slaves = await DarraEtherCAT.ScanAsync(@"\Device\NPF_{...}", cancellationToken: ct);
Console.WriteLine($"扫描到 {slaves.Count} 个从站"); // Found {slaves.Count} slaves

Cancel: AbortScan()​

public static void AbortScan()

Abort every scan in progress (both the synchronous entry points and ScanAsync). Use it to break a blocking network scan quickly when a window closes or the user cancels. An aborted scan reports ScanOutcome.Aborted in its outcome classification (for quick scans, NicScanState.Aborted); it never shows up as "no slaves found".

Example:

// scan on a background thread
var scanTask = Task.Run(() => DarraEtherCAT.StandardScan(adapterName, null, out _));

// the user clicks cancel
DarraEtherCAT.AbortScan();

Scan failure attribution​

When a scan fails you get more than a bare "no slaves found": the outcome code, the real reason the NIC could not be opened, and the raw error code are reported separately, so you can tell "the NIC did not open", "the port is occupied", "the link is not connected" and "the port really is empty" apart.

LastScanError​

public static ScanErrorKind LastScanError { get; }

The readable reason why the most recent ScanSlaves call failed to open the NIC, decoded from the raw system error code.

Return value:

  • ScanErrorKind — None (no error) / DriverDenied (access denied) / DriverMissing (the driver or the NIC does not exist) / DriverBusy (the port is occupied) / NicNotWired (not cabled or the link is unavailable) / Unknown (any other raw code; check the raw code and the log)

The scan runs on the calling thread and the value is thread-local, so reading it right after ScanSlaves returns gives that round's result. A successful scan with 0 slaves, and early returns that never tried to open the NIC (scan winding down / topology write transaction refused), all report None.

LastScanErrorCode​

public static int LastScanErrorCode { get; }

The raw system error code recorded when the most recent ScanSlaves call failed to open the NIC; 0 = no NIC-open error was recorded this round (for example the scan is winding down or the topology write transaction was refused).

Return value:

  • int — raw error code; 0 = nothing recorded

This property carries only "why the NIC did not open" and is not the same thing as the raw return value of the scan interface itself — the latter is passed back through ScanSlaves' out nativeCode (on success it is the slave count). When you display it, show the raw code together with the LastScanError classification so it can be matched against the log.

ClassifyScanFailure(ScanOutcome outcome)​

public static ScanFailureReason ClassifyScanFailure(ScanOutcome outcome)

Translates a scan outcome code into an actionable real cause, so the UI can give concrete guidance such as "restart", "use another port", "plug in the cable" or "retry shortly" instead of always reporting "scan failed".

Parameters:

  • outcome (ScanOutcome) — outcome classification returned by ScanSlaves / StandardScan

Return value:

  • ScanFailureReason — None = not a failure (success / empty bus / no scan was run); Unknown = unclassified, show the raw code and check the log; the remaining values are named causes: AccessDenied / OccupiedByOtherProcess / DriverNotReady / NicNotFound / LinkDown / UnsupportedMedia / TopologyXactRefused / ScanBusy

Unrecognised negative codes and the -1 returned by older versions all map to Unknown — show the raw code plus a pointer to the log rather than inventing a cause for the underlying layer. (int)outcome always equals the raw code and can be displayed as it is.

Example:

var slaves = DarraEtherCAT.ScanSlaves(adapterName, null, out var outcome);
if (outcome != ScanOutcome.Success)
{
var reason = DarraEtherCAT.ClassifyScanFailure(outcome);
Console.WriteLine($"扫描失败原因: {reason}(原始码 {(int)outcome})"); // Scan failure reason: {reason} (raw code {(int)outcome})
}

Full examples​

Scan entry points

The dynamic scan examples below use the traditional entry point GetNetworkInfo(); for the new adapter selection, quick scan, full scan and cancel entry points, see NICs and scanning.

Using a DENI file (recommended)​

var master = new DarraEtherCAT()
.SetENI(@"C:\EtherCAT\MyProject.deni")
.Build()
.Master;

if (master == null) return;

bool ok = master.SetState(EcState.OP, out string stateMsg);
Console.WriteLine(ok ? "运行中" : $"失败: {stateMsg}"); // running / failed: {stateMsg}

Scanning NICs dynamically​

var adapters = DarraEtherCAT.GetNetworkInfo();
var target = adapters.FirstOrDefault(a => a.SlaveNum > 0);
if (target == null) return;

var master = new DarraEtherCAT()
.SetNetwork(target)
.SetEsiFiles(@"C:\ESI")
.EnableAutoStartup()
.Build()
.Master;

if (master == null) return;

Redundancy mode (automatic redundant-pair detection)​

// GetNetworkInfo() probes ≥2 NICs with slaves for cross-NIC redundant pairs by default; both
// ends of a found pair have RedundantSlaveNum > 0 (ring-path WKC accumulated value, not a
// slave count; use it only to tell "redundant pair or not", never as "how many slaves on the ring").
var adapters = DarraEtherCAT.GetNetworkInfo();
var pair = adapters.Where(a => a.RedundantSlaveNum > 0).ToList();
if (pair.Count < 2) return; // no redundant pair found (single-port wiring)

var master = new DarraEtherCAT()
.SetNetwork(pair[0], pair[1])
.SetENI(@"C:\config.deni")
.Build()
.Master;

if (master == null) return;

Multiple instances (independent buses on separate NICs)​

Each master instance manages one independent EtherCAT bus on its own NIC. Creating a new instance needs no restart and takes effect immediately.

Multiple-instance requirements
  • Every 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 takes 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 one logging system without conflicts
// get all NICs that have slaves
var adapters = DarraEtherCAT.GetNetworkInfo()
.Where(a => a.SlaveNum > 0).ToList();

// instance 1 — bind the first NIC
var master1 = new DarraEtherCAT()
.SetNetwork(adapters[0])
.EnableAutoStartup()
.Build()
.Master;

// instance 2 — bind the second NIC (takes effect immediately, no restart)
var master2 = new DarraEtherCAT()
.SetNetwork(adapters[1])
.EnableAutoStartup()
.Build()
.Master;

if (master1 != null) master1.SetState(EcState.OP);
if (master2 != null) master2.SetState(EcState.OP);

// the instances run independently and do not interfere with each other
master1.Events.ProcessDataCyclicSync += (idx) => { /* PDO handling for bus 1 */ };
master2.Events.ProcessDataCyclicSync += (idx) => { /* PDO handling for bus 2 */ };

// closing returns the NIC and port automatically
master2.Close(); // after closing, adapters[1] can be used by a new instance

Multiple-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 per instance