Skip to main content

Slave attributes and methods

Get the Slave& reference with master.GetSlave(index).​

C++-specific sugar

In C++ you can use darra::sugar::idx(master, 1) to get a slave in short form, or if (auto opt = darra::sugar::slave_opt(master, i)) {...} for safe std::optional access (an index out of range does not throw).

Attributes​

CategoryAttributeTypeRead/writeDescription
Basic identityIndex() / SlaveNum()int / uint16_tread-onlySlave index (1-based)
Name()std::stringread-onlyDevice name (read from EEPROM group_name)
DriveName()std::stringread-onlyDrive/device name (read from SDO 0x1008)
Device informationVendorId()uint32_tread-onlyManufacturer ID (read from SII EEPROM)
VendorName()std::stringread-onlyManufacturer name (read from the ESI file)
ProductId()uint32_tread-onlyProduct ID
RevId() / Revision()uint32_tread-onlyRevision number
RevisionNumber()uint32_tread-onlyAlias of RevId(), the same revision number
SerialNumber()uint32_tread-onlySerial number, the runtime identity snapshot rather than a direct EEPROM read: slaves that matched an ESI stay at 0, so 0 means neither "the real value is 0" nor a read failure; use TryGetSerialNumber() for the EEPROM real value
TryGetSerialNumber()std::optional<uint32_t>read-onlyEEPROM serial number: a value = the real value (may be 0); std::nullopt = the read failed (not the same as the device serial number being 0)
HasMDP()boolread-onlyWhether the modular device profile is supported (ETG.5001)
BlockLRW()boolread-onlyLRW logical read/write blocking flag
AddressConfigAddr()uint16_tread-onlyPhysical configuration address
AliasAddress()uint16_tread-onlyAlias address
StateState()EcStateread-onlyCurrent slave state, raw value not folded: the low 4 bits are the base state and bit4 (0x10) is the Error bit, so 0x14 (SafeOp+Error) / 0x18 (OP+Error) are returned as-is
StateRaw()uint8_tread-onlyRaw state byte (bit4 preserved); 0 when the snapshot cannot be read. 0 is neither INIT nor "confirmed no error"
HasError()boolread-onlyWhether bit4 of the snapshot state is set, equivalent to EcStateFormat::HasError(State()); false when it cannot be read = no evidence
ErrorCode()EcALStateread-onlyAL Status Code error code (real read: the full 16-bit ALstatuscode in the slave structure; reads the polled cache while in OP and refreshes with one live frame otherwise; not the high byte of al_status_mirror(). Codes outside the standard table are returned at their raw value and are not folded to Unknown. Use ALStatusCodeLive() to force an on-the-spot re-read)
IsLost()boolread-onlyWhether the slave is lost (disconnected)
Liveness()SlaveLivenessStateread-onlyLiveness three-state: Alive = confirmed alive / Lost = confirmed offline / Unknown = insufficient evidence. IsLost() only answers "is it confirmed lost"; use this method to tell "insufficient evidence"
OfflineReason()SlaveOfflineReasonread-onlyOffline reason classification: RealOffline = truly offline / Unreachable = not confirmed by the server — the server/probe did not see it, but the process data proves it is still contributing (not a confirmed offline) / Unknown = insufficient evidence
HasEnteredOperational()boolread-onlyWhether it has ever successfully entered OP during this run (event-latched; falls back to the current-cycle state when the event surface is not ready)
DroppedFromOperational()boolread-onlyWhether it "entered OP but is not in OP now" (dropped out of OP at runtime)
OutOfOpDurationMs()std::optional<long long>read-onlyMonotonic duration the slave has continuously been out of OP (ms); nullopt = no provable start of the out-of-OP period (in OP / never entered OP / no edge observed yet). System clock changes do not affect this value
OutOfOpDuration()std::optional<std::chrono::milliseconds>read-onlyHow long it has continuously been out of OP; nullopt has the same meaning as above
OutOfOpSinceUtc()std::optional<std::chrono::system_clock::time_point>read-onlyStart of the out-of-OP period (UTC, derived from "current UTC - monotonic duration"); nullopt has the same meaning as above
StateLive()std::optional<EcState>read-onlyState for the current cycle from a forced true-value read, not a cached snapshot; std::nullopt = no real response (slave lost / invalid handle), unknown is never folded into INIT. Use State() for the cached view
StateLiveRead()LiveReadread-onlyLive state read (forces one real read) plus four-state trust; value is the raw AL Status byte (low 4 bits = base state, bit4 = Error), usable as the current state only when IsValid(). The verdict is settled at this entry point; StateLive() is only its convenience view
StateRawLive()uint8_tread-onlyRaw state byte from a forced true-value read (native GetSlaveStateLive); 0 = no real response this cycle, not INIT
HasErrorLive()boolread-onlyWhether bit4 is set in the same true-value read; false when there is no response (no evidence, not "confirmed no error")
ALStatusCodeLive()std::optional<uint16_t>read-onlyAL Status Code from a forced true-value read; a liveness probe runs first, and when the probe confirms there is no response it returns std::nullopt (a frozen or default value is not treated as a measurement). Use ErrorCode() for the cached view
ALStatusCodeLiveRead()LiveReadread-onlyLive AL Status Code (lossless 16-bit) plus four-state trust. When the slave is lost / not responding the lower layer returns 0; this entry point files it as Stale and never reports it as "no error"; ALStatusCodeLive() is only its convenience view
Diagnostic mirrordiag_mirror::slave_wc_contributed(mi, si)WcContributionread-onlyThis slave's contribution state to the Working Counter (WKC) in the current cycle (live direct read, free function)
InputDataValidity()PdoInputValidityread-onlyFour-state validity of the input process data: Valid = this cycle's data is valid; Degraded = this cycle has no full evidence (the group's inputs are incomplete for this cycle; on a single dropped frame / WKC=0 the data is the previous valid frame (last-good); when some slaves are missing, the input bytes of the absent slave and everything downstream may be the process-image initial values established at startup, do not treat it as definitely trustworthy); Stale = cannot be used as the current value; Unknown = no evidence. Use this property to decide "can this frame of data be used"; use IsLost() to decide "has the slave been confirmed offline"
diag_mirror::slave_al_status_mirror(mi, si)AlStatusMirrorread-onlyUnderlying AL status mirror (parsed into state + error + code + raw, free function). A cache sampled while the master is in OP, not the live truth at read time
TopologyTopologyType() / Topology()uint8_tread-onlyConfiguration-time topology structure classification snapshot: 0=NoLink / 1=EndPoint / 2=Line / 3=Fork / 4=Cross; 0xFF=unavailable (invalid handle / no master context), 0 is a valid verdict "no link". TopologyType() is the explicitly named entry point, Topology() is the legacy name for the same source; both share one implementation and one return value. Written once during the config_init scan, not refreshed at runtime, unchanged when a cable is pulled; it is not the measured connection count for the current cycle
LinkCount()intread-onlyMeasured connection count for the current cycle: popcount(topo.active_ports & 0x0F), refreshed by port_state_monitor every 200 ms from the real DLSTAT (0x0110). 1..4 = measured connection count, -1 = unknown / invalid argument (including the 0 placeholder when DLSTAT has not been read); unknown is not "0 connections" and does not mean the slave is offline
ParentStation()uint16_tread-onlyStation address of the parent slave (note: this is actually the 1-based slave index, not the station address; 0 means the parent node is the master)
ParentPort()intread-onlyParent port number: 0..3 is a measured port, -1 = unknown / not calibrated / invalid argument; 0 is a valid P0, -1 must not be folded into 0
P1FoldbackOnly()intread-onlyFoldback reachability under a dual-NIC ring with branches: 1 = the slave is reachable only through the foldback window, 0 = not a branch slave / not calibrated, -1 = invalid master index or station number
EntryPort()uint8_tread-onlyEntry port number
ActivePorts()uint8_tread-onlyActive port bit mask
PhysicalType()uint8_tread-onlyPhysical port type
ConsumedPorts()uint8_tread-onlyBit map of the ports consumed by this slave, recorded during topology configuration (bit0=P0 … bit3=P3). This is not the same quantity as the active ports measured in the current cycle by ActivePorts(); 0 = no port consumed or an invalid handle (the two cannot be told apart)
PDO dataIbits() / Obits()uint16_tread-onlyInput/output data size in bits
Ibytes() / Obytes()uint32_tread-onlyInput/output data size in bytes
Ioffset() / Ooffset()uint32_tread-onlyInput/output offset within the process data area
Istartbit() / Ostartbit()uint8_tread-onlyInput/output start bit
ESI/configurationHasEsi()boolread-onlyWhether an ESI file is loaded
EsiName()std::stringread-onlyESI name (read from EEPROM)
EsiVersion()std::stringread-onlyESI version
ConfigByEsi()boolread-onlyCombined automatic configuration from the ESI (currently equivalent to ConfigureFromEsi: SM/FMMU/PDO mapping)
EEPROMEep8ByteAddressing()boolread-onlyEEPROM addressing mode (true = 8-byte, false = 4-byte)
EepPDI()uint8_tread-onlyPhysical Device Interface (PDI) type
EbusCurrent()int16_tread-onlyE-bus current consumption (mA)
MailboxMbxProto()MailboxProtocolread-onlySupported mailbox protocol capability bit map (SII mbx_proto: bit0=AoE, bit1=EoE, bit2=CoE, bit3=FoE, bit4=SoE, bit5=VoE)
MbxLength()uint16_tread-onlyMailbox send buffer size
MbxReadLength()uint16_tread-onlyMailbox receive buffer size
MbxReadOffset() / MbxWriteOffset()uint16_tread-onlyMailbox read/write offsets
MbxCount()uint8_tread-onlyMailbox protocol counter
CoESupport() / FoESupport() / EoESupport() / SoESupport() / AoESupport() / VoESupport()std::optional<bool>read-onlyThree-state protocol capability: true = supported / false = confirmed unsupported / nullopt = unknown
CoESupportKnown() / FoESupportKnown() / EoESupportKnown() / SoESupportKnown() / AoESupportKnown() / VoESupportKnown()boolread-onlyWhether a definite verdict exists
SupportsCoE() / SupportsFoE() / SupportsEoE() / SupportsSoE() / SupportsAoE() / SupportsVoE()boolread-onlybool view; only "known supported" is true, unknown is folded into false
Protocol detailsCoEDetails()uint8_tread-onlyCoE protocol feature flags
EoEDetails()uint8_tread-onlyEoE protocol feature flags
FoEDetails()uint8_tread-onlyFoE protocol details
SoEDetails()uint8_tread-onlySoE protocol details
FMMUFMMU0Function()uint8_tread-onlyFMMU0 function type (bit 0 = output, bit 1 = input)
FMMU1Function()uint8_tread-onlyFMMU1 function type
FMMU2Function()uint8_tread-onlyFMMU2 function type
FMMU3Function()uint8_tread-onlyFMMU3 function type
DCHasDC()boolread-onlyWhether DC is supported
DCActive()uint16_tread-only0x0980 value as written (0 = not active, non-0 = DC-active). Not the same as armed or in sync: check SlaveDC::Sync0Armed for armed state and the sync window InSync for whether it is in sync
DCCycle0() / DCCycle1()intread-onlySYNC0/SYNC1 cycle (nanoseconds)
DCShift()intread-onlyPhase shift (nanoseconds)
PropagationDelay() / PDelay()intread-onlyPropagation delay of a frame from the master to this slave (nanoseconds)
DCNext() / DCPrevious()uint16_tread-onlyDC next/previous slave index
DCParentPort()intread-onlyCompatibility entry point for ParentPort(); 0..3 = parent port, -1 = unknown, it is not a separate DC-specific field
DCReceiveTimeA/B/C/D()int32_tread-onlyPort A/B/C/D receive time (nanoseconds)
Topology extensionSupportsFrameRepeat() / SupportsFrameRepeat(bool)boolread/writeWhether frame repeat is supported (ETG.1500 §5.4.3)
RedundancyRedundancyActivated()boolread-onlyRedundancy protection is running = the same master-level predicate RingMode >= 1 (Dual / Degraded); always false in line / end-foldback topologies, it is not an independent per-slave verdict
PrimaryLinkBroken()boolread-onlyWhether the primary link is broken
SecondaryLinkBroken()boolread-onlyWhether the secondary link is broken
Mailbox health (2.5.x)MailboxHealth()slave_stats::MailboxHealthread-onlyMailbox health (Unknown/Healthy/Degraded), live direct read
IsFreeRunDemoted()boolread-onlyWhether the slave was forced to demote from DC to FreeRun
HealthDegradedCount()uint32_tread-onlyContinuous count of mailbox semi-failure (approximately seconds)
RecoverMailboxHealth()boolwrite-onlyManually trigger mailbox semi-failure recovery (the runtime library usually recovers automatically)
ConfigurationGroup() / Group(uint8_t)uint8_tread/writeSlave group number (0-7; 0 = unassigned and automatically placed in group 1 before mapping; valid PDO groups are 1-7, must be set before SAFE_OP)
IsOptional() / IsOptional(bool)boolread/writeOptional slave flag; absence does not affect the WKC check (must be set before OP)
SetOptional(bool)voidwrite-onlyEquivalent setter alias of IsOptional(bool), must be set before OP
StartupShouldWritePDOAssignment() / ShouldWritePDOAssignment(bool)boolread/writeWhether to write the PDO Assignment configuration
ShouldWritePDOConfiguration() / ShouldWritePDOConfiguration(bool)boolread/writeWhether to write the PDO Configuration
SupportsCompleteAccess() / SupportsCompleteAccess(bool)boolread/writeWhether Complete Access mode is supported

