Skip to main content

Slave

Obtain a slave reference through master.GetSlave(index) (1-based index).​

Overview​

The Slave class encapsulates all operations on a single EtherCAT slave, including state management, protocol access and IO data read/write. Slave objects are created and managed by EtherCATMaster and cannot be constructed directly.

All protocol sub-objects (CoE, SoE, FoE and so on) use lazy initialization and are created automatically on first access.

Quick start​

Index access​

#include "ethercat.hpp"
using namespace darra;

auto& slave = master.GetSlave(1); // 1st slave (1-based)
int count = master.SlaveCount(); // Total slave count

Query by group​

using namespace darra::ethercat;
uint16_t groupCount = master_other::get_group_slave_count(master, 1); // Slave count of group 1 (the default group)

Address access​

uint16_t addr = slave.ConfigAddr();        // Physical configuration address
uint16_t alias = slave.AliasAddress(); // Alias address

Identity access​

std::string name = slave.Name();           // Device name
uint32_t vid = slave.VendorId(); // Vendor ID
uint32_t pid = slave.ProductId(); // Product ID
uint32_t rev = slave.RevId(); // Revision number
uint32_t sn = slave.SerialNumber(); // serial number (native snapshot; use TryGetSerialNumber() for the EEPROM real value)

// Read the state
EcState state = slave.State();

printf("VendorID=0x%08X ProductID=0x%08X\n", vid, pid);

State and Error bit​

The low 4 bits of AL Status are the state (1/2/3/4/8 = INIT / PreOp / Boot / SafeOp / OP); bit4 (0x10) is the Error bit. The SDK returns the raw value and does not fold it: 0x14 (SafeOp+Error) and 0x18 (OP+Error) stay 0x14 / 0x18.

EcState st = slave.State();                              // Cached snapshot, raw value
bool err = darra::EcStateFormat::HasError(st); // Whether bit4 is set
EcState base = darra::EcStateFormat::GetBaseState(st); // Low 4 bits = SafeOp / OP ...
std::string text = darra::EcStateFormat::Format(st); // "SafeOp+Error" / "OP+Error" / "OP"

// Use the convenience entry points if bit twiddling is unfamiliar (the same snapshot as above)
uint8_t raw = slave.StateRaw(); // Raw status byte, bit4 preserved; 0 when it cannot be read
bool e = slave.HasError(); // (StateRaw() & 0x10) != 0

// Force one real read (sends a frame); use StateLive() to tell "no reply" apart
std::optional<EcState> live = slave.StateLive(); // std::nullopt = no real reply this tick
uint8_t rawLive = slave.StateRawLive(); // Raw bytes of the same entry
bool eLive = slave.HasErrorLive();

raw == 0 means "cannot be read / no real response this cycle" — not INIT, and not "confirmed error-free". ErrorCode()'s AL Status Code is likewise returned as the raw value: codes outside the standard table (for example 0x0038) are not folded into Unknown, nor rewritten into some other code. SDO failure paths likewise do not fabricate GeneralError (0x08000000 only means the slave really returned that code); out-of-table aborts pass through unchanged via SDOReadDetail.abort_code / SDOWriteDetail.abort_code.

A word on NIC enumeration: statics::GetNetworkInfo(dll, need_slave_count=false) does not decode the slave count, and ScanStatus keeps its default NicScanStatus::NotMeasured (not "measured as an empty air interface"); pass true to get the scan conclusion.

Protocol access​

All protocol interfaces are obtained lazily through member methods and created automatically on the first call:

auto& slave = master.GetSlave(1);

// Per-protocol interfaces
CoE& coe = slave.GetCoE(); // CoE (CANopen over EtherCAT)
SoE& soe = slave.GetSoE(); // SoE (Servo over EtherCAT)
FoE& foe = slave.GetFoE(); // FoE (File over EtherCAT)
EoE& eoe = slave.GetEoE(); // EoE (Ethernet over EtherCAT)
AoE& aoe = slave.GetAoE(); // AoE (ADS over EtherCAT)
VoE& voe = slave.GetVoE(); // VoE (Vendor over EtherCAT)
FSoE& fsoe = slave.GetFSoE(); // FSoE (functional safety)
CiA402& cia402 = slave.GetCiA402(); // CiA 402 (servo drives)
Sii& sii = slave.GetSii(); // SII EEPROM complete access (ETG.1000.6 section 6)
ProtocolMethodCategoryRead/writeDescriptionDocumentation
CoEslave.GetCoE()Protocol accessRead-onlySDO object dictionary accessCoE
SoEslave.GetSoE()Protocol accessRead-onlySERCOS IDN parametersSoE
FoEslave.GetFoE()Protocol accessRead-onlyFile transferFoE
EoEslave.GetEoE()Protocol accessRead-onlyEthernet tunnelEoE
AoEslave.GetAoE()Protocol accessRead-onlyBeckhoff ADSAoE
VoEslave.GetVoE()Protocol accessRead-onlyVendor-specific protocolVoE
FSoEslave.GetFSoE()Protocol accessRead-onlyFunctional safety protocolFSoE
CiA 402slave.GetCiA402()Protocol accessRead-onlyServo state machineCiA 402
SIIslave.GetSii()Protocol accessRead-onlySII EEPROM category traversal / control ownership / structured readsSlave API — low-level Sii API

