Code Beispiele Opc Ua Client Sdk
Die nachfolgenden Code Beispiele PLCcom Opc Ua Client Sdk unterstützen .net oder java Entwickler bei der Implementierung von Opc Ua Funktionalitäten in Ihre Applikationen.
Die Einbindung des PLCcom Opc Ua Client Sdk ist sehr einfach und benutzerfreundlich. Die Funktionen richten sich nach den Spezifikationen der Opc Foundation. Die nachfolgenden Beispiele veranschaulichen die wichtigsten Funktionalitäten.
Weiterführende umfangreiche Dokumentationen mit direkt ausführbaren Code-Beispielen finden Sie in der Beispielanwendung in unserem Downloadpaket oder online.
Nachfolgend ein komplettes ausführbares Beispiel:
using PLCcom.Opc.Ua; using PLCcom.Opc.Ua.Client.Sdk; using System; class Program { static void Main(string[] args) { Program p = new Program(); p.Start(); } void Start() { try { string url = "opc.tcp://localhost:50520/UA/DataAccessServer"; Console.WriteLine("Start discover endpoints url: " + url); //get all servers ApplicationDescriptionCollection servers = UaClient.FindServers(new Uri(url), 60000); // populate the server list with the discovery URLs for the available servers. foreach (ApplicationDescription server in servers) { // don't show discovery servers. if (server.ApplicationType == ApplicationType.DiscoveryServer) { continue; } foreach (string discoveryUrl in server.DiscoveryUrls) { //Get Endpoints from server EndpointDescriptionCollection endpoints = UaClient.GetEndpoints(new Uri(url), 60000); if (endpoints.Count > 0) { Console.WriteLine("endpoints found:"); int counter = 0; foreach (EndpointDescription endpoint in endpoints) { Console.WriteLine(counter++.ToString() + " => " + UaClient.EndpointToString(endpoint)); } } else { Console.WriteLine("no discovery endpoints found"); } } } Console.WriteLine("End getting Endports from UA Application"); Console.WriteLine(); Console.WriteLine("press enter for exit"); Console.ReadLine(); } catch (Exception ex) { Console.WriteLine(ex); Console.WriteLine("press enter for exit"); Console.ReadLine(); } } }
Imports PLCcom.Opc.Ua Imports PLCcom.Opc.Ua.Client.Sdk Public Class Program Public Shared Sub Main(ByVal args As String()) Dim p As Program = New Program() p.Start() End Sub Private Sub Start() Try Dim url As String = "opc.tcp://localhost:50520/UA/DataAccessServer" Console.WriteLine($"Start discover endpoints url: { url}") 'get all servers Dim servers As ApplicationDescriptionCollection = UaClient.FindServers(New Uri(url), 60000) ' populate the server list with the discovery URLs for the available servers. For Each server As ApplicationDescription In servers ' don't show discovery servers. If server.ApplicationType = ApplicationType.DiscoveryServer Then Continue For End If For Each discoveryUrl As String In server.DiscoveryUrls 'Get Endpoints from server Dim endpoints As EndpointDescriptionCollection = UaClient.GetEndpoints(New Uri(url), 60000) If endpoints.Count > 0 Then Console.WriteLine("endpoints found:") Dim counter As Integer = 0 For Each endpoint As EndpointDescription In endpoints Console.WriteLine($"{Math.Min(Threading.Interlocked.Increment(counter), counter - 1).ToString() } => { UaClient.EndpointToString(endpoint)}") Next Else Console.WriteLine("no discovery endpoints found") End If Next Next Console.WriteLine("End getting Endports from UA Application") Console.WriteLine() Console.WriteLine("press enter for exit") Console.ReadLine() Catch ex As Exception Console.WriteLine(ex) Console.WriteLine("press enter for exit") Console.ReadLine() End Try End Sub End Class
package tutorials.t01_firstSteps; import plccom.opc.ua.sdk.client.application.SortDirection; import plccom.opc.ua.sdk.client.application.UaClient; import java.net.URI; import org.opcfoundation.ua.core.EndpointDescription; public class Tutorial01_discover_endpoints { public static void main(String[] args) { Tutorial01_discover_endpoints prog = new Tutorial01_discover_endpoints(); prog.start(); } private void start() { try { System.out.println("Start discover discovery server"); String hostname = "localhost"; int port = 4840; // create a discovery uri URI discoveryUri = new URI(String.format("opc.tcp://%s:%s", hostname, port)); System.out.println(String.format("reading Endports from discoveryUri %s", discoveryUri.toString())); // Get endpoints from ua Server with discovery url EndpointDescription[] endpoints = UaClient.discoverEndpoints(discoveryUri); endpoints = UaClient.sortBySecurityLevel(endpoints, SortDirection.Asc); for (EndpointDescription endpoint : endpoints) { System.out.println(endpoint.toString()); } System.out.println(); } catch (Exception e) { e.printStackTrace(); } finally { } } }
Example: Discover OPC UA Server
Das Verbinden zu einem OPC UA Server kann auf Wunsch automatisch oder manuell durchgeführt werden.
Per Default-Einstellung verbindet sich ein Client automatisch zum Server wenn eine Verbindung benötigt wird. Auch der Reconnect nach einem Verbindungsabriss findet automatisch statt.
Das Verhalten kann über die AutoConnect Eigenschaft des Clientobjekt eingestellt werden.
DataAccessClient client = new DataAccessClient(„< Enter your UserName here >“, „< Enter your Serial here >“, sessionConfiguration, false);
oder
client.AutoConnect = false;
Nachfolgend ein komplettes ausführbares Beispiel zum manuellen Verbinden:
using PLCcom.Opc.Ua.Client.Sdk; using System; using PLCcom.Opc.Ua.Client; using PLCcom.Opc.Ua; using System.Threading; class Program { //flag, accept all untrusted certicates or not private bool autoAcceptUntrustedCertificates = true; static void Main(string[] args) { Program program = new Program(); program.Start(); } void Start() { try { //AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException); //TODO //Submit your license information from your license e-mail string LicenseUserName = ""; string LicenseSerial = ""; EndpointDescriptionCollection Endpoints = UaClient.GetEndpoints(new Uri("opc.tcp://localhost:51210/UA/SampleServer"), 60000); //sort endpoints by security level Endpoints = UaClient.SortEndpointsBySecurityLevel(Endpoints); if (Endpoints.Count > 0) { Console.WriteLine("endpoints found:"); int counter = 0; foreach (EndpointDescription endpoint in Endpoints) { Console.WriteLine(counter++.ToString() + " => " + UaClient.EndpointToString(endpoint)); } Console.WriteLine("please enter index of desired endpoint"); string NumberOfEndpoint = Console.ReadLine(); int iNumberOfEndpoint = -1; if (int.TryParse(NumberOfEndpoint, out iNumberOfEndpoint) && iNumberOfEndpoint > -1 && iNumberOfEndpoint < Endpoints.Count) { //create a a SessionConfiguration with the selected endpoint and application name SessionConfiguration sessionConfiguration = SessionConfiguration.Build(System.Reflection.Assembly.GetEntryAssembly().GetName().Name, Endpoints[iNumberOfEndpoint]); //disable autoconnect sessionConfiguration.AutoConnect = false; //output certificate store path Console.WriteLine("Info: Sessionconfiguration created, certificate store path => " + sessionConfiguration.CertificateStorePath); //Create a new opc client instance and pass your license information UaClient client = new UaClient(LicenseUserName, LicenseSerial, sessionConfiguration); Console.WriteLine("Info: license state => " + client.GetLicenceMessage()); //register events client.ServerConnectionLost += Client_ServerConnectionLost; client.ServerConnected += Client_ServerConnected; client.KeepAlive += Client_KeepAlive; client.CertificateValidation += client_CertificateValidation; try { //connect client client.Connect(); //Connect client, not needed if sessionConfiguration.AutoConnect = true Console.WriteLine(client.GetSessionState().ToString()); Console.WriteLine(); Console.WriteLine("press enter for exit"); Console.ReadLine(); return; } catch (Exception ex) { Console.WriteLine(ex); Console.WriteLine("press enter for exit"); Console.ReadLine(); } finally { if (client.GetSessionState() == SessionState.Connected) client.Disconnect(); } } else { Console.WriteLine(); Console.WriteLine("invalid number of Endpoint"); } } else { Console.WriteLine(); Console.WriteLine("no endpoints found"); } Console.WriteLine(); Console.WriteLine("press enter for exit"); Console.ReadLine(); } catch (Exception ex) { Console.WriteLine(ex); Console.WriteLine("press enter for exit"); Console.ReadLine(); } } void client_CertificateValidation(CertificateValidator sender, CertificateValidationEventArgs e) { //external certificate validation if (ServiceResult.IsGood(e.Error)) e.Accept = true; else if ((e.Error.StatusCode.Code == StatusCodes.BadCertificateUntrusted || e.Error.StatusCode.Code == StatusCodes.BadCertificateChainIncomplete) && autoAcceptUntrustedCertificates) e.Accept = true; else { throw new Exception(string.Format("Failed to validate certificate with error code {0}: {1}", e.Error.Code, e.Error.AdditionalInfo)); } } static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e) { // Log the exception, display it, etc //Debug.WriteLine((e.ExceptionObject as Exception).Message); } private void Client_ServerConnected(object sender, EventArgs e) { //event opc ua server is connected Console.WriteLine(DateTime.Now.ToLocalTime() + " Session connected"); } private void Client_ServerConnectionLost(object sender, EventArgs e) { //event connection to opc ua server lost Console.WriteLine(DateTime.Now.ToLocalTime() + " Session connection lost"); } void Client_KeepAlive(Session session, KeepAliveEventArgs e) { //catch the keepalive event of opc ua server } }
Imports PLCcom.Opc.Ua.Client.Sdk Imports System Imports PLCcom.Opc.Ua.Client Imports PLCcom.Opc.Ua Imports System.Reflection Public Class Program 'flag, accept all untrusted certicates or not Private autoAcceptUntrustedCertificates As Boolean = True Public Shared Sub Main(ByVal args As String()) Dim p As Program = New Program() p.Start() End Sub Private Sub Start() Try 'TODO 'Submit your license information from your license e-mail Dim LicenseUserName As String = "" Dim LicenseSerial As String = "" Dim Endpoints As EndpointDescriptionCollection = UaClient.GetEndpoints(New Uri("opc.tcp://localhost:50520/UA/DataAccessServer"), 60000) 'sort endpoints by security level Endpoints = UaClient.SortEndpointsBySecurityLevel(Endpoints) If Endpoints.Count > 0 Then Console.WriteLine("endpoints found:") Dim counter As Integer = 0 For Each endpoint As EndpointDescription In Endpoints Console.WriteLine($"{Math.Min(Threading.Interlocked.Increment(counter), counter - 1).ToString() } => {UaClient.EndpointToString(endpoint)}") Next Console.WriteLine("please enter index of desired endpoint") Dim NumberOfEndpoint As String = Console.ReadLine() Dim iNumberOfEndpoint As Integer = -1 If Integer.TryParse(NumberOfEndpoint, iNumberOfEndpoint) AndAlso iNumberOfEndpoint > -1 AndAlso iNumberOfEndpoint < Endpoints.Count Then 'create a a SessionConfiguration with the selected endpoint and application name Dim sessionConfiguration As SessionConfiguration = SessionConfiguration.Build(Assembly.GetEntryAssembly().GetName().Name, Endpoints(iNumberOfEndpoint)) 'disable autoconnect sessionConfiguration.AutoConnect = False 'output certificate store path Console.WriteLine($"Info: Sessionconfiguration created, certificate store path => {sessionConfiguration.CertificateStorePath}") 'Create a new opc client instance and pass your license information Dim client As UaClient = New UaClient(LicenseUserName, LicenseSerial, sessionConfiguration) Console.WriteLine($"Info: license state => {client.GetLicenceMessage()}") 'register events AddHandler client.ServerConnectionLost, AddressOf Client_ServerConnectionLost AddHandler client.ServerConnected, AddressOf Client_ServerConnected AddHandler client.KeepAlive, AddressOf Client_KeepAlive AddHandler client.CertificateValidation, AddressOf client_CertificateValidation Try 'connect client client.Connect() 'Connect client, not needed if sessionConfiguration.AutoConnect = true Console.WriteLine(client.GetSessionState().ToString()) Console.WriteLine() Console.WriteLine("press enter for exit") Console.ReadLine() Return Finally If client.GetSessionState() = SessionState.Connected Then client.Disconnect() End Try Else Console.WriteLine() Console.WriteLine("invalid number of Endpoint") End If Else Console.WriteLine() Console.WriteLine("no endpoints found") End If Console.WriteLine() Console.WriteLine("press enter for exit") Console.ReadLine() Catch ex As Exception Console.WriteLine(ex) Console.WriteLine("press enter for exit") Console.ReadLine() End Try End Sub Private Sub client_CertificateValidation(ByVal sender As CertificateValidator, ByVal e As CertificateValidationEventArgs) 'external certificate validation If ServiceResult.IsGood(e.Error) Then e.Accept = True ElseIf (e.Error.StatusCode.Code = StatusCodes.BadCertificateUntrusted OrElse e.Error.StatusCode.Code = StatusCodes.BadCertificateChainIncomplete) AndAlso autoAcceptUntrustedCertificates Then e.Accept = True Else Throw New Exception($"Failed to validate certificate with error code {e.Error.Code}: {e.Error.AdditionalInfo}") End If End Sub Private Sub Client_ServerConnected(ByVal sender As Object, ByVal e As EventArgs) 'event opc ua server is connected Console.WriteLine($"{Date.Now.ToLocalTime()} Session connected") End Sub Private Sub Client_ServerConnectionLost(ByVal sender As Object, ByVal e As EventArgs) 'event connection to opc ua server lost Console.WriteLine($"{Date.Now.ToLocalTime()} Session connection lost") End Sub Private Sub Client_KeepAlive(ByVal session As Session, ByVal e As KeepAliveEventArgs) 'catch the keepalive event of opc ua server End Sub End Class
package tutorials.t01_firstSteps; import java.net.URI; import plccom.opc.ua.sdk.client.application.ClientConfiguration; import plccom.opc.ua.sdk.client.application.EndpointProtocol; import plccom.opc.ua.sdk.client.application.UaClient; import plccom.opc.ua.sdk.client.application.listener.SessionConnectionStateChangeListener; import plccom.opc.ua.sdk.client.application.listener.SessionKeepAliveListener; import org.opcfoundation.ua.builtintypes.LocalizedText; import org.opcfoundation.ua.core.EndpointDescription; import org.opcfoundation.ua.core.MessageSecurityMode; import org.opcfoundation.ua.core.ServerState; import org.opcfoundation.ua.core.ServerStatusDataType; public class Tutorial02_simple_connect_to_server implements SessionKeepAliveListener, SessionConnectionStateChangeListener { // Developer's TODO // Submit your license information from your license e-mail private final String LicenseUserName = ""; private final String LicenseSerial = ""; public static void main(String[] args) { Tutorial02_simple_connect_to_server prog = new Tutorial02_simple_connect_to_server(); prog.start(); } private void start() { try { // find endpoint at server by discovery url, protocol and security mode EndpointDescription endpoint = UaClient.findBestEndpoint( new URI("opc.tcp://localhost:50520/UA/DataAccessServer"), EndpointProtocol.opc_tcp, MessageSecurityMode.None); if (endpoint != null) { System.out.println("endpoint found:"); // create Sessionconfiguration ClientConfiguration clientConfiguration = new ClientConfiguration( new LocalizedText(this.getClass().getSimpleName(), "en"), endpoint); clientConfiguration.setAutoConnectEnabled(true); // Create new OPCUAClient UaClient myClient = new UaClient(LicenseUserName, LicenseSerial, clientConfiguration); // print license informations System.out.println(myClient.getLicenceMessage()); // add events for monitoring session myClient.addSessionKeepAliveListener(this); myClient.addSessionConnectionStateChangeListener(this); // Connect client myClient.connect(); System.in.read(); // shutdown client myClient.close(); // remove events for monitoring session myClient.removeSessionKeepAliveListener(this); myClient.removeSessionConnectionStateChangeListener(this); } else { System.out.println("no endpoints found"); } } catch (Exception e) { e.printStackTrace(); } } @Override public void onSessionKeepAlive(ServerStatusDataType serverStatusDataType, ServerState serverState) { System.out.println("incoming Keepalive => Serverstate: " + serverState.toString()); } @Override public void onSessionConnectionStateChanged(boolean isConnected) { System.out.println("incoming SessionConnectionState => Session Connected = " + isConnected); } }
Example: Connect to endpoint
Einfaches Beispiel:
ReferenceDescription rd = client.Browse(„Objects.Server.Data.Static“) ;
Nachfolgend ein komplettes ausführbares Beispiel:
using PLCcom.Opc.Ua; using PLCcom.Opc.Ua.Client.Sdk; using System; using PLCcom.Opc.Ua.Client; class Program { //flag, accept all untrusted certicates or not private bool autoAcceptUntrustedCertificates = true; static void Main(string[] args) { Program program = new Program(); program.Start(); } void Start() { try { //TODO //Submit your license information from your license e-mail string LicenseUserName = ""; string LicenseSerial = ""; EndpointDescriptionCollection Endpoints = UaClient.GetEndpoints(new Uri("opc.tcp://localhost:50520/PLCcom/DataAccessServer"), 60000); //sort endpoints by security level Endpoints = UaClient.SortEndpointsBySecurityLevel(Endpoints); if (Endpoints.Count > 0) { Console.WriteLine("endpoints found:"); int counter = 0; foreach (EndpointDescription Endpoint in Endpoints) { Console.WriteLine(counter++.ToString() + " => " + UaClient.EndpointToString( Endpoint)); } Console.WriteLine("please enter index of desired endpoint"); string NumberOfEndpoint = Console.ReadLine(); Console.WriteLine(""); int iNumberOfEndpoint = -1; if (int.TryParse(NumberOfEndpoint, out iNumberOfEndpoint) && iNumberOfEndpoint > -1 && iNumberOfEndpoint < Endpoints.Count) { //create a a SessionConfiguration with the selected endpoint and application name SessionConfiguration sessionConfiguration = SessionConfiguration.Build(System.Reflection.Assembly.GetEntryAssembly().GetName().Name, Endpoints[iNumberOfEndpoint]); //enable autoconnect sessionConfiguration.AutoConnect = true; //output certificate store path Console.WriteLine("Info: Sessionconfiguration created, certificate store path => " + sessionConfiguration.CertificateStorePath); //Create a new opc client instance and pass your license information using (UaClient client = new UaClient(LicenseUserName, LicenseSerial, sessionConfiguration)) { Console.WriteLine("Info: license state => " + client.GetLicenceMessage()); //register events client.ServerConnectionLost += Client_ServerConnectionLost; client.ServerConnected += Client_ServerConnected; client.KeepAlive += Client_KeepAlive; client.CertificateValidation += client_CertificateValidation; Console.WriteLine(""); Console.WriteLine("please enter browse path (nothing for root or 'exit' for exit program)"); try { NodeId sourceNode = client.GetNodeIdByPath("Objects.Data.Dynamic.Scalar"); //Set start NodeId by path // find all of the components of the node. BrowseDescription nodeToBrowse1 = new BrowseDescription(); nodeToBrowse1.NodeId = sourceNode; nodeToBrowse1.BrowseDirection = BrowseDirection.Forward; nodeToBrowse1.ReferenceTypeId = ReferenceTypeIds.Aggregates; nodeToBrowse1.IncludeSubtypes = true; nodeToBrowse1.NodeClassMask = (uint)(NodeClass.Object | NodeClass.Variable); nodeToBrowse1.ResultMask = (uint)BrowseResultMask.All; // find all nodes organized by the node. BrowseDescription nodeToBrowse2 = new BrowseDescription(); nodeToBrowse2.NodeId = sourceNode; nodeToBrowse2.BrowseDirection = BrowseDirection.Forward; nodeToBrowse2.ReferenceTypeId = ReferenceTypeIds.Organizes; nodeToBrowse2.IncludeSubtypes = true; nodeToBrowse2.NodeClassMask = (uint)(NodeClass.Object | NodeClass.Variable); nodeToBrowse2.ResultMask = (uint)BrowseResultMask.All; BrowseDescriptionCollection nodesToBrowse = new BrowseDescriptionCollection(); nodesToBrowse.Add(nodeToBrowse1); nodesToBrowse.Add(nodeToBrowse2); //now, browse the node ReferenceDescriptionCollection rdc = client.BrowseFull(nodesToBrowse); if ( rdc.Count > 0) { foreach (ReferenceDescription rd in rdc) { Console.WriteLine("Child NodeID found => "+ rd.NodeId+ " NodeClass => " + rd.NodeClass.ToString() + " BrowseName => " + rd.BrowseName.ToString() + " DisplayName => " + rd.DisplayName.ToString()); } } else { Console.WriteLine("no references found"); } } catch (Exception ex) { Console.WriteLine(ex); Console.WriteLine(); } } } else { Console.WriteLine("invalid number of Endpoint"); Console.WriteLine(); } } else { Console.WriteLine("no endpoints found"); Console.WriteLine(); } } catch (Exception ex) { Console.WriteLine(ex); Console.WriteLine(); } finally { Console.WriteLine("press enter for exit"); Console.ReadLine(); } } void client_CertificateValidation(CertificateValidator sender, CertificateValidationEventArgs e) { //external certificate validation if (ServiceResult.IsGood(e.Error)) e.Accept = true; else if ((e.Error.StatusCode.Code == StatusCodes.BadCertificateUntrusted || e.Error.StatusCode.Code == StatusCodes.BadCertificateChainIncomplete) && autoAcceptUntrustedCertificates) e.Accept = true; else { throw new Exception(string.Format("Failed to validate certificate with error code {0}: {1}", e.Error.Code, e.Error.AdditionalInfo)); } } private void Client_ServerConnected(object sender, EventArgs e) { //event opc ua server is connected Console.WriteLine(DateTime.Now.ToLocalTime() + " Session connected"); } private void Client_ServerConnectionLost(object sender, EventArgs e) { //event connection to opc ua server lost Console.WriteLine(DateTime.Now.ToLocalTime() + " Session connection lost"); } void Client_KeepAlive(Session session, KeepAliveEventArgs e) { //catch the keepalive event of opc ua server } }
Imports PLCcom.Opc.Ua Imports PLCcom.Opc.Ua.Client.Sdk Imports System Imports PLCcom.Opc.Ua.Client Imports System.Reflection Public Class Program 'flag, accept all untrusted certicates or not Private autoAcceptUntrustedCertificates As Boolean = True Public Shared Sub Main(ByVal args As String()) Dim p As Program = New Program() p.Start() End Sub Private Sub Start() Try 'TODO 'Submit your license information from your license e-mail Dim LicenseUserName As String = "" Dim LicenseSerial As String = "" Dim Endpoints As EndpointDescriptionCollection = UaClient.GetEndpoints(New Uri("opc.tcp://localhost:50520/PLCcom/DataAccessServer"), 60000) 'sort endpoints by security level Endpoints = UaClient.SortEndpointsBySecurityLevel(Endpoints) If Endpoints.Count > 0 Then Console.WriteLine("endpoints found:") Dim counter As Integer = 0 For Each Endpoint As EndpointDescription In Endpoints Console.WriteLine($"{Math.Min(Threading.Interlocked.Increment(counter), counter - 1).ToString() } => { UaClient.EndpointToString(Endpoint)}") Next Console.WriteLine("please enter index of desired endpoint") Dim NumberOfEndpoint As String = Console.ReadLine() Console.WriteLine("") Dim iNumberOfEndpoint As Integer = -1 If Integer.TryParse(NumberOfEndpoint, iNumberOfEndpoint) AndAlso iNumberOfEndpoint > -1 AndAlso iNumberOfEndpoint < Endpoints.Count Then 'create a a SessionConfiguration with the selected endpoint and application name Dim sessionConfiguration As SessionConfiguration = SessionConfiguration.Build(Assembly.GetEntryAssembly().GetName().Name, Endpoints(iNumberOfEndpoint)) 'enable autoconnect sessionConfiguration.AutoConnect = True 'output certificate store path Console.WriteLine($"Info: Sessionconfiguration created, certificate store path => { sessionConfiguration.CertificateStorePath}") 'Create a new opc client instance and pass your license information Using client As UaClient = New UaClient(LicenseUserName, LicenseSerial, sessionConfiguration) Console.WriteLine($"Info: license state => {client.GetLicenceMessage()}") 'register events AddHandler client.ServerConnectionLost, AddressOf Client_ServerConnectionLost AddHandler client.ServerConnected, AddressOf Client_ServerConnected AddHandler client.KeepAlive, AddressOf Client_KeepAlive AddHandler client.CertificateValidation, AddressOf client_CertificateValidation Console.WriteLine("") Console.WriteLine("please enter browse path (nothing for root or 'exit' for exit program)") Try Dim sourceNode As NodeId = client.GetNodeIdByPath("Objects.Data.Dynamic.Scalar") 'Set start NodeId by path ' find all of the components of the node. Dim nodeToBrowse1 As BrowseDescription = New BrowseDescription() nodeToBrowse1.NodeId = sourceNode nodeToBrowse1.BrowseDirection = BrowseDirection.Forward nodeToBrowse1.ReferenceTypeId = ReferenceTypeIds.Aggregates nodeToBrowse1.IncludeSubtypes = True nodeToBrowse1.NodeClassMask = CUInt(NodeClass.Object Or NodeClass.Variable) nodeToBrowse1.ResultMask = CUInt(BrowseResultMask.All) ' find all nodes organized by the node. Dim nodeToBrowse2 As BrowseDescription = New BrowseDescription() nodeToBrowse2.NodeId = sourceNode nodeToBrowse2.BrowseDirection = BrowseDirection.Forward nodeToBrowse2.ReferenceTypeId = ReferenceTypeIds.Organizes nodeToBrowse2.IncludeSubtypes = True nodeToBrowse2.NodeClassMask = CUInt(NodeClass.Object Or NodeClass.Variable) nodeToBrowse2.ResultMask = CUInt(BrowseResultMask.All) Dim nodesToBrowse As BrowseDescriptionCollection = New BrowseDescriptionCollection() nodesToBrowse.Add(nodeToBrowse1) nodesToBrowse.Add(nodeToBrowse2) 'now, browse the node Dim rdc As ReferenceDescriptionCollection = client.BrowseFull(nodesToBrowse) If rdc.Count > 0 Then For Each rd As ReferenceDescription In rdc Console.WriteLine($"Child NodeID found => {rd.NodeId} NodeClass => {rd.NodeClass.ToString()} BrowseName => {rd.BrowseName.ToString()} DisplayName => {rd.DisplayName.ToString()}") Next Else Console.WriteLine("no references found") End If Catch ex As Exception Console.WriteLine(ex) Console.WriteLine() End Try End Using Else Console.WriteLine("invalid number of Endpoint") Console.WriteLine() End If Else Console.WriteLine("no endpoints found") Console.WriteLine() End If Catch ex As Exception Console.WriteLine(ex) Console.WriteLine() Finally Console.WriteLine("press enter for exit") Console.ReadLine() End Try End Sub Private Sub client_CertificateValidation(ByVal sender As CertificateValidator, ByVal e As CertificateValidationEventArgs) 'external certificate validation If ServiceResult.IsGood(e.Error) Then e.Accept = True ElseIf (e.Error.StatusCode.Code = StatusCodes.BadCertificateUntrusted OrElse e.Error.StatusCode.Code = StatusCodes.BadCertificateChainIncomplete) AndAlso autoAcceptUntrustedCertificates Then e.Accept = True Else Throw New Exception($"Failed to validate certificate with error code {e.Error.Code}: {e.Error.AdditionalInfo}") End If End Sub Private Sub Client_ServerConnected(ByVal sender As Object, ByVal e As EventArgs) 'event opc ua server is connected Console.WriteLine($"{Date.Now.ToLocalTime()} Session connected") End Sub Private Sub Client_ServerConnectionLost(ByVal sender As Object, ByVal e As EventArgs) 'event connection to opc ua server lost Console.WriteLine($"{Date.Now.ToLocalTime()} Session connection lost") End Sub Private Sub Client_KeepAlive(ByVal session As Session, ByVal e As KeepAliveEventArgs) 'catch the keepalive event of opc ua server End Sub End Class
package tutorials.t01_firstSteps; import java.net.URI; import plccom.opc.ua.sdk.client.application.ClientConfiguration; import plccom.opc.ua.sdk.client.application.SortDirection; import plccom.opc.ua.sdk.client.application.UaClient; import plccom.opc.ua.sdk.client.application.listener.SessionConnectionStateChangeListener; import plccom.opc.ua.sdk.client.application.listener.SessionKeepAliveListener; import org.opcfoundation.ua.builtintypes.LocalizedText; import org.opcfoundation.ua.core.BrowseDescription; import org.opcfoundation.ua.core.BrowseDirection; import org.opcfoundation.ua.core.BrowseRequest; import org.opcfoundation.ua.core.BrowseResponse; import org.opcfoundation.ua.core.BrowseResult; import org.opcfoundation.ua.core.BrowseResultMask; import org.opcfoundation.ua.core.EndpointDescription; import org.opcfoundation.ua.core.Identifiers; import org.opcfoundation.ua.core.NodeClass; import org.opcfoundation.ua.core.ReferenceDescription; import org.opcfoundation.ua.core.ServerState; import org.opcfoundation.ua.core.ServerStatusDataType; public class Tutorial05_Browse_by_Path implements SessionKeepAliveListener, SessionConnectionStateChangeListener { // Developer's TODO // Submit your license information from your license e-mail private final String LicenseUserName = ""; private final String LicenseSerial = ""; public static void main(String[] args) { Tutorial05_Browse_by_Path prog = new Tutorial05_Browse_by_Path(); prog.start(); } private void start() { try { String hostname = "localhost"; int port = 4840; // create a discovery uri URI discoveryUri = new URI(String.format("opc.tcp://%s:%s", hostname, port)); System.out.println(String.format("reading Endports from discoveryUri %s", discoveryUri.toString())); // Get endpoints from ua Server with discovery url EndpointDescription[] endpoints = UaClient.discoverEndpoints(discoveryUri); // sort endpoint by message security mode endpoints = UaClient.sortBySecurityLevel(endpoints, SortDirection.Asc); if (endpoints.length > 0) { // create Sessionconfiguration ClientConfiguration clientConfiguration = new ClientConfiguration( new LocalizedText(this.getClass().getSimpleName(), "en"), endpoints[0]); // enable auto connect functionality // set automatic reconnect after 1000 milliseconds in case of losing connection clientConfiguration.setAutoConnectEnabled(true, 1000); // Create new OPCUAClient with Sessionconfiguration UaClient myClient = new UaClient(LicenseUserName, LicenseSerial, clientConfiguration); try { // print license informations System.out.println(myClient.getLicenceMessage()); // add events for monitoring session myClient.addSessionKeepAliveListener(this); myClient.addSessionConnectionStateChangeListener(this); try { // Create a BrowseDescription object // find all of the components of the node. BrowseDescription browseDescription1 = new BrowseDescription(); browseDescription1.setReferenceTypeId(Identifiers.Aggregates); browseDescription1.setBrowseDirection(BrowseDirection.Forward); browseDescription1.setIncludeSubtypes(true); browseDescription1.setNodeClassMask(NodeClass.Object, NodeClass.Variable); browseDescription1.setResultMask(BrowseResultMask.All); // Set start nodeId browseDescription1.setNodeId(myClient.getNodeIdByPath("Objects.Server")); // Create a BrowseRequest or browse the BrowseDescription direct BrowseRequest browseRequest = new BrowseRequest(null, null, null, new BrowseDescription[] { browseDescription1 }); // Browse the node BrowseResponse results = myClient.browse(browseRequest); for (BrowseResult res : results.getResults()) { if (res.getStatusCode().isGood()) { // evaluate references for (ReferenceDescription rd : res.getReferences()) { System.out.println("Child NodeID found => " + rd.getNodeId() + " " + rd.getDisplayName().toString() + " NodeClass => " + rd.getNodeClass().toString()); } } else { System.out.println("operation return bad status code => " + res.getStatusCode().toString()); } } } catch (Exception ex) { System.out.println(ex.getMessage()); } } finally { // shutdown client myClient.close(); } // remove events for monitoring session myClient.removeSessionKeepAliveListener(this); myClient.removeSessionConnectionStateChangeListener(this); } else { System.out.println("no endpoints found"); } } catch (Exception e) { e.printStackTrace(); } } @Override public void onSessionConnectionStateChanged(boolean isConnected) { System.out.println("incoming SessionConnectionState => Session Connected =: " + isConnected); } @Override public void onSessionKeepAlive(ServerStatusDataType serverStatusDataType, ServerState serverState) { System.out.println("incoming Keepalive => Serverstate: " + serverState.toString()); } }
Example: Browse nodes
Beispiel zum Lesen eines Knotens:
DataValue value = client.ReadValue(„Objects.Server.Data.Static.Scalar.Int64Value“);
Beispiel zum Schreiben des Wertes 123 auf einen Knoten:
StatusCode sc = client.WriteValue(„Objects.Server.Data.Static.Scalar.Int64Value“,123);
Nachfolgend ein komplettes ausführbares Beispiel:
using System; using PLCcom.Opc.Ua.Client.Sdk; using PLCcom.Opc.Ua.Client; using PLCcom.Opc.Ua; class Program { //flag, accept all untrusted certicates or not private bool autoAcceptUntrustedCertificates = true; UaClient client = null; static void Main(string[] args) { Program program = new Program(); program.Start(); } void Start() { try { //TODO //Submit your license information from your license e-mail string LicenseUserName = ""; string LicenseSerial = ""; EndpointDescriptionCollection Endpoints = UaClient.GetEndpoints(new Uri("opc.tcp://localhost:50520/PLCcom/DataAccessServer"), 60000); //sort endpoints by security level Endpoints = UaClient.SortEndpointsBySecurityLevel(Endpoints); if (Endpoints.Count > 0) { Console.WriteLine("endpoints found:"); int counter = 0; foreach (EndpointDescription Endpoint in Endpoints) { Console.WriteLine(counter++.ToString() + " => " + UaClient.EndpointToString(Endpoint)); } Console.WriteLine("please enter index of desired endpoint"); string NumberOfEndpoint = Console.ReadLine(); Console.WriteLine(""); int iNumberOfEndpoint = -1; if (int.TryParse(NumberOfEndpoint, out iNumberOfEndpoint) && iNumberOfEndpoint > -1 && iNumberOfEndpoint < Endpoints.Count) { //create a a SessionConfiguration with the selected endpoint and application name SessionConfiguration sessionConfiguration = SessionConfiguration.Build(System.Reflection.Assembly.GetEntryAssembly().GetName().Name, Endpoints[iNumberOfEndpoint]); //enable autoconnect sessionConfiguration.AutoConnect = true; //output certificate store path Console.WriteLine("Info: Sessionconfiguration created, certificate store path => " + sessionConfiguration.CertificateStorePath); //Create a new opc client instance and pass your license information client = new UaClient(LicenseUserName, LicenseSerial, sessionConfiguration); Console.WriteLine("Info: license state => " + client.GetLicenceMessage()); Console.WriteLine(""); //register events client.ServerConnectionLost += Client_ServerConnectionLost; client.ServerConnected += Client_ServerConnected; client.KeepAlive += Client_KeepAlive; client.CertificateValidation += client_CertificateValidation; client.Connect(); Console.WriteLine("press enter to reading synchronous.."); Console.ReadLine(); //Read multiple Nodes within one call //first create a ReadValueIdCollection and fill this with ReadValueId objects ReadValueIdCollection nodesToRead = new ReadValueIdCollection(); ReadValueId nodeToRead = new ReadValueId(); nodeToRead.NodeId = client.GetNodeIdByPath("Objects.Data.Static.Scalar.Int16Value"); nodeToRead.AttributeId = Attributes.Value; nodesToRead.Add(nodeToRead); nodeToRead = new ReadValueId(); nodeToRead.NodeId = client.GetNodeIdByPath("Objects.Data.Static.Scalar.Int32Value"); nodeToRead.AttributeId = Attributes.Value; nodesToRead.Add(nodeToRead); nodeToRead = new ReadValueId(); nodeToRead.NodeId = client.GetNodeIdByPath("Objects.Data.Static.Scalar.Int32Value"); nodeToRead.AttributeId = Attributes.Value; nodesToRead.Add(nodeToRead); //reading the nodes synchronous DataValueCollection readresults = client.Read(nodesToRead); for (int i = 0; i < readresults.Count; i++) { DataValue res = readresults[i]; Console.WriteLine("synchronous read result " + nodesToRead[i].NodeId.ToString() + " Value => " + res.Value.ToString() + " StatusCode => " + res.StatusCode.ToString()); } Console.WriteLine(); Console.WriteLine("press enter to reading asynchronous.."); Console.ReadLine(); //reading the nodes asynchronous client.BeginRead(nodesToRead, GetReadAsyncResult, nodesToRead); Console.ReadLine(); //create a WriteValueCollection and fill this with WriteValue objects WriteValueCollection nodesToWrite = new WriteValueCollection(); WriteValue writeValue = new WriteValue(); writeValue.NodeId = client.GetNodeIdByPath("Objects.Data.Static.Scalar.Int16Value"); writeValue.Value = new DataValue((Int16)(-16)); writeValue.AttributeId = Attributes.Value; nodesToWrite.Add(writeValue); writeValue = new WriteValue(); writeValue.NodeId = client.GetNodeIdByPath("Objects.Data.Static.Scalar.Int32Value"); writeValue.AttributeId = Attributes.Value; writeValue.Value = new DataValue(-3232); nodesToWrite.Add(writeValue); writeValue = new WriteValue(); writeValue.NodeId = client.GetNodeIdByPath("Objects.Data.Static.Scalar.Int64Value"); writeValue.AttributeId = Attributes.Value; writeValue.Value = new DataValue((Int64)(-64646464)); nodesToWrite.Add(writeValue); //writing the nodes synchronous StatusCodeCollection writeResults = client.Write(nodesToWrite); for (int i = 0; i < writeResults.Count; i++) { Console.WriteLine("synchronous write result " + nodesToWrite[i].NodeId.ToString() + " Value => " + nodesToWrite[i].Value.ToString() + " StatusCode => " + writeResults[i].ToString()); } Console.WriteLine(); Console.WriteLine("press enter to writing asynchronous.."); Console.ReadLine(); //writing the nodes asynchronous client.BeginWrite(nodesToWrite, GetWriteAsyncResult, nodesToWrite); } else { Console.WriteLine("invalid number of Endpoint"); Console.WriteLine(); } } else { Console.WriteLine("no endpoints found"); Console.WriteLine(); } } catch (Exception ex) { Console.WriteLine(ex); Console.WriteLine(); } finally { Console.WriteLine("press enter for exit"); Console.ReadLine(); try { //disconnect session client.Disconnect(); //unregister events client.ServerConnectionLost -= Client_ServerConnectionLost; client.ServerConnected -= Client_ServerConnected; client.KeepAlive -= Client_KeepAlive; client.CertificateValidation -= client_CertificateValidation; } catch { } } } private void GetReadAsyncResult(IAsyncResult res) { DataValueCollection values = null; DiagnosticInfoCollection diagnostic = null; ResponseHeader readresults = client.EndRead(res, out values, out diagnostic); ReadValueIdCollection req = res.AsyncState as ReadValueIdCollection; if (req != null) { for (int i = 0; i < values.Count; i++) { Console.WriteLine("asynchronous read result " + req[i].NodeId.ToString() + " Value => " + values[i].ToString() + " StatusCode => " + values[i].StatusCode.ToString()); } } Console.WriteLine(); Console.WriteLine("press enter to writing synchronous.."); } private void GetWriteAsyncResult(IAsyncResult res) { StatusCodeCollection statuscodes = null; DiagnosticInfoCollection diagnostic = null; ResponseHeader readresults = client.EndWrite(res, out statuscodes, out diagnostic); WriteValueCollection req = res.AsyncState as WriteValueCollection; if (req != null) { for (int i = 0; i < statuscodes.Count; i++) { Console.WriteLine("asynchronous write result " + req[i].NodeId.ToString() + " Value => " + req[i].Value.ToString() + " StatusCode => " + statuscodes[i].ToString()); } } Console.WriteLine(); Console.WriteLine("press enter for exit.."); } void client_CertificateValidation(CertificateValidator sender, CertificateValidationEventArgs e) { //external certificate validation if (ServiceResult.IsGood(e.Error)) e.Accept = true; else if ((e.Error.StatusCode.Code == StatusCodes.BadCertificateUntrusted || e.Error.StatusCode.Code == StatusCodes.BadCertificateChainIncomplete) && autoAcceptUntrustedCertificates) e.Accept = true; else { throw new Exception(string.Format("Failed to validate certificate with error code {0}: {1}", e.Error.Code, e.Error.AdditionalInfo)); } } private void Client_ServerConnected(object sender, EventArgs e) { //event opc ua server is connected Console.WriteLine(DateTime.Now.ToLocalTime() + " Session connected"); } private void Client_ServerConnectionLost(object sender, EventArgs e) { //event connection to opc ua server lost Console.WriteLine(DateTime.Now.ToLocalTime() + " Session connection lost"); } void Client_KeepAlive(Session session, KeepAliveEventArgs e) { //catch the keepalive event of opc ua server } }
Imports System Imports PLCcom.Opc.Ua.Client.Sdk Imports PLCcom.Opc.Ua.Client Imports PLCcom.Opc.Ua Imports System.Reflection Public Class Program 'flag, accept all untrusted certicates or not Private autoAcceptUntrustedCertificates As Boolean = True Private client As UaClient = Nothing Public Shared Sub Main(ByVal args As String()) Dim p As Program = New Program() p.Start() End Sub Private Sub Start() Try 'TODO 'Submit your license information from your license e-mail Dim LicenseUserName As String = "" Dim LicenseSerial As String = "" Dim Endpoints As EndpointDescriptionCollection = UaClient.GetEndpoints(New Uri("opc.tcp://localhost:50520/PLCcom/DataAccessServer"), 60000) 'sort endpoints by security level Endpoints = UaClient.SortEndpointsBySecurityLevel(Endpoints) If Endpoints.Count > 0 Then Console.WriteLine("endpoints found:") Dim counter As Integer = 0 For Each Endpoint As EndpointDescription In Endpoints Console.WriteLine($"{Math.Min(Threading.Interlocked.Increment(counter), counter - 1).ToString()} => { UaClient.EndpointToString(Endpoint)}") Next Console.WriteLine("please enter index of desired endpoint") Dim NumberOfEndpoint As String = Console.ReadLine() Console.WriteLine("") Dim iNumberOfEndpoint As Integer = -1 If Integer.TryParse(NumberOfEndpoint, iNumberOfEndpoint) AndAlso iNumberOfEndpoint > -1 AndAlso iNumberOfEndpoint < Endpoints.Count Then 'create a a SessionConfiguration with the selected endpoint and application name Dim sessionConfiguration As SessionConfiguration = SessionConfiguration.Build(Assembly.GetEntryAssembly().GetName().Name, Endpoints(iNumberOfEndpoint)) 'enable autoconnect sessionConfiguration.AutoConnect = True 'output certificate store path Console.WriteLine($"Info: Sessionconfiguration created, certificate store path => { sessionConfiguration.CertificateStorePath}") 'Create a new opc client instance and pass your license information client = New UaClient(LicenseUserName, LicenseSerial, sessionConfiguration) Console.WriteLine($"Info: license state => { client.GetLicenceMessage()}") Console.WriteLine("") 'register events AddHandler client.ServerConnectionLost, AddressOf Client_ServerConnectionLost AddHandler client.ServerConnected, AddressOf Client_ServerConnected AddHandler client.KeepAlive, AddressOf Client_KeepAlive AddHandler client.CertificateValidation, AddressOf client_CertificateValidation client.Connect() Console.WriteLine("press enter to reading synchronous..") Console.ReadLine() 'Read multiple Nodes within one call 'first create a ReadValueIdCollection and fill this with ReadValueId objects Dim nodesToRead As ReadValueIdCollection = New ReadValueIdCollection() Dim nodeToRead As ReadValueId = New ReadValueId() nodeToRead.NodeId = client.GetNodeIdByPath("Objects.Data.Static.Scalar.Int16Value") nodeToRead.AttributeId = Attributes.Value nodesToRead.Add(nodeToRead) nodeToRead = New ReadValueId() nodeToRead.NodeId = client.GetNodeIdByPath("Objects.Data.Static.Scalar.Int32Value") nodeToRead.AttributeId = Attributes.Value nodesToRead.Add(nodeToRead) nodeToRead = New ReadValueId() nodeToRead.NodeId = client.GetNodeIdByPath("Objects.Data.Static.Scalar.Int32Value") nodeToRead.AttributeId = Attributes.Value nodesToRead.Add(nodeToRead) 'reading the nodes synchronous Dim readresults As DataValueCollection = client.Read(nodesToRead) For i As Integer = 0 To readresults.Count - 1 Dim res As DataValue = readresults(i) Console.WriteLine($"synchronous read result { nodesToRead(i).NodeId.ToString() } Value => { res.Value.ToString() } StatusCode => { res.StatusCode.ToString()}") Next Console.WriteLine() Console.WriteLine("press enter to reading asynchronous..") Console.ReadLine() 'reading the nodes asynchronous client.BeginRead(nodesToRead, New AsyncCallback(AddressOf GetReadAsyncResult), nodesToRead) Console.ReadLine() 'create a WriteValueCollection and fill this with WriteValue objects Dim nodesToWrite As WriteValueCollection = New WriteValueCollection() Dim writeValue As WriteValue = New WriteValue() writeValue.NodeId = client.GetNodeIdByPath("Objects.Data.Static.Scalar.Int16Value") writeValue.Value = New DataValue(CShort(-16)) writeValue.AttributeId = Attributes.Value nodesToWrite.Add(writeValue) writeValue = New WriteValue() writeValue.NodeId = client.GetNodeIdByPath("Objects.Data.Static.Scalar.Int32Value") writeValue.AttributeId = Attributes.Value writeValue.Value = New DataValue(-3232) nodesToWrite.Add(writeValue) writeValue = New WriteValue() writeValue.NodeId = client.GetNodeIdByPath("Objects.Data.Static.Scalar.Int64Value") writeValue.AttributeId = Attributes.Value writeValue.Value = New DataValue(CLng(-64646464)) nodesToWrite.Add(writeValue) 'writing the nodes synchronous Dim writeResults As StatusCodeCollection = client.Write(nodesToWrite) For i As Integer = 0 To writeResults.Count - 1 Console.WriteLine($"synchronous write result { nodesToWrite(i).NodeId.ToString() } Value => { nodesToWrite(i).Value.ToString() } StatusCode => { writeResults(i).ToString()}") Next Console.WriteLine() Console.WriteLine("press enter to writing asynchronous..") Console.ReadLine() 'writing the nodes asynchronous client.BeginWrite(nodesToWrite, New AsyncCallback(AddressOf GetWriteAsyncResult), nodesToWrite) Else Console.WriteLine("invalid number of Endpoint") Console.WriteLine() End If Else Console.WriteLine("no endpoints found") Console.WriteLine() End If Catch ex As Exception Console.WriteLine(ex) Console.WriteLine() Finally Console.WriteLine("press enter for exit") Console.ReadLine() Try 'disconnect session client.Disconnect() 'unregister events RemoveHandler client.ServerConnectionLost, AddressOf Client_ServerConnectionLost RemoveHandler client.ServerConnected, AddressOf Client_ServerConnected RemoveHandler client.KeepAlive, AddressOf Client_KeepAlive RemoveHandler client.CertificateValidation, AddressOf client_CertificateValidation Catch End Try End Try End Sub Private Sub GetReadAsyncResult(ByVal res As IAsyncResult) Dim values As DataValueCollection = Nothing Dim diagnostic As DiagnosticInfoCollection = Nothing Dim readresults As ResponseHeader = client.EndRead(res, values, diagnostic) Dim req As ReadValueIdCollection = TryCast(res.AsyncState, ReadValueIdCollection) If req IsNot Nothing Then For i As Integer = 0 To values.Count - 1 Console.WriteLine($"asynchronous read result {req(i).NodeId.ToString()} Value => { values(i).ToString() } StatusCode => { values(i).StatusCode.ToString()}") Next End If Console.WriteLine() Console.WriteLine("press enter to writing synchronous..") End Sub Private Sub GetWriteAsyncResult(ByVal res As IAsyncResult) Dim statuscodes As StatusCodeCollection = Nothing Dim diagnostic As DiagnosticInfoCollection = Nothing Dim readresults As ResponseHeader = client.EndWrite(res, statuscodes, diagnostic) Dim req As WriteValueCollection = TryCast(res.AsyncState, WriteValueCollection) If req IsNot Nothing Then For i As Integer = 0 To statuscodes.Count - 1 Console.WriteLine($"asynchronous write result { req(i).NodeId.ToString() } Value => { req(i).Value.ToString() } StatusCode => { statuscodes(i).ToString()}") Next End If Console.WriteLine() Console.WriteLine("press enter for exit..") End Sub Private Sub client_CertificateValidation(ByVal sender As CertificateValidator, ByVal e As CertificateValidationEventArgs) 'external certificate validation If ServiceResult.IsGood(e.Error) Then e.Accept = True ElseIf (e.Error.StatusCode.Code = StatusCodes.BadCertificateUntrusted OrElse e.Error.StatusCode.Code = StatusCodes.BadCertificateChainIncomplete) AndAlso autoAcceptUntrustedCertificates Then e.Accept = True Else Throw New Exception($"Failed to validate certificate with error code {e.Error.Code}: {e.Error.AdditionalInfo}") End If End Sub Private Sub Client_ServerConnected(ByVal sender As Object, ByVal e As EventArgs) 'event opc ua server is connected Console.WriteLine($"{Date.Now.ToLocalTime()} Session connected") End Sub Private Sub Client_ServerConnectionLost(ByVal sender As Object, ByVal e As EventArgs) 'event connection to opc ua server lost Console.WriteLine($"{Date.Now.ToLocalTime()} Session connection lost") End Sub Private Sub Client_KeepAlive(ByVal session As Session, ByVal e As KeepAliveEventArgs) 'catch the keepalive event of opc ua server End Sub End Class
package tutorials.t02_data_access; import java.net.URI; import java.util.Arrays; import plccom.opc.ua.sdk.client.application.ClientConfiguration; import plccom.opc.ua.sdk.client.application.SortDirection; import plccom.opc.ua.sdk.client.application.UaClient; import plccom.opc.ua.sdk.client.application.listener.SessionConnectionStateChangeListener; import plccom.opc.ua.sdk.client.application.listener.SessionKeepAliveListener; import plccom.opc.ua.sdk.client.core.attributes.UaAttributes; import org.opcfoundation.ua.builtintypes.LocalizedText; import org.opcfoundation.ua.builtintypes.NodeId; import org.opcfoundation.ua.builtintypes.StatusCode; import org.opcfoundation.ua.core.EndpointDescription; import org.opcfoundation.ua.core.Identifiers; import org.opcfoundation.ua.core.ReadResponse; import org.opcfoundation.ua.core.ServerState; import org.opcfoundation.ua.core.ServerStatusDataType; public class Tutorial21_read_write implements SessionKeepAliveListener, SessionConnectionStateChangeListener { // Developer's TODO // Submit your license information from your license e-mail private final String LicenseUserName = ""; private final String LicenseSerial = ""; public static void main(String[] args) { Tutorial21_read_write prog = new Tutorial21_read_write(); prog.start(); } private void start() { try { String hostname = "localhost"; int port = 4840; // create a discovery uri URI discoveryUri = new URI(String.format("opc.tcp://%s:%s", hostname, port)); System.out.println(String.format("reading Endports from discoveryUri %s", discoveryUri.toString())); // Get endpoints from ua Server with discovery url EndpointDescription[] endpoints = UaClient.discoverEndpoints(discoveryUri); // sort endpoint by message security mode endpoints = UaClient.sortBySecurityLevel(endpoints, SortDirection.Asc); if (endpoints.length > 0) { // create Sessionconfiguration ClientConfiguration clientConfiguration = new ClientConfiguration( new LocalizedText(this.getClass().getSimpleName(), "en"), endpoints[0]); // Create new OPCUAClient UaClient myClient = new UaClient(LicenseUserName, LicenseSerial, clientConfiguration); try { // print license informations System.out.println(myClient.getLicenceMessage()); myClient.addSessionKeepAliveListener(this); myClient.addSessionConnectionStateChangeListener(this); myClient.connect(); ///////////////////// read Values //////////////////////// // Read namespace Array ReadResponse res = myClient.read(Identifiers.Server_NamespaceArray, UaAttributes.Value); String[] namespaceArray = (String[]) res.getResults()[0].getValue().getValue(); System.out.println(Arrays.toString(namespaceArray)); // Read a variable by NodeId res = myClient.read(new NodeId(2, 10219), UaAttributes.Value); System.out.println(String.format("Result: %s Statuscode: %s", res.getResults()[0].getValue().toString(), res.getResults()[0].getStatusCode().toString())); // Read a variable by browse path res = myClient.read(myClient.getNodeIdByPath("Objects.Server.Data.Static.Scalar.Int16Value"), UaAttributes.Value); System.out.println(String.format("Result: %s Statuscode: %s", res.getResults()[0].getValue().toString(), res.getResults()[0].getStatusCode().toString())); ///////////////////// read Attributes ///////////////////// //////////////////////// res = myClient.read(myClient.getNodeIdByPath("Objects.Server.Data.Static.Scalar.Int16Value"), UaAttributes.DataType); System.out.println(String.format("Result: %s Statuscode: %s", res.getResults()[0].getValue().toString(), res.getResults()[0].getStatusCode().toString())); res = myClient.read((NodeId) (res.getResults()[0].getValue().getValue()), UaAttributes.BrowseName); System.out.println(String.format("Result: %s Statuscode: %s", res.getResults()[0].getValue().toString(), res.getResults()[0].getStatusCode().toString())); ///////////////////// write values ////////////////////// // write value of a variable to 1111 by NodeId StatusCode rsc = myClient.write(new NodeId(2, 10219), (short) 1111, UaAttributes.Value); System.out.println(String.format("Statuscode for write operation: %s", rsc.toString())); // write value of a variable to 11 by browse path rsc = myClient.write(myClient.getNodeIdByPath("Objects.Server.Data.Static.Scalar.Int16Value"), (short) 11, UaAttributes.Value); System.out.println(String.format("Statuscode for write operation: %s", rsc.toString())); } finally { // shutdown client myClient.close(); } } else { System.out.println("no endpoints found"); } } catch (Exception e) { e.printStackTrace(); } } @Override public void onSessionKeepAlive(ServerStatusDataType serverStatusDataType, ServerState serverState) { System.out.println("incoming Keepalive => Serverstate: " + serverState.toString()); } @Override public void onSessionConnectionStateChanged(boolean isConnected) { System.out.println("incoming SessionConnectionState => Session Connected = " + isConnected); } }
Example: Read or write values
Beispiel:
…
//create and register monitoring item
client.StartMonitoringItem(„Objects.Server.Data.Dynamic.Scalar.Int64Value“, Client_MonitorNotification);
…
//catch the monitoring event
private void Client_MonitorNotification(string Identifier, MonitoredItem monitoredItem, MonitoredItemNotificationEventArgs e)
{
MonitoredItemNotification notification = e.NotificationValue as MonitoredItemNotification;
Console.WriteLine(Identifier + “ “ + monitoredItem.StartNodeId + “ Value: “ + notification.Value + “ Status: “ + notification.Value.StatusCode.ToString());
}
Nachfolgend ein komplettes ausführbares Beispiel:
using System; using PLCcom.Opc.Ua; using PLCcom.Opc.Ua.Client; using PLCcom.Opc.Ua.Client.Sdk; class Program { //flag, accept all untrusted certicates or not private bool autoAcceptUntrustedCertificates = true; //actual publishing state of subscription private PublishingState publishingState = PublishingState.UNDEFINED; static void Main(string[] args) { Program program = new Program(); program.Start(); } void Start() { try { //TODO //Submit your license information from your license e-mail string LicenseUserName = ""; string LicenseSerial = ""; EndpointDescriptionCollection Endpoints = UaClient.GetEndpoints(new Uri("opc.tcp://localhost:50520/PLCcom/DataAccessServer"), 60000); //sort endpoints by security level Endpoints = UaClient.SortEndpointsBySecurityLevel(Endpoints); if (Endpoints.Count > 0) { Console.WriteLine("endpoints found:"); int counter = 0; foreach (EndpointDescription Endpoint in Endpoints) { Console.WriteLine(counter++.ToString() + " => " + UaClient.EndpointToString(Endpoint)); } Console.WriteLine("please enter index of desired endpoint"); string NumberOfEndpoint = Console.ReadLine(); Console.WriteLine(""); int iNumberOfEndpoint = -1; if (int.TryParse(NumberOfEndpoint, out iNumberOfEndpoint) && iNumberOfEndpoint > -1 && iNumberOfEndpoint < Endpoints.Count) { //create a a SessionConfiguration with the selected endpoint and application name SessionConfiguration sessionConfiguration = SessionConfiguration.Build(System.Reflection.Assembly.GetEntryAssembly().GetName().Name, Endpoints[iNumberOfEndpoint]); //enable auto connect functionality sessionConfiguration.AutoConnect = true; //output certificate store path Console.WriteLine("Info: Sessionconfiguration created, certificate store path => " + sessionConfiguration.CertificateStorePath); //Create a new opc client instance and pass your license information using (UaClient client = new UaClient(LicenseUserName, LicenseSerial, sessionConfiguration)) { Console.WriteLine("Info: license state => " + client.GetLicenceMessage()); Console.WriteLine(""); //register events client.ServerConnectionLost += Client_ServerConnectionLost; client.ServerConnected += Client_ServerConnected; client.SessionClosing += Client_SessionClosing; client.KeepAlive += Client_KeepAlive; client.CertificateValidation += client_CertificateValidation; //create a new subscription using (Subscription subscription = new Subscription()) { subscription.PublishingInterval = 1000; subscription.PublishingEnabled = false; subscription.DisplayName = "mySubsription"; //register subscription events subscription.StateChanged += Subscription_StateChanged; subscription.PublishStatusChanged += Subscription_PublishStatusChanged; //add new subscription to client client.AddSubscription(subscription); try { //Create a monitoring item and add to the subscription NodeId nodeId = client.GetNodeIdByPath("Objects.Data.Dynamic.Scalar.Int64Value"); MonitoredItem monitoredItem = new MonitoredItem(subscription.DefaultItem) { StartNodeId = nodeId, SamplingInterval = 500, QueueSize = UInt32.MaxValue, DisplayName = nodeId.ToString() }; //register monitoring event monitoredItem.Notification += Client_MonitorNotification; //add Item to subscription subscription.AddItem(monitoredItem); nodeId = client.GetNodeIdByPath("Objects.Data.Dynamic.Scalar.BooleanValue"); monitoredItem = new MonitoredItem(subscription.DefaultItem) { StartNodeId = nodeId, SamplingInterval = 500, QueueSize = UInt32.MaxValue, DisplayName = nodeId.ToString() }; //register monitoring event monitoredItem.Notification += Client_MonitorNotification; //add Item to subscription subscription.AddItem(monitoredItem); //apply changes subscription.ApplyChanges(); //enable publishing mode of subscription and set PublishingInterval subscription.SetPublishingMode(true); subscription.Modify(); } catch (Exception ex) { Console.WriteLine(ex); } Console.WriteLine(); Console.WriteLine("press enter for exit"); Console.ReadLine(); } } } else { Console.WriteLine("invalid number of Endpoint"); } } else { Console.WriteLine("no endpoints found"); } } catch (Exception ex) { Console.WriteLine(ex); Console.WriteLine("press enter for exit"); Console.ReadLine(); } finally { Console.WriteLine("press enter for exit"); Console.ReadLine(); } } private void Client_MonitorNotification(MonitoredItem monitoredItem, MonitoredItemNotificationEventArgs e) { MonitoredItemNotification notification = e.NotificationValue as MonitoredItemNotification; Console.WriteLine(monitoredItem.StartNodeId.Identifier + " Value: " + notification.Value + " Status: " + notification.Value.StatusCode.ToString()); } private void Subscription_StateChanged(Subscription subscription, SubscriptionStateChangedEventArgs e) { Console.WriteLine(DateTime.Now.ToLocalTime() + " State of Subscription " + UaClient.SubscriptionToString(subscription) + " changed to => " + e.Status.ToString()); } private void Subscription_PublishStatusChanged(object sender, EventArgs e) { /* check your publish state of your subscription if the publish state permanent stopped, then you have to recreate your subscription with old subscription as template In this case, please have a look to the PublishingInterval setting, possibly be the value must be increased */ Subscription subscription = sender as Subscription; if (subscription != null) { PublishingState currentpublishingState = subscription.PublishingStopped ? PublishingState.STOPPED : PublishingState.RUNNING; if (currentpublishingState != publishingState || currentpublishingState == PublishingState.STOPPED) Console.WriteLine(DateTime.Now.ToLocalTime() + "Publishing state of Subscription " + UaClient.SubscriptionToString((Subscription)sender) + " => " + currentpublishingState.ToString()); publishingState = currentpublishingState; } } void client_CertificateValidation(CertificateValidator sender, CertificateValidationEventArgs e) { //external certificate validation if (ServiceResult.IsGood(e.Error)) e.Accept = true; else if ((e.Error.StatusCode.Code == StatusCodes.BadCertificateUntrusted || e.Error.StatusCode.Code == StatusCodes.BadCertificateChainIncomplete) && autoAcceptUntrustedCertificates) e.Accept = true; else { throw new Exception(string.Format("Failed to validate certificate with error code {0}: {1}", e.Error.Code, e.Error.AdditionalInfo)); } } private void Client_ServerConnected(object sender, EventArgs e) { //event opc ua server is connected Console.WriteLine(DateTime.Now.ToLocalTime() + " Session connected"); } private void Client_ServerConnectionLost(object sender, EventArgs e) { //event connection to opc ua server lost Console.WriteLine(DateTime.Now.ToLocalTime() + " Session connection lost"); } void Client_KeepAlive(Session session, KeepAliveEventArgs e) { //catch the keepalive event of opc ua server } private void Client_SessionClosing(object sender, EventArgs e) { Console.WriteLine(DateTime.Now.ToLocalTime() + " Session closed"); } private enum PublishingState { UNDEFINED, RUNNING, STOPPED } }
Imports System Imports System.Reflection Imports PLCcom.Opc.Ua Imports PLCcom.Opc.Ua.Client Imports PLCcom.Opc.Ua.Client.Sdk Public Class Program 'flag, accept all untrusted certicates or not Private autoAcceptUntrustedCertificates As Boolean = True 'actual publishing state of subscription Private publishingState As n_PublishingState = n_PublishingState.UNDEFINED Public Shared Sub Main(ByVal args As String()) Dim p As Program = New Program() p.Start() End Sub Private Sub Start() Try 'TODO 'Submit your license information from your license e-mail Dim LicenseUserName As String = "" Dim LicenseSerial As String = "" Dim Endpoints As EndpointDescriptionCollection = UaClient.GetEndpoints(New Uri("opc.tcp://localhost:50520/PLCcom/DataAccessServer"), 60000) 'sort endpoints by security level Endpoints = UaClient.SortEndpointsBySecurityLevel(Endpoints) If Endpoints.Count > 0 Then Console.WriteLine("endpoints found:") Dim counter As Integer = 0 For Each Endpoint As EndpointDescription In Endpoints Console.WriteLine($"{Math.Min(Threading.Interlocked.Increment(counter), counter - 1).ToString()} => { UaClient.EndpointToString(Endpoint)}") Next Console.WriteLine("please enter index of desired endpoint") Dim NumberOfEndpoint As String = Console.ReadLine() Console.WriteLine("") Dim iNumberOfEndpoint As Integer = -1 If Integer.TryParse(NumberOfEndpoint, iNumberOfEndpoint) AndAlso iNumberOfEndpoint > -1 AndAlso iNumberOfEndpoint < Endpoints.Count Then 'create a a SessionConfiguration with the selected endpoint and application name Dim sessionConfiguration As SessionConfiguration = SessionConfiguration.Build(Assembly.GetEntryAssembly().GetName().Name, Endpoints(iNumberOfEndpoint)) 'enable auto connect functionality sessionConfiguration.AutoConnect = True 'output certificate store path Console.WriteLine($"Info: Sessionconfiguration created, certificate store path => { sessionConfiguration.CertificateStorePath}") 'Create a new opc client instance and pass your license information Using client As UaClient = New UaClient(LicenseUserName, LicenseSerial, sessionConfiguration) Console.WriteLine($"Info: license state => { client.GetLicenceMessage()}") Console.WriteLine("") 'register events AddHandler client.ServerConnectionLost, AddressOf Client_ServerConnectionLost AddHandler client.ServerConnected, AddressOf Client_ServerConnected AddHandler client.SessionClosing, AddressOf Client_SessionClosing AddHandler client.KeepAlive, AddressOf Client_KeepAlive AddHandler client.CertificateValidation, AddressOf client_CertificateValidation 'create a new subscription Using subscription As Subscription = New Subscription() subscription.PublishingInterval = 1000 subscription.PublishingEnabled = False subscription.DisplayName = "mySubsription" 'register subscription events AddHandler subscription.StateChanged, AddressOf Subscription_StateChanged AddHandler subscription.PublishStatusChanged, AddressOf Subscription_PublishStatusChanged 'add new subscription to client client.AddSubscription(subscription) Try 'Create a monitoring item and add to the subscription Dim nodeId As NodeId = client.GetNodeIdByPath("Objects.Data.Dynamic.Scalar.Int64Value") Dim monitoredItem As MonitoredItem = New MonitoredItem(subscription.DefaultItem) With { .StartNodeId = nodeId, .SamplingInterval = 500, .QueueSize = UInteger.MaxValue, .DisplayName = nodeId.ToString() } 'register monitoring event AddHandler monitoredItem.Notification, AddressOf Client_MonitorNotification 'add Item to subscription subscription.AddItem(monitoredItem) nodeId = client.GetNodeIdByPath("Objects.Data.Dynamic.Scalar.BooleanValue") monitoredItem = New MonitoredItem(subscription.DefaultItem) With { .StartNodeId = nodeId, .SamplingInterval = 500, .QueueSize = UInteger.MaxValue, .DisplayName = nodeId.ToString() } 'register monitoring event AddHandler monitoredItem.Notification, AddressOf Client_MonitorNotification 'add Item to subscription subscription.AddItem(monitoredItem) 'apply changes subscription.ApplyChanges() 'enable publishing mode of subscription and set PublishingInterval subscription.SetPublishingMode(True) subscription.Modify() Catch ex As Exception Console.WriteLine(ex) End Try Console.WriteLine() Console.WriteLine("press enter for exit") Console.ReadLine() End Using End Using Else Console.WriteLine("invalid number of Endpoint") End If Else Console.WriteLine("no endpoints found") End If Catch ex As Exception Console.WriteLine(ex) Console.WriteLine("press enter for exit") Console.ReadLine() Finally Console.WriteLine("press enter for exit") Console.ReadLine() End Try End Sub Private Sub Client_MonitorNotification(ByVal monitoredItem As MonitoredItem, ByVal e As MonitoredItemNotificationEventArgs) Dim notification As MonitoredItemNotification = TryCast(e.NotificationValue, MonitoredItemNotification) Console.WriteLine($"{monitoredItem.StartNodeId.Identifier} Value: {notification.Value} Status: {notification.Value.StatusCode.ToString()}") End Sub Private Sub Subscription_StateChanged(ByVal subscription As Subscription, ByVal e As SubscriptionStateChangedEventArgs) Console.WriteLine($"{Date.Now.ToLocalTime()} State of Subscription { UaClient.SubscriptionToString(subscription) } changed to => { e.Status.ToString()}") End Sub Private Sub Subscription_PublishStatusChanged(ByVal sender As Object, ByVal e As EventArgs) ' ' check your publish state of your subscription ' if the publish state permanent stopped, then you have to recreate your subscription with old subscription as template ' In this case, please have a look to the PublishingInterval setting, possibly be the value must be increased ' Dim subscription As Subscription = TryCast(sender, Subscription) If subscription IsNot Nothing Then Dim currentpublishingState As n_PublishingState = If(subscription.PublishingStopped, n_PublishingState.STOPPED, n_PublishingState.RUNNING) If currentpublishingState <> publishingState OrElse currentpublishingState = n_PublishingState.STOPPED Then Console.WriteLine($"{Date.Now.ToLocalTime() } Publishing state of Subscription { UaClient.SubscriptionToString(CType(sender, Subscription)) } => { currentpublishingState.ToString()}") publishingState = currentpublishingState End If End Sub Private Sub client_CertificateValidation(ByVal sender As CertificateValidator, ByVal e As CertificateValidationEventArgs) 'external certificate validation If ServiceResult.IsGood(e.Error) Then e.Accept = True ElseIf (e.Error.StatusCode.Code = StatusCodes.BadCertificateUntrusted OrElse e.Error.StatusCode.Code = StatusCodes.BadCertificateChainIncomplete) AndAlso autoAcceptUntrustedCertificates Then e.Accept = True Else Throw New Exception($"Failed to validate certificate with error code {e.Error.Code}: {e.Error.AdditionalInfo}") End If End Sub Private Sub Client_ServerConnected(ByVal sender As Object, ByVal e As EventArgs) 'event opc ua server is connected Console.WriteLine($"{Date.Now.ToLocalTime()} Session connected") End Sub Private Sub Client_ServerConnectionLost(ByVal sender As Object, ByVal e As EventArgs) 'event connection to opc ua server lost Console.WriteLine($"{Date.Now.ToLocalTime()} Session connection lost") End Sub Private Sub Client_KeepAlive(ByVal session As Session, ByVal e As KeepAliveEventArgs) 'catch the keepalive event of opc ua server End Sub Private Sub Client_SessionClosing(ByVal sender As Object, ByVal e As EventArgs) Console.WriteLine($"{Date.Now.ToLocalTime()} Session closed") End Sub Private Enum n_PublishingState UNDEFINED RUNNING STOPPED End Enum End Class
package tutorials.t02_data_access; import java.net.URI; import java.util.ArrayList; import java.util.List; import plccom.opc.ua.sdk.client.application.ClientConfiguration; import plccom.opc.ua.sdk.client.application.MonitoredItem; import plccom.opc.ua.sdk.client.application.SortDirection; import plccom.opc.ua.sdk.client.application.UaClient; import plccom.opc.ua.sdk.client.application.UaSubscription; import plccom.opc.ua.sdk.client.application.listener.MonitoredItemNotificationListener; import plccom.opc.ua.sdk.client.application.listener.SessionConnectionStateChangeListener; import plccom.opc.ua.sdk.client.application.listener.SessionKeepAliveListener; import plccom.opc.ua.sdk.client.application.listener.SubscriptionListener; import plccom.opc.ua.sdk.client.core.attributes.UaAttributes; import org.opcfoundation.ua.builtintypes.DataValue; import org.opcfoundation.ua.builtintypes.DateTime; import org.opcfoundation.ua.builtintypes.LocalizedText; import org.opcfoundation.ua.builtintypes.NodeId; import org.opcfoundation.ua.builtintypes.StatusCode; import org.opcfoundation.ua.common.ServiceResultException; import org.opcfoundation.ua.core.EndpointDescription; import org.opcfoundation.ua.core.EventFieldList; import org.opcfoundation.ua.core.Identifiers; import org.opcfoundation.ua.core.MonitoredItemCreateRequest; import org.opcfoundation.ua.core.MonitoringMode; import org.opcfoundation.ua.core.MonitoringParameters; import org.opcfoundation.ua.core.ReadValueId; import org.opcfoundation.ua.core.ServerState; import org.opcfoundation.ua.core.ServerStatusDataType; public class Tutorial23_monitoring_nodes implements SessionKeepAliveListener, SessionConnectionStateChangeListener, MonitoredItemNotificationListener, SubscriptionListener { // Developer's TODO // Submit your license information from your license e-mail private final String LicenseUserName = ""; private final String LicenseSerial = ""; public static void main(String[] args) { Tutorial23_monitoring_nodes prog = new Tutorial23_monitoring_nodes(); prog.start(); } private void start() { try { String hostname = "localhost"; int port = 4840; // create a discovery uri URI discoveryUri = new URI(String.format("opc.tcp://%s:%s", hostname, port)); System.out.println(String.format("reading Endports from discoveryUri %s", discoveryUri.toString())); // Get endpoints from ua Server with discovery url EndpointDescription[] endpoints = UaClient.discoverEndpoints(discoveryUri); // sort endpoint by message security mode endpoints = UaClient.sortBySecurityLevel(endpoints, SortDirection.Asc); if (endpoints.length > 0) { // create Sessionconfiguration and set the default publishing // interval ClientConfiguration clientConfiguration = new ClientConfiguration( new LocalizedText("ExampleApplication", "en"), endpoints[0]); // set default publishing interval to 1000 milliseconds clientConfiguration.setDefaultPublishingInterval(1000.0); // enable auto connect functionality // set automatic reconnect after 1000 milliseconds in case of losing connection clientConfiguration.setAutoConnectEnabled(true, 1000); // Create new OPCUAClient try (UaClient myClient = new UaClient(LicenseUserName, LicenseSerial, clientConfiguration)) { // print license informations System.out.println(myClient.getLicenceMessage()); myClient.addSessionKeepAliveListener(this); myClient.addSessionConnectionStateChangeListener(this); myClient.getSubscriptionManager().addSubscriptionListener(this); // Setting up monitoring parameters MonitoringParameters parameters = new MonitoringParameters(); parameters.setSamplingInterval(1000.0); // Create the request list List requests = new ArrayList(); // create and add a create request for a monitoring item // identificated by browse path try { ReadValueId readValueId = new ReadValueId( myClient.getNodeIdByPath("Objects.Server.Data.Dynamic.Scalar.Int32Value"), UaAttributes.Value.getValue(), null, null); requests.add(new MonitoredItemCreateRequest(readValueId, MonitoringMode.Reporting, parameters)); } catch (ServiceResultException e) { e.printStackTrace(); System.out.println(e.getMessage()); } // create and add a create request for a monitoring item // identificated by node { ReadValueId readValueId = new ReadValueId(Identifiers.Server_ServerStatus_CurrentTime, UaAttributes.Value.getValue(), null, null); requests.add(new MonitoredItemCreateRequest(readValueId, MonitoringMode.Reporting, parameters)); } // create and add a create request for a monitoring item // identificated by NodeId try { ReadValueId readValueId = new ReadValueId(new NodeId(2, 10847), UaAttributes.Value.getValue(), null, null); requests.add(new MonitoredItemCreateRequest(readValueId, MonitoringMode.Reporting, parameters)); } catch (Exception e) { System.out.println(e.getMessage()); } // create and add a subscription UaSubscription subscription = myClient.getSubscriptionManager().createSubscription(); // Create, monitoring items and add monitoring item event // listener List monitoredItems = subscription.createMonitoredItems(requests, new MonitoredItemNotificationListener() { @Override public void onValueNotification(MonitoredItem monitoredItem, DataValue value) { // TODO Automatisch generierter Methodenstub } @Override public void onEventNotification(MonitoredItem monitoredItem, EventFieldList eventFieldList) { // TODO Automatisch generierter Methodenstub } }); // Logging output for (MonitoredItem monitoredItem : monitoredItems) if (monitoredItem.getStatusCode().isGood()) System.out.println(String.format("monitoredItem successfully %s created", monitoredItem.getDisplayName())); else System.out.println(String.format("cannot create monitoredItem %s, Statuscode: %s", monitoredItem.getDisplayName(), monitoredItem.getStatusCode())); System.in.read(); // cleaning up myClient.getSubscriptionManager().closeAndClearAllSubscriptions(); } } else { System.out.println("no endpoints found"); } } catch (Exception e) { e.printStackTrace(); } } @Override public void onValueNotification(MonitoredItem monitoredItem, DataValue value) { System.out.println(String.format("Value notification for NodeId %s arrived with Value: %s StatusCode: %s", monitoredItem.getReadValueId().getNodeId().toString(), value.getValue().toString(), value.getStatusCode().toString())); } @Override public void onEventNotification(MonitoredItem monitoredItem, EventFieldList eventFieldList) { System.out.println(String.format("Event notification for NodeId %s arrived", monitoredItem.getDisplayName())); } @Override public void onStatusChangeNotification(UaSubscription subscription, StatusCode statusCode) { System.out.println(String.format("StatusChangeNotification with statusCode %s on subscription %s", statusCode, subscription)); } @Override public void onPublishFailure(ServiceResultException error) { System.out.println(String.format("onPublishFailure %s ", error.getMessage())); } @Override public void onNotificationDataLost(UaSubscription subscription) { System.out.println(String.format("onNotificationDataLost on subscription %s", subscription)); } @Override public void onSubscriptionKeepAlive(UaSubscription subscription, DateTime publishTime) { System.out.println(String.format("onSubscriptionKeepAlive with subscription %s", subscription)); } @Override public void onSessionKeepAlive(ServerStatusDataType serverStatusDataType, ServerState serverState) { System.out.println("incoming Keepalive => Serverstate: " + serverState.toString()); } @Override public void onSessionConnectionStateChanged(boolean isConnected) { System.out.println("incoming SessionConnectionState => Session Connected = " + isConnected); } }
Example: Monitoring items