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 starting at 1. 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 contains 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 and generality.

Factory methods​

EtherCATMaster instances are created through static factory methods; the new constructor is not used.

EtherCATMaster.create()​

public static EtherCATMaster create()
public static EtherCATMaster create(short masterIndex)

Create a master instance; this is the entry point to the fluent API. The parameterless overload assigns the index automatically, the other overload sets it explicitly. Configure the instance with setENI() or setNetwork(), then call build() to initialize it.

Returns:

  • EtherCATMaster — master instance

Example:

EtherCATMaster pending = EtherCATMaster.create()
.setENI("C:\\EtherCAT\\MyProject.deni");
EtherCATMaster.BuildResult result = pending.build();
// judge success by success alone: when the configuration is missing or the file cannot be read,
// master is null; when the slave count is 0 success is also false, but master still points to the current instance
if (!result.success) {
System.out.println("初始化失败: " + result.message); // Initialization failed: {result.message}
return;
}
EtherCATMaster master = result.master;
master.setState(EcState.OP);

EtherCATMaster.createFromJsonFile(String jsonFilePath)​

public static EtherCATMaster createFromJson(String jsonConfig)
public static EtherCATMaster createFromJsonFile(String jsonFilePath)

Initialize the master in one step from a JSON configuration. The full sequence of initialization, network configuration and state transition runs automatically.

Example:

try (EtherCATMaster master = EtherCATMaster.createFromJsonFile("C:\\config.json")) {
System.out.println("从站数量: " + master.slaveCount()); // Slave count:
}

Fluent configuration​

setENI(String path)​

public EtherCATMaster setENI(String path)

Load a DENI/ENI configuration file (deferred configuration, applied at build time).

Parameters:

  • path (String) — DENI or ENI configuration file path

Example:

EtherCATMaster master = EtherCATMaster.create()
.setENI("C:\\EtherCAT\\MyProject.deni");

setNetwork(String primary, String secondary)​

public int setNetwork(String adapter)                          // returns the slave count; -1 = failure
public int setNetwork(String adapter, String redundantAdapter) // returns the slave count; -1 = failure

Bind the NIC and scan immediately, and return the number of slaves found (-1 = failure; read the failure reason with getLastError()). It returns int, so it cannot be chained; for fluent configuration, call setENI(...) first, or call build() separately after setNetwork(...).

Example:

EtherCATMaster master = EtherCATMaster.create();
int count = master.setNetwork("\\Device\\NPF_{...}");
if (count < 0) {
System.err.println("绑定网口失败: " + master.getLastError()); // Failed to bind the network interface:
return;
}

// redundancy mode
int count2 = master.setNetwork("\\Device\\NPF_{primary}", "\\Device\\NPF_{secondary}");

setEsiFile(String path)​

public EtherCATMaster setEsiFile(String path)

Load a single ESI file (deferred configuration, loaded at build()). 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 EtherCATMaster setEsiFiles(String path)

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

enableAutoStartup()​

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

2.5.x automatic MDP orchestration

From 2.5.x, once enableAutoStartup() is enabled, the master detects and configures modular devices (MDP) automatically on entering OP (GCAN-8200 and others), reads the detected modules and sends the matching startup parameters.

Who decides the NIC

setENI and setNetwork take effect at different times: setNetwork(...) binds the NIC and scans immediately (it returns the slave count synchronously and cannot be chained), while setENI(...) only records the path and is read at build(). Therefore the order in which the two calls are written does not change the execution order.

When both are used, the NIC declared in the configuration file is the one that finally takes effect — when build() loads the configuration, it selects and binds the NIC according to that declaration; only when no NIC can be selected from the configuration is the NIC bound earlier by setNetwork(...) kept.

EtherCATMaster master = EtherCATMaster.create();
int count = master.setNetwork("以太网 1"); // binds the port and scans immediately
master.setENI("C:\\config.deni"); // only records the path; read at build()
BuildResult result = master.build(); // selects and binds the NIC declared by the DENI

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

Build​

build()​

public BuildResult build()

Build and initialize the master (terminal method). The sequence is: validate the configuration → load ESI (setEsiFile / setEsiFiles are queued; a failure does not block the build) → load the ENI → match ESI devices automatically (when slaves have been scanned and the ESI is in the library) → configure automatically.

Returns:

  • BuildResult — contains the master instance, the slave count, the success flag and the message

BuildResult structure:

public static class BuildResult {
public final boolean success; // whether it succeeded (false when the slave count is 0)
public final int slaveCount; // slave count
public final short masterIndex; // master index
public final String message; // success/failure message
public final EtherCATMaster master; // master instance (null when the configuration is missing / the file cannot be read; still the current instance when the slave count is 0)
}

