Esempio n. 1
0
        public async Task Read()
        {
            var channel = new UaTcpSessionChannel(
                localDescription,
                certificateStore,
                new AnonymousIdentity(),
                EndpointUrl,
                loggerFactory: loggerFactory);

            await channel.OpenAsync();

            logger.LogInformation($"Opened session with endpoint '{channel.RemoteEndpoint.EndpointUrl}'.");
            logger.LogInformation($"SecurityPolicy: '{channel.RemoteEndpoint.SecurityPolicyUri}'.");
            logger.LogInformation($"SecurityMode: '{channel.RemoteEndpoint.SecurityMode}'.");
            logger.LogInformation($"Activated session '{channel.SessionId}'.");

            var readRequest = new ReadRequest {
                NodesToRead = new[] { new ReadValueId {
                                          NodeId = NodeId.Parse(VariableIds.Server_ServerStatus), AttributeId = AttributeIds.Value
                                      } }
            };
            var readResult = await channel.ReadAsync(readRequest);

            var serverStatus = readResult.Results[0].GetValueOrDefault <ServerStatusDataType>();

            logger.LogInformation("Server status:");
            logger.LogInformation("  ProductName: {0}", serverStatus.BuildInfo.ProductName);
            logger.LogInformation("  SoftwareVersion: {0}", serverStatus.BuildInfo.SoftwareVersion);
            logger.LogInformation("  ManufacturerName: {0}", serverStatus.BuildInfo.ManufacturerName);
            logger.LogInformation("  State: {0}", serverStatus.State);
            logger.LogInformation("  CurrentTime: {0}", serverStatus.CurrentTime);

            logger.LogInformation($"Closing session '{channel.SessionId}'.");
            await channel.CloseAsync();
        }
Esempio n. 2
0
        public async Task Polling()
        {
            var channel = new UaTcpSessionChannel(
                localDescription,
                certificateStore,
                new AnonymousIdentity(),
                EndpointUrl,
                loggerFactory: loggerFactory);

            await channel.OpenAsync();

            logger.LogInformation($"Opened session with endpoint '{channel.RemoteEndpoint.EndpointUrl}'.");
            logger.LogInformation($"SecurityPolicy: '{channel.RemoteEndpoint.SecurityPolicyUri}'.");
            logger.LogInformation($"SecurityMode: '{channel.RemoteEndpoint.SecurityMode}'.");
            logger.LogInformation($"Activated session '{channel.SessionId}'.");

            var readRequest = new ReadRequest {
                NodesToRead = new[] { new ReadValueId {
                                          NodeId = NodeId.Parse(VariableIds.Server_ServerStatus_CurrentTime), AttributeId = AttributeIds.Value
                                      } }
            };

            for (int i = 0; i < 10; i++)
            {
                var readResult = await channel.ReadAsync(readRequest);

                logger.LogInformation("Read {0}", readResult.Results[0].GetValueOrDefault <DateTime>());
                await Task.Delay(1000);
            }

            logger.LogInformation($"Closing session '{channel.SessionId}'.");
            await channel.CloseAsync();
        }
        /// <summary>
        /// Reads first/next level of tag tree.
        /// </summary>
        async Task <Tag> ReadTag(ReferenceDescription[] rds, UaTcpSessionChannel channel, Tag tag)
        {
            ReadValueId[] items = new ReadValueId[1];
            items[0] = new ReadValueId {
                NodeId = NodeId.Parse(rds.Last().NodeId.ToString()), AttributeId = AttributeIds.DataType
            };
            ReadRequest readRequest = new ReadRequest {
                NodesToRead = items
            };
            ReadResponse readResponse = await channel.ReadAsync(readRequest);

            if (string.IsNullOrEmpty(tag.Name))
            {
                tag = new Tag(rds.Take(rds.Length - 1).ToList());
            }
            tag.NestedName(rds.Last().DisplayName);

            if (rds.Length > 2)
            {
                tag.Group4 = rds[1].DisplayName.ToString();
            }
            if (rds.Length > 1)
            {
                tag.Group3 = rds[0].DisplayName.ToString();
            }

            if (readResponse.Results[0].Value != null)
            {
                tag.ConversionFunction = Typ(readResponse.Results[0].Value.ToString());
            }

            return(tag);
        }
Esempio n. 4
0
File: OPC.cs Progetto: krzyfre/HMI
        public static async Task <DataValue[]> ReadVar(int node, string[] VarNames)
        {
            try
            {
                ReadValueId[] valuesToRead = new ReadValueId[VarNames.Length];
                for (int i = 0; i < VarNames.Length; i++)
                {
                    valuesToRead[i] = new ReadValueId
                    {
                        // you can parse the nodeId from a string.
                        NodeId = NodeId.Parse("ns=" + node.ToString() + ";s=" + VarNames[i]),
                        // variable class nodes have a Value attribute.
                        AttributeId = AttributeIds.Value
                    };
                }

                var readRequest = new ReadRequest
                {
                    NodesToRead = valuesToRead
                };
                // send the ReadRequest to the server.
                var readResult = await channel.ReadAsync(readRequest);

                return(readResult.Results);
            }
            catch (Exception ex)
            {
                //await channel.AbortAsync();
                return(null);
            }
        }
