Skip to main content

Connect / Disconnect (C)

Prerequisite Reading

DarraUa_Session_Connect​

OPCUA_API DarraUa_Status OPCUA_CALL
DarraUa_Session_Connect(DarraUa_SessionHandle h);

Establish a connection to the endpoint. Internal serial execution:

  1. Hello — Negotiate BufferSize / MaxMessageSize
  2. OpenSecureChannel — Negotiate an encrypted channel (None / Sign / SignAndEncrypt); if not specified, first open server_cert_path a "None" channel for certificate discovery, then reconnect and upgrade to an encrypted channel
  3. GetEndpoints — Retrieve the UserTokenPolicy PolicyId and, in encrypted mode, also retrieve the server certificate
  4. CreateSession — Create a session using a request session_timeout_ms SessionTimeout
  5. ActivateSession — Activate UserToken with
  6. Loading NamespaceArray (i=2255)
  7. Start the connection-loss watchdog thread + automatically reconnect the worker thread (auto_reconnect=1 this only takes effect when ...)

After successful completion:

  • DarraUa_Session_GetState(h) == UA_SESSION_CONNECTED
ReturnMeaning
UA_STATUS_GOODAll steps were successful
UA_STATUS_BAD_TCP_ENDPOINT_URL_INVALIDendpoint_url does not start with opc.tcp:// / hostname is empty (URL during resolution)
UA_STATUS_BAD_TIMEOUTTCP Connection establishment timeout (connect_timeout_ms) or a specific RPC timeout (request_timeout_ms)
UA_STATUS_BAD_COMMUNICATION_ERRORTCP Connection Failed / Network Unreachable / Communication Interrupted
UA_STATUS_BAD_CERTIFICATE_INVALIDClient Failed to load PFX / Failed to load server certificate
UA_STATUS_BAD_IDENTITY_TOKEN_REJECTEDIncorrect username / password (returned as-is by the server)
UA_STATUS_BAD_SECURITY_CHECKS_FAILEDEncryption/signature calculation or verification failed
UA_STATUS_BAD_SESSION_NOT_ACTIVATEDActivateSession Rejected by the server (the server returned the request as-is)

Examples​

DarraUa_Status st = DarraUa_Session_Connect(h);
if (!UA_STATUS_IS_GOOD(st)) {
fprintf(stderr, "Connect failed: 0x%08X (%s)\n",
(unsigned)st, DarraUa_StatusName(st));
DarraUa_Session_Close(h);
return -1;
}
printf("Connected, state = %d\n", (int)DarraUa_Session_GetState(h));

DarraUa_Session_Disconnect​

OPCUA_API DarraUa_Status OPCUA_CALL
DarraUa_Session_Disconnect(DarraUa_SessionHandle h);

Proactive disconnection, Handle Retention and Reconnection. Inside:

  1. Disconnection Watchdog Thread + Automatic Reconnection Work Thread (Sets the "User-Initiated Disconnection" flag; automatic reconnection is no longer triggered)
  2. Stop AutoPublish (if already running)
  3. CloseSession + CloseSecureChannel
  4. Trigger status callback → UA_SESSION_CLOSING → UA_SESSION_DISCONNECTED
/* Reconnect to the same handle */
DarraUa_Session_Disconnect(h);
/* ... Waiting for a transaction ... */
DarraUa_Session_Connect(h); /* The same handle can be used to call `Connect` multiple times */

DarraUa_Session_Close​

OPCUA_API DarraUa_Status OPCUA_CALL
DarraUa_Session_Close(DarraUa_SessionHandle h);

Close and release the handle. After that, h is no longer available. If the session is still Connected when the method is called, it is disconnected internally first.

DarraUa_Session_Close(h);
h = UA_INVALID_SESSION_HANDLE; /* Reset to Prevent Misuse */

Automatic Reconnection​

cfg.auto_reconnect = 1 At that time, the SDK disconnect watchdog thread monitors the receiving SecureChannel thread; as soon as it detects that the receiving thread has exited due to a socket error, it triggers an automatic reconnection:

Connected
↓ (watchdog detects the receiving thread has exited)
Reconnecting (state callback RECONNECTING)
↓ (retries at reconnect_delay_ms intervals, up to reconnect_max_retries times)
├── Success → Connected (subscriptions auto-restored; AutoPublish restarts if it was enabled before the drop)
└── Retries exhausted → Failed (state callback carries the last error code; handle is kept)

auto_reconnect = 0 When the watchdog detects a disconnection, it immediately sets Failed.

Adjust the reconnection parameters:

cfg.auto_reconnect        = 1;
cfg.reconnect_max_retries = 5;
cfg.reconnect_delay_ms = 3000;

Status Inquiry​

OPCUA_API DarraUa_SessionState OPCUA_CALL
DarraUa_Session_GetState(DarraUa_SessionHandle h);
DarraUa_SessionState s = DarraUa_Session_GetState(h);
int connected = (s == UA_SESSION_CONNECTED);

DarraUa_SessionState Enumeration:

ValueMeaning
UA_SESSION_DISCONNECTED (0)Not connected / Disconnected
UA_SESSION_CONNECTING (1)Currently on Connect (Hello / OpenSecureChannel)
UA_SESSION_CONNECTED (2)Connected; Read, Write, and Subscribe functions are working normally.
UA_SESSION_RECONNECTING (3)A disconnection has been detected; automatically reconnecting
UA_SESSION_CLOSING (4)Disconnecting / Closing
UA_SESSION_FAILED (5)In the final state where reconnection retries have been exhausted (or a disconnection auto_reconnect=0 is detected), the handle is retained and can be called again. _Connect

For detailed status callbacks, see API Event Callbacks.

Complete Example​

#include <opcua/opcua.h>
#include <stdio.h>

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;
cfg.auto_reconnect = 1;

DarraUa_SessionHandle h = UA_INVALID_SESSION_HANDLE;
DarraUa_Status st = DarraUa_Session_Create(&cfg, &h);
if (!UA_STATUS_IS_GOOD(st)) goto cleanup;

st = DarraUa_Session_Connect(h);
if (!UA_STATUS_IS_GOOD(st)) {
fprintf(stderr, "Connect failed: 0x%08X (%s)\n",
(unsigned)st, DarraUa_StatusName(st));
goto cleanup;
}
printf("State = %d\n", (int)DarraUa_Session_GetState(h));

/* ... Business ... */

DarraUa_Session_Disconnect(h);

cleanup:
if (h) DarraUa_Session_Close(h);
DarraUa_Shutdown();
return 0;
}

Next Step​