Example:

EtherCATMaster m = EtherCATMaster.create().setENI("C:\\EtherCAT\\config.deni");
m.setNetwork("\\Device\\NPF_{...}");
BuildResult result = m.enableAutoStartup().build();

if (!result.success) {
System.out.println("初始化失败: " + result.message); // Initialization failed: {result.message}
return;
}

EtherCATMaster master = result.master;
master.setState(EcState.OP);

validate()​

public ValidationResult validate()

Pre-build configuration check; it does not perform the actual build. It checks whether a NIC or ENI configuration has been set and whether the ENI path is an empty string (it does not read the file and does not create an instance).

Returns:

  • ValidationResult — contains the IsValid (boolean) and Errors (List<String>) fields

Example:

EtherCATMaster master = EtherCATMaster.create().setENI("config.deni");
EtherCATMaster.ValidationResult result = master.validate();
if (!result.IsValid) {
for (String error : result.Errors) {
System.out.println("配置错误: " + error); // Configuration error:
}
return;
}
master.build();

State.verifyStartupConfiguration()​

public Map<String, Object> verifyStartupConfiguration()   // com.darra.ethercat.master.State

Check the actual startup configuration after the build: master state/link → ESC state of each slave → AL status code → runtime configuration check. Compared with validate(): validate() only looks at whether the call chain is complete (before the build), while this method requires build() to have run and reads the current hardware values. Suggested after setState(EcState.OP) fails, so the per-item Chinese details locate the blocking point directly.

Returns:

  • valid (boolean) — whether everything passed
  • slave_count (int) — number of detected slaves
  • issues (List\<String\>) — failure details (in Chinese, ready to display)

Example:

State stateMgr = new State(master.MasterIndex);
Map<String, Object> result = stateMgr.verifyStartupConfiguration();

if (!(boolean) result.get("valid")) {
@SuppressWarnings("unchecked")
List<String> issues = (List<String>) result.get("issues");
issues.forEach(System.err::println);
}

Resource release​

close()​

@Override
public void close()

Close the master, clear in-memory data and stop the master and data acquisition threads. Implements the AutoCloseable interface and supports try-with-resources.

try (EtherCATMaster master = EtherCATMaster.create()) {
master.setNetwork("\\Device\\NPF_{...}");
master.setState(EcState.OP);
master.start();
// ...
} // released automatically

stop()​

public void stop()

Stop the master and the PDO threads but keep the instance (it can be started again later).

NICs and scanning​

NIC selection → quick scan → full scan → cancel.

Feature overview​

StepEntry pointWhat it does
NIC selectionNetworkInfo.getAvailableNetworksEnumerates the physical wired NICs that can serve as a primary port, optionally with a per-port slave count
Quick scanNetworkInfo.quickSlaveCountSlave count of a single NIC, without reading the EEPROM; the DENI / drop-down count uses this path
Full scanNetworkInfo.scanSlavesReads the EEPROM / topology per slave and returns the list of slaves that can be selected
CancelNetworkInfo.abortScanAborts the scan in progress

The old entry points are no longer provided; migrate new code to the entries above. Java exposes only the single-port quick scan quickSlaveCount() (no batch quick-scan wrapper); loop over adapters for per-port verdicts.

NIC selection​

NIC enumeration scope

By default only physical wired ports already configured for the real-time environment are listed. Virtual NICs, WiFi and TAP are not included. USB wired NICs such as ASIX are kept as physical wired ports. Do not treat unbound ports as primary-port candidates (see isBoundProtocol()).

NetworkInfo.getAvailableNetworks(boolean isRedundant, boolean needSlavesNum)​

public static List<NetworkInfo> getAvailableNetworks(boolean isRedundant, boolean needSlavesNum)
public static List<NetworkInfo> getAvailableNetworks()

Get the NIC list. By default it contains only physical wired ports configured for the real-time environment. With needSlavesNum=true the slave count of each port is scanned as well. The parameterless overload does not scan slave counts.

Parameters:

  • isRedundant (boolean) — whether to filter for redundant network adapters
  • needSlavesNum (boolean) — whether to detect the slave count on each NIC (requires a scan; slower)

Returns:

  • List<NetworkInfo> — list of network adapter information; an empty list = there really is no usable physical wired port

Exceptions:

  • NetworkInfo.NetworkScanException — thrown when enumeration or reading the scan result fails, or when the runtime library is not loaded; a failure is not folded into an empty list

Related structures:

