Skip to main content

FSoE functional safety

FSoE (Functional Safety over EtherCAT) adds a functional safety protocol layer on top of the standard PDO channel: the master maintains the safety connection state machine, the slave runs the safety logic, and safety data carries CRC and sequence number checks; the cyclic path is fail-closed. This is not a certified safety product, and it is not a PLC capability; the safety level actually reached is decided by the safety device and the overall safety concept.

Get the FSoE& reference through slave.GetFSoE(); manage multiple safety connections with SafetyManager.​

FSoE device detection

slave.GetFSoE() detects this automatically when the slave is initialized. The detection sequence:

  1. CoE prerequisite — the slave must support the CoE mailbox protocol
  2. 0xF980:01 check — try to read the device-level FSoE safety address over SDO; success confirms support
  3. 0x9001:02 check — if the previous step fails, try to read the MDP connection parameters (for multi-module safety devices)

Checking CoE support alone is not enough, because many non-safety devices (an ordinary servo drive, for example) also support CoE. An FSoE device must implement the specific safety object indexes to be recognized correctly.

Quick start​

FSoE workflow​

FSoE establishes an independent safety connection on the EtherCAT PDO channel. The master handles protocol management; the slave handles the safety logic.

State machine sequence:

  • Reset — initial state, waiting for the master to start a session
  • Session — session established, connection ID exchanged
  • Connection — connection established, safety address verified
  • Parameter — parameter download phase (SRA CRC check)
  • Data — normal safety data exchange
  • Failsafe — fail-safe, the slave outputs the safety values
Automatic state advancement

After Initialize() establishes the connection, the intermediate states (Session → Connection → Parameter) and the per-cycle data exchange are both advanced by the runtime PDO thread (the runtime calls the FSoE cycle handler once per cycle inside the PDO thread). The application layer must not call ProcessCycle() itself per cycle — advancing it twice makes the safety state machine take two steps per cycle.

Recommended approach

Use the code export feature of Darra EtherCAT Master Tools to generate the safety data structures and binding code.

Minimal example (digital safety I/O)​

// Safety data struct (exported by the Darra configuration tool)
#pragma pack(push, 1)
struct SafeDigitalInput // EL19xx: 2 bytes
{
uint8_t InputBits; // Safety input status bits (one bit per channel)
uint8_t DiagBits; // Input diagnostic state
};

struct SafeDigitalOutput // EL29xx: 1 byte
{
uint8_t OutputBits; // Safety output control bits
};
#pragma pack(pop)
auto& slave = master.GetSlave(1);  // Safety IO slave with FSoE
auto& fsoe = slave.GetFSoE();

// 1. Establish the FSoE connection (connectionId=0 auto-assigns, safetyAddress comes from the hardware DIP switches, watchdog 100 ms)
if (!fsoe.Initialize(/*connectionId*/ 0, /*safetyAddress*/ 0x0100, /*watchdogMs*/ 100)) {
printf("FSoE 初始化失败\n"); // FSoE initialization failed
return;
}

// 2. Poll status / errors (On* callbacks can be used instead, see the "event callbacks" section)
FSoEState st = fsoe.State();
if (st != FSoEState::Data) {
printf("FSoE 尚未进入 Data: 0x%03X\n", static_cast<int>(st)); // FSoE has not entered Data yet: 0x%03X
}
FSoEError err = fsoe.LastError();
if (err != FSoEError::None) {
printf("FSoE 错误: 0x%04X\n", static_cast<int>(err)); // FSoE error: 0x%04X
}

// 3. Safety data read/write: the runtime PDO thread refreshes the inputs / commits the outputs every cycle.
// The application reads and writes in its own control cycle; do not use master.Events().SetPDOCallbackSync
// drive FSoE (that is a latest-only ordinary notification and carries no same-cycle safety loop), and do not call ProcessCycle() again either.
while (running) {
auto inBytes = fsoe.ReadSafeInput(sizeof(SafeDigitalInput));
if (inBytes.size() == sizeof(SafeDigitalInput)) {
SafeDigitalInput input;
std::memcpy(&input, inBytes.data(), sizeof(input));

SafeDigitalOutput output{};
bool ch0 = (input.InputBits & 0x01) != 0;
output.OutputBits = ch0 ? 0x01 : 0x00;

fsoe.WriteSafeOutput(reinterpret_cast<const uint8_t*>(&output), sizeof(output));
}
std::this_thread::sleep_for(std::chrono::milliseconds(1));
}
PDO cycle timing

Safety inputs are refreshed by the runtime PDO thread every cycle, and safety outputs are committed by it every cycle; the C++ application layer takes no part, and there is no safety callback in step with PDO:

  • ReadSafeInput() returns the safety inputs the runtime has already refreshed
  • WriteSafeOutput() writes the output that will be committed in the next cycle

Neither is same-cycle synchronous. master.Events().SetPDOCallbackSync is an ordinary latest-only PDO notification; it does not carry the safety loop, so do not use it to drive FSoE.

How FSoE differs from ordinary PDO​

FSoE safety data cannot be mapped directly through a zero-copy pointer the way ordinary PDO data can. The reason is the difference at the protocol layer:

Comparison in use

Although the underlying mechanism differs, the call shape of Initialize() + ReadSafeInput() / WriteSafeOutput() is already close to reading and writing ordinary PDO byte by byte; the difference is that there is no same-cycle guarantee, and the runtime advances the cycle.

Ordinary PDO​

The data in the IOmap is the user data; a struct can be overlaid directly onto the memory pointer.

FSoE PDO​

The IOmap holds FSoE protocol frames; the user's safety data is wrapped inside the frame and has to pass the checks.

FSoE must therefore access safety data through ReadSafeInput() / WriteSafeOutput(). Do not read or write the IOmap directly, bypassing the SDK — that breaks the integrity of the safety protocol.

The C++ binding style

The C++ FSoE class does not provide template bindings inferred from a struct type; safety data is measured in bytes: call Initialize() to establish the connection, then use ReadSafeInput(size) / WriteSafeOutput(data, size) to read and write the safety frame buffer (the runtime advances the cycle; the application does not call ProcessCycle()). For multi-connection scenarios use SafetyManager (header slave/fsoe.hpp); its BindSafeInput() / BindSafeOutput() / BindSafeIO() / BindMdpSafeInput() / BindMdpSafeOutput() / BindMdpDriveAxis() are all non-template and take slaveIndex / safetyAddress / byte size / module number / axis number. See FSoE manager below.

Capability check​

auto& fsoe = master.GetSlave(1).GetFSoE();
if (!fsoe.IsCapable()) {
printf("从站不支持 FSoE\n"); // Slave does not support FSoE
return;
}

Method overview​

