首页 > 其他分享 >PLC通讯

PLC通讯

时间:2023-08-17 14:34:22浏览次数:37  
标签:通讯 return milo param client PLC org import


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.api.identity.IdentityProvider;
import org.eclipse.milo.opcua.sdk.client.api.identity.UsernameProvider;
import org.eclipse.milo.opcua.stack.client.DiscoveryClient;
import org.eclipse.milo.opcua.stack.core.Identifiers;
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.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.springframework.util.StringUtils;

import java.util.*;
import java.util.concurrent.ExecutionException;

/**
 * @author TARZAN
 */
@Slf4j
public class OpcUaUtil {

    /**
     * 方法描述: 创建客户端
     *
     * @param endPointUrl
     * @param username
     * @param password
     * @return {@link OpcUaClient}
     * @throws
     */
    public static OpcUaClient createClient(String endPointUrl,String username,String password){
        log.info(endPointUrl);
        try {
            //获取安全策略
            List<EndpointDescription> endpointDescription = DiscoveryClient.getEndpoints(endPointUrl).get();
            //过滤出一个自己需要的安全策略
            EndpointDescription endpoint = endpointDescription.stream()
                    .filter(e -> e.getSecurityPolicyUri().equals(SecurityPolicy.None.getUri()))
                    .findFirst().orElse(null);
            IdentityProvider identityProvider=new AnonymousProvider();
            if(!StringUtils.isEmpty(username)||!StringUtils.isEmpty(password)){
                identityProvider=new UsernameProvider(username,password);
            }
            // 设置配置信息
            OpcUaClientConfig config = OpcUaClientConfig.builder()
                    // opc ua 自定义的名称
                    .setApplicationName(LocalizedText.english("plc"))
                    // 地址
                    .setApplicationUri(endPointUrl)
                    // 安全策略等配置
                    .setEndpoint(endpoint)
                    .setIdentityProvider(identityProvider)
                    //等待时间
                    .setRequestTimeout(UInteger.valueOf(5000))
                    .build();
            // 准备连接
            OpcUaClient opcClient =OpcUaClient.create(config);
            //开启连接
            opcClient.connect().get();
            log.info("连接成功。。。success");
            return opcClient;
        } catch (Exception e) {
            e.printStackTrace();
            log.error("======== opc connection fail ========");
        }
        return null;
    }


    /**
     * 方法描述: 查询所有节点
     *
     * @param client
     * @return {@link Set<String>}
     * @throws
     * @author liwenbin
     * @date 2023年07月03日 13:05:55
     */
    public static Set<String> getAllKeys(OpcUaClient client) throws Exception {
        return browse(null,client);
    }


    /**
     * 方法描述: 查询某个节点下的所有节点
     *
     * @param identifier
     * @param client
     * @return
     * @throws
     */
    public static Set<String> browse(String identifier, OpcUaClient client) throws Exception {
        Set<String> keys=new HashSet<>(500);
        browse(identifier,keys,client);
        return keys;
    }