public class NetworkInfo {
public String getName() // adapter system name (used by setNetwork)
public String getDescription() // adapter description (human-readable)
public String getMacAddress() // MAC address
public Integer getSlaveCount() // slave count (requires needSlavesNum=true); null when not measured
public Integer getRedundantSlaveCount() // redundant ring pair verdict = ring-path WKC, not a slave count; 0 = single-port wiring
public Boolean isBoundProtocol() // whether it is configured for the real-time environment
public NicScanStatus getScanStatus() // verdict classification of this scan (see below)
public boolean isOccupiedByMaster() // whether the scan was skipped because a local master occupies it (a fact, not a failure)
public boolean isUp() // whether the NIC is online

public static final class NicScanStatus { // Immutable value object (not an enum)
public static final NicScanStatus NOT_MEASURED; // not measured this round (not part of the scan / could not open the NIC) — not 0 slaves
public static final NicScanStatus IDLE_NO_SLAVE; // measured empty port: it was scanned and really has 0 slaves
public static final NicScanStatus FOUND; // measured with slaves
public static final NicScanStatus OCCUPIED_BY_MASTER; // a local master occupies this NIC, so the scan skips it by design (a fact, not a failure)

public int nativeCode(); // -2 / 0 / 1 (FOUND = >=1 slave) / -3; unclassified negative codes are raw values
public boolean isUnknown(); // Unclassified raw negative code (negative values other than -2 / -3)
}
}

Distinguishing the three kinds of 0:

  • IDLE_NO_SLAVE — measured empty port: it was scanned and really has 0 slaves
  • OCCUPIED_BY_MASTER — a local master is using this port, so the scan skips it by design; it does not mean the bus is empty
  • NOT_MEASURED — not measured this round (not part of the scan / could not open the NIC)

Unclassified codes are not folded: other negative codes (for example -1 / -4 / -1201) are kept as raw values — nativeCode() is the raw code, isUnknown() is true, and they are never folded into NOT_MEASURED. FOUND only means at least 1 slave; read getSlaveCount() for the actual count.

Master occupancy is not a failure

When a master is already running, the NIC it is using cannot be reopened by a scan. The SDK skips that port by design and marks it NicScanStatus.OCCUPIED_BY_MASTER. Such ports are not rescanned: a getSlaveCount() of null/0 only means "not measured" and does not mean the bus is empty; to get their slave count, read the master's own master.slaveCount() (a read-only snapshot).

Example:

List<NetworkInfo> adapters = NetworkInfo.getAvailableNetworks(false, true);
for (NetworkInfo a : adapters) {
Integer count = a.getSlaveCount();
if (count == null || count == 0) continue;
// getRedundantSlaveCount() is the ring-path WKC, not a slave count: use it only to tell "redundant pair or not",
// do not subtract it from count as a branch slave count (read the topology model after the master is built for ring coverage)
boolean redundantPair = a.getRedundantSlaveCount() != null && a.getRedundantSlaveCount() > 0;
System.out.println(a.getDescription() + ": " + count + " 个从站" + (redundantPair ? " (冗余环对)" : " (单端口)")); // {count} slaves (redundant ring pair / single port)
}

Quick scan​

NetworkInfo.quickSlaveCount(String adapterName)​

public static int quickSlaveCount(String adapterName)

Fast slave count (no EEPROM read). The DENI / drop-down count uses this path. To select slaves, use the full scan NetworkInfo.scanSlaves(...).

Parameters:

  • adapterName (String) — primary network adapter name; must not be null or an empty string

Returns:

  • int — detected slave count; 0 = measured empty port (a normal outcome, not a failure)

Exceptions:

  • NetworkInfo.NetworkScanException — thrown when the underlying call returns a negative error code or the runtime library is not loaded; it never returns 0 to pass as a normal result
  • IllegalArgumentException — adapterName is null or an empty string

Example:

int count = NetworkInfo.quickSlaveCount("\\Device\\NPF_{...}");
System.out.println("快扫从站数: " + count); // Quick-scan slave count: {count}

Full scan​

NetworkInfo.scanSlaves(String primary, String secondary)​

public static List<ScannedSlaveInfo> scanSlaves(String primary, String secondary)
public static List<ScannedSlaveInfo> scanSlaves(String primary) // single port

Full scan (reads the EEPROM / topology) that returns the list of slaves available for selection. When the count is valid the list must not be empty (when details are not ready, a placeholder "slave N" keeps the count).

Parameters:

  • primary (String) — primary network adapter name; must not be null or an empty string
  • secondary (String) — redundant network adapter name; null or an empty string = single-port scan

Returns:

  • List<ScannedSlaveInfo> — slave list. An empty list = the scan completed and the bus really has no slaves (a normal outcome, not a failure).