Bit4 of AL Status is the Error bit, not a fifth state. State() preserves the raw value; to test the base state / Error bit use darra::EcStateFormat::GetBaseState() / HasError() / Format() (which produce text such as "SafeOp+Error" and "OP+Error"). If you would rather not write the bit manipulation yourself, use StateRaw() / HasError() (cached snapshot) or StateRawLive() / HasErrorLive() (forces one true read). raw == 0 only means "could not be read / no response this cycle" — it is neither INIT nor "confirmed no error".

MbxProto() returns the SII mbx_proto capability bit map (strongly typed MailboxProtocol), not the type code MailboxType of the mailbox frame header; to test a capability, prefer the three-state entry points CoESupport() / FoESupport() / EoESupport() / SoESupport() (returning std::optional<bool>), or HasProtocol(slave.MbxProto(), MailboxProtocol::CoE). SupportsXxx() is only a bool view: it returns false for an unknown capability too, so it only suits a plain boolean switch; to tell "confirmed unsupported" from "unknown" you must use the three-state entry point (see the next section).

Three-state protocol capability​

CoE / FoE / EoE / SoE / AoE / VoE all provide a three-state entry point, a bool view and a Known query:

std::optional<bool> FoESupport() const;   // true=supported / false=confirmed unsupported / std::nullopt=unknown
bool FoESupportKnown() const; // = FoESupport().has_value()
bool SupportsFoE() const; // bool view: only "known supported" is true; unknown collapses to false

// Same entry point: EoESupport / SoESupport / AoESupport / VoESupport / CoESupport
// EoESupportKnown / SoESupportKnown / AoESupportKnown / VoESupportKnown / CoESupportKnown
// SupportsEoE / SupportsSoE / SupportsAoE / SupportsVoE / SupportsCoE

Authoritative decision chain (the same rule across the six SDK languages):

  1. details bit0 declared by the device = supported → true (positive evidence). This implementation reads the details bit only for FoE / EoE / SoE; AoE / VoE / CoE are decided from step 2 onwards.
  2. SII word 0x001C (mbx_proto) read successfully this time → that bit is the authoritative verdict, so false can be concluded safely.
  3. The mbx_proto bit in the configuration-time snapshot → positive evidence only. The ESI exact-match fast path hard-codes the CoE bit (0x0004) when supported_proto == 0, so the snapshot bit map must not be used to deny a capability.
  4. None of the above holds → std::nullopt (unknown), never folded into false.

A failed SII read (no EEPROM / slave lost) only degrades to steps 3 and 4 and never fabricates a verdict. Use the three-state entry point when a "confirmed unsupported" result decides whether to disable a feature; for a plain boolean switch you can keep using SupportsXxx().

TopologyType() and LinkCount() are not the same quantity

TopologyType() is a configuration-time structure classification snapshot (0=NoLink / 1=EndPoint / 2=Line / 3=Fork / 4=Cross), written once during the config_init scan, not refreshed at runtime, unchanged when a cable is pulled — it answers "how many ports does this device have". LinkCount() is the measured connection count of the current cycle (port_state_monitor refreshes it every 200 ms from the real DLSTAT (0x0110)); it changes within 200 ms of a cable being pulled, and returns -1 when every link is down or no sample has been taken. Do not use TopologyType() to decide "how many ports are connected right now".

On the C++ side these two entry points return the raw interface values: TopologyType() is a uint8_t, and the failure value is a separate band from "no link" — for an invalid handle / uncalibrated slave the runtime library returns 0xFF = unavailable, while 0 is the valid verdict NoLink; it also returns 0xFF when the runtime library is not ready. The caller must first treat > 4 (or == 0xFF) as unavailable and only then interpret 0..4. When you need the three-state "unavailable" form, use a high-level SDK: C# int TopologyType (-1 for anything outside 0..4), the Java topologyType method (-1), the Python slave.topology_type property (None), the Rust slave.topology_type method (None). A -1 from LinkCount() only means the measured link count of the current cycle is unknown, not that the structure classification is unknown.

WcContribution enum values (WKC contribution state)

Defined in the darra::ethercat::diag_mirror namespace.

enum class WcContribution : uint8_t {
NotContributed = 0, // This slave is not responding right now (lost / Hot-plug in progress) - exposed honestly, not an error-handling failure
Contributed = 1, // This slave is contributing WKC normally right now
Unknown = 0xFF // Underlying cache unknown (not mapped / not refreshed) - exposed honestly, never guessed
};
AlStatusMirror structure (AL status mirror parsing)

Defined in the darra::ethercat::diag_mirror namespace, split out of the 16-bit mirror.

struct AlStatusMirror {
uint16_t raw; // Raw 16-bit mirror (0 means unknown / not refreshed)
uint8_t state; // AL State (low 4 bits, 1/2/4/8 = INIT/PREOP/SAFEOP/OP)
bool error; // AL Status Error bit (bit4)
uint8_t code; // low 8 bits of the AL Status Code (valid only when error is set; codes >= 0x0100 are truncated)
bool known; // true when raw != 0; false = the underlying layer has no mirror of that slave yet

bool is_op() const; // Whether AL State is OP
bool is_safeop() const; // Whether AL State is SAFEOP
bool is_preop() const; // Whether AL State is PREOP
bool is_init() const; // Whether AL State is INIT
};
EcTopologyType / EcPortType enum values
enum class EcTopologyType : uint8_t {
NoLink = 0, // No link
EndPoint = 1, // Endpoint
Line = 2, // Intermediate node (linear topology)
Fork = 3, // Branch point
Cross = 4 // Crossover point
};

enum class EcPortType : uint8_t {
NotUsed = 0, // Unused
MII = 1, // MII
EBUS = 2, // EBUS
EBUSEnhanced = 3 // EBUS enhanced
};
MailboxType enum values
enum class MailboxType : uint16_t {
ErrorMailbox = 0x00, // Mailbox error
ADSOverEtherCAT = 0x01, // AoE
EthernetOverEtherCAT = 0x02, // EoE
CANopenOverEtherCAT = 0x03, // CoE
FileOverEtherCAT = 0x04, // FoE
ServoOverEtherCAT = 0x05, // SoE
VendorOverEtherCAT = 0x0F // VoE
};
EcCoEDetails enum values
enum class EcCoEDetails : uint8_t {
None = 0x00,
SDO = 0x01, // Supports SDO
SDOInfo = 0x02, // Supports SDO Info
PDOAssign = 0x04, // Supports PDO Assign
PDOConfig = 0x08, // Supports PDO Config
Startup = 0x10, // Supports Startup
CompleteAccess = 0x20 // Supports Complete Access
};
EcEoEDetails enum values
enum class EcEoEDetails : uint8_t {
None = 0x00,
SendFrame = 0x01, // Supports sending frames
ReceiveFrame = 0x02, // Supports receiving frames
SetIPParam = 0x04, // Supports setting IP parameters
GetIPParam = 0x08 // Supports reading IP parameters
};

Sub-objects​

CategoryAttributeTypeRead/writeDescription
Sub-objectGetCoE()CoE&read-onlyCANopen over EtherCAT, lazily initialized
GetSoE(driveNo)SoE&read-onlyServo over EtherCAT, optional driveNo parameter
GetFoE()FoE&read-onlyFile over EtherCAT, lazily initialized
GetEoE()EoE&read-onlyEthernet over EtherCAT, lazily initialized
GetAoE()AoE&read-onlyADS over EtherCAT, lazily initialized
GetVoE()VoE&read-onlyVendor over EtherCAT, lazily initialized
GetFSoE()FSoE&read-onlyFunctional Safety over EtherCAT, lazily initialized
GetCiA402()CiA402&read-onlyCiA402 drive control, lazily initialized
GetMDP()MDP*read-onlyMDP modular device, returns nullptr when not supported
C++-specific sugar

For fields with multiple return values such as PDO sizes / offsets, use auto [in_bytes, out_bytes] = darra::sugar::pdo_size(slave); to take them all out with one structured binding.

Enum descriptions​

C++ provides the GetALStatusCodeString() method to get the English description of an AL Status Code:

std::string desc = slave.GetALStatusCodeString();  // "Sync manager watchdog"

Other enums can be cast to an integer with static_cast<int>() and then looked up in a table.

Flags and error acknowledgement​

auto& slave = master.GetSlave(1);

// OpOnly flag (ETG.1500) - whether the slave is only available in OP
bool opOnly = slave.IsOpOnly();

// Device simulation flag - whether the slave is a simulated device
bool emulated = slave.IsDeviceEmulation();

// Acknowledge a slave error (clear the AL Status Code error)
slave.SetErrorAck(true);

// Hot-plug reconfiguration detection
if (slave.NeedsStartupReconfig()) {
// The slave needs its startup configuration re-applied
slave.ClearStartupReconfigFlag();
}

Protocol sub-object access​

auto& slave = master.GetSlave(1);

// Get the protocol instance (lazily initialised)
CoE& coe = slave.GetCoE();
SoE& soe = slave.GetSoE(); // Optional parameter: driveNo
FoE& foe = slave.GetFoE();
EoE& eoe = slave.GetEoE();
AoE& aoe = slave.GetAoE();
VoE& voe = slave.GetVoE();
FSoE& fsoe = slave.GetFSoE();
CiA402& cia = slave.GetCiA402();

Diagnostics​

tip

Slave diagnostic information (communication error rate, redundancy state, DC sync) is accessed through a separate diagnostics interface.

PdoInputValidity — input data validity​

slave.InputDataValidity() answers "can this frame of input data be used as the current value", which is a different fact from "has the slave been confirmed offline" (slave.IsLost()).

