구조체 디코딩 (StructDecoder)
개요
OPC UA 1.04+ 각 사용자 정의 구조체의 필드 정의를 DataType 노드의 DataTypeDefinition 속성 (AttributeId=27, Part 5 §6.4.2)에 넣습니다.설계 흐름은 다음과 같습니다: 클라이언트가 해당 속성을 읽음 → 를 가져옴 → StructureDefinition (Fields[]) 캐싱; ExtensionObject 바이너리를 얻은 후, 필드 순서에 따라 UA Binary 인코딩(Part 6 §5.2)을 사용하여 字段名 → 值 딕셔너리로 역직렬화합니다.
현재 상태 (필독): Decode(Variant) 지금진단 사전만 반환하고, 필드 값은 반환하지 않음, DecodeBody 항상 반환됩니다 null. 자세한 내용은 글 하단의 「구현 제한 사항」을 참조하십시오. 먼저 내용을 모두 읽어보신 후 도입 여부를 결정해 주십시오.
디코딩 규칙은 다음 형태를 다룹니다(현재 ExtensionObject 바이트 스트림과 필드 정의를 얻을 수 없어 디코딩 단계까지 진행되지 않습니다):
- 모든 기본 유형 (Boolean / Int / Float / Double / String / DateTime / Guid / ByteString / NodeId / ExpandedNodeId / StatusCode / QualifiedName / LocalizedText / XmlElement)
- 중첩 구조체 (필드가 다른 사용자 정의 구조체를 DataType 가리키며, 자동으로 재귀 처리됨)
- 열거 (해독 Int32 순서대로)
- 배열 (ValueRank ≥ 1)
- Union (1-based selector)
- 선택적 필드 (UInt32 EncodingMask)
- 재귀 깊이 상한 32단계 + 순환 참조 감지 (한도를 초과하면 예외 발생
InvalidDataException, 스택 오버플로우로 인한 프로세스 종료는 없음)
API
| 구성원 | 분류 | 읽기 및 쓰기 | 설명 |
|---|---|---|---|
| new StructDecoder(ua) | 구조 | — | 세션에 바인딩 (ua == null throw ArgumentNullException) |
| decoder.Decode(Variant v) | 방법 | 읽기 | 디코딩 ExtensionObject, 반환 Dictionary<string, object> |
| decoder.Decode<T>(Variant v) | 방법 | 읽기 | 강타입으로 디코딩 T (필드 이름별 매핑) |
| decoder.DecodeBody(byte[] body, string dataTypeNodeId) | 방법 | 읽기 | 바이트 스트림을 직접 입력 + DataType 디코딩 |
| decoder.ClearCache() | 방법 | — | 필드 테이블 캐시 지우기 (서버 측에서 DataType 변경 시 호출) |
| decoder.CachedDefinitionCount | 속성 | 읽기 | 캐시된 구조체의 수 |
| StructDecoder.StatusKey | 상수 | — | "_status", 진단 필드명 |
| StructDecoder.TypeIdKey | 상수 | — | "_typeId", 진단 필드명 |
진짜 서명:
public sealed class StructDecoder
{
public const string StatusKey = "_status";
public const string TypeIdKey = "_typeId";
public StructDecoder(DarraOpcUa ua);
public void ClearCache();
public int CachedDefinitionCount { get; }
public Dictionary<string, object> Decode(Variant v);
public T Decode<T>(Variant v) where T : new();
public Dictionary<string, object> DecodeBody(byte[] body, string dataTypeNodeId);
}
반환값 규칙:
| 호출 | 아님 ExtensionObject / 입력 매개변수가 null임 | 네 ExtensionObject |
|---|---|---|
Decode(Variant) | null | 만 포함된 _status 사전 (현재 바이트 스트림을 가져올 수 없음) |
Decode<T>(Variant) | default (T 클래스 정의 시 null) | 빈 new T() 인스턴스 하나 — 모든 필드가 기본값으로 설정되어 있습니다 |
DecodeBody(...) | null | null (필드 정의 분석이 아직 연결되지 않았습니다) |
Decode<T> 의 빈 인스턴스를 성공으로 오해하지 마세요.Decode<T> 가 클래스일 T 때, 는 단지 null "가 아니다 ExtensionObject"를 의미할 뿐입니다. 하나를 얻으면null이 아니지만 모든 필드가 기본값인 경우의 경우 T, ExtensionObject 브랜치에 진입했지만 필드를 추출하지 못했음을 의미합니다. 성공 여부를 판단할 때는 반환된 Decode(Variant) 딕셔너리에 가 있는지 여부를 확인해야 _status하며, 가 null인지 Decode<T> 여부는 확인하지 마십시오.
관련 구조:
public sealed class StructDefinition
{
public string Name { get; set; } // 구조체 이름 (DataType 노드 BrowseName)
public string DataTypeId { get; set; } // DataType NodeId (문자열 형식)
public string BaseDataType { get; set; } // 상위 유형 NodeId
public StructureKind Kind { get; set; } // 구조체 유형, 기본값: Structure
public List<StructField> Fields { get; set; } // 필드 테이블 (순서 = 이진 인코딩 순서)
public string DefaultEncodingId { get; set; } // Binary Encoding 노드 NodeId
public bool IsUnion { get; } // Union 인코딩 여부 (선행 선택자)
public bool HasOptionalFields { get; } // Optional 필드가 포함되어 있는지 여부 (선행 EncodingMask)
}
public sealed class StructField
{
public string Name { get; set; } // 필드명
public string Description { get; set; } // 필드 설명 (LocalizedText 의 Text 부분)
public string DataType { get; set; } // 필드 유형 NodeId
public int ValueRank { get; set; } // -1 스칼라 / 0 한 차원 이상 / 1+ 배열, 기본값 -1
public uint[] ArrayDimensions { get; set; } // 각 차원의 상한
public uint MaxStringLength { get; set; } // String/ByteString/XmlElement 최대 길이 (0 = 제한 없음)
public bool IsOptional { get; set; } // Optional 필드 표시
}
public enum StructureKind
{
Structure = 0, // 일반, 순서 고정
StructureWithSubtypedValues = 1, // 자식 유형 필드 포함 (코딩 방식은 Structure와 동일)
StructureWithOptionalFields = 2, // 선택 필드 포함, 선행 UInt32 EncodingMask
Union = 3, // Union, 선행 UInt32 선택자 (1부터 시작, 0=null)
UnionWithSubtypedValues = 4 // Union 자식 유형 (코딩 방식은 Union과 동일)
}
코드 예시
using System;
using System.Collections.Generic;
using DarraOpcUa_Client;
using var ua = new DarraOpcUa("opc.tcp://localhost:4840");
ua.Connect();
var dec = new StructDecoder(ua);
// 1) 사용자 정의 구조체를 포함하는 노드 읽기 (예: : Robot.CurrentPose PoseType)
using var dv = ua.Read("ns=2;s=Robot.CurrentPose");
// 현재 Decode는 진단용 사전만 반환합니다 — 이를 통해 해당 필드가 실제로 해독되었는지 여부를 _status 판단합니다.
var fields = dec.Decode(dv.Value);
if (fields == null)
{
Console.WriteLine("不是 ExtensionObject");
}
else if (fields.TryGetValue(StructDecoder.StatusKey, out var diag))
{
Console.WriteLine($"暂不可用: {diag}");
}
else
{
foreach (var (name, value) in fields)
Console.WriteLine($"{name} = {value}");
}
// 2) 강타입 — 주의: 현재는 모든 필드가 기본값으로 설정된 빈 인스턴스가 반환되므로, 이를 성공으로 간주해서는 안 됩니다.
var pose = dec.Decode<PoseType>(dv.Value);
if (pose != null) Console.WriteLine($"x = {pose.X}");
// 3) 원본 바이트가 이미 있는 경우 DecodeBody
// (현재 상수는 null을 반환함)
byte[] rawBody = LoadExtensionObjectBody(); // 호출 측이 직접 가져온 EO body
var dict = dec.DecodeBody(rawBody, "ns=2;i=3001");
// 4) 캐시 관리
Console.WriteLine($"已缓存结构体定义 = {dec.CachedDefinitionCount}");
dec.ClearCache();
PoseType 호출 측에서 직접 작성한 것으로 POCO, 필드 이름은 서버 측 필드 이름과 일치해야 합니다(이름에 따라 매핑되며, 일치하지 않으면 건너뜁니다):
public class PoseType
{
public double X { get; set; }
public double Y { get; set; }
public double Z { get; set; }
}
구현상의 제약
현재 버전여전히 필드 값을 가져올 수 없습니다, 호출 경로에 따라 설명:
Decode(Variant)반환되지 않는 필드 — TypeId / Body를ExtensionObject가져올 수 없는 경우, 항상 만 포함된 딕셔너리_status(StructDecoder.StatusKey)를 반환합니다.DecodeBody(byte[], string)항복null— 읽기: '나오지DataTypeDefinition않음'StructDefinition, 필드 테이블이 없으면 필드를 파악할 수 없다.Decode<T>빈 인스턴스 함정 — 위 본문 API 표 하단의 경고 사항을 참조하십시오.
사용 가능한 부분:
- 재귀 깊이 상한 32단계, 초과 시 오류 발생
InvalidDataException - 순환 참조 감지 (A→B→A) — 동일한 재귀가 DataType 발생하면 즉시 예외가 발생합니다.
InvalidDataException ClearCache()/CachedDefinitionCount캐시 관리 인터페이스
BuiltinType.DiagnosticInfo 디코딩을 지원하지 않습니다.
모범 사례
- decoder 인스턴스 하나 공유하기 — 필드 테이블 캐시는 인스턴스와 함께 저장되며, 각 세션마다 하나씩 유지됩니다.
- 먼저 판정하고, 그 다음 필드를
_status사용 — 코드 예제의 1단계를 참조하십시오. 필드가 이미Decode반환되었다고 가정하지 마십시오. Decode<T>의 POCO 필드명을 서버 측 필드명과 일치시킵니다 — 이름에 따라 매핑되며, 일치하지 않는 필드는 아무런 오류 메시지 없이 건너뜁니다.- 서버 측에서 DataType 정의가 변경되면
ClearCache()— 캐시는 자동으로 만료되지 않습니다.
다국어 대조
| C# | Python | Java | C++ | Rust | C |
|---|---|---|---|---|---|
| StructDecoder | StructDecoder | StructDecoder | StructDecoder | StructDecoder | DarraUa_StructDecoder |
| Decode | decode | decode | Decode | decode | DarraUa_StructDecoder_Decode |
Decode<T> / DecodeBody / ClearCache / CachedDefinitionCount C#에서는 각각 Python의 decode_typed / decode_body / clear_cache / 에 해당합니다 cached_definition_count.