CategoryMethodTypeRead/writeDescription
Capability (FSoE)IsCapableboolReadWhether the slave supports FSoE
Connection management (FSoE)InitializeboolWriteEstablishes the safety connection; pass connectionId 0 to have the runtime allocate one
Connection management (FSoE)IsInitializedboolReadWhether it is initialized
Connection management (FSoE)CloseboolWriteCloses the connection; on failure returns false and keeps the initialized state so it can be retried
Connection management (FSoE)CloseFailureCountuint32_tReadCumulative number of close failures
Connection management (FSoE)LastCloseFailedboolReadWhether the most recent Close failed
Safety data (FSoE)ReadSafeInputstd::vector<uint8_t>ReadReads the safety inputs; an empty vector = read failure
Safety data (FSoE)WriteSafeOutputboolWriteWrites the safety outputs; committed in the next cycle
Safety data (FSoE)SetFailsafeOutputboolWritePresets the output values used when entering fail-safe
State query (FSoE)StateFSoEStateReadCurrent state; a failed read collapses to Reset, so check StatusValid alongside it
State query (FSoE)StateOrNullstd::optional<FSoEState>ReadThree-valued state; nullopt = cannot read
State query (FSoE)GetStatusstd::optional<FSoEStatus>ReadStatus snapshot; nullopt = cannot read
State query (FSoE)ConnectionStatusFSoEConnectionStatusReadFull connection status; on a failed read the fields hold default values
State query (FSoE)ConnectionStatusOrNullstd::optional<FSoEConnectionStatus>ReadThree-valued full connection status; nullopt = cannot read
State query (FSoE)StatusValidboolReadWhether the most recent status read was valid
State query (FSoE)IsConnectedboolReadWhether a valid connection exists (same as StatusValid)
State query (FSoE)InFailsafeboolReadWhether it is in fail-safe; a failed read returns false, which must not be taken at face value
State query (FSoE)InFailsafeOrNullstd::optional<bool>ReadThree-valued fail-safe; nullopt = cannot read
Diagnostics (FSoE)WatchdogExpiredboolReadWhether the watchdog error count is greater than 0; a failed read returns false, which must not be taken at face value
Diagnostics (FSoE)WatchdogExpiredOrNullstd::optional<bool>Readnullopt = not read; true = the watchdog error count is greater than 0; false = this read succeeded and the count is 0
Diagnostics (FSoE)CrcErrorCountuint32_tReadCRC error count
Diagnostics (FSoE)FramesSentuint32_tReadFrames sent; a three-valued FramesSentOrNull version also exists
Diagnostics (FSoE)FramesReceiveduint32_tReadValid frames received; a three-valued FramesReceivedOrNull version also exists
Diagnostics (FSoE)LastErrorFSoEErrorReadThe last error code
Diagnostics (FSoE)GetLastErrorFSoEErrorReadThe last error code (same as LastError)
Diagnostics (FSoE)ClearErrorvoidWriteClears the error
Diagnostics (FSoE)GetFailsafeReasonFSoEFailsafeReasonReadInfers the fail-safe reason from the last error code
Connection info (FSoE)SafetyAddressuint16_tReadSafety address (the value used at initialization)
Connection info (FSoE)ConnectionIduint16_tReadConnection ID (the value actually allocated when it was generated automatically)
Connection info (FSoE)SafeInputSizeintReadSafety input data size (bytes)
State control (FSoE)RequestStateboolWriteRequests a transition to the target safety state. A rejected request returns false, which does not mean the state has been entered
State control (FSoE)EnterFailsafeboolWriteActively enters fail-safe; the slave outputs switch to the safety values
State control (FSoE)ResetboolWriteResets the safety connection; the state machine restarts the handshake from Reset
State control (FSoE)fsoe_is_valid_state_transitionintReadQueries whether a state transition is allowed
Watchdog (FSoE)CheckWatchdogboolReadChecks the watchdog state
Watchdog (FSoE)GetWatchdogStatusboolReadChecks the watchdog state (same as CheckWatchdog)
Watchdog (FSoE)ConfigureWatchdog / SetWatchdogboolWriteAlways returns false: the watchdog timeout is configured only in Initialize
Watchdog (FSoE)ResetWatchdogboolWriteCurrently equivalent to Reset() (resets the whole connection)
Parameters (FSoE)DownloadParametersstd::optional<uint32_t>WriteDownloads safety parameters in the Parameter state and returns the SRA CRC32
Parameters (FSoE)GetFailsafeParametersstd::vector<uint8_t>ReadCurrently the same semantics as ReadSafeInput
Parameters (FSoE)SetFailsafeParametersboolWriteCurrently the same semantics as WriteSafeOutput
ConnID (FSoE)FSoE.IsConnectionIdAvailableboolReadChecks whether a connection ID is available (a value other than 0)
Cycle (FSoE)ProcessCyclevoidWriteAdvances the cycle; the runtime PDO thread already does this, so the application must not call it again
Callback (FSoE)OnStateChanged / OnError / OnFailsafestd::functionWriteEvent callback members; ProcessCycle dispatches them after comparing each cycle, see the event callbacks section
MDP connection (FSoE)MdpInitConnection / MdpCloseConnectionboolWriteEstablishes / closes the MDP connection of the given module
MDP connection (FSoE)MdpRequestState / MdpResetboolWriteState transition / reset for the given connection
MDP data (FSoE)MdpReadSafeInputstd::vector<uint8_t>ReadReads the safety inputs of the given connection; an empty vector = read failure
MDP data (FSoE)MdpWriteSafeOutputboolWriteWrites the safety outputs of the given connection
MDP data (FSoE)MdpSetFailsafeOutputboolWritePresets the fail-safe outputs of the given connection
MDP data (FSoE)MdpDownloadParametersstd::optional<uint32_t>WriteDownloads safety parameters for the given connection
MDP diagnostics (FSoE)MdpGetStateintReadState code of the given connection (a FSoEState value)
MDP diagnostics (FSoE)MdpGetStatusstd::optional<FSoEConnectionStatus>ReadFull state of the given connection
MDP diagnostics (FSoE)MdpCheckWatchdogboolReadWatchdog check for the given connection
MDP diagnostics (FSoE)MdpGetLastError / MdpClearErrorFSoEError / voidRead/writeError read / clear for the given connection
MDP query (FSoE)MdpGetSlaveConnectionCount / MdpDetectConnectionsuint16_tReadNumber of FSoE connections on the slave
MDP query (FSoE)MdpGetDeviceAddressstd::optional<uint16_t>ReadDevice-level safety address (0xF980:01)
MDP query (FSoE)MdpGetModuleCommParamstd::vector<uint8_t>ReadCommunication parameters of the given module (0x9nn1)
MDP query (FSoE)MdpGetModuleDiagnosisstd::optional<SafeModuleDiag>ReadDiagnostics of the given module (0xAnn0)
Binding (SafetyManager)BindSafeIOboolWriteBinds safety inputs and safety outputs in one call, with their own offsets and byte counts, and establishes one connection
Binding (SafetyManager)BindSafeInputboolWriteBinds safety inputs only, with an output size of 0; for devices with safety inputs only
Binding (SafetyManager)BindSafeOutputboolWriteBinds safety outputs only, with an input size of 0; for devices with safety outputs only
Binding (SafetyManager)BindMdpSafeInput / BindMdpSafeOutputboolWriteMDP version of the binding; establishes the connection by module number
Binding (SafetyManager)BindMdpDriveAxisboolWriteMDP drive-axis binding; carries no safety data size, see the entry below
Manager (SafetyManager)AddConnection / GetConnectionFSoE&Read/writeAdds / accesses a connection
Manager (SafetyManager)ConnectionCountsize_tReadNumber of connections
Manager (SafetyManager)InitializeAllboolWriteInitializes all connections
Manager (SafetyManager)CloseAllboolWriteCloses all connections; entries that fail stay in the table and can be retried
Manager (SafetyManager)SafetyManager.CloseAllFailureCountuint32_tReadProcess-level: cumulative number of connections that CloseAll did not close successfully
Manager (SafetyManager)AllInDataStateboolReadWhether every connection is in the Data state
Manager (SafetyManager)AnyInFailsafeboolReadWhether any connection is in fail-safe; a failed read returns false, which must not be taken at face value
Manager (SafetyManager)AnyInFailsafeOrNullstd::optional<bool>ReadThree-valued; if any connection read fails = nullopt
Manager (SafetyManager)GetDiagnosticsstd::vector<SafeModuleDiag>ReadDiagnostics summary for all connections
Manager (SafetyManager)FindByAddress / FindConnectionByAddressFSoE*ReadFinds a connection by safety address
Manager (SafetyManager)FindByConnectionIdFSoE*ReadFinds a connection by connection ID
Manager (SafetyManager)ReadInputFramestd::vector<uint8_t>ReadReads the raw safety input frame of the given connection
Manager (SafetyManager)WriteOutputFrameboolWriteWrites the raw safety output frame of the given connection
Manager (SafetyManager)GetStatusSummarystd::stringReadStatus summary string
Manager (SafetyManager)ProcessCyclevoidWriteAdvances the cycle; the runtime PDO thread already does this, so the application must not call it again
CRC (FSoECrc16)fsoe_crc16uint16_tReadFSoE CRC-16 computation, with a custom initial value for continued calculation
CRC (FSoECrc16)FSoECrc16.ComputeWithConnectionIduint16_tReadCRC-16 with the ConnID prefix
PDO frame (FSoEPdoFrame)ToBytes / FromBytesstd::vector<uint8_t> / FSoEPdoFrameRead/writeFSoE PDO frame serialization / parsing
PDO frame (FSoEPdoFrame)ValidateCrcSegmentsboolReadVerifies every CRC segment in the frame
PDO frame (FSoEPdoLayout)Validate / ComputeSegmentCountvoid / uint16_tReadLayout self-consistency check / theoretical CRC segment count
FSoEState enumeration
enum class FSoEState : int {
Reset = 0x100, // Initial/reset state
Session = 0x101, // Session established
Connection = 0x102, // Connection established
Parameter = 0x103, // Parameter download
Data = 0x104, // Data exchange (normal operation)
Failsafe = 0x105 // Fail-safe
};
FSoEError enumeration
enum class FSoEError : int {
None = 0x0000, // No error
WrongCommand = 0x0001, // Wrong command
UnknownCommand = 0x0002, // Unknown command
WrongConnectionId = 0x0003, // Connection ID mismatch
CrcError = 0x0004, // CRC check failed
Watchdog = 0x0005, // Watchdog timeout
WrongAddress = 0x0006, // Wrong FSoE address
WrongData = 0x0007, // Invalid data
CommParamLength = 0x0008, // Wrong communication parameter length
CommParam = 0x0009, // Communication parameter error
AppParamLength = 0x000A, // Wrong application parameter length
AppParam = 0x000B, // Application parameter error
UnexpectedSession = 0x000C, // Unexpected session command
FailsafeData = 0x000D, // Fail-safe data received
NotInitialized = 0x0100, // FSoE not initialised (internal error)
MaxConnections = 0x0101, // Maximum connection count reached (internal error)
InvalidStateTransition = 0x0102 // Invalid state transition (internal error)
};
FSoEConnectionStatus
FieldTypeDescription
StateFSoEStateCurrent FSoE state
LastErrorFSoEErrorLast error code
ErrorCountuint32_tTotal error count
FramesSentuint32_tFrames sent
FramesReceiveduint32_tValid frames received
CrcErrorsuint32_tCRC error count
WatchdogErrorsuint32_tWatchdog timeout count
WatchdogExpiredboolWhether the watchdog has expired
InFailsafeboolWhether it is in fail-safe mode
ToggleBituint8_tCurrent toggle bit value
IsInitializedboolWhether the connection is initialized
FSoEConnectionConfig
FieldTypeDescription
ConnectionIduint16_tUnique connection identifier
SafetyAddressuint16_tFSoE slave safety address (set by the DIP switch)
WatchdogTimeMsuint32_tWatchdog timeout (ms), default 100
SafeInputSizeuint16_tSafety input data size (bytes), determined by the device
SafeOutputSizeuint16_tSafety output data size (bytes), determined by the device
PdoInputOffsetuint32_tInput offset in the IOmap (usually slave.Ioffset())
PdoOutputOffsetuint32_tOutput offset in the IOmap (usually slave.Ooffset())
FSoEFailsafeReason enumeration
enum class FSoEFailsafeReason {
WatchdogTimeout, // Watchdog timeout
CrcError, // CRC error
CommunicationError, // Communication error
ApplicationRequest, // Application request
SlaveRequest, // Slave request
MasterRequest, // Master request
RecoveryToData // Return to data mode
};
FSoEStatus
FieldTypeDescription
Stateuint8_tCurrent state code (a FSoEState value)
FailsafeActiveboolWhether it is in fail-safe mode
CrcErrorsuint32_tCRC error count
WatchdogErrorsuint32_tWatchdog timeout count
FSoECommand enumeration
enum class FSoECommand : uint8_t {
Reset = 0x2A, // Reset command
Session = 0x4E, // Session request/response
Connection = 0x64, // Connection request/response
Parameter = 0x52, // Parameter download
Failsafe = 0x08, // Fail-safe mode
Data = 0x36 // Normal data exchange
};
FSoEConnectionMode enumeration
enum class FSoEConnectionMode {
Single, // Single-connection mode - all modules share one FSoE connection and safety address
Multiple // Multi-connection mode - each module has its own FSoE connection and safety address
};
FSoEConnectionType enumeration
enum class FSoEConnectionType : uint16_t {
Master = 0, // FSoE master connection
Slave = 1 // FSoE slave connection
};
SafeModuleProfile enumeration
enum class SafeModuleProfile : uint16_t {
DigitalInput = 190, // FSoE Digital Input
DigitalInOut = 195, // FSoE Digital In-/Output
DigitalOutput = 290, // FSoE Digital Output
DriveConnection = 790, // FSoE MDP Drive Connection
Master = 6900 // FSoE Master
};
FSoECommParameters
FieldTypeDescription
ConnectionIduint16_tConnection ID (SI3)
SafetyAddressuint16_tSafety address (SI2)
WatchdogTimeMsuint32_tWatchdog timeout (ms) (SI4)
CommParamLengthuint16_tCommunication parameter length (SI7)
AppParamLengthuint16_tApplication parameter length (SI8)
Versionstd::stringVersion (SI1), default 01
ConnectionTypeuint16_tConnection type (SI6): 0=Master, 1=Slave
SafeModuleDiag
FieldTypeDescription
ModuleIndexuint16_tModule index
StateFSoEStateModule FSoE state
CrcErrorsuint32_tCRC error count
WatchdogErrorsuint32_tWatchdog timeout count
InFailsafeboolWhether it is in fail-safe
StatusValidboolWhether this read was valid; when false the fields above are the defaults of a failed read and must not be treated as safe
SafeModuleInfo
FieldTypeDescription
ModuleIndexuint16_tModule index
ModuleProfileuint16_tModule profile (a SafeModuleProfile value)
SafeInputSizeuint16_tSafety input bytes
SafeOutputSizeuint16_tSafety output bytes
ConnectionIduint16_tConnection ID
SafetyAddressuint16_tSafety address
Namestd::stringModule name
SafeMdpConfig
FieldTypeDescription
ConnectionIduint16_tConnection ID; 0 = allocated by the runtime
SafetyAddressuint16_tSafety address
WatchdogTimeMsuint32_tWatchdog timeout (ms), default 10
SafeInputSizeuint16_tSafety input data size (bytes)
SafeOutputSizeuint16_tSafety output data size (bytes)
PdoInputOffsetuint32_tByte offset of the safety data in the input PDO
PdoOutputOffsetuint32_tByte offset of the safety data in the output PDO

