yantian yue
2023-10-18 69fbaaa1a5fd16b05953e750ea7fcc3e18e3a27c
提交 | 用户 | 时间
487b2f 1 package cn.stylefeng.guns.opcua.client;
YY 2
f4a343 3 import cn.stylefeng.guns.base.pojo.page.LayuiPageFactory;
YY 4 import cn.stylefeng.guns.base.pojo.page.LayuiPageInfo;
5 import cn.stylefeng.guns.opcua.controller.OpcuaConfController;
6 import cn.stylefeng.guns.opcua.entity.OpcuaConf;
7 import cn.stylefeng.guns.opcua.mapper.OpcuaConfMapper;
8 import cn.stylefeng.guns.opcua.model.params.OpcuaConfParam;
9 import cn.stylefeng.guns.opcua.model.result.OpcuaConfResult;
10 import cn.stylefeng.guns.opcua.service.OpcuaConfService;
11 import cn.stylefeng.roses.kernel.model.response.ResponseData;
12 import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
487b2f 13 import com.google.common.collect.ImmutableList;
YY 14 import cn.stylefeng.guns.opcua.entity.NodeEntity;
15 import lombok.extern.slf4j.Slf4j;
f4a343 16 import org.apache.poi.ss.formula.functions.T;
487b2f 17 import org.eclipse.milo.opcua.sdk.client.OpcUaClient;
YY 18 import org.eclipse.milo.opcua.sdk.client.api.nodes.VariableNode;
19 import org.eclipse.milo.opcua.sdk.client.api.subscriptions.UaSubscription;
20 import org.eclipse.milo.opcua.stack.core.AttributeId;
21 import org.eclipse.milo.opcua.stack.core.BuiltinDataType;
22 import org.eclipse.milo.opcua.stack.core.types.builtin.DataValue;
23 import org.eclipse.milo.opcua.stack.core.types.builtin.NodeId;
24 import org.eclipse.milo.opcua.stack.core.types.builtin.StatusCode;
25 import org.eclipse.milo.opcua.stack.core.types.builtin.Variant;
26 import org.eclipse.milo.opcua.stack.core.types.builtin.unsigned.Unsigned;
27 import org.eclipse.milo.opcua.stack.core.types.enumerated.MonitoringMode;
28 import org.eclipse.milo.opcua.stack.core.types.enumerated.TimestampsToReturn;
29 import org.eclipse.milo.opcua.stack.core.types.structured.MonitoredItemCreateRequest;
30 import org.eclipse.milo.opcua.stack.core.types.structured.MonitoringParameters;
31 import org.eclipse.milo.opcua.stack.core.types.structured.ReadValueId;
32 import org.springframework.beans.factory.annotation.Autowired;
33 import org.springframework.stereotype.Service;
34 import org.springframework.util.CollectionUtils;
35
36 import java.lang.reflect.InvocationTargetException;
37 import java.lang.reflect.Method;
38 import java.util.ArrayList;
39 import java.util.List;
40
41 /**
42  * @ClassName: ClientHandler
43  * @Description: 客户端处理
44  * @author Jellyleo
45  * @date 2019年12月12日
46  */
47 @Slf4j
48 @Service
49 public class ClientHandler {
50
51     // 客户端实例
52     private OpcUaClient client = null;
53
54     @Autowired
55     private ClientRunner clientRunner;
f4a343 56
YY 57     @Autowired
58     private OpcuaConfController opcuaConfController;
69fbaa 59
487b2f 60
YY 61     /**
62      * 
63      * @MethodName: connect
64      * @Description: connect
65      * @throws Exception
66      * @CreateTime 2019年12月18日 上午10:41:09
67      */
68     public String connect() throws Exception {
69
70         if (client != null) {
71             return "客户端已创建";
72         }
73
74         client = clientRunner.run();
75
76         if (client == null) {
77             return "客户端配置实例化失败";
78         }
79
80         // 创建连接
81         client.connect().get();
82         return "创建连接成功";
83     }
84
85     /**
86      * @MethodName: disconnect
87      * @Description: 断开连接
88      * @return
89      * @throws Exception
90      * @CreateTime 2019年12月18日 上午10:45:21
91      */
92     public String disconnect() throws Exception {
93
94         if (client == null) {
95             return "连接已断开";
96         }
97
98         // 断开连接
99         clientRunner.getFuture().complete(client);
100         client = null;
101         return "断开连接成功";
102     }
103
104     /**
105      * @MethodName: subscribe
106      * @Description: 订阅节点变量
107      * @throws Exception
108      * @CreateTime 2019年12月18日 上午10:38:11
109      */
110     public String subscribe(List<NodeEntity> nodes) throws Exception {
111
112         if (client == null) {
113             return "找不到客户端,操作失败";
114         }
115
116 //        List<Node> ns = client.getAddressSpace().browse(new NodeId(2, "模拟通道一.模拟设备一")).get();
117
118         // 查询订阅对象,没有则创建
119         UaSubscription subscription = null;
120         ImmutableList<UaSubscription> subscriptionList = client.getSubscriptionManager().getSubscriptions();
121         if (CollectionUtils.isEmpty(subscriptionList)) {
122             subscription = client.getSubscriptionManager().createSubscription(1000.0).get();
123         } else {
124             subscription = subscriptionList.get(0);
125         }
126
127         // 监控项请求列表
128         List<MonitoredItemCreateRequest> requests = new ArrayList<>();
129
130         if (!CollectionUtils.isEmpty(nodes)) {
131             for (NodeEntity node : nodes) {
132                 // 创建监控的参数
133                 MonitoringParameters parameters = new MonitoringParameters(subscription.nextClientHandle(), 1000.0, // sampling
134                         // interval
135                         null, // filter, null means use default
136                         Unsigned.uint(10), // queue size
137                         true // discard oldest
138                 );
139                 // 创建订阅的变量, 创建监控项请 求
140                 MonitoredItemCreateRequest request = new MonitoredItemCreateRequest(
141                         new ReadValueId(new NodeId(node.getIndex(), node.getIdentifier()), AttributeId.Value.uid(),
142                                 null, null),
143                         MonitoringMode.Reporting, parameters);
144                 requests.add(request);
145             }
146         }
147
148         // 创建监控项,并且注册变量值改变时候的回调函数
149         subscription.createMonitoredItems(TimestampsToReturn.Both, requests, (item, id) -> {
150             item.setValueConsumer((i, v) -> {
151                 handle(i.getReadValueId().getNodeId(), v.getValue());
152             });
153         }).get();
154
155         return "订阅成功";
156     }
157
158     /**
159      * * @MethodName: write
160      * @Description: 回调函数
161      * @CreateTime 2023年10月13日
162      */
163
164     public void handle(NodeId id, Variant value){
69fbaa 165         long startTime = System.currentTimeMillis();
YY 166
f4a343 167         OpcuaConfParam opcuaConfParam=new OpcuaConfParam();
YY 168         opcuaConfParam.setNode(id.getIdentifier().toString());
69fbaa 169         List<OpcuaConfResult> a=opcuaConfController.mylist(opcuaConfParam);
YY 170
487b2f 171         String str1 = id.getIdentifier().toString()+":"+value.getValue().toString();
YY 172         try {
f4a343 173             Class<?> clazz = Class.forName(a.get(0).getRModule());
YY 174             Method method = clazz.getMethod(a.get(0).getRFunction(), String.class);
487b2f 175
YY 176             method.invoke(clazz.newInstance(), str1);
177         } catch (ClassNotFoundException | NoSuchMethodException | IllegalAccessException | InstantiationException |
178                  InvocationTargetException e) {
179             e.printStackTrace();
180         }
69fbaa 181         log.info("代码执行时间:" + (System.currentTimeMillis() - startTime) + "毫秒");
487b2f 182     }
YY 183
184     /**
185      * @MethodName: write
186      * @Description: 变节点量写入
187      * @param node
188      * @throws Exception
189      * @CreateTime 2019年12月18日 上午9:51:40
190      */
191     public String write(NodeEntity node) throws Exception {
192
193         if (client == null) {
194             return "找不到客户端,操作失败";
195         }
196
197         NodeId nodeId = new NodeId(node.getIndex(), node.getIdentifier());
198         Variant value = null;
199         switch (node.getType()) {
200         case "int":
201             value = new Variant(Integer.parseInt(node.getValue().toString()));
202             break;
203         case "boolean":
204             value = new Variant(Boolean.parseBoolean(node.getValue().toString()));
205             break;
206         }
207         DataValue dataValue = new DataValue(value, null, null);
208
209         StatusCode statusCode = client.writeValue(nodeId, dataValue).get();
210
211         return "节点【" + node.getIdentifier() + "】写入状态:" + statusCode.isGood();
212     }
213
214     /**
215      * @MethodName: read
216      * @Description: 读取
217      * @param node
218      * @return
219      * @throws Exception
220      * @CreateTime 2019年12月19日 下午2:40:34
221      */
222     public String read(NodeEntity node) throws Exception {
223
224         if (client == null) {
225             return "找不到客户端,操作失败";
226         }
227
228         NodeId nodeId = new NodeId(node.getIndex(), node.getIdentifier());
229         VariableNode vnode = client.getAddressSpace().createVariableNode(nodeId);
230         DataValue value = vnode.readValue().get();
231         log.info("Value={}", value);
232
233         Variant variant = value.getValue();
234         log.info("Variant={}", variant.getValue());
235
236         log.info("BackingClass={}", BuiltinDataType.getBackingClass(variant.getDataType().get()));
237
238         return "节点【" + node.getIdentifier() + "】:" + variant.getValue();
239     }
240 }