본문으로 건너뛰기

구조체 디코딩

개요​

OPC UA 1.04+ 각 사용자 정의 구조체의 필드 정의를 DataType 노드의 DataTypeDefinition 속성 (AttributeId=27, Part 5 §6.4.2)에 넣습니다.StructDecoder 서버에서 제공한 StructureDefinition 를 사용하여 ExtensionObject 의 UA Binary 바이트 스트림(Part 6 §5.2)을 필드 딕셔너리로 역직렬화합니다. 해석 가능한 내장 함수의 범위와 제한 사항은 아래 「구현 제한」을 참조하십시오.

API​

StructDecoder 는 darra::opcua 네임스페이스 아래의 클래스이며, 헤더 파일은 darra/opcua/struct_decoder.hpp. 디코딩 결과는 std::unordered_map<std::string, std::any> 필드 사전 — 없음DynamicExtensionObject 이러한 유형의 패키징에서 필드 이름은 map의 .입니다 operator[].

구성원분류읽기 및 쓰기설명
StructDecoder(Session& ua)구조—세션에 바인딩 (explicit)
decoder.Decode(variant)방법읽기std::unordered_map<std::string, std::any> 반환
decoder.DecodeBody(body, data_type_node_id)방법읽기body 바이트 스트림이 주어졌을 때 직접 디코딩 DataType NodeId
decoder.ClearCache()방법쓰기DataTypeDefinition 캐시 지우기
decoder.CachedDefinitionCount()방법읽기캐시된 정의 수
map[key]목차읽기필드 가져오기, 값은 std::any
StructDecoder::kStatusKey상수—"_status" — 디코딩 실패 / 자리 표시자 결과의 키
StructDecoder::kTypeIdKey상수—"_typeId" — TypeId가 포함된 키에 자리 표시자 결과를 저장합니다.
StructDecoder::kAttrDataTypeDefinition상수—27 — DataTypeDefinition의 AttributeId

관련 구조 (StructureKind, Part 3 §8.49 StructureType):

  • 구조 (0) — 일반
  • StructureWithSubtypedValues (1) — 하위 유형 포함
  • StructureWithOptionalFields (2) — 선택적 필드 포함 (선행 EncodingMask)
  • Union (3) — Union (선행 선택자)
  • UnionWithSubtypedValues (4) — Union + 하위 유형

코드 예시​

#include <darra/opcua/struct_decoder.hpp>
#include <any>
#include <iostream>
using namespace darra::opcua;

Stack::Init();
Session s("opc.tcp://localhost:4840");
s.Connect();

StructDecoder dec(s);

// 1) 사용자 정의 구조 읽기 — Decode에서 DataValue 내의 Variant
auto dv = s.Read("ns=2;s=Robot.CurrentPose");
auto pose = dec.Decode(dv.Value()); // std::unordered_map<std::string, std::any>

std::cout << "x = " << std::any_cast<double>(pose["X"]) << "\n";
std::cout << "y = " << std::any_cast<double>(pose["Y"]) << "\n";

// 2) 전체 필드 순회 — 결과는 map이며, 직접 반복 처리
for (auto& [name, value] : pose)
std::cout << name << "\n";

// 3) 중첩 구조체 필드의 값은 std::unordered_map<std::string, std::any>입니다.
auto quat = std::any_cast<std::unordered_map<std::string, std::any>>(pose["Quaternion"]);
std::cout << "qw = " << std::any_cast<double>(quat["W"]) << "\n";

// 4) 배열 필드의 값은 std::vector<std::any>입니다.
auto arr = std::any_cast<std::vector<std::any>>(pose["JointAngles"]);
for (auto& a : arr)
std::cout << std::any_cast<double>(a) << "\n";

// 5) 다른 경로를 통해 이미 EO body를 확보한 경우에는 바로 해독한다
std::vector<uint8_t> body = /* ... */;
auto manual = dec.DecodeBody(body, "ns=2;i=3001");

구현상의 제약​

  • ExtensionObject 바이트를 가져올 수 없는 경우, Decode(Variant)는 _status 필드가 포함된 부분 결과를 반환합니다.
  • 원본 바이트가 이미 있는 경우 DecodeBody(bytes, type_id)를 사용하여 직접 디코딩합니다.
  • 필드 정의는 에서 가져왔으며 LoadDefinition, 이 캐시는 현재 연결되어 있지 않아(항상 반환됨 nullptr) 현재 단계에서는 빈 맵을 DecodeBody 반환합니다. 캐시가 연결되면 서명은 변하지 않습니다.
  • Builtin에서 재정의되지 않은 유형(예: DiagnosticInfo, i=25)은 예외를 발생시키며 std::runtime_error("Builtin type not implemented in StructDecoder"), 묵인 처리되지 않습니다.

모범 사례​

  • 디코더를 공유하여, 동일한 서버 및 유형에 대한 정의는 한 번만 로드됩니다.
  • 서버 측에서 정의를 DataType 수정한 후 호출하고, 다시 ClearCache() 디코딩합니다.
  • 중첩 구조의 값은 map이며, 를 사용하여 std::any_cast<std::unordered_map<std::string, std::any>> 추출한 후 접근합니다.
  • Union에서 selector 확인: 디코딩 후 필드가 하나만 남으면, 필드명을 기준으로 어떤 항목이 선택되었는지 판단한다.

다국어 대조​

C#PythonJavaC++RustC
StructDecoderStructDecoderStructDecoderStructDecoderStructDecoderDarraUa_StructDecoderHandle
DecodedecodedecodeDecodedecodeDarraUa_StructDecoder_Decode
DecodeBodydecode_bodydecodeBodyDecodeBodydecode_bodyDarraUa_StructDecoder_DecodeBody
ClearCacheclear_cache—ClearCacheclear_cacheDarraUa_StructDecoder_ClearCache
CachedDefinitionCountcached_definition_count—CachedDefinitionCountcached_definition_countDarraUa_StructDecoder_CachedCount

다음 단계​