Connect / Disconnect (C)
사전 읽기
DarraUa_Session_Connect
OPCUA_API DarraUa_Status OPCUA_CALL
DarraUa_Session_Connect(DarraUa_SessionHandle h);
엔드포인트에 대한 연결을 설정합니다. 내부적으로 순차적으로 실행됩니다:
- Hello — BufferSize / MaxMessageSize 협의
- OpenSecureChannel — 협상된 암호화 채널 (None / Sign / SignAndEncrypt); 지정되지 않은 경우,
server_cert_path먼저 None 채널을 한 번 열어 인증서를 탐색한 후, 다시 연결하여 암호화 채널로 업그레이드합니다. - GetEndpoints — PolicyId를 UserTokenPolicy 확인하고, 암호화 모드에서는 서버 인증서도 함께 가져옵니다.
- CreateSession — 세션 생성,
session_timeout_ms요청을 사용하여 SessionTimeout - ActivateSession — 로 활성화 UserToken
- 로드 중 NamespaceArray (
i=2255) - 연결 끊김 감시(watchdog) 스레드 및 자동 재연결 작업 스레드 시작 (
auto_reconnect=1이때만 실제 효과가 나타남)
성공 시:
DarraUa_Session_GetState(h) == UA_SESSION_CONNECTED
| 반환값 | 의미 |
|---|---|
| UA_STATUS_GOOD | 모든 단계가 성공적으로 완료되었습니다. |
| UA_STATUS_BAD_TCP_ENDPOINT_URL_INVALID | endpoint_url이 opc.tcp://로 시작하지 않음 / 호스트 이름이 비어 있음 (URL 해석 단계) |
| UA_STATUS_BAD_TIMEOUT | TCP 체인 생성 시간 초과 (connect_timeout_ms) 또는 특정 작업의 시간 RPC 초과 (request_timeout_ms) |
| UA_STATUS_BAD_COMMUNICATION_ERROR | TCP 연결 실패 / 네트워크 연결 불가 / 통신 중단 |
| UA_STATUS_BAD_CERTIFICATE_INVALID | 클라이언트 PFX 로딩 실패 / 서버 인증서 로딩 실패 |
| UA_STATUS_BAD_IDENTITY_TOKEN_REJECTED | 사용자 이름 / 비밀번호 오류 (서버에서 그대로 반환됨) |
| UA_STATUS_BAD_SECURITY_CHECKS_FAILED | 암호화/서명 계산 또는 검증 실패 |
| UA_STATUS_BAD_SESSION_NOT_ACTIVATED | ActivateSession 서버에서 거부됨 (서버에서 원본 그대로 반환됨) |
예시
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);
수동으로 연결 해제, 핸들 유지 및 재연결 가능. 내부:
- 연결 끊김 감지(watchdog) 스레드 + 자동 재연결 작업 스레드 ( "사용자 측에서 연결 끊음" 플래그 설정, 더 이상 자동 재연결이 트리거되지 않음)
- 중지 AutoPublish (이미 실행 중인 경우)
- CloseSession + CloseSecureChannel
- 상태 콜백 트리거 →
UA_SESSION_CLOSING→UA_SESSION_DISCONNECTED
/* 동일한 핸들을 다시 연결 */
DarraUa_Session_Disconnect(h);
/* ... 업무 대기 중 ... */
DarraUa_Session_Connect(h); /* 동일한 핸들을 사용하여 Connect를 반복할 수 있습니다. */
DarraUa_Session_Close
OPCUA_API DarraUa_Status OPCUA_CALL
DarraUa_Session_Close(DarraUa_SessionHandle h);
핸들을 닫고 해제합니다.. 이후에는 더 이상 사용할 수 h 없습니다. 호출 시 세션이 여전히 연결된 상태라면, 내부적으로 먼저 연결을 끊습니다.
DarraUa_Session_Close(h);
h = UA_INVALID_SESSION_HANDLE; /* 초기화 및 오용 방지 */
자동 재연결
cfg.auto_reconnect = 1 이때, 연결 SDK 끊김 감시(watchdog) 스레드는 수신 SecureChannel 스레드를 감시하며, 소켓 오류로 인해 수신 스레드가 종료된 것을 감지하면 자동 재연결을 트리거합니다:
Connected
↓ (watchdog이 수신 스레드 종료를 감지)
Reconnecting (상태 콜백 RECONNECTING)
↓ (reconnect_delay_ms 간격으로 재시도, 최대 reconnect_max_retries회)
├── 성공 → Connected (구독 자동 복구; 끊김 전에 AutoPublish를 켠 경우 다시 시작)
└── 재시도 소진 → Failed (상태 콜백에 마지막 오류 코드 포함, 핸들 유지)
auto_reconnect = 0 watchdog이 연결 끊김을 감지하면 바로 Failed.로 설정합니다.
재연결 매개변수 조정:
cfg.auto_reconnect = 1;
cfg.reconnect_max_retries = 5;
cfg.reconnect_delay_ms = 3000;
상태 조회
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 열거:
| 값 | 의미 |
|---|---|
| UA_SESSION_DISCONNECTED (0) | 연결되지 않음 / 연결 해제됨 |
| UA_SESSION_CONNECTING (1) | Connect에 접속 중 (Hello / OpenSecureChannel) |
| UA_SESSION_CONNECTED (2) | 연결됨, 정상적으로 읽기/쓰기/구독 가능 |
| UA_SESSION_RECONNECTING (3) | 연결 끊김이 감지되었습니다. 자동 재연결 중입니다. |
| UA_SESSION_CLOSING (4) | 연결 해제 중 / 닫기 중 |
| UA_SESSION_FAILED (5) | 재연결 재시도 횟수 소진(또는 시간 auto_reconnect=0 초과로 인한 연결 끊김)의 최종 상태에서 핸들은 유지되며, 다시 호출할 수 있음 _Connect |
자세한 상태 콜백은 API 참조 이벤트 콜백.
전체 예시
#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));
/* ... 업무 ... */
DarraUa_Session_Disconnect(h);
cleanup:
if (h) DarraUa_Session_Close(h);
DarraUa_Shutdown();
return 0;
}