ValueWhat you seeRecommended use
ValidThis cycle's PDO exchange was complete; the input image is the current valueUse normally
DegradedThis cycle has no full evidence: the group's inputs are incomplete for this cycle. On a single dropped frame / WKC=0 the data is the previous valid frame (last-good); when some slaves are missing, the input bytes of the absent slave and everything downstream may be the process-image initial values established at startup, not the last valid valueDo not treat this as "the data is definitely trustworthy": either wait for recovery, or cross-check IsLost() / OfflineReason() / InputDataValidity() to see which slaves are untrustworthy. It turns Stale only after N full cycles without recovery (N is computed from the group cycle and the slave watchdog)
StaleThe input image cannot be used as the current value (WKC short / no frame this cycle / slave lost / exchange stalled)Do not use as a live value; take the safe fallback
UnknownNo evidence (no input PDO / group expectation not established / never exchanged / read failed)Unknown is not valid; treat it as unavailable

A read failure / out-of-range index / an older runtime without this capability returns Unknown (fail-closed).

Note: the native-side comment still says "three-state / degradation pending", which is stale text awaiting sync in the native domain; the public SDK contract is the four states in this section.

MasterDiagnosticsInfo::StaleInputCount() counts only slaves confirmed Stale; it does not count while Degraded applies.

Live-read values and the four trust states (LiveRead)​

StateLiveRead() / ALStatusCodeLiveRead() return LiveRead: the raw value plus an evidence level. Only a value that passes IsValid() (that is, validity == LiveReadValidity::Valid) may be used as the current value; the other three states must never be taken as "this is how it is right now". This is the same four-state convention as PdoInputValidity, but about a different object: this section answers "is the state / AL code I just read live trustworthy".

ValueMeaningUsable as the current value
Unknown(0)No usable read (shim not loaded / entry point missing / invalid handle)No. Unknown != normal
Valid(1)This measurement produced a result usable as the current valueYes
Stale(2)A value was obtained, but it is confirmed not current (the lower layer uses 0 as a placeholder when the slave is lost / not responding)No, this is a residual value
Degraded(3)A value was obtained, but only partial evidence is available (liveness state / probe unreadable or unknown)Not as confirmation

Live state criterion: 0 / 0xFF / low 4 bits = 0 -> Unknown; otherwise -> Valid. value keeps the bit4 Error bit (the same convention as StateRaw()); to test the Error bit use HasErrorLive() or look at the raw byte.

Live AL code criteria:

VerdictTriggervalue
UnknownThe shim is not ready, or it returned 0xFFFF (the unavailable sentinel)0xFFFF
DegradedThe liveness state / probe entry point is unavailableRaw code
StaleIsLost() is true, or the probe confirms no responseRaw code (residual)
DegradedProbe evidence is insufficient (unknown)Raw code
ValidIsLost() is false and the probe confirms the slave is onlineRaw code
A lost slave is not "no error"

The lower layer returns 0 for a lost / non-responding slave; that 0 is the "no data" placeholder, not "no error". ALStatusCodeLiveRead() uses the liveness state and probe evidence to file it as Stale; the convenience entry point ALStatusCodeLive() gives std::nullopt in that case. Never read 0 / nullopt as "the device confirmed no fault".

The AL mirror (diag_mirror::slave_al_status_mirror()) carries only the low 8 bits of the code, and codes >= 0x0100 are truncated; for the full 16-bit code always use ErrorCode() or ALStatusCodeLiveRead() in this section.

ReadPortErrorAccumulated()​

struct PortErrorAccumulated {
std::array<uint32_t, 4> RxError{}; // Accumulated port receive errors (P0..P3)
std::array<uint32_t, 4> InvalidFrame{}; // Accumulated invalid frames per port
std::array<uint32_t, 4> LostLink{}; // Accumulated port link breaks
};

std::optional<PortErrorAccumulated> ReadPortErrorAccumulated() const;

Reads back the three sets of 32-bit accumulated values for the 4 ports in one call, 4 entries per set, indexed by port number P0..P3. A std::nullopt return = invalid master / slave index, nothing was read this time (not "the count is 0").

This is not the same quantity as the 8-bit port error snapshot in the slave statistics: these are 32-bit accumulated values that do not lose the high bits to 8-bit wraparound over long runs; use this one for trend analysis and for deciding whether a port is degrading continuously.

Example:

auto& slave = master.GetSlave(1);

if (auto acc = slave.ReadPortErrorAccumulated()) {
for (int p = 0; p < 4; ++p) {
printf("P%d: RxErr=%u, InvalidFrame=%u, LostLink=%u\n", p,
acc->RxError[p], acc->InvalidFrame[p], acc->LostLink[p]);
}
} else {
printf("端口累计值读不到(索引非法)\n"); // Port totals cannot be read (invalid index)\n
}

GetDetailedInfo()​

void* GetDetailedInfo() const;

Returns a pointer to the detail block of this slave (a read-only borrow). The pointer is owned by the runtime library; do not free or modify it. nullptr is returned when the SDK is not ready or the index is invalid.

The memory layout of this block is not part of the public contract (it may change between versions), so do not decode it yourself by offset. For stable fields use the named attributes and methods on this page: State() / ErrorCode() / ReadPortErrorAccumulated() and so on.

ESI methods​

ConfigureFromEsi()​

bool ConfigureFromEsi() const;

Configures the slave automatically from the ESI file (SM/FMMU/PDO mapping).

Return value:

  • bool — whether it succeeded

ConfigByEsi()​

bool ConfigByEsi() const;

Combined automatic configuration (currently equivalent to ConfigureFromEsi(): SM/FMMU/PDO mapping).

Example:

auto& slave = master.GetSlave(1);

// Configure slaves automatically from the ESI file
bool ok = slave.ConfigureFromEsi();
printf("ESI 自动配置: %s\n", ok ? "成功" : "失败"); // ESI auto-configuration: %s (success / failed)

// ESI combined auto-configuration (currently equivalent to ConfigureFromEsi)
bool ok2 = slave.ConfigByEsi();
printf("ESI 综合配置: %s\n", ok2 ? "成功" : "失败"); // ESI combined configuration: %s (success / failed)

Process data watchdog​

SetWatchdog()​

bool SetWatchdog(uint32_t timeoutMs) const;
bool SetWatchdog(uint32_t timeoutMs, WatchdogApplyOutcome& outcome) const;

enum class WatchdogApplyOutcome : uint8_t {
Applied, // What was actually sent == the request
RaisedToSafetyFloor, // Raised and written by the safety lower bound (actual value != requested value)
RejectedOverRegisterLimit,// The request exceeds the 6553 ms register limit, so it was refused and not written
Failed // Write failed / invalid index
};

Sets the process data watchdog timeout of the slave. When the slave receives no process data frame within the timeout, it raises a watchdog error (ALStatusCode 0x001B).

Parameters:

  • timeoutMs (uint32_t) — timeout in milliseconds, 0 = disabled, maximum 6553 ms
  • outcome (WatchdogApplyOutcome&) — [out] three-state out parameter, for telling the apply results apart programmatically

Return value (three states, reported faithfully): same rule as the underlying C API — the return value answers only "does the value actually written equal the request?":

  • true (outcome == Applied) — the value written equals the request and the register write succeeded.
  • false (outcome == RaisedToSafetyFloor, underlying FALSE + GetLastError()==0x20000011) — the value was raised to the safety floor and the raised value was written (required by the topology rules: 5000 ms for branch slaves / 400 ms for PDO slaves on a ring), so the actual value != the requested value; for the actual milliseconds call GetWatchdogConfig() and read wd_time_pd / 10. false is not "not set" — do not skip the following handling as if this were a failure.
  • false (outcome == RejectedOverRegisterLimit, underlying FALSE + GetLastError()==87) — the request exceeds the 6553 ms register limit (0x0420 = u16 × 0.1 ms), so it is rejected and not a single byte is written; the value is not truncated and not silently changed to 6553.
  • false (outcome == Failed, underlying FALSE + GetLastError()==0) — the register write failed or the index is invalid; nothing was written.

All three false cases log a warning (the raised case includes the measured milliseconds); the overload without outcome returns only bool, so use the overload with the out parameter to tell the three states apart.

note

Call this in SafeOp or OP state.

SetPdiWatchdog()​

bool SetPdiWatchdog(int timeoutMs) const;

Sets the PDI watchdog timeout of the slave. The PDI watchdog monitors whether the slave's local application (microcontroller firmware) is running normally.

Parameters:

  • timeoutMs (int) — timeout in milliseconds, 0 = disabled

Return value:

  • true — applied (the value written equals the request).
  • false — the argument is out of range (< 0 or > 6553), so it is rejected and not applied (an error is logged, the value is not silently changed), or the register write failed / the index is invalid.

The PDI watchdog has no safety-floor raise branch, so the "written after being raised" case does not occur.

GetWatchdogConfig()​

bool GetWatchdogConfig(ec_watchdog_config_t& config) const;

Reads the current watchdog configuration of the slave.

Parameters:

  • config (ec_watchdog_config_t&) — output configuration structure

Return value:

  • bool — whether it succeeded

Related structures:

typedef struct {
uint16_t wd_divider; // Watchdog divider
uint16_t wd_time_pdi; // PDI watchdog timeout value
uint16_t wd_time_pd; // Process data watchdog timeout value
} ec_watchdog_config_t;

GetWatchdogStatus()​

bool GetWatchdogStatus(ec_watchdog_status_t& status) const;

Reads the watchdog run status of the slave.

wd_status comes from bit0 of ESC register 0x0440: 0 = the watchdog has overflowed / expired, 1 = the watchdog is normal or not enabled; bits other than bit0 are reserved. 0x0442 / 0x0443 are the watchdog overflow counters (write 0 to reset, a read does not clear them) and are not the same thing as the status bit in 0x0440.

Per-field validity is decided by valid_mask (EC_WD_STATUS_VALID_*): set = the register was really read this time and the field is trustworthy; bit cleared = the register read failed and the corresponding field is fixed at 0, which does not represent the device's real value (including a legitimate "read 0"). wd_status == 0xFF is only kept for compatibility with the old sentinel and is no longer used to infer whether the whole status is valid. When this function returns false the whole status is not trustworthy.

Parameters:

  • status (ec_watchdog_status_t&) — output status structure

Return value:

  • bool — whether it succeeded

Related structures:

typedef struct {
uint8_t wd_status; // SM watchdog status 0x0440 bit0 (0=overflowed/expired, 1=normal or not enabled; 0xFF=read failed/old sentinel)
uint8_t wd_counter; // SM watchdog counter 0x0442
uint16_t wd_divider; // Current divider value 0x0400
uint16_t wd_time_pd; // Current process data watchdog value 0x0420
uint8_t wd_counter_pdi; // PDI watchdog overflow counter 0x0443 (0 when the read fails, see valid_mask)
uint16_t valid_mask; // EC_WD_STATUS_VALID_* bit set: set means that field was really read successfully this time
} ec_watchdog_status_t;

Example:

auto& slave = master.GetSlave(1);

// Set the process data watchdog timeout
slave.SetWatchdog(100); // 100 ms, 0=disabled

// Set the PDI watchdog timeout
slave.SetPdiWatchdog(200);

// Get the watchdog configuration
ec_watchdog_config_t wdConfig{};
if (slave.GetWatchdogConfig(wdConfig)) {
printf("看门狗配置: PD=%u, PDI=%u, 分频器=%u\n", // Watchdog configuration: PD=%u, PDI=%u, divider=%u\n
wdConfig.wd_time_pd, wdConfig.wd_time_pdi, wdConfig.wd_divider);
}