Safety data structures​

Recommended approach

Use the code export feature of Darra EtherCAT Master Tools to generate the safety data structures and binding code. The exported result contains the correct struct sizes, field layout and FSoE binding calls, so you avoid the mistakes of defining them by hand.

Struct definitions​

Safety data structure example:

#pragma pack(push, 1)

// EL19xx digital safety input (2 bytes of safety data)
struct SafeDigitalInput {
uint8_t InputBits; // Safety input status bits (one bit per channel)
uint8_t DiagBits; // Input diagnostic state
};

// EL29xx digital safety output (1 byte of safety data)
struct SafeDigitalOutput {
uint8_t OutputBits; // Safety output control bits
};

// ETG.6100 safety drive input (10 bytes of safety data)
struct SafeDriveInput {
uint16_t SafetyStatusWord; // Safety status word
int32_t SafeActualPosition; // Safe actual position
int32_t SafeActualVelocity; // Safe actual velocity
};

// ETG.6100 safety drive output (2 bytes of safety data)
struct SafeDriveOutput {
uint16_t SafetyControlWord; // Safety control word
};

// Safety encoder input (6 bytes of safety data)
struct SafeEncoderInput {
uint32_t SafePosition; // Safety position value
uint16_t StatusWord; // Status word
};

#pragma pack(pop)
Struct sizes must match

SafeInputSize / SafeOutputSize must match sizeof(T), otherwise reads and writes fail.

State control​

RequestState()​

bool RequestState(FSoEState targetState) const;

Requests an FSoE state transition. A rejected request returns false, which does not mean the state has been entered.

Parameters:

Returns:

  • bool — true if the request is accepted; false if the transition is not legal, the connection is not initialized, or the runtime is not ready
State machine rules

Transitions must follow the state machine rules (see fsoe_is_valid_state_transition()): RESET→SESSION; SESSION→CONNECTION or RESET; CONNECTION→PARAMETER or RESET; PARAMETER→DATA or RESET; DATA→FAILSAFE (the only one; a direct transition to RESET is not allowed); FAILSAFE→DATA or RESET.

Example:

if (!fsoe.RequestState(FSoEState::Data)) {
printf("请求进入 Data 被拒\n"); // Request to enter Data was refused
}

fsoe_is_valid_state_transition()​

int fsoe_is_valid_state_transition(FSoEState from, FSoEState to);

Queries whether one state transition is allowed (a free function in the darra:: namespace); use it for a self-check before calling RequestState().

Parameters:

Returns:

  • int — 1 = allowed; 0 = a valid state but the transition is not allowed; -1 = missing argument or the entry point is unavailable; -5 (EC_FSOE_ERR_STATE) = the state value is outside 0x100..0x105

EnterFailsafe()​

bool EnterFailsafe() const;

Actively enters fail-safe mode. The slave outputs the safety values (preset by SetFailsafeOutput).

Returns:

  • bool — true if the request is accepted; false if the connection is not initialized or the runtime is not ready

Reset()​

bool Reset() const;

Resets the FSoE connection to the initial state and restarts the state machine handshake. A triggered fail-safe does not recover automatically; after removing the fault source, use this to rebuild the connection.

Returns:

  • bool — true if the reset request succeeded; false on failure

Connection management​

IsCapable()​

bool IsCapable() const;

Whether the slave supports FSoE.

Returns:

  • bool — true if supported; false if it is not supported or the runtime is not ready

Initialize()​

bool Initialize(uint16_t connectionId, uint16_t safetyAddress,
uint32_t watchdogMs = 10);

bool Initialize(const FSoEConnectionConfig& config);

Initializes the FSoE connection. Only one connection is kept per slave: calling Initialize() again on an already initialized slave does not update the data sizes of the existing connection, yet returns success; the safety input and output sizes must both be supplied when the connection is established (use BindSafeIO() or fill in FSoEConnectionConfig).

Parameters:

  • connectionId (uint16_t) — connection ID (unique under one master); pass 0 = allocated by the runtime, read the actual value back with ConnectionId()
  • safetyAddress (uint16_t) — slave safety address (hardware DIP switch)
  • watchdogMs (uint32_t) — watchdog timeout (ms); the three-argument version defaults to 10
  • config (FSoEConnectionConfig) — full configuration; the struct defaults WatchdogTimeMs = 100, which differs from the three-argument default, so pass an explicit value when the behaviour has to be certain

Returns:

  • bool — true if the connection is established; false if it is not (runtime not ready, slave does not support FSoE, or the configuration was rejected)

IsInitialized()​

bool IsInitialized() const;

Whether the connection is initialized.

Returns:

  • bool — true if initialized

Close()​

bool Close();

Closes the FSoE connection. On failure the initialized state is kept and the call can be retried directly; the SafetyManager destructor closes all connections automatically.

Returns:

  • bool — true = close confirmed / it was not initialized anyway; false = close failed (can be retried)

CloseFailureCount()​

uint32_t CloseFailureCount() const;

Cumulative number of close failures (0 = never failed).

Returns:

  • uint32_t — cumulative number of close failures

LastCloseFailed()​

bool LastCloseFailed() const;

Whether the most recent Close() failed (sticky; the next successful Close() clears it).

Returns:

  • bool — true if the most recent close failed

Parameters and configuration​

DownloadParameters()​

std::optional<uint32_t> DownloadParameters(const uint8_t* data, uint32_t size) const;

Downloads the safety parameters. Returns the SRA CRC32 check value.

note

Callable only in the Parameter state. The parameter content is generated by the safety configuration tool.

Parameters:

  • data (const uint8_t*) — parameter data
  • size (uint32_t) — data size

Returns:

  • std::optional<uint32_t> — the SRA CRC32 on success; std::nullopt on failure (not in the Parameter state, the connection is not initialized, or the runtime is not ready)

SetFailsafeOutput()​

bool SetFailsafeOutput(const uint8_t* data, uint32_t size) const;

Presets the output values used for fail-safe. When FSoE enters the Failsafe state, the slave switches to these values automatically.

Parameters:

  • data (const uint8_t*) — safety output data
  • size (uint32_t) — data size (bytes)