Esempio n. 5
0
        public async Task SessionTimeoutCausesFault()
        {
            // discover available endpoints of server.
            var getEndpointsRequest = new GetEndpointsRequest
            {
                EndpointUrl = EndpointUrl,
                ProfileUris = new[] { TransportProfileUris.UaTcpTransport }
            };

            Console.WriteLine($"Discovering endpoints of '{getEndpointsRequest.EndpointUrl}'.");
            var getEndpointsResponse = await UaTcpDiscoveryService.GetEndpointsAsync(getEndpointsRequest);

            var selectedEndpoint = getEndpointsResponse.Endpoints.OrderBy(e => e.SecurityLevel).Last();

            var           selectedTokenType = selectedEndpoint.UserIdentityTokens[0].TokenType;
            IUserIdentity selectedUserIdentity;

            switch (selectedTokenType)
            {
            case UserTokenType.UserName:
                selectedUserIdentity = new UserNameIdentity("root", "secret");
                break;

            default:
                selectedUserIdentity = new AnonymousIdentity();
                break;
            }

            var channel = new UaTcpSessionChannel(
                this.localDescription,
                this.certificateStore,
                selectedUserIdentity,
                selectedEndpoint,
                loggerFactory: this.loggerFactory,
                options: new UaTcpSessionChannelOptions {
                SessionTimeout = 10000
            });

            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($"Activated session '{channel.SessionId}'.");

            // server should close session due to inactivity
            await Task.Delay(20000);

            // should throw exception
            var readRequest = new ReadRequest {
                NodesToRead = new[] { new ReadValueId {
                                          NodeId = NodeId.Parse(VariableIds.Server_ServerStatus_CurrentTime), AttributeId = AttributeIds.Value
                                      } }
            };
            await channel.ReadAsync(readRequest);

            Console.WriteLine($"Closing session '{channel.SessionId}'.");
            await channel.CloseAsync();
        }
Esempio n. 6
0
        //private async void DisplayTimeEvent(object sender, ElapsedEventArgs e)
        //{

        //    if (serverName != "")
        //    {
        //        try
        //        {
        //            //await channel.OpenAsync();
        //            var readResult = await channel.ReadAsync(readRequest);
        //            itemDict.Clear();
        //            for (int i = 0; i < itemsNames.Count; i++)
        //            {
        //                itemDict.Add(names[i], readResult.Results[i].Value.ToString());

        //            }
        //            ItemsChanged?.Invoke(itemDict);
        //        }
        //        catch (Exception ex) { MessageBox.Show(ex.Message); }
        //    }
        //}

        public async Task <Dictionary <string, string> > ReadOPCAsync()
        {
            if (serverName != "")
            {
                try
                {
                    //await channel.OpenAsync();
                    var readResult = await channel.ReadAsync(readRequest);

                    itemDict.Clear();
                    for (int i = 0; i < itemsNames.Count; i++)
                    {
                        itemDict.Add(names[i], readResult.Results[i].Value.ToString());
                    }
                }
                catch (Exception ex) { MessageBox.Show(ex.Message); }
            }
            return(itemDict);
        }
Esempio n. 7
0
        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();
        }
        /// <summary>
        /// Reads tag unit.
        /// </summary>
        async Task ReadUnit(ReferenceDescription[] rds, UaTcpSessionChannel channel, Tag tag)
        {
            ReadValueId[] unit = new ReadValueId[1];
            unit[0] = new ReadValueId {
                NodeId = NodeId.Parse(rds.Last().NodeId.ToString()), AttributeId = AttributeIds.Value
            };
            ReadRequest unitRequest = new ReadRequest {
                NodesToRead = unit
            };
            ReadResponse unitResponse = await channel.ReadAsync(unitRequest);

            ExtensionObject EO = (ExtensionObject)unitResponse.Results[0].Value;
            EUInformation   EU = (EUInformation)EO.Body;

            tag.Unit = EU.DisplayName; //zapis jednostki
        }
Esempio n. 9
0
        public override async Task <VTQ[]> ReadDataItems(string group, IList <ReadRequest> items, Duration?timeout)
        {
            int N = items.Count;

            VTQ[] res = new VTQ[N];

            bool connected = await TryConnect();

            if (!connected)
            {
                for (int i = 0; i < N; ++i)
                {
                    VTQ vtq = items[i].LastValue;
                    vtq.Q  = Quality.Bad;
                    res[i] = vtq;
                }
                return(res);
            }

            ReadValueId[] dataItemsToRead = new ReadValueId[N];
            for (int i = 0; i < N; ++i)
            {
                ReadRequest request = items[i];
                NodeId      node    = mapId2Info[request.ID].Node ?? NodeId.Null;
                dataItemsToRead[i] = new ReadValueId {
                    AttributeId = AttributeIds.Value, NodeId = node
                };
            }

            var readRequest = new Workstation.ServiceModel.Ua.ReadRequest {
                NodesToRead        = dataItemsToRead,
                TimestampsToReturn = TimestampsToReturn.Source,
            };

            ReadResponse readResponse = await connection.ReadAsync(readRequest);

            for (int i = 0; i < N; ++i)
            {
                res[i] = MakeVTQ(readResponse.Results[i], items[i].LastValue, items[i].ID);
            }
            return(res);
        }
