最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

使用java的milo框架訪問OPCUA服務(wù)的過程

 更新時間:2022年01月07日 16:17:57   作者:姚華軍  
這篇文章主要介紹了使用java的milo框架訪問OPCUA服務(wù)的方法,本次采用KEPServerEX5模擬服務(wù)端,使用milo開發(fā)的程序作為客戶端,具體操作使用過程跟隨小編一起看看吧

最近接了一個項目,需要訪問工業(yè)的實時數(shù)據(jù)庫,數(shù)據(jù)庫的對外開放接口是OPCUA協(xié)議的,經(jīng)過多方比對,發(fā)現(xiàn)github上milo的評星較高,嘗試了一下,還比較方便好用,現(xiàn)在把使用過程中的坑和大家介紹一下,網(wǎng)上比較全的資料不多,下面是整個過程全部的資料:

本次采用KEPServerEX5模擬服務(wù)端,使用milo開發(fā)的程序作為客戶端

一、搭建服務(wù)端,KEPServerEX5的安裝省略掉,下面是配置過程

設(shè)置通道、設(shè)備、標簽

在這里插入圖片描述

設(shè)置訪問的用戶名和密碼

在這里插入圖片描述

設(shè)置通過opc-ua訪問的節(jié)點

在這里插入圖片描述

二、使用milo的框架,開發(fā)客戶端訪問opcua服務(wù)

1、在pom文件中追擊以下依賴

<!--start milo-->
<dependency>
    <groupId>org.eclipse.milo</groupId>
    <artifactId>sdk-client</artifactId>
    <version>0.2.4</version>
</dependency>
<dependency>
    <groupId>org.bouncycastle</groupId>
    <artifactId>bcpkix-jdk15on</artifactId>
    <version>1.57</version>
</dependency>
<dependency>
    <groupId>org.eclipse.milo</groupId>
    <artifactId>sdk-server</artifactId>
    <version>0.2.4</version>
</dependency>
<!--end milo-->

2、OPC UA協(xié)議對象接口

package com.jndj.platform.common.milo;
import org.eclipse.milo.opcua.sdk.client.OpcUaClient;
import org.eclipse.milo.opcua.sdk.client.api.identity.AnonymousProvider;
import org.eclipse.milo.opcua.sdk.client.api.identity.IdentityProvider;
import org.eclipse.milo.opcua.stack.core.security.SecurityPolicy;
import org.eclipse.milo.opcua.stack.core.types.structured.EndpointDescription;
import java.util.concurrent.CompletableFuture;
import java.util.function.Predicate;
/**
 * @author yaohj
 * @date 2020/7/30
 * OPC UA協(xié)議對象接口
 */
public interface OpcUAClientService {
    /**
     * OPC UA服務(wù)器地址和接口
     */
    default String getEndpointUrl() {
        return "opc.tcp://127.0.0.1:49320";
    }
    /**
     * 過濾返回的server endpoint
     */
    default Predicate<EndpointDescription> endpointFilter() {
        return e -> true;
    }
    /**
     * 連接服務(wù)器的安全策略
     * None、Basic128Rsa15、Basic256、Basic256Sha256、Aes128_Sha256_RsaOaep、Aes256_Sha256_RsaPss
     */
    default SecurityPolicy getSecurityPolicy() {
        return SecurityPolicy.None;
    }
    /**
     * 提供身份驗證
     */
    default IdentityProvider getIdentityProvider() {
        return new AnonymousProvider();
    }
    /**
     * 實際操作服務(wù)、由實現(xiàn)類重寫實現(xiàn)
     */
    void run(OpcUaClient client, CompletableFuture<OpcUaClient> future) throws Exception;
}

3、OPC UA協(xié)議對象實體類