Returns:

  • bool — true on success; false on failure (the connection is not initialized or the runtime is not ready)

Example:

// All outputs are switched off in the fail-safe state
uint8_t failsafe[] = {0x00};
fsoe.SetFailsafeOutput(failsafe, sizeof(failsafe));

// Or use the struct
SafeDriveOutput fs{};
fs.SafetyControlWord |= 0x0001; // Request STO (Safe Torque Off)
fsoe.SetFailsafeOutput(reinterpret_cast<const uint8_t*>(&fs), sizeof(fs));

GetFailsafeParameters() / SetFailsafeParameters()​

std::vector<uint8_t> GetFailsafeParameters(int size) const;
bool SetFailsafeParameters(const uint8_t* data, int size) const;

Fail-safe parameter read and write. Currently the same semantics as the safety data accessors (equivalent to ReadSafeInput() / WriteSafeOutput() respectively); to actually deliver safety parameters use DownloadParameters().

Parameters:

  • size (int) — number of bytes to read
  • data (const uint8_t*) — data buffer
  • size (int) — data size (bytes)

Returns:

  • std::vector<uint8_t> — the read result; an empty vector = read failure
  • bool — true on a successful write

Safety I/O data​

ReadSafeInput()​

std::vector<uint8_t> ReadSafeInput(int size) const;

Reads safety input data. What it returns is the safety input most recently refreshed by the runtime PDO thread (not same-cycle synchronous).

Parameters:

  • size (int) — maximum number of bytes to read

Returns:

  • std::vector<uint8_t> — the safety input data, with the length actually read (no more than requested); an empty vector = read failure (or 0 bytes requested)

WriteSafeOutput()​

bool WriteSafeOutput(const uint8_t* data, int size) const;

Writes safety output data, which the runtime PDO thread commits in the next cycle.

Parameters:

  • data (const uint8_t*) — safety output data
  • size (int) — data size (bytes)

Returns:

  • bool — true on success; false on failure (the connection is not initialized or the runtime is not ready)

Example:

auto& fsoe = master.GetSlave(1).GetFSoE();

// Read the safety inputs
auto input = fsoe.ReadSafeInput(2);
if (!input.empty()) {
bool ch0 = (input[0] & 0x01) != 0;
printf("安全输入 CH0: %s\n", ch0 ? "高" : "低"); // Safety input CH0: %s (high / low)
}

// Write safety outputs
uint8_t output[] = {0x01};
fsoe.WriteSafeOutput(output, sizeof(output));

State queries​

A failed read must not pass as safe

When a status read fails, convenience accessors such as State() / InFailsafe() / WatchdogExpired() return the "cannot read" defaults (Reset / false / 0), which must not be taken as a measured safety conclusion. Either check StatusValid() first to see whether this read was valid, or switch to the three-valued *OrNull() version (nullopt = cannot read). A safety diagnostics screen must show "unknown / read failure" rather than treat the default as safe.

State() / StateOrNull()​

FSoEState State() const;
std::optional<FSoEState> StateOrNull() const;

Current FSoE state. On a failed read, State() collapses to FSoEState::Reset, which must not be passed off as "really in Reset".

Returns:

  • FSoEState — current state
  • std::optional<FSoEState> — current state; nullopt = cannot read (StateOrNull())

GetStatus()​

std::optional<FSoEStatus> GetStatus() const;

Reads the status snapshot (the older status struct).

Returns:

  • std::optional<FSoEStatus> — status snapshot; nullopt = cannot read

ConnectionStatus() / ConnectionStatusOrNull()​

FSoEConnectionStatus ConnectionStatus() const;
std::optional<FSoEConnectionStatus> ConnectionStatusOrNull() const;

Gets the full connection status (state, errors, sent and received frame counts, CRC / watchdog counts, toggle bit and so on; fields in FSoEConnectionStatus). The counter and error fields come from the same snapshot.

Returns:

  • FSoEConnectionStatus — full connection status; on a failed read each field holds its default value and must not be passed off as safe
  • std::optional<FSoEConnectionStatus> — full connection status; nullopt = cannot read (ConnectionStatusOrNull())

StatusValid() / IsConnected()​

bool StatusValid() const;
bool IsConnected() const;

Whether the most recent status read really obtained a valid connection status (the two are the same; IsConnected() is the name that reads naturally in a UI). false = no connection / read failure / runtime not ready, and the default values returned by all the convenience accessors cannot be trusted then.

Returns:

  • bool — true if a valid status was read

InFailsafe() / InFailsafeOrNull()​

bool InFailsafe() const;
std::optional<bool> InFailsafeOrNull() const;

Whether it is in fail-safe mode.

Returns:

  • bool — true for fail-safe; a false from a failed read means "cannot read", not a confirmed non-fail-safe
  • std::optional<bool> — true = fail-safe; false = confirmed not in fail-safe; nullopt = cannot read

WatchdogExpired() / WatchdogExpiredOrNull()​

bool WatchdogExpired() const;
std::optional<bool> WatchdogExpiredOrNull() const;

Whether the watchdog error count is greater than 0 (not "timing out right now"). When the read fails, the false returned by WatchdogExpired() means "cannot read", not that the watchdog is fine.

Returns:

  • bool — true if the watchdog error count is greater than 0
  • std::optional<bool> — nullopt = not read; true = the watchdog error count is greater than 0; false = this read succeeded and the count is 0

CrcErrorCount()​

uint32_t CrcErrorCount() const;

CRC error count. A 0 returned by a failed read means "cannot read", not "there really was no error".

Returns:

  • uint32_t — cumulative CRC error count

FramesSent() / FramesReceived()​

uint32_t FramesSent() const;
std::optional<uint32_t> FramesSentOrNull() const;
uint32_t FramesReceived() const;
std::optional<uint32_t> FramesReceivedOrNull() const;

Frames sent / valid frames received (cumulative). A 0 returned by a failed read means "cannot read", not "not a single frame was sent / received"; when the difference matters, use the OrNull version.

Returns:

  • uint32_t — cumulative frame count
  • std::optional<uint32_t> — cumulative frame count; nullopt = cannot read (the *OrNull() version)

LastError() / GetLastError()​

FSoEError LastError() const;
FSoEError GetLastError() const;

The last error code (the two are the same).

Returns:

  • FSoEError — the last error code; returns FSoEError::None when the runtime is not ready

SafetyAddress() / ConnectionId() / SafeInputSize()​

uint16_t SafetyAddress() const;
uint16_t ConnectionId() const;
int SafeInputSize() const;

The values cached at initialization: safety address, connection ID (when connectionId 0 requested automatic allocation, this is the value actually allocated), safety input data size (bytes).

Returns:

  • uint16_t — safety address / connection ID
  • int — safety input data size (bytes)

Example:

auto& fsoe = master.GetSlave(1).GetFSoE();

FSoEState state = fsoe.State();
bool failsafe = fsoe.InFailsafe();
uint32_t crc_errors = fsoe.CrcErrorCount();
FSoEError err = fsoe.LastError();

FSoEConnectionStatus cs = fsoe.ConnectionStatus();
printf("状态=%d, CRC错误=%u, 失效安全=%s\n", // State=%d, CRC errors=%u, failsafe=%s
static_cast<int>(cs.State), cs.CrcErrors,
cs.InFailsafe ? "是" : "否");

auto status = fsoe.GetStatus(); // std::optional<FSoEStatus>
if (status) {
printf("状态: %d\n", status->State); // State: %d
printf("失效安全: %s\n", status->FailsafeActive ? "是" : "否"); // Failsafe: %s (yes / no)
printf("CRC 错误: %u\n", status->CrcErrors); // CRC errors: %u
printf("看门狗错误: %u\n", status->WatchdogErrors); // Watchdog errors: %u
}

Diagnostics​

ClearError()​

void ClearError() const;

Clears the FSoE error. Once cleared you can try to re-establish the connection.

GetFailsafeReason()​

FSoEFailsafeReason GetFailsafeReason() const;

Gets the reason the fail-safe was triggered. It is inferred from the last error code: watchdog error → WatchdogTimeout; CRC error → CrcError; command / address / data / communication parameter errors → CommunicationError; everything else → ApplicationRequest.

Returns:

Watchdog​

CheckWatchdog() / GetWatchdogStatus()​

bool CheckWatchdog() const;
bool GetWatchdogStatus() const;

Checks the watchdog state (the two are the same).

Returns:

  • bool — the watchdog state query result

ConfigureWatchdog() / SetWatchdog()​

bool ConfigureWatchdog(uint32_t timeoutMs) const;
bool SetWatchdog(uint32_t timeoutMs) const;

The watchdog timeout is configured only in Initialize() and cannot be changed separately at runtime, so both always return false (the entry points are kept for source compatibility only).

Parameters:

  • timeoutMs (uint32_t) — watchdog timeout (ms); does not take part in any computation

Returns:

  • bool — always false

ResetWatchdog()​

bool ResetWatchdog() const;

Resets the watchdog. Currently equivalent to Reset() (resets the whole safety connection); it does not reset only the watchdog timer.

Returns:

  • bool — the same as Reset()

Cycle processing​

ProcessCycle()​

void ProcessCycle() const;

Advances one FSoE cycle (read inputs → advance the state machine → build outputs). The runtime PDO thread already calls it once per cycle, so the application layer must not call it again while the runtime PDO is running (advancing twice takes two steps per cycle). Only an integration that does not use the runtime PDO thread at all and drives the bus itself needs to call it manually, and then it must be called exactly once per cycle. SafetyManager::ProcessCycle() does the same for every connection in the manager.

