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.
- Maven
- Gradle
- Reference the JAR manually
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>
implementation 'xyz.darra:darra-ethercat-master:2.13.16'
If 2.13.16 is not yet available in the repository, install it into the local repository with mvn install:install-file above first, or use "Reference the JAR manually" instead.
Without Maven / Gradle, reference the compiled JAR directly:
- Get
darra-ethercat-master.jarfrom the downloads page and put the runtime libraries for your platform in the runtime directory as well - The bridge dependencies are declared by
pom.xml; resolving them through Maven / Gradle is recommended — when referencing manually, put them on-cpas well - Compile and run:
javac -cp "darra-ethercat-master.jar" App.java
java -cp "darra-ethercat-master.jar;." App
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
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.
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:
| Capability | Description |
|---|---|
| One-step initialization | createFromJson() / 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 transition | setState runs the multi-step state transition chain automatically |
| PDO process data | inputsMapping / outputsMapping map once and connect straight to the process image; copyInputPdo / writeOutputPdo are whole-frame snapshots |
| CiA 402 state machine | slave.cia402() provides one-step enable / fault reset / state parsing |
| EMCY emergency messages | slave.coe().getEmergencyHistory() / clearEmergencyHistory() read and clear the emergency message history of that slave |
| Topology and redundancy | Build and query the slave topology tree; dual-NIC ring redundancy |
| Mailbox protocols | Unified interface for the seven mailbox protocols + statistics + ETG.8200 mailbox gateway, see Mailbox gateway |
| Real-time driver | Microsecond-level PDO cycles, provided with the installer |
Capability index
Find the entry point and the detail page by capability:
| Capability | Entry point | Details |
|---|---|---|
| Master creation and build | EtherCATMaster.create() / createFromJson() / createFromJsonFile() | Initialization |
| Master API and state machine | master.setState() | Master API |
| Master configuration | master.config() | Configuration |
| Distributed Clocks (DC) | master.configureDCAll() / slave.DC() | DC configuration · Slave DC |
| Diagnostics | master.diagnostics() / slave.diagnostics() | Diagnostics · Slave diagnostics |
| Events | master.events() | Events · Slave events |
| Logging | master.logs() | Logging |
| ENI / DENI configuration | setENI() / build() | ENI / DENI |
| Slave groups | Slave grouping query | Groups |
| hot-plug | Replacing a station while running and confirming station replacement | hot-plug |
| Redundant network | setNetwork(主网卡, 备网卡) | Redundancy |
| Master object dictionary | master.masterOD() | Master object dictionary |
| Mailbox gateway | master.mailboxGateway() | Mailbox gateway |
| Slave object | new Slave(masterIndex, slaveNum, master) / master.getSlave(n) | Slave · Slave API |
| PDO process data | slave.slavePdo() | PDO read/write |
| Slave topology | master.slaveTopology() / slave.topology() | Slave API |
| Slave state mirror | slave.wcContributed() / slave.alStatusMirror() / slave.isLost() | Slave diagnostics |
| ESI DC capability | slave.DC().hasEsiDcSync() / dcSyncModeFromEsi() | Slave DC |
| CiA 402 / CiA 401 | slave.cia402() / slave.cia401() | CiA 402 · CiA 401 |
| CoE (SDO / EMCY / OD) | slave.coe() | CoE |
| FoE file transfer | slave.foe() | FoE |
| SoE IDN parameters | slave.soe() (including SERCOS IDN encoding/decoding SoE.SoEElementFlags / SoE.IdnTriple) | SoE |
| AoE channels | slave.aoe() | AoE |
| EoE Ethernet | slave.eoe() | EoE |
| VoE vendor protocol | slave.voe() | VoE |
| FSoE safety | slave.fsoe() | FSoE |
| Modular device MDP | Modular devices are detected and configured automatically when entering OP | MDP |
| Async calls | Async entry points such as setNetworkAsync() / buildAsync() and the CompletableFuture extensions | Sugar |
| Sugar | com.darra.ethercat.sugar | Sugar |
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) andecStateGetNameEn(int)(English: INIT/PREOP/SAFEOP/OP/BOOT). pdoDataTypeName(int)returns the authoritative protocol name (upper case, such asINT8/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).
| Category | Method | Type / Returns | Read/write | Description |
|---|---|---|---|---|
| WKC baseline | getExpectedWKC() | short | read-only | Expected 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 baseline | setExpectedWKC(short) | void | call | Sets the expected WKC; call it during the configuration phase only |
| Counter control | resetDiagnostics() | void | call | Clears the diagnostic counters |
| Counter control | resetSlavePortErrorCounters(short) | boolean | call | Clears the port error counters of the specified slave |
| Counter control | updateSnapshot() | void | call | Refreshes the diagnostic snapshot immediately |
| Cycle statistics | recordPDOCycleStart() | void | call | Records the start of one PDO cycle manually |
| Cycle statistics | recordWKC(short) | void | call | Records one measured WKC value manually |
| Cycle statistics | getCycleStatistics() | DarraCore.CommunicationStats | read-only | Communication statistics snapshot; returns null when it cannot be read |
| Cycle statistics | getPDOAvgCycleTimeNs() | long | read-only | Average cycle time (nanoseconds); returns 0 when there is no data |
| Cycle statistics | getPDOErrorCount() | int | read-only | Total number of failed cycles; returns 0 when there is no data |
| Cycle statistics | getJitterUs() | double | read-only | Cycle jitter = maximum cycle − minimum cycle (microseconds) |
| System management interrupt | getSmiMsrAvailable() | long | read-only | Whether the hardware counter is readable: 1 = readable, 0 = unavailable |
| Real-time thread | getRtPreemptCount() | long | read-only | Cumulative number of times the real-time thread was preempted |
| Real-time thread | getRtPreemptPeakNs() | long | read-only | Peak duration of a preemption of the real-time thread (nanoseconds) |
| Real-time thread | getBigGapUnknownCount() | long | read-only | Cumulative 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.
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.
| Category | Property | Type | Read/write | Description |
|---|---|---|---|---|
| Communication statistics | TotalCycles | int | read-only | Total number of cycles |
| Communication statistics | SuccessfulCycles | int | read-only | Number of successful cycles |
| Communication statistics | FailedCycles | int | read-only | Number of failed cycles (the source of getPDOErrorCount()) |
| Communication statistics | TimeoutCycles | int | read-only | Number of timed-out cycles |
| Communication statistics | AverageCycleTimeUs | double | read-only | Average cycle time (microseconds) |
| Communication statistics | MaxCycleTimeUs | double | read-only | Maximum cycle time (microseconds) |
| Communication statistics | MinCycleTimeUs | double | read-only | Minimum 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.
Link and port diagnostics
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.
| Category | Method | Type / Returns | Read/write | Description |
|---|---|---|---|---|
| Port link | getPhyLinkState() | int | read-only | Two-port bitmap: bit0 = primary port up, bit1 = secondary port up; 0xFFFF = not observable |
| Slave link | getSlaveLinkQuality(short) | short | read-only | Link quality of the specified slave, 0–100%; -1 = unknown / read failed |
| Event ring | getLinkDiagEventCount() | long | read-only | Cumulative total number of link diagnostic events (including history already overwritten by the ring) |
| Event ring | getLinkDiagSeq() | long | read-only | Event ring freshness token: monotonically increasing = recording, no longer increasing = recording is not running |
| Event ring | getLinkDiagEvents(long) | LinkDiagEvent[] | read-only | Reads 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.
| Category | Property | Type | Read/write | Description |
|---|---|---|---|---|
| Event field | timestampUs | long | read-only | Event time (microseconds) |
| Event field | seq | int | read-only | Monotonically increasing sequence number per master |
| Event field | kind | LinkDiagEventKind | read-only | Event kind |
| Event field | port | int | read-only | Port number 0–3 (meaningful only for port events; 0xFF otherwise) |
| Event field | fromState / toState | int | read-only | Previous / new redundancy state |
| Event field | aPeer / aSelf / bPeer / bSelf | int | read-only | Raw snapshot of the trigger tick quadruple (0–65535) |
| Event field | ringIntact | boolean | read-only | true = the ring is closed, false = the ring is broken |
| Event field | isUp | boolean | read-only | true = recovery edge, false = disconnect edge |
| Event field | effectiveWkc | int | read-only | Measured WKC of the topology union |
| Event field | expectedWkc | int | read-only | Expected 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
| Category | Method | Type / Returns | Read/write | Description |
|---|---|---|---|---|
| Redundancy status | getRedundancyStatus() | DarraCore.RedundancyStatus | read-only | Redundancy status snapshot; null = redundancy not enabled / not connected / read failed |
| Redundancy status | isPrimaryLinkUp() | boolean | read-only | Whether the primary link is connected; false when there is no snapshot |
| Redundancy status | isSecondaryLinkUp() | boolean | read-only | Whether the secondary link is connected; false when there is no snapshot |
| Redundancy status | getFailoverCount() | int | read-only | Number 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.
| Category | Property | Type | Read/write | Description |
|---|---|---|---|---|
| Redundancy status | State | int | read-only | 0 = not enabled, 1 = primary port only, 2 = secondary port only, 3 = both ports |
| Redundancy status | PrimaryLinkUp | int | read-only | Whether the primary link is connected (a value other than 0 = connected) |
| Redundancy status | SecondaryLinkUp | int | read-only | Whether the secondary link is connected (a value other than 0 = connected) |
| Redundancy status | PrimaryTxFrames / PrimaryRxFrames | int | read-only | Frames sent / received on the primary link |
| Redundancy status | SecondaryTxFrames / SecondaryRxFrames | int | read-only | Frames sent / received on the secondary link |
| Redundancy status | FailoverCount | int | read-only | Number of failovers |
| Redundancy status | LastFailoverTime | int | read-only | Time 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.
| Category | Method | Type / Returns | Read/write | Description |
|---|---|---|---|---|
| Measured topology | getTopoPriIntact() | int | read-only | Expected 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 topology | getTopoSecIntact() | int | read-only | Branch 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.
| Category | Method | Type / Returns | Read/write | Description |
|---|---|---|---|---|
| Object dictionary | readEtg1510Object(int, byte) | byte[] | read-only | Reads a master object dictionary entry; returns null on failure |
| Object dictionary | writeEtg1510Object(int, byte, byte[]) | boolean | call | Writes 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 range0x0000–0xFFFF; an out-of-range value throwsIllegalArgumentException(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 range0x0000–0xFFFF; an out-of-range value throwsIllegalArgumentException.subindex— subindex.data— data to write; must not benullor 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.
| Category | Method | Type / Returns | Read/write | Description |
|---|---|---|---|---|
| Scan verdict | decodeNicScanStatus(int) | NicScanStatus | read-only | Decodes the raw slave count / reason code of each port into a verdict enum |
| NIC information | getNetworkInfo(String) | NetworkInfo | read-only | Gets a single NIC by adapter name; returns null when it is not found |
| Scan result | getScannedSlaveInfoList() | List<ScannedSlaveInfo> | read-only | Reads the slave details from the last scan; throws when the count falls short |
| NIC information | getSpeed() | long | read-only | Link speed (Mbps); the Java standard API has no source for the speed, so it always returns -1 |
| Scan diagnostics | lastScanWin32Error() | int | read-only | Raw error code of the most recent failure to open the NIC (thread-local) |
| Scan control | resetScanAbort() | void | call | Clears the abort flag before a new scan |
| Scan result | scannedSlaveGeneration() | int | read-only | Scan snapshot generation: even = stable / odd = being written |
| Display helper | aliasAddrHex(ScannedSlaveInfo) | String | read-only | Formats the alias address as 0xXXXX |
| Display helper | vendorIDHex(ScannedSlaveInfo) | String | read-only | Formats the vendor ID as 0xXXXXXXXX |
| Device discovery | determineCouplerStatus(List<ScannedSlaveInfo>) | List<Map<String, Object>> | read-only | Picks 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()istrue, and it is not folded intoNOT_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).
| Category | Property | Type | Read/write | Description |
|---|---|---|---|---|
| Slave details | vendorId | int | read-only | Vendor ID |
| Slave details | productCode | int | read-only | Product code |
| Slave details | revision | int | read-only | Revision number |
| Slave details | serialNumber | int | read-only | Serial number |
| Slave details | name | String | read-only | Slave name |
| Slave details | configAddr | short | read-only | Configuration address |
| Slave details | aliasAddr | short | read-only | Alias address |
| Slave details | parent | short | read-only | Parent slave configuration address |
| Slave details | topology | byte | read-only | Topology type |
| Slave details | activePorts | byte | read-only | Active port bitmap |
| Slave details | entryPort | byte | read-only | Entry port |
| Slave details | parentPort | byte | read-only | Port through which the slave is attached to its parent |
| Slave details | physicalType | byte | read-only | Physical 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— alwaystrue;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 benull.
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 asnew Startup.StartupParameterList(masterNum, slaveNum); it implementsIterable<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);
| Category | Property | Type | Read/write | Description |
|---|---|---|---|---|
| State transition | transitionEnum() | Startup.Transition | read-write | The state transition at which this parameter takes effect; defaults to IP |
| Compatibility property | phase() | int | read-write | Numeric form of the state transition (0 = IP / 1 = PS / 2 = SO) |
| Write timing | isWriteTimingManuallySet() | boolean | read-only | Whether the write timing has been set manually |
| Category | Method | Type / Returns | Read/write | Description |
|---|---|---|---|---|
| Parameter registration | addParameter(short, byte, byte[], String, int, boolean) | boolean | call | Builds 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 benull(when the write timing has not been set manually, aNullPointerExceptionis 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 asPS.
Returns (getter): the state transition number 0–5.
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:
transitionis parsed after upper-casing;nullis treated asIP;dataset tonullis treated as an empty array;- the description is generated automatically as
Write 0xXXXX:YYorRead 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(SIis the same asPI);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