// Get the watchdog status
ec_watchdog_status_t wdStatus{};
if (slave.GetWatchdogStatus(wdStatus)) {
if ((wdStatus.valid_mask & EC_WD_STATUS_VALID_STATUS) == 0)
printf("看门狗状态位本次未读成功(未知)\n"); // The watchdog status bit could not be read this time (unknown)\n
else
printf("看门狗状态: 0x%02X(%s), 计数器=%u\n", // Watchdog status: 0x%02X (%s), counter=%u\n
wdStatus.wd_status,
(wdStatus.wd_status & 0x01) == 0 ? "已溢出/过期" : "正常或未使能", // expired/timed out / normal or not enabled
wdStatus.wd_counter);
}

ReadWatchdogConfig()​

std::optional<ec_watchdog_config_t> ReadWatchdogConfig() const;

Optional view of the watchdog configuration: std::nullopt = cannot read / not supported, clearly distinguished from "read 0" (a read 0 is a valid verdict meaning the watchdog in that direction is disabled).

Return value:

  • std::optional<ec_watchdog_config_t> — the value on success, std::nullopt on failure

ReadWatchdogStatus()​

std::optional<ec_watchdog_status_t> ReadWatchdogStatus() const;

Optional view of the watchdog status: std::nullopt = cannot read / not supported. Reading 0 is a valid verdict (0x0440 bit0 = overflow, counter 0 = not advancing) and does not mean the read failed.

Per-field validity is always decided by valid_mask: bit 1 = the register was really read this time and the field is trustworthy; bit 0 = the read failed and the field is fixed at 0 and not trustworthy. valid_mask all 0 = none of the five registers was read successfully, the whole status is treated as unknown and std::nullopt is returned; wd_status == 0xFF is no longer used to infer overall validity.

Return value:

  • std::optional<ec_watchdog_status_t> — the status when the read succeeded and at least one field is valid, otherwise std::nullopt

State transitions​

SetState()​

bool SetState(EcState target, uint32_t timeoutMs = 3000) const;

Sets the EtherCAT state of the slave (with a timeout). Use it to recover a single slave manually or to move a slave to a given state.

Parameters:

  • target (EcState) — target state
  • timeoutMs (uint32_t) — timeout in milliseconds, default 3000 ms

Return value:

  • bool — whether it succeeded
note

State transitions follow the standard EtherCAT state machine flow, and the protocol layer handles the intermediate states automatically. For example, switching from INIT to OP passes through PreOp → SafeOp → OP automatically.

Example:

auto& slave = master.GetSlave(1);

// Manually recover a single slave to OP
if (slave.State() != EcState::OP)
slave.SetState(EcState::OP);

// Switch the slave to Init (reset)
slave.SetState(EcState::Init, 5000);

ESM wait policy​

While waiting for a slave to enter a state, the runtime library decides whether another wait is worthwhile, and the caller uses the returned flags to either keep waiting or fail honestly. The meaning of each bit:

BitValueNameDescription
bit00x1demote-grace candidateThe AL Status Code is 0x001F (Watchdog Cfg Invalid), or the slave reached SAFE_OP cleanly with no Error, so another short wait is worthwhile
bit10x2hard errorSlave offline / not responding (base state == 0), or the Error bit is set with an AL code other than 0 / 0x001F (a genuinely fatal AL state); fail honestly at once
—0normalNeither of the above

EsmProbeSlaveWaitFlags()​

int EsmProbeSlaveWaitFlags() const;   // Slave members

Reads the ESM wait policy flags of a single slave. The runtime library is the only authority for the decision; the SDK passes it through unchanged, with no second folding and no state change.

Return value:

  • int — flag combination (bit0 / bit1 as in the table above, 0 = normal); -1 = SDK not ready (an out-of-domain value, distinguishable from 0/1/2/3)
Member and free function share a name

The C header also has a free function with the same name, EsmProbeSlaveWaitFlags(mi, si); the one on this page is a Slave member that uses this slave's index, so there is no ambiguity. Both have the same semantics.

Example:

auto& slave = master.GetSlave(1);

int flags = slave.EsmProbeSlaveWaitFlags();
if (flags < 0) {
printf("SDK 未就绪\n"); // SDK not ready\n
} else if (flags & 0x2) {
printf("硬错误, 如实失败\n"); // Hard error, reported as a real failure\n
} else if (flags & 0x1) {
printf("demote-grace 候选, 可再等一轮\n"); // demote-grace candidate, can wait one more round\n
}

ESM state transition timeouts (GetEsmTimeouts / SetEsmTimeouts)​

struct EsmTimeouts {
uint32_t IP = 0; // Init → PreOp (ms)
uint32_t PS = 0; // PreOp → SafeOp (ms)
uint32_t SO = 0; // SafeOp → OP (ms)
uint32_t OS = 0; // OP → SafeOp (ms)
uint32_t SP = 0; // SafeOp → PreOp (ms)
uint32_t PI = 0; // PreOp → Init (ms)
uint32_t BI = 0; // Any → Boot (ms)
uint32_t IB = 0; // Boot → Init (ms)

static EsmTimeouts Default(); // Take the authoritative default (ETG.1020 section 9.4 Table 55)
};

std::optional<EsmTimeouts> GetEsmTimeouts() const;
bool SetEsmTimeouts(const EsmTimeouts& et) const;

Per-slave ESM (EtherCAT State Machine) state transition timeouts, in milliseconds. A default-constructed EsmTimeouts is all 0 = "unspecified"; the structure itself carries no numeric default table. The authoritative defaults are fetched from the runtime library by Default() (ETG.1020 §9.4 Table 55); when the SDK is not ready every entry is 0 (= unknown).

GetEsmTimeouts() — reads the current configuration. Entries whose value is 0 are filled in by the runtime library from the authoritative default table before returning; std::nullopt = SDK not ready / invalid index / read failed.

SetEsmTimeouts(et) — writes the configuration. Passing all 0 clears the overrides, and the next read falls back to the authoritative default table. To change only one entry, first take the full set from GetEsmTimeouts() or Default() and then modify it: the runtime library caches the whole structure as given, and a field that is not set (0) is recorded as 0 ms rather than filled in automatically.

note

Overrides are stored per slave, and a read returns your override first. When advancing into OP, the SafeOp→OP budget of each slave uses the SO value here first (only when it is not overridden does it fall back to the master-level TimeoutSafeOpToOp(), and then to the ETG.1020 Table 55 default table); waits for the other state entries are still controlled by the master-level entry points TimeoutInitToPreOp() / TimeoutPreOpToSafeOp() and so on (see master configuration).

Return value:

  • true — written
  • false — SDK not ready, invalid slave index or write failed
auto& slave = master.GetSlave(1);

// Read the whole thing first (fall back to the authoritative default table if it cannot be read), then change only SafeOp → OP
Slave::EsmTimeouts t = slave.GetEsmTimeouts().value_or(Slave::EsmTimeouts::Default());
t.SO = 5000;
if (!slave.SetEsmTimeouts(t))
printf("ESM 超时未写入, 保持原配置\n"); // ESM timed out and was not written, keeping the original configuration\n

// Clear all overrides and go back to the authoritative default table
slave.SetEsmTimeouts(Slave::EsmTimeouts{});

Diagnostic mirror (direct read)​

MailboxHealth() / IsFreeRunDemoted() / HealthDegradedCount() are Slave member methods; WcContribution / AlStatusMirror are provided by free functions in the darra::ethercat::diag_mirror namespace (they take mi/si and are not part of the Slave member list). slave_wc_contributed() and the member methods are direct reads of the underlying per-slave diagnostic cache: every call reads the runtime library directly, sends and receives no frames, and what you read is the bus reality at that moment, with no refresh needed. slave_al_status_mirror() is not in that category. This value is a cache refreshed by the master only while it is in OP; it is not the live truth at read time. When the master is not currently in OP (or no sample has been taken yet) the getter returns 0 = not sampled / unknown; only a value other than 0 is a trustworthy sample. Once the master leaves OP the sampler stops and the cache keeps its last sample, so this property no longer claims realtime behaviour.

WKC contribution semantics​

diag_mirror::slave_wc_contributed(mi, si) reflects whether this slave is really responding at this moment:

  • Contributed — the slave contributes to the Working Counter (WKC) normally, that is, when the aggregate WKC is complete (actual == expected, in other words when the deficit wc_deficit() == 0), the byte-by-byte comparison is "full" for every slave.
  • NotContributed — the slave is not contributing to the WKC right now (probably offline / recovering from hot-plug). This is not a master fault; once the slave recovers, the underlying diagnostic mirror returns to Contributed on its own.
  • Unknown (0xFF) — the underlying diagnostic mirror has not been filled in yet; reported honestly and never fabricated as "contributed".
Reliability contract

These direct reads only "report the bus reality faithfully" and take part in no WKC tampering or accommodation logic. The per-slave contribution bit is the per-slave decomposition of the aggregate WKC deficit (expected - actual); a deficit greater than 0 means some slave is not contributing at this moment, so raise an alarm and diagnose, without lowering expected and without stopping OP. Matching master-level direct reads: diag_mirror::wc_deficit(mi) / wkc_actual_mirror(mi) / wkc_expected_mirror(mi) / wkc_complete(mi).

Example:

#include "slave/diag_mirror.hpp"
namespace dm = darra::ethercat::diag_mirror;

auto& slave = master.GetSlave(1);
uint16_t mi = 0, si = 1;

if (dm::slave_wc_contributed(mi, si) == dm::WcContribution::NotContributed) {
auto al = dm::slave_al_status_mirror(mi, si);
printf("从站 %u 此刻未贡献 WKC(疑似掉站),AL Code=0x%02X\n", si, al.code); // Slave %u is contributing no WKC right now (suspected slave loss), AL Code=0x%02X\n
}

if (slave.MailboxHealth() == slave_stats::MailboxHealth::Degraded)
printf("从站 %u 在 OP 但邮箱半失效, 已持续 %us\n", si, slave.HealthDegradedCount()); // Slave %u is in OP but the mailbox is half-failing, for %us now\n

Startup configuration​

CategoryAttributeTypeRead/writeDescription
StartupShouldWritePDOAssignment() / ShouldWritePDOAssignment(bool)boolread/writeWhether to write the PDO Assignment at startup, default true
ShouldWritePDOConfiguration() / ShouldWritePDOConfiguration(bool)boolread/writeWhether to write the PDO Configuration at startup, default true
SupportsCompleteAccess() / SupportsCompleteAccess(bool)boolread/writeWhether the slave supports SDO Complete Access

Configuration source declaration (SetConfigSource / GetConfigSource)​

#include "slave/core.hpp"

enum class ConfigSource : uint8_t {
Unknown = 0, // not declared (the default; cannot be written explicitly)
Eni = 1, // configuration came from an ENI (standard ETG.2100 network configuration XML)
Deni = 2 // configuration came from a DENI (Darra extended network configuration, a superset of ENI)
};

const char* ConfigSourceToString(ConfigSource source); // for logging; out-of-range values fall back to "unknown value (N)", never guessed
CategoryAttributeTypeRead/writeDescription
Configuration sourceGetConfigSource()ConfigSourceread-onlyThe value written by the most recent SetConfigSource; the default ConfigSource::Unknown = the caller never declared one
SetConfigSource(ConfigSource)boolwrite-onlytrue = registered; false = invalid argument (Unknown / out-of-range value), not registered (a Warning has been logged)