Thread safety

FSoE and SafetyManager instances do not lock internally: write-type operations on the same instance (Initialize() / Close() / Reset() / RequestState() / Bind*() and so on) and reads must be serialized by the caller; do not call them concurrently across threads. The state read methods are const and can be polled from the control thread, but each read is an independent snapshot.

Event callbacks​

auto& fsoe = master.GetSlave(1).GetFSoE();

// The three callbacks are public std::function members; just assign to them (there is no On*() registration method).
// Dispatched by ProcessCycle() after comparing state/error every cycle - see the dispatch rules at the end of this section.
fsoe.OnStateChanged = [](FSoEState oldState, FSoEState newState) {
printf("FSoE 状态: %d -> %d\n", // FSoE state: %d -> %d
static_cast<int>(oldState), static_cast<int>(newState));
};

fsoe.OnError = [](FSoEError error) {
printf("FSoE 错误: 0x%04X\n", static_cast<int>(error)); // FSoE error: 0x%04X
};

fsoe.OnFailsafe = [](FSoEFailsafeReason reason) {
printf("FSoE 失效安全触发\n"); // FSoE failsafe triggered
};

Callback members:

CategoryMethodTypeRead/writeDescription
Callback (FSoE)OnStateChangedstd::function<void(FSoEState, FSoEState)>WriteState change
Callback (FSoE)OnErrorstd::function<void(FSoEError)>WriteError code change (non-None)
Callback (FSoE)OnFailsafestd::function<void(FSoEFailsafeReason)>WriteEntering fail-safe / recovery to Data

CheckAndRaiseEvents()​

void CheckAndRaiseEvents() const;

Dispatches the event callbacks from the current connection state and error code. ProcessCycle() calls it automatically once per cycle; an integration that drives the bus itself can also drive it separately (for example, comparing the state once on demand in a business thread), but it only reads state and does not advance the protocol — calling it on its own will not move the connection forward.

Behaviour:

  • Returns immediately when Initialize() has not been called; reads one state snapshot only and does not advance the protocol
  • The first observation only establishes the baseline; after that it compares and fires OnStateChanged / OnFailsafe / OnError per the dispatch rules below
  • A failed state read returns immediately without firing events and without changing the baseline — a failed read is not a state transition
  • Any exception thrown by a callback is swallowed and logged as a Warning; it never feeds back into cycle processing

Threading and reentrancy: The method itself is const; the dispatch baseline is observation cache rather than connection state. ProcessCycle() has already called it once, so calling it again within the same cycle sees no state change and dispatches nothing; do not call it in parallel with ProcessCycle(), because concurrent baseline updates on the same instance have no lock protection.

Dispatch rules

The three callbacks are dispatched by CheckAndRaiseEvents() inside ProcessCycle() after the state is read back each cycle:

  • The first observation only establishes the baseline; the "first state after power-up" is not counted as a transition;
  • State change → OnStateChanged(old, new);
  • Entering Failsafe (it was not Failsafe before) → OnFailsafe(原因由错误码推定);
  • Failsafe → Data → OnFailsafe(RecoveryToData);
  • Error code change and not None → OnError(error);
  • Failed state read = no event fired and no baseline change (a failed read is not a state transition).

Exceptions thrown by callbacks are always swallowed and logged; they never feed back into cycle processing. When you need to query actively, you can still poll fsoe.State() / StateOrNull() / ConnectionStatus() / LastError() / GetFailsafeReason().

OnSafeDataUpdated has been removed: the SDK provides no safety data update event, and there is no trigger source for one; read safety data with ReadSafeInput() each cycle, or watch the state transitions (the Data state means safety data is being exchanged).

MDP multi-connection mode​

An MDP device (a safety I/O coupler, a multi-axis drive and so on) contains several safety modules. Multi-connection mode creates an independent FSoE connection for each module, and each connection has its own state machine, watchdog and safety data buffer.

Which one to use
  • Single connection — simple devices, single-axis drives; establish one connection directly with slave.GetFSoE()
  • Multiple connections — when modules need independent monitoring / recovery (for example each axis of a multi-axis drive with its own safety connection), add connections one by one with SafetyManager

MdpInitConnection() / MdpCloseConnection()​

bool MdpInitConnection(uint16_t connIndex, const SafeMdpConfig& cfg) const;
bool MdpCloseConnection(uint16_t connIndex) const;

Establishes / closes the MDP connection of the given module.

Parameters:

  • connIndex (uint16_t) — connection (module) index
  • cfg (SafeMdpConfig) — connection configuration; pass ConnectionId 0 to have the runtime allocate one

Returns:

  • bool — true on success; false on failure (the runtime is not ready or the configuration was rejected)

MdpGetState() / MdpGetStatus()​

int MdpGetState(uint16_t connIndex) const;
std::optional<FSoEConnectionStatus> MdpGetStatus(uint16_t connIndex) const;

Reads the state / full state of the given connection.

Parameters:

  • connIndex (uint16_t) — connection (module) index

Returns:

  • int — state code (a FSoEState value)
  • std::optional<FSoEConnectionStatus> — full state; nullopt = cannot read

MdpReadSafeInput() / MdpWriteSafeOutput()​

std::vector<uint8_t> MdpReadSafeInput(uint16_t connIndex, int size) const;
bool MdpWriteSafeOutput(uint16_t connIndex, const uint8_t* data, int size) const;

Reads / writes the safety data of the given connection.

Parameters:

  • connIndex (uint16_t) — connection (module) index
  • size (int) — byte count
  • data (const uint8_t*) — safety output data

Returns:

  • std::vector<uint8_t> — safety input data; an empty vector = read failure
  • bool — true on a successful write

MdpRequestState() / MdpReset()​

bool MdpRequestState(uint16_t connIndex, FSoEState targetState) const;
bool MdpReset(uint16_t connIndex) const;

Requests a state transition / reset of the given connection. The state machine rules are the same as for a single connection (see RequestState()).

Parameters:

  • connIndex (uint16_t) — connection (module) index
  • targetState (FSoEState) — target state

Returns:

  • bool — true if the request succeeded; false if it was rejected or the runtime is not ready

MdpDownloadParameters() / MdpSetFailsafeOutput()​

std::optional<uint32_t> MdpDownloadParameters(uint16_t connIndex,
const uint8_t* data, uint32_t size) const;
bool MdpSetFailsafeOutput(uint16_t connIndex, const uint8_t* data, uint32_t size) const;

Downloads safety parameters (Parameter state) / presets the fail-safe output values for the given connection.

Parameters:

  • connIndex (uint16_t) — connection (module) index
  • data (const uint8_t*) — data
  • size (uint32_t) — data size (bytes)

Returns:

  • std::optional<uint32_t> — the SRA CRC32 on success; nullopt on failure
  • bool — true on success

MdpCheckWatchdog() / MdpGetLastError() / MdpClearError()​

bool MdpCheckWatchdog(uint16_t connIndex) const;
FSoEError MdpGetLastError(uint16_t connIndex) const;
void MdpClearError(uint16_t connIndex) const;

Watchdog check, error read and error clear for the given connection.

Parameters:

  • connIndex (uint16_t) — connection (module) index

Returns:

  • bool — the watchdog state query result
  • FSoEError — the last error code

MdpGetSlaveConnectionCount() / MdpDetectConnections()​

uint16_t MdpGetSlaveConnectionCount() const;
uint16_t MdpDetectConnections() const;

The number of FSoE connections on the slave / detects whether the slave is an MDP device and returns the supported connection count.

Returns:

  • uint16_t — number of FSoE connections

MdpGetDeviceAddress() / MdpGetModuleCommParam() / MdpGetModuleDiagnosis()​

std::optional<uint16_t> MdpGetDeviceAddress() const;
std::vector<uint8_t> MdpGetModuleCommParam(uint16_t moduleNumber, uint32_t maxSize = 256) const;
std::optional<SafeModuleDiag> MdpGetModuleDiagnosis(uint16_t moduleNumber) const;

Device-level safety address (0xF980:01), communication parameters of the given module (0x9nn1), diagnostics of the given module (0xAnn0).

Parameters:

  • moduleNumber (uint16_t) — module number
  • maxSize (uint32_t) — read limit (bytes), default 256

Returns:

  • std::optional<uint16_t> — device-level safety address; nullopt = cannot read
  • std::vector<uint8_t> — raw module communication parameter bytes; empty = read failure
  • std::optional<SafeModuleDiag> — module diagnostics; nullopt = cannot read

For a slave that supports MDP (Modular Device Profile) you can manage several independent FSoE connections:

auto& fsoe = master.GetSlave(1).GetFSoE();

// Initialise the MDP connection
SafeMdpConfig cfg{};
cfg.ConnectionId = 1;
cfg.SafetyAddress = 0x0100;
cfg.WatchdogTimeMs = 100;
cfg.SafeInputSize = 2;
cfg.SafeOutputSize = 1;
cfg.PdoInputOffset = 0;
cfg.PdoOutputOffset = 0;
fsoe.MdpInitConnection(0, cfg);

// Get the MDP connection state
int state = fsoe.MdpGetState(0);

// Get the full MDP connection state
auto mdpStatus = fsoe.MdpGetStatus(0); // std::optional<FSoEConnectionStatus>
if (mdpStatus) {
printf("MDP连接0: 状态=%d, CRC错误=%u\n", // MDP connection 0: state=%d, CRC errors=%u
static_cast<int>(mdpStatus->State), mdpStatus->CrcErrors);
}

