Session 세션 (C)
C SDK 의 Session은 객체가 아니라, DarraUa_SessionHandle (uint32_t)로 식별되는 내부 컨텍스트입니다. 모든 DarraUa_Session_* 함수의 첫 번째 인수는 이 핸들입니다.
이 선언은 <opcua/opcua_session.h>에 위치하며, 메인 헤더 opcua.h에 이미 포함되어 있습니다.
하위 페이지 이동
- 구조체 필드 및 기본값 설정에 대해서는 다음을 참조하십시오. 구조 및 구성.
- 연결 / 끊기 / 상태 코드에 대해서는 다음을 참조하십시오 Connect / Disconnect.
- 단일 노드 / 일괄 읽기/쓰기에 대해서는 다음을 참조하십시오. Read / Write.
- 상태 변경 콜백에 대해서는 다음을 참조하십시오. 이벤트 콜백.
- 네임스페이스 역조회에 대해서는 다음을 참조하십시오. Namespaces.
- 하트비트 및 세션 유지에 대해서는 다음을 참조하십시오. KeepAlive.
핸들 유형
typedef uint32_t DarraUa_SessionHandle;
#define UA_INVALID_SESSION_HANDLE 0u
0 이는 유효하지 않은 값입니다. 출력 매개변수는 성공 시에만 기록되며, 실패했을 때는 쓰지 않는다 — 호출 측은 먼저 핸들 변수를 UA_INVALID_SESSION_HANDLE로 초기화한 다음, 반환된 DarraUa_Status로 실패 여부를 판단해야 합니다.
공용 구성 필드 (DarraUa_SessionConfig)
| 분류 | 속성 | 유형 | 접근 | 설명 |
|---|---|---|---|---|
| 연결 | endpoint_url | const char* | in | OPC UA 엔드포인트, 예 opc.tcp://host:4840 |
security_mode | DarraUa_MessageSecurityMode | in | None / Sign / SignAndEncrypt | |
security_policy_uri | const char* | in | SecurityPolicy URI (#None / #Basic256Sha256) | |
| 로그인 | user_token_type | DarraUa_UserTokenType | in | Anonymous / Username / Certificate / Issued |
username | const char* | in | user_token_type=USERNAME일 때 사용 | |
password | const char* | in | username과 함께 사용 | |
| 인증서 | client_cert_path | const char* | in | 클라이언트 PFX 경로 (Sign 필수) |
client_key_path | const char* | in | 클라이언트 PFX (PKCS#12) 전체 파일의 비밀번호 — 필드명은 client_key_path이지만, 값은 경로가 아닌 비밀번호입니다. NULL로 두는 것은 비밀번호 없는 PFX에만 성립하며, 비밀번호가 있는 PFX는 NULL로 두면 연결 수립이 바로 실패합니다. 자세한 내용은 [구조 및 구성](./constructors) 참조 | |
server_cert_path | const char* | in | 서버 인증서 PFX (PKCS#12, 비밀번호 없음) 경로 — DER이 아닙니다. 전달하지 않음 = **서버 신원을 검증하지 않음** (TOFU 없음, 지문을 저장하지 않고 대조하지 않음); 로딩 실패 시 WARN만 기록하고 조용히 다운그레이드됩니다. 자세한 내용은 [구조 및 구성](./constructors) 참조 | |
| 타임아웃 | session_timeout_ms | uint32_t | in | 요청된 서버 측 세션 유지 시간, 기본값 60000 (60초) |
connect_timeout_ms | uint32_t | in | 연결 수립 TCP 타임아웃, 기본값 10000 (10초) | |
request_timeout_ms | uint32_t | in | 단일 RPC 타임아웃, 기본값 5000 (5초) | |
keepalive_interval_ms | uint32_t | in | 하트비트 주기, 기본값 10000, 0 = 비활성화 | |
| 재연결 | auto_reconnect | uint32_t | in | 1 = 활성화, 0 = 재연결 안 함 |
reconnect_max_retries | uint32_t | in | 기본값 3 | |
reconnect_delay_ms | uint32_t | in | 기본값 2000 |
반드시 먼저 DarraUa_SessionConfig_Init(&cfg)를 호출하여 모든 필드에 기본값을 채운 다음, 필요한 필드만 덮어쓰십시오.
전체 API 빠른 참조
수명 주기
DarraUa_SessionConfig_Init(&cfg)— 기본값 입력DarraUa_Session_Create(&cfg, &h)— 핸들 생성 (아직 연결되지 않음)DarraUa_Session_Connect(h)— Hello → SecureChannel → Session → ActivateDarraUa_Session_Disconnect(h)— 수동으로 연결 해제, 핸들 유지 시 재연결 가능DarraUa_Session_Close(h)— 핸들을 닫고 해제합니다.
상태
DarraUa_Session_GetState(h)—DarraUa_SessionState열거형을 반환DarraUa_Session_SetStateCallback(h, cb, ctx)— 등록 상태 변경 콜백
읽기 / 쓰기
DarraUa_Session_ReadNode(h, "i=2258", attr, &st)— 문자열 NodeId 단일 노드 읽기DarraUa_Session_Read(h, items, n, out_dvs)— 일괄 읽기 (구조체 배열)DarraUa_Session_ReadNodes(h, ids, attrs, n, out_dvs)— 일괄 읽기 (문자열 배열)DarraUa_Session_WriteNode(h, "ns=2;s=X", attr, v)— 문자열 NodeId 단일 노드 쓰기DarraUa_Session_Write(h, items, n, out_results)— 일괄 작성
탐색 / 경로 분석
DarraUa_Session_BrowseNode(h, "i=84", filter, &res)— 단일 노드 (문자열)DarraUa_Session_Browse(h, &node_id, filter, &res)— 단일 노드 (구조체)DarraUa_Session_BrowseNodes(h, ids, n, filter, results)— 일괄 열람DarraUa_Session_BrowseNext(h, release, cp, cp_len, &res)— 다음 페이지로 넘어가기DarraUa_Session_TranslateBrowsePaths(h, ...)— 경로 일괄 분석DarraUa_Session_ResolveBrowsePath(h, start, path, buf, bufSz)— 단일 상대 경로 분석DarraUa_Session_RegisterNodes(h, ids, n, &out)— 임시 등록, 높은 효율 NodeIdDarraUa_Session_UnregisterNodes(h, ids, n)— 해지
네임스페이스
DarraUa_Session_LoadNamespaceArray(h)— 강제 재읽기 i=2255DarraUa_Session_GetNamespaceCount(h)— 네임스페이스 수DarraUa_Session_GetNamespaceUri(h, idx)— URI 조회DarraUa_Session_FindNamespaceIndex(h, uri)— 역조회 URI → 색인
구독하기
DarraUa_Subscription_Create(h, &cfg, &sub)— 데이터 구독 생성DarraUa_Session_Publish(h, timeout_ms)— 수동 펌프DarraUa_Session_StartAutoPublish(h)/_Stop— 백엔드 발행 스레드DarraUa_Session_TransferSubscriptions(...)— 세션 간 구독 이전
방법 / 이력
DarraUa_Session_Call(h, &obj, &method, args, n, &out, &nout, &st)— Call OPC UA MethodDarraUa_Session_HistoryRead*(...)— 5가지 모드 HistoryReadDarraUa_Session_HistoryUpdateData / HistoryDeleteRange— 기록 작성 / 삭제
제어
DarraUa_Session_Cancel(h, request_handle, &cancelled_count)— 완료되지 않은 요청 취소
상태 기계
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;
호출 흐름:
Disconnected
↓ Session_Connect
Connecting
↓
Connected
↓ (네트워크 예외 + auto_reconnect=1)
Reconnecting
├── 성공 → Connected
└── 재시도 소진 → Failed (종료 상태, 핸들 유지; 이후 _Close 호출 시에만 → Closing → Disconnected)
전체 예시
#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;
}