Session (C)
In the C SDK, a Session is not an object but an internal context identified by DarraUa_SessionHandle (uint32_t). The first argument of every DarraUa_Session_* function is this handle.
The declaration lives in <opcua/opcua_session.h>, which is already pulled in by the main header opcua.h.
Subpage Redirect
- For information on configuring struct fields and default values, please refer to Structure and Configuration.
- For information on establishing a connection, disconnecting, and status codes, please refer to Connect / Disconnect.
- For single-node / batch read/write operations, please refer to Read / Write.
- For status change callbacks, please refer to Event Callbacks.
- For namespace lookup, please refer to Namespaces.
- For information on heartbeat and session keep-alive, please refer to KeepAlive.
Handle Type
typedef uint32_t DarraUa_SessionHandle;
#define UA_INVALID_SESSION_HANDLE 0u
0 This is an invalid value. Output parameters are written only when the operation is successful, Don't write when you fail — The caller must first initialize the handle variable to UA_INVALID_SESSION_HANDLE, and then use the returned value to check DarraUa_Status for failure.
Public Configuration Fields (DarraUa_SessionConfig)
| Category | Property | Type | Access | Description |
|---|---|---|---|---|
| Connections | endpoint_url | const char* | in | OPC UA endpoint, such as opc.tcp://host:4840 |
security_mode | DarraUa_MessageSecurityMode | in | None / Sign / SignAndEncrypt | |
security_policy_uri | const char* | in | SecurityPolicy URI (#None / #Basic256Sha256) | |
| Login | user_token_type | DarraUa_UserTokenType | in | Anonymous / Username / Certificate / Issued |
username | const char* | in | Used when user_token_type=USERNAME | |
password | const char* | in | Used with username | |
| Certificates | client_cert_path | const char* | in | Client PFX path (required for Sign) |
client_key_path | const char* | in | Password for the entire client PFX (PKCS#12) file — the field name is client_key_path, and the value is the password, not the path. Leaving it as NULL is valid only for a passwordless PFX; for a PFX with a password, leaving it as NULL will make connection setup fail immediately. For details, see [Structure and Configuration](./constructors) | |
server_cert_path | const char* | in | Path to the server certificate PFX (PKCS#12, passwordless) — Not DER. If not provided = **Do not verify the server's identity** (None TOFU, no fingerprints to compare); If loading fails, it silently downgrades with only a WARN message; see [Structure and Configuration](./constructors) | |
| Timeout | session_timeout_ms | uint32_t | in | Server-side session timeout duration; default is 60,000 (60 seconds) |
connect_timeout_ms | uint32_t | in | Connection establishment TCP timeout; default is 10,000 (10 seconds) | |
request_timeout_ms | uint32_t | in | Single RPC timeout, default 5000 (5 seconds) | |
keepalive_interval_ms | uint32_t | in | Keep-alive interval, default 10000, 0 = disabled | |
| Reconnect | auto_reconnect | uint32_t | in | 1 = Enabled, 0 = Do not reconnect |
reconnect_max_retries | uint32_t | in | Default: 3 | |
reconnect_delay_ms | uint32_t | in | Default: 2000 |
Be sure to first DarraUa_SessionConfig_Init(&cfg) set all fields to their default values, then override the fields as needed.
Complete API Quick Reference
Life Cycle
DarraUa_SessionConfig_Init(&cfg)— Fill in the default valuesDarraUa_Session_Create(&cfg, &h)— Create a handle (not yet connected)DarraUa_Session_Connect(h)— Hello → SecureChannel → Session → ActivateDarraUa_Session_Disconnect(h)— Disconnected by the user; the handle is retained and can be reconnectedDarraUa_Session_Close(h)— Close and release the handle
Status
DarraUa_Session_GetState(h)— Returns theDarraUa_SessionStateenumerationDarraUa_Session_SetStateCallback(h, cb, ctx)— Registration Status Change Callback
Read / Write
DarraUa_Session_ReadNode(h, "i=2258", attr, &st)— String NodeId Single-node readDarraUa_Session_Read(h, items, n, out_dvs)— Bulk Read (Array of Structures)DarraUa_Session_ReadNodes(h, ids, attrs, n, out_dvs)— Bulk Read (String Array)DarraUa_Session_WriteNode(h, "ns=2;s=X", attr, v)— String NodeId Single-node writeDarraUa_Session_Write(h, items, n, out_results)— Write in Bulk
Browsing / Path Resolution
DarraUa_Session_BrowseNode(h, "i=84", filter, &res)— Single node (string)DarraUa_Session_Browse(h, &node_id, filter, &res)— Single Node (Structure)DarraUa_Session_BrowseNodes(h, ids, n, filter, results)— Batch ViewDarraUa_Session_BrowseNext(h, release, cp, cp_len, &res)— Continue to the next pageDarraUa_Session_TranslateBrowsePaths(h, ...)— Batch Path ParsingDarraUa_Session_ResolveBrowsePath(h, start, path, buf, bufSz)— Parsing a Single Relative PathDarraUa_Session_RegisterNodes(h, ids, n, &out)— Register for a Temporary High-Efficiency Plan NodeIdDarraUa_Session_UnregisterNodes(h, ids, n)— Unsubscribe
Namespace
DarraUa_Session_LoadNamespaceArray(h)— Force re-read i=2255DarraUa_Session_GetNamespaceCount(h)— Number of namespacesDarraUa_Session_GetNamespaceUri(h, idx)— URI SearchDarraUa_Session_FindNamespaceIndex(h, uri)— Reverse Lookup URI → Index
Subscribe
DarraUa_Subscription_Create(h, &cfg, &sub)— Create a data subscriptionDarraUa_Session_Publish(h, timeout_ms)— Manual PumpDarraUa_Session_StartAutoPublish(h)/_Stop— Background Publish ThreadDarraUa_Session_TransferSubscriptions(...)— Migrating Subscriptions Across Sessions
Methods / History
DarraUa_Session_Call(h, &obj, &method, args, n, &out, &nout, &st)— Call OPC UA MethodDarraUa_Session_HistoryRead*(...)— 5 Modes HistoryReadDarraUa_Session_HistoryUpdateData / HistoryDeleteRange— Write / Delete History
Control
DarraUa_Session_Cancel(h, request_handle, &cancelled_count)— Cancel Unfinished Requests
State Machine
typedef enum {
UA_SESSION_DISCONNECTED = 0,
UA_SESSION_CONNECTING = 1,
UA_SESSION_CONNECTED = 2,
UA_SESSION_RECONNECTING = 3,
UA_SESSION_CLOSING = 4,
UA_SESSION_FAILED = 5
} DarraUa_SessionState;
Call Flow:
Disconnected
↓ Session_Connect
Connecting
↓
Connected
↓ (network error + auto_reconnect=1)
Reconnecting
├── Success → Connected
└── Retries exhausted → Failed (terminal state, handle kept; only a later _Close call moves it → Closing → Disconnected)
Complete Example
#include <opcua/opcua.h>
#include <stdio.h>
#if defined(_WIN32)
# include <windows.h>
# define OPCUA_SLEEP_SEC(s) Sleep((s) * 1000)
#else
# include <unistd.h>
# define OPCUA_SLEEP_SEC(s) sleep(s)
#endif
static void on_state(DarraUa_SessionHandle h, DarraUa_SessionState st,
DarraUa_Status code, void* ctx)
{
(void)h; (void)ctx;
printf("Session state -> %d (status 0x%08X)\n", (int)st, (unsigned)code);
}
int main(int argc, char** argv)
{
const char* endpoint = (argc >= 2) ? argv[1] : "opc.tcp://localhost:4840";
DarraUa_Initialize();
DarraUa_SessionConfig cfg;
DarraUa_SessionConfig_Init(&cfg);
cfg.endpoint_url = endpoint;
cfg.security_mode = UA_MSG_SECURITY_MODE_NONE;
cfg.security_policy_uri = "http://opcfoundation.org/UA/SecurityPolicy#None";
cfg.user_token_type = UA_USER_TOKEN_ANONYMOUS;
DarraUa_SessionHandle h = UA_INVALID_SESSION_HANDLE;
if (!UA_STATUS_IS_GOOD(DarraUa_Session_Create(&cfg, &h))) goto cleanup;
DarraUa_Session_SetStateCallback(h, on_state, NULL);
if (!UA_STATUS_IS_GOOD(DarraUa_Session_Connect(h))) goto cleanup;
/* Read */
DarraUa_Status st = 0;
DarraUa_DataValue* dv = DarraUa_Session_ReadNode(
h, "i=2258", UA_ATTR_VALUE, &st);
if (dv) {
DarraUa_DateTime ft = DarraUa_Variant_GetDateTime(
DarraUa_DataValue_GetValue(dv));
printf("CurrentTime ft=%lld\n", (long long)ft);
DarraUa_DataValue_Delete(dv);
}
cleanup:
if (h) {
DarraUa_Session_Disconnect(h);
DarraUa_Session_Close(h);
}
DarraUa_Shutdown();
return 0;
}