public static async Task <object> WriteVar(int node, KeyValuePair <string, object>[] ValuesToSet) { try { WriteValue[] valuesToWrite = new WriteValue[ValuesToSet.Length]; for (int i = 0; i < ValuesToSet.Length; i++) { valuesToWrite[i] = new WriteValue { // you can parse the nodeId from a string. NodeId = NodeId.Parse("ns=" + node.ToString() + ";s=" + ValuesToSet[i].Key), // variable class nodes have a Value attribute. AttributeId = AttributeIds.Value, Value = new DataValue(ValuesToSet[i].Value) }; } var writeRequest = new WriteRequest { NodesToWrite = valuesToWrite }; // send the ReadRequest to the server. var writeResult = await channel.WriteAsync(writeRequest); return(writeResult); } catch (Exception ex) { //await channel.AbortAsync(); return(null); } }
public async Task DatapoolReadOpcWriteAsync(OpcDatapoolModel dataModel, UaTcpSessionChannel channel) { // Read the Thermo tag value and write to the OPC Server DataValue value; switch (dataModel.TagInfo.Type) { case Thermo.Datapool.Datapool.dpTypes.FLOAT: value = new DataValue(new Variant(dataModel.TagInfo.AsDouble), sourceTimestamp: DateTime.Now, serverTimestamp: DateTime.Now); break; case Thermo.Datapool.Datapool.dpTypes.INT: value = new DataValue(new Variant(dataModel.TagInfo.AsInt), sourceTimestamp: DateTime.Now); break; case Thermo.Datapool.Datapool.dpTypes.STRING: value = new DataValue(new Variant(dataModel.TagInfo.AsString), sourceTimestamp: DateTime.Now); break; case Thermo.Datapool.Datapool.dpTypes.BOOL: value = new DataValue(new Variant(dataModel.TagInfo.AsBoolean), sourceTimestamp: DateTime.Now); break; default: throw new InvalidCastException($"Cannot write {dataModel.TagInfo.Type} data type to OPC."); } var writeRequest = new WriteRequest { NodesToWrite = new WriteValue[] { new WriteValue { NodeId = dataModel.NodeId, Value = value, AttributeId = AttributeIds.Value } } }; var response = await channel.WriteAsync(writeRequest); }
public async Task StructureTest() { var channel = new UaTcpSessionChannel( localDescription, certificateStore, new AnonymousIdentity(), EndpointUrl, loggerFactory: loggerFactory); await channel.OpenAsync(); var readRequest = new ReadRequest { NodesToRead = new[] { new ReadValueId { AttributeId = AttributeIds.Value, NodeId = NodeId.Parse("ns=2;s=Demo.Static.Arrays.Structure") }, }, }; var readResponse = await channel.ReadAsync(readRequest); foreach (var result in readResponse.Results) { StatusCode.IsGood(result.StatusCode) .Should().BeTrue(); } // reading this node returns an array of ExtensionObjects var obj = readResponse.Results[0].Value; // create new DataValue for writing. Most servers reject writing values with timestamps. var newValue = new DataValue(obj); var writeRequest = new WriteRequest { NodesToWrite = new[] { new WriteValue { AttributeId = AttributeIds.Value, NodeId = NodeId.Parse("ns=2;s=Demo.Static.Arrays.Structure"), Value = newValue }, }, }; var writeResponse = await channel.WriteAsync(writeRequest); foreach (var result in writeResponse.Results) { StatusCode.IsGood(result) .Should().BeTrue(); } logger.LogInformation($"Closing session '{channel.SessionId}'."); await channel.CloseAsync(); }
public async Task WriteBool(string name, bool value) { var writeRequest = new Workstation.ServiceModel.Ua.WriteRequest { NodesToWrite = new[] { new Workstation.ServiceModel.Ua.WriteValue { NodeId = Workstation.ServiceModel.Ua.NodeId.Parse("ns=4;s=|var|" + serverName + "." + name), AttributeId = AttributeIds.Value, Value = new Workstation.ServiceModel.Ua.DataValue(value) } } }; try { var writeResult = await channel.WriteAsync(writeRequest); } catch (Exception ex) { } }
private static async Task Write(List <NodeId> nodesIds, DataValue dataval) { // setup logger var loggerFactory = new LoggerFactory(); loggerFactory.AddDebug(LogLevel.Debug); // Describe this app. var appDescription = new ApplicationDescription() { ApplicationName = "DataLoggingConsole", ApplicationUri = $"urn:{System.Net.Dns.GetHostName()}:DataLoggingConsole", ApplicationType = ApplicationType.Client, }; // Create a certificate store on disk. // Create array of NodeIds to log. var nodeIds = nodesIds.ToArray(); try { // Discover endpoints. var getEndpointsRequest = new GetEndpointsRequest { EndpointUrl = discoveryUrl, ProfileUris = new[] { TransportProfileUris.UaTcpTransport } }; var getEndpointsResponse = await UaTcpDiscoveryService.GetEndpointsAsync(getEndpointsRequest).ConfigureAwait(false); if (getEndpointsResponse.Endpoints == null || getEndpointsResponse.Endpoints.Length == 0) { throw new InvalidOperationException($"'{discoveryUrl}' returned no endpoints."); } // Choose the endpoint with highest security level. var remoteEndpoint = getEndpointsResponse.Endpoints.OrderBy(e => e.SecurityLevel).Last(); // Create a session with the server. var session = new UaTcpSessionChannel(appDescription, certificateStore, async e => GetIUserIdentity(remoteEndpoint).GetAwaiter().GetResult(), remoteEndpoint, loggerFactory); try { await session.OpenAsync(); RegisterNodesResponse registerNodesResponse = null; if (true) // True registers the nodeIds to improve performance of the server. { // Register array of nodes to read. var registerNodesRequest = new RegisterNodesRequest { NodesToRegister = nodeIds }; registerNodesResponse = await session.RegisterNodesAsync(registerNodesRequest); } WriteRequest writeRequest = new WriteRequest(); writeRequest.NodesToWrite = new WriteValue[1] { new WriteValue() { NodeId = nodeIds[0], AttributeId = AttributeIds.Value, Value = dataval } }; WriteRequest request = writeRequest; StatusCode statusCode; // write the nodes. statusCode = (await session.WriteAsync(request).ConfigureAwait(false)).Results[0];; } catch { await session.AbortAsync(); throw; } await session.AbortAsync(); } catch (Exception e) { // ignored } }
public async Task CreateEventSubscription() { // describe this client application. var clientDescription = new ApplicationDescription { ApplicationName = "Workstation.UaClient.FeatureTests", ApplicationUri = $"urn:{System.Net.Dns.GetHostName()}:Workstation.UaClient.FeatureTests", ApplicationType = ApplicationType.Client }; // place to store certificates var certificateStore = new DirectoryStore("./pki"); // create a 'UaTcpSessionChannel', a client-side channel that opens a 'session' with the server. var channel = new UaTcpSessionChannel( clientDescription, certificateStore, new AnonymousIdentity(), // the anonymous identity "opc.tcp://localhost:48010"); // the endpoint of Unified Automation's UaCPPServer. try { // try opening a session and reading a few nodes. await channel.OpenAsync(); Console.WriteLine($"Opened session with endpoint '{channel.RemoteEndpoint.EndpointUrl}'."); Console.WriteLine($"SecurityPolicy: '{channel.RemoteEndpoint.SecurityPolicyUri}'."); Console.WriteLine($"SecurityMode: '{channel.RemoteEndpoint.SecurityMode}'."); Console.WriteLine($"UserIdentityToken: '{channel.UserIdentity}'."); // build a CreateSubscriptionRequest. See 'OPC UA Spec Part 4' paragraph 5.13.2 var req = new CreateSubscriptionRequest { RequestedPublishingInterval = 500.0, // intervals are in milliseconds RequestedMaxKeepAliveCount = 30, RequestedLifetimeCount = 30 * 3, PublishingEnabled = true, }; var res = await channel.CreateSubscriptionAsync(req); // the result will return the server's subscription id. You will needs this to // add monitored items. var id = res.SubscriptionId; Console.WriteLine($"Created subscription '{id}'."); // build a CreateMonitoredItemsRequest. See 'OPC UA Spec Part 4' paragraph 5.12.2 var req2 = new CreateMonitoredItemsRequest { SubscriptionId = id, TimestampsToReturn = TimestampsToReturn.Both, ItemsToCreate = new MonitoredItemCreateRequest[] { new MonitoredItemCreateRequest { ItemToMonitor = new ReadValueId { AttributeId = AttributeIds.EventNotifier, NodeId = NodeId.Parse(ObjectIds.Server) }, MonitoringMode = MonitoringMode.Reporting, // specify a unique ClientHandle. The ClientHandle is returned in the PublishResponse RequestedParameters = new MonitoringParameters { ClientHandle = 42, SamplingInterval = -1.0, QueueSize = 1000, DiscardOldest = true, // events require an EventFilter with a SelectClause (a list of fields to receive) Filter = new EventFilter { SelectClauses = EventHelper.GetSelectClauses <BaseEvent>() } }, }, }, }; var res2 = await channel.CreateMonitoredItemsAsync(req2); Console.WriteLine("\nSubscribe to PublishResponse stream."); // when the session is open, the client sends a stream of PublishRequests to the server. // You can subscribe to all the PublishResponses -or- subscribe to the responses from // a single subscription. var token = channel // receive responses for the subscription we just created .Where(pr => pr.SubscriptionId == id) // subscribe with an 'OnNext' function, and an 'OnError' function .Subscribe( pr => { // loop thru all the event notifications and write them out. var enls = pr.NotificationMessage.NotificationData.OfType <EventNotificationList>(); foreach (var enl in enls) { foreach (var efl in enl.Events) { var ev = EventHelper.Deserialize <BaseEvent>(efl.EventFields); Console.WriteLine($"time: {ev.Time}, src: {ev.SourceName}, msg: {ev.Message}, sev: {ev.Severity}"); } } }, ex => Console.WriteLine("Exception in publish response handler: {0}", ex.GetBaseException().Message) ); // publish for 5 seconds and then close. for (int i = 0; i < 10; i++) { // trigger an event on the Unified Automation server. var writeResult = await channel.WriteAsync( new WriteRequest { // Write true, false, true, false, ... NodesToWrite = new[] { new WriteValue { NodeId = NodeId.Parse("ns=2;s=Demo.Events.Trigger_BaseEvent"), AttributeId = AttributeIds.Value, Value = new DataValue(i % 2 == 0) } } } ); await Task.Delay(500); } Console.WriteLine($"\nClosing session '{channel.SessionId}'."); await channel.CloseAsync(); } catch (Exception ex) { await channel.AbortAsync(); Console.WriteLine(ex.Message); } }
public override async Task <WriteDataItemsResult> WriteDataItems(string group, IList <DataItemValue> values, Duration?timeout) { int N = values.Count; bool connected = await TryConnect(); if (!connected) { var failed = new FailedDataItemWrite[N]; for (int i = 0; i < N; ++i) { DataItemValue request = values[i]; failed[i] = new FailedDataItemWrite(request.ID, "No connection to OPC UA server"); } return(WriteDataItemsResult.Failure(failed)); } List <FailedDataItemWrite> listFailed = null; var dataItemsToWrite = new List <WriteValue>(N); for (int i = 0; i < N; ++i) { DataItemValue request = values[i]; string id = request.ID; if (mapId2Info.ContainsKey(id)) { ItemInfo info = mapId2Info[request.ID]; NodeId di = info.Node ?? NodeId.Null; try { //if (!di.IsWriteable) throw new Exception($"OPC item '{di.Name}' is not writeable"); dataItemsToWrite.Add(MakeWriteValue(di, request.Value.V, info.Type, info.Dimension)); } catch (Exception exp) { if (listFailed == null) { listFailed = new List <FailedDataItemWrite>(); } listFailed.Add(new FailedDataItemWrite(id, exp.Message)); } } else { if (listFailed == null) { listFailed = new List <FailedDataItemWrite>(); } listFailed.Add(new FailedDataItemWrite(id, $"No data item with id '{id}' found.")); } } if (dataItemsToWrite.Count > 0) { WriteRequest req = new WriteRequest() { NodesToWrite = dataItemsToWrite.ToArray() }; WriteResponse resp = await connection.WriteAsync(req); // TODO: Check result? } if (listFailed == null) { return(WriteDataItemsResult.OK); } else { return(WriteDataItemsResult.Failure(listFailed.ToArray())); } }
public async Task WriteIndexRange() { // describe this client application. var clientDescription = new ApplicationDescription { ApplicationName = "Workstation.UaClient.FeatureTests", ApplicationUri = $"urn:{System.Net.Dns.GetHostName()}:Workstation.UaClient.FeatureTests", ApplicationType = ApplicationType.Client }; // place to store certificates var certificateStore = new DirectoryStore("./pki"); // create a 'UaTcpSessionChannel', a client-side channel that opens a 'session' with the server. var channel = new UaTcpSessionChannel( clientDescription, certificateStore, new AnonymousIdentity(), // the anonymous identity "opc.tcp://localhost:48010"); // the endpoint of Unified Automation's UaCPPServer. try { // try opening a session and reading a few nodes. await channel.OpenAsync(); Console.WriteLine($"Opened session with endpoint '{channel.RemoteEndpoint.EndpointUrl}'."); Console.WriteLine($"SecurityPolicy: '{channel.RemoteEndpoint.SecurityPolicyUri}'."); Console.WriteLine($"SecurityMode: '{channel.RemoteEndpoint.SecurityMode}'."); Console.WriteLine($"UserIdentityToken: '{channel.UserIdentity}'."); // build a WriteRequest. See 'OPC UA Spec Part 4' paragraph 5.10.4 var writeRequest = new WriteRequest { // set the NodesToWrite to an array of WriteValues. NodesToWrite = new[] { // construct a WriteValue from a NodeId, AttributeId and DataValue. new WriteValue { // use a saved NodeId or Parse the nodeId from a string. // e.g. "ns=2;s=Demo.Static.Scalar.Double" NodeId = NodeId.Parse("ns=2;s=Demo.CTT.AllProfiles.Arrays.Double"), // variable class nodes have a Value attribute. AttributeId = AttributeIds.Value, // ask to write an slice of the underlying array IndexRange = "1:2", // the DataValue type has to match the underlying array type exactly. Value = new DataValue(new double[] { 41.0, 42.0 }), } } }; // send the WriteRequest to the server. var writeResult = await channel.WriteAsync(writeRequest); // 'Results' will be a array of status codes, one for every WriteValue. var result = writeResult.Results[0]; Console.WriteLine($"Write result: {result}"); Console.WriteLine($"Closing session '{channel.SessionId}'."); await channel.CloseAsync(); } catch (Exception ex) { await channel.AbortAsync(); Console.WriteLine(ex.Message); } }