temz 2023-03-13 13:26 采纳率: 100%
浏览 86
已结题

求java或C#读写和订阅OPC数据

想通过java 或C#读写和订阅OPCUA的数据,但是没有OPC相关的依赖jar包和资料(网上有好多用milo做的,但是我都找不全),有没有牛人能给提供下相关的jar包和demo程序呢,有需要的话可以交些学费

  • 写回答

7条回答 默认 最新

  • 极客智能体-在线 2023-03-13 14:29
    关注

    以下答案由GPT-3.5大模型与博主波罗歌共同编写:
    你可以使用OPC Foundation的UA-.NETStandard和UA-Java SDK来访问OPC UA数据。

    在Java上,可以使用Eclipse Milo,一个开源的OPC UA Stack实现。Milo非常易于使用,它提供了可用于各种用例的高级API,例如:

    • 建立安全连接(Secure Connection)
    • 浏览节点(Browsing Nodes)
    • 订阅变量(Subscribing to variables)
    • 调用方法(Calling methods)
    • 等等

    以下是使用Eclipse Milo访问OPC UA数据的简单示例:

    import org.eclipse.milo.opcua.sdk.client.OpcUaClient;
    import org.eclipse.milo.opcua.sdk.client.api.identity.UsernameProvider;
    import org.eclipse.milo.opcua.sdk.client.api.identity.X509IdentityProvider;
    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.StatusCode;
    import org.eclipse.milo.opcua.stack.core.types.enumerated.IdType;
    import org.eclipse.milo.opcua.stack.core.types.structured.EndpointDescription;
    import org.eclipse.milo.opcua.stack.core.types.structured.LocalizedText;
    
    import java.util.List;
    import java.util.Map;
    import java.util.concurrent.CompletableFuture;
    
    public class Example {
        public static void main(String[] args) throws Exception {
            // Replace with the correct endpoint URL for your server
            String endpointUrl = "opc.tcp://localhost:12686/sample";
    
            OpcUaClientConfig config = OpcUaClientConfig.builder()
                .setEndpoint(endpointUrl)
                .setIdentityProvider(new X509IdentityProvider(
                    cert -> "user",
                    cert -> cert.getSubject().getRfc822Name()))
                .build();
    
            OpcUaClient client = new OpcUaClient(config);
    
            CompletableFuture<Void> future = client.connect();
    
            // Block until connected, or timeout after 15 seconds
            future.get();
    
            // Browse for nodes on the server
            CompletableFuture<List<ReferenceDescription>> browseFuture = client.browseFlat();
    
            List<ReferenceDescription> nodes = browseFuture.get();
    
            // Find the node you want to read or subscribe to
            NodeId nodeId = new NodeId(0, "MyObject");
    
            // Read the value of the node
            CompletableFuture<DataValue> readFuture = client.readValue(nodeId);
    
            DataValue value = readFuture.get();
    
            System.out.println(value.getValue());
    
            // Subscribe to updates on the node in real-time
            CompletableFuture<StatusCode> subscribeFuture = client.subscribe(nodeId);
    
            // Block until subscription is active, or timeout after 5 seconds
            subscribeFuture.get();
    
            for (int i = 0; i < 10; i++) {
                // Wait for a notification to arrive
                CompletableFuture<DataValue> notificationFuture = client.nextNotification();
    
                DataValue notification = notificationFuture.get();
    
                System.out.println(notification.getValue());
            }
    
            // Shutdown the client gracefully
            client.disconnect().get();
        }
    }
    

    在C#上,可以使用OPC Foundation .NET Stack实现OPC UA。

    以下是使用OPC Foundation .NET Stack来访问OPC UA数据的简单示例:

    using System;
    using System.Threading.Tasks;
    using Opc.Ua;
    using Opc.Ua.Client;
    
    public class Example {
        static async Task Main(string[] args) {
            // Replace with the correct endpoint URL for your server
            Uri endpointUrl = new Uri("opc.tcp://localhost:12686/sample");
    
            // Create a new session using a self-signed certificate
            var session = await Session.Create(
                configuration: new SessionConfiguration {
                    UserIdentity = new UserIdentity(new AnonymousIdentityToken()),
                    Endpoint = new ConfiguredEndpoint(null, new EndpointDescription {
                        EndpointUrl = endpointUrl.ToString(),
                        SecurityMode = MessageSecurityMode.None,
                        SecurityPolicyUri = SecurityPolicy.None.Uri
                    }),
                    TransportSendingBufferSize = 10 * 1024 * 1024,
                    OperationTimeout = 60 * 1000,
                });
    
            // Browse for nodes on the server
            var browseRequest = new BrowseRequest {
                NodesToBrowse = new[] {
                    new BrowseDescription {
                        NodeId = NodeId.Parse("ns=0;i=85"), // Browse the root folder
                        BrowseDirection = BrowseDirection.Forward,
                        ReferenceTypeId = ReferenceTypeIds.HierarchicalReferences,
                        IncludeSubtypes = true,
                        NodeClassMask =
                            (uint) (NodeClass.Object | NodeClass.Variable | NodeClass.Method),
                        ResultMask = (uint) (BrowseResultMask.All)
                    }
                }
            };
    
            var browseResponse = await session.BrowseAsync(browseRequest);
    
            // Find the node you want to read or subscribe to
            var nodeId = NodeId.Parse("ns=0;i=85/2:MyObject");
    
            // Read the value of the node
            var readRequest = new ReadRequest {
                NodesToRead = new[] {
                    new ReadValueId {
                        NodeId = nodeId,
                        AttributeId = Attributes.Value
                    }
                }
            };
    
            var readResponse = await session.ReadAsync(readRequest);
    
            var value = readResponse.Results[0].Value;
    
            Console.WriteLine(value);
    
            // Subscribe to updates on the node in real-time
            var subscription = new Subscription(session.DefaultSubscription) {
                PublishingInterval = 1000,
                KeepAliveCount = 10,
                LifetimeCount = 20,
                MaxNotificationsPerPublish = 1000,
                PublishingEnabled = true,
                Priority = 1
            };
    
            var monitoredItem = new MonitoredItem(subscription.DefaultItem) {
                StartNodeId = nodeId,
                AttributeId = Attributes.Value,
                MonitoringMode = MonitoringMode.Reporting,
                SamplingInterval = 100,
                DiscardOldest = true
            };
    
            await subscription.AddItemAsync(monitoredItem);
    
            subscription.Create();
    
            Console.WriteLine("Subscribed to changes on node {0}", nodeId);
    
            for (int i = 0; i < 10; i++) {
                // Wait for a notification to arrive
                var notification = await subscription.WaitNextNotificationAsync();
    
                Console.WriteLine(notification.Value);
            }
    
            // Dispose of resources and close the session gracefully
            await session.CloseAsync();
        }
    }
    

    这些示例应该可以帮助你开始使用Java或C#访问OPC UA数据并进行开发。希望对你有所帮助!
    如果我的回答解决了您的问题,请采纳!

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(6条)

报告相同问题?

问题事件

  • 已结题 (查看结题原因) 3月16日
  • 已采纳回答 3月14日
  • 创建了问题 3月13日

悬赏问题

  • ¥50 三种调度算法报错 有实例
  • ¥15 关于#python#的问题,请各位专家解答!
  • ¥200 询问:python实现大地主题正反算的程序设计,有偿
  • ¥15 smptlib使用465端口发送邮件失败
  • ¥200 总是报错,能帮助用python实现程序实现高斯正反算吗?有偿
  • ¥15 对于squad数据集的基于bert模型的微调
  • ¥15 为什么我运行这个网络会出现以下报错?CRNN神经网络
  • ¥20 steam下载游戏占用内存
  • ¥15 CST保存项目时失败
  • ¥20 java在应用程序里获取不到扬声器设备