Declares which network configuration file this slave's startup parameters / PDO configuration came from. Declaration only: it loads no file, reads or writes no slave and issues no bus operation — actually loading the configuration still goes through the master-side ENI/DENI load + Build.

  • A later write overwrites an earlier one — it may be called repeatedly and supports switching Eni ↔ Deni; GetConfigSource() always returns the most recent declaration.
  • Unknown cannot be written — "not declared" is the default, and writing it explicitly would fabricate a source, so it is rejected with a Warning (returns false, nothing is registered).
  • Repeating the same value does not spam the log — a log line is written only when the declared value actually changes.
The SDK does not record the ENI/DENI source per slave

This is SDK-side declaration state, not a value read back from the device. The SDK records only two things per slave: explicit_replace (explicit plan) and esi_installed (merged ESI defaults); there is no ENI/DENI source field — do not use GetConfigSource() to check the device's actual state. The enum values 0/1/2 match the C ec_config_source_t and the C# ConfigSource value for value.

The only entry points

The configuration source is declared solely through the Slave::SetConfigSource() / Slave::GetConfigSource() member pair; the earlier empty darra::ethercat::SetConfigSourceENI() / SetConfigSourceDENI() free functions have been removed and must not be used.

Example:

auto& slave = master.GetSlave(1);

if (!slave.SetConfigSource(ConfigSource::Deni))
printf("声明失败 —— Unknown 是「未声明」的默认值,不能显式写入\n"); // Declaration failed — Unknown is the default for "not declared" and cannot be written explicitly\n

printf("从站 1 的配置来源声明 = %s\n", // Slave 1 configuration source declaration = %s\n
ConfigSourceToString(slave.GetConfigSource()));

Startup parameter snapshot (ReadStartupSnapshot / ReplaceStartupSnapshot)​

namespace darra::ethercat::slave_startup {

inline int ReadStartupSnapshot(uint16_t mi, uint16_t si,
ec_startup_param_t* buffer, int capacity,
int* required, uint32_t* generation,
uint64_t* revision, uint32_t* source_flags);

inline int ReplaceStartupSnapshot(uint16_t mi, uint16_t si,
const ec_startup_param_t* params, int count,
uint32_t expected_generation,
uint64_t expected_revision,
uint64_t* new_revision);

}

Read-only reading and optimistic-concurrency whole replacement of the slave startup parameter snapshot. ReadStartupSnapshot does not modify the startup parameter queue (different semantics from Add / Replace / Apply), and does not truncate when the capacity is too small: it writes the real entry count back through required and returns a failure, so the caller can grow the buffer and read again and always gets a complete snapshot. ReplaceStartupSnapshot replaces under optimistic concurrency on (generation, revision); a mismatch of the expected values is rejected and nothing is written, so it never silently overwrites parameters someone else has just written.

Return value:

  • int — 0 = success; negative = failure (invalid argument / insufficient capacity / expectation mismatch / not ready)

ESC register access (advanced)​

Read and write slave ESC (EtherCAT Slave Controller) registers directly, for fault diagnosis, custom ESC operations and low-level debugging. The protocol layer uses FPRD/FPWR datagrams and falls back automatically through the primary → secondary → APWR chain.

Advanced API

You do not need to call this in normal SDK use; the state transition / PDO / mailbox flows configure the registers automatically. This API is for in-depth diagnosis and special cases (for example reading error counters, forcing a port policy, or debugging an ESI burn that does not take effect).

Register definitions are in ETG.1000.4 §6 / ETG.1000.6 §5 (public standards), for example:

RegisterDescription
0x0000Type / Revision / Build (device type)
0x0030AL Control (the master issues a state request)
0x0130AL Status (current slave state)
0x0134AL Status Code (error code)
0x0300-0x030FPort 0-3 error counters
0x0400-0x043FWatchdog configuration / counters
0x0440-0x0443SM watchdog status / overflow counters: 0x0440 bit0 (0 = overflowed/expired, 1 = normal or not enabled; 0xFF = read failed/unknown); writing 0 to 0x0442/0x0443 resets them, a read does not clear them

ReadRegister()​

bool ReadRegister(uint16_t addr, uint8_t* data, uint32_t len) const;

Reads a slave ESC register (FPRD).

Parameters:

  • addr (uint16_t) — register address (for example 0x0130 = AL Status)
  • data (uint8_t*) — receive buffer
  • len (uint32_t) — number of bytes to read (1/2/4 and so on)

Return value:

  • bool — true on success, false on failure (slave offline / timeout)

WriteRegister()​

bool WriteRegister(uint16_t addr, const uint8_t* data, uint32_t len) const;

Writes a slave ESC register (FPWR).

Parameters:

  • addr (uint16_t) — register address
  • data (const uint8_t*) — data to write
  • len (uint32_t) — number of bytes

Return value:

  • bool — true on success

Example:

auto& slave = master.GetSlave(1);

// Read the AL Status (0x0130, 2 bytes)
uint8_t alStatus[2] = {0};
if (slave.ReadRegister(0x0130, alStatus, 2)) {
uint16_t state = alStatus[0] | (alStatus[1] << 8);
printf("AL Status = 0x%04X (state=%u, err=%s)\n",
state, state & 0x0F, (state & 0x10) ? "yes" : "no");
}

// Read the AL Status Code (0x0134, error code)
uint8_t alCode[2] = {0};
slave.ReadRegister(0x0134, alCode, 2);
uint16_t code = alCode[0] | (alCode[1] << 8);
printf("AL Status Code = 0x%04X\n", code);

// Write AL Control = 0x04 (request SafeOp)
uint8_t alCtrl[2] = { 0x04, 0x00 };
slave.WriteRegister(0x0030, alCtrl, 2);

EEPROM (SII) access​

Read and write the slave SII EEPROM (Slave Information Interface, ETG.1000.6 §6). The EEPROM stores device identity and configuration information such as VendorID / ProductCode / RevisionNo / SerialNo / SyncManager / FMMU / PDO mapping / Strings. The SDK normally reads it automatically during config_init, so an application usually does not need to access it directly.

Risky operation

Use EEPROM writes with care — a wrong write can corrupt the slave identity information and, in the worst case, permanently brick the slave, leaving recovery to the vendor's tool. Use it only for:

  • Burning an alias address (ESC 0x0012)
  • Repairing factory data that was overwritten by mistake
  • Vendor-authorised firmware / parameter programming

Each word takes the EEPROM over from the PDI and gives it back after the write, so you do not call Sii::Acquire() / Sii::Release() manually; the explicit Sii::Acquire() / Sii::Release() pair is for holding a whole range while writing a batch, so the PDI cannot take it back in the middle.

EEPROM writes require the slave to be in Init / PreOp state; a write in OP state is rejected.

EEPROM sizes are usually 1 KB - 16 KB (addressed in words, 1 word = 2 byte). The first 8 words hold basic vendor information, followed by the Category list (Strings / General / FMMU / SyncM / TxPdo / RxPdo / DC / End=0xFFFF).

ReadEeprom(uint16_t byte_offset, uint16_t byte_length)​

std::vector<uint8_t> ReadEeprom(uint16_t byte_offset, uint16_t byte_length) const;

Reads a byte range of the slave SII EEPROM (looping word by word). The SDK handles BUSY polling and word alignment automatically; applications should prefer this high-level API.

Parameters:

  • byte_offset (uint16_t) — start byte offset (even alignment recommended)
  • byte_length (uint16_t) — number of bytes to read (even recommended)

Return value:

  • std::vector<uint8_t> — byte_length bytes of data; an empty vector on failure or invalid arguments

WriteEeprom(uint16_t byte_offset, const std::vector<uint8_t>& data)​

bool WriteEeprom(uint16_t byte_offset, const std::vector<uint8_t>& data) const;

Writes a byte range of the slave SII EEPROM (looping word by word, using SIIWriteWord internally). Both byte_offset and data.size() must be even.

Parameters:

  • byte_offset (uint16_t) — start byte offset (must be even)
  • data (std::vector<uint8_t>) — bytes to write (length must be even)

Return value:

  • bool — true when every word was written successfully

Example:

auto& slave = master.GetSlave(1);

// Read vendor_id (EEPROM byte offset 0x10, length 4)
auto data = slave.ReadEeprom(0x10, 4);
if (data.size() == 4) {
uint32_t vendor = data[0] | (data[1] << 8) | (data[2] << 16) | (data[3] << 24);
printf("VendorID = 0x%08X\n", vendor);
}

// Read the first 16 bytes of the header (including PDIControl/StationAlias and so on)
auto header = slave.ReadEeprom(0, 16);

// Write the alias address (EEPROM byte offset 0x08)
// The slave must be in Init/PreOp!
if (slave.State() == EcState::Init) {
slave.WriteEeprom(0x08, std::vector<uint8_t>{0x01, 0x00}); // alias = 1
}
High-level API vs low-level SII API
  • First choice: ReadEeprom / WriteEeprom (byte oriented, word alignment handled for you)
  • Second choice: wrapped attributes such as slave.VendorId() / ProductId() / EsiName() (the serial number SerialNumber() is a runtime snapshot — use TryGetSerialNumber() below for the EEPROM real value)
  • Advanced use (as needed): the slave.GetSii().* sub-object API below offers word-level, Category-level and control-ownership access for enumerating Categories / reading raw PDO mapping bytes / burning an alias. Reading and writing the ESC registers (0x0500-0x050F) directly requires the application to handle BUSY polling and timing itself and is not recommended.

Serial number (TryGetSerialNumber)​

uint32_t                SerialNumber() const;        // runtime identity snapshot
std::optional<uint32_t> TryGetSerialNumber() const; // snapshot → live SII read

SerialNumber() returns the SER field of the runtime identity snapshot: cold configuration reads the SER word only for slaves that did not match an ESI (a performance trade-off), so slaves that matched an ESI stay at 0. Its 0 is therefore neither a genuine device serial number of 0 nor a read failure.

TryGetSerialNumber() shares its source with the SII EEPROM identity area (word 0x000E..0x000F). Order of operations: ① a runtime snapshot that already holds a value other than 0 is returned directly without touching the EEPROM; ② a snapshot of 0 triggers a live read of the two SII words.

Return valueMeaning
A value (the std::optional is engaged)The real value was obtained, possibly 0 (the device declares serial number 0)
std::nulloptThe read failed (the wrapper layer is not ready / an SII word did not come back); this does not mean the device serial number is 0
The three 0s are not the same thing

SerialNumber() returning 0, TryGetSerialNumber() returning std::nullopt, and TryGetSerialNumber() returning an engaged value of 0 are three different facts: the first only says the snapshot was not read (it may have been skipped by cold configuration, and it may really be 0), the second is a failed read (unknown), and only the third means "the device serial number really is 0". Never convert one into another.

Example:

auto& slave = master.GetSlave(1);

slave.SerialNumber(); // runtime snapshot: 0 may mean "not read", or a real value of 0

if (auto sn = slave.TryGetSerialNumber())
printf("序列号 = %u(0 也是合法真值)\n", *sn); // Serial number = %u (0 is also a valid real value)\n
else
printf("序列号未知(SII 读不出来)\n"); // Serial number unknown (cannot be read from SII)\n
note

When the snapshot is 0, every call really reads the EEPROM — cache it yourself if you need it frequently. To fetch Vendor / Product / Revision / Serial in one go, use GetSii().TryReadIdentity() below.

Advanced usage: the low-level Sii API​