Esempio n. 10
0
        private async void DisplayTimeEvent(object sender, ElapsedEventArgs e)
        {
            if (serverName != "")
            {
                try
                {
                    //await channel.OpenAsync();
                    var readResult = await channel.ReadAsync(readRequest);

                    itemDict.Clear();
                    for (int i = 0; i < itemsNames.Count; i++)
                    {
                        itemDict.Add(names[i], readResult.Results[i].Value.ToString());
                        //MessageBox.Show(readResult.Results[i].Value.ToString());
                    }
                    ItemsChanged?.Invoke(itemDict);
                }
                catch (Exception ex) { MessageBox.Show(ex.Message); }
            }
        }
        /// <summary>
        /// Most important method - reading the tags.
        /// </summary>
        public async Task <List <Tag> > OPCReadAsync(string OPCAdress)
        {
            //Preparing data to connect to OPC server
            Tags = new List <Tag>();
            var loggerFactory = new LoggerFactory();

            var appDescription = new ApplicationDescription()
            {
                ApplicationName = "OPC",
                ApplicationUri  = $"urn:{System.Net.Dns.GetHostName()}:OPC",
                ApplicationType = ApplicationType.Client,
            };

            var certificateStore = new DirectoryStore(
                Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "Workstation.ConsoleApp", "pki"));

            var channel = new UaTcpSessionChannel(
                appDescription,
                certificateStore,
                new AnonymousIdentity(), //by now doesn't support signing in
                OPCAdress,
                loggerFactory: loggerFactory);

            try
            {
                Stopwatch stopwatch = new Stopwatch(); //measuring operations time
                stopwatch.Start();

                await channel.OpenAsync(); //opening channel

                OnNewEvent(new LogEventArgs("Connected to OPC Server"));

                //opening OPC tree branches to find actual tags - only proper for B&R X20 PLC
                BrowseRequest browseRequest = new BrowseRequest {
                    NodesToBrowse = new BrowseDescription[] { new BrowseDescription {
                                                                  NodeId = NodeId.Parse(ObjectIds.RootFolder), BrowseDirection = BrowseDirection.Forward, ReferenceTypeId = NodeId.Parse(ReferenceTypeIds.HierarchicalReferences), NodeClassMask = (uint)NodeClass.Variable | (uint)NodeClass.Object | (uint)NodeClass.Method, IncludeSubtypes = true, ResultMask = (uint)BrowseResultMask.All
                                                              } },
                };
                BrowseResponse browseResponse = await channel.BrowseAsync(browseRequest);

                browseRequest = new BrowseRequest {
                    NodesToBrowse = new BrowseDescription[] { new BrowseDescription {
                                                                  NodeId = ExpandedNodeId.ToNodeId(browseResponse.Results[0].References[0].NodeId, channel.NamespaceUris), BrowseDirection = BrowseDirection.Forward, ReferenceTypeId = NodeId.Parse(ReferenceTypeIds.HierarchicalReferences), NodeClassMask = (uint)NodeClass.Variable | (uint)NodeClass.Object | (uint)NodeClass.Method, IncludeSubtypes = true, ResultMask = (uint)BrowseResultMask.All
                                                              } },
                };
                browseResponse = await channel.BrowseAsync(browseRequest);

                browseRequest = new BrowseRequest {
                    NodesToBrowse = new BrowseDescription[] { new BrowseDescription {
                                                                  NodeId = ExpandedNodeId.ToNodeId(browseResponse.Results[0].References[1].NodeId, channel.NamespaceUris), BrowseDirection = BrowseDirection.Forward, ReferenceTypeId = NodeId.Parse(ReferenceTypeIds.HierarchicalReferences), NodeClassMask = (uint)NodeClass.Variable | (uint)NodeClass.Object | (uint)NodeClass.Method, IncludeSubtypes = true, ResultMask = (uint)BrowseResultMask.All
                                                              } },
                };
                browseResponse = await channel.BrowseAsync(browseRequest);

                browseRequest = new BrowseRequest {
                    NodesToBrowse = new BrowseDescription[] { new BrowseDescription {
                                                                  NodeId = ExpandedNodeId.ToNodeId(browseResponse.Results[0].References[0].NodeId, channel.NamespaceUris), BrowseDirection = BrowseDirection.Forward, ReferenceTypeId = NodeId.Parse(ReferenceTypeIds.HierarchicalReferences), NodeClassMask = (uint)NodeClass.Variable | (uint)NodeClass.Object | (uint)NodeClass.Method, IncludeSubtypes = true, ResultMask = (uint)BrowseResultMask.All
                                                              } },
                };
                browseResponse = await channel.BrowseAsync(browseRequest);

                browseRequest = new BrowseRequest {
                    NodesToBrowse = new BrowseDescription[] { new BrowseDescription {
                                                                  NodeId = ExpandedNodeId.ToNodeId(browseResponse.Results[0].References[0].NodeId, channel.NamespaceUris), BrowseDirection = BrowseDirection.Forward, ReferenceTypeId = NodeId.Parse(ReferenceTypeIds.HierarchicalReferences), NodeClassMask = (uint)NodeClass.Variable | (uint)NodeClass.Object | (uint)NodeClass.Method, IncludeSubtypes = true, ResultMask = (uint)BrowseResultMask.All
                                                              } },
                };
                browseResponse = await channel.BrowseAsync(browseRequest);

                browseRequest = new BrowseRequest {
                    NodesToBrowse = new BrowseDescription[] { new BrowseDescription {
                                                                  NodeId = ExpandedNodeId.ToNodeId(browseResponse.Results[0].References[1].NodeId, channel.NamespaceUris), BrowseDirection = BrowseDirection.Forward, ReferenceTypeId = NodeId.Parse(ReferenceTypeIds.HierarchicalReferences), NodeClassMask = (uint)NodeClass.Variable | (uint)NodeClass.Object | (uint)NodeClass.Method, IncludeSubtypes = true, ResultMask = (uint)BrowseResultMask.All
                                                              } },
                };
                browseResponse = await channel.BrowseAsync(browseRequest);

                browseRequest = new BrowseRequest {
                    NodesToBrowse = new BrowseDescription[] { new BrowseDescription {
                                                                  NodeId = ExpandedNodeId.ToNodeId(browseResponse.Results[0].References[10].NodeId, channel.NamespaceUris), BrowseDirection = BrowseDirection.Forward, ReferenceTypeId = NodeId.Parse(ReferenceTypeIds.HierarchicalReferences), NodeClassMask = (uint)NodeClass.Variable | (uint)NodeClass.Object | (uint)NodeClass.Method, IncludeSubtypes = true, ResultMask = (uint)BrowseResultMask.All
                                                              } },
                };
                BrowseResponse browseResponse0 = await channel.BrowseAsync(browseRequest);

                int nestingLevel = 0;                                                       //nesting level counter
                Tag tag          = new Tag();                                               //initializing first tag
                int allTagsCount = browseResponse0.Results[0].References.Length - 1;        //for counting progress percentage

                for (int i = browseResponse0.Results[0].References.Length - 1; i >= 0; i--) //first level loop
                {
                    var rd = browseResponse0.Results[0].References[i];
                    if (Tags.Count > 0 && rd.DisplayName.ToString() == Tags[0].Name)
                    {
                        break;
                    }                                                                           //to avoid getting the same tags second time

                    nestingLevel = 0;
                    ReadValueId[] items = new ReadValueId[1];
                    items[0] = new ReadValueId {
                        NodeId = NodeId.Parse(rd.NodeId.ToString()), AttributeId = AttributeIds.DataType
                    };
                    ReadRequest readRequest = new ReadRequest {
                        NodesToRead = items
                    };
                    ReadResponse readResponse = await channel.ReadAsync(readRequest);


                    if (string.IsNullOrEmpty(tag.Name))
                    {
                        tag = new Tag(rd.DisplayName.ToString());
                    }


                    if (readResponse.Results[0].Value != null)
                    {
                        tag.ConversionFunction = Typ(readResponse.Results[0].Value.ToString());
                    }

                    browseRequest = new BrowseRequest {
                        NodesToBrowse = new BrowseDescription[] { new BrowseDescription {
                                                                      NodeId = ExpandedNodeId.ToNodeId(rd.NodeId, channel.NamespaceUris), BrowseDirection = BrowseDirection.Forward, ReferenceTypeId = NodeId.Parse(ReferenceTypeIds.HierarchicalReferences), NodeClassMask = (uint)NodeClass.Variable | (uint)NodeClass.Object | (uint)NodeClass.Method, IncludeSubtypes = true, ResultMask = (uint)BrowseResultMask.All
                                                                  } },
                    };
                    browseResponse = await channel.BrowseAsync(browseRequest);

                    foreach (var rd1 in browseResponse.Results[0].References ?? new ReferenceDescription[0]) //second level loop (nesting=1)
                    {
                        if (!rd1.NodeId.ToString().Contains("#"))
                        {
                            nestingLevel = 1;
                            tag          = await ReadTag(new ReferenceDescription[] { rd, rd1 }, channel, tag);

                            browseRequest = new BrowseRequest {
                                NodesToBrowse = new BrowseDescription[] { new BrowseDescription {
                                                                              NodeId = ExpandedNodeId.ToNodeId(rd1.NodeId, channel.NamespaceUris), BrowseDirection = BrowseDirection.Forward, ReferenceTypeId = NodeId.Parse(ReferenceTypeIds.HierarchicalReferences), NodeClassMask = (uint)NodeClass.Variable | (uint)NodeClass.Object | (uint)NodeClass.Method, IncludeSubtypes = true, ResultMask = (uint)BrowseResultMask.All
                                                                          } },
                            };
                            browseResponse = await channel.BrowseAsync(browseRequest);

                            foreach (var rd2 in browseResponse.Results[0].References ?? new ReferenceDescription[0]) //third level loop (nesting=2)
                            {
                                if (!rd2.NodeId.ToString().Contains("#"))
                                {
                                    nestingLevel = 2;
                                    tag          = await ReadTag(new ReferenceDescription[] { rd, rd1, rd2 }, channel, tag);

                                    browseRequest = new BrowseRequest {
                                        NodesToBrowse = new BrowseDescription[] { new BrowseDescription {
                                                                                      NodeId = ExpandedNodeId.ToNodeId(rd2.NodeId, channel.NamespaceUris), BrowseDirection = BrowseDirection.Forward, ReferenceTypeId = NodeId.Parse(ReferenceTypeIds.HierarchicalReferences), NodeClassMask = (uint)NodeClass.Variable | (uint)NodeClass.Object | (uint)NodeClass.Method, IncludeSubtypes = true, ResultMask = (uint)BrowseResultMask.All
                                                                                  } },
                                    };
                                    browseResponse = await channel.BrowseAsync(browseRequest);

                                    foreach (var rd3 in browseResponse.Results[0].References ?? new ReferenceDescription[0]) //fourth level loop (nesting=3)
                                    {
                                        if (!rd3.NodeId.ToString().Contains("#"))
                                        {
                                            nestingLevel = 3;
                                            tag          = await ReadTag(new ReferenceDescription[] { rd, rd1, rd2, rd3 }, channel, tag);
                                        }
                                        else if (rd3.NodeId.ToString().Contains("#EngineeringUnits"))
                                        {
                                            await ReadUnit(new ReferenceDescription[] { rd, rd1, rd2, rd3 }, channel, tag);
                                        }

                                        if (nestingLevel == 3 && !string.IsNullOrEmpty(tag.Name))
                                        {
                                            tag = SaveTag(tag);
                                        }
                                    }
                                }
                                else if (rd2.NodeId.ToString().Contains("#EngineeringUnits"))
                                {
                                    await ReadUnit(new ReferenceDescription[] { rd, rd1, rd2 }, channel, tag);
                                }


                                if (nestingLevel == 2 && !string.IsNullOrEmpty(tag.Name))
                                {
                                    tag = SaveTag(tag);
                                }
                            }
                        }

                        else if (rd1.NodeId.ToString().Contains("#EngineeringUnits"))
                        {
                            await ReadUnit(new ReferenceDescription[] { rd, rd1 }, channel, tag);
                        }


                        if (nestingLevel == 1 && !string.IsNullOrEmpty(tag.Name))
                        {
                            tag = SaveTag(tag);
                        }
                    }
                    if (nestingLevel == 0 && !string.IsNullOrEmpty(tag.Name))
                    {
                        tag = SaveTag(tag);
                    }

                    OnProgressChanged(new ProgressChangedArgs((allTagsCount - i) * 100 / allTagsCount)); //computing progress percentage
                }


                await channel.CloseAsync(); //closing the channel

                stopwatch.Stop();

                OnNewEvent(new LogEventArgs(Tags.Count + " tags read, time elapsed: " + stopwatch.Elapsed.TotalSeconds.ToString("F3") + " s"));
            }
            catch (Exception ex)
            {
                OnNewEvent(new LogEventArgs("Error connecting to OPC server."));
                await channel.AbortAsync();
            }

            return(Tags);
        }
