Skip to main content

Java SDK overview

EtherCAT master class library for web back ends and enterprise system integration. The public API uses Java camelCase naming throughout.

Installation​

The release package (see the downloads page) contains the main jar, the -sources.jar (source package), the -javadoc.jar, the .pom, the README and the LICENSE. The main jar does not contain the SDK runtime libraries; those ship with the distribution in per-platform folders and must be deployed to the runtime directory as well. The bridge dependencies are not in the package: they are declared by pom.xml and fetched automatically by Maven / Gradle. Installing through Maven / Gradle is recommended so that the bridge dependencies are resolved automatically.

First install the jar and pom from the release package into the local repository (-DpomFile is required so that the bridge dependencies are resolved transitively):

mvn install:install-file -Dfile=darra-ethercat-master-2.13.16.jar -DpomFile=darra-ethercat-master-2.13.16.pom

Then declare the dependency (the bridge dependencies come in with the transitive dependencies):

<dependency>
<groupId>xyz.darra</groupId>
<artifactId>darra-ethercat-master</artifactId>
<version>2.13.16</version>
</dependency>

Requirements​

  • Operating system — Windows 10/11 (Windows 7+ minimum)
  • Java — JDK 11+ (JDK 17 LTS recommended)
  • Privileges — Administrator
  • Real-time driver — required for microsecond-level real-time performance, provided with the installer

Quick start​

Use the Darra configuration tool to scan the network, configure the slaves and export a DENI file, then load it in code with one line:

import com.darra.ethercat.master.EtherCATMaster;
import com.darra.ethercat.data.EcState;
import com.darra.ethercat.slave.Slave;

EtherCATMaster.BuildResult r = EtherCATMaster.create()
.setENI("C:/EtherCAT/MyProject.deni")
.build();
if (!r.success) throw new RuntimeException(r.message);

try (EtherCATMaster master = r.master) {
master.setState(EcState.OP);
// The DENI path does not populate the slave list: construct the slave object directly from the master index + slave index
Slave slave = new Slave(master.MasterIndex, (short) 1, master);
// Start communicating...
} // close() releases resources automatically
Getting slaves on the DENI path

After one-step DENI initialization the master does not populate the slave list: master.getSlave(n) throws IndexOutOfBoundsException and master.slaves() returns an empty list. In the current version, construct the slave directly from the master index + slave index with new Slave(master.MasterIndex, (short) 1, master); see ENI/DENI configuration loading.

Alternative: automatic NIC search (no DENI)​

Use NetworkInfo.getAvailableNetworks(false, true) to scan all NICs and probe the slave count, then take the one that has slaves:

import com.darra.ethercat.master.EtherCATMaster;
import com.darra.ethercat.statics.NetworkInfo;
import com.darra.ethercat.data.EcState;
import java.util.List;

// Scan all NICs and probe the slave count (takes about 500ms-1.5s)
List<NetworkInfo> nets = NetworkInfo.getAvailableNetworks(false, true);

// Pick the NIC that has slaves
NetworkInfo ec = nets.stream()
.filter(n -> n.getSlaveCount() != null && n.getSlaveCount() > 0)
.findFirst()
.orElseThrow(() -> new RuntimeException("未发现 EtherCAT 网络")); // (SDK output, = no EtherCAT network found)
System.out.printf("找到: %s (从站 %d 台, MAC=%s)%n", // Found: %s (%d slaves, MAC=%s)%n
ec.getDescription(), ec.getSlaveCount(), ec.getMacAddress());

try (EtherCATMaster master = EtherCATMaster.create()) {
master.setNetwork(ec.getName(), null); // Returns the slave count; a value below 1 means the network could not be brought up
master.setState(EcState.OP);
}

Which one to use:

  • DENI — production; loads the full set of ESI / PDO / DC parameters in one line (recommended).
  • Automatic search — demos / tooling applications / scenarios without preconfigured startup parameters.
Naming style

Accessor methods use Java camelCase throughout (master.slaveCount() / slave.name() / slave.coe()). Fixed values are public final fields: slave.SlaveNum / master.MasterIndex.

Feature overview​

Shortcuts for common operation sequences:

CapabilityDescription
One-step initializationcreateFromJson() / createFromJsonFile() initialize the master in one step; on failure they throw RuntimeException (a runtime return of 0/0xFFFF is treated as failure), and no longer return an empty master with MasterIndex=0 (see Initialization)
State chain transitionsetState runs the multi-step state transition chain automatically
PDO process datainputsMapping / outputsMapping map once and connect straight to the process image; copyInputPdo / writeOutputPdo are whole-frame snapshots
CiA 402 state machineslave.cia402() provides one-step enable / fault reset / state parsing
EMCY emergency messagesslave.coe().getEmergencyHistory() / clearEmergencyHistory() read and clear the emergency message history of that slave
Topology and redundancyBuild and query the slave topology tree; dual-NIC ring redundancy
Mailbox protocolsUnified interface for the seven mailbox protocols + statistics + ETG.8200 mailbox gateway, see Mailbox gateway
Real-time driverMicrosecond-level PDO cycles, provided with the installer

Capability index​

Find the entry point and the detail page by capability:

