OPCDAServiceImpl.java 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265
  1. package com.sckj.opc.dauaservice;
  2. import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
  3. import com.google.common.eventbus.AsyncEventBus;
  4. import com.sckj.opc.dto.OPCPointDTO;
  5. import com.sckj.opc.entity.OPCData;
  6. import com.sckj.opc.entity.OPCPoint;
  7. import com.sckj.opc.entity.OPCServer;
  8. import com.sckj.opc.service.OPCDataServiceImpl;
  9. import com.sckj.opc.service.OPCPointServiceImpl;
  10. import com.sckj.opc.service.OPCServerServiceImpl;
  11. import com.sckj.opc.utils.CustomUtil;
  12. import lombok.extern.slf4j.Slf4j;
  13. import org.apache.commons.lang3.ObjectUtils;
  14. import org.jinterop.dcom.common.JIException;
  15. import org.openscada.opc.lib.common.ConnectionInformation;
  16. import org.openscada.opc.lib.da.*;
  17. import org.springframework.beans.BeanUtils;
  18. import org.springframework.beans.factory.annotation.Value;
  19. import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
  20. import org.springframework.stereotype.Service;
  21. import javax.annotation.PreDestroy;
  22. import javax.annotation.Resource;
  23. import java.text.DecimalFormat;
  24. import java.util.Calendar;
  25. import java.util.List;
  26. import java.util.Objects;
  27. import java.util.concurrent.Callable;
  28. import java.util.concurrent.ConcurrentHashMap;
  29. import java.util.concurrent.Executors;
  30. import java.util.concurrent.Future;
  31. @Service
  32. @Slf4j
  33. public class OPCDAServiceImpl {
  34. @Resource
  35. OPCServerServiceImpl opcServerService;
  36. @Resource
  37. OPCPointServiceImpl opcPointService;
  38. @Resource
  39. OPCDataServiceImpl opcDataService;
  40. @Resource
  41. private AsyncEventBus asyncEventBus;
  42. @Resource(name = "taskExecutor")
  43. ThreadPoolTaskExecutor taskExecutor;
  44. @Value("${spring.profiles.active}")
  45. protected String activeProfiles;
  46. private ConcurrentHashMap<Long, Server> mOPCDaClientMap = new ConcurrentHashMap<>();
  47. private ConcurrentHashMap<String, OPCData> mOPCDaPointsMap = new ConcurrentHashMap<>();
  48. /**
  49. * 获得基础的连接信息
  50. */
  51. public Server createServer(OPCServer opcServer) {
  52. return mOPCDaClientMap.computeIfAbsent(opcServer.getId(), id -> {
  53. final ConnectionInformation ci = new ConnectionInformation();
  54. ci.setHost(opcServer.getIp());
  55. ci.setUser(opcServer.getUsername());
  56. ci.setPassword(opcServer.getPassword());
  57. ci.setClsid(opcServer.getClsid());
  58. log.info("Create Server : {}", opcServer);
  59. log.info("availableProcessors:{}", Runtime.getRuntime().availableProcessors());
  60. final Server server = new Server(ci, Executors.newSingleThreadScheduledExecutor());
  61. AutoReconnectController controller = new AutoReconnectController(server);
  62. controller.connect();
  63. return server;
  64. });
  65. }
  66. public Object createSubscription(OPCServer opcServer, OPCPoint opcPoint) {
  67. StringBuilder sb = new StringBuilder();
  68. if (ObjectUtils.isNotEmpty(opcPoint) && !mOPCDaPointsMap.containsKey(opcPoint.getPointName())) {
  69. Future<String> future = taskExecutor.submit(new Callable<String>() {
  70. @Override
  71. public String call() {
  72. try {
  73. Server server = createServer(opcServer);
  74. AccessBase access = new SyncAccess(server, opcPoint.getPeriod() * 1000);
  75. String newPointName = opcPoint.getPointName();
  76. if (ObjectUtils.isEmpty(newPointName)) {
  77. return null;
  78. }
  79. newPointName = CustomUtil.createNewPointName(newPointName,activeProfiles);
  80. log.info("{} start subscribe", newPointName);
  81. mOPCDaPointsMap.put(opcPoint.getPointName(), OPCData.builder().build());
  82. access.addItem(newPointName, (item, itemstate) -> {
  83. int errorCode = itemstate.getErrorCode();
  84. String pointName = item.getId();
  85. Calendar calendar = itemstate.getTimestamp();
  86. Object object = null;
  87. try {
  88. object = itemstate.getValue().getObject();
  89. } catch (JIException e) {
  90. e.printStackTrace();
  91. }
  92. synchronized (mOPCDaPointsMap) {
  93. //DA中订阅是按照定时计算的,存在重复的数据项,进行过滤
  94. OPCData previousData = mOPCDaPointsMap.get(opcPoint.getPointName());
  95. Object currentData = object;
  96. //直接比较原始对象,避免字符串转换误差
  97. boolean isNewData = previousData == null ||
  98. !Objects.equals(previousData.getData(), currentData);
  99. // 添加数值精度处理(处理小数点后2位)
  100. if (!isNewData && currentData instanceof Number) {
  101. DecimalFormat df = new DecimalFormat("#.##");
  102. String prev = df.format(previousData.getData());
  103. String curr = df.format(currentData);
  104. isNewData = !prev.equals(curr);
  105. }
  106. if (isNewData) {
  107. OPCData opcData = OPCData.builder()
  108. .data(object)
  109. .serverTime(calendar.getTime())
  110. .sourceTime(calendar.getTime())
  111. .statusCode((long) errorCode)
  112. .pointName(pointName)
  113. .build();
  114. // 使用put原子操作更新数据
  115. mOPCDaPointsMap.put(opcPoint.getPointName(), opcData);
  116. //post给其他模块使用
  117. asyncEventBus.post(opcData);
  118. log.debug("DA,{},{}", item.getId(), itemstate);
  119. }
  120. }
  121. });
  122. access.bind();
  123. while (mOPCDaPointsMap.containsKey(opcPoint.getPointName())) {
  124. //阻塞,直到关闭订阅
  125. Thread.sleep(100); // 避免 CPU 空转
  126. }
  127. access.unbind();
  128. log.info("{} stop subscribe", opcPoint.getPointName());
  129. } catch (Exception e) {
  130. e.printStackTrace();
  131. return e.getMessage();
  132. }
  133. return "";
  134. }
  135. });
  136. // try {
  137. // String result = future.get(10, TimeUnit.SECONDS); //
  138. // log.error(">>> error:{}", result);
  139. // if (ObjectUtils.isNotEmpty(result)) {
  140. // sb.append(opcPoint.getPointName() + "订阅异常:" + result);
  141. // }
  142. // } catch (Exception e) {
  143. // e.printStackTrace();
  144. // log.info("订阅异常:{}", opcPoint.getPointName());
  145. // }
  146. }
  147. return sb;
  148. }
  149. public Object subscribe(OPCPoint opcPoint) {
  150. try {
  151. OPCPointDTO opcPointDTO = opcPointService.selectInfoWithServer(opcPoint);
  152. QueryWrapper<OPCPoint> pointQueryWrapper = new QueryWrapper<>();
  153. pointQueryWrapper.lambda().eq(OPCPoint::getStatus, "1");
  154. OPCServer opcServer = new OPCServer();
  155. BeanUtils.copyProperties(opcPointDTO, opcServer);
  156. return createSubscription(opcServer, opcPointDTO);
  157. } catch (Exception e) {
  158. e.printStackTrace();
  159. }
  160. return null;
  161. }
  162. /***
  163. * 取消订阅
  164. * @param opcPoint
  165. */
  166. public void unsubscribe(OPCPoint opcPoint) {
  167. mOPCDaPointsMap.remove(opcPoint.getId());
  168. }
  169. /***
  170. * 取消可用订阅
  171. */
  172. public void unsubscribeAvailable() {
  173. mOPCDaPointsMap.clear();
  174. }
  175. /**
  176. * 项目启动时自动创建 PLC连接并订阅节点
  177. */
  178. public void subscribeAvailable() {
  179. QueryWrapper<OPCServer> serverQueryWrapper = new QueryWrapper<>();
  180. serverQueryWrapper.lambda().eq(OPCServer::getStatus, "1");
  181. List<OPCServer> opcServerList = opcServerService.list(serverQueryWrapper);
  182. if (ObjectUtils.isEmpty(opcServerList)) {
  183. return;
  184. }
  185. for (OPCServer opcServer : opcServerList) {
  186. QueryWrapper<OPCPoint> pointQueryWrapper = new QueryWrapper<>();
  187. pointQueryWrapper.lambda().eq(OPCPoint::getOpcServerId, opcServer.getId()).eq(OPCPoint::getStatus, "1");
  188. List<OPCPoint> opcPointList = opcPointService.list(pointQueryWrapper);
  189. if (ObjectUtils.isNotEmpty(opcPointList)) {
  190. log.info("start point list:");
  191. for (OPCPoint opcPoint : opcPointList) {
  192. log.info(opcPoint.getPointName());
  193. createSubscription(opcServer, opcPoint);
  194. }
  195. }
  196. }
  197. }
  198. /**
  199. * 读取节点数据
  200. * <p>
  201. * identifier也可以通过UaExpert客户端去查询,这个值=通道名称.设备名称.标记名称
  202. *
  203. * @param opcPoint
  204. * @throws Exception
  205. */
  206. public String readNodeValue(OPCPoint opcPoint) throws Exception {
  207. OPCPointDTO opcPointDTO = opcPointService.selectInfoWithServer(opcPoint);
  208. if (ObjectUtils.isEmpty(opcPointDTO)) {
  209. return null;
  210. }
  211. OPCServer opcServer = new OPCServer();
  212. BeanUtils.copyProperties(opcPointDTO, opcServer);
  213. Server server = createServer(opcServer);
  214. Group group = server.addGroup();
  215. Item item = group.addItem(opcPointDTO.getPointName());
  216. return String.valueOf(item.read(true).getValue().getObject());
  217. }
  218. @PreDestroy
  219. public void releaseServer() {
  220. if (ObjectUtils.isNotEmpty(mOPCDaClientMap)) {
  221. for (Server server : mOPCDaClientMap.values()) {
  222. server.dispose();
  223. }
  224. }
  225. }
  226. }