Esempio n. 12
0
        public async Task StackTest()
        {
            var channel = new UaTcpSessionChannel(
                localDescription,
                certificateStore,
                new AnonymousIdentity(),
                EndpointUrl,
                loggerFactory: loggerFactory);

            await channel.OpenAsync();

            logger.LogInformation($"Opened session with endpoint '{channel.RemoteEndpoint.EndpointUrl}'.");
            logger.LogInformation($"SecurityPolicy: '{channel.RemoteEndpoint.SecurityPolicyUri}'.");
            logger.LogInformation($"SecurityMode: '{channel.RemoteEndpoint.SecurityMode}'.");
            logger.LogInformation($"Activated session '{channel.SessionId}'.");

            var readRequest = new ReadRequest
            {
                NodesToRead = new[]
                {
                    new ReadValueId {
                        AttributeId = AttributeIds.Value, NodeId = NodeId.Parse("ns=2;s=Demo.Static.Scalar.Boolean")
                    },
                    new ReadValueId {
                        AttributeId = AttributeIds.Value, NodeId = NodeId.Parse("ns=2;s=Demo.Static.Scalar.SByte")
                    },
                    new ReadValueId {
                        AttributeId = AttributeIds.Value, NodeId = NodeId.Parse("ns=2;s=Demo.Static.Scalar.Int16")
                    },
                    new ReadValueId {
                        AttributeId = AttributeIds.Value, NodeId = NodeId.Parse("ns=2;s=Demo.Static.Scalar.Int32")
                    },
                    new ReadValueId {
                        AttributeId = AttributeIds.Value, NodeId = NodeId.Parse("ns=2;s=Demo.Static.Scalar.Int64")
                    },
                    new ReadValueId {
                        AttributeId = AttributeIds.Value, NodeId = NodeId.Parse("ns=2;s=Demo.Static.Scalar.Byte")
                    },
                    new ReadValueId {
                        AttributeId = AttributeIds.Value, NodeId = NodeId.Parse("ns=2;s=Demo.Static.Scalar.UInt16")
                    },
                    new ReadValueId {
                        AttributeId = AttributeIds.Value, NodeId = NodeId.Parse("ns=2;s=Demo.Static.Scalar.UInt32")
                    },
                    new ReadValueId {
                        AttributeId = AttributeIds.Value, NodeId = NodeId.Parse("ns=2;s=Demo.Static.Scalar.UInt64")
                    },
                    new ReadValueId {
                        AttributeId = AttributeIds.Value, NodeId = NodeId.Parse("ns=2;s=Demo.Static.Scalar.Float")
                    },
                    new ReadValueId {
                        AttributeId = AttributeIds.Value, NodeId = NodeId.Parse("ns=2;s=Demo.Static.Scalar.Double")
                    },
                    new ReadValueId {
                        AttributeId = AttributeIds.Value, NodeId = NodeId.Parse("ns=2;s=Demo.Static.Scalar.String")
                    },
                    new ReadValueId {
                        AttributeId = AttributeIds.Value, NodeId = NodeId.Parse("ns=2;s=Demo.Static.Scalar.DateTime")
                    },
                    new ReadValueId {
                        AttributeId = AttributeIds.Value, NodeId = NodeId.Parse("ns=2;s=Demo.Static.Scalar.Guid")
                    },
                    new ReadValueId {
                        AttributeId = AttributeIds.Value, NodeId = NodeId.Parse("ns=2;s=Demo.Static.Scalar.ByteString")
                    },
                    new ReadValueId {
                        AttributeId = AttributeIds.Value, NodeId = NodeId.Parse("ns=2;s=Demo.Static.Scalar.XmlElement")
                    },
                    new ReadValueId {
                        AttributeId = AttributeIds.Value, NodeId = NodeId.Parse("ns=2;s=Demo.Static.Scalar.LocalizedText")
                    },
                    new ReadValueId {
                        AttributeId = AttributeIds.Value, NodeId = NodeId.Parse("ns=2;s=Demo.Static.Scalar.QualifiedName")
                    },
                    new ReadValueId {
                        AttributeId = AttributeIds.Value, NodeId = NodeId.Parse("ns=2;s=Demo.Static.Arrays.Boolean")
                    },
                    new ReadValueId {
                        AttributeId = AttributeIds.Value, NodeId = NodeId.Parse("ns=2;s=Demo.Static.Arrays.SByte")
                    },
                    new ReadValueId {
                        AttributeId = AttributeIds.Value, NodeId = NodeId.Parse("ns=2;s=Demo.Static.Arrays.Int16")
                    },
                    new ReadValueId {
                        AttributeId = AttributeIds.Value, NodeId = NodeId.Parse("ns=2;s=Demo.Static.Arrays.Int32")
                    },
                    new ReadValueId {
                        AttributeId = AttributeIds.Value, NodeId = NodeId.Parse("ns=2;s=Demo.Static.Arrays.Int64")
                    },
                    new ReadValueId {
                        AttributeId = AttributeIds.Value, NodeId = NodeId.Parse("ns=2;s=Demo.Static.Arrays.Byte")
                    },
                    new ReadValueId {
                        AttributeId = AttributeIds.Value, NodeId = NodeId.Parse("ns=2;s=Demo.Static.Arrays.UInt16")
                    },
                    new ReadValueId {
                        AttributeId = AttributeIds.Value, NodeId = NodeId.Parse("ns=2;s=Demo.Static.Arrays.UInt32")
                    },
                    new ReadValueId {
                        AttributeId = AttributeIds.Value, NodeId = NodeId.Parse("ns=2;s=Demo.Static.Arrays.UInt64")
                    },
                    new ReadValueId {
                        AttributeId = AttributeIds.Value, NodeId = NodeId.Parse("ns=2;s=Demo.Static.Arrays.Float")
                    },
                    new ReadValueId {
                        AttributeId = AttributeIds.Value, NodeId = NodeId.Parse("ns=2;s=Demo.Static.Arrays.Double")
                    },
                    new ReadValueId {
                        AttributeId = AttributeIds.Value, NodeId = NodeId.Parse("ns=2;s=Demo.Static.Arrays.String")
                    },
                    new ReadValueId {
                        AttributeId = AttributeIds.Value, NodeId = NodeId.Parse("ns=2;s=Demo.Static.Arrays.DateTime")
                    },
                    new ReadValueId {
                        AttributeId = AttributeIds.Value, NodeId = NodeId.Parse("ns=2;s=Demo.Static.Arrays.Guid")
                    },
                    new ReadValueId {
                        AttributeId = AttributeIds.Value, NodeId = NodeId.Parse("ns=2;s=Demo.Static.Arrays.ByteString")
                    },
                    new ReadValueId {
                        AttributeId = AttributeIds.Value, NodeId = NodeId.Parse("ns=2;s=Demo.Static.Arrays.XmlElement")
                    },
                    new ReadValueId {
                        AttributeId = AttributeIds.Value, NodeId = NodeId.Parse("ns=2;s=Demo.Static.Arrays.LocalizedText")
                    },
                    new ReadValueId {
                        AttributeId = AttributeIds.Value, NodeId = NodeId.Parse("ns=2;s=Demo.Static.Arrays.QualifiedName")
                    },
                },
            };

            var sw = new Stopwatch();

            sw.Restart();
            for (int i = 0; i < 1; i++)
            {
                var readResponse = await channel.ReadAsync(readRequest);

                foreach (var result in readResponse.Results)
                {
                    StatusCode.IsGood(result.StatusCode)
                    .Should().BeTrue();
                    var obj = result.GetValue();
                }
            }

            sw.Stop();
            logger.LogInformation($"{sw.ElapsedMilliseconds} ms");

            logger.LogInformation($"Closing session '{channel.SessionId}'.");
            await channel.CloseAsync();
        }
        public async Task ReadIndexRange()
        {
            // 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 ReadRequest. See 'OPC UA Spec Part 4' paragraph 5.10.2
                var readRequest = new ReadRequest
                {
                    // set the NodesToRead to an array of ReadValueIds.
                    NodesToRead = new[] {
                        // construct a ReadValueId from a NodeId and AttributeId.
                        new ReadValueId {
                            // 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 read a range of the underlying array
                            IndexRange = "1:2"
                        }
                    }
                };
                // send the ReadRequest to the server.
                var readResult = await channel.ReadAsync(readRequest);

                // 'Results' will be an array of DataValues, one for every ReadValueId.
                // A DataValue holds the sampled value, timestamps and quality status code.
                var result = readResult.Results[0].GetValueOrDefault <double[]>();

                Console.WriteLine($"Read result: {string.Join(' ', result)}");

                Console.WriteLine($"Closing session '{channel.SessionId}'.");
                await channel.CloseAsync();
            }
            catch (Exception ex)
            {
                await channel.AbortAsync();

                Console.WriteLine(ex.Message);
            }
        }