CapabilityEntry pointDetails
Master creation and buildEtherCATMaster.create() / createFromJson() / createFromJsonFile()Initialization
Master API and state machinemaster.setState()Master API
Master configurationmaster.config()Configuration
Distributed Clocks (DC)master.configureDCAll() / slave.DC()DC configuration · Slave DC
Diagnosticsmaster.diagnostics() / slave.diagnostics()Diagnostics · Slave diagnostics
Eventsmaster.events()Events · Slave events
Loggingmaster.logs()Logging
ENI / DENI configurationsetENI() / build()ENI / DENI
Slave groupsSlave grouping queryGroups
hot-plugReplacing a station while running and confirming station replacementhot-plug
Redundant networksetNetwork(主网卡, 备网卡)Redundancy
Master object dictionarymaster.masterOD()Master object dictionary
Mailbox gatewaymaster.mailboxGateway()Mailbox gateway
Slave objectnew Slave(masterIndex, slaveNum, master) / master.getSlave(n)Slave · Slave API
PDO process dataslave.slavePdo()PDO read/write
Slave topologymaster.slaveTopology() / slave.topology()Slave API
Slave state mirrorslave.wcContributed() / slave.alStatusMirror() / slave.isLost()Slave diagnostics
ESI DC capabilityslave.DC().hasEsiDcSync() / dcSyncModeFromEsi()Slave DC
CiA 402 / CiA 401slave.cia402() / slave.cia401()CiA 402 · CiA 401
CoE (SDO / EMCY / OD)slave.coe()CoE
FoE file transferslave.foe()FoE
SoE IDN parametersslave.soe() (including SERCOS IDN encoding/decoding SoE.SoEElementFlags / SoE.IdnTriple)SoE
AoE channelsslave.aoe()AoE
EoE Ethernetslave.eoe()EoE
VoE vendor protocolslave.voe()VoE
FSoE safetyslave.fsoe()FSoE
Modular device MDPModular devices are detected and configured automatically when entering OPMDP
Async callsAsync entry points such as setNetworkAsync() / buildAsync() and the CompletableFuture extensionsSugar
Sugarcom.darra.ethercat.sugarSugar

Complete example​

// Enable the CiA 402 drive
slave.cia402().enable();

// Typed SDO read/write (returns SdoTypedResult; always judge success by ok)
CoE.SdoTypedResult<Integer> pos = slave.coe().sdoReadInt32((short) 0x6064, (byte) 0);
if (!pos.ok) throw new IllegalStateException("读 0x6064 失败, abort=0x" // (SDK output, = read of 0x6064 failed, abort=0x)
+ Integer.toHexString(pos.abortCode) + ", wkc=" + pos.wkc);

CoE.SdoTypedResult<Void> wr = slave.coe().sdoWriteInt32((short) 0x607A, (byte) 0, 100000);
if (!wr.ok) throw new IllegalStateException("写 0x607A 失败, abort=0x" // (SDK output, = write of 0x607A failed, abort=0x)
+ Integer.toHexString(wr.abortCode) + ", wkc=" + wr.wkc);

// Emergency message history (returns every entry recorded for that slave) and the child slave topology
List<CoE.EmergencyMessage> history = slave.coe().getEmergencyHistory();
List<Integer> children = master.topologyChildren(parentIdx);

Java-specific sugar​

The com.darra.ethercat.sugar package provides an optional set of extensions (the standard API is unaffected): try-with-resources, Stream<Slave> / Optional<Slave> / Iterable for-each, CompletableFuture<T> async, a BlockingQueue<EmergencyEvent> diagnostic queue, immutable record identities, lambda listeners and the fluent MasterBuilder.

Error code localisation​

Error code text goes through the static methods of com.darra.ethercat.statics.ProtocolCodes:

import com.darra.ethercat.statics.ProtocolCodes;

String al = ProtocolCodes.alStatusDescription(code); // AL Status description in Chinese
String sdo = ProtocolCodes.sdoAbortDescription(abort); // SDO Abort description in Chinese
String pdo = ProtocolCodes.pdoDataTypeName(dataType); // PDO data type protocol name, e.g. UINT16 / REAL32

// Additional classification information
int sev = ProtocolCodes.alStatusSeverity(code); // 0=Info 1=Warning 2=Error 3=Fatal
String hint = ProtocolCodes.sdoAbortHint(abort); // handling hint
boolean retry = ProtocolCodes.sdoAbortIsRetryable(abort); // whether the operation can be retried
  • AL Status currently provides Chinese descriptions only (alStatusDescription); there is no entry point for English text.
  • SDO Abort likewise provides Chinese descriptions only (sdoAbortDescription); no English description is available.
  • State names are available separately through ecStateGetName(int) (Chinese) and ecStateGetNameEn(int) (English: INIT/PREOP/SAFEOP/OP/BOOT).
  • pdoDataTypeName(int) returns the authoritative protocol name (upper case, such as INT8 / UINT16 / REAL32 / VISIBLE_STRING), not a display alias.

Version compatibility​

Current SDK version: 2.13.16. The runtime libraries, real-time driver and GUI share one version number; a MINOR / MAJOR upgrade requires reinstalling the matching driver.

Diagnostic counters and cycle statistics​

com.darra.ethercat.master.Diagnostics is instantiated directly with the master index. It is not the same class as the MasterDiagnosticsInfo returned by master.diagnostics(), so do not mix the two entry points:

import com.darra.ethercat.master.Diagnostics;

Diagnostics diag = new Diagnostics(master.MasterIndex);

The members below only maintain and observe counters: they do not change the state machine, do not change the topology model and do not lower the expected value. They throw IllegalStateException while the master is shutting down or has been released (getPDOAvgCycleTimeNs() / getPDOErrorCount() are the exception: they return 0 as for missing data).

