Java使用Milo实现OPC UA客户端,封装spring boot starter


最新版本更新日志查看:https://github.com/kangaroo1122/milo-spring-boot-starter/blob/main/UPDATE.mdhttps://gitee.com/vampire001/milo-spring-boot-starter/blob/master/UPDATE.md,此处不再更新

一、milo库

由eclipse开源,地址:https://github.com/eclipse/milo,可以基于此开发OPC UA客户端或者服务端。

本文介绍基于milo 封装的spring boot starter,yml配置OPC UA地址,是否匿名等信息,即可连接OPC UA服务器。

二、OPC UA服务端

这里使用的是kepware 6.6 版本,可参考之前的文章配置:Kepware配置OPC UA实现匿名or用户名/密码连接

三、工具使用

3.1 依赖

引入maven仓库地址,当前最新为:3.0.2 ,代码已上传至GitHub,有问题issues,欢迎star

查看最新版本:https://central.sonatype.com/artifact/com.kangaroohy/milo-spring-boot-starter

<dependency>
    <groupId>com.kangaroohy</groupId>
    <artifactId>milo-spring-boot-starter</artifactId>
    <version>${lastVersion}</version>
</dependency>

3.2 配置

yml配置OPC UA地址,是否匿名等信息

kangaroohy:
  milo:
  	primary: default
    config:
      default:
        endpoint: opc.tcp://127.0.0.1:49320
        security-policy: none
kangaroohy:
  milo:
  	primary: default
    config:
      default:
        endpoint: opc.tcp://127.0.0.1:49320
        security-policy: basic256sha256
        username: OPCUA
        password: 123456

特别提醒:

在kepware中,用户名/密码访问时,opcua配置,安全策略中三个策略全部勾选

同时kepware选项属性中的OPC UA配置,不允许匿名访问

此时,security-policy可选值:basic256sha256,basic256,basic128rsa15都可

同时配置上 用户名/密码 即可访问服务器

3.3 连接池

由于kepware中OPC UA最多只能有128个连接,且milo创建、释放连接比较耗时,因此本工具封装自带了一个连接池配置,默认会生成3个连接,可配置如下信息,达到连接管理的目的

kangaroohy:
  milo:
    pool:
      max-idle: 5
      max-total: 20
      min-idle: 2
      initial-size: 3

3.4 写

注入MiloService即可使用,支持:批量读、单个写、批量写、遍历节点信息等

其中:写值时可能需要指定数据类型,视点位情况而定

Opc后边的字段对应Kepware中的tag数据类型(Ua除外,为通用类型)

在这里插入图片描述

3.4.1 通用类型

如Kep类型为:Boolean、LLong、Long、String、Float、Double,调用方法:miloService.writeToOpcUa(ReadWriteEntity entity)

@SpringBootTest
@RunWith(SpringRunner.class)
public class MiloTest {
    @Autowired
    MiloService miloService;
    
    @Test
    public void writeToOpcUa() {
        miloService.writeToOpcUa(
                ReadWriteEntity.builder()
                        .identifier("GA.T1.Boolean")
                        //Kep中是Boolean类型
                        .value(true)
                        .build());
        miloService.writeToOpcUa(
                ReadWriteEntity.builder()
                        .identifier("GA.T1.LLong")
                        //Kep中是LLong类型,即:Int64,Java中的Long类型
                        .value(1235468L)
                        .build());
        miloService.writeToOpcUa(
                ReadWriteEntity.builder()
                        .identifier("GA.T1.Long")
                        //Kep中是Long类型,即:Int32,Java中的int类型
                        .value(123456)
                        .build());
        miloService.writeToOpcUa(
                ReadWriteEntity.builder()
                        .identifier("GA.T1.String")
                        .value("字符串")
                        .build());
        miloService.writeToOpcUa(
                ReadWriteEntity.builder()
                        .identifier("GA.T1.Float")
                        //Kep中是Float类型
                        .value(123.123F)
                        .build());
        miloService.writeToOpcUa(
                ReadWriteEntity.builder()
                        .identifier("GA.T1.Double")
                        //Kep中是Double类型
                        .value(123.123)
                        .build());
    }
}

3.4.2 已提供方法的类型

如Kep类型为:Short、Word、Byte、Char,调用方法:miloService.writeToOpcXXX(ReadWriteEntity entity),XXX对应kep类型

@SpringBootTest
@RunWith(SpringRunner.class)
public class MiloTest {
    @Autowired
    MiloService miloService;