Esempio n. 14
0
        private static async Task TestAsync(CancellationToken token = default(CancellationToken))
        {
            var discoveryUrl = $"opc.tcp://localhost:26543";
            var cycleTime    = 5000;

            // setup logger
            var loggerFactory = new LoggerFactory();

            loggerFactory.AddConsole(LogLevel.Information);
            var logger = loggerFactory?.CreateLogger <Program>();

            // 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.
            var certificateStore = new DirectoryStore(
                Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "DataLoggingConsole", "pki"));

            // Create array of NodeIds to log.
            var nodeIds = new[]
            {
                NodeId.Parse("i=2258")
            };

            while (!token.IsCancellationRequested)
            {
                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();

                    // Choose a User Identity.
                    IUserIdentity userIdentity = null;
                    if (remoteEndpoint.UserIdentityTokens.Any(p => p.TokenType == UserTokenType.Anonymous))
                    {
                        userIdentity = new AnonymousIdentity();
                    }
                    else if (remoteEndpoint.UserIdentityTokens.Any(p => p.TokenType == UserTokenType.UserName))
                    {
                        // If a username / password is requested, provide from .config file.
                        userIdentity = new UserNameIdentity("root", "secret");
                    }
                    else
                    {
                        throw new InvalidOperationException("Server must accept Anonymous or UserName identity.");
                    }

                    // Create a session with the server.
                    var session = new UaTcpSessionChannel(appDescription, certificateStore, async e => userIdentity, 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);
                        }

                        // Prepare read request.
                        var readRequest = new ReadRequest
                        {
                            NodesToRead = (registerNodesResponse?.RegisteredNodeIds ?? nodeIds)
                                          .Select(n => new ReadValueId {
                                NodeId = n, AttributeId = AttributeIds.Value
                            })
                                          .ToArray()
                        };

                        while (!token.IsCancellationRequested)
                        {
                            // Read the nodes.
                            var readResponse = await session.ReadAsync(readRequest).ConfigureAwait(false);

                            // Write the results.
                            for (int i = 0; i < readRequest.NodesToRead.Length; i++)
                            {
                                logger?.LogInformation($"{nodeIds[i]}; value: {readResponse.Results[i]}");
                            }

                            try
                            {
                                await Task.Delay(cycleTime, token);
                            }
                            catch { }
                        }
                        await session.CloseAsync();
                    }
                    catch
                    {
                        await session.AbortAsync();

                        throw;
                    }
                }
                catch (Exception ex)
                {
                    logger?.LogError(ex.Message);
                }

                try
                {
                    await Task.Delay(cycleTime, token);
                }
                catch { }
            }
        }
        public async Task ReadHistoryRawValues()
        {
            // 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}'.");

                Console.WriteLine("\nCheck if DataLogger active.");

                // check if DataLoggerActive is true. If not, then call method StartLogging.
                var req = new ReadRequest
                {
                    NodesToRead = new[] {
                        new ReadValueId {
                            NodeId = NodeId.Parse("ns=2;s=Demo.History.DataLoggerActive"), AttributeId = AttributeIds.Value
                        }
                    },
                };
                var res = await channel.ReadAsync(req);

                if (StatusCode.IsBad(res.Results[0].StatusCode))
                {
                    throw new InvalidOperationException("Error reading 'Demo.History.DataLoggerActive'. ");
                }
                var isActive = res.Results[0].GetValueOrDefault <bool>();

                if (!isActive)
                {
                    Console.WriteLine("Activating DataLogger.");

                    var req1 = new CallRequest
                    {
                        MethodsToCall = new[] {
                            new CallMethodRequest {
                                ObjectId = NodeId.Parse("ns=2;s=Demo.History"), // parent node
                                MethodId = NodeId.Parse("ns=2;s=Demo.History.StartLogging")
                            },
                        },
                    };
                    var res1 = await channel.CallAsync(req1);

                    if (StatusCode.IsBad(res1.Results[0].StatusCode))
                    {
                        throw new InvalidOperationException("Error calling method 'Demo.History.StartLogging'.");
                    }
                    Console.WriteLine("Note: Datalogger has just been activated, so there will be little or no history data to read.");
                    Console.WriteLine("      Try again in 1 minute.");
                }

                Console.WriteLine("\nReading history for last 1 minute(s).");

                // A continuation point is returned if there are more values to return than the
                // limit set by parameter NumValuesPerNode. A client should continue calling HistoryRead
                // until the continuation point returns null.
                byte[] cp = null;

                do
                {
                    var req2 = new HistoryReadRequest
                    {
                        HistoryReadDetails = new ReadRawModifiedDetails
                        {
                            StartTime        = DateTime.UtcNow.Add(TimeSpan.FromSeconds(-60)), // set start time to 1 minute ago
                            EndTime          = DateTime.UtcNow,
                            NumValuesPerNode = 100,                                            // sets limit. if there are more values to return then a continuation point is returned.
                            ReturnBounds     = false,                                          // set true to return interpolated values for the start and end times
                        },
                        TimestampsToReturn        = TimestampsToReturn.Both,
                        ReleaseContinuationPoints = false, // set true to abandon returning any remaining values from this interval
                        NodesToRead = new[] {
                            new HistoryReadValueId {
                                NodeId = NodeId.Parse("ns=2;s=Demo.History.DoubleWithHistory"), ContinuationPoint = cp
                            },
                        },
                    };

                    var res2 = await channel.HistoryReadAsync(req2);

                    if (StatusCode.IsGood(res2.Results[0].StatusCode))
                    {
                        var historyData = res2.Results[0].HistoryData as HistoryData;

                        Console.WriteLine($"Found {historyData.DataValues.Length} value(s) for node '{req2.NodesToRead[0].NodeId}':");

                        foreach (var dv in historyData.DataValues)
                        {
                            Console.WriteLine($"Read {dv.Value}, q: {dv.StatusCode}, ts: {dv.SourceTimestamp}");
                        }

                        cp = res2.Results[0].ContinuationPoint;
                        // if ContinuationPoint is null, then there is no more data to return.
                        if (cp == null)
                        {
                            break;
                        }
                    }
                    else
                    {
                        Console.WriteLine($"HistoryRead return statuscode: {res2.Results[0].StatusCode}");
                        break;
                    }
                } while (cp != null); // loop while ContinuationPoint is not null.

                Console.WriteLine($"\nClosing session '{channel.SessionId}'.");
                await channel.CloseAsync();
            }
            catch (Exception ex)
            {
                await channel.AbortAsync();

                Console.WriteLine(ex.Message);
            }
        }