CategoryMethodType / ReturnsRead/writeDescription
WKC baselinegetExpectedWKC()shortread-onlyExpected WKC fixed at configuration time; falls back to the backup reading when the live reading is unavailable, and returns 0 when neither is available
WKC baselinesetExpectedWKC(short)voidcallSets the expected WKC; call it during the configuration phase only
Counter controlresetDiagnostics()voidcallClears the diagnostic counters
Counter controlresetSlavePortErrorCounters(short)booleancallClears the port error counters of the specified slave
Counter controlupdateSnapshot()voidcallRefreshes the diagnostic snapshot immediately
Cycle statisticsrecordPDOCycleStart()voidcallRecords the start of one PDO cycle manually
Cycle statisticsrecordWKC(short)voidcallRecords one measured WKC value manually
Cycle statisticsgetCycleStatistics()DarraCore.CommunicationStatsread-onlyCommunication statistics snapshot; returns null when it cannot be read
Cycle statisticsgetPDOAvgCycleTimeNs()longread-onlyAverage cycle time (nanoseconds); returns 0 when there is no data
Cycle statisticsgetPDOErrorCount()intread-onlyTotal number of failed cycles; returns 0 when there is no data
Cycle statisticsgetJitterUs()doubleread-onlyCycle jitter = maximum cycle − minimum cycle (microseconds)
System management interruptgetSmiMsrAvailable()longread-onlyWhether the hardware counter is readable: 1 = readable, 0 = unavailable
Real-time threadgetRtPreemptCount()longread-onlyCumulative number of times the real-time thread was preempted
Real-time threadgetRtPreemptPeakNs()longread-onlyPeak duration of a preemption of the real-time thread (nanoseconds)
Real-time threadgetBigGapUnknownCount()longread-onlyCumulative number of large gaps with an unknown cause

getExpectedWKC()​

public short getExpectedWKC()

Reads the expected WKC fixed at configuration time. It takes the live reading first; when that cannot be read it falls back to the backup reading, and when neither is available it returns 0 (unknown) rather than inventing a number. The expected WKC is determined by the topology — as long as the topology does not change, it is a fixed value.

Parameters: none.

Returns: the expected WKC; 0 = unknown.

System.out.println("期望 WKC: " + diag.getExpectedWKC());   // Expected WKC:

setExpectedWKC(short expectedWkc)​

public void setExpectedWKC(short expectedWkc)

Sets the expected WKC during the configuration phase.

Parameters:

  • expectedWkc — the expected WKC.

Returns: none.

Do not lower the expected value at runtime

A measurement below the expectation means a slave is not responding: report it as-is and locate the slave one by one, instead of changing the expectation to make the data "match up". The expected value is the true value from the configuration phase; lowering it at runtime hides a lost slave.

resetDiagnostics()​

public void resetDiagnostics()

Clears the diagnostic counters (cycle statistics, error counts and so on). It does not change the expected WKC or the topology model; already recorded link diagnostic events are not cleared — the event ring overwrites them naturally as it fills.

Parameters: none.

Returns: none.

resetSlavePortErrorCounters(short slaveIndex)​

public boolean resetSlavePortErrorCounters(short slaveIndex)

Clears the port error counters of the specified slave, so that link quality can be re-evaluated after slave maintenance.

Parameters:

  • slaveIndex — slave index (1-based).

Returns: true = success; false = failure (the slave does not exist or the call did not succeed).

if (!diag.resetSlavePortErrorCounters((short) 3)) {
System.out.println("从站 3 端口错误计数器清零未成功"); // Clearing slave 3's port error counters did not succeed
}

updateSnapshot()​

public void updateSnapshot()

Refreshes the diagnostic snapshot immediately, so that several subsequent reads land on the same tick.

Parameters: none.

Returns: none.

recordPDOCycleStart()​

public void recordPDOCycleStart()

Records the start of one PDO cycle manually. Use it when the application runs its own PDO loop and keeps its own accounting; no call is needed when the SDK drives the cycle, and a repeated call is counted again.

Parameters: none.

Returns: none.

recordWKC(short wkc)​

public void recordWKC(short wkc)

Records one measured WKC value manually. Use it together with recordPDOCycleStart() for the cycle statistics of a self-managed loop.

Parameters:

  • wkc — the WKC measured in this tick.

Returns: none.

diag.recordPDOCycleStart();
try {
// Send one process data frame on its own
diag.recordWKC(actualWkc);
} catch (Exception e) {
System.out.println("本拍未完成: " + e.getMessage()); // This cycle did not complete:
}

getCycleStatistics()​

public DarraCore.CommunicationStats getCycleStatistics()

Returns a communication statistics snapshot. When the read fails or there is no data it returns null and writes a WARNING log entry; do not treat the previous tick's object as the current reading.

Parameters: none.

Returns: the statistics snapshot; null = read failed / no data yet.

CategoryPropertyTypeRead/writeDescription
Communication statisticsTotalCyclesintread-onlyTotal number of cycles
Communication statisticsSuccessfulCyclesintread-onlyNumber of successful cycles
Communication statisticsFailedCyclesintread-onlyNumber of failed cycles (the source of getPDOErrorCount())
Communication statisticsTimeoutCyclesintread-onlyNumber of timed-out cycles
Communication statisticsAverageCycleTimeUsdoubleread-onlyAverage cycle time (microseconds)
Communication statisticsMaxCycleTimeUsdoubleread-onlyMaximum cycle time (microseconds)
Communication statisticsMinCycleTimeUsdoubleread-onlyMinimum cycle time (microseconds)
DarraCore.CommunicationStats cs = diag.getCycleStatistics();
if (cs == null) {
System.out.println("通信统计暂不可读"); // Communication statistics are temporarily unreadable
} else {
System.out.printf("周期 %d 次,失败 %d 次,平均 %.1f us%n", // %d cycles, %d failures, average %.1f us%n
cs.TotalCycles, cs.FailedCycles, cs.AverageCycleTimeUs);
}