// Read/write MDP safety IO
auto mdp_input = fsoe.MdpReadSafeInput(0, 2);
uint8_t mdp_out[] = {0x01};
fsoe.MdpWriteSafeOutput(0, mdp_out, sizeof(mdp_out));

// MDP request a state transition
fsoe.MdpRequestState(0, FSoEState::Data);

// MDP download safety parameters
uint8_t params[] = {0x01, 0x02};
auto crc = fsoe.MdpDownloadParameters(0, params, sizeof(params));

// MDP set fail-safe outputs
uint8_t fs_out[] = {0x00};
fsoe.MdpSetFailsafeOutput(0, fs_out, sizeof(fs_out));

// MDP check watchdog
bool wd_ok = fsoe.MdpCheckWatchdog(0);

// MDP get last error / clear errors
FSoEError mdpErr = fsoe.MdpGetLastError(0);
fsoe.MdpClearError(0);

// Reset the MDP connection
fsoe.MdpReset(0);

// Close the MDP connection
fsoe.MdpCloseConnection(0);

MDP detection and queries​

auto& fsoe = master.GetSlave(1).GetFSoE();

// Detect how many FSoE connections the slave supports
uint16_t connCount = fsoe.MdpDetectConnections();
printf("FSoE 连接数: %u\n", connCount); // FSoE connection count: %u

// Get the number of FSoE connections of a slave
uint16_t slaveConnCount = fsoe.MdpGetSlaveConnectionCount();

// Read the device-level safety address (0xF980:01)
auto devAddr = fsoe.MdpGetDeviceAddress();
if (devAddr) printf("设备安全地址: 0x%04X\n", *devAddr); // Device safety address: 0x%04X

// Read the module communication parameters
auto commParam = fsoe.MdpGetModuleCommParam(0);

// Read the module diagnostic data
auto diag = fsoe.MdpGetModuleDiagnosis(0);
if (diag) {
printf("模块0: 状态=%d, 失效安全=%s\n", // Module 0: state=%d, failsafe=%s
static_cast<int>(diag->State), diag->InFailsafe ? "是" : "否");
}

FSoE manager​

The SafetyManager class is the connection manager in the C++ SDK for managing multiple FSoE connections; it is provided by slave/fsoe.hpp.

using namespace darra;

SafetyManager mgr(dll, master.MasterNumber());

// Add a connection
auto& conn1 = mgr.AddConnection(1);
auto& conn2 = mgr.AddConnection(2);

// Initialise all connections
mgr.InitializeAll();

// Global safety state check
if (mgr.AllInDataState()) {
printf("所有连接处于 Data 状态\n"); // All connections are in the Data state
}

// Whether any connection is in the fail-safe state
if (mgr.AnyInFailsafe()) {
printf("有连接处于失效安全状态\n"); // Some connections are in the failsafe state
}

// Cyclic processing: the runtime PDO thread already calls it once per cycle; do not call it again here (double advancing = two steps in one tick)
// Call mgr.ProcessCycle() manually only in a self-built cycle that does not use the runtime PDO thread at all;

// Get the diagnostics
auto diags = mgr.GetDiagnostics();

// Close all connections
mgr.CloseAll();

SafetyManager methods​

AddConnection() / GetConnection() / ConnectionCount()​

FSoE& AddConnection(uint16_t slaveIndex);
FSoE& GetConnection(size_t index);
size_t ConnectionCount() const;

Adds a connection bound to the given slave / accesses a connection by index / the number of connections.

Parameters:

  • slaveIndex (uint16_t) — slave index
  • index (size_t) — connection index (out of range throws std::out_of_range)

Returns:

  • FSoE& — the new / existing connection
  • size_t — number of connections

InitializeAll() / CloseAll()​

bool InitializeAll();
bool CloseAll();

InitializeAll() initializes the connections one by one with the default configuration (connection ID 0 = automatic allocation, safety address 0, watchdog 100ms, safety data size 0); when real sizes are needed, use Bind*() or call Initialize(config) on each connection. CloseAll() closes all connections, and entries that fail stay in the connection table so they can be retried; the SafetyManager destructor also calls it automatically.

Returns:

  • bool — InitializeAll() returns true if all succeeded; CloseAll() returns true if all were closed and false if at least one was not

SafetyManager.CloseAllFailureCount()​

static uint32_t CloseAllFailureCount();

Process-wide cumulative count: the number of connections that CloseAll() did not close successfully.

Returns:

  • uint32_t — cumulative number of connections not closed (0 = never failed)

AllInDataState()​

bool AllInDataState() const;

Whether every connection is in the Data state. Returns false if any connection is not in Data or its state cannot be read; when the difference matters, use StateOrNull() on each connection.

Returns:

  • bool — true if all are in the Data state

AnyInFailsafe() / AnyInFailsafeOrNull()​

bool AnyInFailsafe() const;
std::optional<bool> AnyInFailsafeOrNull() const;

Whether any connection is in fail-safe.

Returns:

  • bool — true if a connection is in fail-safe; a false from a failed read means "cannot read" and must not be taken at face value
  • std::optional<bool> — true = a connection is in fail-safe; false = all are confirmed not in fail-safe; nullopt = the state of some connection cannot be read

GetDiagnostics()​

std::vector<SafeModuleDiag> GetDiagnostics() const;

The diagnostics summary of all connections; each entry contains the state, the CRC / watchdog counts and StatusValid (fields in SafeModuleDiag).

Returns:

FindByAddress() / FindByConnectionId()​

FSoE* FindByAddress(uint16_t safetyAddress);
FSoE* FindConnectionByAddress(uint16_t safetyAddress); // Same as FindByAddress
FSoE* FindByConnectionId(uint16_t connectionId);

Finds a connection by safety address / connection ID.

Parameters:

  • safetyAddress (uint16_t) — safety address
  • connectionId (uint16_t) — connection ID

Returns:

  • FSoE* — the connection found; nullptr if there is none

BindSafeIO()​

bool BindSafeIO(uint16_t slaveIndex, int safeInputOffset, int safeInputSize,
int safeOutputOffset, int safeOutputSize,
uint16_t safetyAddress = 0, uint32_t watchdogMs = 100);

Binds safety inputs and safety outputs in one call, with their own offsets and byte counts, and establishes one connection. The input / output sizes and PDO offsets must all be supplied in one call: only one connection is kept per slave, so when inputs are bound first and outputs second the second connection attempt has no effect and the output size is silently lost while success is still reported.

Parameters:

  • slaveIndex (uint16_t) — slave index
  • safeInputOffset (int) — byte offset of the safety data in the input PDO
  • safeInputSize (int) — safety input data size (bytes)
  • safeOutputOffset (int) — byte offset of the safety data in the output PDO
  • safeOutputSize (int) — safety output data size (bytes)
  • safetyAddress (uint16_t) — safety address, default 0
  • watchdogMs (uint32_t) — watchdog timeout (ms), default 100

Returns:

  • bool — true if the connection was established; false if an offset / size is negative or the connection attempt failed

Example:

SafetyManager mgr(master.Dll(), master.MasterNumber());
if (!mgr.BindSafeIO(1, 0, 2, 0, 1, 0x0100, 100)) {
printf("绑定失败,检查安全地址与数据长度\n"); // Binding failed, check the safety address and the data length
}

BindSafeInput() / BindSafeOutput()​

bool BindSafeInput(uint16_t slaveIndex, uint16_t safetyAddress,
uint16_t inputSize, uint32_t watchdogMs = 100);
bool BindSafeOutput(uint16_t slaveIndex, uint16_t safetyAddress,
uint16_t outputSize, uint32_t watchdogMs = 100);

Binds safety inputs only (output size 0) or safety outputs only (input size 0); for devices with safety inputs or outputs only. The safety data size really is handed to the connection (passing 0 builds the connection with 0 bytes, so reading safety inputs always returns empty).

Parameters:

  • slaveIndex (uint16_t) — slave index
  • safetyAddress (uint16_t) — safety address
  • inputSize / outputSize (uint16_t) — safety data size (bytes)
  • watchdogMs (uint32_t) — watchdog timeout (ms), default 100

Returns:

  • bool — true if the connection was established

BindMdpSafeInput() / BindMdpSafeOutput()​

bool BindMdpSafeInput(uint16_t slaveIndex, uint16_t safetyAddress,
uint16_t inputSize, int moduleNumber = 0, uint32_t watchdogMs = 100);
bool BindMdpSafeOutput(uint16_t slaveIndex, uint16_t safetyAddress,
uint16_t outputSize, int moduleNumber = 0, uint32_t watchdogMs = 100);

MDP version of the binding: goes through the MDP multi-connection entry point, with moduleNumber as the connection index.

Parameters:

  • slaveIndex (uint16_t) — slave index
  • safetyAddress (uint16_t) — safety address
  • inputSize / outputSize (uint16_t) — safety data size (bytes)
  • moduleNumber (int) — module number (connection index), default 0; a negative value returns false
  • watchdogMs (uint32_t) — watchdog timeout (ms), default 100

Returns:

  • bool — true if the connection was established

BindMdpDriveAxis()​

bool BindMdpDriveAxis(uint16_t slaveIndex, int axisIndex,
uint16_t safetyAddress = 0, uint32_t watchdogMs = 100);

MDP drive-axis safety binding. It does not discover the safety data sizes / PDO offsets and builds the connection with 0; when real sizes are needed use BindMdpSafeInput() / BindMdpSafeOutput() instead, or call MdpInitConnection() on the connection with the sizes filled in. The MDP connection index = axisIndex + 1.