    /**
     * 方法描述: 查询某个节点下的所有节点
     *
     * @param identifier
     * @param client
     * @return
     * @throws
     */
    private static Set<String> browse(String identifier, Set<String> keys, OpcUaClient 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) {
            System.out.println(reference.getNodeId().getIdentifier().toString()+" "+reference.getNodeClass().getValue());
            keys.add(identifier);
            if(reference.getNodeClass().getValue()==NodeClass.Object.getValue()){
                browse(reference.getNodeId().getIdentifier().toString(),keys,client);
            }
        }
        return keys;
    }


    /**
     * 方法描述: 读取单个节点值
     *
     * @param identifier
     * @param client
     * @return {@link Object}
     * @throws
     */
    public static Object readValue(String identifier, OpcUaClient client){
        NodeId nodeId = new NodeId(2, identifier);
        DataValue value = null;
        try {
            client.readValue(0.0, TimestampsToReturn.Both,nodeId);
            value = client.readValue(0.0, TimestampsToReturn.Both, nodeId).get();
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        }
        if(Objects.nonNull(value)&&Objects.nonNull(value.getValue())&&Objects.nonNull(value.getValue().getValue())) {
            return value.getValue().getValue();
        }
        return null;
    }

    /**
     * 方法描述: 读取多个点位的值
     *
     * @param keys 点位集合
     * @param client 客户端
     * @return {@link List<DataValue>}
     * @throws
     */
    public static List<DataValue> readValues(Set<String> keys, OpcUaClient client){
        List<NodeId> nodeIdList=new ArrayList<>(500);
        keys.forEach(e->{
            NodeId nodeId = new NodeId(2, e);
            nodeIdList.add(nodeId);
        });
        try {
            List<DataValue> dataValues=client.readValues(0.0, TimestampsToReturn.Both,nodeIdList).get();
            return dataValues;
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * 写入值
     *
     * @param identifier
     * @param value
     * @throws Exception
     */
    public static void writeValue(String identifier, Object value,OpcUaClient client) throws Exception {
        //创建变量节点
        NodeId nodeId = new NodeId(2, identifier);
        //创建Variant对象和DataValue对象
        Variant v = new Variant(value);
        DataValue dataValue = new DataValue(v, null, null);
        StatusCode statusCode = client.writeValue(nodeId, dataValue).get();
        if(statusCode.isGood()){
            log.info("数据写入成功");
        }else {
            log.error("数据写入失败");
        }
    }


    /**
     * 方法描述:  写入多个节点的值
     *
     * @param keys  节点集合
     * @param values  值集合
     * @param client  客户端
     * @return {@link Object}
     * @throws
     */
    public static Object writeValues(Set<String> keys,List<Object> values,OpcUaClient client){
        List<NodeId> nodeIs=new ArrayList<>(keys.size());
        keys.forEach(e->{
            NodeId nodeId = new NodeId(2, e);
            nodeIs.add(nodeId);
        });
        List<DataValue> dataValues=new ArrayList<>(values.size());
        values.forEach(e->{
            Variant value=new Variant(Double.parseDouble(e.toString()));
            DataValue dataValue=new DataValue(value);
            dataValues.add(dataValue);
        });
        try {
            client.writeValues(nodeIs,dataValues).get();
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * 方法描述: 断开连接
     *
     * @param client
     * @return
     */
    public static void disconnect(OpcUaClient client){
        try {
            client.disconnect().get();
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        }
    }

}


标签:通讯,return,milo,param,client,PLC,org,import
From: https://blog.51cto.com/u_16124071/7122381

相关文章

  • 在Teams/Outlook全局通讯簿中隐藏AAD帐户和组
    背景需求出于安全考虑,某些AzureAD中的组和用户,需要在通讯簿中隐藏,而不被其他用户搜索到。操作步骤隐藏用户使用如下命令查看用户ShowInAddressList属性:Get-AzureADUser-ObjectIduser@contoso.onmicrosoft.comShowInaddresslist=Null代表账号默认不隐藏使用如下命令修改ShowIn......
  • 采集设备都有哪几种方式实现通讯及如何选择
    采集设备都有哪几种方式实现通讯及如何选择采集设备通讯可以通过不同的方式实现,例如:串口通讯:使用串口传输数据,通讯速度较慢,但是稳定可靠。以太网通讯:采集设备通过以太网接口连接到网络,实现数据的传输,通讯速度快,但是需要网络支持。无线通讯:采集设备通过无线方式连接到服务器或者......
  • C#通过PLCSIM ADVANCED与博图连接
    上位机,这里使用C#做上位机程序;在实际项目中,一般上位机可以直接与西门子PLC连接通信;在项目调试阶段,没有PLC的情况下可以通过PLCSIMADVANCED仿真软件与博图连接,实现仿真调试。 步骤如下:第一步、创建博图项目并设置相关参数。1、右键项目树中的项目名称➡属性➡保护➡勾选块......
  • 系统和服务通讯(Topshelf+TouchSocket)
    服务不是单独的,总要和其他系统进行信息交互,记录一个解决方案(方便,好用)Topshelf秒建Windows服务推荐一个超轻量级的.NET网络通信框架新建控制台,然后安装Topshelf和TouchSocket,作为服务示例代码:namespaceTestServer{classProgram{staticvoidMain(s......
  • MT6833天玑700平台_联发科MTK5G安卓核心板智能通讯模块
    联发科MT6833(天玑700)安卓核心板采用八核CPU,包含两颗主频高达2.2GHz的ArmCortex-A76「大」核心,提供更高的效能,带来更畅快的使用体验。高性能LPDDR4X内存频率高达2133MHz,及更快数据传输的UFS2.2,无论是看视频、玩游戏、拍照片、即时聊天或是在线办公都能享有非凡的体验。天玑700采用7......
  • 晨控CK-GW06-E01与汇川H5U系列PLC通讯手册
    晨控CK-GW06-E01与汇川H5U系列PLC通讯手册晨控CK-GW06-E01是一款支持标准工业通讯协议EtherNetIP的网关控制器,方便用户集成到PLC等控制系统中。本控制器提供了网络POE供电和直流电源供电两种方式,确保用户在使用无POE供电功能的交换机时可采用外接电源供电;系统还集成了六路......
  • CAN转PN网关profinet通讯协议与D
    你是否曾经遇到过这样的问题:如何将各种CAN设备连接到PROFINet网络中?捷米JM-PN-CAN通讯网关或许能为你解决这个难题!捷米JM-PN-CAN网关是一款自主研发的通讯网关,具有将从站功能发挥到极致。它能够将各种CAN设备轻松接入到PROfinet网络中,让你的设备实现更加高效、稳定的通信......
  • MODBUS TCP转CCLINK IE协议网关cclinkie通讯设置
    你是否曾经遇到过需要将不同的设备连接到一个统一的网络中?或者你是否曾经遇到过设备之间的通讯协议不兼容的问题?捷米的JM-CCLKIE-TCP通讯网关就是为解决这些问题而设计的。JM-CCLKIE-TCP通讯网关是一款自主研发的CCLINKIEFIELDBASIC从站功能的通讯网关,它的主要功能是将各种MO......
  • MT8788安卓核心板详细参数_MTK安卓主板开发板智能通讯模块
    MT8788安卓核心板集成了一个高效的12nmSoC,内置4GLTE调制解调器,将强大的硬件与到处可连接的全面功能设计相结合。MTK8788智能终端具备许多功能,包括4G、2.4G/5G双频WiFi、蓝牙4.2BLE、2.5W功放、USB、mipi屏接口、三路摄像头接口、GPS和各种传感器等等。MTK8788智能终端还采用了超......
  • 如何用AIRIOT物联网平台接入Modbus通讯协议
    Modbus协议是一种已广泛应用于当今工业控制领域的通用通讯协议。通过此协议,控制器相互之间、或控制器经由网络(如以太网)可以和其它设备之间进行通信。Modbus协议使用的是主从通讯技术,即由主设备主动查询和操作从设备。一般将主控设备方所使用的协议称为ModbusMaster,从设备方使用的......