getPDOAvgCycleTimeNs()​

public long getPDOAvgCycleTimeNs()

Average cycle time, converted from the average cycle (microseconds) of getCycleStatistics() into nanoseconds.

Parameters: none.

Returns: nanoseconds; 0 = no data or read failed.

getPDOErrorCount()​

public int getPDOErrorCount()

Total number of failed cycles (taken from the failed-cycle field of the statistics snapshot).

Parameters: none.

Returns: the number of failed cycles; 0 = no failed cycles, or no data yet.

getJitterUs()​

public double getJitterUs()

Cycle jitter = maximum cycle − minimum cycle, in microseconds.

Parameters: none.

Returns: the jitter in microseconds; 0 = no data.

getSmiMsrAvailable()​

public long getSmiMsrAvailable()

Whether the hardware counter for system management interrupts is readable. 1 = readable, 0 = unavailable (the real-time data path is not enabled) or the read failed. It only tells you whether the counting channel is ready; do not use it to judge whether an interrupt ever occurred on the system.

Parameters: none.

Returns: 1 / 0.

getRtPreemptCount()​

public long getRtPreemptCount()

Cumulative number of times the real-time thread was preempted.

Parameters: none.

Returns: the cumulative count; 0 = no preemption was recorded, or the real-time data path is not enabled.

getRtPreemptPeakNs()​

public long getRtPreemptPeakNs()

Peak duration for which the real-time thread was preempted, restored into long as an unsigned 32-bit quantity.

Parameters: none.

Returns: the peak duration (nanoseconds); 0 = nothing recorded or the data path is not enabled.

getBigGapUnknownCount()​

public long getBigGapUnknownCount()

Cumulative number of large cycle gaps whose cause is unknown.

Parameters: none.

Returns: the cumulative count; 0 = no large gap with an unknown cause, or the data path is not enabled.

The members in this group only read port state and the event ring; they send no frames and change no state. They throw IllegalStateException while the master is shutting down or has been released.

CategoryMethodType / ReturnsRead/writeDescription
Port linkgetPhyLinkState()intread-onlyTwo-port bitmap: bit0 = primary port up, bit1 = secondary port up; 0xFFFF = not observable
Slave linkgetSlaveLinkQuality(short)shortread-onlyLink quality of the specified slave, 0–100%; -1 = unknown / read failed
Event ringgetLinkDiagEventCount()longread-onlyCumulative total number of link diagnostic events (including history already overwritten by the ring)
Event ringgetLinkDiagSeq()longread-onlyEvent ring freshness token: monotonically increasing = recording, no longer increasing = recording is not running
Event ringgetLinkDiagEvents(long)LinkDiagEvent[]read-onlyReads out events since the given sequence number; ring capacity 256; returns an empty array when there are no new events

getPhyLinkState()​

public int getPhyLinkState()

Two-port link bitmap, identical to getPhyLinkBitMask(): bit0 = primary port up, bit1 = secondary port up, 0xFFFF = not observable (the read failed or this version does not provide it). master.diagnostics() has an entry point of the same name, so master.diagnostics().getPhyLinkState() can be called directly.

Parameters: none.

Returns: the bitmap as int.

int mask = diag.getPhyLinkState();
if (mask == 0xFFFF) {
System.out.println("端口链路: 不可观测"); // Port link: not observable
} else {
System.out.printf("主口 %s / 副口 %s%n", // Primary port %s / secondary port %s%n
(mask & 1) != 0 ? "up" : "down",
(mask & 2) != 0 ? "up" : "down");
}
0xFFFF does not mean "both ports are up"

Check for 0xFFFF (not observable) before interpreting the bits, otherwise 0xFFFF is misread as both ports being connected.

getSlaveLinkQuality(short slaveIndex)​

public short getSlaveLinkQuality(short slaveIndex)

Reads the link quality percentage of the specified slave. The quality is derived from the port error counters, which suits trend observation and maintenance hints.

Parameters:

  • slaveIndex — slave index (1-based).

Returns: 0–100 = link quality; -1 = unknown / read failed.

short q = diag.getSlaveLinkQuality((short) 2);
System.out.println("从站 2 链路质量: " + (q < 0 ? "未知" : q + "%")); // Slave 2 link quality: unknown / {q}%

getLinkDiagEventCount()​

public long getLinkDiagEventCount()

Cumulative total number of link diagnostic events, including records already overwritten by the event ring. Use it together with getLinkDiagSeq() to tell whether new events have occurred.

Parameters: none.

Returns: the cumulative event count; 0 = no events yet, or this version does not provide the entry point.

getLinkDiagSeq()​

public long getLinkDiagSeq()

Freshness token of the event ring: monotonically increasing means the recording side keeps writing; when it stops growing, recording is not running. Save it as the starting point for the next getLinkDiagEvents(long).

Parameters: none.

Returns: the current token; 0 = unknown / this version does not provide the entry point.

getLinkDiagEvents(long sinceSeq)​

public LinkDiagEvent[] getLinkDiagEvents(long sinceSeq)

Reads the link diagnostic events after sinceSeq. The event ring has capacity 256 (LinkDiagEvent.RING_CAPACITY) and overwrites the oldest events once it is full.

When there are no new events, or this version does not provide the entry point, it returns an empty array (never null); a real read failure also returns an empty array after writing an ERROR log entry. So judge an "empty array" together with getLinkDiagSeq(): only when the token has not changed are there really no new events.