Esempio n. 16
0
        public async Task SetChanel()
        {
            var clientDescription = new ApplicationDescription
            {
                ApplicationName = "Workstation.UaClient.FeatureTests",
                ApplicationUri  = $"urn:{System.Net.Dns.GetHostName()}:Workstation.UaClient.FeatureTests",
                ApplicationType = Workstation.ServiceModel.Ua.ApplicationType.Client
            };

            channel = new UaTcpSessionChannel(
                clientDescription,
                null, // no x509 certificates
                new AnonymousIdentity(),
                url,
                SecurityPolicyUris.None);

            try
            {
                await channel.OpenAsync();

                var readRequestGetName = new Workstation.ServiceModel.Ua.ReadRequest
                {
                    NodesToRead = new[] {
                        new Workstation.ServiceModel.Ua.ReadValueId {
                            NodeId      = Workstation.ServiceModel.Ua.NodeId.Parse(Workstation.ServiceModel.Ua.VariableIds.Server_ServerStatus),
                            AttributeId = AttributeIds.Value
                        }
                    }
                };
                var readResultName = await channel.ReadAsync(readRequestGetName);

                var serverStatusGetName = readResultName.Results[0].GetValueOrDefault <Workstation.ServiceModel.Ua.ServerStatusDataType>();
                serverName = serverStatusGetName.BuildInfo.ProductName;


                ReadValueId[] reads = new ReadValueId[itemsNames.Count];
                int           index = 0;
                names = new String[itemsNames.Count];
                foreach (string name in itemsNames)
                {
                    reads[index] = new Workstation.ServiceModel.Ua.ReadValueId
                    {
                        NodeId      = Workstation.ServiceModel.Ua.NodeId.Parse("ns=4;s=|var|" + serverName + "." + name),
                        AttributeId = AttributeIds.Value
                    };
                    //MessageBox.Show(itemsNames.Count.ToString());
                    names[index] = name;
                    index++;
                }
                readRequest = new Workstation.ServiceModel.Ua.ReadRequest
                {
                    NodesToRead = reads
                };
            }
            catch (Exception ex)
            {
                await channel.AbortAsync();

                MessageBox.Show(ex.Message);
            }
        }