package com.jndj.platform.common.milo;
import com.google.common.collect.ImmutableList;
import org.eclipse.milo.opcua.sdk.client.OpcUaClient;
import org.eclipse.milo.opcua.stack.core.types.builtin.*;
import org.eclipse.milo.opcua.stack.core.types.enumerated.TimestampsToReturn;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.concurrent.CompletableFuture;
@Service("OpcUAClientService")
public class OpcUAClientServiceImpl implements OpcUAClientService {
    /**
     * 覆蓋接口的方法,建立和OPC UA的服務(wù)
     */
    @Override
    public void run(OpcUaClient client, CompletableFuture<OpcUaClient> future) throws Exception {
        // 同步建立連接
        client.connect().get();
        // 異步讀取數(shù)據(jù)
        readTagData(client).thenAccept(values -> {
            DataValue nodeId_Tag1 = values.get(0);
            DataValue nodeId_Tag2 = values.get(1);
            System.out.println("#########Tag1=" + nodeId_Tag1.getValue().getValue());
            System.out.println("#########Tag2=" + nodeId_Tag2.getValue().getValue());
            future.complete(client);
        });
    }
    /**
     * 讀取標簽點的數(shù)據(jù)
     */
    private CompletableFuture<List<DataValue>> readTagData(OpcUaClient client) {
        NodeId nodeId_Tag1 = new NodeId(2, "Channel1.Device1.Tag1");
        NodeId nodeId_Tag2 = new NodeId(2, "Channel1.Device1.Tag2");
        List<NodeId> nodeIds = ImmutableList.of(nodeId_Tag1, nodeId_Tag2);
        return client.readValues(0.0, TimestampsToReturn.Both, nodeIds);
    }
}

4、OPC UA協(xié)議運行對象

package com.jndj.platform.common.milo;
import org.eclipse.milo.opcua.sdk.client.OpcUaClient;
import org.eclipse.milo.opcua.sdk.client.api.config.OpcUaClientConfig;
import org.eclipse.milo.opcua.sdk.client.api.identity.UsernameProvider;
import org.eclipse.milo.opcua.stack.client.UaTcpStackClient;
import org.eclipse.milo.opcua.stack.core.Stack;
import org.eclipse.milo.opcua.stack.core.types.builtin.LocalizedText;
import org.eclipse.milo.opcua.stack.core.types.structured.EndpointDescription;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import static org.eclipse.milo.opcua.stack.core.types.builtin.unsigned.Unsigned.uint;
@Service("OpcUAClientRunner")
public class OpcUAClientRunner {
    private final Logger logger = LoggerFactory.getLogger(getClass());
    private final CompletableFuture<OpcUaClient> future = new CompletableFuture<>();
    private final OpcUAClientService opcUAClientService;
    public OpcUAClientRunner(OpcUAClientService opcUAClientService) {
        this.opcUAClientService = opcUAClientService;
    }
    /**
     * OPC UA的運行入口程序
     */
    public void run() {
        try {
            // 創(chuàng)建OPC UA客戶端
            OpcUaClient opcUaClient = createClient();
            // future執(zhí)行完畢后,異步判斷狀態(tài)
            future.whenCompleteAsync((c, ex) -> {
                if (ex != null) {
                    logger.error("連接OPC UA服務(wù)錯誤: {}", ex.getMessage(), ex);
                }
                // 關(guān)閉OPC UA客戶端
                try {
                    opcUaClient.disconnect().get();
                    Stack.releaseSharedResources();
                } catch (InterruptedException | ExecutionException e) {
                    logger.error("OPC UA服務(wù)關(guān)閉錯誤: {}", e.getMessage(), e);
                }
            });
            try {
                // 獲取OPC UA服務(wù)器的數(shù)據(jù)
                opcUAClientService.run(opcUaClient, future);
                future.get(5, TimeUnit.SECONDS);
            } catch (Throwable t) {
                logger.error("OPC UA客戶端運行錯誤: {}", t.getMessage(), t);
                future.completeExceptionally(t);
            }
        } catch (Throwable t) {
            logger.error("OPC UA客戶端創(chuàng)建錯誤: {}", t.getMessage(), t);
            future.completeExceptionally(t);
        }
    }
    /**
     * 創(chuàng)建OPC UA的服務(wù)連接對象
     */
    private OpcUaClient createClient() throws Exception {
        Path securityTempDir = Paths.get(System.getProperty("java.io.tmpdir"), "security");
        Files.createDirectories(securityTempDir);
        if (!Files.exists(securityTempDir)) {
            throw new Exception("不能夠創(chuàng)建安全路徑: " + securityTempDir);
        }
        KeyStoreLoader loader = new KeyStoreLoader().load(securityTempDir);
        // 獲取OPC UA的服務(wù)器端節(jié)點
        EndpointDescription[] endpoints =
                UaTcpStackClient.getEndpoints(opcUAClientService.getEndpointUrl()).get();
        EndpointDescription endpoint = Arrays.stream(endpoints)
                .filter(e -> e.getEndpointUrl().equals(opcUAClientService.getEndpointUrl()))
                .findFirst().orElseThrow(() -> new Exception("沒有節(jié)點返回"));
        // 設(shè)置OPC UA的配置信息
        OpcUaClientConfig config =
                OpcUaClientConfig.builder()
                        .setApplicationName(LocalizedText.english("OPC UA SCREEN"))
                        .setApplicationUri("urn:DATA-TRANSFER:OPC UA SCREEN")
                        .setCertificate(loader.getClientCertificate())
                        .setKeyPair(loader.getClientKeyPair())
                        .setEndpoint(endpoint)
                        .setIdentityProvider(new UsernameProvider("Administrator", "123456"))
                        .setRequestTimeout(uint(5000))
                        .build();
        // 創(chuàng)建OPC UA客戶端
        return new OpcUaClient(config);
    }
}

