Hot-plug
Hot-plug means unplugging, replacing and plugging a module back in while the system is running. First separate the two kinds of use: their configuration and "who handles it" are completely different.
| Mode | Typical scenario | What gets swapped | Does the master need reconfiguration |
|---|---|---|---|
| Fixed slot · Spare replacement | Regular motors, remote IO modules; fixed position and fixed order | Same-model spares | No. Plug it back into the original slot or the chain end and the master restores it automatically from the original configuration |
| Tool module change | Robot grippers, various tool modules; swapped at 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 ever takes a same-model spare, and when the module goes back into the original slot or the chain end the bus layer can handle it entirely on its own; a tool module change swaps the model and the purpose, and because the master does not know how the new tool module is meant to be used, the application layer has to be involved.
| Layer | What the master does automatically | What the application layer must do |
|---|---|---|
| Bus layer | A dropped slave does not stop the bus or lower the expectation, and the reason is reported truthfully; on re-insertion it is discovered automatically, its identity is checked, and it is brought back to OP on the declared configuration | No involvement needed |
| Application layer | Reports the identity expected by the configuration together with the identity actually read | Determine which tool module was swapped in, choose the PDO layout and process parameters, and decide when to allow operation to continue |
If it is all automatic, why does the application still have to take part? Because the master only recognizes identity and declarations, not process requirements. It can make "who is in this slot right now" automatic and truthful; as for "how this tool module should be used", only your program knows. Hot-plug events are the handoff point between the two: as soon as a slot changes, the master tells you the expected identity and the measured identity together, and you make the choice and the configuration in the application layer.
Properties
| Category | Property | Type | Read/write | Description |
|---|---|---|---|---|
| Binding mode | master.HotplugBindMode() / master.HotplugBindMode(mode) | darra::HotplugBindMode | Read/write | How a module on site maps to a declared slot in the DENI. Default ByIdentity; only a value set before Build affects this chain build, while a value set afterwards affects only the next re-insertion or rebuild |
| Absence policy | slave.IsOptional() / slave.IsOptional(true) | bool | Read/write | This slot may be absent. In a DENI it is written <deni:Optional>true</deni:Optional>; in code, set it before SetState(EcState::OP) |
| Recovery observability | diag_mirror::GetHotSwapRescanCount(mi) | uint32_t | Read-only | Cumulative completed rounds of automatic rebuild. Use it to confirm that the master really tried |
| Recovery observability | diag_mirror::GetHotSwapRescanLastResult(mi) | int | Read-only | Result code of the last automatic rebuild. 0 = success or nothing has happened yet, a negative value = the specific failure reason |
Both binding modes identify a module by its identity; neither hard-binds it by slot number:
ByIdentity(1, the default): alias first (the ESC alias in the module's EEPROM), then Vendor + Product matching; wiring order does not matter. Use it when tool modules may change position. When you have several modules of the same model, burn a different alias into each one so that the assignment stays unambiguous when one is absent.ByPosition(0): the declared position carries engineering meaning — each declared slot is one physical workstation. Identification is still alias + Vendor + Product; additionally, the relative physical order of the modules present must match the declared order. Missing slaves are allowed, and later modules do not shift forward. Use it for fixed wiring that only swaps same-model spares: a wiring order that does not match the declared order is called out; same-model modules cannot be told apart from each other, so that has to rely on alias.
Declare an optional slot in the DENI and make the alias match what is burned into the module's 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 master(dll);
master.SetENI("C:/EtherCAT/line.deni");
// Fixed wiring that only swaps same-model spares: have the master additionally verify the workstation order
master.HotplugBindMode(darra::HotplugBindMode::ByPosition);
master.Build();
A change takes effect on the next scan, configuration load or re-plug rebuild, and does not rewrite bindings that are already established. A value set before Build is first remembered by this instance and sent down as soon as Build() has the master instance and before the configuration file is read, so it already affects this chain build. Passing a value outside the enum throws std::invalid_argument; a rejection by the underlying layer (invalid master index / invalid mode) throws std::runtime_error; in both cases the current value is left unchanged. If the mode remembered before Build is rejected inside Build(), Build() returns false outright and LastError() gives the failure code; it never quietly runs in the default mode.
Methods
master_other::acknowledge_slave_replacement(EtherCATMaster& m, uint16_t slaveIndex)
When the identity does not match, the master refuses to let the module through: it does not guess "can the module you swapped in be used", but holds that station outside OP, reports SlaveIdentityMismatch, and then retries on its own backoff schedule. During the backoff it does not read the identity every cycle, and it never applies the old configuration to the new module.
acknowledge_slave_replacement is exactly this signal: "a person has finished handling it, check again right away". After the call the master clears the backoff for that station and re-reads the identity in the very next scan cycle:
- It matches → the module recovers automatically and
SlaveOnlineis raised - Still no match →
SlaveIdentityMismatchis reported again and the backoff continues
It does not change the expected identity in the configuration, and it never forces 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.
The reason it is exposed is also here: only the site or the application knows when the swap is finished and whether the correct spare was fitted; the SDK cannot make that judgment for you, and it should not make you restart the whole bus just to retry one slot immediately.
namespace darra { namespace ethercat { namespace master_other {
inline bool acknowledge_slave_replacement(EtherCATMaster& m, uint16_t slaveIndex);
} } }
Parameters:
m(EtherCATMaster&) — master referenceslaveIndex(uint16_t) — slave index (1-based, matches the configuration)
Returns:
bool— returnstrueif the request was accepted and the check restarted immediately;falseif the parameter is invalid, or if that station is not currently in the lost state (there is no replacement waiting to be confirmed)
Calling it on a station that has already recovered, or that never dropped out, returns false. Calling it before a SlaveIdentityMismatch event arrives is equally ineffective and returns false.
Example:
if (darra::ethercat::master_other::acknowledge_slave_replacement(master, 3))
printf("已让主站重新核对从站 3\n"); // Asked the master to re-verify slave 3\n
else
printf("从站 3 当前没有待确认的替换,或编号无效\n"); // Slave 3 has no pending replacement to acknowledge, or the index is invalid\n
Events
Hot-plug events all live on master.Events(). The three events have different roles:
SlaveIdentityMismatch— the module in this slot does not match the identity expected by the configuration. The payload carries the expected and 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().
For the full event list see Events.
void OnSlaveIdentityMismatch(SlaveIdentityMismatchCallback cb);
void OnSlaveLost(SlaveOfflineCallback cb);
void OnSlaveDiscovered(SlaveOnlineCallback cb);
master.Events().OnSlaveIdentityMismatch(
[&](uint16_t mi, uint16_t si,
uint32_t eV, uint32_t eP, uint32_t eR,
uint32_t aV, uint32_t aP, uint32_t aR) {
// Getting here means Vendor or Product does not match the configuration: the model changed, or it was plugged into the wrong position
printf("从站 %u 实测 0x%08X/0x%08X,配置期望 0x%08X/0x%08X\n", // Slave %u measured 0x%08X/0x%08X, configuration expects 0x%08X/0x%08X\n
si, aV, aP, eV, eP);
});
master.Events().OnSlaveLost([](uint16_t si) {
printf("从站 %u 离线\n", si); // Slave %u offline\n
});
master.Events().OnSlaveDiscovered([](uint16_t si) {
printf("从站 %u 重新应答(是否到 OP 看 slave.State())\n", si); // Slave %u is responding again (check slave.State() for whether it reached OP)\n
});
SlaveIdentityMismatch
Raised when a module's identity does not match. The criterion is that Vendor or Product differs from the configuration (binding by alias checks the alias too). Revision never causes rejection: different revisions of the same model (spares, firmware upgrades) are treated as the same model, and the master only refreshes the record; this is also why a same-model spare plugged back into the original slot or the chain end recovers automatically.
The callback carries 8 positional parameters and there is no separate payload structure:
| Parameter | Type | Description |
|---|---|---|
masterIndex | uint16_t | Master index |
slaveIndex | uint16_t | Slave index (1-based) |
expectedVendor / expectedProduct / expectedRevision | uint32_t | The identity expected by the configuration |
actualVendor / actualProduct / actualRevision | uint32_t | The identity actually read now |
Revision is used only for the record and for troubleshooting, never as grounds for rejection; Vendor and Product are the hard criterion. If the Vendor/Product in the event look identical and the master still reports an identity mismatch, check whether that station's alias matches its DENI declaration (alias binding counts it into the criterion).
The Revision matching rule is decided by master.GetConfig().ScanRevisionMatch(); this SDK defaults to ScanRevisionMatchMode::IgnoreRevision (only Vendor + Product are compared, Revision is not). ScanRevisionMatchMode also defines two optional modes, Exact and CompatibleHigher (CompatibleHigher requires the measured Revision not to fall below the configured value for a match), but this SDK currently does not support dispatching them to the scan: setting them on the configuration object returns false and logs a warning, and setting them at the scan or streaming-build entry points reports an error outright. When you need strict revision checking, read slave.RevId() in the application layer and compare it yourself.
The master retries that station on its backoff schedule and does not repeat the event every cycle. For one slave the event is raised only once while it sits in IDENT_REJECTED; once the identity is corrected, the next retry (or an immediate retry via acknowledge_slave_replacement) recovers it; if it is still not corrected, SlaveIdentityMismatch is reported again.
SlaveOffline
Raised when a module stops answering. The callback carries only a slave index: SlaveOfflineCallback(uint16_t slaveIndex).
An optional slot that is declared in the DENI but has never been plugged in since the chain was built may also receive an offline notification reported at the declared position. This is not slave loss; it means "this slot never came online" and is handled as an allowed absence. To tell the causes apart, subscribe to OnSlaveOfflineDetailed: it is delivered on the same tick as OnSlaveLost, and its payload SlaveOfflineEventArgs carries the offline reason classification (reason) and the evidence at the moment of delivery (probe / contribution); for the details see Events.
SlaveOnline
Raised when a module answers again. The callback likewise carries only a slave index: SlaveOnlineCallback(uint16_t slaveIndex).
It only means "this station is visible again"; it does not mean it has reached OP. Only after the master has configured the module automatically and promoted 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.
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 declared one: Vendor and Product must match. A Revision difference is recorded only and is not grounds for rejection (same-model spares and firmware upgrades are both allowed). When there are several modules of the same model they are told apart by alias, so one is never mistaken for another.
- Configure automatically — once it is confirmed, the master pushes the module up to OP on that slot's declaration.
- Restore the data — PDOs take effect with the declared layout, inputs and outputs refresh as usual, and the other slaves are unaffected.
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 behavior; it has no separate switch and no manual trigger entry point; 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 the original slot or the chain end | Accepted as the same model, the record is refreshed, and it is promoted normally | Nothing to do; Revision is recorded only and is not grounds for rejection |
| Declared, replaced with a different model (tool module) | Does not apply the old slot's configuration to the new module; if the DENI also declares this tool module and the identity matches, it is configured on that declaration; if it is not found, an identity mismatch or an extra device is reported and it is not promoted | Select the configuration from the tool module catalog; if the DENI does not declare this tool module, add the declaration first, then 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 the bus, 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 power, wiring, and configuration |
When troubleshooting, check three things first: slave.IsLost() (whether the dropout is confirmed), slave.State() (the current state) and slave.ErrorCode() (the full AL Status Code). For an identity mismatch, compare the expected and measured values in SlaveIdentityMismatch; if a module reaches OP and then drops again, or never reaches OP, 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 stable OP state, the number of physical stations may not exceed the number of registered stations, or a mid-chain insertion may have been blocked by the order gate. GetHotSwapRescanLastResult gives the result code of the last attempt, and a negative value means the specific failure reason; what the result codes mean is in Automatic rebuild accounting.
Automatic promotion happens only for modules that are declared in the configuration and whose identity check passes. 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 make it 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 (identity mismatch / 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 crux of a tool module change is not the unplugging and the plugging in, but the choice and the configuration the application layer has to make after the module is plugged in. The three steps below are the recommended way.
Step one: declare every tool module you might use in the DENI. Each tool module type takes one declared slot with its own Vendor / Product / PDO layout written out and marked optional (<deni:Optional>true</deni:Optional>). If the workstation is fixed, write a fixed Position; if tool modules may change position, use ByIdentity and burn into every tool module an alias that is unique and a value other than 0. 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 station: 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 events to decide whether this is a spare or a model change. Look at the expected identity and the measured identity in SlaveIdentityMismatch:
- Same Vendor and Product → the same model; a Revision difference is only a different version, and when the module is plugged back into the original slot or the chain end the master restores it automatically as a spare, so the application layer does not change its configuration.
- Different Vendor or Product → the model changed; handle it as a tool module change.
acknowledge_slave_replacement is only meaningful for "the correct module was swapped back in"; a module of a different model is not accepted because of it. A tool module change goes through the path of a DENI declaration plus application-layer configuration.
If the new tool module is already declared in the DENI and its identity also matches, the master configures it to OP on that declaration; in that case you usually receive SlaveOnline first. After reading the actual identity from that station, follow the same selection and configuration below.
Step three: pick the configuration from the measured identity and send it down. Take slave.VendorId() / slave.ProductId() / slave.RevId() to the tool module catalog to find the matching configuration; first verify that slave.Ibytes() / slave.Obytes() agree with this tool module's PDO layout, then send the process parameters (SDO) and the output safe values. If any one of them does not agree, do not write outputs — hold the safe state and raise an alarm.
PDO assignment follows the DENI; at runtime, do not adapt to a new tool module by changing the PDO mapping from the application layer. For a model that is not declared in the DENI, the correct approach is to add the declaration and rebuild the chain, not to force a mapping change at runtime.
// Tool module catalog: find the PDO layout, process parameters and safe outputs by measured identity
void OnModuleChanged(darra::EtherCATMaster& master, darra::dll_t& dll, uint16_t slaveIndex)
{
if (slaveIndex == 0 || slaveIndex > master.SlaveCount()) return;
darra::Slave& slave = master.GetSlave(slaveIndex);
// Configure and write outputs only on a clean OP; offline and OP+Error both count as unusable
if (slave.IsLost() || slave.State() != darra::EcState::OP) return;
const ToolConfig* tool = toolCatalog.Find(slave.VendorId(), slave.ProductId(), slave.RevId());
if (tool == nullptr)
{
printf("从站 %u 插入了未登记工具模块,保持安全态\n", slaveIndex); // Slave %u has an unregistered tool module inserted, staying in safe state\n
return;
}
if (slave.Ibytes() != tool->InputBytes || slave.Obytes() != tool->OutputBytes)
{
printf("工具模块 %s 的 PDO 大小与 DENI 不一致,拒绝配置\n", tool->Name.c_str()); // Tool module %s PDO size does not match DENI, configuration rejected\n
return;
}
darra::CoE& coe = slave.GetCoE();
for (const auto& p : tool->Parameters)
{
darra::SDOWriteDetail detail{};
if (!coe.SDOWrite(p.Index, p.SubIndex, p.Data.data(),
static_cast<int>(p.Data.size()), false, detail))
printf("参数 0x%04X:0x%02X 写入失败,中止码 0x%08X\n", // Parameter 0x%04X:0x%02X write failed, abort code 0x%08X\n
p.Index, p.SubIndex, detail.abort_code);
}
// The safe output values go through a versioned partial write: patch by offset, without overwriting other owners' writes
if (!darra::SlavePDO::PatchOutputFrame(
dll, master.MasterNumber(), slaveIndex, 0,
tool->SafeOutputs.data(), tool->SafeOutputs.size()))
printf("工具模块 %s 的安全输出写入失败\n", tool->Name.c_str()); // Write to tool module %s safety output failed\n
}
Complete example
#include "ethercat.hpp"
using namespace darra::ethercat;
int main()
{
dll_t dll;
EtherCATMaster master(dll);
master.SetENI("C:/EtherCAT/line.deni");
// Fixed slot + spare replacement: position and order are fixed, use ByPosition.
// It must be set before Build: Build binds the slots declared in the DENI to the measured slaves according to it.
master.HotplugBindMode(darra::HotplugBindMode::ByPosition);
if (!master.Build())
{
printf("初始化失败:%s (错误码 %ld)\n", // Initialization failed: %s (error code %ld)\n
master.LastBuildRejectText(), master.LastError());
return 1;
}
master.Events().OnSlaveIdentityMismatch(
[](uint16_t, uint16_t si,
uint32_t eV, uint32_t eP, uint32_t,
uint32_t aV, uint32_t aP, uint32_t) {
// Vendor or Product does not match: the model changed, or it was plugged into the wrong position.
// A Revision difference on the same model never reaches here; the master restores it automatically as a spare.
printf("从站 %u 实测 0x%08X/0x%08X,配置期望 0x%08X/0x%08X\n", // Slave %u measured 0x%08X/0x%08X, configuration expects 0x%08X/0x%08X\n
si, aV, aP, eV, eP);
});
master.Events().OnSlaveLost([](uint16_t si) {
printf("从站 %u 离线\n", si); // Slave %u offline\n
});
master.Events().OnSlaveDiscovered([](uint16_t si) {
printf("从站 %u 重新应答(到 OP 后再配置)\n", si); // Slave %u is responding again (reconfigure after it reaches OP)\n
});
if (!master.SetState(EcState::OP))
printf("切换 OP 失败\n"); // Failed to switch to OP\n
// After the operator swaps the correct module back in, have the master re-check this station:
// master_other::acknowledge_slave_replacement(master, 3);
}