    @Test
    public void writeToOpcUa() {
        miloService.writeToOpcShort(
                ReadWriteEntity.builder()
                        .identifier("GA.T1.Short")
                        //Kep中是Short类型,即:Int16,带符号整数
                        .value(-123)
                        .build());
        miloService.writeToOpcWord(
                ReadWriteEntity.builder()
                        .identifier("GA.T1.Word")
                        //Kep中是Word类型,即:UInt16,无符号整数
                        .value(123)
                        .build());
        miloService.writeToOpcByte(
                ReadWriteEntity.builder()
                        .identifier("GA.BIT_8.Byte")
                        //Kep中是Byte类型,8位无符号整数
                        .value(123)
                        .build());
        miloService.writeToOpcChar(
                ReadWriteEntity.builder()
                        .identifier("GA.BIT_8.Char")
                        //Kep中是Char类型,8位带符号整数
                        .value(-123)
                        .build());
    }
}

3.4.3 其他类型

其他的数据类型,则需要调用方法:miloService.writeSpecifyType(WriteEntity entity),自行指定转换类型.variant(new Variant(xxx))

new Variant(xxx):

new Variant(String[])

new Variant(Unsigned.ushort(“123”))

参数类型具体以标签数据类型为准,列如:

@SpringBootTest
@RunWith(SpringRunner.class)
public class MiloTest {
    @Autowired
    MiloService miloService;

    @Test
    public void writeToOpcUa() {
        UByte[] bytes = new UByte[10];
        bytes[0] = UByte.valueOf(1);
        bytes[1] = UByte.valueOf(2);
        bytes[2] = UByte.valueOf(3);
        bytes[3] = UByte.valueOf(4);

        miloService.writeSpecifyType(
                WriteEntity.builder()
                        .identifier("GA.BIT_8.Bytes")
                        //Kep中是Byte Array类型
                        .variant(new Variant(bytes))
                        .build());
    }
}

3.5 读

在这里插入图片描述

读比较简单,传相应的TAG id数组即可,调用方法:readFromOpcUa(List ids)

id格式:通道名.设备名.TAG

如:GA.T1.T1001R_1

3.6 遍历节点

在这里插入图片描述

可遍历指定节点相关信息

3.7 订阅

这里使用的是实现ApplicationRunner接口,实现在项目启动时,自动订阅相关点位

当点位数值发生改变,则会触发回调,根据回调即可实现相应的逻辑

每新增一个订阅都会长期占用一个opc ua连接,不会释放,支持配置订阅扫描时长,具体可查询方法参数

@Component
@Slf4j
public class CustomRunner implements ApplicationRunner {

    @Autowired
    private MiloService miloService;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        sub();
    }

    private void sub() throws Exception {
        List<String> ids = new ArrayList<>();
        ids.add("GA.T1.T1001R");
        ids.add("GA.T1.String");
        miloService.subscriptionFromOpcUa(ids, (id, value) -> log.info("subscription 点位:{} 订阅到消息:{}", id, value));
    }
}
  • 7
    点赞
  • 30
    收藏
    觉得还不错? 一键收藏
  • 54
    评论
Java Eclipse环境下实现OPC UA客户端代码,可以使用Milo库。以下是一个简单实现的示例代码: 1. 导入Milo库和其他必要的依赖: ``` <dependency> <groupId>org.eclipse.milo</groupId> <artifactId>milo-client-sdk</artifactId> <version>x.x.x</version> </dependency> ``` 2. 创建一个OPC UA客户端: ```java OpcUaClient client; try { // 连接到OPC UA服务器 OpcUaClientConfig config = OpcUaClientConfig.builder() .setEndpoint(endpointUrl) // OPC UA服务器的URL .setRequestTimeout(uint(5000)) // 请求超时时间 .build(); client = new OpcUaClient(config); client.connect().get(); // 建立连接 // 连接成功后,进行其他操作,例如读取或写入节点值 } catch (Exception e) { e.printStackTrace(); } ``` 3. 读取节点值: ```java try { // 读取单个节点值 NodeId nodeId = new NodeId(namespaceIndex, identifier); // 根据节点的命名空间和标识符创建节点ID DataValue value = client.readValue(Duration.ofMillis(5000), TimestampsToReturn.Both, nodeId).get(); // 处理读取到的值 System.out.println(value.getValue().getValue()); } catch (Exception e) { e.printStackTrace(); } ``` 4. 写入节点值: ```java try { // 写入单个节点值 NodeId nodeId = new NodeId(namespaceIndex, identifier); // 根据节点的命名空间和标识符创建节点ID Variant variant = new Variant(writeValue); // 写入的值 StatusCode statusCode = client.writeValue(nodeId, variant).get(); // 处理写入结果 System.out.println("Write status: " + statusCode); } catch (Exception e) { e.printStackTrace(); } ``` 需要注意的是,以上代码只是一个简单的示例,实际使用中可能会涉及更多的细节和功能。此外,还需要根据具体的OPC UA服务器配置和节点信息进行调整。详细的使用指南可以参考Milo库的文档和示例代码。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 54
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值