5、OPC UA訪問證書類

package com.jndj.platform.common.milo;
import org.eclipse.milo.opcua.sdk.server.util.HostnameUtil;
import org.eclipse.milo.opcua.stack.core.util.SelfSignedCertificateBuilder;
import org.eclipse.milo.opcua.stack.core.util.SelfSignedCertificateGenerator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.security.*;
import java.security.cert.X509Certificate;
import java.util.regex.Pattern;
class KeyStoreLoader {
    private final Logger logger = LoggerFactory.getLogger(getClass());
    private static final Pattern IP_ADDR_PATTERN = Pattern.compile(
        "^(([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.){3}([01]?\\d\\d?|2[0-4]\\d|25[0-5])$");
    // 證書別名
    private static final String CLIENT_ALIAS = "client-ai";
    // 獲取私鑰的密碼
    private static final char[] PASSWORD = "password".toCharArray();
    // 證書對象
    private X509Certificate clientCertificate;
    // 密鑰對對象
    private KeyPair clientKeyPair;
    KeyStoreLoader load(Path baseDir) throws Exception {
        // 創(chuàng)建一個使用`PKCS12`加密標準的KeyStore。KeyStore在后面將作為讀取和生成證書的對象。
        KeyStore keyStore = KeyStore.getInstance("PKCS12");
        // PKCS12的加密標準的文件后綴是.pfx,其中包含了公鑰和私鑰。
        // 而其他如.der等的格式只包含公鑰,私鑰在另外的文件中。
        Path serverKeyStore = baseDir.resolve("example-client.pfx");
        logger.info("Loading KeyStore at {}", serverKeyStore);
        // 如果文件不存在則創(chuàng)建.pfx證書文件。
        if (!Files.exists(serverKeyStore)) {
            keyStore.load(null, PASSWORD);
            // 用2048位的RAS算法。`SelfSignedCertificateGenerator`為Milo庫的對象。
            KeyPair keyPair = SelfSignedCertificateGenerator.generateRsaKeyPair(2048);
            // `SelfSignedCertificateBuilder`也是Milo庫的對象,用來生成證書。
            // 中間所設(shè)置的證書屬性可以自行修改。
            SelfSignedCertificateBuilder builder = new SelfSignedCertificateBuilder(keyPair)
                .setCommonName("Eclipse Milo Example Client")
                .setOrganization("digitalpetri")
                .setOrganizationalUnit("dev")
                .setLocalityName("Folsom")
                .setStateName("CA")
                .setCountryCode("US")
                .setApplicationUri("urn:eclipse:milo:examples:client")
                .addDnsName("localhost")
                .addIpAddress("127.0.0.1");
            // Get as many hostnames and IP addresses as we can listed in the certificate.
            for (String hostname : HostnameUtil.getHostnames("0.0.0.0")) {
                if (IP_ADDR_PATTERN.matcher(hostname).matches()) {
                    builder.addIpAddress(hostname);
                } else {
                    builder.addDnsName(hostname);
                }
            }
            // 創(chuàng)建證書
            X509Certificate certificate = builder.build();
            // 設(shè)置對應(yīng)私鑰的別名,密碼,證書鏈
            keyStore.setKeyEntry(CLIENT_ALIAS, keyPair.getPrivate(), PASSWORD, new X509Certificate[]{certificate});
            try (OutputStream out = Files.newOutputStream(serverKeyStore)) {
                // 保存證書到輸出流
                keyStore.store(out, PASSWORD);
            }
        } else {
            try (InputStream in = Files.newInputStream(serverKeyStore)) {
                // 如果文件存在則讀取
                keyStore.load(in, PASSWORD);
            }
        }
        // 用密碼獲取對應(yīng)別名的私鑰。
        Key serverPrivateKey = keyStore.getKey(CLIENT_ALIAS, PASSWORD);
        if (serverPrivateKey instanceof PrivateKey) {
            // 獲取對應(yīng)別名的證書對象。
            clientCertificate = (X509Certificate) keyStore.getCertificate(CLIENT_ALIAS);
            // 獲取公鑰
            PublicKey serverPublicKey = clientCertificate.getPublicKey();
            // 創(chuàng)建Keypair對象。
            clientKeyPair = new KeyPair(serverPublicKey, (PrivateKey) serverPrivateKey);
        }
        return this;
    }
    // 返回證書
    X509Certificate getClientCertificate() {
        return clientCertificate;
    }
    // 返回密鑰對
    KeyPair getClientKeyPair() {
        return clientKeyPair;
    }
}