Parameters:

  • slaveIndex (uint16_t) — slave index
  • axisIndex (int) — axis number; a negative value returns false
  • safetyAddress (uint16_t) — safety address, default 0
  • watchdogMs (uint32_t) — watchdog timeout (ms), default 100

Returns:

  • bool — true if the connection was established

ReadInputFrame() / WriteOutputFrame()​

std::vector<uint8_t> ReadInputFrame(size_t connectionIndex);
bool WriteOutputFrame(size_t connectionIndex, const std::vector<uint8_t>& frameData);

Reads / writes the raw safety frame of the given connection.

Parameters:

  • connectionIndex (size_t) — connection index
  • frameData (const std::vector<uint8_t>&) — output frame data

Returns:

  • std::vector<uint8_t> — the input frame; empty = index out of range / the connection has no safety input size
  • bool — true on a successful write; false if the index is out of range or the data is empty

GetStatusSummary()​

std::string GetStatusSummary() const;

Status summary string (the connection count and the state code of each connection).

Returns:

  • std::string — summary text

FSoE ConnID check (ETG.5120 §5.2.3)​

The FSoE protocol assigns every safety connection a unique 16-bit Connection ID (ConnID), which tells multiple safety connections on the same bus apart. Before creating a new connection the master must check that the ConnID is available, so that a conflict with an existing connection does not cause CRC or state machine errors.

IsConnectionIdAvailable()​

static bool IsConnectionIdAvailable(dll_t& dll, uint16_t connId);
bool IsConnectionIdAvailable(uint16_t connId) const;

Checks whether the given ConnID is available (not occupied by any active connection). The static version takes a dll_t& (such as master.Dll()); the member version uses the DLL held by the slave instance. It applies globally across slaves.

Parameters:

  • dll (dll_t&) — DLL context (the static version only)
  • connId (uint16_t) — the Connection ID to check (a value other than 0)

Returns:

  • bool — true means available, false means already occupied or the check failed

Example:

auto& fsoe = master.GetSlave(1).GetFSoE();

// Find the first free ConnID (starting from 1, using the member version)
uint16_t allocId = 0;
for (uint16_t id = 1; id < 0x1000; ++id) {
if (fsoe.IsConnectionIdAvailable(id)) {
allocId = id;
break;
}
}

if (allocId == 0) {
std::cerr << "无可用 ConnID\n"; // No ConnID available
return -1;
}

std::cout << "分配 ConnID: 0x" << std::hex << allocId << "\n"; // Allocated ConnID: 0x

// Initialise the FSoE connection with the assigned ConnID
fsoe.Initialize(allocId, /*safetyAddress*/ 0x0100, /*watchdogMs*/ 100);
ConnID allocation advice
  • ConnID 0x0000 is reserved and should not be used
  • All connections under the same FSoE master must have unique ConnIDs (ETG.5120 §5.2.3)
  • Linear allocation starting at 0x0001 is recommended, or the simplified strategy ConnID == SafetyAddress

FSoE CRC-16 and PDO frames (ETG.5120 §5.2)​

The lower-level FSoE protocol engine already verifies and computes CRC automatically, so users do not need to touch it; the API set below is used only in these scenarios:

  • Comparing against a reference implementation in unit tests when writing your own FSoE master / slave stack
  • Parsing a PCAP capture, restoring frame fields offline and recomputing the CRC
  • Diagnosing "the real CRC does not match the CRC the slave expects" when interoperating with a third-party safety PLC

IFSoECrc16 interface​

class IFSoECrc16 {
public:
virtual ~IFSoECrc16() = default;

/// Compute the CRC-16 of the buffer
virtual uint16_t Compute(const uint8_t* data, size_t length) const = 0;
/// vector overload
uint16_t Compute(const std::vector<uint8_t>& data) const;
};

CRC-16 abstraction interface. It lets an application supply its own implementation to mock / replace the default one. The interface itself has only Compute(); computation with a ConnectionID seed is the static method ComputeWithConnectionId() of the FSoECrc16 class, not an interface virtual function.

FSoECrc16 class (safety polynomial)​

class FSoECrc16 : public IFSoECrc16 {
public:
/// connectionId uses std::optional; std::nullopt = do not inject the ConnID prefix
explicit FSoECrc16(std::optional<uint16_t> connectionId = std::nullopt);

/// Default instance without a ConnID prefix (safe polynomial, init 0xFFFF)
static const FSoECrc16& SafetyPolynomial();

/// Factory: CRC-16 instance carrying a ConnectionID
static FSoECrc16 CreateWithConnectionId(uint16_t connectionId);

/// Static method: equivalent to CreateWithConnectionId(connId).Compute(data, length)
static uint16_t ComputeWithConnectionId(const uint8_t* data, size_t length,
uint16_t connectionId);

uint16_t Compute(const uint8_t* data, size_t length) const override;
};

Every computation forwards to the runtime's safety polynomial implementation: ETG.5100 §8.1.3.2 safety polynomial 0x139B7 (low 16 bits 0x39B7), initial value 0xFFFF, bit7→bit0 per byte, no reflection, no final XOR.

The constructor does not accept polynomial / initial value / xorOut parameters — a safety protocol CRC allows exactly one algorithm, and leaving the polynomial configurable amounts to letting the caller compute a wrong safety frame that "looks right". When connectionId is passed to the constructor, Compute() injects it as a data prefix (the standard FSoE practice); the static ComputeWithConnectionId(data, len, connId) can also be used directly.

Example:

using darra::ethercat::FSoECrc16;
using darra::ethercat::IFSoECrc16;

// Safety polynomial instance without a ConnID prefix
const IFSoECrc16& crc = FSoECrc16::SafetyPolynomial();
uint16_t v = crc.Compute(payload.data(), payload.size());

// Compute the CRC for a specific connection (standard FSoE usage) - static method
uint16_t safeCrc = FSoECrc16::ComputeWithConnectionId(
payload.data(), payload.size(), 0x0042);

// Or construct an instance with a ConnID and call Compute() directly
auto crc2 = FSoECrc16::CreateWithConnectionId(0x0042);
uint16_t safeCrc2 = crc2.Compute(payload.data(), payload.size());

fsoe_crc16()​

uint16_t fsoe_crc16(const uint8_t* data, size_t length, uint16_t init = 0xFFFF);

darra::fsoe_crc16 is the convenient computation without the ConnID prefix: use it when you need to control the initial value yourself (continued calculation) or do not want to inject the ConnID. For computation with a ConnID use FSoECrc16::ComputeWithConnectionId(data, len, connId) or a FSoECrc16::CreateWithConnectionId(connId) instance (the ConnID takes part in the CRC computation, ETG.5120 §5.2.3).

Parameters:

  • data (const uint8_t*) — data buffer; nullptr is treated as an empty buffer
  • length (size_t) — byte count
  • init (uint16_t) — CRC register initial value; pass 0xFFFF for a fresh computation, or the previous result to continue

Returns:

  • uint16_t — CRC-16 value

The algorithm is fixed and not configurable: safety polynomial 0x139B7 (low 16 bits 0x39B7, ETG.5100 §8.1.3.2), bit7→bit0 per byte, no reflection, no final XOR, implemented uniformly by the runtime.

Example:

// No ConnID prefix (you can supply your own initial value to continue a computation)
uint16_t crc = darra::fsoe_crc16(frame.data(), frame.size(), /*init=*/0xFFFF);

// With the ConnID prefix (standard FSoE usage) - static method
uint16_t safeCrc = FSoECrc16::ComputeWithConnectionId(
frame.data(), frame.size(), /*connectionId=*/0x0042);

FSoEPdoFrame and FSoEPdoLayout​

FSoEPdoFrame / FSoEPdoLayout are used on the application side to assemble / parse FSoE PDO frames (CommandByte + data segments + CRC segments + ConnectionID).

struct FSoEPdoLayout {
uint16_t CommandOffset = 0; // Command byte offset
uint16_t SafeDataOffset = 1; // SafeData start offset
uint16_t SafeDataLength = 2; // SafeData total length
uint16_t CrcSegmentCount = 1; // CRC section count = ceil(SafeDataLength*8/16)
std::vector<uint16_t> CrcOffsets; // CRC offset of each section (size = CrcSegmentCount)
uint16_t ConnIdOffset = 0; // ConnID byte offset
uint16_t TotalLength = 0; // Total frame length
uint16_t PaddingBytes = 0; // Padding of the odd byte at the end (0/1)

void Validate() const; // Check the layout self-consistency, throw std::invalid_argument if it is invalid
static uint16_t ComputeSegmentCount(uint32_t safeDataBits); // Compute the theoretical CRC section count
};

class FSoEPdoFrame {
public:
FSoECommand Command = FSoECommand::Reset; // FSoE Command (enum, not uint8_t)
uint16_t ConnectionId = 0; // ConnectionID
std::vector<uint8_t> SafeData; // Safety data segment
std::vector<uint16_t> CrcSegments; // CRC-16 of each section (split by layout)

/// Serialise to a byte stream (the CRC sections are computed and filled in by the runtime; the crc parameter is kept only for source compatibility)
std::vector<uint8_t> ToBytes(const FSoEPdoLayout& layout,
const IFSoECrc16* crc = nullptr);

/// Build an FSoEPdoFrame from the raw byte stream (all CRC sections are verified when a non-null crc is passed)
static FSoEPdoFrame FromBytes(const uint8_t* data, size_t data_size,
const FSoEPdoLayout& layout,
const IFSoECrc16* crc = nullptr);

/// Verify every CRC section (using the frame's own ConnectionId; the parameter is kept only for source compatibility)
bool ValidateCrcSegments(const IFSoECrc16& crc) const;
bool ValidateCrcSegments(uint16_t connectionId) const;
};