Parameters:

  • sinceSeq — the sequence number read last time; 0 = start from the oldest readable event in the ring.

Returns: the event array; an empty array = no new readable events.

CategoryPropertyTypeRead/writeDescription
Event fieldtimestampUslongread-onlyEvent time (microseconds)
Event fieldseqintread-onlyMonotonically increasing sequence number per master
Event fieldkindLinkDiagEventKindread-onlyEvent kind
Event fieldportintread-onlyPort number 0–3 (meaningful only for port events; 0xFF otherwise)
Event fieldfromState / toStateintread-onlyPrevious / new redundancy state
Event fieldaPeer / aSelf / bPeer / bSelfintread-onlyRaw snapshot of the trigger tick quadruple (0–65535)
Event fieldringIntactbooleanread-onlytrue = the ring is closed, false = the ring is broken
Event fieldisUpbooleanread-onlytrue = recovery edge, false = disconnect edge
Event fieldeffectiveWkcintread-onlyMeasured WKC of the topology union
Event fieldexpectedWkcintread-onlyExpected WKC fixed at configuration time

Event kinds (Diagnostics.LinkDiagEventKind): UNKNOWN(0) / A_LINK_DOWN(1) / B_LINK_DOWN(2) / MIDDLE_BROKEN(3) / HEALTHY(4) / TOTAL_LOST(5) / PHY_A(6) / PHY_B(7) / FAILOVER(8) / RECOVER(9) / QUICK_FLAP(10) / WKC_TUPLE(11). Unknown numbers fall into UNKNOWN; reading never throws.

long lastSeq = 0;   // Keeps the last sequence number read
for (Diagnostics.LinkDiagEvent e : diag.getLinkDiagEvents(lastSeq)) {
System.out.printf("[%d us] %s port=%d 环完整=%s WKC=%d/%d%n", // [%d us] %s port=%d ring intact=%s WKC=%d/%d%n
e.timestampUs, e.kind, e.port, e.ringIntact, e.effectiveWkc, e.expectedWkc);
lastSeq = e.seq;
}

Redundancy and failover​

CategoryMethodType / ReturnsRead/writeDescription
Redundancy statusgetRedundancyStatus()DarraCore.RedundancyStatusread-onlyRedundancy status snapshot; null = redundancy not enabled / not connected / read failed
Redundancy statusisPrimaryLinkUp()booleanread-onlyWhether the primary link is connected; false when there is no snapshot
Redundancy statusisSecondaryLinkUp()booleanread-onlyWhether the secondary link is connected; false when there is no snapshot
Redundancy statusgetFailoverCount()intread-onlyNumber of failovers; 0 when there is no snapshot

getRedundancyStatus()​

public DarraCore.RedundancyStatus getRedundancyStatus()

Returns a redundancy status snapshot. What you get is a self-owned value copy (detached from the runtime buffer), so it can be held safely for a long time and its fields read freely after the buffer has been returned.

Parameters: none.

Returns: the status snapshot; null = redundancy not enabled / not connected / read failed (a read failure writes an ERROR log entry). It throws IllegalStateException while the master is shutting down or has been released.

CategoryPropertyTypeRead/writeDescription
Redundancy statusStateintread-only0 = not enabled, 1 = primary port only, 2 = secondary port only, 3 = both ports
Redundancy statusPrimaryLinkUpintread-onlyWhether the primary link is connected (a value other than 0 = connected)
Redundancy statusSecondaryLinkUpintread-onlyWhether the secondary link is connected (a value other than 0 = connected)
Redundancy statusPrimaryTxFrames / PrimaryRxFramesintread-onlyFrames sent / received on the primary link
Redundancy statusSecondaryTxFrames / SecondaryRxFramesintread-onlyFrames sent / received on the secondary link
Redundancy statusFailoverCountintread-onlyNumber of failovers
Redundancy statusLastFailoverTimeintread-onlyTime of the last failover (Unix timestamp, seconds)
DarraCore.RedundancyStatus st = diag.getRedundancyStatus();
if (st == null) {
System.out.println("冗余未启用或暂不可读"); // Redundancy is not enabled or is temporarily unreadable
} else {
System.out.printf("状态=%d 主口=%s 副口=%s 切换=%d 次%n", // state=%d primary port=%s secondary port=%s switches=%d%n
st.State, st.PrimaryLinkUp != 0, st.SecondaryLinkUp != 0, st.FailoverCount);
}

isPrimaryLinkUp()​

public boolean isPrimaryLinkUp()

Whether the primary link is connected. Each call takes a fresh snapshot internally.

Parameters: none.

Returns: true = connected; false = disconnected or no status snapshot.

isSecondaryLinkUp()​

public boolean isSecondaryLinkUp()

Whether the secondary link is connected. It takes its snapshot independently of isPrimaryLinkUp(); when you need conclusions for both ports from the same tick, call getRedundancyStatus() once and read the fields.

Parameters: none.

Returns: true = connected; false = disconnected or no status snapshot.

getFailoverCount()​

public int getFailoverCount()

Cumulative number of failovers.

Parameters: none.

Returns: the failover count; 0 = never failed over, or no status snapshot.

Measured topology​

The two readings describe the expected WKC share on the port adjacency graph; compare them with the measured value of the corresponding path to judge whether that path really carries frames through. They are not a "whole-topology total": the shares of the two paths are mutually exclusive.