Esempio n. 17
0
        public async Task SessionTimeoutCausesFault()
        {
            // get or add application certificate.
            var localCertificate = this.localDescription.GetCertificate();

            if (localCertificate == null)
            {
                throw new ServiceResultException(StatusCodes.BadSecurityChecksFailed, "Application certificate is missing.");
            }

            // discover available endpoints of server.
            var getEndpointsRequest = new GetEndpointsRequest
            {
                EndpointUrl = this.endpointUrl,
                ProfileUris = new[] { TransportProfileUris.UaTcpTransport }
            };

            Console.WriteLine($"Discovering endpoints of '{getEndpointsRequest.EndpointUrl}'.");
            var getEndpointsResponse = await UaTcpDiscoveryClient.GetEndpointsAsync(getEndpointsRequest);

            var selectedEndpoint = getEndpointsResponse.Endpoints.OrderBy(e => e.SecurityLevel).Last();

            var           selectedTokenType = selectedEndpoint.UserIdentityTokens[0].TokenType;
            IUserIdentity selectedUserIdentity;

            switch (selectedTokenType)
            {
            case UserTokenType.UserName:
                selectedUserIdentity = new UserNameIdentity("root", "secret");
                break;

            case UserTokenType.Certificate:
                selectedUserIdentity = new X509Identity(localCertificate);
                break;

            default:
                selectedUserIdentity = new AnonymousIdentity();
                break;
            }

            var channel = new UaTcpSessionChannel(
                this.localDescription,
                localCertificate,
                selectedUserIdentity,
                selectedEndpoint,
                sessionTimeout: 10000);

            Console.WriteLine($"Creating session with endpoint '{channel.RemoteEndpoint.EndpointUrl}'.");
            Console.WriteLine($"SecurityPolicy: '{channel.RemoteEndpoint.SecurityPolicyUri}'.");
            Console.WriteLine($"SecurityMode: '{channel.RemoteEndpoint.SecurityMode}'.");
            await channel.OpenAsync();

            Console.WriteLine($"Activated session '{channel.SessionId}'.");

            // server should close session due to inactivity
            await Task.Delay(20000);

            // should throw exception
            var readRequest = new ReadRequest {
                NodesToRead = new[] { new ReadValueId {
                                          NodeId = NodeId.Parse(VariableIds.Server_ServerStatus_CurrentTime), AttributeId = AttributeIds.Value
                                      } }
            };
            await channel.ReadAsync(readRequest);

            Console.WriteLine($"Closing session '{channel.SessionId}'.");
            await channel.CloseAsync();
        }