6、業(yè)務(wù)service類

package com.jndj.platform.phase2.service.impl;
import com.jndj.platform.common.milo.OpcUAClientRunner;
import com.jndj.platform.common.milo.OpcUAClientService;
import com.jndj.platform.phase2.service.Phase2Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
 * @author yaohj
 * @date 2020/7/22
 * 獲取二期發(fā)電數(shù)據(jù)(三、四號機組)
 */
@Service("phase2Service")
public class Phase2ServiceImpl implements Phase2Service {
    @Autowired
    private OpcUAClientService opcUAClientService;
    /**
     * 獲取二期發(fā)電數(shù)據(jù)(三、四號機組),保存到數(shù)據(jù)庫中
     */
    @Override
    public void searchPhase2ElectricData() {
        new OpcUAClientRunner(opcUAClientService).run();
    }
}

7、業(yè)務(wù)Controller類、定時調(diào)度

package com.jndj.platform.phase2.controller;
import com.jndj.platform.phase2.service.Phase2Service;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Controller;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
 * @author yaohj
 * @date 2020/7/22
 * 獲取二期發(fā)電數(shù)據(jù)(三、四號機組)
 */
@Controller
public class Phase2Controller {
    private static final Logger logger = LoggerFactory.getLogger(Phase2Controller.class);
    private static final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy:mm:dd HH:mm:ss");
    @Autowired
    private Phase2Service phase2Service;
    /**
     * 獲取二期發(fā)電數(shù)據(jù)(三、四號機組),保存到數(shù)據(jù)庫中(x分鐘調(diào)度一次)
     */
    @Scheduled(initialDelay = 30000, fixedRate = 30000)
    public void searchGasData() {
        logger.info("####獲取二期發(fā)電數(shù)據(jù)(三、四號機組) - 定時任務(wù)執(zhí)行時間:"+ dateFormat.format(new Date()));
        phase2Service.searchPhase2ElectricData();
    }
}

8、運行結(jié)果、定時獲取到opcua服務(wù)中的數(shù)據(jù)

在這里插入圖片描述

OK,以上是所有的源代碼,大家的問題基本能夠解決。