Exceptions:

  • NetworkInfo.NetworkScanException — thrown when the scan fails, the runtime library is not loaded or the scan cache cannot be read; it is no longer folded into an empty list or 0.
  • IllegalArgumentException — primary is null or an empty string.

Related structures:

public static class ScannedSlaveInfo {
public int vendorId; // vendor ID
public int productCode; // product code
public int revision; // revision number
public int serialNumber; // serial number
public String name; // device name
public short configAddr; // configured address
public short aliasAddr; // alias address
public short parent; // parent slave index (0 = the master is the parent node)
public byte topology; // 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; // active port bitmap
public byte entryPort; // entry port
public byte parentPort; // port number on the parent slave
public byte physicalType; // physical port type
}

public static class NetworkScanException extends RuntimeException {
public ScanOutcome getOutcome(); // outcome classification
}

public static final class ScanOutcome {
public static final ScanOutcome SUCCESS; // scan completed, the bus really has no slaves
public static final ScanOutcome OPEN_FAILED; // could not open the NIC / invalid argument
public static final ScanOutcome TOPOLOGY_XACT_REFUSED; // topology write transaction refused, this round of scanning is incomplete
public static final ScanOutcome SCAN_CLOSING; // the previous round of scanning is still winding down, try again shortly

// named reasons for NIC open failure (getNativeCode() always equals the native code)
public static final ScanOutcome OPEN_ACCESS_DENIED; // native -1201: the driver safety gate denied access
public static final ScanOutcome OPEN_OCCUPIED; // native -1202: the port is in use
public static final ScanOutcome OPEN_NOT_READY; // native -1203: the driver or NIC is not ready
public static final ScanOutcome OPEN_NIC_NOT_FOUND; // native -1204: no such NIC in the driver NIC pool
public static final ScanOutcome OPEN_LINK_DOWN; // native -1205: the port link is down
public static final ScanOutcome OPEN_BAD_MEDIA; // native -1206: non-wired medium

// topology verdict (not a NIC open failure)
public static final ScanOutcome OPEN_TOPOLOGY_LOOP; // native -1208: zero responses and the linear bus is wired as a ring

public boolean isSuccess(); // whether the scan completed normally (0 slaves here = a truly empty bus)
public boolean isUnknown(); // whether this is an unrecognized failure outcome
}

OPEN_TOPOLOGY_LOOP (-1208) is a wiring conclusion: zero responses (there really are 0 slaves) and the linear bus is judged to be wired as a ring. The remedy is to change the OUT port of the last slave back to unconnected; this is the opposite of the remedy for OPEN_LINK_DOWN (-1205, the network cable is not connected). ScanOutcome.OPEN_TOPOLOGY_LOOP.getFailureReason() returns ScanFailureReason.TOPOLOGY_LOOP.

To decide whether the scan succeeded, use isSuccess(); do not write getOutcome() == ScanOutcome.SUCCESS — a scan that found slaves also counts as success. When the outcome is unavailable, treat it as "scan not completed" and never assume an empty bus.

The async entry returns only a count

The async form MasterAsync.scanAsync(...) returns the number of slaves, not a slave list. For per-slave details use the list returned by this (synchronous) method.

Example:

try {
List<ScannedSlaveInfo> slaves = NetworkInfo.scanSlaves("\\Device\\NPF_{...}", null);
if (slaves.isEmpty()) {
System.out.println("扫描完成,总线上没有从站"); // Scan complete, there are no slaves on the bus
}
} catch (NetworkInfo.NetworkScanException e) {
System.out.println("扫描失败: 结局 " + e.getOutcome()); // Scan failed: outcome {e.getOutcome()}
}

Cancel​

NetworkInfo.abortScan()​

public static void abortScan()

Abort all scanning operations in progress. Use it to break a blocking network scan quickly when a window closes or the user cancels.

Rescanning after cancel

Cancel aborts only the current round. For the next round, go through the NIC selection entry (getAvailableNetworks) again first; it clears the abort flag left by the previous round, after which quick scans and full scans are started as usual.

Example:

// scan on a background thread
Thread scanThread = new Thread(() -> NetworkInfo.scanSlaves(adapterName, null));
scanThread.start();

// the user clicks cancel
NetworkInfo.abortScan();

NIC availability check​

EtherCATMaster.isAdapterAvailable(String adapterName)​

public static boolean isAdapterAvailable(String adapterName)

Check whether a NIC can currently be used by a new master instance in this process. The criterion is the in-process NIC occupancy registry: a successful setNetwork(...) binding registers the NIC (one entry for the primary NIC and one for the redundant NIC), and the entry lapses automatically once close() has finished releasing it.