Get the Sii& reference through slave.GetSii() (lazily initialized). The Sii class offers finer-grained EEPROM access at word level, Category level and control-ownership level (ETG.1000.6 §6). For ordinary applications, prefer ReadEeprom / WriteEeprom above.

  • Single word
    • ReadWord(uint16_t wordAddr, uint16_t& value) (bool, read) — reads one EEPROM word (wordAddr is in words), returns false on failure
    • WriteWord(uint16_t wordAddr, uint16_t value) (bool, write) — writes one EEPROM word (with PDI handover protection), returns false on failure
  • Control ownership
    • Acquire() (bool, write) — forces the master to take over the EEPROM (for holding a whole range while writing a batch; a single-word write takes over internally, no manual call needed)
    • Release() (bool, write) — hands EEPROM control back to the PDI
    • ReadControlReg() (std::optional<uint8_t>, read) — reads the raw SII control register byte, returns std::nullopt on failure
    • IsHeldByPdi() (bool, read) — whether EEPROM control is held by the PDI (true = held by the PDI, false = held by the master)
  • Category
    • FindCategory(SiiCategory cat) (std::optional<std::pair<uint32_t, uint32_t>>, read) — finds a Category's (byte offset, byte size); returns std::nullopt when it does not exist
    • ReadCategory(SiiCategory cat, int maxBytes = 4096) (std::optional<std::vector<uint8_t>>, read) — reads the whole Category data block; returns std::nullopt when it does not exist
    • EnumerateCategories(int max = 64) (std::vector<SiiCategory>, read) — enumerates every Category type on the slave; returns an empty vector on failure
    • TryFindCategory(SiiCategory cat, uint32_t& byteOffset, uint32_t& byteSize) (SiiReadStatus, read) — finds a Category's (byte offset, byte size); distinguishes "the chain really has no such category" from "read failed"
    • TryReadCategory(SiiCategory cat, std::vector<uint8_t>& data, int maxBytes = 4096) (SiiReadStatus, read) — reads the whole Category data block; distinguishes "does not exist" from "read failed"; Ok + empty data = a legitimately empty Category
  • Structured
    • GetStrings(int maxBufBytes = 4096) (std::vector<std::string>, read) — reads the Strings Category and parses it into a list of strings (NUL separated)
    • GetStringByIndex(uint8_t stringIndex, int maxBytes = 256) (std::string, read) — takes a single string by index (1-based) (GroupName / DeviceName / ImageName and so on)
    • GetGeneralInfo() (std::optional<SiiGeneralInfo>, read) — reads and parses the General Category (type = 30) into structured information
    • TryGetGeneralInfo(std::optional<SiiGeneralInfo>& info) (SiiReadStatus, read) — reads and parses the General Category (type = 30); distinguishes "the chain has no GENERAL" from "read failed"
  • Identity area
    • TryReadIdentity(SiiIdentity& identity) (SiiReadStatus, read) — reads the complete identity area (V/P/R/Serial, 8 words, 0x0008..0x000F); only Ok / ReadFailed are possible (the identity area always exists, there is no NotFound); on failure the output is cleared to 0 as a whole, so no half identity is handed out
    • TryReadSerialNumber(uint32_t& serial) (SiiReadStatus, read) — reads only the Serial word of the identity area (word 0x000E / 0x000F); on Ok it is the real value (may be 0), on ReadFailed it is set to 0 = unknown

SII read status (three states):

enum class SiiReadStatus : uint8_t {
Ok = 0, // The truth value read
NotFound = 1, // The chain is readable and genuinely has no such category - a normal result, not an error
ReadFailed = 2 // SII cannot be read / the locate or length word read failed - must not be treated as "absent"
};

The values 0/1/2 match the C side EC_SII_READ_* and the C# SiiReadStatus value for value. Ok is a real value; NotFound means the category chain is readable and genuinely lacks that category (a normal result, not an error); ReadFailed means the SII could not be read, or locating / reading the length word failed, and it must never be treated as "not present".

  • The older FindCategory / ReadCategory / GetGeneralInfo return std::optional, where std::nullopt means both "not present" and "read failed", so the two are indistinguishable. Use the Try* variants to tell them apart; the old entry points keep their behaviour.

  • Attribution — the locate call only has a binary result, so on failure the SDK cross-checks the category chain: shell not bound (entry unavailable / shell_ready() false) → ReadFailed; category-chain enumeration returns a negative value (not even an SII context) → ReadFailed; the chain does contain the category yet locating or the length-word read failed → ReadFailed; the chain is readable and genuinely without it → NotFound. TryGetGeneralInfo follows the same rule: only "the chain really has no GENERAL category" is NotFound, everything else is ReadFailed.

  • Output conventions — on failure byteOffset / byteSize are set to 0, data is cleared and info becomes std::nullopt; half a block is never handed out. Ok with an empty data means a legitimately empty category, not a failure.

  • maxBytes: 0 reads no bytes at all (Ok + empty); a negative value is an invalid request — no bus access, straight to ReadFailed.

class Sii {
public:
// Single word read/write
bool ReadWord(uint16_t wordAddr, uint16_t& value) const;
bool WriteWord(uint16_t wordAddr, uint16_t value) const;

// Control authority management
std::optional<uint8_t> ReadControlReg() const;
bool IsHeldByPdi() const;
bool Acquire() const;
bool Release() const;

// Category traversal
std::optional<std::pair<uint32_t, uint32_t>> FindCategory(SiiCategory cat) const;
std::optional<std::vector<uint8_t>> ReadCategory(SiiCategory cat, int maxBytes = 4096) const;
std::vector<SiiCategory> EnumerateCategories(int max = 64) const;

// Category is tri-state (distinguishes "absent" from "read failed")
SiiReadStatus TryFindCategory(SiiCategory cat, uint32_t& byteOffset, uint32_t& byteSize) const;
SiiReadStatus TryReadCategory(SiiCategory cat, std::vector<uint8_t>& data, int maxBytes = 4096) const;

// Structured read
std::vector<std::string> GetStrings(int maxBufBytes = 4096) const;
std::string GetStringByIndex(uint8_t stringIndex, int maxBytes = 256) const;
std::optional<SiiGeneralInfo> GetGeneralInfo() const;
SiiReadStatus TryGetGeneralInfo(std::optional<SiiGeneralInfo>& info) const;

// Identity area (ETG.1000.6 word 0x0008..0x000F)
SiiReadStatus TryReadIdentity(SiiIdentity& identity) const;
SiiReadStatus TryReadSerialNumber(uint32_t& serial) const;
};

Identity area (TryReadIdentity / TryReadSerialNumber)

The identity area (ETG.1000.6 word 0x0008..0x000F) holds four entries; each occupies two consecutive words and the 32-bit value is assembled with the low word first: value = (uint32_t)low | ((uint32_t)high << 16).

struct SiiIdentity {
uint32_t VendorId = 0; // word 0x0008 low word / 0x0009 high word
uint32_t ProductCode = 0; // word 0x000A low word / 0x000B high word
uint32_t RevisionNo = 0; // word 0x000C low word / 0x000D high word
uint32_t SerialNo = 0; // word 0x000E low word / 0x000F high word
};

The identity area always exists in the EEPROM, so there are only Ok / ReadFailed — no NotFound:

Return valueMeaning
SiiReadStatus::OkThe identity area is complete and the output holds the EEPROM real values (any entry may be 0 — 0 can be a value the device declares)
SiiReadStatus::ReadFailedA word did not come back (incomplete identity area); the output is cleared to 0 as a whole = unknown, not a real value of 0

Output conventions: if any word does not come back the call is judged ReadFailed as a whole — no half identity is handed out — and on failure the output is cleared to 0 (no stale values from a previous call are left behind); "unreadable" is never folded into 0.

auto& sii = slave.GetSii();

SiiIdentity id;
if (sii.TryReadIdentity(id) == SiiReadStatus::Ok)
printf("V=0x%08X P=0x%08X R=0x%08X SN=%u\n",
id.VendorId, id.ProductCode, id.RevisionNo, id.SerialNo);
else
printf("身份区读不全 —— 不交付半份身份,也不能当成序列号 0\n"); // Identity area could not be read completely — a half identity is never delivered, and it must not be taken as serial number 0\n

uint32_t serial = 0;
if (sii.TryReadSerialNumber(serial) == SiiReadStatus::Ok)
printf("序列号 = %u(0 也是合法真值)\n", serial); // Serial number = %u (0 is also a valid real value)\n
Difference from the runtime snapshot

These two entry points read the EEPROM directly, so they are not affected by the cold-configuration trade-off that skips the SER word on slaves that matched an ESI; Slave::SerialNumber() reads the runtime snapshot, which stays 0 for those slaves. Every call really reads 8 words (TryReadIdentity) / 2 words (TryReadSerialNumber), so cache the values yourself if you need them frequently.

Three-state reads:

auto& sii = slave.GetSii();

// 1) Locate + length: three outcomes Ok / NotFound / ReadFailed
uint32_t off = 0, size = 0;
switch (sii.TryFindCategory(SiiCategory::TxPdo, off, size)) {
case SiiReadStatus::Ok:
printf("TxPdo: 偏移 %u, 长度 %u\n", off, size); // TxPdo: offset %u, length %u\n
break;
case SiiReadStatus::NotFound:
printf("链上确实没有 TxPdo(正常结果)\n"); // Normal result, not an error
break;
case SiiReadStatus::ReadFailed:
printf("SII 读不出来,不能断言不存在\n"); // Must not be treated as NotFound
break;
}

// 2) Read the whole segment: on failure data is cleared and partial data is never delivered
std::vector<uint8_t> data;
if (sii.TryReadCategory(SiiCategory::RxPdo, data) == SiiReadStatus::Ok)
printf("RxPdo: %zu 字节\n", data.size()); // 0 bytes = a valid empty category

// 3) Structured General: on failure info is reset to nullopt
std::optional<SiiGeneralInfo> info;
if (sii.TryGetGeneralInfo(info) == SiiReadStatus::Ok)
printf("E-bus 电流: %d mA\n", info->EbusCurrentMa); // E-bus current: %d mA\n
SiiCategory enum (ETG.1000.6 Table 17)
enum class SiiCategory : uint16_t {
Strings = 10,
DataTypes = 20,
General = 30,
FMMU = 40,
SyncM = 41,
TxPdo = 50,
RxPdo = 51,
DC = 60,
End = 0xFFFF,
};
SiiGeneralInfo structure (ETG.1000.6 Table 18, General Category type=30)

Each *Idx field is a 1-based entry index in the Strings Category; combine it with GetStringByIndex() to fetch the actual string.

struct SiiGeneralInfo {
uint8_t GroupIdx; // GroupType entry index (1-based)
uint8_t ImageIdx; // ImageName entry index
uint8_t OrderIdx; // Order number entry index
uint8_t NameIdx; // DeviceName entry index
uint8_t CoeDetails; // CoE detail bitmap
uint8_t FoeDetails; // FoE support (bit0)
uint8_t EoeDetails; // EoE support (bit0)
uint8_t SoeDetails; // SoE support (bit0)
uint8_t Flags; // Flag bits
int16_t EbusCurrentMa; // E-bus current (mA)
uint16_t PhysicalPort; // Physical port encoding (4 nibbles, 1 port per nibble)

// CoE detail bit parsing method
bool SupportsSdo() const;
bool SupportsSdoInfo() const;
bool SupportsPdoAssign() const;
bool SupportsPdoConfig() const;
bool UploadAtStartup() const;
bool SupportsCompleteAccess() const;
bool SupportsFoE() const;
bool SupportsEoE() const;
bool SupportsSoE() const;
};

Example:

auto& slave = master.GetSlave(1);
auto& sii = slave.GetSii();

// Enumerate Category
for (auto cat : sii.EnumerateCategories())
printf(" Category: %u\n", static_cast<unsigned>(cat));