CategoryMethodType / ReturnsRead/writeDescription
Measured topologygetTopoPriIntact()intread-onlyExpected WKC share of the primary path (sent on the primary port, received on the secondary port) forward along the port adjacency graph; 0 = model not established
Measured topologygetTopoSecIntact()intread-onlyBranch share of the secondary path (sent on the secondary port, received on the primary port); always 0 for a chain (end-foldback) shape

getTopoPriIntact()​

public int getTopoPriIntact()

Expected WKC share of the primary path: it accumulates the contributions on the ring forward along the port adjacency graph and does not descend into branches. Use it against the measured value of the primary path to judge whether the primary path brings the frame back intact.

Parameters: none.

Returns: the expected share; 0 = the topology model has not been established yet (no evidence — do not judge a fault from it); a read exception returns -1.

getTopoSecIntact()​

public int getTopoSecIntact()

Branch share of the secondary path: it walks the same chain in reverse and accumulates only the contributions reachable through branch entries; for a pure ring without branches it falls back to the ring share.

Parameters: none.

Returns: the branch share; 0 = the topology model has not been established, or the shape is a chain (end-foldback) — in that shape the secondary port only receives and never sends, the secondary path does not exist structurally, and 0 is not a fault; a read exception returns -1.

int pri = diag.getTopoPriIntact();
int sec = diag.getTopoSecIntact();
System.out.printf("期望份额: 主路径 %d / 副路径 %d%n", pri, sec); // Expected shares: primary path %d / secondary path %d%n

Master object dictionary (ETG.1510)​

Access the master's own object dictionary through the standard ETG.1510 indices. Commonly used indices: 0xF120 / 0x1018 for master identity, 0x8nnn / 0x9nnn / 0xAnnn for slave-related objects, 0x10F0 / 0x10F3 for parameter backup and diagnostic history.

CategoryMethodType / ReturnsRead/writeDescription
Object dictionaryreadEtg1510Object(int, byte)byte[]read-onlyReads a master object dictionary entry; returns null on failure
Object dictionarywriteEtg1510Object(int, byte, byte[])booleancallWrites a master object dictionary entry; returns true on success

readEtg1510Object(int index, byte subindex)​

public byte[] readEtg1510Object(int index, byte subindex)

Reads a master object dictionary entry by standard index and returns the raw bytes.

Parameters:

  • index — object index, valid range 0x0000–0xFFFF; an out-of-range value throws IllegalArgumentException (no masking or value rewriting).
  • subindex — subindex.

Returns: the bytes read; null = read failed or the length is 0.

byte[] vendor = diag.readEtg1510Object(0x1018, (byte) 1);
if (vendor == null) System.out.println("读取主站厂商 ID 失败"); // Failed to read the master vendor ID

writeEtg1510Object(int index, byte subindex, byte[] data)​

public boolean writeEtg1510Object(int index, byte subindex, byte[] data)

Writes a master object dictionary entry by standard index.

Parameters:

  • index — object index, valid range 0x0000–0xFFFF; an out-of-range value throws IllegalArgumentException.
  • subindex — subindex.
  • data — data to write; must not be null or an empty array.

Returns: true = written successfully; false = invalid arguments (data empty) or the write failed.

NIC scan and device discovery​

Static entry points of com.darra.ethercat.statics.NetworkInfo, used together with NetworkInfo.getAvailableNetworks(...). A failed scan always throws NetworkScanException; an empty list or 0 is no longer passed off as a normal result.

CategoryMethodType / ReturnsRead/writeDescription
Scan verdictdecodeNicScanStatus(int)NicScanStatusread-onlyDecodes the raw slave count / reason code of each port into a verdict enum
NIC informationgetNetworkInfo(String)NetworkInforead-onlyGets a single NIC by adapter name; returns null when it is not found
Scan resultgetScannedSlaveInfoList()List<ScannedSlaveInfo>read-onlyReads the slave details from the last scan; throws when the count falls short
NIC informationgetSpeed()longread-onlyLink speed (Mbps); the Java standard API has no source for the speed, so it always returns -1
Scan diagnosticslastScanWin32Error()intread-onlyRaw error code of the most recent failure to open the NIC (thread-local)
Scan controlresetScanAbort()voidcallClears the abort flag before a new scan
Scan resultscannedSlaveGeneration()intread-onlyScan snapshot generation: even = stable / odd = being written
Display helperaliasAddrHex(ScannedSlaveInfo)Stringread-onlyFormats the alias address as 0xXXXX
Display helpervendorIDHex(ScannedSlaveInfo)Stringread-onlyFormats the vendor ID as 0xXXXXXXXX
Device discoverydetermineCouplerStatus(List<ScannedSlaveInfo>)List<Map<String, Object>>read-onlyPicks out the couplers and counts their child modules

decodeNicScanStatus(int rawSlaveNum)​

public static NicScanStatus decodeNicScanStatus(int rawSlaveNum)

Decodes the raw slave count / reason code of each port into NetworkInfo.NicScanStatus (an immutable value object, not an enum):

  • > 0 → FOUND: slaves were measured;
  • 0 → IDLE_NO_SLAVE: the port was measured empty, there really are no slaves;
  • -2 → NOT_MEASURED: nothing was measured in this round (not 0 slaves), nativeCode() is still -2;
  • -3 → OCCUPIED_BY_MASTER: a master on this machine occupies the NIC, so the scan skips it by design (a fact, not a failure);
  • any other unclassified negative code → the raw value is kept: nativeCode() is the native code, isUnknown() is true, and it is not folded into NOT_MEASURED.

