gt преди 2 години
родител
ревизия
5000d6088c

+ 1 - 1
chuanyi_server/src/main/java/com/judong/chuanyiserver/controller/ConnectController.java

@@ -39,7 +39,7 @@ public class ConnectController {
      */
     @GetMapping("/testConnect")
     public Result testConnect(ServerInformation serverInformation) throws AlreadyConnectedException, JIException, UnknownHostException {
-        if (Blank.isEmpty(serverInformation, serverInformation.getIpAddress(), serverInformation.getIpUserName(), serverInformation.getIpPassword(), serverInformation.getAgreementType())) {
+        if (Blank.isEmpty(serverInformation, serverInformation.getIpAddress(), serverInformation.getAgreementType())) {
             return Result.no(ResultEnum.REQUEST_WRONGPARAMS.getRespCode(), ResultEnum.REQUEST_WRONGPARAMS.getRespMsg());
         }
         return connectService.testConnect(serverInformation);

+ 4 - 0
chuanyi_server/src/main/java/com/judong/chuanyiserver/entity/ServerInformation.java

@@ -38,6 +38,10 @@ public class ServerInformation implements Serializable {
      */
     private Integer agreementType;
     /**
+     * 是否匿名
+     */
+    private Integer isAnonymous;
+    /**
      * 创建时间
      */
     private Date createTime;

+ 2 - 2
chuanyi_server/src/main/java/com/judong/chuanyiserver/service/ConnectService.java

@@ -19,7 +19,7 @@ public interface ConnectService {
 
     Result selectAllConnect();
 
-    Result editConnect( ServerInformation serverInformation);
+    Result editConnect(ServerInformation serverInformation);
 
-    Result deleteConnect( int id);
+    Result deleteConnect(int id);
 }

+ 19 - 31
chuanyi_server/src/main/java/com/judong/chuanyiserver/service/impl/ConnectServiceImpl.java

@@ -3,6 +3,7 @@ package com.judong.chuanyiserver.service.impl;
 import com.judong.chuanyiserver.dao.ConnectDao;
 import com.judong.chuanyiserver.entity.ServerInformation;
 import com.judong.chuanyiserver.enums.ResultEnum;
+import com.judong.chuanyiserver.exception.CustomException;
 import com.judong.chuanyiserver.service.ConnectService;
 import com.judong.chuanyiserver.util.*;
 import lombok.extern.slf4j.Slf4j;
@@ -30,40 +31,24 @@ public class ConnectServiceImpl implements ConnectService {
 
     @Override
     public Result testConnect(ServerInformation serverInformation) throws AlreadyConnectedException, JIException, UnknownHostException {
-        // 连接信息
-        ConnectionInformation ci = new ConnectionInformation();
-        //服务
-        Server server = new Server(ci, Executors.newSingleThreadScheduledExecutor());
-        try {
-            ci.setHost(serverInformation.getIpAddress()); // 安装opc电脑IP
-            ci.setDomain(""); // 域,为空就行
-            ci.setUser(serverInformation.getIpUserName()); // 电脑上自己建好的用户名
-            ci.setPassword(serverInformation.getIpPassword()); // 用户名的密码
-            ci.setClsid("7BC0CC8E-482C-47CA-ABDC-0FE7F9C6E729"); // KEPServer的注册表ID,可以在“组件服务”里看到
-            // ci.setProgId("");
-
-            // 连接到服务
-            long start = System.currentTimeMillis();
-            server.connect();
-            long finish = System.currentTimeMillis();
-            log.info("连接耗费时间为:" + (finish - start) + "毫秒");
-            if (null == server.getServerState()) {
-                return Result.no(ResultEnum.NOT_FOUND.getRespCode(), "连接失败");
-            }
-            if (OPCSERVERSTATE.OPC_STATUS_RUNNING == server.getServerState().getServerState()) {
-                return Result.ok(true);
-            }
-        } finally {
-            //关闭连接使用
-            server.dispose();
+        switch (serverInformation.getAgreementType()) {
+            case ConstantStr.OPC_DA:
+                if(Blank.isEmpty(serverInformation.getIpUserName(),serverInformation.getIpPassword())){
+                    return Result.no(ResultEnum.REQUEST_WRONGPARAMS.getRespCode(), ResultEnum.REQUEST_WRONGPARAMS.getRespMsg());
+                }
+                return OpcServerDaUtil.opcDaTestConnect(serverInformation);
+            case ConstantStr.OPC_UA:
+                return OpcServerDaUtil.opcDaTestConnect(serverInformation);
+            default:
+                throw new CustomException(ResultEnum.NOT_FOUND.getRespCode(), "没有此协议类型");
         }
-        return Result.no(ResultEnum.SERVER_ERROR.getRespCode(), ResultEnum.SERVER_ERROR.getRespMsg());
     }
 
     @Override
     public synchronized Result saveConnect(ServerInformation serverInformation) {
         String userId = userUtil.getCurrentUserId();
         serverInformation.setUserId(userId);
+        serverInformation.setIpPassword(RSAUtil.encryptByPublic(serverInformation.getIpPassword(), RSAUtil.PUBLIC_KEY));
         ServerInformation si = connectDao.getServerInformation(userId, serverInformation.getIpAddress());
         if (Blank.isNotEmpty(si)) {
             return Result.no(ResultEnum.REQUEST_WRONGPARAMS.getRespCode(), "该用户下此ip已被使保存,请更换其他ip");
@@ -82,6 +67,7 @@ public class ConnectServiceImpl implements ConnectService {
     @Override
     public synchronized Result editConnect(ServerInformation serverInformation) {
         String userId = userUtil.getCurrentUserId();
+        serverInformation.setIpPassword(RSAUtil.encryptByPublic(serverInformation.getIpPassword(), RSAUtil.PUBLIC_KEY));
         ServerInformation si = connectDao.getServerInformationEdit(serverInformation.getId(), userId, serverInformation.getIpAddress());
         if (Blank.isNotEmpty(si)) {
             return Result.no(ResultEnum.REQUEST_WRONGPARAMS.getRespCode(), "该用户下此ip已被使保存,请更换其他ip");
@@ -107,11 +93,13 @@ public class ConnectServiceImpl implements ConnectService {
         if (Blank.isEmpty(serverInformation)) {
             return Result.no(ResultEnum.NOT_FOUND.getRespCode(), ResultEnum.NOT_FOUND.getRespMsg());
         }
-        //如果协议类型为OPCDA
-        if (serverInformation.getAgreementType() == ConstantStr.OPC_DA) {
-            return OpcServerDaUtil.opcDaReadItemTree(serverInformation);
+        switch (serverInformation.getAgreementType()) {
+            //如果协议类型为OPCDA
+            case ConstantStr.OPC_DA:
+                return OpcServerDaUtil.opcDaReadItemTree(serverInformation);
+            default:
+                throw new CustomException(ResultEnum.NOT_FOUND.getRespCode(), "没有此协议类型");
         }
-        return Result.no(ResultEnum.SERVER_ERROR.getRespCode(), ResultEnum.SERVER_ERROR.getRespMsg());
     }
 
     @Override

+ 8 - 8
chuanyi_server/src/main/java/com/judong/chuanyiserver/service/impl/UserServiceImpl.java

@@ -97,22 +97,22 @@ public class UserServiceImpl implements UserService {
         JSONObject json = new JSONObject();
         isExistUser.setPassword("");
         json.put("user", isExistUser);
+        //生成token
+        String token = TokenUtil.token(isExistUser.getUserName(), ConstantStr.HALF_HOUR);
+        json.put("token", token);
+        redisUtil.set(token, isExistUser.getUserId(), ConstantStr.HALF_HOUR);
         List<Integer> roleIdList = userDao.getRoleIdListByUserId(isExistUser.getUserId());
         if (Blank.isEmpty(roleIdList)) {
-            json.put("roleIdList", "");
-            return Result.ok("没有角色信息");
+            json.put("roleIdList", new ArrayList<>());
+            return Result.ok(json);
         }
         json.put("roleIdList", roleIdList);
         List<Permission> permissionList = userDao.getPermissionByRoleList(roleIdList);
         if (Blank.isEmpty(permissionList)) {
-            json.put("permissionList", "");
-            return Result.ok("没有权限信息");
+            json.put("permissionList", new ArrayList<>());
+            return Result.ok(json);
         }
         json.put("permissionList", permissionList);
-        //生成token
-        String token = TokenUtil.token(isExistUser.getUserName(), ConstantStr.HALF_HOUR);
-        json.put("token", token);
-        redisUtil.set(token, isExistUser.getUserId(), ConstantStr.HALF_HOUR);
         //更新用户登录状态
         if (userDao.updateLoginState(isExistUser.getUserId()) <= 0) {
             return Result.no(ResultEnum.SERVER_ERROR.getRespCode(), "更新登录状态失败");

+ 43 - 15
chuanyi_server/src/main/java/com/judong/chuanyiserver/util/KeyStoreLoader.java

@@ -1,3 +1,8 @@
+/**
+ * Created by Jellyleo on 2019年12月19日
+ * Copyright © 2019 jellyleo.com
+ * All rights reserved.
+ */
 package com.judong.chuanyiserver.util;
 
 import org.eclipse.milo.opcua.sdk.server.util.HostnameUtil;
@@ -14,44 +19,62 @@ import java.nio.file.Path;
 import java.security.*;
 import java.security.cert.X509Certificate;
 import java.util.regex.Pattern;
+
 public 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 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 String CLIENT_ALIAS = "jlclient-ai";
     // 获取私钥的密码
-    private static final char[] PASSWORD = "password".toCharArray();
+    private static final char[] PASSWORD = "123456".toCharArray();
+
+    private final Logger logger = LoggerFactory.getLogger(getClass());
+
     // 证书对象
     private X509Certificate clientCertificate;
     // 密钥对对象
     private KeyPair clientKeyPair;
 
+    /**
+     * @param baseDir
+     * @return
+     * @throws Exception
+     * @MethodName: load
+     * @Description: load
+     * @CreateTime 2019年12月11日 下午4:02:43
+     */
     public KeyStoreLoader load(Path baseDir) throws Exception {
         // 创建一个使用`PKCS12`加密标准的KeyStore。KeyStore在后面将作为读取和生成证书的对象。
         KeyStore keyStore = KeyStore.getInstance("PKCS12");
+
         // PKCS12的加密标准的文件后缀是.pfx,其中包含了公钥和私钥。
         // 而其他如.der等的格式只包含公钥,私钥在另外的文件中。
-        Path serverKeyStore = baseDir.resolve("example-client.pfx");
-        logger.info("正在加载KeyStore: {}", serverKeyStore);
+        Path serverKeyStore = baseDir.resolve("jellyleo-client.pfx");
+
+        logger.info("正在加载KeyStore{}", serverKeyStore);
+
         // 如果文件不存在则创建.pfx证书文件。
         if (!Files.exists(serverKeyStore)) {
             keyStore.load(null, PASSWORD);
+
             // 用2048位的RAS算法。`SelfSignedCertificateGenerator`为Milo库的对象。
             KeyPair keyPair = SelfSignedCertificateGenerator.generateRsaKeyPair(2048);
+
             // `SelfSignedCertificateBuilder`也是Milo库的对象,用来生成证书。
             // 中间所设置的证书属性可以自行修改。
             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")
+                    .setCommonName("UaClient@Jellyleo")
+                    .setOrganization("JL")
+                    .setOrganizationalUnit("per")
+                    .setLocalityName("jl")
+                    .setStateName("JiangSu")
+                    .setCountryCode("CN")
+                    .setApplicationUri("urn:Jellyleo:UnifiedAutomation:UaExpert@Jellyleo")
+                    .addDnsName("Jellyleo")
                     .addIpAddress("127.0.0.1");
+
             // 获取证书中列出的尽可能多的主机名和IP地址。
             for (String hostname : HostnameUtil.getHostnames("0.0.0.0")) {
                 if (IP_ADDR_PATTERN.matcher(hostname).matches()) {
@@ -62,6 +85,7 @@ public class KeyStoreLoader {
             }
             // 创建证书
             X509Certificate certificate = builder.build();
+
             // 设置对应私钥的别名,密码,证书链
             keyStore.setKeyEntry(CLIENT_ALIAS, keyPair.getPrivate(), PASSWORD, new X509Certificate[]{certificate});
             try (OutputStream out = Files.newOutputStream(serverKeyStore)) {
@@ -74,6 +98,7 @@ public class KeyStoreLoader {
                 keyStore.load(in, PASSWORD);
             }
         }
+
         // 用密码获取对应别名的私钥。
         Key serverPrivateKey = keyStore.getKey(CLIENT_ALIAS, PASSWORD);
         if (serverPrivateKey instanceof PrivateKey) {
@@ -84,12 +109,15 @@ public class KeyStoreLoader {
             // 创建Keypair对象。
             clientKeyPair = new KeyPair(serverPublicKey, (PrivateKey) serverPrivateKey);
         }
+
         return this;
     }
+
     // 返回证书
     public X509Certificate getClientCertificate() {
         return clientCertificate;
     }
+
     // 返回密钥对
     public KeyPair getClientKeyPair() {
         return clientKeyPair;

+ 38 - 2
chuanyi_server/src/main/java/com/judong/chuanyiserver/util/OpcServerDaUtil.java

@@ -4,10 +4,13 @@ import com.alibaba.fastjson.JSONObject;
 import com.judong.chuanyiserver.config.OpcServerDaPoolFactory;
 import com.judong.chuanyiserver.entity.ServerInformation;
 import com.judong.chuanyiserver.enums.ResultEnum;
+import lombok.extern.slf4j.Slf4j;
 import org.apache.commons.pool2.impl.GenericKeyedObjectPool;
 import org.jinterop.dcom.common.JIException;
 import org.jinterop.dcom.core.JIVariant;
 import org.openscada.opc.dcom.da.OPCSERVERSTATE;
+import org.openscada.opc.lib.common.AlreadyConnectedException;
+import org.openscada.opc.lib.common.ConnectionInformation;
 import org.openscada.opc.lib.da.Group;
 import org.openscada.opc.lib.da.Item;
 import org.openscada.opc.lib.da.Server;
@@ -17,10 +20,12 @@ import org.openscada.opc.lib.da.browser.TreeBrowser;
 
 import java.net.UnknownHostException;
 import java.util.*;
+import java.util.concurrent.Executors;
 
 /**
  * OPCDa协议工具类
  */
+@Slf4j
 public class OpcServerDaUtil {
 
     /**
@@ -90,6 +95,37 @@ public class OpcServerDaUtil {
         return OpcServerDaPoolFactory.getPool();
     }
 
+    public static Result opcDaTestConnect(ServerInformation serverInformation) throws AlreadyConnectedException, JIException, UnknownHostException {
+        // 连接信息
+        ConnectionInformation ci = new ConnectionInformation();
+        //服务
+        Server server = new Server(ci, Executors.newSingleThreadScheduledExecutor());
+        try {
+            ci.setHost(serverInformation.getIpAddress()); // 安装opc电脑IP
+            ci.setDomain(""); // 域,为空就行
+            ci.setUser(serverInformation.getIpUserName()); // 电脑上自己建好的用户名
+            ci.setPassword(serverInformation.getIpPassword()); // 用户名的密码
+            ci.setClsid("7BC0CC8E-482C-47CA-ABDC-0FE7F9C6E729"); // KEPServer的注册表ID,可以在“组件服务”里看到
+            // ci.setProgId("");
+
+            // 连接到服务
+            long start = System.currentTimeMillis();
+            server.connect();
+            long finish = System.currentTimeMillis();
+            log.info("连接耗费时间为:" + (finish - start) + "毫秒");
+            if (null == server.getServerState()) {
+                return Result.no(ResultEnum.NOT_FOUND.getRespCode(), "连接失败");
+            }
+            if (OPCSERVERSTATE.OPC_STATUS_RUNNING == server.getServerState().getServerState()) {
+                return Result.ok(true);
+            }
+        } finally {
+            //关闭连接使用
+            server.dispose();
+        }
+        return Result.no(ResultEnum.SERVER_ERROR.getRespCode(), ResultEnum.SERVER_ERROR.getRespMsg());
+    }
+
     /**
      * 通过服务器信息读取服务器树item
      *
@@ -98,7 +134,7 @@ public class OpcServerDaUtil {
      * @throws Exception
      */
     public static Result opcDaReadItemTree(ServerInformation serverInformation) throws Exception {
-        String opcServerDaPoolKey = OpcServerDaUtil.generateOpcPoolKey(serverInformation.getIpAddress(), serverInformation.getIpUserName(), serverInformation.getIpPassword());
+        String opcServerDaPoolKey = OpcServerDaUtil.generateOpcPoolKey(serverInformation.getIpAddress(), serverInformation.getIpUserName(), RSAUtil.decrypt(serverInformation.getIpPassword(), "utf-8"));
         if (OpcServerDaUtil.validationKey(opcServerDaPoolKey)) {
             Server server = OpcServerDaUtil.getServer(opcServerDaPoolKey);
             if (null == server.getServerState()) {
@@ -123,7 +159,7 @@ public class OpcServerDaUtil {
      * @throws Exception
      */
     public static Result opcDaReadItemValue(ServerInformation serverInformation, String itemName) throws Exception {
-        String opcServerDaPoolKey = OpcServerDaUtil.generateOpcPoolKey(serverInformation.getIpAddress(), serverInformation.getIpUserName(), serverInformation.getIpPassword());
+        String opcServerDaPoolKey = OpcServerDaUtil.generateOpcPoolKey(serverInformation.getIpAddress(), serverInformation.getIpUserName(), RSAUtil.decrypt(serverInformation.getIpPassword(), "utf-8"));
         if (OpcServerDaUtil.validationKey(opcServerDaPoolKey)) {
             Server server = OpcServerDaUtil.getServer(opcServerDaPoolKey);
             if (null == server.getServerState()) {

+ 110 - 161
chuanyi_server/src/main/java/com/judong/chuanyiserver/util/OpcServerUaUtil.java

@@ -1,67 +1,101 @@
 package com.judong.chuanyiserver.util;
 
+import com.alibaba.fastjson.JSONObject;
+import lombok.extern.slf4j.Slf4j;
 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.AnonymousProvider;
 import org.eclipse.milo.opcua.sdk.client.nodes.UaNode;
-import org.eclipse.milo.opcua.sdk.client.subscriptions.ManagedDataItem;
-import org.eclipse.milo.opcua.sdk.client.subscriptions.ManagedSubscription;
-import org.eclipse.milo.opcua.stack.core.AttributeId;
+import org.eclipse.milo.opcua.stack.client.DiscoveryClient;
 import org.eclipse.milo.opcua.stack.core.Identifiers;
+import org.eclipse.milo.opcua.stack.core.UaException;
 import org.eclipse.milo.opcua.stack.core.security.SecurityPolicy;
-import org.eclipse.milo.opcua.stack.core.types.builtin.*;
-import org.eclipse.milo.opcua.stack.core.types.builtin.unsigned.UInteger;
-import org.eclipse.milo.opcua.stack.core.types.enumerated.MonitoringMode;
+import org.eclipse.milo.opcua.stack.core.types.builtin.LocalizedText;
+import org.eclipse.milo.opcua.stack.core.types.builtin.NodeId;
+import org.eclipse.milo.opcua.stack.core.types.builtin.unsigned.Unsigned;
 import org.eclipse.milo.opcua.stack.core.types.enumerated.TimestampsToReturn;
-import org.eclipse.milo.opcua.stack.core.types.structured.MonitoredItemCreateRequest;
-import org.eclipse.milo.opcua.stack.core.types.structured.MonitoringParameters;
-import org.eclipse.milo.opcua.stack.core.types.structured.ReadValueId;
-
+import org.eclipse.milo.opcua.stack.core.types.structured.EndpointDescription;
+import org.jinterop.dcom.common.JIException;
+import org.openscada.opc.lib.da.Server;
+import org.openscada.opc.lib.da.browser.Branch;
+import org.openscada.opc.lib.da.browser.TreeBrowser;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.util.ObjectUtils;
+
+import java.net.UnknownHostException;
 import java.nio.file.Files;
 import java.nio.file.Path;
 import java.nio.file.Paths;
 import java.util.ArrayList;
+import java.util.Collection;
 import java.util.List;
 import java.util.Objects;
-import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.ExecutionException;
+import java.util.function.Predicate;
 
+@Slf4j
 public class OpcServerUaUtil {
+
+    private static final String certPath = "C:/Users/Administrator/Desktop/";
+    private static final String endpointUrl = "opc.tcp://192.168.0.252:49322";
+//    private static final String endpointUrl = "opc.tcp://192.168.0.252:37800";
+
     /**
      * 创建OPC UA客户端
      *
      * @return
      */
-    public OpcUaClient createClient() throws Exception {
-        //opc ua服务端地址
-        String endPointUrl = "opc.tcp://192.168.0.138:37800";
-        Path securityTempDir = Paths.get(System.getProperty("java.io.tmpdir"), "security");
+    public static OpcUaClient createClient() throws Exception {
+        Path securityTempDir = Paths.get(certPath, "security");
+
         Files.createDirectories(securityTempDir);
         if (!Files.exists(securityTempDir)) {
-            throw new Exception("unable to create security dir: " + securityTempDir);
+            log.info("无法创建安全目录: " + securityTempDir);
+            return null;
+        }
+        KeyStoreLoader keyStoreLoader = new KeyStoreLoader();
+        KeyStoreLoader loader = keyStoreLoader.load(securityTempDir);
+        // 搜索OPC节点
+        List<EndpointDescription> endpoints = null;
+        try {
+            endpoints = DiscoveryClient.getEndpoints(endpointUrl).get();
+        } catch (Throwable e) {
+            String discoveryUrl = endpointUrl;
+            if (!discoveryUrl.endsWith("/")) {
+                discoveryUrl += "/";
+            }
+            discoveryUrl += "discovery";
+            endpoints = DiscoveryClient.getEndpoints(discoveryUrl).get();
         }
-        return OpcUaClient.create(endPointUrl,
-                endpoints ->
-                        endpoints.stream()
-                                .filter(e -> e.getSecurityPolicyUri().equals(SecurityPolicy.None.getUri()))
-                                .findFirst(),
-                configBuilder ->
-                        configBuilder
-                                .setApplicationName(LocalizedText.english("eclipse milo opc-ua client"))
-                                .setApplicationUri("urn:eclipse:milo:examples:client")
-                                //访问方式(new AnonymousProvider()表示使用匿名方式访问,也可以通过new UsernameProvider(userName, password)方式访问。)
-                                .setIdentityProvider(new AnonymousProvider())
-                                .setRequestTimeout(UInteger.valueOf(5000))
-                                .build()
-        );
+        EndpointDescription endpoint = endpoints.stream()
+                .filter(e -> e.getSecurityPolicyUri().equals(SecurityPolicy.None.getUri())).filter(endpointFilter())
+                .findFirst().orElseThrow(() -> new Exception("no desired endpoints returned"));
+        OpcUaClientConfig config = OpcUaClientConfig.builder()
+                .setApplicationName(LocalizedText.english("my"))
+                .setApplicationUri("urn:Jellyleo:UnifiedAutomation:UaExpert@Jellyleo")
+                .setCertificate(loader.getClientCertificate()).setKeyPair(loader.getClientKeyPair())
+                .setEndpoint(endpoint)
+//				.setIdentityProvider(new UsernameProvider("jellyleo", "123456"))
+                .setIdentityProvider(new AnonymousProvider()) // 匿名验证
+                .setRequestTimeout(Unsigned.uint(5000)).build();
+
+        return OpcUaClient.create(config);
     }
 
-    /**
-     * 遍历树形节点
-     *
-     * @param client OPC UA客户端
-     * @param uaNode 节点
-     * @throws Exception
-     */
-    private static void browseNode(OpcUaClient client, UaNode uaNode) throws Exception {
+    private static Predicate<EndpointDescription> endpointFilter() {
+        return e -> true;
+    }
+
+    public static CompletableFuture<OpcUaClient> getFuture() {
+        return new CompletableFuture<>();
+    }
+
+    public static List<JSONObject> generOpcUaTree(OpcUaClient client, UaNode uaNode) throws UaException, ExecutionException, InterruptedException {
+        if(Blank.isEmpty(client)){
+            return null;
+        }
+        List<JSONObject> jsonList = new ArrayList<>();
         List<? extends UaNode> nodes;
         if (uaNode == null) {
             nodes = client.getAddressSpace().browseNodes(Identifiers.ObjectsFolder);
@@ -69,134 +103,49 @@ public class OpcServerUaUtil {
             nodes = client.getAddressSpace().browseNodes(uaNode);
         }
         for (UaNode nd : nodes) {
+            if(Blank.isEmpty(nd)){
+                continue;
+            }
             //排除系统行性节点,这些系统性节点名称一般都是以"_"开头
             if (Objects.requireNonNull(nd.getBrowseName().getName()).contains("_")) {
-                continue;
+//                continue;
             }
-            System.out.println("Node= " + nd.getBrowseName().getName());
-            browseNode(client, nd);
+            JSONObject jsonObject = new JSONObject();
+            jsonObject.put("label", nd.getBrowseName().getName());
+//            jsonObject.put("value",client.readValue(0.0, TimestampsToReturn.Neither, nd.getNodeId()).get());
+            jsonObject.put("children", generOpcUaTree(client, nd));
+            jsonList.add(jsonObject);
         }
+        return jsonList;
     }
 
-    /**
-     * 读取节点数据
-     *
-     * @param client OPC UA客户端
-     * @throws Exception
-     */
-    private static void readNode(OpcUaClient client) throws Exception {
-        int namespaceIndex = 2;
-        String identifier = "TD-01.SB-01.AG-01";
-        //节点
-        NodeId nodeId = new NodeId(namespaceIndex, identifier);
-        //读取节点数据
-        DataValue value = client.readValue(0.0, TimestampsToReturn.Neither, nodeId).get();
-        //标识符
-        identifier = String.valueOf(nodeId.getIdentifier());
-        System.out.println(identifier + ": " + String.valueOf(value.getValue().getValue()));
-    }
-
-    /**
-     * 写入节点数据
-     *
-     * @param client
-     * @throws Exception
-     */
-    private static void writeNodeValue(OpcUaClient client) throws Exception {
-        //节点
-        NodeId nodeId = new NodeId(2, "TD-01.SB-01.AG-01");
-        short i = 3;
-        //创建数据对象,此处的数据对象一定要定义类型,不然会出现类型错误,导致无法写入
-        DataValue nowValue = new DataValue(new Variant(i), null, null);
-        //写入节点数据
-        StatusCode statusCode = client.writeValue(nodeId, nowValue).join();
-        System.out.println("结果:" + statusCode.isGood());
-    }
-
-    /**
-     * 订阅(单个)
-     *
-     * @param client
-     * @throws Exception
-     */
-    private static void subscribe(OpcUaClient client) throws Exception {
-        //创建发布间隔1000ms的订阅对象
-        client
-                .getSubscriptionManager()
-                .createSubscription(1000.0)
-                .thenAccept(t -> {
-                    //节点
-                    NodeId nodeId = new NodeId(2, "TD-01.SB-01.AG-01");
-                    ReadValueId readValueId = new ReadValueId(nodeId, AttributeId.Value.uid(), null, null);
-                    //创建监控的参数
-                    MonitoringParameters parameters = new MonitoringParameters(UInteger.valueOf(1), 1000.0, null, UInteger.valueOf(10), true);
-//                    MonitoringParameters parameters = new MonitoringParameters(UInteger.valueOf(atomic.getAndIncrement()), 1000.0, null, UInteger.valueOf(10), true);
-                    //创建监控项请求
-                    //该请求最后用于创建订阅。
-                    MonitoredItemCreateRequest request = new MonitoredItemCreateRequest(readValueId, MonitoringMode.Reporting, parameters);
-                    List<MonitoredItemCreateRequest> requests = new ArrayList<>();
-                    requests.add(request);
-                    //创建监控项,并且注册变量值改变时候的回调函数。
-                    t.createMonitoredItems(
-                            TimestampsToReturn.Both,
-                            requests,
-                            (item, id) -> item.setValueConsumer((it, val) -> {
-                                System.out.println("nodeid :" + it.getReadValueId().getNodeId());
-                                System.out.println("value :" + val.getValue().getValue());
-                            })
-                    );
-                }).get();
-
-        //持续订阅
-        Thread.sleep(Long.MAX_VALUE);
-    }
-
-    /**
-     * 批量订阅
-     *
-     * @param client
-     * @throws Exception
-     */
-    private static void managedSubscriptionEvent(OpcUaClient client) throws Exception {
-        final CountDownLatch eventLatch = new CountDownLatch(1);
-
-        //处理订阅业务
-        handlerNode(client);
-
-        //持续监听
-        eventLatch.await();
-    }
-
-    /**
-     * 处理订阅业务
-     *
-     * @param client OPC UA客户端
-     */
-    private static void handlerNode(OpcUaClient client) {
-        try {
-            //创建订阅
-            ManagedSubscription subscription = ManagedSubscription.create(client);
-
-            //你所需要订阅的key
-            List<String> key = new ArrayList<>();
-            key.add("TD-01.SB-01.AG-01");
-            key.add("TD-01.SB-01.AG-02");
-
-            List<NodeId> nodeIdList = new ArrayList<>();
-            for (String s : key) {
-                nodeIdList.add(new NodeId(2, s));
-            }
-
-            //监听
-            List<ManagedDataItem> dataItemList = subscription.createDataItems(nodeIdList);
-            for (ManagedDataItem managedDataItem : dataItemList) {
-                managedDataItem.addDataValueListener((t) -> {
-                    System.out.println(managedDataItem.getNodeId().getIdentifier().toString() + ":" + t.getValue().getValue().toString());
-                });
-            }
-        } catch (Exception e) {
-            e.printStackTrace();
-        }
-    }
+//    private  void browseNode(OpcUaClient client, UaNode uaNode) throws Exception {
+//        List<? extends UaNode> nodes;
+//        if (uaNode == null) {
+//			nodes = client.getAddressSpace().browseNodes(Identifiers.ObjectsFolder);//从根目录
+////            nodes = client.getAddressSpace().browseNodes(new NodeId(2,"my"));//指定目录
+//        } else {
+//            nodes = client.getAddressSpace().browseNodes(uaNode);
+//        }
+//        if (ObjectUtils.isEmpty(nodes)) {
+//            return;
+//        }
+//        for (UaNode nd : nodes) {
+//            if (nd.getBrowseName().getName().contains("test")) {
+//                browseNode(client, nd);
+//            }
+//            if (nd.getBrowseName().getName().contains("name")) {
+//                Object identifier = nd.getNodeId().getIdentifier();
+//                String s = identifier.toString();
+//
+//                nodeNames.add(s);
+//            }
+////			//排除系统行性节点,这些系统性节点名称一般都是以"_"开头
+////			if (Objects.requireNonNull(nd.getBrowseName().getName()).contains("_")) {
+////				continue;
+////			}
+//        }
+//        System.err.println();
+//    }
 
 }

+ 1 - 1
chuanyi_server/src/main/java/com/judong/chuanyiserver/util/RSAUtil.java

@@ -15,7 +15,7 @@ import javax.crypto.Cipher;
 public class RSAUtil {
 	
 	public static void main(String[] args) {
-		String a = "fsfdfdg汉字sfsf";
+		String a = "jd123456";
 		String b = encryptByPublic(a, PUBLIC_KEY);
 		System.out.println(b);
 		try {

+ 1 - 1
chuanyi_server/src/main/resources/mapper/ConnectDao.xml

@@ -32,7 +32,7 @@
         where id = #{id}
     </select>
     <select id="selectAllConnect" resultType="com.judong.chuanyiserver.entity.ServerInformation">
-        select id, user_id, ip_address, ip_user_name, ip_password, agreement_type, create_time
+        select id, ip_address, agreement_type, create_time
         from server_information
         where user_id = #{userId}
         order by create_time desc