// Read the structured General Category information
if (auto info = sii.GetGeneralInfo()) {
printf("E-bus 电流: %d mA, CoE Complete Access: %s\n", // E-bus current: %d mA, CoE Complete Access: %s\n
info->EbusCurrentMa,
info->SupportsCompleteAccess() ? "是" : "否");
// Use NameIdx to get the device name string
std::string name = sii.GetStringByIndex(info->NameIdx);
printf("设备名: %s\n", name.c_str()); // Device name: %s\n
}

// Read the PDO mapping Category byte array (TxPdo)
if (auto txPdo = sii.ReadCategory(SiiCategory::TxPdo))
printf("TxPdo Category: %zu 字节\n", txPdo->size()); // TxPdo Category: %zu bytes\n

// word-level write; the slave must be in Init/PreOp
// Here Sii::Acquire()/Sii::Release() show how to hold a whole segment for batch writes (a single write needs no manual hold)
if (slave.State() == EcState::Init && sii.Acquire()) {
sii.WriteWord(0x04, 0x0001); // alias = 1
sii.WriteWord(0x05, 0x0000); // Reserved field
sii.Release();
}

DL Port control​

Read and write the ESC DL Port Control register (0x0101) directly, for port fault injection tests and manual diagnostics of redundancy / ring topologies.

Advanced API

No call is needed during normal operation. Most users should diagnose port status by subscribing to the SlavePortLinkChanged event and reading the port error counters. Use it only when you need to actively simulate a port fault (to test redundancy switching) or to investigate a specific port.

DEBUG builds only

WriteDLPort() / ReadDLPort() are exposed in the SDK headers for debug builds only; Release / production builds do not provide these two methods. Port fault injection is for test scenarios only.

The ESC has 4 physical ports P0 / P1 / P2 / P3; the bits of the DL Port Control register are defined as follows:

DLPORT valueBehaviour
0x00Auto — all ports are managed by the ESC automatically (default)
0x03Disable P0
0x0CDisable P1
0x30Disable P2
0xC0Disable P3

The SDK automatically uses the primary → secondary → APWR three-level fallback write path, so even after P0 is disabled the slave can still be reached through the secondary port / broadcast.

WriteDLPort(value)​

bool WriteDLPort(uint8_t value) const;

Writes the slave DL Port control register (0x0101).

Parameters:

  • value (uint8_t) — DLPORT value (see the table above)

Return value:

  • bool — true on success

ReadDLPort()​

uint8_t ReadDLPort() const;

Reads the current value of the slave DL Port control register.

Return value:

  • uint8_t — current DLPORT value (0 when the read fails)

Example:

auto& slave = master.GetSlave(1);

// Simulate a P1 port fault (to test the redundancy switchover)
bool ok = slave.WriteDLPort(0x0C);
printf("关闭 P1: %s\n", ok ? "成功" : "失败"); // Close P1: %s (success / failed)

// Read-back confirmation
uint8_t dlport = slave.ReadDLPort();
printf("当前 DLPORT = 0x%02X\n", dlport); // Current DLPORT = 0x%02X\n

// Restored after the fault clears
slave.WriteDLPort(0x00); // Restore Auto
Pair with redundancy diagnostics

After disabling a port, subscribe to master.Events().OnSlavePortLinkChanged(cb) and check master.GetDiagnostics().GetBreakPoints() to verify that redundancy switching took effect.

SyncManager control​

auto& slave = master.GetSlave(1);

// Enable the output SyncManager
slave.EnableOutputSyncManager();

// Disable the output SyncManager
slave.DisableOutputSyncManager();

ConfigureSyncManager(sm_idx, addr, len, ctrl, enable)​

bool ConfigureSyncManager(uint8_t sm_idx, uint16_t addr, uint16_t len,
uint8_t ctrl, bool enable) const;

Writes one SyncManager configuration entry by SM index.

Parameters:

  • sm_idx (uint8_t) — SyncManager index starting at 0 (SM0 / SM1 are usually the mailbox, SM2 / SM3 the process data); an index beyond the slave's SM count fails immediately
  • addr (uint16_t) — SM start address; 0 = keep the current configuration (as read from EEPROM / SII)
  • len (uint16_t) — SM buffer length; 0 = do not change the length, keep the current value
  • ctrl (uint8_t) — SM control byte; 0 = keep the current value. When the current value is 0 as well, the default is restored by index: SM0=0x26 (mailbox output, 1 buffer), SM1=0x22 (mailbox input, 1 buffer), SM2=0x24 (PDO output, 3 buffers), SM3=0x20 (PDO input, 3 buffers)
  • enable (bool) — whether to set the enable bit

Return value:

  • true — the configuration was committed
  • false — invalid slave / SM index, the configuration write failed, or the configuration window is already closed (the state changed after the build, so the write is refused)
note

In PreOp, writes to SM2 / SM3 (the process data SMs) are not sent to the hardware immediately; they are written together by the configuration flow when the slave enters SafeOp. When addr is 0, only the local override is updated. The normal startup flow already configures the SMs from the ESI / ENI, so manual changes are needed only for custom mappings or experiments.

ConfigureFMMU(...)​

bool ConfigureFMMU(uint8_t fmmu_idx, uint32_t logical_addr, uint16_t length,
uint8_t log_start_bit, uint8_t log_end_bit,
uint16_t phys_start_addr, uint8_t phys_start_bit,
uint8_t type, bool active) const;

Configures one FMMU mapping.

Parameters:

  • fmmu_idx (uint8_t) — FMMU index starting at 0 (0-15); out of range fails immediately
  • logical_addr (uint32_t) — logical address, that is, the start address within the process image
  • length (uint16_t) — mapping length in bytes
  • log_start_bit / log_end_bit (uint8_t) — logical start bit / end bit
  • phys_start_addr (uint16_t) — start address in the slave physical memory
  • phys_start_bit (uint8_t) — physical start bit
  • type (uint8_t) — 1 = read (input), 2 = write (output), 3 = read + write
  • active (bool) — whether to activate this FMMU

Return value:

  • true — written
  • false — invalid slave / FMMU index, the configuration write failed, or the configuration window is already closed
Advanced API

Changing an FMMU by hand directly moves where the process data lands. Use it only for custom mappings and diagnostic experiments; after changing it, always read the process data back to confirm the byte positions, and do not mix it with mappings generated from the ESI / ENI.

GetFMMUs() / GetSyncManagerTypes()​

std::vector<uint8_t> GetFMMUs() const;             // FMMU0..FMMU3 function types, always 4 entries
std::vector<uint8_t> GetSyncManagerTypes() const;

GetFMMUs() returns the function type codes of FMMU0..FMMU3 (bit0 = output, bit1 = input), always 4 entries.

GetSyncManagerTypes() currently returns the same array as GetFMMUs() (the same source) and reads no SM registers; do not treat it as per-SM control bytes or as evidence of the SM count. To write SM configuration use ConfigureSyncManager().

Slave identity verification​

C++-specific sugar

In C++ you can take the three identity values at once with auto [vendor, product, rev] = darra::sugar::identity_tuple(slave); structured binding, so logging / formatting does not have to chain several property calls.

Fields of the slave identity structure ec_slave_identity_t: VendorId (vendor ID) / ProductCode (product code) / RevisionNo (revision number) / SerialNo (serial number).

auto& slave = master.GetSlave(1);

// Get slave identity information
ec_slave_identity_t identity{};
if (slave.GetIdentity(identity)) {
printf("VID=0x%08X, PID=0x%08X\n", identity.VendorId, identity.ProductCode);
}

// Verify the slave identity
ec_slave_identity_t expected{};
expected.VendorId = 0x00000002;
expected.ProductCode = 0x03F03052;
bool match = slave.VerifyIdentity(expected, true, false);

Scan result structure (ScannedSlaveInfo)​

The per-slave entry returned by darra::ethercat::statics::ScanSlaves(...), defined in statics/network.hpp. A full scan reads the identity information and topology of every slave, so these fields are usable before any Slave object exists; they suit a device list, a model check and naming before power-up.

namespace darra::ethercat::statics {

struct ScannedSlaveInfo {
int Index = 0; // Slave index (from 1)
std::string Name; // Slave name
uint32_t VendorId = 0; // Vendor ID
uint32_t ProductCode = 0; // Product code
uint32_t RevisionNumber = 0; // Revision number
uint32_t SerialNumber = 0; // Sequence number
uint16_t ConfigAddr = 0; // Configuration address
uint16_t AliasAddr = 0; // Alias address

uint16_t ParentIndex = 0; // Parent slave index (0 = the parent is the master)
uint8_t Topology = 0; // Topology type: 0=no link 1=endpoint 2=middle 3=branch 4=crossover
uint8_t ActivePorts = 0; // Active port bitmap (bit0=Port0 ... bit3=Port3)
uint8_t EntryPort = 0; // Entry port
uint8_t ParentPort = 0; // Parent port
uint8_t PhysicalType = 0; // Physical port type (ESC register 0x0007)
int Depth = 0; // Topology depth (from the root node)

int MbxProtocol = 0; // Mailbox protocol capability bitmap
};

}
CategoryAttributeTypeRead/writeDescription
Identity formattingVendorIdHex()std::stringread-onlyHexadecimal text of the vendor ID, format 0x%08X
ProductCodeHex()std::stringread-onlyHexadecimal text of the product code, format 0x%08X
AliasAddrHex()std::stringread-onlyHexadecimal text of the alias address, format 0x%04X
Device classificationDeviceType()std::stringread-onlyReturns Coupler / Terminal / Device; for a vendor the SDK's coupler / terminal table does not know, a heuristic on port type then yields Box / Coupler / Extension / Terminal / Device
IsCoupler()boolread-onlyWhether the slave is a coupler: the SDK's table is checked first, and for an unknown vendor the decision uses topology, name keywords and the port combination; when unsure it is treated as not a coupler (rather a separate slave than a wrong coupler verdict)
GetPortTypeString(portType)const char*read-onlyStatic method: 0=N/A, 1=NC, 2=EBUS, 3=MII; any other value returns a placeholder containing the raw number. The returned string uses a thread-local buffer, so the next call on the same thread overwrites it
Mailbox capabilityHasCoE()boolread-onlyMailbox capability bit map bit2
HasFoE()boolread-onlyBit map bit3
HasEoE()boolread-onlyBit map bit1
HasSoE()boolread-onlyBit map bit4
HasAoE()boolread-onlyBit map bit0
HasVoE()boolread-onlyBit map bit5

GetPortType(port) accepts only 0..3 and returns -1 otherwise; the codes it returns are 0 = not implemented / 1 = not configured / 2 = EBUS / 3 = MII, which are not the same set as the EcPortType enum on this page (0 = NotUsed, 1 = MII); do not convert values between the two.

The HasCoE() group is a plain bit map test with no three-state form: a 0 bit returns false, which only means "not declared in this scan snapshot" and does not mean the device confirms it is unsupported. For a definite verdict, connect to the slave and use the Slave three-state entry points CoESupport() / FoESupport() and so on.

Example:

using namespace darra::ethercat;

statics::ScanOutcome outcome{};
int code = 0;
auto list = statics::ScanSlaves(dll, "\\Device\\NPF_{...}", "", outcome, code);

for (const auto& s : list) {
printf("[%d] %s VID=%s PID=%s alias=%s type=%s coupler=%s\n",
s.Index, s.Name.c_str(),
s.VendorIdHex().c_str(), s.ProductCodeHex().c_str(),
s.AliasAddrHex().c_str(), s.DeviceType().c_str(),
s.IsCoupler() ? "yes" : "no");
}

DC configuration methods​

