/// <summary> /// Finds the endpoint that best matches the current settings. /// </summary> private EndpointDescription SelectEndpoint() { try { Cursor = Cursors.WaitCursor; // determine the URL that was selected. string discoveryUrl = UrlCB.Text; if (UrlCB.SelectedIndex >= 0) { discoveryUrl = (string)UrlCB.SelectedItem; } // return the selected endpoint. return(CoreClientUtils.SelectEndpoint(discoveryUrl, UseSecurityCK.Checked, m_discoverTimeout)); } finally { Cursor = Cursors.Default; } }
public void Setup(string configSectionName) { applicationInstance = new ApplicationInstance { ApplicationName = "KamstrupOpcClient", ApplicationType = ApplicationType.Client, ConfigSectionName = configSectionName, }; applicationConfiguration = applicationInstance.LoadApplicationConfiguration(false).Result; doIHaveCertificate = applicationInstance.CheckApplicationInstanceCertificate(false, 0).Result; if (doIHaveCertificate) { applicationConfiguration.ApplicationUri = Utils.GetApplicationUriFromCertificate(applicationConfiguration.SecurityConfiguration.ApplicationCertificate.Certificate); autoAcceptCertificates = applicationConfiguration.SecurityConfiguration.AutoAcceptUntrustedCertificates; } applicationConfiguration.CertificateValidator.CertificateValidation += CertificateValidation; endpointDescription = CoreClientUtils.SelectEndpoint(this.endPointUrl, false); var endpointConfiguration = EndpointConfiguration.Create(applicationConfiguration); configuredEndpoint = new ConfiguredEndpoint(null, endpointDescription, endpointConfiguration); session = Session.Create(applicationConfiguration, configuredEndpoint, false, "Kamstrup OPC Client", 60000, null, null).Result; session.KeepAlive += KeepAlive; subscription = new Subscription(session.DefaultSubscription) { PublishingInterval = 1000 }; subscription.DefaultItem.Notification += OnNotification; session.AddSubscription(subscription); session.FetchNamespaceTables(); var ns = session.NamespaceUris; }
/// <summary> /// Connects the specified endpoint URL. /// </summary> /// <param name="endpointUrl">The endpoint URL.</param> /// <exception cref="System.ArgumentNullException">endpointUrl</exception> /// <exception cref="System.ArgumentException">endpointUrl</exception> public async Task Connect(string endpointUrl) { if (String.IsNullOrEmpty(endpointUrl)) { throw new ArgumentNullException(nameof(endpointUrl)); } if (!Uri.IsWellFormedUriString(endpointUrl, UriKind.Absolute)) { throw new ArgumentException(endpointUrl + " is not a valid URL.", nameof(endpointUrl)); } bool serverHalted = false; do { serverHalted = false; try { EndpointDescription endpointDescription = CoreClientUtils.SelectEndpoint(endpointUrl, true); EndpointConfiguration endpointConfiguration = EndpointConfiguration.Create(Application.ApplicationConfiguration); ConfiguredEndpoint endpoint = new ConfiguredEndpoint(null, endpointDescription, endpointConfiguration); await Connect(endpoint); } catch (ServiceResultException e) { if (e.StatusCode == StatusCodes.BadServerHalted) { serverHalted = true; await Task.Delay(1000); } else { throw; } } } while (serverHalted); }
private async Task <Opc.Ua.Client.Session> createSession(string url) { // select the best endpoint. EndpointDescription endpointDescription = CoreClientUtils.SelectEndpoint(url, true, 5000); EndpointConfiguration endpointConfiguration = EndpointConfiguration.Create(m_configuration); ConfiguredEndpoint endpoint = new ConfiguredEndpoint(null, endpointDescription, endpointConfiguration); UserIdentity user = new UserIdentity(); Opc.Ua.Client.Session session = await Opc.Ua.Client.Session.Create( m_configuration, endpoint, false, false, "Collector Server", 60000, user, null); return(session); }
/// <summary> /// Creates a new session. /// </summary> /// <returns>The new session object.</returns> public async Task <Session> Connect() { // disconnect from existing session. //Disconnect(); if (m_configuration == null) { throw new ArgumentNullException("m_configuration"); } // TODO bool useSecurity = false; // select the best endpoint. EndpointDescription endpointDescription = CoreClientUtils.SelectEndpoint(serverUrl, useSecurity, m_discoverTimeout); EndpointConfiguration endpointConfiguration = EndpointConfiguration.Create(m_configuration); ConfiguredEndpoint endpoint = new ConfiguredEndpoint(null, endpointDescription, endpointConfiguration); m_session = await Session.Create( m_configuration, endpoint, false, !DisableDomainCheck, (String.IsNullOrEmpty(SessionName))?m_configuration.ApplicationName : SessionName, 60000, UserIdentity, PreferredLocales); // set up keep alive callback. m_session.KeepAlive += new KeepAliveEventHandler(Session_KeepAlive); // raise an event. DoConnectComplete(null); // return the new session. return(m_session); }
/// <summary> /// Creates a new session. /// </summary> /// <returns>The new session object.</returns> private async Task <Session> Connect(string serverUrl) { // disconnect from existing session. Disconnect( ); if (m_configuration == null) { throw new ArgumentNullException("m_configuration"); } // select the best endpoint. EndpointDescription endpointDescription = CoreClientUtils.SelectEndpoint(serverUrl, UseSecurity); EndpointConfiguration endpointConfiguration = EndpointConfiguration.Create(m_configuration); ConfiguredEndpoint endpoint = new ConfiguredEndpoint(null, endpointDescription, endpointConfiguration); m_session = await Session.Create( m_configuration, endpoint, false, false, (string.IsNullOrEmpty(OpcUaName))?m_configuration.ApplicationName : OpcUaName, 60000, UserIdentity, new string[] { }); // set up keep alive callback. m_session.KeepAlive += new KeepAliveEventHandler(Session_KeepAlive); // update the client status m_IsConnected = true; // raise an event. DoConnectComplete(null); // return the new session. return(m_session); }
public bool open(string endpoint) { var application = new ApplicationInstance { ApplicationName = "OPC UA Client Lua", ApplicationType = ApplicationType.Client, ConfigSectionName = "Opc.Ua.Client.Lua" }; // load the application configuration. var taskConfig = application.LoadApplicationConfiguration(false); taskConfig.Wait(); var config = taskConfig.Result; var selectedEndpoint = CoreClientUtils.SelectEndpoint(endpoint, false, 15000); var endpointConfiguration = EndpointConfiguration.Create(config); var __endpoint = new ConfiguredEndpoint(null, selectedEndpoint, endpointConfiguration); var taskSession = Session.Create(config, __endpoint, false, "OPC UA Client Lua", 60000, new UserIdentity(new AnonymousIdentityToken()), null); taskSession.Wait(); this.session = taskSession.Result; return(true); }
/// <summary> /// Connects to a single OPC UA Server's endpoint /// </summary> public static async Task EndpointConnect(Uri endpointUrl) { EndpointDescription selectedEndpoint = CoreClientUtils.SelectEndpoint(endpointUrl.AbsoluteUri, true); ConfiguredEndpoint configuredEndpoint = new ConfiguredEndpoint(selectedEndpoint.Server, EndpointConfiguration.Create(m_configuration)); configuredEndpoint.Update(selectedEndpoint); Session newSession = await Session.Create( m_configuration, configuredEndpoint, true, false, m_configuration.ApplicationName, 60000, new UserIdentity(new AnonymousIdentityToken()), null); if (newSession != null) { Trace("Created session with updated endpoint " + selectedEndpoint.EndpointUrl + " from server!"); newSession.KeepAlive += new KeepAliveEventHandler((sender, e) => StandardClient_KeepAlive(sender, e, newSession)); m_sessions.Add(newSession); } }
public void InitializeOPCUAClient() { //Console.WriteLine("Step 1 - Create application configuration and certificate."); var config = new ApplicationConfiguration() { ApplicationName = MyApplicationName, ApplicationUri = Utils.Format(@"urn:{0}:" + MyApplicationName + "", ServerAddress), ApplicationType = ApplicationType.Client, SecurityConfiguration = new SecurityConfiguration { ApplicationCertificate = new CertificateIdentifier { StoreType = @"Directory", StorePath = @"%CommonApplicationData%\OPC Foundation\CertificateStores\MachineDefault", SubjectName = Utils.Format(@"CN={0}, DC={1}", MyApplicationName, ServerAddress) }, TrustedIssuerCertificates = new CertificateTrustList { StoreType = @"Directory", StorePath = @"%CommonApplicationData%\OPC Foundation\CertificateStores\UA Certificate Authorities" }, TrustedPeerCertificates = new CertificateTrustList { StoreType = @"Directory", StorePath = @"%CommonApplicationData%\OPC Foundation\CertificateStores\UA Applications" }, RejectedCertificateStore = new CertificateTrustList { StoreType = @"Directory", StorePath = @"%CommonApplicationData%\OPC Foundation\CertificateStores\RejectedCertificates" }, AutoAcceptUntrustedCertificates = true, AddAppCertToTrustedStore = true }, TransportConfigurations = new TransportConfigurationCollection(), TransportQuotas = new TransportQuotas { OperationTimeout = 15000 }, ClientConfiguration = new ClientConfiguration { DefaultSessionTimeout = 60000 }, TraceConfiguration = new TraceConfiguration() }; config.Validate(ApplicationType.Client).GetAwaiter().GetResult(); if (config.SecurityConfiguration.AutoAcceptUntrustedCertificates) { config.CertificateValidator.CertificateValidation += (s, e) => { e.Accept = (e.Error.StatusCode == StatusCodes.BadCertificateUntrusted); }; } var application = new ApplicationInstance { ApplicationName = MyApplicationName, ApplicationType = ApplicationType.Client, ApplicationConfiguration = config }; application.CheckApplicationInstanceCertificate(false, 2048).GetAwaiter().GetResult(); //string serverAddress = Dns.GetHostName(); string serverAddress = ServerAddress;; var selectedEndpoint = CoreClientUtils.SelectEndpoint("opc.tcp://" + serverAddress + ":" + ServerPortNumber + "", useSecurity: SecurityEnabled, operationTimeout: 15000); // Console.WriteLine($"Step 2 - Create a session with your server: {selectedEndpoint.EndpointUrl} "); OPCSession = Session.Create(config, new ConfiguredEndpoint(null, selectedEndpoint, EndpointConfiguration.Create(config)), false, "", 60000, null, null).GetAwaiter().GetResult(); { //Console.WriteLine("Step 4 - Create a subscription. Set a faster publishing interval if you wish."); var subscription = new Subscription(OPCSession.DefaultSubscription) { PublishingInterval = 1000 }; //Console.WriteLine("Step 5 - Add a list of items you wish to monitor to the subscription."); var list = new List <MonitoredItem> { }; //list.Add(new MonitoredItem(subscription.DefaultItem) { DisplayName = "M0404.CPU945.iBatchOutput", StartNodeId = "ns=2;s=M0404.CPU945.iBatchOutput" }); list.Add(new MonitoredItem(subscription.DefaultItem) { DisplayName = "ServerStatusCurrentTime", StartNodeId = "i=2258" }); foreach (KeyValuePair <string, TagClass> td in TagList) { list.Add(new MonitoredItem(subscription.DefaultItem) { DisplayName = td.Value.DisplayName, StartNodeId = "ns=" + OPCNameSpace + ";s=" + td.Value.NodeID + "" }); } list.ForEach(i => i.Notification += OnTagValueChange); subscription.AddItems(list); //Console.WriteLine("Step 6 - Add the subscription to the session."); OPCSession.AddSubscription(subscription); subscription.Create(); } }
static void Main(string[] args) { Console.WriteLine("Step 1 - Create application configuration and certificate."); var config = new ApplicationConfiguration() { ApplicationName = "MyHomework", ApplicationUri = Utils.Format(@"urn:{0}:MyHomework", System.Net.Dns.GetHostName()), ApplicationType = ApplicationType.Client, SecurityConfiguration = new SecurityConfiguration { ApplicationCertificate = new CertificateIdentifier { StoreType = @"Directory", StorePath = @"%CommonApplicationData%\OPC Foundation\CertificateStores\MachineDefault", SubjectName = Utils.Format(@"CN={0}, DC={1}", "MyHomework", System.Net.Dns.GetHostName()) }, TrustedIssuerCertificates = new CertificateTrustList { StoreType = @"Directory", StorePath = @"%CommonApplicationData%\OPC Foundation\CertificateStores\UA Certificate Authorities" }, TrustedPeerCertificates = new CertificateTrustList { StoreType = @"Directory", StorePath = @"%CommonApplicationData%\OPC Foundation\CertificateStores\UA Applications" }, RejectedCertificateStore = new CertificateTrustList { StoreType = @"Directory", StorePath = @"%CommonApplicationData%\OPC Foundation\CertificateStores\RejectedCertificates" }, AutoAcceptUntrustedCertificates = true, AddAppCertToTrustedStore = true }, TransportConfigurations = new TransportConfigurationCollection(), TransportQuotas = new TransportQuotas { OperationTimeout = 15000 }, ClientConfiguration = new ClientConfiguration { DefaultSessionTimeout = 60000 }, TraceConfiguration = new TraceConfiguration() }; config.Validate(ApplicationType.Client).GetAwaiter().GetResult(); if (config.SecurityConfiguration.AutoAcceptUntrustedCertificates) { config.CertificateValidator.CertificateValidation += (s, e) => { e.Accept = (e.Error.StatusCode == StatusCodes.BadCertificateUntrusted); }; } var application = new ApplicationInstance { ApplicationName = "MyHomework", ApplicationType = ApplicationType.Client, ApplicationConfiguration = config }; application.CheckApplicationInstanceCertificate(false, 2048).GetAwaiter().GetResult(); var selectedEndpoint = CoreClientUtils.SelectEndpoint("opc.tcp://" + Dns.GetHostName() + ":48010", useSecurity: true, operationTimeout: 15000); Console.WriteLine($"Step 2 - Create a session with your server: {selectedEndpoint.EndpointUrl} "); using (var session = Session.Create(config, new ConfiguredEndpoint(null, selectedEndpoint, EndpointConfiguration.Create(config)), false, "", 60000, null, null).GetAwaiter().GetResult()) { Console.WriteLine("Step 3 - Browse the server namespace."); ReferenceDescriptionCollection refs; Byte[] cp; session.Browse(null, null, ObjectIds.ObjectsFolder, 0u, BrowseDirection.Forward, ReferenceTypeIds.HierarchicalReferences, true, (uint)NodeClass.Variable | (uint)NodeClass.Object | (uint)NodeClass.Method, out cp, out refs); Console.WriteLine("DisplayName: BrowseName, NodeClass"); foreach (var rd in refs) { Console.WriteLine("{0}: {1}, {2}", rd.DisplayName, rd.BrowseName, rd.NodeClass); ReferenceDescriptionCollection nextRefs; byte[] nextCp; session.Browse(null, null, ExpandedNodeId.ToNodeId(rd.NodeId, session.NamespaceUris), 0u, BrowseDirection.Forward, ReferenceTypeIds.HierarchicalReferences, true, (uint)NodeClass.Variable | (uint)NodeClass.Object | (uint)NodeClass.Method, out nextCp, out nextRefs); foreach (var nextRd in nextRefs) { Console.WriteLine("+ {0}: {1}, {2}", nextRd.DisplayName, nextRd.BrowseName, nextRd.NodeClass); } } Console.WriteLine("Step 4 - Create a subscription. Set a faster publishing interval if you wish."); var subscription = new Subscription(session.DefaultSubscription) { PublishingInterval = 1000 }; Console.WriteLine("Step 5 - Add a list of items you wish to monitor to the subscription."); var list = new List <MonitoredItem> { new MonitoredItem(subscription.DefaultItem) { DisplayName = "ServerStatusCurrentTime", StartNodeId = "i=2258" } }; list.ForEach(i => i.Notification += OnNotification); subscription.AddItems(list); Console.WriteLine("Step 6 - Add the subscription to the session."); session.AddSubscription(subscription); subscription.Create(); Console.WriteLine("Press any key to remove subscription..."); Console.ReadKey(true); } Console.WriteLine("Press any key to exit..."); Console.ReadKey(true); }
private async Task RunClient(string endpointURL) { //Create an Application Configuration Utils.SetTraceOutput(Utils.TraceOutput.DebugAndFile); var config = new ApplicationConfiguration() { ApplicationName = "UA Core Sample Client", ApplicationType = ApplicationType.Client, ApplicationUri = "urn:" + Utils.GetHostName() + ":OPCFoundation:CoreSampleClient", SecurityConfiguration = new SecurityConfiguration { ApplicationCertificate = new CertificateIdentifier { StoreType = "X509Store", StorePath = "CurrentUser\\UA_MachineDefault", SubjectName = "UA Core Sample Client" }, TrustedPeerCertificates = new CertificateTrustList { StoreType = "Directory", StorePath = "OPC Foundation/CertificateStores/UA Applications", }, TrustedIssuerCertificates = new CertificateTrustList { StoreType = "Directory", StorePath = "OPC Foundation/CertificateStores/UA Certificate Authorities", }, RejectedCertificateStore = new CertificateTrustList { StoreType = "Directory", StorePath = "OPC Foundation/CertificateStores/RejectedCertificates", }, NonceLength = 32, AutoAcceptUntrustedCertificates = true }, TransportConfigurations = new TransportConfigurationCollection(), TransportQuotas = new TransportQuotas { OperationTimeout = 15000 }, ClientConfiguration = new ClientConfiguration { DefaultSessionTimeout = 60000 } }; await config.Validate(ApplicationType.Client); bool haveAppCertificate = config.SecurityConfiguration.ApplicationCertificate.Certificate != null; if (!haveAppCertificate) { Console.WriteLine(" INFO: Creating new application certificate: {0}", config.ApplicationName); X509Certificate2 certificate = CertificateFactory.CreateCertificate( config.SecurityConfiguration.ApplicationCertificate.StoreType, config.SecurityConfiguration.ApplicationCertificate.StorePath, null, config.ApplicationUri, config.ApplicationName, config.SecurityConfiguration.ApplicationCertificate.SubjectName, null, CertificateFactory.defaultKeySize, DateTime.UtcNow - TimeSpan.FromDays(1), CertificateFactory.defaultLifeTime, CertificateFactory.defaultHashSize, false, null, null ); config.SecurityConfiguration.ApplicationCertificate.Certificate = certificate; } haveAppCertificate = config.SecurityConfiguration.ApplicationCertificate.Certificate != null; if (haveAppCertificate) { config.ApplicationUri = Utils.GetApplicationUriFromCertificate(config.SecurityConfiguration.ApplicationCertificate.Certificate); if (config.SecurityConfiguration.AutoAcceptUntrustedCertificates) { config.CertificateValidator.CertificateValidation += new CertificateValidationEventHandler(CertificateValidator_CertificateValidation); } } else { //TODO: throw EX: missing application certificate, using unsecure connection } // Discover endpoints var selectedEndpoint = CoreClientUtils.SelectEndpoint(endpointURL, haveAppCertificate); //Create a session with OPC UA server var endpointConfiguration = EndpointConfiguration.Create(config); var endpoint = new ConfiguredEndpoint(null, selectedEndpoint, endpointConfiguration); var session = await Session.Create(config, endpoint, false, ".Net Core OPC UA Console Client", 60000, new UserIdentity(new AnonymousIdentityToken()), null); Session = session; }
public async Task <ConnectionStatus> OpcClient(string endpointURL) { try { Uri endpointURI = new Uri(endpointURL); var selectedEndpoint = CoreClientUtils.SelectEndpoint(endpointURL, false, 15000); info.LabelText = "Selected endpoint uses: " + selectedEndpoint.SecurityPolicyUri.Substring(selectedEndpoint.SecurityPolicyUri.LastIndexOf('#') + 1); var endpointConfiguration = EndpointConfiguration.Create(config); var endpoint = new ConfiguredEndpoint(selectedEndpoint.Server, endpointConfiguration); endpoint.Update(selectedEndpoint); var platform = Device.RuntimePlatform; var sessionName = ""; switch (Device.RuntimePlatform) { case "Android": sessionName = "AIS Demonstrator Android Applikation"; break; // other cases are irrelevant for the Industrie 4.0 Demonstrator as of now case "UWP": sessionName = "OPC UA Xamarin Client UWP"; break; case "iOS": sessionName = "OPC UA Xamarin Client IOS"; break; } #region OPC UA User Authentication handling /* * Partially copied from https://github.com/OPCFoundation/UA-.NETStandard/issues/446 */ UserTokenPolicy utp = new UserTokenPolicy(); utp.TokenType = UserTokenType.UserName; UserTokenPolicyCollection utpCollection = new UserTokenPolicyCollection(); utpCollection.Add(utp); selectedEndpoint.UserIdentityTokens = utpCollection; selectedEndpoint.SecurityMode = MessageSecurityMode.SignAndEncrypt; UserIdentity SessionUserIdentity = new UserIdentity(MainActivity.UserName, MainActivity.UserPassword); #endregion session = await Session.Create(config, endpoint, false, sessionName, 30000, SessionUserIdentity, null); if (session != null) { connectionStatus = ConnectionStatus.Connected; #region Subscription + monitoredItems // Code for Monitored Items based on http://opcfoundation.github.io/UA-.NETStandard/help/index.htm#client_development.htm // Create Subscription Subscription subscription = new Subscription() // new Subscription(OpcClient.session.DefaultSubscription) { PublishingInterval = 1000, PublishingEnabled = true }; // CoffeeLevel MonitoredItem CoffeeLevel = new MonitoredItem(subscription.DefaultItem) { StartNodeId = "ns=1;s=CoffeeLevel", DisplayName = "MonitoredCoffeeLevel", AttributeId = Attributes.Value, MonitoringMode = MonitoringMode.Reporting, SamplingInterval = 1000, // check the CoffeeLevel every second QueueSize = 1, // only the most recent value for the CoffeeLevel is needed, thus we only need a queuesize of one DiscardOldest = true // we only need the most recent value for CoffeeLevel }; CoffeeLevel.Notification += (sender, e) => OnNotification(sender, e, ref valueCoffeeLevel); // WaterLevel MonitoredItem WaterLevel = new MonitoredItem(subscription.DefaultItem) { StartNodeId = "ns=1;s=WaterLevel", DisplayName = "MonitoredWaterLevel", AttributeId = Attributes.Value, MonitoringMode = MonitoringMode.Reporting, SamplingInterval = 1000, // check the CoffeeLevel every second QueueSize = 1, // only the most recent value for the CoffeeLevel is needed, thus we only need a queuesize of one DiscardOldest = true // we only need the most recent value for CoffeeLevel }; WaterLevel.Notification += (sender, e) => OnNotification(sender, e, ref valueWaterLevel); // CleanlinessLevel MonitoredItem CleanlinessLevel = new MonitoredItem(subscription.DefaultItem) { StartNodeId = "ns=1;s=Cleanliness", DisplayName = "MonitoredCleanlinessLevel", AttributeId = Attributes.Value, MonitoringMode = MonitoringMode.Reporting, SamplingInterval = 1000, // check the CoffeeLevel every second QueueSize = 1, // only the most recent value for the CoffeeLevel is needed, thus we only need a queuesize of one DiscardOldest = true // we only need the most recent value for CoffeeLevel }; CleanlinessLevel.Notification += (sender, e) => OnNotification(sender, e, ref valueCleanlinessLevel); // add MonitoredItems to Subscription subscription.AddItem(CoffeeLevel); subscription.AddItem(WaterLevel); subscription.AddItem(CleanlinessLevel); // add Subscription to Session session.AddSubscription(subscription); subscription.Create(); #endregion } else { connectionStatus = ConnectionStatus.NotConnected; } // register keep alive handler session.KeepAlive += Client_KeepAlive; } catch { connectionStatus = ConnectionStatus.Error; } return(connectionStatus); }
public async Task StartAsync(string endpointUrl) { if (!IsSessionStarted) { ApplicationInstance application = new ApplicationInstance { ApplicationName = "OPC-UA Sample", ApplicationType = ApplicationType.Client, ConfigSectionName = "OpcUA" }; var config = new ApplicationConfiguration() { ApplicationName = "UADEMO.prosysopc.com:OPCUA:SimulationServer", ApplicationUri = "urn:UADEMO.prosysopc.com:OPCUA:SimulationServer", ApplicationType = ApplicationType.Client, SecurityConfiguration = new SecurityConfiguration { ApplicationCertificate = new CertificateIdentifier { StoreType = @"X509Store", StorePath = @"CurrentUser\UA_MachineDefault", SubjectName = "DC=UADEMO.prosysopc.com, O=Prosys OPC, CN=SimulationServer@UADEMO" }, TrustedIssuerCertificates = new CertificateTrustList { StoreType = @"Directory", StorePath = @"%CommonApplicationData%\OPC Foundation\CertificateStores\UA Certificate Authorities" }, TrustedPeerCertificates = new CertificateTrustList { StoreType = @"Directory", StorePath = @"%CommonApplicationData%\OPC Foundation\CertificateStores\UA Applications" }, RejectedCertificateStore = new CertificateTrustList { StoreType = @"Directory", StorePath = @"%CommonApplicationData%\OPC Foundation\CertificateStores\RejectedCertificates" }, AutoAcceptUntrustedCertificates = true, AddAppCertToTrustedStore = true }, TransportConfigurations = new TransportConfigurationCollection(), TransportQuotas = new TransportQuotas { OperationTimeout = 15000 }, ClientConfiguration = new ClientConfiguration { DefaultSessionTimeout = 60000 }, TraceConfiguration = new TraceConfiguration() }; await config.Validate(ApplicationType.Client).ConfigureAwait(false); // Handle application certificate config.CertificateValidator.CertificateValidation += (_, e) => e.Accept = true; try { var selectedEndpoint = CoreClientUtils.SelectEndpoint(endpointUrl, false, 60000); // 15s timeout var endpointConfiguration = EndpointConfiguration.Create(config); var endpoint = new ConfiguredEndpoint(null, selectedEndpoint, endpointConfiguration); Session = await Session.Create( config, endpoint, false, application.ApplicationName, 60000, new UserIdentity(new AnonymousIdentityToken()), null ).ConfigureAwait(false); IsSessionStarted = true; } catch (Exception e) { Console.Error.Write(e); } } }
private async Task ConsoleClient() { Log(conn_name + " - " + "Create an Application Configuration..."); exitCode = ExitCode.ErrorCreateApplication; ApplicationInstance application = new ApplicationInstance { ApplicationName = "JSON-SCADA OPC-UA Client", ApplicationType = ApplicationType.Client, ConfigSectionName = "", }; bool haveAppCertificate = false; ApplicationConfiguration config = null; try { // load the application configuration. Log(conn_name + " - " + "Load config from " + OPCUA_conn.configFileName); config = await application.LoadApplicationConfiguration(OPCUA_conn.configFileName, false); // config.SecurityConfiguration.AutoAcceptUntrustedCertificates = true; // check the application certificate. haveAppCertificate = await application.CheckApplicationInstanceCertificate(false, 0); if (!haveAppCertificate) { Log(conn_name + " - " + "FATAL: Application instance certificate invalid!", LogLevelNoLog); Environment.Exit(1); } if (haveAppCertificate) { config.ApplicationUri = X509Utils.GetApplicationUriFromCertificate(config.SecurityConfiguration.ApplicationCertificate.Certificate); if (config.SecurityConfiguration.AutoAcceptUntrustedCertificates) { autoAccept = true; } config.CertificateValidator.CertificateValidation += new CertificateValidationEventHandler(CertificateValidator_CertificateValidation); } else { Log(conn_name + " - " + "WARN: missing application certificate, using unsecure connection."); } } catch (Exception e) { Log(conn_name + " - WARN: " + e.Message); } if (config == null) { Log(conn_name + " - " + "FATAL: error in XML config file!", LogLevelNoLog); Environment.Exit(1); } try { Log(conn_name + " - " + "Discover endpoints of " + OPCUA_conn.endpointURLs[0]); exitCode = ExitCode.ErrorDiscoverEndpoints; var selectedEndpoint = CoreClientUtils.SelectEndpoint(OPCUA_conn.endpointURLs[0], haveAppCertificate && OPCUA_conn.useSecurity, 15000); Log(conn_name + " - " + "Selected endpoint uses: " + selectedEndpoint.SecurityPolicyUri.Substring(selectedEndpoint.SecurityPolicyUri.LastIndexOf('#') + 1)); Log(conn_name + " - " + "Create a session with OPC UA server."); exitCode = ExitCode.ErrorCreateSession; var endpointConfiguration = EndpointConfiguration.Create(config); var endpoint = new ConfiguredEndpoint(null, selectedEndpoint, endpointConfiguration); await Task.Delay(50); session = await Session.Create(config, endpoint, false, "OPC UA Console Client", 60000, new UserIdentity(new AnonymousIdentityToken()), null); // Log("" + session.KeepAliveInterval); // default is 5000 session.KeepAliveInterval = System.Convert.ToInt32(OPCUA_conn.timeoutMs); // register keep alive handler session.KeepAlive += Client_KeepAlive; } catch (Exception e) { Log(conn_name + " - WARN: " + e.Message); } if (session == null) { Log(conn_name + " - " + "FATAL: error creating session!", LogLevelNoLog); Environment.Exit(1); } Log(conn_name + " - " + "Browsing the OPC UA server namespace."); exitCode = ExitCode.ErrorBrowseNamespace; await FindObjects(session, ObjectIds.ObjectsFolder); await Task.Delay(50); Log(conn_name + " - " + "Add a list of items (server current time and status) to the subscription."); exitCode = ExitCode.ErrorMonitoredItem; ListMon.ForEach(i => i.Notification += OnNotification); //ListMon.ForEach(i => i.SamplingInterval = System.Convert.ToInt32(System.Convert.ToDouble(OPCUA_conn.autoCreateTagSamplingInterval) * 1000); // ListMon.ForEach(i => Log(conn_name + " - " + i.DisplayName)); Log(conn_name + " - " + ListMon.Count + " Objects found"); Log(conn_name + " - " + "Create a subscription with publishing interval of " + System.Convert.ToDouble(OPCUA_conn.autoCreateTagPublishingInterval) + "seconds"); exitCode = ExitCode.ErrorCreateSubscription; var subscription = new Subscription(session.DefaultSubscription) { PublishingInterval = System.Convert.ToInt32(System.Convert.ToDouble(OPCUA_conn.autoCreateTagPublishingInterval) * 1000), PublishingEnabled = true }; await Task.Delay(50); subscription.AddItems(ListMon); await Task.Delay(50); Log(conn_name + " - " + "Add the subscription to the session."); Log(conn_name + " - " + subscription.MonitoredItemCount + " Monitored items"); exitCode = ExitCode.ErrorAddSubscription; session.AddSubscription(subscription); subscription.Create(); subscription.ApplyChanges(); Log(conn_name + " - " + "Running..."); exitCode = ExitCode.ErrorRunning; }
public static async Task ConsoleSampleClient(string endpointURL) { Console.WriteLine("1 - Create an Application Configuration."); Utils.SetTraceOutput(Utils.TraceOutput.DebugAndFile); var config = new ApplicationConfiguration() { ApplicationName = "UA Core Sample Client", ApplicationType = ApplicationType.Client, ApplicationUri = "urn:" + Utils.GetHostName() + ":OPCFoundation:CoreSampleClient", SecurityConfiguration = new SecurityConfiguration { ApplicationCertificate = new CertificateIdentifier { StoreType = "X509Store", StorePath = "CurrentUser\\UA_MachineDefault", SubjectName = "UA Core Sample Client" }, TrustedPeerCertificates = new CertificateTrustList { StoreType = "Directory", StorePath = "OPC Foundation/CertificateStores/UA Applications", }, TrustedIssuerCertificates = new CertificateTrustList { StoreType = "Directory", StorePath = "OPC Foundation/CertificateStores/UA Certificate Authorities", }, RejectedCertificateStore = new CertificateTrustList { StoreType = "Directory", StorePath = "OPC Foundation/CertificateStores/RejectedCertificates", }, NonceLength = 32, AutoAcceptUntrustedCertificates = true }, TransportConfigurations = new TransportConfigurationCollection(), TransportQuotas = new TransportQuotas { OperationTimeout = 15000 }, ClientConfiguration = new ClientConfiguration { DefaultSessionTimeout = 60000 } }; await config.Validate(ApplicationType.Client); bool haveAppCertificate = config.SecurityConfiguration.ApplicationCertificate.Certificate != null; if (!haveAppCertificate) { Console.WriteLine(" INFO: Creating new application certificate: {0}", config.ApplicationName); X509Certificate2 certificate = CertificateFactory.CreateCertificate( config.SecurityConfiguration.ApplicationCertificate.StoreType, config.SecurityConfiguration.ApplicationCertificate.StorePath, null, config.ApplicationUri, config.ApplicationName, config.SecurityConfiguration.ApplicationCertificate.SubjectName, null, CertificateFactory.defaultKeySize, DateTime.UtcNow - TimeSpan.FromDays(1), CertificateFactory.defaultLifeTime, CertificateFactory.defaultHashSize, false, null, null ); config.SecurityConfiguration.ApplicationCertificate.Certificate = certificate; } haveAppCertificate = config.SecurityConfiguration.ApplicationCertificate.Certificate != null; if (haveAppCertificate) { config.ApplicationUri = Utils.GetApplicationUriFromCertificate(config.SecurityConfiguration.ApplicationCertificate.Certificate); if (config.SecurityConfiguration.AutoAcceptUntrustedCertificates) { config.CertificateValidator.CertificateValidation += new CertificateValidationEventHandler(CertificateValidator_CertificateValidation); } } else { Console.WriteLine(" WARN: missing application certificate, using unsecure connection."); } Console.WriteLine("2 - Discover endpoints of {0}.", endpointURL); var selectedEndpoint = CoreClientUtils.SelectEndpoint(endpointURL, haveAppCertificate); Console.WriteLine(" Selected endpoint uses: {0}", selectedEndpoint.SecurityPolicyUri.Substring(selectedEndpoint.SecurityPolicyUri.LastIndexOf('#') + 1)); Console.WriteLine("3 - Create a session with OPC UA server."); var endpointConfiguration = EndpointConfiguration.Create(config); var endpoint = new ConfiguredEndpoint(null, selectedEndpoint, endpointConfiguration); var session = await Session.Create(config, endpoint, false, ".Net Core OPC UA Console Client", 60000, new UserIdentity(new AnonymousIdentityToken()), null); Console.WriteLine("4 - Browse the OPC UA server namespace."); ReferenceDescriptionCollection references; Byte[] continuationPoint; references = session.FetchReferences(ObjectIds.ObjectsFolder); session.Browse( null, null, ObjectIds.ObjectsFolder, 0u, BrowseDirection.Forward, ReferenceTypeIds.HierarchicalReferences, true, (uint)NodeClass.Variable | (uint)NodeClass.Object | (uint)NodeClass.Method, out continuationPoint, out references); Console.WriteLine(" DisplayName, BrowseName, NodeClass"); foreach (var rd in references) { Console.WriteLine(" {0}, {1}, {2}", rd.DisplayName, rd.BrowseName, rd.NodeClass); ReferenceDescriptionCollection nextRefs; byte[] nextCp; session.Browse( null, null, ExpandedNodeId.ToNodeId(rd.NodeId, session.NamespaceUris), 0u, BrowseDirection.Forward, ReferenceTypeIds.HierarchicalReferences, true, (uint)NodeClass.Variable | (uint)NodeClass.Object | (uint)NodeClass.Method, out nextCp, out nextRefs); foreach (var nextRd in nextRefs) { Console.WriteLine(" + {0}, {1}, {2}", nextRd.DisplayName, nextRd.BrowseName, nextRd.NodeClass); } } Console.WriteLine("5 - Create a subscription with publishing interval of 1 second."); var subscription = new Subscription(session.DefaultSubscription) { PublishingInterval = 1000 }; Console.WriteLine("6 - Add a list of items (server current time and status) to the subscription."); var list = new List <MonitoredItem> { new MonitoredItem(subscription.DefaultItem) { DisplayName = "ServerStatusCurrentTime", StartNodeId = "i=2258" } }; list.ForEach(i => i.Notification += OnNotification); subscription.AddItems(list); Console.WriteLine("7 - Add the subscription to the session."); session.AddSubscription(subscription); subscription.Create(); Console.WriteLine("8 - Running...Press any key to exit..."); Console.ReadKey(true); }
public OpcMethodTest(string testserverUrl, int maxShortWaitSec, int maxLongWaitSec, CancellationToken ct) : base("OpcMethodTest", testserverUrl, maxShortWaitSec, maxLongWaitSec, ct) { string logPrefix = $"{_logClassPrefix}:OpcMethodTest:"; Logger.Information($"{logPrefix} Publisher URL: {PublisherUrl}"); //TestserverUrl = testserverUrl; _application = new ApplicationInstance { ApplicationName = "UA Core Sample Client", ApplicationType = ApplicationType.Client, ConfigSectionName = "Opc.Ua.SampleClient" }; // load the application configuration. _config = _application.LoadApplicationConfiguration(false).Result; // check the application certificate. bool haveAppCertificate = _application.CheckApplicationInstanceCertificate(false, 0).Result; if (!haveAppCertificate) { Logger.Fatal($"{logPrefix} Application instance certificate invalid!"); throw new Exception("Application instance certificate invalid!"); } if (haveAppCertificate) { _config.ApplicationUri = Utils.GetApplicationUriFromCertificate(_config.SecurityConfiguration.ApplicationCertificate.Certificate); if (_config.SecurityConfiguration.AutoAcceptUntrustedCertificates) { AutoAccept = true; } _config.CertificateValidator.CertificateValidation += new CertificateValidationEventHandler(CertificateValidator_CertificateValidation); } else { Logger.Warning($"{logPrefix} Missing application certificate, using unsecure connection."); } Logger.Information($"{logPrefix} Discover endpoints of {PublisherUrl}."); _selectedEndpoint = CoreClientUtils.SelectEndpoint(PublisherUrl, haveAppCertificate, 15000); Logger.Information($"{logPrefix} Selected endpoint uses: {0}", _selectedEndpoint.SecurityPolicyUri.Substring(_selectedEndpoint.SecurityPolicyUri.LastIndexOf('#') + 1)); Logger.Information($"{logPrefix} Create a session with OPC UA server."); _endpointConfiguration = EndpointConfiguration.Create(_config); _configuredEndpoint = new ConfiguredEndpoint(null, _selectedEndpoint, _endpointConfiguration); // create session _session = Session.Create(_config, _configuredEndpoint, false, "OPC UA Console Client", 60000, new UserIdentity(new AnonymousIdentityToken()), null).Result; _session.KeepAlive += Client_KeepAlive; Logger.Information($"{logPrefix} Browse the OPC UA server namespace."); ReferenceDescriptionCollection references; Byte[] continuationPoint; references = _session.FetchReferences(ObjectIds.ObjectsFolder); _session.Browse( null, null, ObjectIds.ObjectsFolder, 0u, BrowseDirection.Forward, ReferenceTypeIds.HierarchicalReferences, true, (uint)NodeClass.Variable | (uint)NodeClass.Object | (uint)NodeClass.Method, out continuationPoint, out references); Logger.Information($"{logPrefix} DisplayName, BrowseName, NodeClass"); foreach (var rd in references) { Logger.Information($"{logPrefix} {rd.DisplayName}, {rd.BrowseName}, {rd.NodeClass}"); ReferenceDescriptionCollection nextRefs; byte[] nextCp; _session.Browse( null, null, ExpandedNodeId.ToNodeId(rd.NodeId, _session.NamespaceUris), 0u, BrowseDirection.Forward, ReferenceTypeIds.HierarchicalReferences, true, (uint)NodeClass.Variable | (uint)NodeClass.Object | (uint)NodeClass.Method, out nextCp, out nextRefs); foreach (var nextRd in nextRefs) { Logger.Information($"{logPrefix} + {nextRd.DisplayName}, {nextRd.BrowseName}, {nextRd.NodeClass}"); } _publishingIntervalSec = maxLongWaitSec; Logger.Information($"{logPrefix} Create a subscription with publishing interval of {_publishingIntervalSec} second."); var subscription = new Subscription(_session.DefaultSubscription) { PublishingInterval = _publishingIntervalSec * 1000 }; Logger.Information($"{logPrefix} Add a list of items (server current time and status) to the subscription."); var list = new List <MonitoredItem> { new MonitoredItem(subscription.DefaultItem) { DisplayName = "ServerStatusCurrentTime", StartNodeId = "i=" + Variables.Server_ServerStatus_CurrentTime.ToString(CultureInfo.InvariantCulture) } }; _lastTimestamp = new DateTime(0); list.ForEach(i => i.Notification += OnNotification); subscription.AddItems(list); Logger.Information($"{logPrefix} Add the subscription to the session."); _session.AddSubscription(subscription); subscription.Create(); //await Task.Delay(-1, ct); //subscription.Delete(true); } }
private async Task Client() { Logger.Info("1 - Create an Application Configuration."); ExitCode = ExitCode.ErrorCreateApplication; var application = new ApplicationInstance { ApplicationType = ApplicationType.Client, ConfigSectionName = nameof(OpcUaClient) }; // load the application configuration. var config = await application.LoadApplicationConfiguration("OpcUaClient.Config.xml", false); // check the application certificate. var haveAppCertificate = await application.CheckApplicationInstanceCertificate(false, 0); if (!haveAppCertificate) { throw new Exception("Application instance certificate invalid!"); } config.ApplicationUri = Utils.GetApplicationUriFromCertificate(config.SecurityConfiguration.ApplicationCertificate .Certificate); config.CertificateValidator.CertificateValidation += CertificateValidator_CertificateValidation; Logger.Info("2 - Discover endpoints of {0}.", EndpointUrl); ExitCode = ExitCode.ErrorDiscoverEndpoints; var selectedEndpoint = CoreClientUtils.SelectEndpoint(EndpointUrl, true, 15000); Logger.Info(" Selected endpoint uses: {0}", selectedEndpoint.SecurityPolicyUri.Substring(selectedEndpoint.SecurityPolicyUri.LastIndexOf('#') + 1)); Logger.Info("3 - Create a session with OPC UA server."); ExitCode = ExitCode.ErrorCreateSession; var endpointConfiguration = EndpointConfiguration.Create(config); var endpoint = new ConfiguredEndpoint(null, selectedEndpoint, endpointConfiguration); Session = await Session.Create(config, endpoint, false, "OPC UA Console Client", 60000, new UserIdentity(new AnonymousIdentityToken()), null); // register keep alive handler Session.KeepAlive += Client_KeepAlive; Logger.Info("4 - Browse the OPC UA server namespace."); ExitCode = ExitCode.ErrorBrowseNamespace; /*byte[] continuationPoint; * * var references = _session.FetchReferences(ObjectIds.ObjectsFolder); * * _session.Browse( * null, * null, * ObjectIds.ObjectsFolder, * 0u, * BrowseDirection.Forward, * ReferenceTypeIds.HierarchicalReferences, * true, * (uint) NodeClass.Variable | (uint) NodeClass.Object | (uint) NodeClass.Method, * out continuationPoint, * out references); * * Console.WriteLine(" DisplayName, BrowseName, NodeClass"); * foreach (var rd in references) * { * Console.WriteLine(" {0}, {1}, {2}", rd.DisplayName, rd.BrowseName, rd.NodeClass); * ReferenceDescriptionCollection nextRefs; * byte[] nextCp; * _session.Browse( * null, * null, * ExpandedNodeId.ToNodeId(rd.NodeId, _session.NamespaceUris), * 0u, * BrowseDirection.Forward, * ReferenceTypeIds.HierarchicalReferences, * true, * (uint) NodeClass.Variable | (uint) NodeClass.Object | (uint) NodeClass.Method, * out nextCp, * out nextRefs); * * foreach (var nextRd in nextRefs) * Console.WriteLine(" + {0}, {1}, {2}", nextRd.DisplayName, nextRd.BrowseName, * nextRd.NodeId); * }*/ Logger.Info("5 - Create a subscription with publishing interval of 1 second."); ExitCode = ExitCode.ErrorCreateSubscription; var subscription = new Subscription(Session.DefaultSubscription) { PublishingInterval = 1000 }; Logger.Info("6 - Add a list of items (server current time and status) to the subscription."); ExitCode = ExitCode.ErrorMonitoredItem; var list = new List <MonitoredItem> { new MonitoredItem(subscription.DefaultItem) { DisplayName = "ServerStatusCurrentTime", StartNodeId = "i=" + Variables.Server_ServerStatus_CurrentTime } }; list.AddRange(_monitoredItems); subscription.AddItems(list); Logger.Info("7 - Add the subscription to the session."); ExitCode = ExitCode.ErrorAddSubscription; Session.AddSubscription(subscription); subscription.Create(); ExitCode = ExitCode.ErrorRunning; IsConnected = true; _timer.Dispose(); }
private async Task <Session> ConsoleSampleClient() { Console.WriteLine("1 - Create an Application Configuration."); ExitCode = ExitCode.ErrorCreateApplication; ApplicationInstance application = new ApplicationInstance { ApplicationName = "UA Core Complex Client", ApplicationType = ApplicationType.Client, ConfigSectionName = "Opc.Ua.ComplexClient" }; // load the application configuration. ApplicationConfiguration config = await application.LoadApplicationConfiguration(false); // check the application certificate. bool haveAppCertificate = await application.CheckApplicationInstanceCertificate(false, 0); if (!haveAppCertificate) { throw new Exception("Application instance certificate invalid!"); } if (haveAppCertificate) { config.ApplicationUri = Utils.GetApplicationUriFromCertificate(config.SecurityConfiguration.ApplicationCertificate.Certificate); if (config.SecurityConfiguration.AutoAcceptUntrustedCertificates) { _autoAccept = true; } config.CertificateValidator.CertificateValidation += new CertificateValidationEventHandler(CertificateValidator_CertificateValidation); } else { Console.WriteLine(" WARN: missing application certificate, using unsecure connection."); } Console.WriteLine("2 - Discover endpoints of {0}.", _endpointURL); ExitCode = ExitCode.ErrorDiscoverEndpoints; var selectedEndpoint = CoreClientUtils.SelectEndpoint(_endpointURL, haveAppCertificate, 15000); Console.WriteLine(" Selected endpoint uses: {0}", selectedEndpoint.SecurityPolicyUri.Substring(selectedEndpoint.SecurityPolicyUri.LastIndexOf('#') + 1)); Console.WriteLine("3 - Create a session with OPC UA server."); ExitCode = ExitCode.ErrorCreateSession; var endpointConfiguration = EndpointConfiguration.Create(config); var endpoint = new ConfiguredEndpoint(null, selectedEndpoint, endpointConfiguration); _session = await Session.Create(config, endpoint, false, "OPC UA Console Client", 60000, new UserIdentity(new AnonymousIdentityToken()), null); // register keep alive handler _session.KeepAlive += Client_KeepAlive; Console.WriteLine("4 - Browse for all custom type variables."); ExitCode = ExitCode.ErrorReadComplexTypes; Stopwatch stopWatch = new Stopwatch(); stopWatch.Start(); var allVariableNodes = BrowseAllVariables(); var allCustomTypeVariables = allVariableNodes.Where(n => ((VariableNode)n).DataType == DataTypeIds.Structure).ToList(); allCustomTypeVariables.AddRange(allVariableNodes.Where(n => ((VariableNode)n).DataType.NamespaceIndex != 0).ToList()); stopWatch.Stop(); Console.WriteLine($" -- Browse all nodes took {stopWatch.ElapsedMilliseconds}ms."); Console.WriteLine($" -- Browsed {allVariableNodes.Count} nodes, from which {allCustomTypeVariables.Count} are custom type variables."); if (LoadTypeSystem) { Console.WriteLine("5 - Load the server type dictionary."); ExitCode = ExitCode.ErrorLoadTypeDictionary; stopWatch.Reset(); stopWatch.Start(); var complexTypeSystem = new ComplexTypeSystem(_session); await complexTypeSystem.Load(); stopWatch.Stop(); Console.WriteLine($"Load type system took {stopWatch.ElapsedMilliseconds}ms."); Console.WriteLine($"Custom types defined for this session:"); foreach (var type in complexTypeSystem.GetDefinedTypes()) { Console.WriteLine($"{type.Namespace}.{type.Name}"); } Console.WriteLine($"Loaded {_session.DataTypeSystem.Count} dictionaries:"); foreach (var dictionary in _session.DataTypeSystem) { Console.WriteLine($" + {dictionary.Value.Name}"); foreach (var type in dictionary.Value.DataTypes) { Console.WriteLine($" -- {type.Key}:{type.Value}"); } } } else { Console.WriteLine("4 - Not loading the server type dictionary."); } foreach (VariableNode variableNode in allCustomTypeVariables) { try { var value = _session.ReadValue(variableNode.NodeId); CastInt32ToEnum(variableNode, value); Console.WriteLine($" -- {variableNode}:{value}"); var extensionObject = value.Value as ExtensionObject; if (extensionObject != null) { var complexType = extensionObject.Body as BaseComplexType; if (complexType != null) { foreach (var item in complexType.GetPropertyEnumerator()) { if (Verbose) { Console.WriteLine($" -- -- {item.Name}:{complexType[item.Name]}"); } if (WriteComplexInt && item.PropertyType == typeof(Int32)) { var data = complexType[item.Name]; if (data != null) { complexType[item.Name] = (Int32)data + 1; } Console.WriteLine($" -- -- Write: {item.Name}, {complexType[item.Name]}"); WriteValue(_session, variableNode.NodeId, value); } } } } if (PrintAsJson) { PrintValueAsJson(variableNode.BrowseName.Name, value); } } catch (ServiceResultException sre) { if (sre.StatusCode == StatusCodes.BadUserAccessDenied) { Console.WriteLine($" -- {variableNode}: Access denied!"); } } } Console.WriteLine("6 - Create a subscription with publishing interval of 1 second."); ExitCode = ExitCode.ErrorCreateSubscription; var subscription = new Subscription(_session.DefaultSubscription) { PublishingInterval = 1000 }; Console.WriteLine("7 - Add all custom values and the server time to the subscription."); ExitCode = ExitCode.ErrorMonitoredItem; var list = new List <MonitoredItem> { new MonitoredItem(subscription.DefaultItem) { DisplayName = "ServerStatusCurrentTime", StartNodeId = "i=" + Variables.Server_ServerStatus_CurrentTime.ToString() } }; list.ForEach(i => i.Notification += OnNotification); foreach (var customVariable in allCustomTypeVariables) { var newItem = new MonitoredItem(subscription.DefaultItem) { DisplayName = customVariable.DisplayName.Text, StartNodeId = ExpandedNodeId.ToNodeId(customVariable.NodeId, _session.NamespaceUris) }; newItem.Notification += OnComplexTypeNotification; list.Add(newItem); } subscription.AddItems(list); Console.WriteLine("8 - Add the subscription to the session."); ExitCode = ExitCode.ErrorAddSubscription; _session.AddSubscription(subscription); subscription.Create(); Console.WriteLine("9 - Running...Press Ctrl-C to exit..."); ExitCode = ExitCode.ErrorRunning; return(_session); }
/// <summary> /// Connects to the OPC server asynchronously. /// </summary> public async Task <bool> ConnectAsync(ConnectionOptions connectionOptions, int operationTimeout = -1) { AutoAccept = false; OpcSession = null; ApplicationInstance application = new ApplicationInstance { ApplicationName = string.Format("KpOpcUa_{0} Driver", kpNumStr), ApplicationType = ApplicationType.Client, ConfigSectionName = "Scada.Comm.Devices.KpOpcUa" }; // load the application configuration WriteConfigFile(out string configFileName); ApplicationConfiguration config = await application.LoadApplicationConfiguration(configFileName, false); // check the application certificate bool haveAppCertificate = await application.CheckApplicationInstanceCertificate(false, 0); if (!haveAppCertificate) { throw new ScadaException(Localization.UseRussian ? "Сертификат экземпляра приложения недействителен!" : "Application instance certificate invalid!"); } if (haveAppCertificate) { config.ApplicationUri = Opc.Ua.Utils.GetApplicationUriFromCertificate( config.SecurityConfiguration.ApplicationCertificate.Certificate); if (config.SecurityConfiguration.AutoAcceptUntrustedCertificates) { AutoAccept = true; } if (CertificateValidation != null) { config.CertificateValidator.CertificateValidation += CertificateValidation; } } else { WriteToLog(Localization.UseRussian ? "Предупреждение: отсутствует сертификат приложения, используется незащищенное соединение." : "Warning: missing application certificate, using unsecure connection."); } // create session EndpointDescription selectedEndpoint = CoreClientUtils.SelectEndpoint( connectionOptions.ServerUrl, haveAppCertificate, operationTimeout); selectedEndpoint.SecurityMode = connectionOptions.SecurityMode; selectedEndpoint.SecurityPolicyUri = connectionOptions.GetSecurityPolicy(); EndpointConfiguration endpointConfiguration = EndpointConfiguration.Create(config); ConfiguredEndpoint endpoint = new ConfiguredEndpoint(null, selectedEndpoint, endpointConfiguration); UserIdentity userIdentity = connectionOptions.AuthenticationMode == AuthenticationMode.Username ? new UserIdentity(connectionOptions.Username, connectionOptions.Password) : new UserIdentity(new AnonymousIdentityToken()); OpcSession = await Session.Create(config, endpoint, false, "Rapid SCADA KpOpcUa_" + kpNumStr, (uint)config.ClientConfiguration.DefaultSessionTimeout, userIdentity, null); WriteToLog(string.Format(Localization.UseRussian ? "OPC сессия успешно создана: {0}" : "OPC session created successfully: {0}", connectionOptions.ServerUrl)); return(true); }
#pragma warning disable CS1998 // Async method lacks 'await' operators and will run synchronously public async Task <OpcObject> ConnectAsync() #pragma warning restore CS1998 // Async method lacks 'await' operators and will run synchronously { if (string.IsNullOrEmpty(this.Url)) { return(new OpcObject()); } Console.WriteLine("Step 1 - Create application configuration and certificate."); var config = new ApplicationConfiguration() { ApplicationName = "MyHomework", ApplicationUri = Utils.Format(@"urn:{0}:MyHomework", System.Net.Dns.GetHostName()), ApplicationType = ApplicationType.Client, SecurityConfiguration = new SecurityConfiguration { ApplicationCertificate = new CertificateIdentifier { StoreType = @"Directory", StorePath = @"%CommonApplicationData%\OPC Foundation\CertificateStores\MachineDefault", SubjectName = "MyHomework" }, TrustedIssuerCertificates = new CertificateTrustList { StoreType = @"Directory", StorePath = @"%CommonApplicationData%\OPC Foundation\CertificateStores\UA Certificate Authorities" }, TrustedPeerCertificates = new CertificateTrustList { StoreType = @"Directory", StorePath = @"%CommonApplicationData%\OPC Foundation\CertificateStores\UA Applications" }, RejectedCertificateStore = new CertificateTrustList { StoreType = @"Directory", StorePath = @"%CommonApplicationData%\OPC Foundation\CertificateStores\RejectedCertificates" }, AutoAcceptUntrustedCertificates = true }, TransportConfigurations = new TransportConfigurationCollection(), TransportQuotas = new TransportQuotas { OperationTimeout = 15000 }, ClientConfiguration = new ClientConfiguration { DefaultSessionTimeout = 60000 }, TraceConfiguration = new TraceConfiguration() }; config.Validate(ApplicationType.Client).GetAwaiter().GetResult(); if (config.SecurityConfiguration.AutoAcceptUntrustedCertificates) { config.CertificateValidator.CertificateValidation += (s, e) => { e.Accept = (e.Error.StatusCode == StatusCodes.BadCertificateUntrusted); }; } var application = new ApplicationInstance { ApplicationName = "MyHomework", ApplicationType = ApplicationType.Client, ApplicationConfiguration = config }; application.CheckApplicationInstanceCertificate(false, 2048).GetAwaiter().GetResult(); //var selectedEndpoint = CoreClientUtils.SelectEndpoint("opc.tcp://" + Dns.GetHostName() + ":48010", useSecurity: true/* , operationTimeout: 15000 */); var selectedEndpoint = CoreClientUtils.SelectEndpoint(this.Url, false); Console.WriteLine($"Step 2 - Create a session with your server: {selectedEndpoint.EndpointUrl} "); this.session = Session.Create(config, new ConfiguredEndpoint(null, selectedEndpoint, EndpointConfiguration.Create(config)), false, "", 60000, null, null).GetAwaiter().GetResult(); return(null); }
public static void create_server() { var selectedEndpoint = CoreClientUtils.SelectEndpoint("opc.tcp://" + "127.0.0.1" + ":" + "4840" + "", useSecurity: false); session = Session.Create(config, new ConfiguredEndpoint(null, selectedEndpoint, EndpointConfiguration.Create(config)), false, "", 60000, null, null).GetAwaiter().GetResult(); }
/// <summary> /// Creates a session with the endpoint. /// </summary> /// public async void OPCConnect(ApplicationInstance application, ConfiguredEndpoint endpoint) { if (endpoint == null) { return; } // load the application configuration. ApplicationConfiguration config = await application.LoadApplicationConfiguration(false); // check the application certificate. bool haveAppCertificate = await application.CheckApplicationInstanceCertificate(false, 0); if (!haveAppCertificate) { throw new Exception("Application instance certificate invalid!"); } else if (haveAppCertificate) { config.ApplicationUri = Utils.GetApplicationUriFromCertificate(config.SecurityConfiguration.ApplicationCertificate.Certificate); if (config.SecurityConfiguration.AutoAcceptUntrustedCertificates) { autoAccept = true; } config.CertificateValidator.CertificateValidation += new CertificateValidationEventHandler(CertificateValidator_CertificateValidation); } //Checks if endpoint URL selected is same as retained endpoint URL string endpointURL = endpoint.EndpointUrl.ToString(); string retainedEndpoint = null; bool retainSession = false; retainedEndpoint = await LoadSessionAsync(endpointURL); try { if (retainedEndpoint == null || !retainSession) { selectedEndpoint = CoreClientUtils.SelectEndpoint(endpointURL, haveAppCertificate, 15000); } else { selectedEndpoint = CoreClientUtils.SelectEndpoint(retainedEndpoint, haveAppCertificate, 15000); } //Select endpoint after discovery. //Creates session with OPC Server sessionEndpoint = selectedEndpoint.EndpointUrl; m_endpoint_configuration = EndpointConfiguration.Create(config); m_endpoint = new ConfiguredEndpoint(null, selectedEndpoint, m_endpoint_configuration); m_session = await Session.Create(config, m_endpoint, false, "OpcEdgeClient", 60000, new UserIdentity(new AnonymousIdentityToken()), null); // Open dialog to declare Session name. if (new SessionOpenDlg().ShowDialog(m_session, opcSession.PreferredLocales) == false) { return; } // Deletes the existing session. opcSession.Close(); // Adds session to tree. opcSession.AddNode(m_session); //Checks if service has a session connected and disconnects if connected. if (client.CheckConnected()) { client.OPCDisconnect(); } // Passes endpointURL to service for connection. client.OPCConnect(selectedEndpoint.EndpointUrl); if (m_session != null) { // stop any reconnect operation. if (m_reconnectHandler != null) { m_reconnectHandler.Dispose(); m_reconnectHandler = null; } //Register keep alive handler & sets view m_session.KeepAlive += new KeepAliveEventHandler(StandardClient_KeepAlive); opcBrowse.SetView(m_session, BrowseViewType.Objects, null); StandardClient_KeepAlive(m_session, null); //Saves session endpoint URL. m_session.SessionName = "My Session"; await SaveSessionAsync(m_session); //Recreates prior session's subscriptions and monitored items. if (retainedEndpoint == endpointURL) { RecreateSession(m_session); } } OpcConnectionLabel.Text = "Currently Connected to: " + selectedEndpoint.EndpointUrl; } catch (Exception ex) { // Log the exception. MessageBox.Show(ex.Message); } }
//Initializes OPC Application instance. public async void InitializeClients() { //Creates directory for retained information in case it was deleted somehow. createDirectories(); //Initialize OPC Application Instance application = new ApplicationInstance { ApplicationName = "MQTT-OPC Broker", ApplicationType = ApplicationType.ClientAndServer, ConfigSectionName = "Opc.Ua.SampleClient" }; // load the application configuration. application.LoadApplicationConfiguration(false).Wait(); // check the application certificate. application.CheckApplicationInstanceCertificate(false, 0).Wait(); m_configuration = app_configuration = application.ApplicationConfiguration; // get list of cached endpoints. m_endpoints = m_configuration.LoadCachedEndpoints(true); m_endpoints.DiscoveryUrls = app_configuration.ClientConfiguration.WellKnownDiscoveryUrls; if (!app_configuration.SecurityConfiguration.AutoAcceptUntrustedCertificates) { app_configuration.CertificateValidator.CertificateValidation += new CertificateValidationEventHandler(CertificateValidator_CertificateValidation); } sessionEndpoint = client.SessionEndpoint(); //If service is currently connected to a OPC endpoint, recreate the connection on the client. if (sessionEndpoint != null) { sessionEndpoint = Regex.Replace(sessionEndpoint, "\\\\|\"", ""); // load the application configuration. ApplicationConfiguration config = await application.LoadApplicationConfiguration(false); // check the application certificate. bool haveAppCertificate = await application.CheckApplicationInstanceCertificate(false, 0); if (!haveAppCertificate) { throw new Exception("Application instance certificate invalid!"); } else if (haveAppCertificate) { config.ApplicationUri = Utils.GetApplicationUriFromCertificate(config.SecurityConfiguration.ApplicationCertificate.Certificate); if (config.SecurityConfiguration.AutoAcceptUntrustedCertificates) { autoAccept = true; } config.CertificateValidator.CertificateValidation += new CertificateValidationEventHandler(CertificateValidator_CertificateValidation); } try { //Creates session with OPC Server selectedEndpoint = CoreClientUtils.SelectEndpoint(sessionEndpoint, haveAppCertificate, 15000); m_endpoint_configuration = EndpointConfiguration.Create(config); m_endpoint = new ConfiguredEndpoint(null, selectedEndpoint, m_endpoint_configuration); m_session = await Session.Create(config, m_endpoint, false, "OpcEdgeClient", 60000, new UserIdentity(new AnonymousIdentityToken()), null); // Open dialog to declare Session name. //new SessionOpenDlg().ShowDialog(m_session, opcSession.PreferredLocales); // Deletes the existing session. opcSession.Close(); // Adds session to tree. opcSession.AddNode(m_session); //Checks if service has a session connected and disconnects if connected. if (client.CheckConnected()) { client.OPCDisconnect(); } // Passes endpointURL to service for connection. client.OPCConnect(selectedEndpoint.EndpointUrl); if (m_session != null) { // stop any reconnect operation. if (m_reconnectHandler != null) { m_reconnectHandler.Dispose(); m_reconnectHandler = null; } //Register keep alive handler & sets view m_session.KeepAlive += new KeepAliveEventHandler(StandardClient_KeepAlive); opcBrowse.SetView(m_session, BrowseViewType.Objects, null); StandardClient_KeepAlive(m_session, null); //Saves session endpoint URL. m_session.SessionName = "My Session"; await SaveSessionAsync(m_session); //Recreates prior session's subscriptions and monitored items. string retainedEndpoint = await LoadSessionAsync(selectedEndpoint.EndpointUrl); if (sessionEndpoint == retainedEndpoint) { RecreateSession(m_session); } } OpcConnectionLabel.Text = "Currently Connected to: " + selectedEndpoint.EndpointUrl; } catch (Exception ex) { // Log the exception. MessageBox.Show(ex.Message); } } }
public void opcUaServerInit() { string storePath = AppContext.BaseDirectory; var config = new ApplicationConfiguration() { ApplicationName = "Axiu-Opcua", ApplicationUri = Utils.Format(@"urn:{0}:Axiu-Opcua", System.Net.Dns.GetHostName()), ApplicationType = ApplicationType.Client, SecurityConfiguration = new SecurityConfiguration { ApplicationCertificate = new CertificateIdentifier { StoreType = @"Directory", StorePath = Path.Combine(storePath, @"OPC Foundation/CertificateStores/MachineDefault"), SubjectName = Utils.Format(@"CN={0}, DC={1}", "Axiu-Opcua", System.Net.Dns.GetHostName()) }, TrustedIssuerCertificates = new CertificateTrustList { StoreType = @"Directory", StorePath = Path.Combine(storePath, @"OPC Foundation/CertificateStores/UA Certificate Authorities") }, TrustedPeerCertificates = new CertificateTrustList { StoreType = @"Directory", StorePath = Path.Combine(storePath, @"OPC Foundation/CertificateStores/UA Applications") }, RejectedCertificateStore = new CertificateTrustList { StoreType = @"Directory", StorePath = Path.Combine(storePath, @"OPC Foundation/CertificateStores/RejectedCertificates") }, AutoAcceptUntrustedCertificates = true, AddAppCertToTrustedStore = true }, TransportConfigurations = new TransportConfigurationCollection(), TransportQuotas = new TransportQuotas { OperationTimeout = 15000 }, ClientConfiguration = new ClientConfiguration { DefaultSessionTimeout = 60000 }, TraceConfiguration = new TraceConfiguration() }; config.Validate(ApplicationType.Client).GetAwaiter().GetResult(); if (config.SecurityConfiguration.AutoAcceptUntrustedCertificates) { config.CertificateValidator.CertificateValidation += (s, e) => { e.Accept = (e.Error.StatusCode == StatusCodes.BadCertificateUntrusted); }; } var application = new ApplicationInstance { ApplicationName = "Axiu-Opcua", ApplicationType = ApplicationType.Client, ApplicationConfiguration = config }; application.CheckApplicationInstanceCertificate(false, 2048).GetAwaiter().GetResult(); var selectedEndpoint = CoreClientUtils.SelectEndpoint(url, useSecurity: true, int.MaxValue); Console.WriteLine("配置已准备完毕,即将打开链接会话..."); _session = Session.Create(config, new ConfiguredEndpoint(null, selectedEndpoint, EndpointConfiguration.Create(config)), false, "", int.MaxValue, null, null).GetAwaiter().GetResult(); // ReadNodeList("ns=3;s=\"上位通讯\""); // AddSubscrip(null); Console.WriteLine("完成链接会话..."); SubscribeToDataChanges(); }
private void Init() { try { ApplicationInstance application = new ApplicationInstance { ApplicationName = ClientName, ApplicationType = ApplicationType.Client, ConfigSectionName = string.Empty }; var config = new ApplicationConfiguration() { ApplicationName = ClientName, ApplicationUri = $"urn:localhost:{ClientName}", //"urn:localhost:OPCFoundation:CoreSampleClient", $"urn:localhost:{ClientName}", ApplicationType = ApplicationType.Client, ProductUri = "http://opcfoundation.org/UA/CoreSampleClient", SecurityConfiguration = new SecurityConfiguration { ApplicationCertificate = new CertificateIdentifier { StoreType = @"Directory", StorePath = @"%LocalApplicationData%\OPC Foundation\CertificateStores\MachineDefault", SubjectName = Utils.Format(@"CN={0}, DC={1}", ClientName, "localhost") }, //System.Net.Dns.GetHostName()) }, TrustedIssuerCertificates = new CertificateTrustList { StoreType = @"Directory", StorePath = @"%LocalApplicationData%/OPC Foundation/pki/issuer" }, TrustedPeerCertificates = new CertificateTrustList { StoreType = @"Directory", StorePath = @"%LocalApplicationData%/OPC Foundation/pki/trusted" }, RejectedCertificateStore = new CertificateTrustList { StoreType = @"Directory", StorePath = @"%LocalApplicationData%/OPC Foundation/pki/rejected" }, AutoAcceptUntrustedCertificates = true, RejectSHA1SignedCertificates = false, MinimumCertificateKeySize = 512 }, TransportConfigurations = new TransportConfigurationCollection(), TransportQuotas = new TransportQuotas { OperationTimeout = 15000, MaxStringLength = 1048576, MaxByteStringLength = 4194304, MaxBufferSize = 65535, ChannelLifetime = 300000, SecurityTokenLifetime = 3600000 }, ClientConfiguration = new ClientConfiguration { DefaultSessionTimeout = 60000, WellKnownDiscoveryUrls = new StringCollection(new List <string> { "opc.tcp://{0}:4840/UADiscovery" }), DiscoveryServers = new EndpointDescriptionCollection(), MinSubscriptionLifetime = 10000 }, TraceConfiguration = new TraceConfiguration() { OutputFilePath = @"%LocalApplicationData%/Logs/Opc.Ua.CoreSampleClient.log.txt", DeleteOnLoad = true }, CertificateValidator = new CertificateValidator(), }; application.ApplicationConfiguration = ApplicationInstance.FixupAppConfig(config); config.Validate(ApplicationType.Client); // check the application certificate. bool haveAppCertificate = application.CheckApplicationInstanceCertificate(false, 0).Result; if (!haveAppCertificate) { throw new Exception("Application instance certificate invalid!"); } if (haveAppCertificate) { config.ApplicationUri = Utils.GetApplicationUriFromCertificate(config.SecurityConfiguration.ApplicationCertificate.Certificate); config.SecurityConfiguration.AutoAcceptUntrustedCertificates = true; config.SecurityConfiguration.RejectSHA1SignedCertificates = false; //config.SecurityConfiguration.MinimumCertificateKeySize = 1024; config.CertificateValidator.CertificateValidation += CertificateValidator_CertificateValidation; } var securityEnabled = true; if (string.IsNullOrWhiteSpace(_OPC_User) && string.IsNullOrWhiteSpace(_OPC_Password)) { securityEnabled = false; } EndpointDescription selectedEndpoint; if (SecurityPolicy.HasValue && MessageSecurity.HasValue) { selectedEndpoint = OPCCoreUtils.SelectEndpointBySecurity(Address, SecurityPolicy.Value, MessageSecurity.Value, 15000); } else { selectedEndpoint = CoreClientUtils.SelectEndpoint(Address, useSecurity: securityEnabled, operationTimeout: 15000); } Logger?.LogDebug($"Endpoint selected: {selectedEndpoint.SecurityPolicyUri} {selectedEndpoint.SecurityMode}"); // log the security mode used var endpointConfiguration = EndpointConfiguration.Create(config); var endpoint = new ConfiguredEndpoint(null, selectedEndpoint, endpointConfiguration); // set the port (avoid splitting strings) Port = endpoint.EndpointUrl.Port; UserIdentity UI; if (securityEnabled) { UI = new UserIdentity(OPC_User, OPC_Password); } else { UI = new UserIdentity(new AnonymousIdentityToken()); } // N.B. do NOT lower the sessionTimeout when creating ClientSession ClientSession = Session.Create(config, endpoint, false, $"{ClientName}", 10000, UI, null).Result; // register Event handlers ClientSession.KeepAlive += Client_KeepAlive; ClientSession.Notification += NotificationEventHandler; ClientSession.SubscriptionsChanged += SubscriptionChangedHandler; ClientSession.PublishError += PublishErrorEventHandler; ClientSession.RenewUserIdentity += RenewUserIdentityEventHandler; ClientSession.SessionClosing += SessionClosingHandler; IsAvailable = true; } catch (Exception ex) { Logger?.LogDebug($"OPC - Client Initilization error. Ex: {ex.Message} - Type: {ex.InnerException?.Message}"); IsAvailable = false; } }
//ns=2;s=Scalar_CreateTime public void Execte() { string storePath = AppContext.BaseDirectory; var config = new ApplicationConfiguration() { ApplicationName = "Axiu-Opcua", ApplicationUri = Utils.Format(@"urn:{0}:Axiu-Opcua", System.Net.Dns.GetHostName()), ApplicationType = ApplicationType.Client, SecurityConfiguration = new SecurityConfiguration { ApplicationCertificate = new CertificateIdentifier { StoreType = @"Directory", StorePath = Path.Combine(storePath, @"OPC Foundation/CertificateStores/MachineDefault"), SubjectName = Utils.Format(@"CN={0}, DC={1}", "Axiu-Opcua", System.Net.Dns.GetHostName()) }, TrustedIssuerCertificates = new CertificateTrustList { StoreType = @"Directory", StorePath = Path.Combine(storePath, @"OPC Foundation/CertificateStores/UA Certificate Authorities") }, TrustedPeerCertificates = new CertificateTrustList { StoreType = @"Directory", StorePath = Path.Combine(storePath, @"OPC Foundation/CertificateStores/UA Applications") }, RejectedCertificateStore = new CertificateTrustList { StoreType = @"Directory", StorePath = Path.Combine(storePath, @"OPC Foundation/CertificateStores/RejectedCertificates") }, AutoAcceptUntrustedCertificates = true, AddAppCertToTrustedStore = true }, TransportConfigurations = new TransportConfigurationCollection(), TransportQuotas = new TransportQuotas { OperationTimeout = 15000 }, ClientConfiguration = new ClientConfiguration { DefaultSessionTimeout = 60000 }, TraceConfiguration = new TraceConfiguration() }; config.Validate(ApplicationType.Client).GetAwaiter().GetResult(); if (config.SecurityConfiguration.AutoAcceptUntrustedCertificates) { config.CertificateValidator.CertificateValidation += (s, e) => { e.Accept = (e.Error.StatusCode == StatusCodes.BadCertificateUntrusted); }; } var application = new ApplicationInstance { ApplicationName = "Axiu-Opcua", ApplicationType = ApplicationType.Client, ApplicationConfiguration = config }; application.CheckApplicationInstanceCertificate(false, 2048).GetAwaiter().GetResult(); var selectedEndpoint = CoreClientUtils.SelectEndpoint(url, useSecurity: true, int.MaxValue); Console.WriteLine("配置已准备完毕,即将打开链接会话..."); using (var session = Session.Create(config, new ConfiguredEndpoint(null, selectedEndpoint, EndpointConfiguration.Create(config)), false, "", int.MaxValue, null, null).GetAwaiter().GetResult()) { #region 读取目录下所有节点 //读取目录下所有节点 List <string> idList = new List <string>(); ReferenceDescriptionCollection nextRefs; byte[] nextCp; ////session.Browse(null, null, "ns=2;s=1_6_20", 0u, BrowseDirection.Forward, ReferenceTypeIds.HierarchicalReferences, true, (uint)NodeClass.Variable | (uint)NodeClass.Object | (uint)NodeClass.Method, out nextCp, out nextRefs); ////foreach (var nextRd in nextRefs) ////{ //// //Console.WriteLine("{0}: {1}, {2}", nextRd.DisplayName, nextRd.BrowseName, nextRd.NodeClass); //// idList.Add(nextRd.NodeId.ToString()); ////} Console.Write("请输入监听通道ID:"); string devStr = Console.ReadLine(); if (string.IsNullOrEmpty(devStr)) { return; } List <string> folders = new List <string>(); string nodeId = "ns=2;s=1_" + devStr; session.Browse(null, null, nodeId, 0u, BrowseDirection.Forward, ReferenceTypeIds.HierarchicalReferences, true, (uint)NodeClass.Variable | (uint)NodeClass.Object | (uint)NodeClass.Method, out nextCp, out nextRefs); foreach (var nextRd in nextRefs) { //Console.WriteLine("{0}: {1}, {2}", nextRd.DisplayName, nextRd.BrowseName, nextRd.NodeClass); folders.Add(nextRd.NodeId.ToString()); } List <string> nodes = new List <string>(); foreach (var item in folders) { session.Browse(null, null, item, 0u, BrowseDirection.Forward, ReferenceTypeIds.HierarchicalReferences, true, (uint)NodeClass.Variable | (uint)NodeClass.Object | (uint)NodeClass.Method, out nextCp, out nextRefs); foreach (var nextRd in nextRefs) { //Console.WriteLine("{0}: {1}, {2}", nextRd.DisplayName, nextRd.BrowseName, nextRd.NodeClass); nodes.Add(nextRd.NodeId.ToString()); } } Console.WriteLine("通道总节点数:" + nodes.Count + "; 第一个:" + nodes[0]); #endregion #region 读单个节点 //读单个节点 //ReadValueIdCollection nodesToRead = new ReadValueIdCollection //{ // new ReadValueId( ) // { // NodeId = "ns=2;s=0_0_0_1_7", // AttributeId = Attributes.Value // } //}; //// read the current value //session.Read(null, 0, TimestampsToReturn.Neither, nodesToRead, out DataValueCollection results, out DiagnosticInfoCollection diagnosticInfos); //ClientBase.ValidateResponse(results, nodesToRead); //ClientBase.ValidateDiagnosticInfos(diagnosticInfos, nodesToRead); //Console.WriteLine("取到单值结果: " + results[0].ToString()); #endregion #region 读取历史数据 //读取历史数据 //HistoryReadValueIdCollection historyReads = new HistoryReadValueIdCollection() //{ // new HistoryReadValueId( ) // { // NodeId = "ns=2;s=0_0_0_1_7" // } //}; //ExtensionObject extension = new ExtensionObject(); //ReadProcessedDetails details = new ReadProcessedDetails() { StartTime = DateTime.Now.AddMinutes(-5), EndTime = DateTime.Now }; //extension.Body = details; //session.HistoryRead(null, extension, TimestampsToReturn.Neither, true, historyReads, out HistoryReadResultCollection hresults, out DiagnosticInfoCollection hdiagnosticInfos); //foreach (var item in hresults) //{ // var res = item.HistoryData.Body as Opc.Ua.KeyValuePair; // Console.WriteLine("历史数据:" + res.Key.Name + " --- " + res.Value); //} #endregion #region 读取历史事件 //HistoryReadValueIdCollection historyEvents = new HistoryReadValueIdCollection() //{ // new HistoryReadValueId( ) // { // NodeId = "ns=2;s=1_1_1" // } //}; //EventFilter hFilter = new EventFilter(); //hFilter.AddSelectClause(ObjectTypeIds.BaseEventType, new QualifiedName("id=0101")); //ExtensionObject extension2 = new ExtensionObject(); //ReadEventDetails details2 = new ReadEventDetails() { StartTime = DateTime.Now.AddDays(-1), EndTime = DateTime.Now, Filter = hFilter }; //extension2.Body = details2; //session.HistoryRead(null, extension2, TimestampsToReturn.Neither, false, historyEvents, out HistoryReadResultCollection hresults2, out DiagnosticInfoCollection hdiagnosticInfos2); //foreach (var item in hresults2) //{ // if (item.HistoryData.Body!=null) // { // var res = item.HistoryData.Body as byte[]; // Console.WriteLine(Encoding.UTF8.GetString(res)); // } //} #endregion #region 订阅事件 var subscription = new Subscription(session.DefaultSubscription) { PublishingInterval = 3000 }; EventFilter eventFilter = new EventFilter(); eventFilter.AddSelectClause(ObjectTypeIds.BaseEventType, new QualifiedName(BrowseNames.Message)); List <MonitoredItem> list = new List <MonitoredItem>(); foreach (var item in folders) { MonitoredItem model = new MonitoredItem(subscription.DefaultItem) { DisplayName = item + "的事件", StartNodeId = item, Filter = eventFilter, AttributeId = 12 }; model.Notification += OnEventNotification; list.Add(model); break; } subscription.AddItems(list); bool radd = session.AddSubscription(subscription); subscription.Create(); #endregion #region 订阅测点 Console.WriteLine("即将开始订阅固定节点消息..."); //var submeas = new Subscription(session.DefaultSubscription) { PublishingInterval = 1000 }; //List<MonitoredItem> measlist = new List<MonitoredItem>(); //int index = 0, jcount = 0; //foreach (var item in nodes) //{ // index++; jcount++; // MonitoredItem monitor = new MonitoredItem(submeas.DefaultItem) { DisplayName = "测点:" + item, StartNodeId = item }; // monitor.Notification += OnNotification; // measlist.Add(monitor); // if (index > 5999) // { // submeas.AddItems(measlist); // session.AddSubscription(submeas); // submeas.Create(); // index = 0; // submeas = new Subscription(session.DefaultSubscription) { PublishingInterval = 1000 }; // measlist.Clear(); // } //} //if (measlist.Count > 0) //{ // submeas.AddItems(measlist); // session.AddSubscription(submeas); // submeas.Create(); //} //Console.WriteLine("订阅节点数:" + jcount); //var subscription = new Subscription(session.DefaultSubscription) { PublishingInterval = 1000 }; //List<MonitoredItem> list = new List<MonitoredItem>(); //foreach (var item in nodes.Take(5000)) //{ // MonitoredItem monitor = new MonitoredItem(subscription.DefaultItem) { DisplayName = "测点:" + item, StartNodeId = item }; // list.Add(monitor); //} //list.ForEach(i => i.Notification += OnNotification); //subscription.AddItems(list); //session.AddSubscription(subscription); //subscription.Create(); #endregion #region 写入内容 //WriteValueCollection writeValues = new WriteValueCollection() //{ // new WriteValue() // { // NodeId="ns=2;s=1_ctr_1", // AttributeId=Attributes.Value, // Value=new DataValue(){ Value="false" } // } //}; //session.Write(null, writeValues, out StatusCodeCollection wresults, out DiagnosticInfoCollection wdiagnosticInfos); //foreach (var item in wresults) //{ // Console.WriteLine("写入结果:" + item.ToString()); //} #endregion Console.WriteLine("指定节点消息已订阅,请勿关闭程序..."); while (true) { Thread.Sleep(3000); Console.WriteLine("测点更新次数:" + ntCount); ntCount = 0; } Console.ReadKey(true); //subscription.DeleteItems(); } Console.WriteLine("Press any key to exit..."); Console.ReadKey(true); }
private async Task <Session> ConsoleSampleClient() { Console.WriteLine("1 - Create an Application Configuration."); ExitCode = ExitCode.ErrorCreateApplication; ApplicationInstance application = new ApplicationInstance { ApplicationName = "UA Core Complex Client", ApplicationType = ApplicationType.Client, ConfigSectionName = "Opc.Ua.ComplexClient" }; // load the application configuration. ApplicationConfiguration config = await application.LoadApplicationConfiguration(false).ConfigureAwait(false); // check the application certificate. bool haveAppCertificate = await application.CheckApplicationInstanceCertificate(false, 0).ConfigureAwait(false); if (!haveAppCertificate) { throw new Exception("Application instance certificate invalid!"); } ReverseConnectManager reverseConnectManager = null; if (ReverseConnectUri != null) { // start the reverse connection manager reverseConnectManager = new ReverseConnectManager(); reverseConnectManager.AddEndpoint(ReverseConnectUri); reverseConnectManager.StartService(config); } if (haveAppCertificate) { config.ApplicationUri = Utils.GetApplicationUriFromCertificate(config.SecurityConfiguration.ApplicationCertificate.Certificate); if (config.SecurityConfiguration.AutoAcceptUntrustedCertificates) { m_autoAccept = true; } config.CertificateValidator.CertificateValidation += new CertificateValidationEventHandler(CertificateValidator_CertificateValidation); } else { Console.WriteLine(" WARN: missing application certificate, using unsecure connection."); } Console.WriteLine("2 - Discover endpoints of {0}.", m_endpointURL); ExitCode = ExitCode.ErrorDiscoverEndpoints; EndpointDescription selectedEndpoint; if (reverseConnectManager == null) { selectedEndpoint = CoreClientUtils.SelectEndpoint(m_endpointURL, haveAppCertificate, 15000); } else { Console.WriteLine(" Waiting for reverse connection."); ITransportWaitingConnection connection = await reverseConnectManager.WaitForConnection( new Uri(m_endpointURL), null, new CancellationTokenSource(60000).Token); if (connection == null) { throw new ServiceResultException(StatusCodes.BadTimeout, "Waiting for a reverse connection timed out."); } selectedEndpoint = CoreClientUtils.SelectEndpoint(config, connection, haveAppCertificate, 15000); } Console.WriteLine(" Selected endpoint uses: {0}", selectedEndpoint.SecurityPolicyUri.Substring(selectedEndpoint.SecurityPolicyUri.LastIndexOf('#') + 1)); Console.WriteLine("3 - Create a session with OPC UA server."); ExitCode = ExitCode.ErrorCreateSession; // create the user identity UserIdentity userIdentity; if (String.IsNullOrEmpty(Username) && String.IsNullOrEmpty(Password)) { userIdentity = new UserIdentity(new AnonymousIdentityToken()); } else { userIdentity = new UserIdentity(Username, Password); } // create worker session if (reverseConnectManager == null) { m_session = await CreateSession(config, selectedEndpoint, userIdentity).ConfigureAwait(false); } else { Console.WriteLine(" Waiting for reverse connection."); ITransportWaitingConnection connection = await reverseConnectManager.WaitForConnection( new Uri(m_endpointURL), null, new CancellationTokenSource(60000).Token); if (connection == null) { throw new ServiceResultException(StatusCodes.BadTimeout, "Waiting for a reverse connection timed out."); } m_session = await CreateSession(config, connection, selectedEndpoint, userIdentity).ConfigureAwait(false); } // register keep alive handler m_session.KeepAlive += Client_KeepAlive; Console.WriteLine("4 - Browse for all custom type variables."); ExitCode = ExitCode.ErrorReadComplexTypes; Stopwatch stopWatch = new Stopwatch(); stopWatch.Start(); var allVariableNodes = BrowseAdddressSpace ? BrowseAllVariables() : new List <INode>(); var allCustomTypeVariables = allVariableNodes.Where(n => ((VariableNode)n).DataType.NamespaceIndex != 0).ToList(); stopWatch.Stop(); Console.WriteLine($" -- Browse all nodes took {stopWatch.ElapsedMilliseconds}ms."); Console.WriteLine($" -- Browsed {allVariableNodes.Count} nodes, from which {allCustomTypeVariables.Count} are custom type variables."); stopWatch.Reset(); // for testing clear the nodecache m_session.NodeCache.Clear(); stopWatch.Start(); if (LoadTypeSystem) { Console.WriteLine("5 - Load the server type dictionary."); ExitCode = ExitCode.ErrorLoadTypeDictionary; stopWatch.Reset(); stopWatch.Start(); var complexTypeSystem = new ComplexTypeSystem(m_session); await complexTypeSystem.Load().ConfigureAwait(false); stopWatch.Stop(); Console.WriteLine($"Load type system took {stopWatch.ElapsedMilliseconds}ms."); Console.WriteLine($"Custom types defined for this session:"); foreach (var type in complexTypeSystem.GetDefinedTypes()) { Console.WriteLine($"{type.Namespace}.{type.Name}"); } Console.WriteLine($"Loaded {m_session.DataTypeSystem.Count} dictionaries:"); foreach (var dictionary in m_session.DataTypeSystem) { Console.WriteLine($" + {dictionary.Value.Name}"); foreach (var type in dictionary.Value.DataTypes) { Console.WriteLine($" -- {type.Key}:{type.Value}"); } } } else { Console.WriteLine("4 - Not loading the server type dictionary."); } foreach (VariableNode variableNode in allCustomTypeVariables) { try { var value = m_session.ReadValue(variableNode.NodeId); CastInt32ToEnum(variableNode, value); Console.WriteLine($" -- {variableNode}:{value}"); if (value.Value is ExtensionObject extensionObject) { if (extensionObject.Body is BaseComplexType complexType) { foreach (var item in complexType.GetPropertyEnumerator()) { if (Verbose) { Console.WriteLine($" -- -- {item.Name}:{complexType[item.Name]}"); } if (WriteComplexInt && item.PropertyType == typeof(Int32)) { var data = complexType[item.Name]; if (data != null) { complexType[item.Name] = (Int32)data + 1; } Console.WriteLine($" -- -- Increment: {item.Name}, {complexType[item.Name]}"); WriteValue(m_session, variableNode.NodeId, value); } } } } if (PrintAsJson) { PrintValueAsJson(variableNode.BrowseName.Name, value); } } catch (ServiceResultException sre) { if (sre.StatusCode == StatusCodes.BadUserAccessDenied) { Console.WriteLine($" -- {variableNode}: Access denied!"); } } } Console.WriteLine("6 - Create test sessions which load only single types as needed."); if (LoadTypeSystem) { foreach (VariableNode variableNode in allCustomTypeVariables) { Session testSession = null; try { Console.WriteLine($"Open session for {variableNode}:"); testSession = await CreateSession(config, selectedEndpoint, userIdentity).ConfigureAwait(false); var complexTypeSystem = new ComplexTypeSystem(testSession); NodeId dataType = variableNode.DataType; Type nullType = testSession.Factory.GetSystemType(dataType); var valueBefore = testSession.ReadValue(variableNode.NodeId); Console.WriteLine($" -- {valueBefore}"); Type systemType = await complexTypeSystem.LoadType(dataType).ConfigureAwait(false); var valueAfter = testSession.ReadValue(variableNode.NodeId); Console.WriteLine($" -- {variableNode}: {systemType} {dataType}"); Console.WriteLine($" -- {valueAfter}"); Console.WriteLine($"Custom types defined for {variableNode}:"); foreach (var type in complexTypeSystem.GetDefinedTypes()) { Console.WriteLine($" -- {type.Namespace}.{type.Name}"); } } catch (ServiceResultException sre) { if (sre.StatusCode == StatusCodes.BadUserAccessDenied) { Console.WriteLine($" -- {variableNode}: Access denied!"); } } finally { testSession?.Close(); } } } else { Console.WriteLine("6 - Not testing to load individual types."); } Console.WriteLine("7 - Create a subscription with publishing interval of 1 second."); ExitCode = ExitCode.ErrorCreateSubscription; var subscription = new Subscription(m_session.DefaultSubscription) { PublishingInterval = 1000 }; Console.WriteLine("8 - Add all custom values and the server time to the subscription."); ExitCode = ExitCode.ErrorMonitoredItem; var list = new List <MonitoredItem> { new MonitoredItem(subscription.DefaultItem) { DisplayName = "ServerStatusCurrentTime", StartNodeId = "i=" + Variables.Server_ServerStatus_CurrentTime.ToString() } }; list.ForEach(i => i.Notification += OnNotification); foreach (var customVariable in allCustomTypeVariables) { var newItem = new MonitoredItem(subscription.DefaultItem) { DisplayName = customVariable.DisplayName.Text, StartNodeId = ExpandedNodeId.ToNodeId(customVariable.NodeId, m_session.NamespaceUris) }; newItem.Notification += OnComplexTypeNotification; list.Add(newItem); } subscription.AddItems(list); Console.WriteLine("9 - Add the subscription to the session."); ExitCode = ExitCode.ErrorAddSubscription; m_session.AddSubscription(subscription); subscription.Create(); Console.WriteLine("10 - Running...Press Ctrl-C to exit..."); ExitCode = ExitCode.ErrorRunning; return(m_session); }
private async Task <bool> Connect() { try { string path = config.ServerPath; Boolean cert = config.UseCertificate; var configSert = new ApplicationConfiguration() { ApplicationName = "ScadaCommSvc", ApplicationUri = "urn:MAIN:OPCUA:SimulationServer", ApplicationType = ApplicationType.Client, SecurityConfiguration = new SecurityConfiguration { ApplicationCertificate = new CertificateIdentifier { StoreType = @"Directory", StorePath = @"%CommonApplicationData%\OPC Foundation\CertificateStores\MachineDefault", SubjectName = "CN=SimulationServer, C=FR, O= Prosys OPC, DC=MAIN" }, TrustedIssuerCertificates = new CertificateTrustList { StoreType = @"Directory", StorePath = @"%CommonApplicationData%\OPC Foundation\CertificateStores\UA Certificate Authorities" }, TrustedPeerCertificates = new CertificateTrustList { StoreType = @"Directory", StorePath = @"%CommonApplicationData%\OPC Foundation\CertificateStores\UA Applications" }, RejectedCertificateStore = new CertificateTrustList { StoreType = @"Directory", StorePath = @"%CommonApplicationData%\OPC Foundation\CertificateStores\RejectedCertificates" }, AutoAcceptUntrustedCertificates = true, AddAppCertToTrustedStore = true }, TransportConfigurations = new TransportConfigurationCollection(), TransportQuotas = new TransportQuotas { OperationTimeout = 15000 }, ClientConfiguration = new ClientConfiguration { DefaultSessionTimeout = 60000 }, TraceConfiguration = new TraceConfiguration() }; configSert.Validate(ApplicationType.Client).GetAwaiter().GetResult(); if (configSert.SecurityConfiguration.AutoAcceptUntrustedCertificates) { configSert.CertificateValidator.CertificateValidation += (s, e) => { e.Accept = (e.Error.StatusCode == StatusCodes.BadCertificateUntrusted); }; } var application = new ApplicationInstance { ApplicationName = "ScadaCommSvc", ApplicationType = ApplicationType.Client, ApplicationConfiguration = configSert }; application.CheckApplicationInstanceCertificate(false, 2048).GetAwaiter().GetResult(); if (string.IsNullOrEmpty(path)) { throw new Exception(Localization.UseRussian ? "сервер не задан" : "server is undefined"); } EndpointDescription selectedEndpoint = CoreClientUtils.SelectEndpoint(path, cert, 15000); EndpointConfiguration endpointConfiguration = EndpointConfiguration.Create(configSert /*m_configuration*/); ConfiguredEndpoint endpoint = new ConfiguredEndpoint(null, selectedEndpoint, endpointConfiguration); m_session = await Opc.Ua.Client.Session.Create(/*m_configuration*/ configSert, endpoint, false, "KpOpcUA Demo", 60000, /*new UserIdentity(new AnonymousIdentityToken())*/ null, null); m_session.KeepAlive += Client_KeepAlive; return(true); } catch (Exception ex) { WriteToLog((Localization.UseRussian ? "Ошибка при соединении с OPC-сервером: " : "Error connecting to OPC UA server: ") + ex.Message); return(false); } }
/// <summary> /// Connects the session if it is disconnected. /// </summary> public async Task ConnectSessionAsync(CancellationToken ct) { bool sessionLocked = false; try { EndpointDescription selectedEndpoint = null; ConfiguredEndpoint configuredEndpoint = null; sessionLocked = await LockSessionAsync(); // if the session is already connected or connecting or shutdown in progress, return if (!sessionLocked || ct.IsCancellationRequested || State == SessionState.Connected || State == SessionState.Connecting) { return; } Logger.Information($"Connect and monitor session and nodes on endpoint '{EndpointUrl.AbsoluteUri}'."); State = SessionState.Connecting; try { // release the session to not block for high network timeouts. ReleaseSession(); sessionLocked = false; // start connecting selectedEndpoint = CoreClientUtils.SelectEndpoint(EndpointUrl.AbsoluteUri, UseSecurity); configuredEndpoint = new ConfiguredEndpoint(null, selectedEndpoint, EndpointConfiguration.Create(OpcApplicationConfiguration)); uint timeout = SessionTimeout * ((UnsuccessfulConnectionCount >= OpcSessionCreationBackoffMax) ? OpcSessionCreationBackoffMax : UnsuccessfulConnectionCount + 1); Logger.Information($"Create {(UseSecurity ? "secured" : "unsecured")} session for endpoint URI '{EndpointUrl.AbsoluteUri}' with timeout of {timeout} ms."); OpcUaClientSession = await Session.Create( OpcApplicationConfiguration, configuredEndpoint, true, false, OpcApplicationConfiguration.ApplicationName, timeout, new UserIdentity(new AnonymousIdentityToken()), null); } catch (Exception e) { Logger.Error(e, $"Session creation to endpoint '{EndpointUrl.AbsoluteUri}' failed {++UnsuccessfulConnectionCount} time(s). Please verify if server is up and {ProgramName} configuration is correct."); State = SessionState.Disconnected; OpcUaClientSession = null; return; } finally { if (OpcUaClientSession != null) { sessionLocked = await LockSessionAsync(); if (sessionLocked) { Logger.Information($"Session successfully created with Id {OpcUaClientSession.SessionId}."); if (!selectedEndpoint.EndpointUrl.Equals(configuredEndpoint.EndpointUrl.AbsoluteUri, StringComparison.OrdinalIgnoreCase)) { Logger.Information($"the Server has updated the EndpointUrl to '{selectedEndpoint.EndpointUrl}'"); } // init object state and install keep alive UnsuccessfulConnectionCount = 0; OpcUaClientSession.KeepAliveInterval = OpcKeepAliveIntervalInSec * 1000; OpcUaClientSession.KeepAlive += StandardClient_KeepAlive; // fetch the namespace array and cache it. it will not change as long the session exists. DataValue namespaceArrayNodeValue = OpcUaClientSession.ReadValue(VariableIds.Server_NamespaceArray); _namespaceTable.Update(namespaceArrayNodeValue.GetValue <string[]>(null)); // show the available namespaces Logger.Information($"The session to endpoint '{selectedEndpoint.EndpointUrl}' has {_namespaceTable.Count} entries in its namespace array:"); int i = 0; foreach (var ns in _namespaceTable.ToArray()) { Logger.Information($"Namespace index {i++}: {ns}"); } // fetch the minimum supported item sampling interval from the server. DataValue minSupportedSamplingInterval = OpcUaClientSession.ReadValue(VariableIds.Server_ServerCapabilities_MinSupportedSampleRate); _minSupportedSamplingInterval = minSupportedSamplingInterval.GetValue(0); Logger.Information($"The server on endpoint '{selectedEndpoint.EndpointUrl}' supports a minimal sampling interval of {_minSupportedSamplingInterval} ms."); State = SessionState.Connected; } else { State = SessionState.Disconnected; } } } } catch (Exception e) { Logger.Error(e, "Error in ConnectSessions."); } finally { if (sessionLocked) { ReleaseSession(); } } }
public async Task ConnectAndMonitor() { _opcSessionSemaphore.Wait(); Trace($"Connect and monitor session and nodes on endpoint '{EndpointUri.AbsoluteUri}'."); try { // if the session is disconnected, create it. if (State == SessionState.Disconnected) { EndpointDescription selectedEndpoint = CoreClientUtils.SelectEndpoint(EndpointUri.AbsoluteUri, true); ConfiguredEndpoint configuredEndpoint = new ConfiguredEndpoint(selectedEndpoint.Server, EndpointConfiguration.Create(OpcConfiguration)); configuredEndpoint.Update(selectedEndpoint); try { uint timeout = SessionTimeout * ((UnsuccessfulConnectionCount >= OpcSessionCreationBackoffMax) ? OpcSessionCreationBackoffMax : UnsuccessfulConnectionCount + 1); Trace($"Create session for endpoint URI '{EndpointUri.AbsoluteUri}' with timeout of {timeout} ms."); Session = await Session.Create( OpcConfiguration, configuredEndpoint, true, false, OpcConfiguration.ApplicationName, timeout, new UserIdentity(new AnonymousIdentityToken()), null); if (Session != null) { Trace($"Session successfully created with Id {Session.SessionId}."); if (!selectedEndpoint.EndpointUrl.Equals(configuredEndpoint.EndpointUrl)) { Trace($"the Server has updated the EndpointUrl to '{selectedEndpoint.EndpointUrl}'"); } // init object state and install keep alive UnsuccessfulConnectionCount = 0; State = SessionState.Connected; Session.KeepAliveInterval = OpcKeepAliveIntervalInSec * 1000; Session.KeepAlive += new KeepAliveEventHandler((sender, e) => StandardClient_KeepAlive(sender, e, Session)); // fetch the namespace array and cache it. it will not change as long the session exists. NodeId namespaceArrayNodeId = new NodeId(Variables.Server_NamespaceArray, 0); DataValue namespaceArrayNodeValue = Session.ReadValue(namespaceArrayNodeId); _namespaceTable.Update(namespaceArrayNodeValue.GetValue <string[]>(null)); // show the available namespaces Trace($"The session to endpoint '{selectedEndpoint.EndpointUrl}' has {_namespaceTable.Count} entries in its namespace array:"); int i = 0; foreach (var ns in _namespaceTable.ToArray()) { Trace($"Namespace index {i++}: {ns}"); } } } catch (Exception e) { Trace(e, $"Session creation to endpoint '{EndpointUri.AbsoluteUri}' failed {++UnsuccessfulConnectionCount} time(s). Please verify if server is up and Publisher configuration is correct."); State = SessionState.Disconnected; Session = null; return; } } // stop monitoring of nodes if requested and remove them from the monitored items list. var itemsToRemove = MonitoredItemsInfo.Where(i => i.State == MonitoredItemInfo.MonitoredItemState.StopMonitoring); if (itemsToRemove.GetEnumerator().MoveNext()) { itemsToRemove.GetEnumerator().Reset(); Trace($"Remove nodes on endpoint '{EndpointUri.AbsoluteUri}'"); Session.DefaultSubscription.RemoveItems(itemsToRemove.Select(i => i.MonitoredItem)); } // ensure all nodes on this session are monitored. Trace($"Start monitoring nodes on endpoint '{EndpointUri.AbsoluteUri}'"); var unmonitoredItems = MonitoredItemsInfo.Where(i => i.State == MonitoredItemInfo.MonitoredItemState.Unmonitored); foreach (var item in unmonitoredItems) { // if the session is disconnected, we stop trying and wait for the next cycle if (State == SessionState.Disconnected) { break; } NodeId currentNodeId; try { Subscription subscription = Session.DefaultSubscription; if (Session.AddSubscription(subscription)) { Trace("Create default subscription."); subscription.Create(); } // lookup namespace index if ExpandedNodeId format has been used and build NodeId identifier. if (!string.IsNullOrEmpty(item.StartNodeId.NamespaceUri)) { currentNodeId = NodeId.Create(item.StartNodeId.Identifier, item.StartNodeId.NamespaceUri, _namespaceTable); } else { currentNodeId = new NodeId((NodeId)item.StartNodeId); } // get the DisplayName for the node, otherwise use the nodeId Node node = Session.ReadNode(currentNodeId); item.DisplayName = node.DisplayName.Text ?? currentNodeId.ToString(); // add the new monitored item. MonitoredItem monitoredItem = new MonitoredItem(subscription.DefaultItem) { StartNodeId = currentNodeId, AttributeId = item.AttributeId, DisplayName = node.DisplayName.Text, MonitoringMode = item.MonitoringMode, SamplingInterval = item.SamplingInterval, QueueSize = item.QueueSize, DiscardOldest = item.DiscardOldest }; monitoredItem.Notification += item.Notification; subscription.AddItem(monitoredItem); subscription.ApplyChanges(); item.MonitoredItem = monitoredItem; item.State = MonitoredItemInfo.MonitoredItemState.Monitoreded; item.EndpointUri = EndpointUri; Trace($"Created monitored item for node '{currentNodeId}' on endpoint '{EndpointUri.AbsoluteUri}'"); } catch (Exception e) when(e.GetType() == typeof(ServiceResultException)) { ServiceResultException sre = (ServiceResultException)e; switch ((uint)sre.Result.StatusCode) { case StatusCodes.BadSessionIdInvalid: { Trace($"Session with Id {Session.SessionId} is no longer available on endpoint '{EndpointUri}'. Cleaning up."); // clean up the session _opcSessionSemaphore.Release(); Disconnect(); break; } case StatusCodes.BadNodeIdInvalid: case StatusCodes.BadNodeIdUnknown: { Trace($"Failed to monitor node '{item.StartNodeId.Identifier}' on endpoint '{EndpointUri}'."); Trace($"OPC UA ServiceResultException is '{sre.Result}'. Please check your publisher configuration for this node."); break; } default: { Trace($"Unhandled OPC UA ServiceResultException '{sre.Result}' when monitoring node '{item.StartNodeId.Identifier}' on endpoint '{EndpointUri}'. Continue."); break; } } } catch (Exception e) { Trace(e, $"Failed to monitor node '{item.StartNodeId.Identifier}' on endpoint '{EndpointUri}'"); } } // shutdown unused sessions. var unusedSessions = OpcSessions.Where(s => s.MonitoredItemsInfo.Count == 0); foreach (var unusedSession in unusedSessions) { await unusedSession.Shutdown(); OpcSessions.Remove(unusedSession); } } finally { _opcSessionSemaphore.Release(); } }