C++-specific sugar
On top of the C++17/C++20 standard, the C++ SDK provides a fully optional set of "sugar" components, all under the include/internal/sugar/ subdirectory and the darra::sugar namespace. They modify no header of the main SDK and are entirely free functions / standalone classes; include them only when you need them.
Design principles
- Does not modify the main SDK: every sugar item is a free function or a standalone class; the bytes of the main hpp files do not change.
- No mandatory dependencies: no new third-party library, only the STL (
<future><thread><optional><tuple><string_view><concepts>). - C++17 compatible: available under C++17 by default; C++20 features (concepts) are compiled conditionally behind a macro switch.
- Include on demand: one file per topic, or pull everything in with a single
#include "internal/sugar/sugar.hpp". - Does not break the existing API: every existing PascalCase property method is kept unchanged.
Include everything in one line
#include "ethercat.hpp"
#include "internal/sugar/sugar.hpp"
using namespace darra::ethercat;
using namespace darra::sugar;
You can also include per topic:
#include "internal/sugar/scoped.hpp" // RAII only
#include "internal/sugar/iter.hpp" // range-based for / STL algorithms only
#include "internal/sugar/snapshot.hpp" // Snapshot view only
Module overview
| Header | Topic | Key symbols |
|---|---|---|
internal/sugar/scoped.hpp | RAII guards | ScopedStart / ScopedState / ScopedLockIO / MakeMaster() |
internal/sugar/iter.hpp | Iteration views | SlavesView / slaves(master) |
internal/sugar/index.hpp | Indexed access | at() / slave_opt() / find_by_id() / find_by_name() / idx() |
internal/sugar/snapshot.hpp | Data snapshots | SlaveSnapshot / slaves_snapshot() / master_snapshot() |
internal/sugar/async.hpp | Asynchronous operations | StartAsync() / StopAsync() / BuildAsync() / WaitForState() |
internal/sugar/tuple.hpp | Structured binding | identity_tuple() / pdo_size() / wkc_stats() |
internal/sugar/string_view.hpp | string_view parameters | set_network() / set_eni() |
internal/sugar/concepts.hpp | C++20 type constraints | SlaveLike / MasterLike |
RAII scope guards (scoped.hpp)
Current state
EtherCATMaster already implements RAII itself: the destructor calls Dispose() automatically, which internally stops PDO, releases master resources and clears the slave cache. Ordinary users no longer need to call Stop/Dispose manually.
{
EtherCATMaster master(dll);
master.SetNetwork("\\Device\\NPF_{...}").Build();
master.SetState(EcState::OP);
master.Start();
// ... cyclic communication ...
} // Leave the scope: destructor -> Dispose() -> stop the PDO + release the master resources + clear the slave cache
ScopedStart: Start on entry, Stop on exit
Suited to starting a stretch of cyclic communication temporarily:
master.Build();
master.SetState(EcState::OP);
{
darra::sugar::ScopedStart guard(master);
if (!guard) {
std::cerr << "Start 失败\n"; // Start failed
return -1;
}
// Cyclic communication in progress
std::this_thread::sleep_for(std::chrono::seconds(5));
}
// Automatic Stop()
If you do not want Stop to run on scope exit (for example when handing the master over to another object), call release():
ScopedStart guard(master);
if (!guard) return;
guard.release(); // Give up the guardian; the user is responsible for Stop afterwards
ScopedState: switch state on entry, restore on exit
master.SetState(EcState::PreOp);
{
darra::sugar::ScopedState op(master, EcState::OP);
if (!op) {
std::cerr << "无法切到 OP\n"; // Could not switch to OP
return;
}
// Temporary OP to do something
}
// Leaving the scope automatically switches back to PreOp (the old_ recorded when ScopedState was constructed)
ScopedLockIO: IOmap mutex guard
In the high-performance MutexProtection=false mode you must pair LockIOmap/UnlockIOmap manually. LockIOmap() is a try-lock (it returns bool: true means the lock is held; on false you must neither enter the critical section nor unlock), and ScopedLockIO merely wraps that pair of calls in RAII:
master.MutexProtection(false); // Disable the automatic lock
void HighFreqCallback(uint16_t mi) {
darra::sugar::ScopedLockIO lk(master);
if (!lk) return; // Did not get the lock: skip this tick; the guard destructor will not unlock either
std::vector<uint8_t> inFrame;
darra::SlavePDO::CopyInputFrame(dll, master.MasterNumber(), 1, inFrame);
}
MakeMaster: one-line factory
Avoids the repeated three-step Builder + Validate + Build boilerplate:
try {
auto master = darra::sugar::MakeMaster(dll, "\\Device\\NPF_{...}");
master.SetState(EcState::OP);
master.Start();
} catch (const darra::ethercat::DarraException& e) {
std::cerr << "MakeMaster 失败: " << e.what() << "\n"; // MakeMaster failed:
}
Redundant mode:
auto master = darra::sugar::MakeMaster(dll,
"\\Device\\NPF_{primary}",
"\\Device\\NPF_{redundant}");
range-based for / STL algorithms (iter.hpp)
Built-in iterator
EtherCATMaster::SlaveIterator already supports range-based for:
for (auto s : master) {
std::cout << s.SlaveNum() << " " << s.Name() << "\n";
}
Note that *it returns Slave by value (a lightweight handle).
SlavesView view
sugar::SlavesView provides clearer view semantics and is suited to use with STL algorithms:
#include <algorithm>
auto v = darra::sugar::slaves(master);
// Count how many slaves support DC
auto dc_count = std::count_if(v.begin(), v.end(),
[](Slave& s) { return s.HasDC(); });
// Find the first missing slave
auto it = std::find_if(v.begin(), v.end(),
[](Slave& s) { return s.IsLost(); });
if (it != v.end()) {
std::cout << "丢失从站: " << it->Name() << " idx=" << it.index() << "\n"; // Lost slave:
}
// View size
std::cout << "size=" << v.size() << " empty=" << v.empty() << "\n";
SlavesView::iterator meets the input_iterator requirements: operator* / operator-> / operator++ / operator== / operator!=, plus the value_type / iterator_category and other typedefs the STL expects.
Indexed access (index.hpp)
Bounds checking
EtherCATMaster::GetSlave(idx) is lazy-create, so its out-of-range behaviour depends on the underlying layer. sugar::at() provides an explicit bounds check:
try {
auto& s = darra::sugar::at(master, 99); // Out of range throws DarraException
} catch (const darra::ethercat::DarraException& e) {
std::cerr << e.what() << "\n";
// sugar::at out of range: idx=99 current slave count=8
}
std::optional null safety
if (auto opt = darra::sugar::slave_opt(master, 1)) {
Slave& s = opt->get();
std::cout << s.Name() << "\n";
} else {
std::cout << "从站不存在\n"; // Slave does not exist
}
Find by ID or name
// Find the first match by vendor:product
auto found = darra::sugar::find_by_id(master, 0x000000ABu, 0x12345678u);
if (found) std::cout << "在槽位 " << found->get().Index() << "\n"; // In slot
// Find by name
auto el2008 = darra::sugar::find_by_name(master, "EL2008");
if (el2008) {
el2008->get().GetCoE(); // Chained call
}
Short call sugar
auto& s = darra::sugar::idx(master, 1); // Equivalent to master.GetSlave(1)
Data snapshots (snapshot.hpp)
The Slave class holds a dll_t& reference and is neither copyable nor serializable. When you need to:
- send the current slave state to an HMI / write it to a log
- process it asynchronously on another thread (avoiding holding dll_t)
- assert on it in a unit test
you first take a snapshot into plain data.
SlaveSnapshot POD
struct SlaveSnapshot {
uint16_t index;
std::string name;
uint32_t vendor_id;
uint32_t product_id;
uint32_t revision;
uint32_t serial_number;
uint16_t config_addr;
uint16_t alias_addr;
uint16_t input_bits;
uint16_t output_bits;
bool has_dc;
EcState state;
};
auto snaps = darra::sugar::slaves_snapshot(master);
for (auto& s : snaps) {
std::cout << "[" << s.index << "] " << s.name
<< " VID=0x" << std::hex << s.vendor_id
<< " PID=0x" << s.product_id
<< " state=" << static_cast<int>(s.state) << "\n";
}
// Cross-thread handoff - safe to copy/move
std::async(std::launch::async, [snaps]() {
upload_to_hmi(snaps);
});
MasterSnapshot
auto m = darra::sugar::master_snapshot(master);
log("WKC=%u/%u err_cnt=%u dc=%lld",
m.wkc, m.expected_wkc, m.error_cnt, (long long)m.dc_time_ns);
std::future asynchronous operations (async.hpp)
EtherCATMaster::SetStateAsync already returns std::future<bool>:
auto fut = master.SetStateAsync(EcState::OP, 10000);
// ... do other work at the same time ...
bool ok = fut.get(); // Blocking wait
internal/sugar/async.hpp adds more asynchronous wrappers.
StartAsync / StopAsync / BuildAsync
auto fut = darra::sugar::BuildAsync(master);
// The UI thread keeps refreshing so it does not block
while (fut.wait_for(std::chrono::milliseconds(50)) != std::future_status::ready) {
pump_ui_messages();
}
bool ok = fut.get();
SlaveSetStateAsync: asynchronous state change for a single slave
auto& s = master.GetSlave(1);
auto fut = darra::sugar::SlaveSetStateAsync(s, EcState::SafeOp, 3000);
if (!fut.get()) std::cerr << s.Name() << " 切 SafeOp 失败\n"; // failed to switch to SafeOp
WaitForState: passive polling wait
Suited to the case where another thread starts the state change and this thread waits passively:
auto fut = darra::sugar::WaitForState(master, EcState::OP, 5000, 50);
if (fut.get()) std::cout << "已进入 OP\n"; // Entered OP
else std::cerr << "超时\n"; // Timeout
structured binding (tuple.hpp)
// Slave identity
auto [vendor, product, rev] = darra::sugar::identity_tuple(slave);
// PDO size
auto [in_bytes, out_bytes] = darra::sugar::pdo_size(slave);
// PDO offset (bytes, start bit)
auto [io, ib, oo, ob] = darra::sugar::pdo_offsets(slave);
// The master WKC trio
auto [wkc, ewkc, errs] = darra::sugar::wkc_stats(master);
// Redundancy WKC
auto [pri_wkc, sec_wkc] = darra::sugar::redundancy_wkc(master);
// Master state trio
auto [st, al_err, link] = darra::sugar::state_tuple(master);
When writing logs or formatting output you no longer have to chain calls such as master.WKC() and master.ExpectedWKC() in long sequences.
std::string_view parameters (string_view.hpp)
The SetNetwork / SetENI prototypes take const std::string&. If you already hold a std::string_view (for example a substring produced by configuration parsing), you would have to construct a temporary std::string, which is verbose to write.
using namespace std::string_view_literals;
darra::sugar::set_network(master, "\\Device\\NPF_{primary}"sv);
darra::sugar::set_eni(master, "C:/cfg/site.eni"sv);
Tradeoff: the DLL boundary still needs a c_str() terminator, so sugar makes one std::string(view) copy internally; the value lies in a consistent calling style — the caller does not convert by hand.
C++20 concepts (concepts.hpp)
Enabled only when
__cplusplus >= 202002L; under C++17concepts.hppis an empty file and reports no error.
#include "internal/sugar/concepts.hpp"
template<darra::sugar::SlaveLike S>
void log_slave(const S& s) {
std::cout << s.Name() << " VID=" << s.VendorId() << "\n";
}
// Real slaves
log_slave(master.GetSlave(1));
// User-defined mock
struct FakeSlave {
std::string Name() const { return "fake"; }
uint32_t VendorId() const { return 0x42; }
uint32_t ProductId() const { return 0x1234; }
};
log_slave(FakeSlave{});
SlaveLike requires the type to expose the three methods Name() VendorId() ProductId() (their return values must convert to std::string / uint32_t). MasterLike requires SlaveCount() / Build() in the same way.
constexpr enumerator constants
EcState / EcALState / EcLinkState are strongly typed enum class enumerations with constexpr semantics built in; no additional sugar is needed:
constexpr EcState target = EcState::OP;
static_assert(target == EcState::OP);
For an exhaustive switch over the enumeration, include #include <type_traits> and convert explicitly with static_cast<int>:
switch (master.State()) {
case EcState::Init: ...; break;
case EcState::PreOp: ...; break;
case EcState::SafeOp: ...; break;
case EcState::OP: ...; break;
default: ...;
}
std::function callbacks (current state)
The C++ SDK uses std::function throughout as the callback carrier; register callbacks with On*() / SetPDOCallbackSync():
master.Events().SetPDOCallbackSync([&](uint16_t mi) {
// Lambda capture - perfectly fine
auto& s = master.GetSlave(1);
/* ... */
});
master.OnStateChanged([](EcState old_st, EcState new_st) {
std::cout << "state " << (int)old_st << " -> " << (int)new_st << "\n";
});
Each MasterEvents event is a multi-subscriber std::vector<std::function<...>>; register with On*() /
SetPDOCallbackSync() (you can register several callbacks) and never assign with = directly.
A callback can be a lambda, a std::bind result, a function pointer or a functor. This is an existing feature; sugar adds no duplicate wrapper.
Full example: all the sugar combined
#include "ethercat.hpp"
#include "internal/sugar/sugar.hpp"
#include <algorithm>
#include <iostream>
using namespace darra::ethercat;
using namespace darra::sugar;
int main() {
dll_t dll; // SDK context (RAII)
try {
// 1. One-line factory + RAII
auto master = MakeMaster(dll, "\\Device\\NPF_{...}");
// 2. structured binding to read the state
auto [st, err, link] = state_tuple(master);
std::cout << "init state=" << (int)st << "\n";
// 3. Async switch to OP
auto fut_op = master.SetStateAsync(EcState::OP, 10000);
if (!fut_op.get()) {
std::cerr << "OP 失败\n"; // OP failed
return -2;
}
// 4. Scope Start
ScopedStart run(master);
if (!run) return -3;
// 5. STL finds DC slaves
auto v = slaves(master);
auto dc_count = std::count_if(v.begin(), v.end(),
[](Slave& s) { return s.HasDC(); });
std::cout << dc_count << " 个 DC 从站\n"; // DC slaves
// 6. Snapshot reporting
auto snaps = slaves_snapshot(master);
std::async(std::launch::async, [snaps]() {
// Send the snapshot to the HMI on a worker thread
upload(snaps);
});
// 7. Cycle callback
master.Events().SetPDOCallbackSync([&master](uint16_t mi) {
std::vector<uint8_t> inFrame;
darra::SlavePDO::CopyInputFrame(dll, master.MasterNumber(), 1, inFrame);
});
std::this_thread::sleep_for(std::chrono::seconds(10));
} catch (const DarraException& e) {
std::cerr << "异常: " << e.what() << " code=" << e.code() << "\n"; // Exception:
return -1;
}
// master destructor -> Stop -> Dispose
return 0;
}
What is not part of sugar
To avoid confusion, the following are not part of sugar; the main SDK provides them directly:
- Move semantics (
EtherCATMaster(EtherCATMaster&&)): already implemented in the main class - Copy prohibition: already
= deletein the main class std::optional<EtherCATMaster>factory:InitializeSpecificMasteralready returns it- Basic range-based for:
master.begin()/end()are already usable directly - Exception class:
DarraExceptionis inutils/dll.hpp - Automatic Dispose: already implemented in
~EtherCATMaster
sugar is an additional layer; the standard API remains fully usable.
Build requirements
| Header | Minimum standard |
|---|---|
scoped.hpp / iter.hpp / index.hpp / snapshot.hpp / tuple.hpp | C++17 |
async.hpp | C++17 (<future> <thread> <chrono>) |
string_view.hpp | C++17 (<string_view>) |
concepts.hpp | C++20 (__cplusplus >= 202002L) — becomes an empty file under C++17 |
sugar.hpp (umbrella) | C++17 and later, concepts skipped automatically |
CMake example:
target_compile_features(my_app PRIVATE cxx_std_17)
# If you need concepts:
# target_compile_features(my_app PRIVATE cxx_std_20)
target_include_directories(my_app PRIVATE ${SDK_PATH}/include)
Reference graph
ethercat.hpp (main SDK umbrella, original state)
└── master/core.hpp (EtherCATMaster - has RAII / begin-end / SetStateAsync)
└── slave/core.hpp (Slave - has PascalCase properties)
│
│ (sugar is an overlay layer and does not modify any of the files above)
▼
internal/sugar/sugar.hpp (sugar umbrella)
├── scoped.hpp ──┐
├── iter.hpp ──┤
├── index.hpp ──┼─ only #includes the main SDK headers + STL
├── snapshot.hpp ──┤
├── async.hpp ──┤
├── tuple.hpp ──┤
├── string_view.hpp ──┤
└── concepts.hpp ──┘ (conditional compilation)
FAQ
Q: Does sugar affect the binary ABI? A: No. All sugar is inline free functions / class templates, compiled with the application code; the binary interface of the library does not change.
Q: Is the SDK fully usable without sugar?
A: Yes, fully. Including ethercat.hpp on its own is the full SDK. sugar is only a convenience at the level of writing style.
Q: Cross-compiler compatibility? A: Tested under C++17 mode on MSVC 19.20+ / GCC 9+ / Clang 10+; the C++20 concepts part requires MSVC 19.30+ / GCC 10+ / Clang 13+.