您的位置:首页 > 科技 > IT业 > 不收费的网站_石家庄新闻头条新闻最新今天_外贸订单怎样去寻找_网络营销公司有哪些公司

不收费的网站_石家庄新闻头条新闻最新今天_外贸订单怎样去寻找_网络营销公司有哪些公司

2024/12/23 2:47:45 来源:https://blog.csdn.net/weixin_40986713/article/details/143489661  浏览:    关键词:不收费的网站_石家庄新闻头条新闻最新今天_外贸订单怎样去寻找_网络营销公司有哪些公司
不收费的网站_石家庄新闻头条新闻最新今天_外贸订单怎样去寻找_网络营销公司有哪些公司

前言

之前我写的springboot项目中的opc ua连接配置信息都是写在springboot项目的yml文件里,每次修改连接配置都需要重启springboot服务。而且在大多数时候,我部署项目的时候,还不知道opc ua的连接信息,部署完毕后,才从相关的技术人员哪里拿到opc ua的连接信息,索引我想,要是能够设置成通过网页配置的可能会更好,说干就干,下面是实现教程!

快速开始

引入Maven依赖

在pom.xml文件配置里引入milo的jar依赖,配置如下:

        <!-- milo opc ua --><dependency><groupId>org.eclipse.milo</groupId><artifactId>sdk-client</artifactId><version>0.6.11</version></dependency>

编写java代码

controller层代码


