Darra OPC UA Client — C++ SDK
Darra OPC UA Client C++ Bindings. header-only, C++17, RAII, Namespaces darra::opcua. The concept hierarchy is consistent with C# (Session / Subscription / Variant / DataValue), and the specific API syntax has been adjusted to conform to C++ conventions — seeCross-Language Alignment.
- Getting Started → Session (Construct / Connect / Read / Write / KeepAlive)
- Browse → Nodes (Browse / Path Resolution / RegisterNodes)
- Real-time → Subscription (CreateSubscription / MonitoredItem / on_data_change)
- History → History (Raw / Modified / AtTime / Processed / Events / Update / Delete)
- Call → Method (Call)
- Discover → Discovery (GetEndpoints / FindServers)
- Data → Data Types (Variant / DataValue / WellKnownNodes)
- Security → Security (Certificates / Encryption)
Installation
C++ SDK is header-only, There is no need to compile the .cpp files separately. Simply Darra.OpcUa.Core add the include/ directories where the C++ and C packages were extracted to the project's include path, and then link the C implementation.
- CMake (Recommended)
- Manual (Makefile / MSBuild)
- vcpkg (future versions)
add_executable(my_app main.cpp)
target_include_directories(my_app PRIVATE
${CMAKE_SOURCE_DIR}/third_party/darra_opcua_cpp/include
${CMAKE_SOURCE_DIR}/third_party/darra_opcua_c/include)
target_link_libraries(my_app PRIVATE Darra.OpcUa.Core)
target_compile_features(my_app PRIVATE cxx_std_17)
g++ -std=c++17 main.cpp \
-I third_party/darra_opcua_cpp/include \
-I third_party/darra_opcua_c/include \
-L third_party/darra_opcua_c/lib \
-lDarra.OpcUa.Core -o my_app
# Future versions will include a vcpkg port; for now, please use the `include` command directly CMake .
vcpkg install darra-opcua
System Requirements
| Item | Requirements |
|---|---|
| Compiler | C++17 |
| Operating System | Windows 10/11 x64 |
| Platform | x64 |
| Agreement | OPC UA TCP (opc.tcp://) |
Namespace
#include <darra/opcua/client.hpp> // Session / Variant / DataValue / Subscription
#include <darra/opcua/discovery.hpp> // Discovery::GetEndpoints / FindServers
#include <darra/opcua/history.hpp> // HistoryAggregate / HistoryUpdateType
#include <darra/opcua/well_known_nodes.hpp> // Standard Node Constants
using namespace darra::opcua;
Main Types:
| C++ Types | C# Equivalent | Uses |
|---|---|---|
| darra::opcua::Session | DarraOpcUa | Client Superclass (One Session) |
| darra::opcua::Subscription | OpcUaSubscription | Data Subscription Container |
| darra::opcua::EventSubscription | OpcUaEventSubscription | Event Subscriptions (Alarms & Conditions) |
| darra::opcua::NodeCollection / Node | NodeCollection / OpcUaNode | Lazy Load Node Access |
| darra::opcua::Variant / DataValue | Same Name | Data Encapsulation |
| darra::opcua::Discovery (static) | Same Name | GetEndpoints / FindServers |
| darra::opcua::WellKnownNodes (static) | Same Name | OPC Foundation Standard Node Constants |
| darra::opcua::Exception | OpcUaException | Exceptions associated StatusCode with "carry" |
Quick Start in One Minute
#include <darra/opcua/client.hpp>
#include <iostream>
using namespace darra::opcua;
int main() {
Stack::Init(); // Global Initialization
{
Session s("opc.tcp://localhost:4840"); // RAII, Stack Object
s.Connect();
// Read
auto dv = s.Read("ns=2;s=Temperature");
std::cout << "Temperature = " << dv.Value().AsString() << " degC\n";
// Write
Variant v; v.SetDouble(42.0);
s.Write("ns=2;s=Setpoint", v);
// Subscribe
auto sub = s.CreateSubscription(500.0);
sub.AddNode("ns=2;s=Counter", [](DataValue const& dv) {
std::cout << "Counter = " << dv.Value().AsString() << "\n";
});
} // Session Destruction (Automatic Close)
Stack::Shutdown();
return 0;
}
Session The destructor will be called DarraUa_Session_Close, soFirst, let it finish s its destructor, then Stack::Shutdown(), Do not reverse the order.
Advanced API Overview
| Feature | Entry API | Description |
|---|---|---|
| Connection / Encryption | Session(...) + s.Connect() | None / Sign / SignAndEncrypt + Anonymous / Username |
| Single-Point Read/Write | s.Read / s.Write | Single Node, Single Attribute |
| Batch Read | s.ReadMany(node_ids[, attr]) | Once RPC, N nodes |
| Browse Tree | s.Browse / BrowseMany / BrowseWithPaging / BrowseNext | Full pagination support |
| Path Resolution | s.Resolve / TranslateBrowsePaths | Browse Path → NodeId |
| Registration Node | s.RegisterNodes / UnregisterNodes | The server returns a temporary object with a lifecycle of "Session NodeId." |
| Data Subscriptions | s.CreateSubscription + sub.AddNode / AddMany | publishing / sampling, two-layer |
| Event Subscription | s.SubscribeEvents | Alarms & Conditions |
| Adjustment Methods | s.Call(obj_id, mtd_id, inputs) | OPC UA Method Node |
| History Reading | s.ReadHistory / ReadHistoryModified / AtTime / Processed / Events | 5 Modes |
| History Writing | s.UpdateHistory / DeleteHistoryRange | Insert / Replace / Update / Delete |
| Heartbeat | s.SetKeepAliveInterval(ms) | Background Periodic Monitoring |
| Automatic Reconnection | (Built-in; controlled by ConnectionConfig.auto_reconnect) | Try again after reconnecting TransferSubscriptions; if that fails, clear the local subscription table. |
| Unified Event | s.Events().on_* | Current Automatic Push StateChanged / KeepAlive (two types) + Communication Errors |
| Service Discovery | Discovery::GetEndpoints / FindServers | No session required |
RAII And Exceptions
The C++ SDK makes every resource RAII: stack objects manage their own lifetime, so do not use new — destructors free everything. Errors are uniformly thrown as darra::opcua::Exception, which carries status_code() / status():
try {
Session s("opc.tcp://localhost:4840");
s.Connect();
auto dv = s.Read("ns=2;s=NotExist");
} catch (Exception const& ex) {
std::cerr << "OPC UA error: " << ex.what()
<< " status=0x" << std::hex << ex.status_code() << std::dec << "\n";
if (ex.status() == Status::BadNodeIdUnknown) { /* Processing */ }
}
Move-only semantics
Subscription / EventSubscription / Variant / DataValue Cannot be copied but can be moved (like std::unique_ptr):
auto sub1 = s.CreateSubscription(500.0);
// Subscription sub2 = sub1; // Compilation error: copy constructor deleted
Subscription sub2 = std::move(sub1); // OK, Expires sub1 thereafter
Session Cannot be copied or moved —— It only declares Session(Session const&) = delete and operator=(Session const&) = delete, with no move construct. To transfer a session, use std::unique_ptr<Session> to pass it along.
As a result, the resource will not be released twice.
FileTime Time Arrangement
All History API times are expressed in FileTime (UTC 100ns since 1601-01-01), consistent with Windows DateTime.ToFileTimeUtc():
constexpr int64_t WIN_EPOCH_OFFSET = 116444736000000000LL; // 1601 → 1970 interval
auto now_ns = std::chrono::duration_cast<std::chrono::nanoseconds>(
std::chrono::system_clock::now().time_since_epoch()).count();
int64_t now_ft = WIN_EPOCH_OFFSET + now_ns / 100;
Cross-Language Alignment
The API naming and behavior of the C# SDK are the reference implementation for the other language bindings. The Java, Python, C++, Rust, and C bindings follow their own language conventions, but the semantics are consistent (e.g. C# ua.Read(...) ↔ C++ s.Read(...) ↔ Python ua.read(...)). Start with C#; switching to another language later only requires renaming — the concepts and semantics stay the same.
ButNot every line has the same API shape, C++ has its own limitations (see the respective pages for details):
- The session type in C++ is
darra::opcua::Session, and in C# it isDarraOpcUa - C++ is largelyMethods(
dv.Value()/dv.SourceTimestamp()), not a property field - The state type in C++ is
enum class Status, notStatusCode - C++ does not have
Reconnect(), does not have subscription-based recovery, and does not have subscription EventFilter overloads with DataChangeFilter /
Just read through the left sidebar in order to master everything SDK API.