Eclipse Milo 处理PLC"字(Word)"类型,最直接和正确的做法是使用其内置的 UShort 类型

在 Eclipse Milo 这个 OPC UA 库中,向一个 UInt16 类型的数据点写入数据,最直接和正确的做法是使用其内置的 UShort 类型。

为了方便你快速理解和上手,我整理了下面的核心信息表:

操作环节 OPC UA 类型 Milo 中的对应类型 核心写入方法/类
写入 UInt16 UShort new Variant(new UShort(value))Unsigned.ushort(value)

📝 详细写入步骤

在实际代码中,向一个 UInt16 节点写入值通常包含以下步骤:

  1. 创建 UShort 对象:将你的整数值(如 500)包装成 UShort 对象。
  2. 封装为 Variant:OPC UA 通信使用 Variant 作为通用数据容器。
  3. 构造 DataValue:将 Variant 封装进 DataValue,并可以设置时间戳、状态码等。
  4. 执行写入:通过节点的 writeValue 方法写入。

以下是一个完整的代码示例,展示了如何向节点 ns=2;s="YourUInt16NodeId" 写入值 500

import org.eclipse.milo.opcua.stack.core.types.builtin.*;
import org.eclipse.milo.opcua.stack.core.types.builtin.unsigned.UShort;
import org.eclipse.milo.opcua.sdk.client.nodes.UaVariableNode;
import java.util.concurrent.ExecutionException;

// ... 省略客户端连接等初始化代码

// 1. 指定要写入的节点
NodeId nodeId = new NodeId(2, "YourUInt16NodeId");
UaVariableNode node = client.getAddressSpace().createVariableNode(nodeId);

// 2. 创建要写入的值(例如 500),并包装为 UShort
// 方法一:直接构造 UShort
// UShort uShortValue = new UShort(500);
// 方法二:使用 Unsigned 工具类(效果相同)
 UShort uShortValue = Unsigned.ushort(500);

// 3. 将值封装进 Variant 和 DataValue
Variant variant = new Variant(uShortValue);
DataValue dataValue = new DataValue(variant, null, null);

// 4. 执行写入操作
try {
    StatusCode status = node.writeValue(dataValue).get();
    if (status.isGood()) {
        System.out.println("写入 UInt16 成功。");
    } else {
        System.out.println("写入失败,状态码: " + status);
    }
} catch (InterruptedException | ExecutionException e) {
    e.printStackTrace();
}

🔍 重要说明与建议

  • 为什么是 UShort? 由于 Java 语言本身不支持无符号整数类型,Milo 库提供了 UShortUIntegerULong 等类来完整表示 OPC UA 的无符号类型,并处理相关的取值范围和运算,直接使用这些类是最规范的方式。
  • 读取时的处理:当你从该节点读取数据时,返回的 Variant 中的值也是 UShort 对象。你可以通过调用 UShorttoInt()toLong() 等方法将其转换为标准的 Java 类型进行计算或展示。
  • 不要直接使用基础类型:避免试图直接用 Java 的 intshort 进行强转,这会导致 ClassCastException。如果确实需要基于 int 值处理,正确做法是先将 int 转为 UShort 再写入,或从 UShort 转回 int

总结来说,使用 UShort 是 Milo 中处理 UInt16 类型数据点的标准方式

posted @ 2026-01-08 09:27  dirgo  阅读(10)  评论(0)    收藏  举报