import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springblade.coalface.modules.communicate.entity.OpcUaCommunicate;
import org.springblade.coalface.modules.communicate.service.CommunicateService;
import org.springblade.coalface.modules.opcua.service.OpcUaTemplate;
import org.springblade.core.tool.api.R;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;import javax.validation.Valid;
import java.util.regex.Matcher;
import java.util.regex.Pattern;@RestController
@Api(tags = "通讯配置")
@RequestMapping("/communicate/config")
@AllArgsConstructor
@Slf4j
public class CommunicateController {private final OpcUaTemplate opcUaTemplate;private final CommunicateService communicateService;private static final String OPC_TCP_REGEX = "^opc.tcp://(\\d{1,3}\\.){3}\\d{1,3}:(\\d{1,5})$";@GetMapping("/opcua")@ApiOperation(value = "获取opc ua配置")public R<OpcUaCommunicate> getOpcUaConfig() {return R.data(communicateService.getOpcUaCommunicate());}@PostMapping("/opcua/update")@ApiOperation(value = "修改opc ua配置")@Transactional(rollbackFor = Exception.class)public R<String> updateOpcUaConfig(@RequestBody @Valid OpcUaCommunicate opcUaCommunicate) {if(!isValidOpcTcp(opcUaCommunicate.getEndPointUrl())){return R.fail("opu ua endPointUrl格式错误");}opcUaTemplate.updateConfig(opcUaCommunicate);communicateService.saveOpcUaCommunicate(opcUaCommunicate);return R.success();}// 检验URL格式的方法public  boolean isValidOpcTcp(String url) {return isValidRegex(url, OPC_TCP_REGEX);}public  boolean isValidRegex(String url, String regex) {if (url == null) {return false;}Pattern URL_PATTERN = Pattern.compile(regex);Matcher matcher = URL_PATTERN.matcher(url);if(matcher.matches()){int startIndex = url.indexOf("//") + 2; // 找到"//"的位置并加2,跳过"//"int endIndex = url.indexOf(":", startIndex);String ip=url.substring(startIndex, endIndex);String[] parts = ip.split("\\.");for (String part : parts) {int num = Integer.parseInt(part);if (num < 0 || num > 255) {return false;}}String port=url.substring(endIndex+1);System.out.println(port);int portNum = Integer.parseInt(port);return portNum >= 0 && portNum <= 65535;}return false;}}

接口参数类

代码如下:

package org.springblade.coalface.modules.communicate.entity;import lombok.Data;import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;@Data
public class OpcUaCommunicate {@NotNullprivate Boolean enabled;@NotBlankprivate String endPointUrl;private String username;private String password;
}

service服务类

CommunicateService	类,主要是为了将	opc u	a的连接配置信息,保存或者修改到`mongodb`数据库中,并从数据库中查询配置的方法。

代码如下:


import org.springblade.coalface.modules.communicate.entity.OpcUaCommunicate;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;import javax.annotation.Resource;
import java.util.Objects;@Service
@Component
public class CommunicateService {@Resourceprivate MongoTemplate mongoTemplate;private final static String COMMUNICATE_OPC_UA = "communicate_opc_ua";public void saveOpcUaCommunicate(OpcUaCommunicate opcUaCommunicate){mongoTemplate.remove(new Query(),COMMUNICATE_OPC_UA);mongoTemplate.save(opcUaCommunicate,COMMUNICATE_OPC_UA);}public OpcUaCommunicate getOpcUaCommunicate(){OpcUaCommunicate opcUaCommunicate= mongoTemplate.findOne(new Query(),OpcUaCommunicate.class,COMMUNICATE_OPC_UA);if(Objects.isNull(opcUaCommunicate)){opcUaCommunicate=new OpcUaCommunicate();opcUaCommunicate.setEnabled(false);opcUaCommunicate.setEndPointUrl("opc.tcp://127.0.0.1:12685");return opcUaCommunicate;}return opcUaCommunicate;}}
  • 默认设置enabled=false,关闭连接配置

OpcUaTemplate类,主要是为了创建和修改 opc ua客户端和批量读取点位的方法,
代码如下:

import lombok.extern.slf4j.Slf4j;
import org.eclipse.milo.opcua.sdk.client.OpcUaClient;
import org.eclipse.milo.opcua.sdk.client.api.UaClient;
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.sdk.client.api.identity.UsernameProvider;
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.DataValue;
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.UInteger;
import org.eclipse.milo.opcua.stack.core.types.enumerated.BrowseDirection;
import org.eclipse.milo.opcua.stack.core.types.enumerated.BrowseResultMask;
import org.eclipse.milo.opcua.stack.core.types.enumerated.NodeClass;
import org.eclipse.milo.opcua.stack.core.types.enumerated.TimestampsToReturn;
import org.eclipse.milo.opcua.stack.core.types.structured.BrowseDescription;
import org.eclipse.milo.opcua.stack.core.types.structured.BrowseResult;
import org.eclipse.milo.opcua.stack.core.types.structured.EndpointDescription;
import org.eclipse.milo.opcua.stack.core.types.structured.ReferenceDescription;
import org.springblade.coalface.listener.OpcSubscriptionListener;
import org.springblade.coalface.modules.communicate.entity.OpcUaCommunicate;
import org.springblade.coalface.modules.communicate.service.CommunicateService;
import org.springblade.coalface.modules.opcua.dto.OpcKey;
import org.springblade.core.tool.utils.CollectionUtil;
import org.springblade.core.tool.utils.StringUtil;
import org.springframework.stereotype.Service;import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.concurrent.ExecutionException;
import java.util.function.Function;@Slf4j
@Service
public class OpcUaTemplate {@Resourceprivate CommunicateService communicateService;private OpcUaClient opcUaClient;@PostConstructprivate void init() {try {OpcUaCommunicate opcUaCommunicate= communicateService.getOpcUaCommunicate();System.out.println(opcUaCommunicate);if(opcUaCommunicate.getEnabled()){opcUaClient=createClient(opcUaCommunicate.getEndPointUrl(),opcUaCommunicate.getUsername(),opcUaCommunicate.getPassword());this.connect();opcUaClient.getSubscriptionManager().createSubscription(1000.0).get();opcUaClient.getSubscriptionManager().addSubscriptionListener(new OpcSubscriptionListener(opcUaClient));}} catch (UaException e) {log.error(e.getMessage());throw new RuntimeException(e);} catch (ExecutionException | InterruptedException e) {throw new RuntimeException(e);}}public OpcUaClient createClient(String endPointUrl,String username,String password) throws UaException {Function<List<EndpointDescription>, Optional<EndpointDescription>> selectEndpoint = endpoints -> {final Optional<EndpointDescription> endpoint = endpoints.stream().filter(e -> e.getSecurityPolicyUri().equals(SecurityPolicy.None.getUri())).findFirst();EndpointDescription newEndpoint = new EndpointDescription(endPointUrl, endpoint.get().getServer(), endpoint.get().getServerCertificate(),endpoint.get().getSecurityMode(), endpoint.get().getSecurityPolicyUri(), endpoint.get().getUserIdentityTokens(),endpoint.get().getTransportProfileUri(), endpoint.get().getSecurityLevel());return Optional.of(newEndpoint);};IdentityProvider identityProvider=new AnonymousProvider();if(StringUtil.isNotBlank(username)&&StringUtil.isNotBlank(password)){identityProvider=new UsernameProvider(username,password);}return OpcUaClient.create(endPointUrl,selectEndpoint,configBuilder -> configBuilder.setApplicationName(LocalizedText.english("eclipse milo coalface client")).setApplicationUri("urn:eclipse:milo:coalface:client")//访问方式.setIdentityProvider(identityProvider).setRequestTimeout(UInteger.valueOf(60000)).build());}public void connect() {try {opcUaClient.connect().whenComplete((result, ex) -> {if (ex != null) {log.error(ex.getMessage());} else {log.info("{} 连接成功!", opcUaClient.getConfig().getApplicationUri());}}).get();} catch (InterruptedException | ExecutionException e) {throw new RuntimeException(e);}}public void disconnect() {if(Objects.nonNull(opcUaClient)) {try {opcUaClient.disconnect().whenComplete((result, ex) -> {if (ex != null) {log.error(ex.getMessage());} else {log.info("{} 断开连接成功!", opcUaClient.getConfig().getApplicationUri());}}).get();} catch (InterruptedException | ExecutionException e) {throw new RuntimeException(e);}}}public List<String> getBrowseKeys(String identifier) {List<String> keys = new ArrayList<>(1000);try {opcUaClient.connect().get();browse(identifier, keys, opcUaClient);opcUaClient.disconnect().get();} catch (Exception e) {log.error(e.getMessage());}keys.remove(null);return keys;}private void browse(String identifier, List<String> keys, UaClient client) throws Exception {NodeId nodeId = Identifiers.ObjectsFolder;if (!StringUtils.isEmpty(identifier)) {nodeId = new NodeId(2, identifier);}BrowseDescription browse = new BrowseDescription(nodeId,BrowseDirection.Forward,Identifiers.References,true,UInteger.valueOf(NodeClass.Object.getValue() | NodeClass.Variable.getValue()),UInteger.valueOf(BrowseResultMask.All.getValue()));BrowseResult browseResult = client.browse(browse).get();ReferenceDescription[] references = browseResult.getReferences();for (ReferenceDescription reference : references) {if (reference.getNodeClass().getValue() == NodeClass.Variable.getValue()) {keys.add(reference.getNodeId().getIdentifier().toString());}browse(reference.getNodeId().getIdentifier().toString(), keys, client);}}public List<DataValue> readValues(List<OpcKey> keys) {//  List<String> keyNames = getKeyNames(keys);/*  List<DataValue> res= BatchUtil.protectBach(keyNames, idList->{return this.readValues(idList, client);},1000);*/List<DataValue> dataValues = new ArrayList<>(1000);if (Objects.isNull(opcUaClient)) {return dataValues;}if (CollectionUtil.isNotEmpty(keys)) {List<NodeId> nodeIds = new ArrayList<>(1000);keys.forEach(e -> {NodeId nodeId = new NodeId(2, e.getPointAddress());nodeIds.add(nodeId);});try {dataValues = opcUaClient.readValues(0.0, TimestampsToReturn.Neither, nodeIds).get();} catch (InterruptedException | ExecutionException e) {log.error("{} {}", opcUaClient.getConfig().getApplicationUri(), e.getMessage());}}return dataValues;}public void updateConfig(OpcUaCommunicate opcUaCommunicate) {this.disconnect();if(opcUaCommunicate.getEnabled()){try {opcUaClient=createClient(opcUaCommunicate.getEndPointUrl());this.connect();opcUaClient.getSubscriptionManager().createSubscription(1000.0).get();opcUaClient.getSubscriptionManager().addSubscriptionListener(new OpcSubscriptionListener(opcUaClient));} catch (UaException | ExecutionException | InterruptedException e) {throw new RuntimeException(e);}}else{opcUaClient=null;}}
}
  • 项目启动时,会先从mongodb中读取opc ua 连接配置,如果没有则返回默认配置
  • 用户和密码都不为空的时候,是密码校验连接模式,否则是匿名用户连接模式

结语

以上便是全部的代码教程,个别工具类是blade框架内自带的工具类,需要根据自己的情况进行替换。谢谢大家,觉得不错就一键三联!!!

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com