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.
slave.GetFSoE() detects this automatically when the slave is initialized. The detection sequence:
- CoE prerequisite — the slave must support the CoE mailbox protocol
- 0xF980:01 check — try to read the device-level FSoE safety address over SDO; success confirms support
- 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
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.
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));
}
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 refreshedWriteSafeOutput()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:
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++ 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
| Category | Method | Type | Read/write | Description |
|---|---|---|---|---|
| Capability (FSoE) | IsCapable | bool | Read | Whether the slave supports FSoE |
| Connection management (FSoE) | Initialize | bool | Write | Establishes the safety connection; pass connectionId 0 to have the runtime allocate one |
| Connection management (FSoE) | IsInitialized | bool | Read | Whether it is initialized |
| Connection management (FSoE) | Close | bool | Write | Closes the connection; on failure returns false and keeps the initialized state so it can be retried |
| Connection management (FSoE) | CloseFailureCount | uint32_t | Read | Cumulative number of close failures |
| Connection management (FSoE) | LastCloseFailed | bool | Read | Whether the most recent Close failed |
| Safety data (FSoE) | ReadSafeInput | std::vector<uint8_t> | Read | Reads the safety inputs; an empty vector = read failure |
| Safety data (FSoE) | WriteSafeOutput | bool | Write | Writes the safety outputs; committed in the next cycle |
| Safety data (FSoE) | SetFailsafeOutput | bool | Write | Presets the output values used when entering fail-safe |
| State query (FSoE) | State | FSoEState | Read | Current state; a failed read collapses to Reset, so check StatusValid alongside it |
| State query (FSoE) | StateOrNull | std::optional<FSoEState> | Read | Three-valued state; nullopt = cannot read |
| State query (FSoE) | GetStatus | std::optional<FSoEStatus> | Read | Status snapshot; nullopt = cannot read |
| State query (FSoE) | ConnectionStatus | FSoEConnectionStatus | Read | Full connection status; on a failed read the fields hold default values |
| State query (FSoE) | ConnectionStatusOrNull | std::optional<FSoEConnectionStatus> | Read | Three-valued full connection status; nullopt = cannot read |
| State query (FSoE) | StatusValid | bool | Read | Whether the most recent status read was valid |
| State query (FSoE) | IsConnected | bool | Read | Whether a valid connection exists (same as StatusValid) |
| State query (FSoE) | InFailsafe | bool | Read | Whether it is in fail-safe; a failed read returns false, which must not be taken at face value |
| State query (FSoE) | InFailsafeOrNull | std::optional<bool> | Read | Three-valued fail-safe; nullopt = cannot read |
| Diagnostics (FSoE) | WatchdogExpired | bool | Read | Whether the watchdog error count is greater than 0; a failed read returns false, which must not be taken at face value |
| Diagnostics (FSoE) | WatchdogExpiredOrNull | std::optional<bool> | Read | nullopt = not read; true = the watchdog error count is greater than 0; false = this read succeeded and the count is 0 |
| Diagnostics (FSoE) | CrcErrorCount | uint32_t | Read | CRC error count |
| Diagnostics (FSoE) | FramesSent | uint32_t | Read | Frames sent; a three-valued FramesSentOrNull version also exists |
| Diagnostics (FSoE) | FramesReceived | uint32_t | Read | Valid frames received; a three-valued FramesReceivedOrNull version also exists |
| Diagnostics (FSoE) | LastError | FSoEError | Read | The last error code |
| Diagnostics (FSoE) | GetLastError | FSoEError | Read | The last error code (same as LastError) |
| Diagnostics (FSoE) | ClearError | void | Write | Clears the error |
| Diagnostics (FSoE) | GetFailsafeReason | FSoEFailsafeReason | Read | Infers the fail-safe reason from the last error code |
| Connection info (FSoE) | SafetyAddress | uint16_t | Read | Safety address (the value used at initialization) |
| Connection info (FSoE) | ConnectionId | uint16_t | Read | Connection ID (the value actually allocated when it was generated automatically) |
| Connection info (FSoE) | SafeInputSize | int | Read | Safety input data size (bytes) |
| State control (FSoE) | RequestState | bool | Write | Requests a transition to the target safety state. A rejected request returns false, which does not mean the state has been entered |
| State control (FSoE) | EnterFailsafe | bool | Write | Actively enters fail-safe; the slave outputs switch to the safety values |
| State control (FSoE) | Reset | bool | Write | Resets the safety connection; the state machine restarts the handshake from Reset |
| State control (FSoE) | fsoe_is_valid_state_transition | int | Read | Queries whether a state transition is allowed |
| Watchdog (FSoE) | CheckWatchdog | bool | Read | Checks the watchdog state |
| Watchdog (FSoE) | GetWatchdogStatus | bool | Read | Checks the watchdog state (same as CheckWatchdog) |
| Watchdog (FSoE) | ConfigureWatchdog / SetWatchdog | bool | Write | Always returns false: the watchdog timeout is configured only in Initialize |
| Watchdog (FSoE) | ResetWatchdog | bool | Write | Currently equivalent to Reset() (resets the whole connection) |
| Parameters (FSoE) | DownloadParameters | std::optional<uint32_t> | Write | Downloads safety parameters in the Parameter state and returns the SRA CRC32 |
| Parameters (FSoE) | GetFailsafeParameters | std::vector<uint8_t> | Read | Currently the same semantics as ReadSafeInput |
| Parameters (FSoE) | SetFailsafeParameters | bool | Write | Currently the same semantics as WriteSafeOutput |
| ConnID (FSoE) | FSoE.IsConnectionIdAvailable | bool | Read | Checks whether a connection ID is available (a value other than 0) |
| Cycle (FSoE) | ProcessCycle | void | Write | Advances the cycle; the runtime PDO thread already does this, so the application must not call it again |
| Callback (FSoE) | OnStateChanged / OnError / OnFailsafe | std::function | Write | Event callback members; ProcessCycle dispatches them after comparing each cycle, see the event callbacks section |
| MDP connection (FSoE) | MdpInitConnection / MdpCloseConnection | bool | Write | Establishes / closes the MDP connection of the given module |
| MDP connection (FSoE) | MdpRequestState / MdpReset | bool | Write | State transition / reset for the given connection |
| MDP data (FSoE) | MdpReadSafeInput | std::vector<uint8_t> | Read | Reads the safety inputs of the given connection; an empty vector = read failure |
| MDP data (FSoE) | MdpWriteSafeOutput | bool | Write | Writes the safety outputs of the given connection |
| MDP data (FSoE) | MdpSetFailsafeOutput | bool | Write | Presets the fail-safe outputs of the given connection |
| MDP data (FSoE) | MdpDownloadParameters | std::optional<uint32_t> | Write | Downloads safety parameters for the given connection |
| MDP diagnostics (FSoE) | MdpGetState | int | Read | State code of the given connection (a FSoEState value) |
| MDP diagnostics (FSoE) | MdpGetStatus | std::optional<FSoEConnectionStatus> | Read | Full state of the given connection |
| MDP diagnostics (FSoE) | MdpCheckWatchdog | bool | Read | Watchdog check for the given connection |
| MDP diagnostics (FSoE) | MdpGetLastError / MdpClearError | FSoEError / void | Read/write | Error read / clear for the given connection |
| MDP query (FSoE) | MdpGetSlaveConnectionCount / MdpDetectConnections | uint16_t | Read | Number of FSoE connections on the slave |
| MDP query (FSoE) | MdpGetDeviceAddress | std::optional<uint16_t> | Read | Device-level safety address (0xF980:01) |
| MDP query (FSoE) | MdpGetModuleCommParam | std::vector<uint8_t> | Read | Communication parameters of the given module (0x9nn1) |
| MDP query (FSoE) | MdpGetModuleDiagnosis | std::optional<SafeModuleDiag> | Read | Diagnostics of the given module (0xAnn0) |
| Binding (SafetyManager) | BindSafeIO | bool | Write | Binds safety inputs and safety outputs in one call, with their own offsets and byte counts, and establishes one connection |
| Binding (SafetyManager) | BindSafeInput | bool | Write | Binds safety inputs only, with an output size of 0; for devices with safety inputs only |
| Binding (SafetyManager) | BindSafeOutput | bool | Write | Binds safety outputs only, with an input size of 0; for devices with safety outputs only |
| Binding (SafetyManager) | BindMdpSafeInput / BindMdpSafeOutput | bool | Write | MDP version of the binding; establishes the connection by module number |
| Binding (SafetyManager) | BindMdpDriveAxis | bool | Write | MDP drive-axis binding; carries no safety data size, see the entry below |
| Manager (SafetyManager) | AddConnection / GetConnection | FSoE& | Read/write | Adds / accesses a connection |
| Manager (SafetyManager) | ConnectionCount | size_t | Read | Number of connections |
| Manager (SafetyManager) | InitializeAll | bool | Write | Initializes all connections |
| Manager (SafetyManager) | CloseAll | bool | Write | Closes all connections; entries that fail stay in the table and can be retried |
| Manager (SafetyManager) | SafetyManager.CloseAllFailureCount | uint32_t | Read | Process-level: cumulative number of connections that CloseAll did not close successfully |
| Manager (SafetyManager) | AllInDataState | bool | Read | Whether every connection is in the Data state |
| Manager (SafetyManager) | AnyInFailsafe | bool | Read | Whether any connection is in fail-safe; a failed read returns false, which must not be taken at face value |
| Manager (SafetyManager) | AnyInFailsafeOrNull | std::optional<bool> | Read | Three-valued; if any connection read fails = nullopt |
| Manager (SafetyManager) | GetDiagnostics | std::vector<SafeModuleDiag> | Read | Diagnostics summary for all connections |
| Manager (SafetyManager) | FindByAddress / FindConnectionByAddress | FSoE* | Read | Finds a connection by safety address |
| Manager (SafetyManager) | FindByConnectionId | FSoE* | Read | Finds a connection by connection ID |
| Manager (SafetyManager) | ReadInputFrame | std::vector<uint8_t> | Read | Reads the raw safety input frame of the given connection |
| Manager (SafetyManager) | WriteOutputFrame | bool | Write | Writes the raw safety output frame of the given connection |
| Manager (SafetyManager) | GetStatusSummary | std::string | Read | Status summary string |
| Manager (SafetyManager) | ProcessCycle | void | Write | Advances the cycle; the runtime PDO thread already does this, so the application must not call it again |
| CRC (FSoECrc16) | fsoe_crc16 | uint16_t | Read | FSoE CRC-16 computation, with a custom initial value for continued calculation |
| CRC (FSoECrc16) | FSoECrc16.ComputeWithConnectionId | uint16_t | Read | CRC-16 with the ConnID prefix |
| PDO frame (FSoEPdoFrame) | ToBytes / FromBytes | std::vector<uint8_t> / FSoEPdoFrame | Read/write | FSoE PDO frame serialization / parsing |
| PDO frame (FSoEPdoFrame) | ValidateCrcSegments | bool | Read | Verifies every CRC segment in the frame |
| PDO frame (FSoEPdoLayout) | Validate / ComputeSegmentCount | void / uint16_t | Read | Layout 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
| Field | Type | Description |
|---|---|---|
| State | FSoEState | Current FSoE state |
| LastError | FSoEError | Last error code |
| ErrorCount | uint32_t | Total error count |
| FramesSent | uint32_t | Frames sent |
| FramesReceived | uint32_t | Valid frames received |
| CrcErrors | uint32_t | CRC error count |
| WatchdogErrors | uint32_t | Watchdog timeout count |
| WatchdogExpired | bool | Whether the watchdog has expired |
| InFailsafe | bool | Whether it is in fail-safe mode |
| ToggleBit | uint8_t | Current toggle bit value |
| IsInitialized | bool | Whether the connection is initialized |
FSoEConnectionConfig
| Field | Type | Description |
|---|---|---|
| ConnectionId | uint16_t | Unique connection identifier |
| SafetyAddress | uint16_t | FSoE slave safety address (set by the DIP switch) |
| WatchdogTimeMs | uint32_t | Watchdog timeout (ms), default 100 |
| SafeInputSize | uint16_t | Safety input data size (bytes), determined by the device |
| SafeOutputSize | uint16_t | Safety output data size (bytes), determined by the device |
| PdoInputOffset | uint32_t | Input offset in the IOmap (usually slave.Ioffset()) |
| PdoOutputOffset | uint32_t | Output 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
| Field | Type | Description |
|---|---|---|
| State | uint8_t | Current state code (a FSoEState value) |
| FailsafeActive | bool | Whether it is in fail-safe mode |
| CrcErrors | uint32_t | CRC error count |
| WatchdogErrors | uint32_t | Watchdog 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
| Field | Type | Description |
|---|---|---|
| ConnectionId | uint16_t | Connection ID (SI3) |
| SafetyAddress | uint16_t | Safety address (SI2) |
| WatchdogTimeMs | uint32_t | Watchdog timeout (ms) (SI4) |
| CommParamLength | uint16_t | Communication parameter length (SI7) |
| AppParamLength | uint16_t | Application parameter length (SI8) |
| Version | std::string | Version (SI1), default 01 |
| ConnectionType | uint16_t | Connection type (SI6): 0=Master, 1=Slave |
SafeModuleDiag
| Field | Type | Description |
|---|---|---|
| ModuleIndex | uint16_t | Module index |
| State | FSoEState | Module FSoE state |
| CrcErrors | uint32_t | CRC error count |
| WatchdogErrors | uint32_t | Watchdog timeout count |
| InFailsafe | bool | Whether it is in fail-safe |
| StatusValid | bool | Whether this read was valid; when false the fields above are the defaults of a failed read and must not be treated as safe |
SafeModuleInfo
| Field | Type | Description |
|---|---|---|
| ModuleIndex | uint16_t | Module index |
| ModuleProfile | uint16_t | Module profile (a SafeModuleProfile value) |
| SafeInputSize | uint16_t | Safety input bytes |
| SafeOutputSize | uint16_t | Safety output bytes |
| ConnectionId | uint16_t | Connection ID |
| SafetyAddress | uint16_t | Safety address |
| Name | std::string | Module name |
SafeMdpConfig
| Field | Type | Description |
|---|---|---|
| ConnectionId | uint16_t | Connection ID; 0 = allocated by the runtime |
| SafetyAddress | uint16_t | Safety address |
| WatchdogTimeMs | uint32_t | Watchdog timeout (ms), default 10 |
| SafeInputSize | uint16_t | Safety input data size (bytes) |
| SafeOutputSize | uint16_t | Safety output data size (bytes) |
| PdoInputOffset | uint32_t | Byte offset of the safety data in the input PDO |
| PdoOutputOffset | uint32_t | Byte offset of the safety data in the output PDO |
Safety data structures
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)
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:
targetState(FSoEState) — target state
Returns:
bool—trueif the request is accepted;falseif the transition is not legal, the connection is not initialized, or the runtime is not ready
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—trueif the request is accepted;falseif 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—trueif the reset request succeeded;falseon failure
Connection management
IsCapable()
bool IsCapable() const;
Whether the slave supports FSoE.
Returns:
bool—trueif supported;falseif 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 withConnectionId()safetyAddress(uint16_t) — slave safety address (hardware DIP switch)watchdogMs(uint32_t) — watchdog timeout (ms); the three-argument version defaults to 10config(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—trueif the connection is established;falseif 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—trueif 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—trueif 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.
Callable only in the Parameter state. The parameter content is generated by the safety configuration tool.
Parameters:
data(const uint8_t*) — parameter datasize(uint32_t) — data size
Returns:
std::optional<uint32_t>— the SRA CRC32 on success;std::nullopton 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 datasize(uint32_t) — data size (bytes)
Returns:
bool—trueon success;falseon 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 readdata(const uint8_t*) — data buffersize(int) — data size (bytes)
Returns:
std::vector<uint8_t>— the read result; an empty vector = read failurebool—trueon 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 datasize(int) — data size (bytes)
Returns:
bool—trueon success;falseon 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
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—trueif a valid status was read
InFailsafe() / InFailsafeOrNull()
bool InFailsafe() const;
std::optional<bool> InFailsafeOrNull() const;
Whether it is in fail-safe mode.
Returns:
bool—truefor fail-safe; afalsefrom a failed read means "cannot read", not a confirmed non-fail-safestd::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—trueif the watchdog error count is greater than 0std::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 countstd::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::Nonewhen 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 IDint— 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:
- FSoEFailsafeReason — the reason the fail-safe was triggered
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— alwaysfalse
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 asReset()
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.
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:
| Category | Method | Type | Read/write | Description |
|---|---|---|---|---|
| Callback (FSoE) | OnStateChanged | std::function<void(FSoEState, FSoEState)> | Write | State change |
| Callback (FSoE) | OnError | std::function<void(FSoEError)> | Write | Error code change (non-None) |
| Callback (FSoE) | OnFailsafe | std::function<void(FSoEFailsafeReason)> | Write | Entering 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/OnErrorper 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.
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.
- 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) indexcfg(SafeMdpConfig) — connection configuration; pass ConnectionId 0 to have the runtime allocate one
Returns:
bool—trueon success;falseon 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) indexsize(int) — byte countdata(const uint8_t*) — safety output data
Returns:
std::vector<uint8_t>— safety input data; an empty vector = read failurebool—trueon 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) indextargetState(FSoEState) — target state
Returns:
bool—trueif the request succeeded;falseif 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) indexdata(const uint8_t*) — datasize(uint32_t) — data size (bytes)
Returns:
std::optional<uint32_t>— the SRA CRC32 on success;nullopton failurebool—trueon 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 numbermaxSize(uint32_t) — read limit (bytes), default 256
Returns:
std::optional<uint16_t>— device-level safety address;nullopt= cannot readstd::vector<uint8_t>— raw module communication parameter bytes; empty = read failurestd::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 indexindex(size_t) — connection index (out of range throwsstd::out_of_range)
Returns:
FSoE&— the new / existing connectionsize_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()returnstrueif all succeeded;CloseAll()returnstrueif all were closed andfalseif 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—trueif 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—trueif a connection is in fail-safe; afalsefrom a failed read means "cannot read" and must not be taken at face valuestd::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:
std::vector<SafeModuleDiag> — diagnostics in connection order
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 addressconnectionId(uint16_t) — connection ID
Returns:
FSoE*— the connection found;nullptrif 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 indexsafeInputOffset(int) — byte offset of the safety data in the input PDOsafeInputSize(int) — safety input data size (bytes)safeOutputOffset(int) — byte offset of the safety data in the output PDOsafeOutputSize(int) — safety output data size (bytes)safetyAddress(uint16_t) — safety address, default 0watchdogMs(uint32_t) — watchdog timeout (ms), default 100
Returns:
bool—trueif the connection was established;falseif 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 indexsafetyAddress(uint16_t) — safety addressinputSize/outputSize(uint16_t) — safety data size (bytes)watchdogMs(uint32_t) — watchdog timeout (ms), default 100
Returns:
bool—trueif 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 indexsafetyAddress(uint16_t) — safety addressinputSize/outputSize(uint16_t) — safety data size (bytes)moduleNumber(int) — module number (connection index), default 0; a negative value returnsfalsewatchdogMs(uint32_t) — watchdog timeout (ms), default 100
Returns:
bool—trueif 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 indexaxisIndex(int) — axis number; a negative value returnsfalsesafetyAddress(uint16_t) — safety address, default 0watchdogMs(uint32_t) — watchdog timeout (ms), default 100
Returns:
bool—trueif 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 indexframeData(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 sizebool—trueon a successful write;falseif 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—truemeans available,falsemeans 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 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 bufferlength(size_t) — byte countinit(uint16_t) — CRC register initial value; pass0xFFFFfor 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 throwsstd::invalid_argumentuint16_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;nullptrmay 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.SafeDataLengthstd::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 bytesdata_size(size_t) — byte count (must not be less than layout.TotalLength)layout(const FSoEPdoLayout&) — frame layoutcrc(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 failedstd::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—trueif every CRC segment matches;falseif 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
}
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 contextmasterIndex(uint16_t) — master indexslaveIndex(uint16_t) — slave index
Returns:
bool—trueif the slave supports FSoEuint16_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
| Symptom | Cause | Handling |
|---|---|---|
| The binding returns false, or the connection never reaches the Data state for a long time | The safety address does not match the device DIP switch, or the data byte counts do not match the device definition | Check 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 nullopt | The connection status was not read this time | Do 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 true | The watchdog error count is greater than 0 | Confirm the link, then call Reset to re-run the handshake |
| The connection cannot be established and stays in the session or connection phase | The connection ID conflicts with another safety connection | Leave the connection ID at 0 and let the runtime allocate one, or pick a free ID before establishing the connection |
| Close / CloseAll returns false | The safety connection was not closed | Retry 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-safe | The fail-safe was triggered and the fault source is still present | Remove 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;
}