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.hotplug_bind_mode() / master.set_hotplug_bind_mode(mode) | HotplugBindMode | Read/write | Which declared slot in the DENI a field module maps to. Default ByIdentity; a value set before build() affects this link-up, one set afterwards only affects the next re-insertion or rebuild |
| Absence policy | slave.is_optional() / slave.set_optional(flag) | bool | 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 set_state(EcState::Operational) |
| Recovery observability | master.diagnostics_info().hot_swap_rescan_count() | u32 | Read-only | Completed rounds of automatic rebuild so far. Use it to confirm that the master really tried |
| Recovery observability | master.diagnostics_info().last_hot_swap_rescan_result() | HotSwapCode | Read-only | Result code of the last automatic rebuild. Ok = success or nothing has happened yet (disambiguate with the round count or the time), the other variants = the specific failure reason |
Both binding modes identify by identity; neither hard-binds by index:
ByIdentity(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.ByPosition(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():
use darra_ethercat::{EtherCATMaster, HotplugBindMode};
let built = EtherCATMaster::builder()
.set_eni(r"C:\EtherCAT\line.deni")
// Fixed wiring, only same-model spares swapped: let the master also check the workstation order
.set_hotplug_bind_mode(HotplugBindMode::ByPosition)
.build()?;
A change takes effect on the next DENI binding / configuration load / re-plug rebuild, and does not rewrite bindings that are already established. A mode set before build() is dispatched once as soon as the master index is obtained, and if that dispatch fails build() fails directly; on an instance where build() has already completed you can call set_hotplug_bind_mode at any time, it only affects the next re-insertion or rebuild.
HotplugBindMode has only two members, ByPosition / ByIdentity, so an illegal value cannot even be expressed in the type. To rebuild one from a raw u8, use HotplugBindMode::from_raw, which returns a parameter error for any value other than 0/1. A rejected setting returns Err and leaves the current value unchanged; it never silently runs in the default mode.
Methods
acknowledge_slave_replacement(slave_num)
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.
acknowledge_slave_replacement 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.
pub fn acknowledge_slave_replacement(&self, slave_num: u16) -> Result<bool>
Parameters:
slave_num(u16) — slave index (1-based, matches the configuration)
Returns:
Result<bool>—Ok(true)accepted and the identity is re-checked immediately;Ok(false)this station is not currently in the lost state (there is no replacement to confirm);Errthe parameter is invalid (slave_numis 0) or the master has been released
Calling it on a station that has already recovered, or that never dropped out in the first place, returns Ok(false).
Example:
if master.acknowledge_slave_replacement(3)? {
println!("已让主站重新核对从站 3"); // Master asked to re-check slave 3
} else {
println!("从站 3 当前没有待确认的替换"); // Slave 3 currently has no pending replacement to acknowledge
}
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.is_lost().
The full event list is in Events.
pub fn on_slave_identity_mismatch<F>(&self, callback: F)
where F: Fn(SlaveIdentityMismatch) + Send + Sync + 'static
pub fn on_slave_offline<F>(&self, callback: F)
where F: Fn(u16) + Send + Sync + 'static
pub fn on_slave_online<F>(&self, callback: F)
where F: Fn(u16) + Send + Sync + 'static
master.events().on_slave_identity_mismatch(|ev| {
// Reaching here means Vendor or Product does not match the configuration: a different model, or plugged into the wrong position
println!("从站 {} 实测 0x{:08X}/0x{:08X},配置期望 0x{:08X}/0x{:08X}", // Slave {} measured 0x{:08X}/0x{:08X}, configuration expects 0x{:08X}/0x{:08X}
ev.slave_index, ev.actual_vendor, ev.actual_product,
ev.expected_vendor, ev.expected_product);
});
master.events().on_slave_offline(|slave_index| println!("从站 {slave_index} 离线")); // Slave {slave_index} offline
master.events().on_slave_online(|slave_index|
println!("从站 {slave_index} 重新应答(是否到 OP 看 slave.state())")); // Slave {slave_index} is responding again (check slave.state() to see whether it reached OP)
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. The default identity match mode is "ignore Revision", and this SDK does not offer a switch for it.
| Field | Type | Description |
|---|---|---|
master_index | u16 | Master index |
slave_index | u16 | Slave index (1-based) |
expected_vendor / expected_product / expected_revision | u32 | The identity expected by the configuration |
actual_vendor / actual_product / actual_revision | u32 | The identity actually read right now |
Revision is only recorded and used for troubleshooting, never as a reason to reject; Vendor and Product are the hard criteria. 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 acknowledge_slave_replacement) 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: Fn(u16), with a 1-based slave index.
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 on_slave_offline_detailed: its payload SlaveOfflineEventArgs carries timestamp_utc / reason (the offline reason category) and the evidence at that moment, probe / contribution.
SlaveOnline
Raised when a module answers again. The callback likewise carries only a slave index: Fn(u16), with a 1-based slave index.
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::Operational. Before writing outputs, confirm both that slave.is_lost() == false and that the state is a clean OP.
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.is_lost() (whether the loss is confirmed), slave.state() (the current state) and slave.error_code() (the full AL Status Code). 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 hot_swap_rescan_count() 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. last_hot_swap_rescan_result() gives the last result code HotSwapCode, and description() is its explanation.
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 ByIdentity 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.
acknowledge_slave_replacement 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.vendor_id() / product_id() / rev_id() to look up the matching configuration in the tool module catalog, first verify that the ibytes / obytes given by slave.detailed_info() 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.
// Tool module catalog: find the PDO layout, process parameters and safe outputs from the measured identity
fn on_module_changed(master: &EtherCATMaster, slave_index: u16) -> darra_ethercat::Result<()> {
let slave = master.slave(slave_index)?;
// Configure and write outputs only on a clean OP; offline, OP+Error and not in OP all count as unusable
if slave.is_lost() || slave.state() != Some(EcState::Operational) {
return Ok(());
}
let tool = match tool_catalog.find(slave.vendor_id(), slave.product_id(), slave.rev_id()) {
Some(t) => t,
None => {
println!("从站 {slave_index} 插入了未登记工具模块,保持安全态"); // Slave {slave_index} has an unregistered tool module inserted, staying in the safe state
return Ok(());
}
};
// The PDO size follows the DENI declaration: verify it before sending anything down
let info = match slave.detailed_info() {
Some(i) => i,
None => {
println!("从站 {slave_index} 读不到 IO 字节数,拒绝配置"); // Slave {slave_index}: could not read the IO byte count, configuration rejected
return Ok(());
}
};
if info.ibytes != tool.input_bytes || info.obytes != tool.output_bytes {
println!("工具模块 {} 的 PDO 大小与 DENI 不一致,拒绝配置", tool.name); // Tool module {} PDO size does not match the DENI, configuration rejected
return Ok(());
}
// Send the process parameters one by one over SDO
for p in &tool.parameters {
if let Err(e) = slave.sdo_write(p.index, p.subindex, false, &p.data) {
println!("参数 0x{:04X}:{:02X} 写入失败:{}", p.index, p.subindex, e); // Failed to write parameter 0x{:04X}:{:02X}: {}
}
}
// Write the safe values back to the output process image as one whole frame
if slave.pdo().try_write_outputs(&tool.safe_outputs).is_err() {
println!("工具模块 {} 的安全输出写入失败", tool.name); // Failed to write the safety output of tool module {}
}
Ok(())
}
Complete example
use darra_ethercat::{EcState, EtherCATMaster, HotplugBindMode};
fn main() -> darra_ethercat::Result<()> {
let built = EtherCATMaster::builder()
.set_eni(r"C:\EtherCAT\line.deni")
// Fixed slot + spare replacement: position and order are fixed, so use ByPosition.
// It must be set before build(): build() binds the slots declared in the DENI to the measured slaves according to it.
.set_hotplug_bind_mode(HotplugBindMode::ByPosition)
.build()?;
if !built.success {
eprintln!("初始化失败:{}", built.message); // Initialization failed: {}
return Ok(());
}
let mut master = built.master;
master.events().on_slave_identity_mismatch(|ev| {
// 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.
println!("从站 {} 实测 0x{:08X}/0x{:08X},配置期望 0x{:08X}/0x{:08X}", // Slave {} measured 0x{:08X}/0x{:08X}, configuration expects 0x{:08X}/0x{:08X}
ev.slave_index, ev.actual_vendor, ev.actual_product,
ev.expected_vendor, ev.expected_product);
});
master.events().on_slave_offline(|slave_index| println!("从站 {slave_index} 离线")); // Slave {slave_index} offline
master.events().on_slave_online(|slave_index|
println!("从站 {slave_index} 重新应答(到 OP 后再配置)")); // Slave {slave_index} is responding again (reconfigure it after it reaches OP)
master.set_state(EcState::Operational)?;
master.start();
// After the operator has swapped the correct module back in, let the master re-check this station:
// master.acknowledge_slave_replacement(3)?;
Ok(())
}