NicScanStatus carries int nativeCode() and boolean isUnknown(), and equals / hashCode go by the native code. The nativeCode() of FOUND is 1 (one named verdict for at least 1 slave); read getSlaveCount() for the actual slave count.

Parameters:

  • rawSlaveNum — the raw slave count / reason code.

Returns: the verdict object; never null.

NetworkInfo.NicScanStatus s = NetworkInfo.decodeNicScanStatus(raw);
if (s == NetworkInfo.NicScanStatus.IDLE_NO_SLAVE) {
System.out.println("网口扫过了,确实 0 个从站"); // The network interface was scanned and there really are 0 slaves
}

getNetworkInfo(String adapterName)​

public static NetworkInfo getNetworkInfo(String adapterName)

Gets the information of a single NIC by adapter name (the same naming as getName()). null or an empty string returns null directly; a failure of the underlying scan throws NetworkScanException and is not folded into "not found".

Parameters:

  • adapterName — the adapter name.

Returns: the NIC information; null = invalid name or no match.

getScannedSlaveInfoList()​

public static List<ScannedSlaveInfo> getScannedSlaveInfoList()

Reads the slave details obtained by the last scanSlaves(...). A scan must have completed first.

Parameters: none.

Returns: the list of slave details; an empty list = the last scan completed and there really are no slaves on the bus. When the slave total is negative or reading any slave fails, it throws NetworkScanException (it does not return a half-empty list).

CategoryPropertyTypeRead/writeDescription
Slave detailsvendorIdintread-onlyVendor ID
Slave detailsproductCodeintread-onlyProduct code
Slave detailsrevisionintread-onlyRevision number
Slave detailsserialNumberintread-onlySerial number
Slave detailsnameStringread-onlySlave name
Slave detailsconfigAddrshortread-onlyConfiguration address
Slave detailsaliasAddrshortread-onlyAlias address
Slave detailsparentshortread-onlyParent slave configuration address
Slave detailstopologybyteread-onlyTopology type
Slave detailsactivePortsbyteread-onlyActive port bitmap
Slave detailsentryPortbyteread-onlyEntry port
Slave detailsparentPortbyteread-onlyPort through which the slave is attached to its parent
Slave detailsphysicalTypebyteread-onlyPhysical port type
for (NetworkInfo.ScannedSlaveInfo s : NetworkInfo.getScannedSlaveInfoList()) {
System.out.println(NetworkInfo.aliasAddrHex(s) + " " + s.name
+ " VID=" + NetworkInfo.vendorIDHex(s));
}

getSpeed()​

public long getSpeed()

Link speed (Mbps). The Java standard java.net.NetworkInterface does not provide a source for the speed, so this method still returns -1 after a NIC is matched; read the real speed from the system side if you need it.

Parameters: none.

Returns: -1 = unknown (the current implementation is always unknown).

lastScanWin32Error()​

public static int lastScanWin32Error()

Raw error code of the most recent failure to open the NIC during a scan, so that "why can't the NIC be opened" can be pinned to a concrete cause.

thread-local: it must be called on the same thread that started the scan; it cannot be read across threads.

Parameters: none.

Returns: 0 = no error; 5 = permission denied; 2 / 1168 = the driver is not ready, or the NIC is not in the available NIC list; 170 = device busy (BUSY) — the specific cause is determined by the driver instance's LastError, and four values can come back with 170: 30 = the RT real-time channels are exhausted; 2 = the instance is still held by another 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; 172 = another process already holds the EtherCAT master (fast fail, no retry); any other value other than 0 = an unclassified raw code, shown as-is — check the log. When this version does not provide the entry point it throws NetworkScanException.

resetScanAbort()​

public static void resetScanAbort()

Clears the abort flag before a new scan; used together with abortScan(). It returns immediately (no operation) when the runtime library is not loaded.

Parameters: none.

Returns: none.

scannedSlaveGeneration()​

public static int scannedSlaveGeneration()

Process-wide generation of the scan snapshot: even = the snapshot is stable, odd = it is being written. Note the generation before reading the snapshot and compare it once more after reading; if they differ, the result has been rewritten by another scan and cannot be used as the same snapshot.

Parameters: none.

Returns: the current generation. When this version does not provide the entry point it throws NetworkScanException.

int before = NetworkInfo.scannedSlaveGeneration();
List<NetworkInfo.ScannedSlaveInfo> slaves = NetworkInfo.getScannedSlaveInfoList();
int after = NetworkInfo.scannedSlaveGeneration();
if (before != after) System.out.println("读取期间快照被改写,这份结果已过期"); // The snapshot was overwritten during the read, so this result is stale

aliasAddrHex(ScannedSlaveInfo info)​

public static String aliasAddrHex(ScannedSlaveInfo info)

Formats the alias address as 0xXXXX (displayed as an unsigned 16-bit value). The parameter must not be null.

Parameters:

  • info — the slave details.

Returns: the formatted string.

vendorIDHex(ScannedSlaveInfo info)​

public static String vendorIDHex(ScannedSlaveInfo info)

Formats the vendor ID as 0xXXXXXXXX. The parameter must not be null.

Parameters:

  • info — the slave details.

Returns: the formatted string.

determineCouplerStatus(List<ScannedSlaveInfo> slaves)​

public static List<Map<String, Object>> determineCouplerStatus(List<ScannedSlaveInfo> slaves)

Picks out couplers with the coupler identification rules built into the runtime library and counts the child modules attached below each of them. Slaves that are not couplers do not appear in the result.

Each item of the returned list is a Map:

  • index — coupler configuration address (short);
  • name — slave name (String);
  • is_coupler — always true;
  • child_count — number of slaves whose parent configuration address equals this coupler's configuration address (int).