PDO data read/write​

After entering OP, map a packed struct onto the process image and modify fields directly from multiple threads:

#pragma pack(push, 1)
struct InPdo { uint16_t statusWord; int32_t actualPosition; };
struct OutPdo { uint16_t controlWord; int32_t targetPosition; };
#pragma pack(pop)

const InPdo& inputs = darra::SlavePDO::InputsMapping<InPdo>(
dll, master.MasterNumber(), 1);
OutPdo& outputs = darra::SlavePDO::OutputsMapping<OutPdo>(
dll, master.MasterNumber(), 1);
outputs.controlWord = 0x000F;
printf("位置: %d\n", inputs.actualPosition); // Position: %d

EMCY emergency messages​

An EtherCAT slave sends an EMCY (Emergency) message when it detects an abnormality. The SDK provides two sets of interfaces:

  • SDO 0x1003 history — coe.GetEmergencyHistory() / ClearEmergencyHistory()
  • Real-time cache — free functions in the darra::ethercat::slave_emcy namespace
using namespace darra::ethercat;

int n = slave_emcy::emcy_count(dll, mi, si);
auto records = slave_emcy::emcy_history(dll, mi, si);
for (auto& r : records) {
printf("EMCY t=%u ms code=0x%04X reg=0x%02X\n",
r.timestamp_ms, r.error_code, r.error_register);
}
slave_emcy::clear_emcy(dll, mi, si);

Topology query​

EtherCAT naturally forms a line / ring / branch topology from the port connections of each ESC. After entering the OP state, the SDK can pull the parent-child relations of all nodes from the DLL in one call, cache them in a TopologyTree, and then run DFS / BFS / depth queries and so on.

using namespace darra::ethercat;

auto tree = BuildTopology(master.Dll(), master.MasterNumber());
if (!tree.IsBuilt()) return;

// Print the roots (there can be several when there are N primary NICs or a redundancy ring)
for (auto rootIdx : tree.RootSlaves()) {
auto* root = tree.FindNode(rootIdx);
if (root) printf("根: Slave[%u] ports=0x%02X\n", root->SlaveIndex, root->ActivePorts); // Root: Slave[%u] ports=0x%02X
}

// DFS / BFS over the whole tree; abort immediately when the visitor returns false
tree.DFS([&](const TopologyNode& n, int depth) {
printf("%*sSlave[%u] addr=%s 子=%zu\n",
depth * 2, "", n.SlaveIndex, n.Address.c_str(), n.Children.size());
return true;
});

Related structures:

struct TopologyNode {
uint16_t SlaveIndex; // Slave index (1-based)
uint16_t ConfigAddr; // Configuration address
std::string Address; // Configuration address as a hex string (e.g. "0x1001")
uint16_t ParentIndex; // Parent node index, 0 means the root
uint8_t EntryPort; // Entry port (0-3)
uint8_t ActivePorts; // Active port bitmap (Bit0..Bit3 correspond to P0..P3)
uint8_t Topology; // 0=no link / 1=endpoint / 2=middle / 3=branch / 4=crossover
uint8_t PortType; // Port physical type bitmap (2 bits per port: 0=not implemented / 1=not configured / 2=EBUS / 3=MII)
int Depth; // Depth to the root node
std::vector<uint16_t> Children; // Child node index list
};

Methods: IsRoot() / ActivePortCount() / GetPortType(port) / EntryPortType(). TopologyTree provides RootSlaves() / GetChildren() / GetChildCount() / FindNode() / DFS() / BFS().

Full example​

#include "ethercat.hpp"
using namespace darra;

int main() {
EtherCATMaster master(dll);
master.SetNetwork("\\Device\\NPF_{...}")
.SetENI("config.deni")
.Build();

// Iterate over all slaves
for (uint16_t i = 1; i <= master.SlaveCount(); ++i) {
auto& slave = master.GetSlave(i);
printf("[%d] VID=0x%08X PID=0x%08X 状态=%d\n", // [%d] VID=0x%08X PID=0x%08X status=%d
i, slave.VendorId(), slave.ProductId(),
static_cast<int>(slave.State()));
}

// Protocol in use
auto& slave1 = master.GetSlave(1);
auto data = slave1.GetCoE().SDORead(0x1018, 0x01);
if (!data.empty()) {
uint32_t vendor_id;
std::memcpy(&vendor_id, data.data(), 4);
printf("VendorID: 0x%08X\n", vendor_id);
}

return 0;
} // The destructor does Stop + Dispose automatically