Read / Write
前置阅读
- 数据类型 Variant 和 DataValue 是所有读写的基础.
- 高频访问相同节点请用 RegisterNodes 加速.
- 实时变化通知用 Subscription 而不是循环 Read.
Read
public DataValue Read(string nodeId, AttributeId attribute = AttributeId.Value);
读单节点的指定 Attribute.
| 参数 | 类型 | 默认 | 说明 |
|---|---|---|---|
| nodeId | string | — | NodeId 字符串 (i=2258 / ns=2;s=...) |
| attribute | AttributeId | Value (13) | 要读的属性 |
返回: DataValue (实现 IDisposable, 必须用 using)
异常: OpcUaException (BadNodeIdUnknown / BadNotReadable / BadCommunicationError / ...)
// 读 Value
using var dv = ua.Read("ns=2;s=Temperature");
Console.WriteLine(dv.Value.AsDouble); // AsDouble 返回 double? (类型不匹配时为 null), 直接传 double 形参会编译不过
// 读 DisplayName
using var dn = ua.Read("ns=2;s=Temperature", AttributeId.DisplayName);
Console.WriteLine(dn.Value.AsString);
ReadMany
同 Attribute 批量
public IReadOnlyList<DataValue> ReadMany(
IReadOnlyList<string> nodeIds,
AttributeId attribute = AttributeId.Value);
一次 RPC 批量读多个节点的同一 Attribute.
var nodes = new[] { "ns=2;s=T1", "ns=2;s=T2", "ns=2;s=T3" };
var values = ua.ReadMany(nodes);
for (int i = 0; i < nodes.Length; i++)
{
var dv = values[i]; // 单项失败时该槽位是 null
using (dv) Console.WriteLine($"{nodes[i]} = {(dv == null ? "<null>" : dv.Value.ToString())}");
}
任意 NodeId + AttributeId 组合
public IReadOnlyList<DataValue> ReadMany(
IReadOnlyList<(string nodeId, AttributeId attr)> items);
var items = new (string, AttributeId)[]
{
("ns=2;s=T1", AttributeId.Value),
("ns=2;s=T1", AttributeId.DataType),
("ns=2;s=T2", AttributeId.Value),
};
var results = ua.ReadMany(items);
foreach (var dv in results)
using (dv) Console.WriteLine(dv == null ? "<null>" : dv.ToString());
性能: 批量比循环单读省掉 N-1 次 RPC 往返.
ReadMany 的失败语义
- 整批调用失败 (服务端返回非 Good) → 抛
OpcUaException("ReadMany failed", status), 一条结果都没有 - 单项失败 → 该槽位在返回列表里是
null, 其余项照常返回 - 返回的每个
DataValue都归调用方, 必须using/Dispose
Write
public StatusCode Write(string nodeId, Variant value, AttributeId attribute = AttributeId.Value);
写单节点.
using var v = new Variant();
v.Double = 42.5;
StatusCode st = ua.Write("ns=2;s=Setpoint", v);
if (st != StatusCode.Good) Console.WriteLine($"Write failed: {st}");
返回 StatusCode (Good / BadNotWritable / BadTypeMismatch / BadUserAccessDenied / ...).
业务级失败走返回值, 但仍会抛异常
业务级失败 (BadNotWritable / BadTypeMismatch / BadUserAccessDenied 等) 不抛异常, 通过返回的 StatusCode 判断, 必须检查返回值, 不要假定 Good。
但 Write 有两条路径会抛:
value == null→ArgumentNullException- 会话级故障 (
BadSessionClosed/BadSessionIdInvalid/BadServerNotConnected/BadConnectionClosed/BadSecureChannelClosed) → 自动重连一次再重试, 仍失败则抛OpcUaException
不想写 try/catch 就用 WriteSafe (把异常折叠成 StatusCode)。
Variant 赋值速查
Variant 只有无参构造, 赋值走类型 setter:
using var v = new Variant();
v.Boolean = true;
v.Int16 = 42;
v.Int32 = 42;
v.Int64 = 42L;
v.Double = 3.14;
v.Float = 3.14f;
v.String = "hello";
v.DateTime = DateTime.UtcNow;
// 数组
v.SetDoubleArray(new[] { 1.0, 2.0, 3.0 });
v.SetStringArray(new[] { "a", "b", "c" });
详见 Variant 数据类型.
DataValue 字段速查
| 字段 | 类型 | 说明 |
|---|---|---|
| Value | Variant | 实际值 |
| Status | StatusCode | Good / Bad* / Uncertain* |
| IsGood | bool | 是否 Good |
| SourceTimestamp | DateTime? | 数据源时间戳 |
| ServerTimestamp | DateTime? | 服务端打的时间戳 |
using var dv = ua.Read("ns=2;s=T1");
if (!dv.IsGood)
{
Console.WriteLine($"Bad value: {dv.Status}");
return;
}
Console.WriteLine($"{dv.Value.AsDouble} @ {dv.SourceTimestamp}");
AttributeId 常用值
| Id | 名称 | 说明 |
|---|---|---|
| 1 | NodeId | 节点 ID |
| 2 | NodeClass | 节点类别 |
| 3 | BrowseName | 浏览名 |
| 4 | DisplayName | 显示名 |
| 5 | Description | 描述 |
| 13 | Value | 变量值 (默认) |
| 14 | DataType | 数据类型 NodeId |
| 17 | AccessLevel | 访问权限位 |
| 20 | Historizing | 是否在记录历史 |
| 21 | Executable | Method 是否可执行 |
最佳实践
- 批量优先: 监控多个 Tag 用
ReadMany, 不要循环Read(省 N-1 次 RPC) - 多 Attribute 也用批量: 大量读同一节点的不同 Attribute, 用
ReadMany((nodeId, attr))形式 - 必须 Dispose:
DataValue实现 IDisposable, 漏 Dispose 会泄漏资源 - Write 检查返回值: 不要假定一定 Good
- 实时变化用订阅: 不要 1 秒一次轮询 Read, 改用
SubscriptionDataChanged 事件 (服务端推送)