auto& slave = master.GetSlave(1);

// Configure DC synchronisation
slave.ConfigureDC(1000000); // SYNC0 = 1ms
slave.ConfigureDC(1000000, 500000); // SYNC0 + SYNC1
slave.ConfigureDC(125000, 0, 100000); // SYNC0 + offset

// Disable DC
slave.DisableDC();

// Propagation delay
int delay = slave.PropagationDelay();

// Sync window state
auto syncStatus = slave.GetSyncWindowStatus();
if (syncStatus) {
printf("同步差=%dns, 同步=%s\n", // sync diff=%dns, synced=%s\n
syncStatus->DiffNs, syncStatus->InSync ? "是" : "否");
}

GetDCReceiveTime() and DCReceiveTimeA/B/C/D()​

struct DCReceiveTime {
int32_t A = 0; // Port A receive time (ns)
int32_t B = 0; // Port B
int32_t C = 0; // Port C
int32_t D = 0; // Port D
};

DCReceiveTime GetDCReceiveTime() const; // Take all four ports in one pass
int32_t DCReceiveTimeA() const; // Single-port direct read
int32_t DCReceiveTimeB() const;
int32_t DCReceiveTimeC() const;
int32_t DCReceiveTimeD() const;

DC receive times of ports A / B / C / D, in nanoseconds. GetDCReceiveTime() only packs the four accessors into a structure; the values are exactly the same as calling them one by one, and no extra frame is sent.

These four accessors return the number only, with no separate validity bit: when the slave has no DC capability / cannot be read, the runtime library value is returned as is and is not folded into std::nullopt. To decide whether DC is usable, check HasDC() first and then the measured side of GetSyncWindowStatus().

GetDcArmOutcome()​

std::optional<DcArmResult> GetDcArmOutcome() const;

Always returns std::nullopt. The final-state accounting that the automatic startup DC arm policy produces for this slave is not inside the C++ SDK (the decision is made by an upper state machine, and the SDK has no equivalent data source), so it is not disguised as any of Unknown / armed / failed.

Get the reason text with DcArmOutcomeUnavailableReason() (UTF-8 Chinese, ready to display). To see whether this slave actually generates SYNC0, look at Sync0Armed(); to see whether it is really in sync, look at GetSyncWindowStatus().

GetDcJitterStats() / ResetDcJitterStats()​

struct DcJitterStats {
uint32_t SampleCount = 0; // Sample count within the window
int32_t MinNs = 0; // Minimum phase offset within the window (ns)
int32_t MaxNs = 0; // Maximum phase offset within the window (ns)
int32_t AvgNs = 0; // Average phase offset within the window (ns, truncated toward zero)
};

std::optional<DcJitterStats> GetDcJitterStats() const;
void ResetDcJitterStats() const;

Per-slave SYNC0 phase jitter: reads the current window live and triggers no bus frame. std::nullopt = no DC capability / slave index out of range / no sample yet / context generation changed; 0 ns is a valid true value (perfect sync), and the two are not mixed.

Difference from the master-level MasterDiagnosticsInfo::DcJitter(): that one reads a 2-second sampling snapshot (cached), while this method takes the current window every time.

ResetDcJitterStats() resets the window of this slave, and the next sample opens a new one; it clears statistics only and does not change the DC configuration.

DcSlaveSnapshot::ArmOutcomeUnavailableReason()​

struct DcSlaveSnapshot {
// ……the remaining fields and how to read them are on the master DC diagnostics page
std::optional<DcArmResult> ArmOutcome; // Always nullopt on the C++ side

static const char* ArmOutcomeUnavailableReason();
};

The per-slave entries in the master-level DC diagnostics snapshot also carry ArmOutcome, which is always std::nullopt on the C++ side, for the same reason as Slave::GetDcArmOutcome(): the final-state accounting is not inside the C++ SDK and there is no equivalent data source. ArmOutcomeUnavailableReason() returns that Chinese reason text, ready to display in a UI or a log.

See master DC diagnostics for how to obtain the snapshot and for its lifetime.

PDO input and output​

The recommended path is to map once into the real-time process image after entering OP: darra::SlavePDO::InputsMapping<T> returns const T& (read-only on the input side) and OutputsMapping<T> returns T&; the reference points straight at the real-time process image (live IOmap), so reading a field from any thread gives the current value and there is no need to remap every cycle. CopyInputFrame / WriteOutputFrame take a generation whole-frame snapshot and are not zero-copy; ReadInputDirect / WriteOutputDirect follow the same whole-frame contract internally.

std::vector<uint8_t> inFrame;
if (darra::SlavePDO::CopyInputFrame(dll, master.MasterNumber(), 1, inFrame)) {
printf("输入帧 %zu 字节\n", inFrame.size()); // Input frame %zu bytes\n
}

uint8_t outData[] = {0x0F, 0x00, 0, 0, 0, 0};
darra::SlavePDO::PdoWriteResult wr = darra::SlavePDO::WriteOutputFrame(
dll, master.MasterNumber(), 1, outData, sizeof(outData));
if (!wr.Succeeded(sizeof(outData))) {
// BUSY (bounded retries exhausted, can be retried later) is distinguishable from a permanent failure
printf("写入未完成: status=%d, written=%u, required=%u\n", // Write incomplete: status=%d, written=%u, required=%u\n
static_cast<int>(wr.status), wr.written, wr.required);
}

Slave::WriteOutput(...) also returns darra::SlavePDO::PdoWriteResult (no longer a bool): use Succeeded(size) to test that the whole frame was written, or status to tell Busy / SizeMismatch / Failed apart.

WriteOutputByte(offset, value)​

bool WriteOutputByte(uint32_t offset, uint8_t value) const;

Changes a single byte in the output process image: the runtime library takes the current output frame, replaces the byte at offset and commits it back as a versioned transaction (with bounded retries internally). offset must lie within the current output frame length; an out-of-range offset returns false.

It suits changing one command byte or flag. To change several consecutive bytes / the whole frame, commit once with WriteOutput() or SlavePDO::PatchOutputFrame(); do not call the single-byte write repeatedly, otherwise every cycle leaves an intermediate state behind.

Return value:

  • true — the byte was committed
  • false — the offset is out of range / there is no output mapping at present / the commit failed (conflict retries exhausted, for instance; you can retry later)

Example:

auto& slave = master.GetSlave(1);

if (!slave.WriteOutputByte(0, 0x01))
printf("单字节写失败(偏移越界或当前无输出映射)\n"); // Single-byte write failed (offset out of range or no output mapping right now)\n

SlavePdoAccess direct reads and mapping​

darra::ethercat::SlavePdoAccess is the older wrapper for process data access; its constructor takes (dll, mi, si) and it is not attached to the Slave object. New code should prefer the static function family of darra::SlavePDO (see PDO read/write); the entry points below are still available and can be used as before once you understand their lifetime.

#include "ethercat.hpp"

darra::ethercat::SlavePdoAccess pdo(dll, master.MasterNumber(), 1);
CategoryMethodReturn typeRead/writeDescription
PDO direct readReadInputDataDirect(buffer, offset, length)intread-onlyCopies length bytes from the start of the input snapshot to buffer + offset; returns the number of bytes copied, 0 on failure
InputSpan()std::pair<uint8_t*, int>read-onlyThread-local input snapshot (pointer, byte count); not the live image
OutputSpan()std::pair<uint8_t*, int>read-onlyThread-local output snapshot (pointer, byte count); not the live image
InputsMappingInfo()MappingInforead-onlyLive input image (pointer, byte count, slave index)
OutputsMappingInfo()MappingInforead/writeLive output image (pointer, byte count, slave index); writing to the pointer contents writes back
PDO mappingBindPdoStruct<T>(isInput)T*read/writeTreats the live image directly as structure T; read-only on the input side, and a write on the output side writes back
struct MappingInfo {
void* pointer; // live process image pointer
int size; // Byte count for this direction
uint16_t slave_index; // The station number passed to the constructor
};

ReadInputDataDirect(buffer, offset, length) — length must be given explicitly and be greater than 0; length <= 0 no longer means "the whole frame" and always returns 0 (the old semantics copied a whole frame into a buffer of unknown capacity, so a buffer that was too small was written out of bounds). offset is the offset in the destination buffer; the source data always starts at byte 0 of the input snapshot, not at the offset. The caller must ensure the buffer capacity >= offset + length. To read a whole frame safely, use SlavePDO::ReadInputDirect(dll, mi, si, buffer, bufferSize) (when the capacity is insufficient it copies no partial frame and returns 0).

InputSpan() / OutputSpan() — returns the (指针, 字节数) of a thread-local snapshot. The snapshot is reused and overwritten by the next call to the same function on the same thread, so copy it out if you need it longer; it is not the live process image, and what you read is not the bus value "at this instant". For the current value on a hot path use SlavePDO::InputsMapping<T> / OutputsMapping<T> or the live pointer.

InputsMappingInfo() / OutputsMappingInfo() — returns the pointer, byte count and slave index of the live process image. The pointer is owned by the master and stays valid across cycles (until the master rebuilds the process image or shuts down); read-only on the input side, and on the output side writing to the pointer contents writes back. An empty pointer or a size of 0 means there is no mapping at present (not in OP / no PDO in that direction).

BindPdoStruct<T>(isInput) — treats the live image directly as structure T. T must be trivially copyable and standard layout (a compile-time static_assert rejects types with virtual functions / reference members / non-trivial copy); nullptr is returned when the mapped byte count is smaller than sizeof(T) or the pointer is unavailable. The function does not check field alignment, so the structure must use #pragma pack(push, 1) / __attribute__((packed)) itself, otherwise the fields are misaligned.

The class's WriteOutputDataDirect() is deprecated and always returns 0 (permanently fail-closed); for a whole-frame write use SetOutputs() or SlavePDO::WriteOutputFrame(), and for a partial write use SlavePDO::PatchOutputFrame().

Example:

using namespace darra::ethercat;

#pragma pack(push, 1)
struct MyPdo { uint16_t status; int32_t position; };
#pragma pack(pop)

SlavePdoAccess pdo(dll, master.MasterNumber(), 1);

// Partial read: the source starts at byte 0 of the input snapshot, written to buf + 2, 4 bytes in total
uint8_t buf[6]{};
int n = pdo.ReadInputDataDirect(buf, 2, 4); // n == 4, the data lands in buf[2..5]

// Struct overlay: points straight at the live input image
if (MyPdo* p = pdo.BindPdoStruct<MyPdo>(true)) {
printf("status=%u pos=%d\n", (unsigned)p->status, (int)p->position);
}

// live output image: writing the pointer contents writes back
auto out = pdo.OutputsMappingInfo();
if (out.pointer && out.size >= (int)sizeof(MyPdo)) {
auto* cmd = static_cast<MyPdo*>(out.pointer);
cmd->status = 0x0001;
}

String representation​

auto& slave = master.GetSlave(1);
printf("%s\n", slave.ToString().c_str());
// Output: "Slave[1] MyDevice (0x00000002:0x03F03052)"

Complete example​

#include "ethercat.hpp"
using namespace darra;

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

auto& slave = master.GetSlave(1);

// Identity information
printf("VID=0x%08X PID=0x%08X\n", slave.VendorId(), slave.ProductId());
printf("名称: %s\n", slave.Name().c_str()); // Name: %s\n

// Watchdog
slave.SetWatchdog(100);

// State transition
slave.SetState(EcState::OP, 5000);

// Topology
printf("活动端口: 0x%02X, 父节点: %d\n", // Active port: 0x%02X, parent: %d\n
slave.ActivePorts(), slave.ParentStation());

return 0;
}