Parameters:

  • adapterName (String) — NIC adapter name (the same name used with setNetwork)

Returns:

  • boolean — true = no active occupant in this process, so it can be bound; false = already occupied, or the name is null / an empty string

Boundary behaviour:

  • A NIC that no instance has ever bound → true
  • The occupant has called close() and the release has finished (or the occupant has been reclaimed) → true (the leftover entry lapses automatically)
  • The occupant is inside close(), or the release has not finished yet → false (a conservative verdict: the NIC may still be held, so reporting "available" would be a false positive)
  • NIC names are case-sensitive: "eth0" and "ETH0" are two independent registrations that do not affect each other
In-process occupancy only

This method answers only "will this process collide with another instance"; it does not probe the physical link state and does not mean the NIC itself is online. Cross-process exclusivity is decided by the runtime library. For the NIC's current slave count, read the master's own master.slaveCount().

Example:

NetworkInfo target = NetworkInfo.getAvailableNetworks(false, true).stream()
.filter(a -> a.getSlaveCount() != null && a.getSlaveCount() > 0)
.findFirst().orElse(null);

if (target != null && EtherCATMaster.isAdapterAvailable(target.getName())) {
EtherCATMaster master = EtherCATMaster.create();
master.setNetwork(target.getName());
} else {
System.out.println("该网卡已被本进程内其它主站实例占用"); // This NIC is already in use by another master instance in this process
}

Full example​

// 1. NIC selection: pick a physical wired port that has slaves
NetworkInfo target = NetworkInfo.getAvailableNetworks(false, true).stream()
.filter(a -> a.getSlaveCount() != null && a.getSlaveCount() > 0)
.findFirst().orElse(null);
if (target == null) return;

// 2. Quick scan: just the count
int count = NetworkInfo.quickSlaveCount(target.getName());

// 3. Full scan: per-slave details
List<NetworkInfo.ScannedSlaveInfo> slaves = NetworkInfo.scanSlaves(target.getName(), null);
System.out.println(target.getDescription() + " 快扫 " + count + " 站,完整扫描 " + slaves.size() + " 站"); // {target.getDescription()}: quick scan {count} slaves, full scan {slaves.size()} slaves

// 4. Cancel: for use while a scan runs on a background thread
NetworkInfo.abortScan();

Full examples​

Using a DENI file (recommended)​

EtherCATMaster.BuildResult result = EtherCATMaster.create()
.setENI("C:\\EtherCAT\\MyProject.deni")
.build();

if (!result.success) {
System.out.println("初始化失败: " + result.message); // Initialization failed: {result.message}
return;
}

EtherCATMaster master = result.master;
master.setState(EcState.OP);
master.start();

Scanning NICs dynamically​

List<NetworkInfo> adapters = NetworkInfo.getAvailableNetworks(false, true);
NetworkInfo target = adapters.stream()
.filter(a -> a.getSlaveCount() != null && a.getSlaveCount() > 0)
.findFirst().orElse(null);
if (target == null) return;

EtherCATMaster m = EtherCATMaster.create().setEsiFiles("C:\\ESI").enableAutoStartup();
m.setNetwork(target.getName());
EtherCATMaster.BuildResult result = m.build();

if (!result.success) return;
EtherCATMaster master = result.master;

Redundancy mode (automatic redundant-pair detection)​

List<NetworkInfo> adapters = NetworkInfo.getAvailableNetworks(false, true);
List<NetworkInfo> pair = new java.util.ArrayList<>();
for (NetworkInfo a : adapters) {
// getRedundantSlaveCount() > 0 only says "this port is one end of a redundant pair"; its value is the ring-path WKC, not a slave count
if (a.getRedundantSlaveCount() != null && a.getRedundantSlaveCount() > 0) pair.add(a);
}
if (pair.size() < 2) return; // no redundant pair found

try (EtherCATMaster master = EtherCATMaster.create()) {
master.setNetwork(pair.get(0).getName(), pair.get(1).getName());
master.setENI("C:\\config.deni");
master.build();
master.setState(EcState.OP);
master.start();
}

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
// instance 1 — bind the first NIC
EtherCATMaster master1 = EtherCATMaster.create();
master1.setNetwork("\\Device\\NPF_{nic1}");
master1.setState(EcState.OP);
master1.start();

// instance 2 — bind the second NIC (takes effect immediately, no restart)
EtherCATMaster master2 = EtherCATMaster.create();
master2.setNetwork("\\Device\\NPF_{nic2}");
master2.setState(EcState.OP);
master2.start();

// closing returns the NIC and port automatically
master2.close(); // after closing, that NIC can be used by a new instance