FSoEPdoLayout.Validate() / FSoEPdoLayout.ComputeSegmentCount()​

void Validate() const;
static uint16_t ComputeSegmentCount(uint32_t safeDataBits);

Layout self-consistency check / theoretical CRC segment count. Validate() criteria: the number of CrcOffsets must equal CrcSegmentCount, SafeDataLength ≤ 64 bytes, CRC segments ≤ 32, the segment count must equal ceil(SafeDataLength / 2), every offset must fall inside TotalLength, and PaddingBytes may only be 0 or 1.

Parameters:

  • safeDataBits (uint32_t) — number of safety data bits

Returns:

  • void — an illegal layout throws std::invalid_argument
  • uint16_t — theoretical CRC segment count; 0 bits returns 1

ToBytes()​

std::vector<uint8_t> ToBytes(const FSoEPdoLayout& layout,
const IFSoECrc16* crc = nullptr);

Serializes to a byte stream. The CRC segments are computed uniformly by the runtime and written back into this object's CrcSegments; the crc parameter is kept for source compatibility only and takes no part in the computation.

Parameters:

  • layout (const FSoEPdoLayout&) — frame layout (must already be self-consistent)
  • crc (const IFSoECrc16*) — kept for source compatibility only; nullptr may be passed

Returns:

  • std::vector<uint8_t> — frame bytes (length = layout.TotalLength)

Exceptions:

  • std::invalid_argument — the layout is illegal, or the SafeData length does not match layout.SafeDataLength
  • std::runtime_error — frame encoding failed or the runtime is not ready

FSoEPdoFrame.FromBytes()​

static FSoEPdoFrame FromBytes(const uint8_t* data, size_t data_size,
const FSoEPdoLayout& layout,
const IFSoECrc16* crc = nullptr);

Parses a frame from a byte stream. When crc is a non-null pointer, every CRC segment is verified as well (the verification uses the frame's own ConnectionId; the passed instance takes no part in the computation).

Parameters:

  • data (const uint8_t*) — frame bytes
  • data_size (size_t) — byte count (must not be less than layout.TotalLength)
  • layout (const FSoEPdoLayout&) — frame layout
  • crc (const IFSoECrc16*) — a non-null pointer adds CRC verification; nullptr = parse only

Returns:

  • FSoEPdoFrame — the parsed frame

Exceptions:

  • std::invalid_argument — data is empty / too short / parsing failed
  • std::runtime_error — CRC verification failed or the runtime is not ready

ValidateCrcSegments()​

bool ValidateCrcSegments(const IFSoECrc16& crc) const;
bool ValidateCrcSegments(uint16_t connectionId) const;

Verifies every CRC segment in the frame. Both overloads use the frame's own ConnectionId for the check; the parameter is kept for source compatibility only and takes no part in the computation.

Returns:

  • bool — true if every CRC segment matches; false if the runtime is not ready, the segment count is not consistent with the safety data length, or a CRC does not match

Example (assemble a frame and send it out):

using namespace darra::ethercat;

FSoEPdoLayout layout;
layout.SafeDataLength = 6;
layout.CrcSegmentCount = FSoEPdoLayout::ComputeSegmentCount(6 * 8); // 3 sections
layout.CrcOffsets = {3, 6, 9}; // CRC offset of each section (filled in from the actual frame layout)
layout.TotalLength = 13; // Must be self-consistent, otherwise Validate() throws

FSoEPdoFrame f;
f.Command = FSoECommand::Data; // FSoE Data Command (enum)
f.SafeData = {0x01, 0x02, 0x03, 0x04, 0x05, 0x06};
f.ConnectionId = 0x0042;

// The CRC sections are computed and filled in by the runtime (f.CrcSegments); the crc parameter is kept only for source compatibility
auto crc = FSoECrc16::CreateWithConnectionId(f.ConnectionId);
auto bytes = f.ToBytes(layout, &crc);

// ... write bytes to the PDO output area ...

Example (parse a capture and verify):

const IFSoECrc16& crcSpec = FSoECrc16::SafetyPolynomial();
auto frame = FSoEPdoFrame::FromBytes(buf, len, layout, &crcSpec);

// Verification uses the frame's own ConnectionId; crcSpec is kept only for source compatibility
if (!frame.ValidateCrcSegments(crcSpec)) {
printf("FSoE CRC 校验失败, 帧不合法\n"); // FSoE CRC check failed, the frame is invalid
}
Business code must not assemble frames and send them to the slave

During normal operation the FSoE protocol engine already hides FSoEPdoFrame inside the connection. Frame format and CRC computation rules are in ETG.5120 §5.2 / §5.2.5.

Helper functions​

dx_fsoe_is_slave_capable() / dx_fsoe_process_cycle() / dx_fsoe_get_connection_count()​

bool dx_fsoe_is_slave_capable(dll_t& dll, uint16_t masterIndex, uint16_t slaveIndex);
void dx_fsoe_process_cycle(dll_t& dll, uint16_t masterIndex);
uint16_t dx_fsoe_get_connection_count(dll_t& dll, uint16_t masterIndex);

Free functions in the darra:: namespace: check FSoE capability by master / slave index, advance one global FSoE cycle, and query the master's FSoE connection count (without going through a FSoE instance). dx_fsoe_process_cycle() should likewise be called only in a self-driven cycle; the runtime PDO thread already does it.

Parameters:

  • dll (dll_t&) — DLL context
  • masterIndex (uint16_t) — master index
  • slaveIndex (uint16_t) — slave index

Returns:

  • bool — true if the slave supports FSoE
  • uint16_t — the master's FSoE connection count

FSoEConnectionManager​

FSoEConnectionManager is the connection-oriented management interface (slave/fsoe.hpp); it holds a SafetyManager internally. Its members are:

FSoEConnectionManager(dll_t& dll, uint16_t masterIndex);

std::vector<FSoE*> GetConnections();
FSoE* GetConnection(size_t index); // Returns nullptr on out of range
size_t GetConnectionCount() const;
FSoE* FindConnectionByAddress(uint16_t safetyAddress);
FSoE& AddConnection(uint16_t slaveIndex);
void ProcessCycle(); // The runtime PDO thread already does this; the application must not call it again
SafetyManager& Manager();

Failures and handling​

SymptomCauseHandling
The binding returns false, or the connection never reaches the Data state for a long timeThe safety address does not match the device DIP switch, or the data byte counts do not match the device definitionCheck the safety address against the DIP switch; re-check the input and output byte counts against the device definition (BindSafeIO must carry both in one call)
WatchdogExpiredOrNull is nulloptThe connection status was not read this timeDo not treat it as a healthy watchdog. Confirm the PDO cycle is running and the slave is still in OP, then read again
WatchdogExpiredOrNull is trueThe watchdog error count is greater than 0Confirm the link, then call Reset to re-run the handshake
The connection cannot be established and stays in the session or connection phaseThe connection ID conflicts with another safety connectionLeave the connection ID at 0 and let the runtime allocate one, or pick a free ID before establishing the connection
Close / CloseAll returns falseThe safety connection was not closedRetry Close() directly, or call CloseAll() once more; entries that fail stay in the connection table, and the failure counts are available from CloseFailureCount / CloseAllFailureCount
The connection does not recover automatically after entering fail-safeThe fail-safe was triggered and the fault source is still presentRemove the fault source, then call Reset to rebuild the connection; if the device does not allow recovery, follow the safety procedure

Complete example​

#include "ethercat.hpp"
#include <cstdio>

using namespace darra;

int main() {
darra::ethercat::dll_t dll;
EtherCATMaster master(dll);
master.SetNetwork("\\Device\\NPF_{...}").SetENI("line.deni");
if (!master.Build() || !master.SetState(EcState::OP) || !master.Start())
return 1;

// 2 bytes of safety input, 1 byte of safety output; the safety address comes from the device DIP switches
SafetyManager mgr(master.Dll(), master.MasterNumber());
if (!mgr.BindSafeIO(1, 0, 2, 0, 1, 0x0100, 100)) {
printf("绑定失败,检查安全地址与数据长度\n"); // Binding failed, check the safety address and the data length
return 1;
}

FSoE& conn = mgr.GetConnection(0);
if (!conn.RequestState(FSoEState::Data)) {
printf("未能请求进入 Data\n"); // Could not request entry into Data
return 1;
}

for (int cycle = 0; cycle < 1000; ++cycle) {
auto wd = conn.WatchdogExpiredOrNull();
if (!wd) {
printf("看门狗状态未知,不能当成正常\n"); // Watchdog state unknown, it must not be treated as normal
break;
}
if (*wd) {
printf("看门狗错误计数大于 0,输出已切到安全值\n"); // Watchdog error count is greater than 0, the outputs have been switched to the safe value
break;
}
auto in = conn.ReadSafeInput(2); // Byte 0 is the channel bits
uint8_t out[1] = {0};
if (in.size() == 2 && (in[0] & 0x01)) out[0] = 0x01;
conn.WriteSafeOutput(out, 1);
}

conn.EnterFailsafe();
conn.Reset();
if (!mgr.CloseAll())
printf("有连接未能关闭,可再调一次 CloseAll\n"); // Some connections could not be closed, call CloseAll once more
return 0;
}