Parameters:

  • slaves — the slave list obtained from the scan; must not be null.

Returns: the list of coupler entries; an empty list = no coupler in the list. When the runtime library is not loaded or the identification call fails, it throws NetworkScanException (it does not return half a result).

for (Map<String, Object> c : NetworkInfo.determineCouplerStatus(slaves)) {
System.out.printf("耦合器 0x%04X %s,子模块 %s 个%n", // Coupler 0x%04X %s, %s submodules%n
(Short) c.get("index"), c.get("name"), c.get("child_count"));
}

Startup parameter list​

Startup parameters are carried by two public static nested classes in com.darra.ethercat.slave.Startup; refer to them by their qualified names:

  • Startup.StartupParameter — a single startup parameter (index / subindex / data / priority / state transition / write timing);
  • Startup.StartupParameterList — the parameter list, constructed as new Startup.StartupParameterList(masterNum, slaveNum); it implements Iterable<StartupParameter> and can be used directly in a for-each loop.
import com.darra.ethercat.slave.Startup;

Startup.StartupParameterList list =
new Startup.StartupParameterList(master.MasterIndex, (short) 1);

Startup.StartupParameter p = new Startup.StartupParameter();
p.Index = (short) 0x6060;
p.SubIndex = (byte) 0;
p.Data = new byte[]{ 0x08 };
p.transitionEnum(Startup.Transition.PS);
list.addParameter(p);
CategoryPropertyTypeRead/writeDescription
State transitiontransitionEnum()Startup.Transitionread-writeThe state transition at which this parameter takes effect; defaults to IP
Compatibility propertyphase()intread-writeNumeric form of the state transition (0 = IP / 1 = PS / 2 = SO)
Write timingisWriteTimingManuallySet()booleanread-onlyWhether the write timing has been set manually
CategoryMethodType / ReturnsRead/writeDescription
Parameter registrationaddParameter(short, byte, byte[], String, int, boolean)booleancallBuilds and registers one startup parameter from explicit arguments

transitionEnum()​

public Transition transitionEnum()
public void transitionEnum(Transition value)

Reads / sets the state transition at which this parameter takes effect (Startup.Transition: IP / PS / SO / OS / SP / PI); defaults to IP.

After a write, if the write timing has not been set manually (see isWriteTimingManuallySet()), the default timing of that transition is applied with it: IP / OS / SP use "after the transition", PS / SO / PI use "before the transition". Call writeTiming(WriteTiming) first when the timing must be fixed.

Parameters (setter):

  • value — the target state transition; must not be null (when the write timing has not been set manually, a NullPointerException is thrown where the default timing is resolved).

Returns (getter): the current state transition; never null.

Startup.StartupParameter p = new Startup.StartupParameter();
p.transitionEnum(Startup.Transition.PS); // PreOp → SafeOp
System.out.println(p.transitionEnum()); // PS

phase()​

public int phase()
public void phase(int value)

Numeric compatibility property of the state transition. The getter returns transitionEnum().value(): 0 = IP / 1 = PS / 2 = SO / 3 = OS / 4 = SP / 5 = PI.

The setter recognises only 0 / 1 / 2; any other value (including 3 / 4 / 5) falls back to PS — that is, phase(int) cannot express OS / SP / PI, so use transitionEnum(Transition) for those three transitions. After a write it likewise applies the default timing when "the write timing has not been set manually".

Parameters (setter):

  • value — 0 / 1 / 2; any other value is handled as PS.

Returns (getter): the state transition number 0–5.

3 / 4 / 5 raise no error

Writing 3 / 4 / 5 does not throw; it silently falls back to PS. When migrating between languages, do not assume the numeric value is preserved — setting by transition name is safer.

isWriteTimingManuallySet()​

public boolean isWriteTimingManuallySet()

Returns whether the write timing has been set manually. When it is false, changing transitionEnum / phase applies the default timing of the new transition automatically; when it is true the timing stays as it is until writeTiming(WriteTiming) is called again.

Parameters: none.

Returns: true = set manually; false = still automatic.

addParameter(short index, byte subIndex, byte[] data, String transition, int priority, boolean isRead)​

public boolean addParameter(short index, byte subIndex, byte[] data,
String transition, int priority, boolean isRead)

On Startup.StartupParameterList, builds and registers one startup parameter from explicit arguments:

  • transition is parsed after upper-casing; null is treated as IP;
  • data set to null is treated as an empty array;
  • the description is generated automatically as Write 0xXXXX:YY or Read 0xXXXX:YY;
  • the data length (maximum 256 bytes) and the priority range (0–65535) are validated before registration;
  • an existing entry with the same index, subindex and priority is replaced, so two entries never coexist.

When validation fails or an exception occurs during registration it returns false and writes an ERROR log entry (no exception is thrown). The overload of the same name public void addParameter(StartupParameter param) takes an already built parameter and is equivalent to add(param).

Parameters:

  • index — SDO index;
  • subIndex — SDO subindex;
  • data — data to write (may be empty for a read);
  • transition — transition identifier: IP / PS / SO / OS / SP / PI / SI (SI is the same as PI);
  • priority — priority, 0–65535, the smaller the number the higher the priority;
  • isRead — true = read operation.

Returns: true = registered; false = validation failed or registration threw.

boolean ok = list.addParameter((short) 0x6060, (byte) 0,
new byte[]{ 0x08 }, "PS", 100, false);
if (!ok) System.out.println("启动参数登记失败,检查数据长度与优先级"); // Startup parameter registration failed, check the data length and priority