到此這篇關(guān)于使用java的milo框架訪問OPCUA服務(wù)的方法的文章就介紹到這了,更多相關(guān)java訪問OPCUA服務(wù)內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • Java裝飾者模式的深入了解

    Java裝飾者模式的深入了解

    這篇文章主要為大家介紹了Java裝飾者模式,具有一定的參考價值,感興趣的小伙伴們可以參考一下,希望能夠給你帶來幫助
    2022-01-01
  • Java多線程 自定義線程池詳情

    Java多線程 自定義線程池詳情

    這篇文章主要介紹了Java多線程 自定義線程池,文章主要是學習代碼,沒有過多解析,需要的朋友可以參考一下文章的具體內(nèi)容
    2021-10-10
  • Spring?Boot?底層原理基礎(chǔ)深度解析

    Spring?Boot?底層原理基礎(chǔ)深度解析

    這篇文章主要介紹了Spring?Boot?底層原理基礎(chǔ),包括底層注解@Configuration,底層注解@Import及底層注解@Conditional的相關(guān)知識,本文結(jié)合示例代碼給大家介紹的非常詳細,需要的朋友可以參考下
    2022-04-04
  • java實現(xiàn)學生管理系統(tǒng)(面向?qū)ο?

    java實現(xiàn)學生管理系統(tǒng)(面向?qū)ο?

    這篇文章主要為大家詳細介紹了java實現(xiàn)學生管理系統(tǒng)(面向?qū)ο螅?,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2020-03-03
  • Spring注解與P/C命名空間超詳細解析

    Spring注解與P/C命名空間超詳細解析

    Spring注解方式減少了配置文件內(nèi)容,更加便于管理,并且使用注解可以大大提高了開發(fā)效率!注解本身是沒有功能的,和xml一樣,注解和xml都是一種元數(shù)據(jù),元數(shù)據(jù)即解釋數(shù)據(jù)的數(shù)據(jù),也就是所謂的配置
    2022-11-11
  • java 內(nèi)部類的實例詳解

    java 內(nèi)部類的實例詳解

    這篇文章主要介紹了java 內(nèi)部類的實例詳解的相關(guān)資料,希望通過本文大家能夠理解掌握java內(nèi)部類的使用,需要的朋友可以參考下
    2017-09-09
  • MyBatis使用<foreach>標簽報錯問題及解決

    MyBatis使用<foreach>標簽報錯問題及解決

    這篇文章主要介紹了MyBatis使用<foreach>標簽報錯問題及解決,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
    2024-03-03
  • elasticsearch啟動警告無法鎖定JVM內(nèi)存

    elasticsearch啟動警告無法鎖定JVM內(nèi)存

    今天小編就為大家分享一篇關(guān)于elasticsearch啟動警告無法鎖定JVM內(nèi)存,小編覺得內(nèi)容挺不錯的,現(xiàn)在分享給大家,具有很好的參考價值,需要的朋友一起跟隨小編來看看吧
    2019-03-03
  • Java實現(xiàn)五子棋游戲(控制臺版)

    Java實現(xiàn)五子棋游戲(控制臺版)

    這篇文章主要為大家詳細介紹了Java控制臺版實現(xiàn)五子棋游戲,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2021-10-10
  • SpringCloud注冊中心之consul詳細講解使用方法

    SpringCloud注冊中心之consul詳細講解使用方法

    Consul是一款由HashiCorp公司開源的,用于服務(wù)治理的軟件,Spring Cloud Consul對其進行了封裝,這篇文章主要介紹了springcloud組件consul服務(wù)治理,需要的朋友可以參考下
    2022-11-11

最新評論

万州区| 通渭县| 沙坪坝区| 邵东县| 任丘市| 惠来县| 陇南市| 那曲县| 五家渠市| 闵行区| 濉溪县| 高青县| 鹿邑县| 株洲县| 镇平县| 胶州市| 巨野县| 钟祥市| 密山市| 中宁县| 毕节市| 衡阳县| 鄂伦春自治旗| 江油市| 桂东县| 多伦县| 香格里拉县| 厦门市| 金山区| 浦县| 汕尾市| 惠安县| 尼勒克县| 白水县| 威远县| 太湖县| 博白县| 甘孜| 巨野县| 略阳县| 洪洞县|