Hot-plug
Hot-plug means unplugging a module, swapping it and plugging it back in while the system is running. Tell the two uses apart first, because their configuration and who handles what are completely different.
| Mode | Typical use | What gets swapped | Does the master need reconfiguring |
|---|---|---|---|
| Fixed slot · spare replacement | Routine motors, remote IO modules; fixed position, fixed order | A spare of the same model | No. Plug it back into the original slot or the chain end and the master recovers automatically with the original configuration |
| Tool module swap | Robot fixtures, all kinds of tool modules; swap any time | Possibly a different model, different PDO layout | Yes. Declare the tool module in the DENI first; the application layer picks the matching tool module from the event and configures it |
Both of these are called hot-plug, but the responsibility differs. A fixed slot only takes a spare of the same model, and when it is plugged back into its original slot or at the chain end the bus layer can handle it fully automatically; a tool module swap changes the model and the purpose, the master does not know how to use the new tool module, so the application layer has to take part.
| Layer | What the master does automatically | What the application layer must do |
|---|---|---|
| Bus layer | A dropped slave does not stop the bus, does not lower the expected count, and reports the reason truthfully; on re-insertion it rediscovers the module, checks the identity and pushes the module back to OP as declared | Nothing |
| Application layer | Reports the identity expected by the configuration together with the identity actually read | Decide which tool module was swapped in, choose the PDO layout and the process parameters, and decide when further motion is allowed |
If it is fully automatic, why does the application still have to take part? Because the master only understands identity and declarations, not processes. It can make "who occupies this slot now" automatic and truthful; as for "how this tool module is used", only your program knows. Hot-plug events are the handover point between the two: as soon as a slot changes, the master reports the expected identity and the measured identity together, and you make the choice and the configuration at the application layer.
Properties
| Category | Property | Type | Read/write | Description |
|---|---|---|---|---|
| Bind mode | master.getHotplugBindMode() / master.setHotplugBindMode(mode) | HotplugBindMode | Read/write | Which declared slot in the DENI a field module maps to. Default BY_IDENTITY; a value set before build() affects this link-up, one set afterwards only affects the next re-insertion or rebuild |
| Absence policy | slave.isOptional() / slave.isOptional(true) | boolean | Read/write | Whether this slot may be absent. In the DENI it is written <deni:Optional>true</deni:Optional>; in code it must be set before setState(EcState.OP) |
| Recovery observability | diag.getHotSwapRescanCount() | int | Read-only | Completed rounds of automatic rebuild so far. Use it to confirm that the master really tried |
| Recovery observability | diag.getLastHotSwapRescanResult() | int | Read-only | Result code of the last automatic rebuild. 0 = success or nothing has happened yet; a negative value = the specific failure reason |
diag is the master diagnostics entry point, created from the master index: Diagnostics diag = new Diagnostics(master.MasterIndex);. Recovery observability also has getLastHotSwapRescanTimeMs() (the time of the last completion); the meaning of the result codes of the three methods is in Diagnostics.
Both binding modes identify by identity; neither hard-binds by index:
BY_IDENTITY(1, the default): match by alias (the ESC alias burned into the module EEPROM) first, then by Vendor + Product; the wiring order has no effect. Use it when a tool module may change position. When there are several modules of the same model, burn a different alias into each one so ownership stays unambiguous when one is absent.BY_POSITION(0): a declared position carries engineering meaning — every declared slot is one physical workstation. Identification still goes by alias + Vendor + Product; the extra requirement is that the relative physical order of the modules present matches the declared order. Missing slaves are allowed and the modules behind them do not shift forward. Use it for fixed wiring where only same-model spares are swapped: a mismatch between the wiring order and the declared order is called out; same-model swaps cannot be told apart, so alias has to do that work.
Declare an optional slot in the DENI and make the alias match what is burned into the module EEPROM:
<Slave>
<Info>...</Info>
<deni:SlaveConfig>
<deni:Position>3</deni:Position>
<deni:AliasAddress>0x0103</deni:AliasAddress>
<deni:Optional>true</deni:Optional>
</deni:SlaveConfig>
</Slave>
The binding mode must be set before build():
EtherCATMaster ecat = EtherCATMaster.create().setENI("C:/EtherCAT/line.deni");
// Fixed wiring, only same-model spares swapped: let the master also check the workstation order
ecat.setHotplugBindMode(HotplugBindMode.BY_POSITION);
EtherCATMaster.BuildResult result = ecat.build();
A change takes effect on the next scan / configuration load / re-plug rebuild, and does not rewrite bindings that are already established. Passing null throws IllegalArgumentException on the spot, and a rejection from the underlying layer throws IllegalStateException; in both cases the current value is left unchanged. It never silently runs in the default mode.
Methods
acknowledgeSlaveReplacement(int slaveNum)
On an identity mismatch the master refuses to let the module through: it does not guess whether the module you fitted will work, it keeps that station out of OP, reports SlaveIdentityMismatch, and retries on its own back-off schedule. During the back-off it does not read the identity every cycle, and it does not apply the old configuration to the new module.
acknowledgeSlaveReplacement is the signal meaning "the person has finished handling it, check again right away". Once called, the master clears the back-off for that station and re-reads the identity in the next scan cycle:
- It matches → the module is recovered automatically and
SlaveOnlineis raised - It still does not match →
SlaveIdentityMismatchis reported again and the back-off continues
It does not change the expected identity in the configuration, and it does not force a module of a different model through. It only makes the master retry earlier; it does not make the "can this module be used" decision for you.
That is also why it is exposed: only the site or the application knows when the swap is finished and whether the right spare was fitted. The SDK cannot make that judgement for you, and it should not make you restart the whole bus just to retry one slot immediately.
public boolean acknowledgeSlaveReplacement(int slaveNum)
Parameters:
slaveNum(int) — slave index (1-based, matches the configuration)
Returns:
boolean—truewhen the request is accepted and the identity is re-checked immediately;falsewhen the parameter is invalid or this station is not currently in the lost state (there is no replacement to confirm)
Calling it on a station that has already recovered, or that never dropped out in the first place, returns false.
Example:
if (master.acknowledgeSlaveReplacement(3))
System.out.println("已让主站重新核对从站 3"); // Told the master to re-verify slave 3
else
System.out.println("从站 3 当前没有待确认的替换,或编号无效"); // Slave 3 currently has no pending replacement to acknowledge, or the index is invalid
Events
All hot-plug events live on master.events(). The three events have different jobs:
SlaveIdentityMismatch— the module in this slot does not match the identity expected by the configuration. The payload carries the expected and the measured Vendor / Product / Revision; whether the model changed is judged from Vendor and Product.SlaveOffline— the module no longer answers.SlaveOnline— the module answers again. It only means the station was rediscovered, not that it has reached OP; whether it is usable still depends onslave.state()andslave.isLost().
The full event list is in Events.
public void addSlaveIdentityMismatchListener(SlaveIdentityMismatchListener listener)
public void addSlaveOfflineListener(SlaveOfflineListener listener)
public void addSlaveOnlineListener(SlaveOnlineListener listener)
master.events().addSlaveIdentityMismatchListener(args -> {
// Reaching here means Vendor or Product does not match the configuration: a different model, or plugged into the wrong position
System.out.printf("从站 %d 实测 0x%08X/0x%08X,配置期望 0x%08X/0x%08X%n", // Slave %d measured 0x%08X/0x%08X, configuration expects 0x%08X/0x%08X%n
args.slaveIndex, args.actualVendor, args.actualProduct,
args.expectedVendor, args.expectedProduct);
});
master.events().addSlaveOfflineListener(slaveIndex ->
System.out.printf("从站 %d 离线%n", slaveIndex)); // Slave %d offline%n
master.events().addSlaveOnlineListener(slaveIndex ->
System.out.printf("从站 %d 重新应答(是否到 OP 看 slave.state())%n", slaveIndex)); // Slave %d responded again (whether it reached OP: see slave.state())%n
SlaveIdentityMismatch
Raised when a module does not match. The criterion is that Vendor or Product differs from the configuration (in alias-bound scenarios the alias is checked as well). Revision never takes part in a rejection: different versions of the same model (spares, firmware upgrades) are treated as the same model and the master only refreshes the record. That is also why a same-model spare plugged back into its original slot or at the chain end can recover automatically.
| Field | Type | Description |
|---|---|---|
masterIndex | int | Master index |
slaveIndex | int | Slave index (1-based) |
expectedVendor / expectedProduct / expectedRevision | long | The identity expected by the configuration |
actualVendor / actualProduct / actualRevision | long | The identity actually read right now |
Java has no unsigned integer type, so these six identity fields carry 32-bit unsigned values in long; print them with %08X.
Vendor and Product are the hard criteria; Revision is only recorded and used for troubleshooting. The default identity match mode is IGNORE_REVISION; Revision is compared only after switching it to EXACT / COMPATIBLE_HIGHER. Scanning in this SDK always runs as IGNORE_REVISION, and the switch cannot currently be dispatched — see Configuration. If the Vendor/Product in the event looks consistent but the master still reports an identity mismatch, check that this station's alias matches the DENI declaration (alias-bound scenarios count it into the criteria).
The master retries this station on its back-off schedule and does not repeat the event every cycle. Once the identity is corrected, the next retry (or an immediate retry through acknowledgeSlaveReplacement) recovers it; if it is still wrong, SlaveIdentityMismatch is reported again.
SlaveOffline
Raised when a module no longer answers. The callback carries only a slave index: SlaveOfflineListener.onSlaveOffline(short slaveIndex).
An optional slot that is declared in the DENI but has never been plugged in since link-up may also receive an offline notice reported at its declared position. That is not a slave loss — it means the slot never came up — and it is simply handled as an optional absence. To tell the reasons apart, subscribe to addSlaveOfflineDetailedListener: it is delivered in the same tick as the offline event, and its payload SlaveOfflineEventArgs carries reason (really offline / not acknowledged by the server / unknown) and the evidence at that moment (probe, contribution, timestampUtc); the field meanings are in Events.
SlaveOnline
Raised when a module answers again. The callback likewise carries only a slave index: SlaveOnlineListener.onSlaveOnline(short slaveIndex).
It only means the station has been seen again; it does not mean it has reached OP. Only after the master configures the module automatically and promotes it to OP does slave.state() become EcState.OP. Before writing outputs, confirm both that slave.isLost() == false and that the state is a clean OP (state() does not carry the Error bit, so judging a clean OP also requires slave.hasError() == false).
What happens after plugging in
After a module is plugged back in, the master handles it in the following order:
- Detect — the module is seen answering again in the cyclic communication.
- Find the slot — under the current binding mode, the corresponding slot is found in the configuration.
- Check the identity — see whether the module plugged back in is the one you declared: Vendor and Product must match. A difference in Revision is only recorded and is not a reason to reject (same-model spares and firmware upgrades are both allowed). Several modules of the same model are told apart by alias, so one is never mistaken for another.
- Configure automatically — once the module is confirmed, the master applies that slot's configuration and drives the module to OP.
- Restore the data — PDOs take effect with the layout from the configuration and inputs and outputs refresh as usual; the other slaves are not affected.
Automatic promotion is not unconditional. Only two cases are handled automatically: a module plugged in at the end of the chain, or re-inserted into its original empty slot. The master checks about once per second, and a module already being promoted is not triggered again. Automatic rebuild is the master's default behaviour with no separate switch; what you have to do is declare the slots and identities clearly in the DENI.
If a module is plugged in mid-chain and shifts the order of the modules behind it, the master does not handle it automatically: it does not rewrite the positions of other modules; it stops and prompts you to rescan the bus. This is deliberate — rewriting positions would misconfigure other stations.
Automatic promotion covers only chain-end insertion and empty-slot re-insertion, and expected_wkc does not change because of automatic promotion.
| Situation | Master behavior | What the application layer must do |
|---|---|---|
| Declared, matches the declaration, at the chain end or re-inserted into an empty slot | Configured automatically and brought up to OP | Nothing to do |
| Declared, same model (different Revision), plugged back into its original slot or at the chain end | Accepted as the same model, the record is refreshed, and it is promoted normally | Nothing to do; Revision is only recorded and is not a reason to reject |
| Declared, swapped for a different model (tool module) | The old slot configuration is not applied to the new module; if the DENI declares this tool module separately and the identity matches, it is configured from that declaration; if no declaration is found, an identity mismatch or an extra device is reported and the module is not promoted | Pick the configuration from the tool module catalog; when the DENI does not declare this tool module, add the declaration first and rebuild |
| Declared, matches the declaration, but inserted mid-chain and shifts the later modules | Not promoted; prompts you to rescan the bus | Stop and rescan, or rebuild |
| Device not in the configuration | Not promoted; reported truthfully as an extra device | Handle it manually, or add the device to the DENI |
| Optional slot absent | Not an error; the other slaves keep running as usual | Nothing to do |
| Mandatory slot absent | OP is not reached; the absence is reported truthfully | Check the power supply, the wiring and the configuration |
When troubleshooting, look at three things first: slave.isLost() (whether the loss is confirmed), slave.state() (the current state) and slave.errorCode() (the full AL Status Code). state() only gives the basic state, so judging a clean OP also requires slave.hasError() == false. For an identity mismatch, look at the expected and the measured identity in SlaveIdentityMismatch; if it reaches OP and then drops, or never reaches OP at all, look at the AL code and the startup parameter (SDO) errors. The AL code table is in Diagnostics.
If getHotSwapRescanCount() never grows, the master has not started an automatic rebuild: it may not be in a steady OP, the physical slave count may not exceed the registered count, or a mid-chain insertion may have been stopped by the order gate. getLastHotSwapRescanResult() gives the last result code, where a negative value is the specific failure reason.
Automatic promotion happens only for modules that are declared in the configuration and match their declaration. Extra devices that are not declared, and modules that do not match, are never promoted automatically: the master does not pull them into OP just because they were plugged in, and it does not add them to the control outputs by itself. Plugging an extra device into a production line does not turn it into a station that can be written to.
Failures are reported truthfully; a failure is never reported as success. The station stays un-promoted and the reason is given (does not match / unknown device / missing configuration / promotion failure), and recovery keeps retrying. actual_wkc reflects the missing station truthfully, and expected_wkc is never lowered to make the numbers match.
Tool module change: how the application layer picks and configures
The point of a tool module swap is not the unplugging and the plugging — it is the choice and the configuration the application layer has to make after the module is plugged in. The three steps below are recommended.
Step one: declare every tool module you might use in the DENI. Each tool module takes one declared slot with its own Vendor / Product / PDO layout, marked optional (<deni:Optional>true</deni:Optional>). If the workstation is fixed, write a fixed Position; if a tool module may change position, use BY_IDENTITY and burn a unique alias other than 0 into each tool module. For a tool module that is not declared in the DENI the master will not guess how to configure it — it only reports "identity mismatch" or "extra device" truthfully.
<!-- Tool module positions: both tool modules are declared as optional slots, each with its own PDO layout -->
<Slave>
<Info>
<VendorId>#x00000002</VendorId>
<ProductCode>#x09224052</ProductCode>
</Info>
<deni:SlaveConfig>
<deni:Position>10</deni:Position>
<deni:AliasAddress>0x0110</deni:AliasAddress>
<deni:Optional>true</deni:Optional>
</deni:SlaveConfig>
</Slave>
<Slave>
<Info>
<VendorId>#x00000002</VendorId>
<ProductCode>#x09224053</ProductCode>
</Info>
<deni:SlaveConfig>
<deni:Position>11</deni:Position>
<deni:AliasAddress>0x0111</deni:AliasAddress>
<deni:Optional>true</deni:Optional>
</deni:SlaveConfig>
</Slave>
Step two: use the event to tell a spare apart from a model change. Look at the expected and the measured identity in SlaveIdentityMismatch:
- Vendor and Product the same → the same model; a difference in Revision is only a version difference, and when it is plugged back into its original slot or at the chain end the master recovers it as a spare, so the application layer does not change the configuration.
- Vendor or Product different → the model changed, so handle it as a tool module swap.
acknowledgeSlaveReplacement only means anything for "the correct module was swapped back in"; a module of a different model is not accepted because of it. A tool module swap goes through a DENI declaration plus application-layer configuration.
If the new tool module is already declared in the DENI and the identity matches, the master configures it to OP from that declaration; at that point you usually receive SlaveOnline first. Once you have read the actual identity from that station, run the same selection and configuration below.
Step three: pick the configuration from the measured identity and send it down. Use slave.vendorId() / slave.productId() / slave.revId() to look up the matching configuration in the tool module catalog, first verify that slave.ibytes() / slave.obytes() match the PDO layout of this tool module, then send the process parameters (SDO) and the safe output values. If any one of them does not match, do not write outputs: hold the safe state and raise an alarm.
PDO assignment follows the DENI; do not adapt a new tool module by changing the PDO mapping from the application layer at runtime. Swapping in a model that the DENI does not declare is handled by adding the declaration and rebuilding the link, not by hard-rewriting the mapping at runtime.
import com.darra.ethercat.data.EcState;
import com.darra.ethercat.master.EtherCATMaster;
import com.darra.ethercat.slave.CoE;
import com.darra.ethercat.slave.Slave;
// Tool module catalog: find the PDO layout, process parameters and safe outputs from the measured identity
void onModuleChanged(EtherCATMaster master, int slaveIndex) {
// Build this station directly from the master index + slave index (the DENI path way, see ENI/DENI configuration loading)
Slave slave = new Slave(master.MasterIndex, (short) slaveIndex, master);
// Configure and write outputs only on a clean OP; offline, OP+Error and not in OP all count as unusable
if (slave.isLost() || slave.state() != EcState.OP || slave.hasError()) return;
ToolConfig tool = toolCatalog.find(slave.vendorId(), slave.productId(), slave.revId());
if (tool == null) {
System.out.printf("从站 %d 插入了未登记工具模块,保持安全态%n", slaveIndex); // Slave %d has an unregistered tool module inserted, staying in safe state%n
return;
}
if (slave.ibytes() != tool.inputBytes || slave.obytes() != tool.outputBytes) {
System.out.printf("工具模块 %s 的 PDO 大小与 DENI 不一致,拒绝配置%n", tool.name); // Tool module %s PDO size does not match DENI, configuration rejected%n
return;
}
for (Param p : tool.parameters) {
CoE.SdoWriteResult w = slave.coe().sdoWrite(p.index, p.subIndex, p.data);
if (!w.ok)
System.out.printf("参数 0x%04X:%02X 写入失败,中止码 0x%08X%n", // Parameter 0x%04X:%02X write failed, abort code 0x%08X%n
p.index, p.subIndex, w.abortCode);
}
// Apply all output patches in one versioned transaction; a return of 0 means nothing landed
if (slave.PDO().batchWrite(new int[] { 0 }, new byte[][] { tool.safeOutputs }) == 0)
System.out.printf("工具模块 %s 的安全输出写入失败%n", tool.name); // Failed to write the safety output of tool module %s%n
}
Complete example
import com.darra.ethercat.master.EtherCATMaster;
import com.darra.ethercat.data.EcState;
import com.darra.ethercat.data.EtherCATTypes.HotplugBindMode;
EtherCATMaster ecat = EtherCATMaster.create().setENI("C:/EtherCAT/line.deni");
// Fixed slot + spare replacement: position and order are fixed, so use BY_POSITION.
// It must be set before build(): build() binds the slots declared in the DENI to the measured slaves according to it.
ecat.setHotplugBindMode(HotplugBindMode.BY_POSITION);
EtherCATMaster.BuildResult result = ecat.build();
if (!result.success) {
System.out.println("初始化失败:" + result.message); // Initialization failed:
return;
}
EtherCATMaster master = result.master;
if (master == null) return;
master.events().addSlaveIdentityMismatchListener(args -> {
// Vendor or Product does not match: a different model, or plugged into the wrong position.
// A Revision difference between same-model modules never reaches here; the master recovers it as a spare.
System.out.printf("从站 %d 实测 0x%08X/0x%08X,配置期望 0x%08X/0x%08X%n", // Slave %d measured 0x%08X/0x%08X, configuration expects 0x%08X/0x%08X%n
args.slaveIndex, args.actualVendor, args.actualProduct,
args.expectedVendor, args.expectedProduct);
});
master.events().addSlaveOfflineListener(slaveIndex ->
System.out.printf("从站 %d 离线%n", slaveIndex)); // Slave %d offline%n
master.events().addSlaveOnlineListener(slaveIndex ->
System.out.printf("从站 %d 重新应答(到 OP 后再配置)%n", slaveIndex)); // Slave %d responded again (configure after it reaches OP)%n
if (!master.setState(EcState.OP))
System.out.println("切换 OP 失败"); // Failed to switch to OP
// After the operator has swapped the correct module back in, let the master re-check this station:
// master.acknowledgeSlaveReplacement(3);
master.close();