Darra OPC UA Client — C SDK
Darra OPC UA Client 프로토콜 스택의 최하층에 위치한 대외 인터페이스이며, C#, Java, Python, C++, Rust 등 다섯 가지 언어 바인딩의 공통 기반이기도 합니다. 다른 언어와 달리, C 사용자에게는 래퍼 클래스가 없습니다. — #include <opcua/opcua.h>만으로 DarraUa_* 시리즈 C ABI 함수를 직접 호출하면 됩니다.
- 시작하기 → Session 세션 (생성 / 연결 / 읽기 / 쓰기 / KeepAlive)
- 보기 → Nodes 노드 (Browse / 경로 분석 / RegisterNodes)
- 실시간 → 구독 (Subscription_Create / MonitoredItem / DataChange)
- 이력 → History 이력 (Raw / Modified / AtTime / Processed / Events / Update / Delete)
- 호출 → Method 방법 (Session_Call)
- 찾기 → 디스커버리 (Discovery_GetEndpoints / FindServers)
- 데이터 → Data Types (Variant / DataValue / WellKnownNodes)
- 보안 → Security (인증서 / 암호화)
설치
- CMake (권장)
- MSVC 한 줄 컴파일
- GCC / Clang
cmake_minimum_required(VERSION 3.16)
project(my_opcua_app C)
set(SDK_ROOT "/path/to/darra_opcua_c")
add_executable(my_app main.c)
target_include_directories(my_app PRIVATE "${SDK_ROOT}/include")
target_link_directories(my_app PRIVATE "${SDK_ROOT}/build")
target_link_libraries(my_app PRIVATE Darra.OpcUa.Core)
cl /utf-8 /I<sdk>\include main.c /link <sdk>\build\Darra.OpcUa.Core.lib
gcc -I<sdk>/include main.c -L<sdk>/build -lDarra.OpcUa.Core -o my_app
시스템 요구 사항
| 항목 | 요구 사항 |
|---|---|
| 운영 체제 | Windows 10/11 x64 |
| 플랫폼 | x64 |
| 협정 | OPC UA TCP (opc.tcp://) |
| 라이브러리 | Darra.OpcUa.Core.dll |
헤더 파일
프로토콜 스택의 메인 ABI 엔트리는 이며 <opcua/opcua.h>, 여기에는 이미 status / types / session / subscribe 하위 헤더가 포함되어 있습니다. 이력 및 이벤트 구독은 필요에 따라 추가됩니다:
#include <opcua/opcua.h> /* Session + Browse + Subscription */
#include <opcua/opcua_history.h> /* HistoryRead / HistoryUpdate */
#include <opcua/opcua_event.h> /* 이벤트 구독 (알람 및 조건) */
C SDK 또 다른 확장 모듈 통합 진입점이 하나 더 있는데 <opcua_sdk.h>, 한 줄로 11개의 확장 모듈을 모두 불러올 수 있습니다(각 모듈을 개별적으로 포함시킬 수도 있습니다):
| 모듈 | 헤더 파일 | 용도 |
|---|---|---|
| Safe API | opcua_safe.h | BrowseSafe / ReadSafe / WriteSafe / CallSafe / ReadHistorySafe |
| Filter | opcua_filter.h | DataChangeFilter / EventFilter / Triggering |
| NodeId 강타입 | opcua_node_id.h | OwnedNodeId + Parse / ToString / Well-Known |
| NumericRange | opcua_numeric_range.h | NumericRange + ReadRange / WriteRange |
| ServerInfo | opcua_server_info.h | ServerStatus + BuildInfo |
| BrowseCrawler | opcua_browse_crawler.h | Browse 전체 트리 크롤링 (콜백 방식) |
| MethodBuilder | opcua_method_builder.h | Method 스트림 생성자 호출 |
| HistoryStream | opcua_history_stream.h | 이력 페이지 이터레이터 |
| FileTransfer | opcua_file_transfer.h | FileType 클라이언트 |
| Alarm | opcua_alarm.h | Alarms & Conditions (10 Method) |
| StructDecoder | opcua_struct_decoder.h | Variant ExtensionObject 디코딩 |
주요 유형:
| 유형 | 용도 |
|---|---|
| DarraUa_SessionHandle | 세션 핸들 (uint32_t, 0 = 유효하지 않음) |
| DarraUa_SubscriptionHandle | 구독 핸들 |
| DarraUa_MonitoredItemHandle | MonitoredItem 핸들 |
| DarraUa_Variant* | 범용 값 컨테이너 (opaque) |
| DarraUa_DataValue* | Read가 반환하는 전체 값 (opaque) |
| DarraUa_BrowseResult* | Browse 반환된 자식 노드 목록 (opaque) |
| DarraUa_Status | StatusCode (uint32_t, 0 = Good) |
| DarraUa_NodeClass / DarraUa_AttributeId | OPC UA 열거 |
지연
demo에서 대기 처리 시 를 <windows.h> 직접 사용합니다 Sleep(ms):
#include <windows.h>
#define OPCUA_SLEEP_MS(ms) Sleep(ms)
#define OPCUA_SLEEP_SEC(s) Sleep((s) * 1000)
일분 만에 빠르게 시작하기
#include <opcua/opcua.h>
#include <stdio.h>
int main(int argc, char** argv)
{
const char* endpoint = (argc >= 2) ? argv[1] : "opc.tcp://localhost:4840";
/* 1. 라이브러리 초기화 */
DarraUa_Initialize();
/* 2. 구성 + 세션 생성 */
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;
DarraUa_Session_Create(&cfg, &h);
DarraUa_Session_Connect(h);
/* 3. 읽기 ServerStatus.CurrentTime */
DarraUa_Status st = 0;
DarraUa_DataValue* dv = DarraUa_Session_ReadNode(
h, "i=2258", UA_ATTR_VALUE, &st);
if (dv && UA_STATUS_IS_GOOD(st)) {
const DarraUa_Variant* v = DarraUa_DataValue_GetValue(dv);
DarraUa_DateTime ft = DarraUa_Variant_GetDateTime(v);
printf("CurrentTime ft=%lld\n", (long long)ft);
DarraUa_DataValue_Delete(dv);
}
/* 4. 역방향 청소 */
DarraUa_Session_Disconnect(h);
DarraUa_Session_Close(h);
DarraUa_Shutdown();
return 0;
}
고급 API 개요
| 기능 | 엔트리 API | 설명 |
|---|---|---|
| 라이브러리 초기화 / 제거 | DarraUa_Initialize / DarraUa_Shutdown | 프로세스 수준, 내부 참조 카운트 |
| 세션 생성 | DarraUa_Session_Create(&cfg, &h) | 연결하지 않음 |
| 연결 / 끊기 | DarraUa_Session_Connect / Disconnect / Close | None / Sign / SignAndEncrypt + Anonymous / Username |
| 단일 지점 읽기/쓰기 | DarraUa_Session_ReadNode / WriteNode | 문자열 NodeId 편리함 API |
| 일괄 읽기 | DarraUa_Session_ReadNodes / Read | 한 번의 RPC, N개 노드 |
| 열람 | DarraUa_Session_BrowseNode / Browse / BrowseNodes / BrowseNext | 페이지 나누기 기능 지원 |
| 경로 분석 | DarraUa_Session_TranslateBrowsePaths / ResolveBrowsePath | 탐색 경로 → NodeId |
| 등록 노드 | DarraUa_Session_RegisterNodes / UnregisterNodes | 동일한 노드에 고주파로 반복적으로 접속할 때 서버 측 해석 부하를 줄입니다 (이득은 서버 측 실제 테스트 결과에 따름). |
| 데이터 구독 | DarraUa_Subscription_Create + _AddNode / _AddNodes | 발행 / 샘플링 이중 구조 |
| 이벤트 구독 | DarraUa_Subscription_AddEventItem (opcua_event.h) | 알람 및 조건 |
| 조정 방법 | DarraUa_Session_Call(...) | OPC UA Method 노드 |
| 이력 읽기 | DarraUa_Session_HistoryReadRaw / DarraUa_Session_HistoryReadModified / DarraUa_Session_HistoryReadAtTime / DarraUa_Session_HistoryReadProcessed / DarraUa_Session_HistoryReadEvents | 5가지 모드 |
| 이력 쓰기 | DarraUa_Session_HistoryUpdateData / DarraUa_Session_HistoryDeleteRange | Insert / Replace / Update / Remove |
| 하트비트 | cfg.keepalive_interval_ms | 백그라운드 주기적 감지 |
| 자동 재연결 | cfg.auto_reconnect = 1 | 연결 끊김 감지 → 재연결 |
| 서비스 탐색 | DarraUa_Discovery_GetEndpoints / DarraUa_Discovery_FindServers | 세션이 필요하지 않습니다 |
| 네임스페이스 | DarraUa_Session_GetNamespaceUri / FindNamespaceIndex | ns 드리프트 방지 |
메모리 소유권
C에는 RAII / 가 없으므로 GC, 모든 "힙 객체 반환"은 해당 메서드를 호출해야 합니다 API _Delete. 할당하는 쪽에서 해제해야 하며, Stack이 할당한 객체는 Stack이 제공하는 해제 _Delete 기능을 사용해야 합니다. 절대로 혼용해서는 안 됩니다. free() (크로스 호환성 문제가 발생하면 프로그램이 DLL CRT 중단됩니다).
| 배분 | 해방 |
|---|---|
| DarraUa_Variant_New() | DarraUa_Variant_Delete(v) |
| DarraUa_Session_ReadNode(...) | DarraUa_DataValue_Delete(dv) |
| DarraUa_Session_BrowseNode(...) | DarraUa_BrowseResult_Delete(br) |
| DarraUa_Session_HistoryReadRaw(...) | DarraUa_DataValueArray_Delete(arr, count) |
| DarraUa_Session_HistoryReadEvents(...) | DarraUa_EventArray_Delete(arr, count) |
| DarraUa_Session_Call(...) | DarraUa_VariantArray_Delete(arr, count) |
| DarraUa_Discovery_GetEndpoints(...) | DarraUa_GetEndpointsResult_Delete(r) |
| DarraUa_Session_TranslateBrowsePaths(...) 항목 | DarraUa_Free(out_node_ids[i]) |
| Stack 내부의 malloc이 생성하는 "네이키드 버퍼" | DarraUa_Free(p) |
핸들(uint32_t)은 스택 풀에서 관리되므로, 다음을 수행하지 마십시오 free():
| 핸들 | 닫기 |
|---|---|
| DarraUa_SessionHandle | DarraUa_Session_Close(h) |
| DarraUa_SubscriptionHandle | DarraUa_Subscription_Delete(sub) |
| DarraUa_MonitoredItemHandle | DarraUa_MonitoredItem_Delete(sub, mi) |
오류 처리 템플릿
C: 오류가 없으며, 각각 API 다음과 같이 반환됩니다 DarraUa_Status:
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));
/* cleanup으로 이동, 레이블로 이동 */
}
스레드 모델과 콜백
- 콜백은 Stack의 내부 스레드(DLL 내부 스레드 풀)에 의해 트리거되며, 호출 스레드와는 다릅니다.
- 수동 펌프 모드(설정
DarraUa_Session_Publish)에서, 콜백은 Publish를 호출한 스레드에서 트리거됩니다. - SDK 백그라운드 스레드가 지속적으로 발행하도록
DarraUa_Session_StartAutoPublish(h)설정 - 동일한 세션 내의 동시 호출은 호출 측에서 직접 순차화해야 합니다. 내부 잠금은 요청 핸들 카운트와 구독 테이블만 보호하며, Read / Write / Browse 등의 요청 경로에는 적용되지 않습니다.
- 콜백 내에서 스레드 간 공유 데이터에 접근할 때는 반드시 잠금을 걸거나 원자적 연산을 사용해야 하며, 장시간 계산이나 차단 작업을 수행해서는 안 됩니다. IO
언어 간 정렬
C SDK 노출된 함수와 C# SDK 일대일 대응: C#은 C와 동등합니다 ua.Read("ns=2;s=X") DarraUa_Session_ReadNode(handle, "ns=2;s=X", attr, &status). 개념적 내용(프로토콜/동작)에 대해서는 C# 문서를 우선적으로 참조하시기 바랍니다. C 문서는 C 고유의 메모리 소유권과 콜백 스레드 의미론만을 강조합니다.
| 작업 | C# (DarraOpcUa) | C |
|---|---|---|
| 큐 초기화 | (암시적) | DarraUa_Initialize() |
| 세션 생성 | new DarraOpcUa(url) | DarraUa_Session_Create(&cfg, &h) |
| 연결 | ua.Connect() | DarraUa_Session_Connect(h) |
| 단일 노드 읽기 | ua.Read("i=2258") | DarraUa_Session_ReadNode(h, "i=2258", attr, &st) |
| 주문 작성 노드 | ua.Write(id, v) | DarraUa_Session_WriteNode(h, id, attr, v) |
| 열람 | ua.Browse("i=84") | DarraUa_Session_BrowseNode(h, "i=84", filter, &res) |
| 구독 생성 | ua.CreateSubscription(500) | DarraUa_Subscription_Create(h, &cfg, &sub) |
| 노드 하나 구독하기 | sub.Add("i=2258") | DarraUa_Subscription_AddNode(sub, "i=2258", attr, smpl, cb, ctx, &mi) |
| Pump | ua.Publish(2000) | DarraUa_Session_Publish(h, 2000) |
| 파기 | using var ua | DarraUa_Session_Close(h) |
왼쪽 사이드바의 순서대로 읽어 나가면 모든 내용을 파악할 수 있습니다 C ABI.