示例#1
0
        /// <summary>
        /// Adds index ranges to the collection.
        /// </summary>
        private void AddIndexRanges(
            Node node,
            ReadValueIdCollection nodesToRead,
            params uint[] attributeIds)
        {
            if (attributeIds != null)
            {
                for (int ii = 0; ii < attributeIds.Length; ii++)
                {
                    ReadValueId nodeToRead = new ReadValueId();

                    nodeToRead.NodeId      = node.NodeId;
                    nodeToRead.AttributeId = attributeIds[ii];
                    nodeToRead.IndexRange  = "1:2";
                    nodeToRead.Handle      = node;

                    nodesToRead.Add(nodeToRead);

                    nodeToRead = new ReadValueId();

                    nodeToRead.NodeId      = node.NodeId;
                    nodeToRead.AttributeId = attributeIds[ii];
                    nodeToRead.IndexRange  = "10000000:20000000";
                    nodeToRead.Handle      = node;

                    nodesToRead.Add(nodeToRead);
                }
            }
        }
示例#2
0
        /// <summary>
        /// Adds index ranges to the collection.
        /// </summary>
        private void AddDataEncodings(
            Node node,
            ReadValueIdCollection nodesToRead,
            params uint[] attributeIds)
        {
            if (attributeIds != null)
            {
                for (int ii = 0; ii < attributeIds.Length; ii++)
                {
                    ReadValueId nodeToRead = new ReadValueId();

                    nodeToRead.NodeId       = node.NodeId;
                    nodeToRead.AttributeId  = attributeIds[ii];
                    nodeToRead.DataEncoding = BrowseNames.DefaultBinary;
                    nodeToRead.Handle       = node;

                    nodesToRead.Add(nodeToRead);

                    nodeToRead = new ReadValueId();

                    nodeToRead.NodeId       = node.NodeId;
                    nodeToRead.AttributeId  = attributeIds[ii];
                    nodeToRead.DataEncoding = BrowseNames.DefaultXml;
                    nodeToRead.Handle       = node;

                    nodesToRead.Add(nodeToRead);
                }
            }
        }
示例#3
0
        private void ReadMI_Click(object sender, EventArgs e)
        {
            try
            {
                // get the current session.
                Session session = Get <Session>(NodesTV.SelectedNode);

                if (session == null || !session.Connected)
                {
                    return;
                }

                // build list of nodes to read.
                ReadValueIdCollection valueIds = new ReadValueIdCollection();

                MonitoredItem monitoredItem = Get <MonitoredItem>(NodesTV.SelectedNode);

                if (monitoredItem != null)
                {
                    ReadValueId valueId = new ReadValueId();

                    valueId.NodeId       = monitoredItem.ResolvedNodeId;
                    valueId.AttributeId  = monitoredItem.AttributeId;
                    valueId.IndexRange   = monitoredItem.IndexRange;
                    valueId.DataEncoding = monitoredItem.Encoding;

                    valueIds.Add(valueId);
                }
                else
                {
                    Subscription subscription = Get <Subscription>(NodesTV.SelectedNode);

                    if (subscription != null)
                    {
                        foreach (MonitoredItem item in subscription.MonitoredItems)
                        {
                            ReadValueId valueId = new ReadValueId();

                            valueId.NodeId       = item.ResolvedNodeId;
                            valueId.AttributeId  = item.AttributeId;
                            valueId.IndexRange   = item.IndexRange;
                            valueId.DataEncoding = item.Encoding;

                            valueIds.Add(valueId);
                        }
                    }
                }

                // show form.
                new ReadDlg().Show(session, valueIds);
            }
            catch (Exception exception)
            {
                GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception);
            }
        }
示例#4
0
        /// <summary>
        /// 读取一个节点的指定属性
        /// </summary>
        /// <param name="nodeId"></param>
        /// <param name="attribute"></param>
        /// <returns></returns>
        private DataValue ReadNoteDataValueAttributes(NodeId nodeId, uint attribute)
        {
            NodeId sourceId = nodeId;
            ReadValueIdCollection nodesToRead = new ReadValueIdCollection();
            ReadValueId           nodeToRead  = new ReadValueId();

            nodeToRead.NodeId      = sourceId;
            nodeToRead.AttributeId = attribute;
            nodesToRead.Add(nodeToRead);
            int startOfProperties = nodesToRead.Count;
            // find all of the pror of the node.
            BrowseDescription nodeToBrowse1 = new BrowseDescription();

            nodeToBrowse1.NodeId          = sourceId;
            nodeToBrowse1.BrowseDirection = BrowseDirection.Forward;
            nodeToBrowse1.ReferenceTypeId = ReferenceTypeIds.HasProperty;
            nodeToBrowse1.IncludeSubtypes = true;
            nodeToBrowse1.NodeClassMask   = 0;
            nodeToBrowse1.ResultMask      = (uint)BrowseResultMask.All;
            BrowseDescriptionCollection nodesToBrowse = new BrowseDescriptionCollection();

            nodesToBrowse.Add(nodeToBrowse1);
            // fetch property references from the server.
            ReferenceDescriptionCollection references = FormUtils.Browse(CommonMethods.opcUaClient.Session, nodesToBrowse, false);

            if (references == null)
            {
                return(null);
            }
            for (int ii = 0; ii < references.Count; ii++)
            {
                // ignore external references.
                if (references[ii].NodeId.IsAbsolute)
                {
                    continue;
                }
                ReadValueId nodeToRead2 = new ReadValueId();
                nodeToRead2.NodeId      = (NodeId)references[ii].NodeId;
                nodeToRead2.AttributeId = Attributes.Value;
                nodesToRead.Add(nodeToRead2);
            }
            // read all values.
            DataValueCollection      results         = null;
            DiagnosticInfoCollection diagnosticInfos = null;

            CommonMethods.opcUaClient.Session.Read(
                null,
                0,
                TimestampsToReturn.Neither,
                nodesToRead,
                out results,
                out diagnosticInfos);
            ClientBase.ValidateResponse(results, nodesToRead);
            ClientBase.ValidateDiagnosticInfos(diagnosticInfos, nodesToRead);
            return(results[0]);
        }
示例#5
0
        /// <summary>读取一个节点的所有属性</summary>
        /// <param name="tag"></param>
        /// <returns></returns>
        //public OpcuaNodeAttribute[] ReadNoteAttributes(string tag)
        //{
        //    NodeId nodeId = new NodeId(tag);
        //    ReadValueIdCollection nodesToRead = new ReadValueIdCollection();
        //    for (uint index = 2; index <= 22U; ++index)
        //        nodesToRead.Add(new ReadValueId()
        //        {
        //            NodeId = nodeId,
        //            AttributeId = index
        //        });
        //    int count = nodesToRead.Count;
        //    BrowseDescription browseDescription = new BrowseDescription();
        //    browseDescription.NodeId = nodeId;
        //    browseDescription.BrowseDirection = BrowseDirection.Forward;
        //    browseDescription.ReferenceTypeId = ReferenceTypeIds.HasProperty;
        //    browseDescription.IncludeSubtypes = true;
        //    browseDescription.NodeClassMask = 0U;
        //    browseDescription.ResultMask = 63U;
        //    BrowseDescriptionCollection nodesToBrowse = new BrowseDescriptionCollection();
        //    nodesToBrowse.Add(browseDescription);
        //    ReferenceDescriptionCollection descriptionCollection = FormUtils.Browse(this.m_session, nodesToBrowse, false);
        //    if (descriptionCollection == null)
        //        return new OpcuaNodeAttribute[0];
        //    for (int index = 0; index < descriptionCollection.Count; ++index)
        //    {
        //        if (!descriptionCollection[index].NodeId.IsAbsolute)
        //            nodesToRead.Add(new ReadValueId()
        //            {
        //                NodeId = (NodeId)descriptionCollection[index].NodeId,
        //                AttributeId = 13U
        //            });
        //    }
        //    DataValueCollection results = (DataValueCollection)null;
        //    DiagnosticInfoCollection diagnosticInfos = (DiagnosticInfoCollection)null;
        //    this.m_session.Read((RequestHeader)null, 0.0, TimestampsToReturn.Neither, nodesToRead, out results, out diagnosticInfos);
        //    ClientBase.ValidateResponse((IList)results, (IList)nodesToRead);
        //    ClientBase.ValidateDiagnosticInfos(diagnosticInfos, (IList)nodesToRead);
        //    List<OpcNodeAttribute> opcNodeAttributeList = new List<OpcNodeAttribute>();
        //    for (int index = 0; index < results.Count; ++index)
        //    {
        //        OpcNodeAttribute opcNodeAttribute1 = new OpcNodeAttribute();
        //        BuiltInType builtInType;
        //        if (index < count)
        //        {
        //            if (!(results[index].StatusCode == 2150957056U))
        //            {
        //                opcNodeAttribute1.Name = Attributes.GetBrowseName(nodesToRead[index].AttributeId);
        //                if (StatusCode.IsBad(results[index].StatusCode))
        //                {
        //                    opcNodeAttribute1.Type = Utils.Format("{0}", (object)Attributes.GetDataTypeId(nodesToRead[index].AttributeId));
        //                    opcNodeAttribute1.Value = (object)Utils.Format("{0}", (object)results[index].StatusCode);
        //                }
        //                else
        //                {
        //                    TypeInfo typeInfo = TypeInfo.Construct(results[index].Value);
        //                    OpcNodeAttribute opcNodeAttribute2 = opcNodeAttribute1;
        //                    builtInType = typeInfo.BuiltInType;
        //                    string str = builtInType.ToString();
        //                    opcNodeAttribute2.Type = str;
        //                    if (typeInfo.ValueRank >= 0)
        //                        opcNodeAttribute1.Type += "[]";
        //                    opcNodeAttribute1.Value = results[index].Value;
        //                }
        //            }
        //            else
        //                continue;
        //        }
        //        else if (!(results[index].StatusCode == 2150891520U))
        //        {
        //            opcNodeAttribute1.Name = Utils.Format("{0}", (object)descriptionCollection[index - count]);
        //            if (StatusCode.IsBad(results[index].StatusCode))
        //            {
        //                opcNodeAttribute1.Type = string.Empty;
        //                opcNodeAttribute1.Value = (object)Utils.Format("{0}", (object)results[index].StatusCode);
        //            }
        //            else
        //            {
        //                TypeInfo typeInfo = TypeInfo.Construct(results[index].Value);
        //                OpcNodeAttribute opcNodeAttribute2 = opcNodeAttribute1;
        //                builtInType = typeInfo.BuiltInType;
        //                string str = builtInType.ToString();
        //                opcNodeAttribute2.Type = str;
        //                if (typeInfo.ValueRank >= 0)
        //                    opcNodeAttribute1.Type += "[]";
        //                opcNodeAttribute1.Value = results[index].Value;
        //            }
        //        }
        //        else
        //            continue;
        //        opcNodeAttributeList.Add(opcNodeAttribute1);
        //    }
        //    return opcNodeAttributeList.ToArray();
        //}

        /// <summary>读取一个节点的所有属性</summary>
        /// <param name="tag"></param>
        /// <returns></returns>
        public DataValue[] ReadNoteDataValueAttributes(string tag)
        {
            NodeId nodeId = new NodeId(tag);
            ReadValueIdCollection nodesToRead = new ReadValueIdCollection();

            for (uint index = 1; index <= 22U; ++index)
            {
                nodesToRead.Add(new ReadValueId()
                {
                    NodeId      = nodeId,
                    AttributeId = index
                });
            }
            int count = nodesToRead.Count;
            BrowseDescription browseDescription = new BrowseDescription();

            browseDescription.NodeId          = nodeId;
            browseDescription.BrowseDirection = BrowseDirection.Forward;
            browseDescription.ReferenceTypeId = ReferenceTypeIds.HasProperty;
            browseDescription.IncludeSubtypes = true;
            browseDescription.NodeClassMask   = 0U;
            browseDescription.ResultMask      = 63U;
            BrowseDescriptionCollection nodesToBrowse = new BrowseDescriptionCollection();

            nodesToBrowse.Add(browseDescription);
            ReferenceDescriptionCollection descriptionCollection = FormUtils.Browse(this.m_session, nodesToBrowse, false);

            if (descriptionCollection == null)
            {
                return(new DataValue[0]);
            }
            for (int index = 0; index < descriptionCollection.Count; ++index)
            {
                if (!descriptionCollection[index].NodeId.IsAbsolute)
                {
                    nodesToRead.Add(new ReadValueId()
                    {
                        NodeId      = (NodeId)descriptionCollection[index].NodeId,
                        AttributeId = 13U
                    });
                }
            }
            DataValueCollection      results         = (DataValueCollection)null;
            DiagnosticInfoCollection diagnosticInfos = (DiagnosticInfoCollection)null;

            this.m_session.Read((RequestHeader)null, 0.0, TimestampsToReturn.Neither, nodesToRead, out results, out diagnosticInfos);
            ClientBase.ValidateResponse((IList)results, (IList)nodesToRead);
            ClientBase.ValidateDiagnosticInfos(diagnosticInfos, (IList)nodesToRead);
            return(results.ToArray());
        }
示例#6
0
        /// <summary>
        /// 0:NodeClass  1:Value  2:AccessLevel  3:DisplayName  4:Description
        /// </summary>
        /// <param name="nodeIds"></param>
        /// <returns></returns>
        private DataValue[] ReadOneNodeFiveAttributes(List <NodeId> nodeIds)
        {
            ReadValueIdCollection nodesToRead = new ReadValueIdCollection();

            foreach (var nodeId in nodeIds)
            {
                NodeId sourceId = nodeId;
                nodesToRead.Add(new ReadValueId()
                {
                    NodeId      = sourceId,
                    AttributeId = Attributes.NodeClass
                });
                nodesToRead.Add(new ReadValueId()
                {
                    NodeId      = sourceId,
                    AttributeId = Attributes.Value
                });
                nodesToRead.Add(new ReadValueId()
                {
                    NodeId      = sourceId,
                    AttributeId = Attributes.AccessLevel
                });
                nodesToRead.Add(new ReadValueId()
                {
                    NodeId      = sourceId,
                    AttributeId = Attributes.DisplayName
                });
                nodesToRead.Add(new ReadValueId()
                {
                    NodeId      = sourceId,
                    AttributeId = Attributes.Description
                });
            }

            // read all values.
            m_OpcUaClient.Session.Read(
                null,
                0,
                TimestampsToReturn.Neither,
                nodesToRead,
                out DataValueCollection results,
                out DiagnosticInfoCollection diagnosticInfos);

            ClientBase.ValidateResponse(results, nodesToRead);
            ClientBase.ValidateDiagnosticInfos(diagnosticInfos, nodesToRead);

            return(results.ToArray());
        }
        private DataValueCollection Read_Value(string node)
        {
            //Read variables in the server’s address space
            ReadValueIdCollection nodesToRead = new ReadValueIdCollection();
            ReadValueId           nodeToRead  = new ReadValueId();

            nodeToRead.NodeId      = node;
            nodeToRead.AttributeId = Attributes.Value;
            nodesToRead.Add(nodeToRead);

            DataValueCollection      results         = null;
            DiagnosticInfoCollection diagnosticInfos = null;

            m_session.Read(
                null,
                0,
                TimestampsToReturn.Neither,
                nodesToRead,
                out results,
                out diagnosticInfos);

            ClientBase.ValidateResponse(results, nodesToRead);
            ClientBase.ValidateDiagnosticInfos(diagnosticInfos, nodesToRead);

            return(results);
        }
示例#8
0
        /// <summary>
        /// read specified node data from server
        /// <summary>
        private object Read_Node(NodeId nodeid)
        {
            DataValueCollection      results;
            DiagnosticInfoCollection diagnosticInfos;
            ReadValueIdCollection    valuesToRead = new ReadValueIdCollection();

            ReadValueId valueToRead = new ReadValueId();

            valueToRead.NodeId      = nodeid;
            valueToRead.AttributeId = Attributes.Value;

            valuesToRead.Add(valueToRead);

            m_design_session.Read(
                null,
                0,
                TimestampsToReturn.Neither,
                valuesToRead,
                out results,
                out diagnosticInfos);

            object val           = results.Last().Value;
            string message_value = String.Format("Read from node: '{0}'({1}) = '{2}'", "", nodeid.ToString(), val);

            if (!StatusCode.IsGood(results.Last().StatusCode))
            {
                string message_status = String.Format("Error! Read from node ({0}) status code: {1}", nodeid.ToString(), results.Last().StatusCode);
                Debug.WriteLine(message_status);
            }
            return(val);
        }
示例#9
0
        private void ReadMI_Click(object sender, EventArgs e)
        {
            try {
                if (NodesTV.SelectedNode == null)
                {
                    return;
                }

                ReferenceDescription reference = NodesTV.SelectedNode.Tag as ReferenceDescription;

                if (reference == null || (reference.NodeClass & (NodeClass.Variable | NodeClass.VariableType)) == 0)
                {
                    return;
                }

                Session session = m_browser.Session;

                // build list of nodes to read.
                ReadValueIdCollection valueIds = new ReadValueIdCollection();

                ReadValueId valueId = new ReadValueId();

                valueId.NodeId       = (NodeId)reference.NodeId;
                valueId.AttributeId  = Attributes.Value;
                valueId.IndexRange   = null;
                valueId.DataEncoding = null;

                valueIds.Add(valueId);

                // show form.
                new ReadDlg().Show(session, valueIds);
            } catch (Exception exception) {
                GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception);
            }
        }
示例#10
0
        /// <summary>read several value nodes from server</summary>
        /// <param name="Tags">all Tags</param>
        /// <returns></returns>
        public IEnumerable <DataValue> ReadNodes(string[] Tags)
        {
            ReadValueIdCollection nodesToRead = new ReadValueIdCollection();

            for (int i = 0; i < Tags.Length; ++i)
            {
                nodesToRead.Add(new ReadValueId()
                {
                    NodeId      = new NodeId(Tags[i]),
                    AttributeId = 13U
                });
            }
            DataValueCollection      results;
            DiagnosticInfoCollection diagnosticInfos;

            this.m_session.Read((RequestHeader)null, 0.0, TimestampsToReturn.Neither, nodesToRead, out results, out diagnosticInfos);
            ClientBase.ValidateResponse((IList)results, (IList)nodesToRead);
            ClientBase.ValidateDiagnosticInfos(diagnosticInfos, (IList)nodesToRead);
            foreach (DataValue dataValue in (List <DataValue>)results)
            {
                DataValue v = dataValue;
                yield return(v);

                v = (DataValue)null;
            }
            List <DataValue> .Enumerator enumerator = new List <DataValue> .Enumerator();
        }
示例#11
0
        /// <summary>Read a tag asynchronously</summary>
        /// <typeparam name="T">The type of tag to read</typeparam>
        /// <param name="tag">The fully-qualified identifier of the tag. You can specify a subfolder by using a comma delimited name.
        /// E.g: the tag `foo.bar` reads the tag `bar` on the folder `foo`</param>
        /// <returns>The value retrieved from the OPC</returns>
        public Task <T> ReadNodeAsync <T>(string tag)
        {
            ReadValueIdCollection valueIdCollection = new ReadValueIdCollection();

            valueIdCollection.Add(new ReadValueId()
            {
                NodeId      = new NodeId(tag),
                AttributeId = 13U
            });
            ReadValueIdCollection    nodesToRead          = valueIdCollection;
            TaskCompletionSource <T> taskCompletionSource = new TaskCompletionSource <T>();

            this.m_session.BeginRead((RequestHeader)null, 0.0, TimestampsToReturn.Neither, nodesToRead, (AsyncCallback)(ar =>
            {
                DataValueCollection results;
                DiagnosticInfoCollection diagnosticInfos;
                ResponseHeader responseHeader = this.m_session.EndRead(ar, out results, out diagnosticInfos);
                try
                {
                    this.CheckReturnValue(responseHeader.ServiceResult);
                    this.CheckReturnValue(results[0].StatusCode);
                    taskCompletionSource.TrySetResult((T)results[0].Value);
                }
                catch (Exception ex)
                {
                    taskCompletionSource.TrySetException(ex);
                }
            }), (object)null);
            return(taskCompletionSource.Task);
        }
示例#12
0
        /// <summary>
        /// Gets the supported key formats.
        /// </summary>
        /// <param name="publicKeyFormats">The public key formats.</param>
        /// <param name="privateKeyFormats">The private key formats.</param>
        /// <exception cref="System.InvalidOperationException">Connection to server is not active.</exception>
        public string[] GetSupportedKeyFormats()
        {
            if (!IsConnected)
            {
                Connect();
            }

            ReadValueIdCollection nodesToRead = new ReadValueIdCollection();

            nodesToRead.Add(new ReadValueId()
            {
                NodeId      = ExpandedNodeId.ToNodeId(Opc.Ua.VariableIds.ServerConfiguration_SupportedPrivateKeyFormats, m_session.NamespaceUris),
                AttributeId = Attributes.Value
            });

            DataValueCollection      results         = null;
            DiagnosticInfoCollection diagnosticInfos = null;

            m_session.Read(
                null,
                0,
                TimestampsToReturn.Neither,
                nodesToRead,
                out results,
                out diagnosticInfos);

            ClientBase.ValidateResponse(results, nodesToRead);
            ClientBase.ValidateDiagnosticInfos(diagnosticInfos, nodesToRead);

            return(results[0].GetValue <string[]>(null));
        }
示例#13
0
        /// <summary>
        /// read several value nodes from server
        /// </summary>
        /// <param name="tags">所以的节点数组信息</param>
        /// <returns>all values</returns>
        public List <T> ReadNodes <T>(string[] tags)
        {
            List <T> result = new List <T>( );
            ReadValueIdCollection nodesToRead = new ReadValueIdCollection( );

            for (int i = 0; i < tags.Length; i++)
            {
                nodesToRead.Add(new ReadValueId( )
                {
                    NodeId      = new NodeId(tags[i]),
                    AttributeId = Attributes.Value
                });
            }

            // 读取当前的值
            m_session.Read(
                null,
                0,
                TimestampsToReturn.Neither,
                nodesToRead,
                out DataValueCollection results,
                out DiagnosticInfoCollection diagnosticInfos);

            ClientBase.ValidateResponse(results, nodesToRead);
            ClientBase.ValidateDiagnosticInfos(diagnosticInfos, nodesToRead);

            foreach (var item in results)
            {
                result.Add((T)item.Value);
            }
            return(result);
        }
示例#14
0
        /// <summary>
        /// read several value nodes from server
        /// </summary>
        /// <param name="nodeIds">all NodeIds</param>
        /// <returns>all values</returns>
        public List <DataValue> ReadNodes(NodeId[] nodeIds)
        {
            ReadValueIdCollection nodesToRead = new ReadValueIdCollection( );

            for (int i = 0; i < nodeIds.Length; i++)
            {
                nodesToRead.Add(new ReadValueId( )
                {
                    NodeId      = nodeIds[i],
                    AttributeId = Attributes.Value
                });
            }

            // 读取当前的值
            m_session.Read(
                null,
                0,
                TimestampsToReturn.Neither,
                nodesToRead,
                out DataValueCollection results,
                out DiagnosticInfoCollection diagnosticInfos);

            ClientBase.ValidateResponse(results, nodesToRead);
            ClientBase.ValidateDiagnosticInfos(diagnosticInfos, nodesToRead);

            return(results.ToList( ));
        }
        private void retriveNodeIdDataType(ref List <CommandActions> commandActionList)
        {
            ReadValueIdCollection nodesForRead = new ReadValueIdCollection();

            foreach (var msgCmd in commandActionList)
            {
                foreach (var action in msgCmd.actions)
                {
                    ReadValueId nofeForRead = new ReadValueId();
                    nofeForRead.AttributeId = Attributes.Value;
                    nofeForRead.NodeId      = action.nodeId;
                    nodesForRead.Add(nofeForRead);
                }
            }
            DataValueCollection dataValueList = _uaClient.Read(nodesForRead);

            int index = 0;

            foreach (var msgCmd in commandActionList)
            {
                foreach (var action in msgCmd.actions)
                {
                    if (dataValueList[index] != null)
                    {
                        action.dataType = dataValueList[index].WrappedValue.TypeInfo.BuiltInType;
                    }
                    index++;
                }
            }
        }
示例#16
0
        /// <summary>
        /// Reads the value through the passed in session from a remote server.
        /// </summary>
        /// <param name="session"></param>
        /// <param name="requestHeader"></param>
        /// <param name="operations"></param>
        /// <param name="skipAttributeIdInvalid"></param>
        /// <param name="traceOnly"></param>
        /// <returns></returns>
        public async Task <DataValue> ReadValueAsync(Session session,
                                                     RequestHeader requestHeader, List <OperationResultModel> operations,
                                                     bool skipAttributeIdInvalid, bool traceOnly)
        {
            var readValueCollection = new ReadValueIdCollection {
                new ReadValueId {
                    NodeId      = LocalId,
                    AttributeId = Attributes.Value
                }
            };

            if (NodeClass == NodeClass.Unspecified)
            {
                readValueCollection.Add(new ReadValueId {
                    NodeId      = LocalId,
                    AttributeId = Attributes.NodeClass
                });
            }
            // Update value
            await ReadAsync(session, requestHeader, readValueCollection, operations,
                            skipAttributeIdInvalid, traceOnly);

            if (operations == null &&
                NodeClass != NodeClass.VariableType && NodeClass != NodeClass.Variable)
            {
                throw new InvalidOperationException(
                          "Node is not a variable or variable type node and does not have value");
            }
            return(_attributes[Attributes.Value]);
        }
示例#17
0
 public string VariableRead(string node)
 {
     try
     {
         DataValueCollection      values          = null;
         DiagnosticInfoCollection diagnosticInfos = null;
         ReadValueIdCollection    nodesToRead     = new ReadValueIdCollection();
         ReadValueId valueId = new ReadValueId();
         valueId.NodeId       = new NodeId(node);
         valueId.AttributeId  = Attributes.Value;
         valueId.IndexRange   = null;
         valueId.DataEncoding = null;
         nodesToRead.Add(valueId);
         ResponseHeader responseHeader = session.Read(null, 0, TimestampsToReturn.Both, nodesToRead, out values, out diagnosticInfos);
         string         value          = "";
         if (values[0].Value != null)
         {
             var rawValue = values[0].WrappedValue.ToString();
             value = rawValue.Replace("|", "\r\n").Replace("{", "").Replace("}", "");
         }
         return(value);
     }
     catch
     {
         return(null);
     }
 }
示例#18
0
        /// <summary>
        /// read several value nodes from server
        /// </summary>
        /// <param name="Tags">all Tags</param>
        /// <returns></returns>
        public IEnumerable <DataValue> ReadNodes(string[] Tags)
        {
            ReadValueIdCollection nodesToRead = new ReadValueIdCollection();

            for (int i = 0; i < Tags.Length; i++)
            {
                nodesToRead.Add(new ReadValueId()
                {
                    NodeId      = new NodeId(Tags[i]),
                    AttributeId = Attributes.Value
                });
            }

            // 读取当前的值
            m_session.Read(
                null,
                0,
                TimestampsToReturn.Neither,
                nodesToRead,
                out DataValueCollection results,
                out DiagnosticInfoCollection diagnosticInfos);

            ClientBase.ValidateResponse(results, nodesToRead);
            ClientBase.ValidateDiagnosticInfos(diagnosticInfos, nodesToRead);

            foreach (var v in results)
            {
                yield return(v);
            }
        }
        public async Task <ActionResult> VariableWriteFetch(string jstreeNode)
        {
            string[] delimiter       = { "__$__" };
            string[] jstreeNodeSplit = jstreeNode.Split(delimiter, 3, StringSplitOptions.None);
            string   node;
            var      actionResult = "";

            if (jstreeNodeSplit.Length == 1)
            {
                node = jstreeNodeSplit[0];
            }
            else
            {
                node = jstreeNodeSplit[1];
            }

            bool retry = true;

            while (true)
            {
                try
                {
                    DataValueCollection      values          = null;
                    DiagnosticInfoCollection diagnosticInfos = null;
                    ReadValueIdCollection    nodesToRead     = new ReadValueIdCollection();
                    ReadValueId valueId = new ReadValueId();
                    valueId.NodeId       = new NodeId(node);
                    valueId.AttributeId  = Attributes.Value;
                    valueId.IndexRange   = null;
                    valueId.DataEncoding = null;
                    nodesToRead.Add(valueId);
                    Session session = await OpcSessionHelper.Instance.GetSessionAsync(Session.SessionID, (string)Session["EndpointUrl"]);

                    ResponseHeader responseHeader = session.Read(null, 0, TimestampsToReturn.Both, nodesToRead, out values,
                                                                 out diagnosticInfos);
                    if (values[0].Value != null)
                    {
                        if (values[0].WrappedValue.ToString().Length > 30)
                        {
                            actionResult  = values[0].WrappedValue.ToString().Substring(0, 30);
                            actionResult += "...";
                        }
                        else
                        {
                            actionResult = values[0].WrappedValue.ToString();
                        }
                    }
                    return(Content(actionResult));
                }
                catch (Exception exception)
                {
                    if (!retry)
                    {
                        return(Content(CreateOpcExceptionActionString(exception)));
                    }
                    retry = false;
                }
            }
        }
示例#20
0
        /// <summary>
        /// Reads the application description from the GDS.
        /// </summary>
        private ApplicationDescription Read(NodeId nodeId)
        {
            NamespaceTable wellKnownNamespaceUris = new NamespaceTable();

            wellKnownNamespaceUris.Append(Namespaces.OpcUaGds);

            string[] browsePaths = new string[] {
                "1:ApplicationName", "1:ApplicationType", "1:ApplicationUri", "1:ProductUri", "1:GatewayServerUri",
                "1:DiscoveryUrls"
            };

            List <NodeId> propertyIds = ClientUtils.TranslateBrowsePaths(
                ServerCTRL.Session,
                nodeId,
                wellKnownNamespaceUris,
                browsePaths);

            ReadValueIdCollection nodesToRead = new ReadValueIdCollection();

            foreach (NodeId propertyId in propertyIds)
            {
                ReadValueId nodeToRead = new ReadValueId();
                nodeToRead.NodeId      = propertyId;
                nodeToRead.AttributeId = Attributes.Value;
                nodesToRead.Add(nodeToRead);
            }

            DataValueCollection      results         = null;
            DiagnosticInfoCollection diagnosticInfos = null;

            ServerCTRL.Session.Read(
                null,
                0,
                TimestampsToReturn.Neither,
                nodesToRead,
                out results,
                out diagnosticInfos);

            ClientBase.ValidateResponse(results, nodesToRead);
            ClientBase.ValidateDiagnosticInfos(diagnosticInfos, nodesToRead);

            ApplicationDescription application = new ApplicationDescription();

            application.ApplicationName  = results[0].GetValue <LocalizedText>(null);
            application.ApplicationType  = (ApplicationType)results[1].GetValue <int>((int)ApplicationType.Server);
            application.ApplicationUri   = results[2].GetValue <string>(null);
            application.ProductUri       = results[3].GetValue <string>(null);
            application.GatewayServerUri = results[4].GetValue <string>(null);

            string[] discoveryUrls = results[5].GetValue <string[]>(null);

            if (discoveryUrls != null)
            {
                application.DiscoveryUrls = new StringCollection(discoveryUrls);
            }

            return(application);
        }
示例#21
0
        /// <summary>
        /// Reads the attributes for the node.
        /// </summary>
        public Dictionary <string, string> ReadAttributes(NodeId nodeId)
        {
            Dictionary <string, string> re = new Dictionary <string, string>();

            if (NodeId.IsNull(nodeId))
            {
                return(re);
            }

            // build list of attributes to read.
            ReadValueIdCollection nodesToRead = new ReadValueIdCollection();

            foreach (uint attributeId in Attributes.GetIdentifiers())
            {
                ReadValueId nodeToRead = new ReadValueId();
                nodeToRead.NodeId      = nodeId;
                nodeToRead.AttributeId = attributeId;
                nodesToRead.Add(nodeToRead);
            }

            // read the attributes.
            DataValueCollection      results         = null;
            DiagnosticInfoCollection diagnosticInfos = null;

            m_session.Read(
                null,
                0,
                TimestampsToReturn.Neither,
                nodesToRead,
                out results,
                out diagnosticInfos);

            ClientBase.ValidateResponse(results, nodesToRead);
            ClientBase.ValidateDiagnosticInfos(diagnosticInfos, nodesToRead);

            // add the results to the display.
            for (int ii = 0; ii < results.Count; ii++)
            {
                // check for error.
                if (StatusCode.IsBad(results[ii].StatusCode))
                {
                    if (results[ii].StatusCode == StatusCodes.BadAttributeIdInvalid)
                    {
                        continue;
                    }
                }

                // add the metadata for the attribute.
                uint   attributeId = nodesToRead[ii].AttributeId;
                string skey        = Attributes.GetBrowseName(attributeId);

                string sval = GetAttributeDisplayText(m_session, attributeId, results[ii].WrappedValue);

                re.Add(skey, sval);
            }

            return(re);
        }
示例#22
0
        /// <summary>
        /// Adds the attributes to the control.
        /// </summary>
        private void AddAttributes()
        {
            // build list of attributes to read.
            ReadValueIdCollection nodesToRead = new ReadValueIdCollection();

            foreach (uint attributeId in Attributes.GetIdentifiers())
            {
                ReadValueId valueId = new ReadValueId();

                valueId.NodeId       = m_nodeId;
                valueId.AttributeId  = attributeId;
                valueId.IndexRange   = null;
                valueId.DataEncoding = null;

                nodesToRead.Add(valueId);
            }

            // read attributes.
            DataValueCollection      values;
            DiagnosticInfoCollection diagnosticInfos;

            m_session.Read(
                null,
                0,
                TimestampsToReturn.Neither,
                nodesToRead,
                out values,
                out diagnosticInfos);

            ClientBase.ValidateResponse(values, nodesToRead);
            ClientBase.ValidateDiagnosticInfos(diagnosticInfos, nodesToRead);

            // update control.
            for (int ii = 0; ii < nodesToRead.Count; ii++)
            {
                // check if node supports attribute.
                if (values[ii].StatusCode == StatusCodes.BadAttributeIdInvalid)
                {
                    continue;
                }

                NodeField field = new NodeField();

                field.ValueId    = nodesToRead[ii];
                field.Name       = Attributes.GetBrowseName(nodesToRead[ii].AttributeId);
                field.Value      = values[ii].Value;
                field.StatusCode = values[ii].StatusCode;

                if (diagnosticInfos != null && diagnosticInfos.Count > ii)
                {
                    field.DiagnosticInfo = diagnosticInfos[ii];
                }

                AddItem(field, "SimpleItem", -1);
            }
        }
        /// <summary>
        /// Add attribute for a particular node to ReadValueCollection
        /// </summary>
        /// <param name="node"></param>
        /// <param name="attributeId"></param>
        /// <param name="nodesToRead"></param>
        private void addAttribute(NodeId node, uint attributeId, ReadValueIdCollection nodesToRead)
        {
            // Get NodeId from tree node .
            ReadValueId attributeToRead = new ReadValueId();

            attributeToRead.NodeId      = node;
            attributeToRead.AttributeId = attributeId;
            attributeToRead.UserData    = Attributes.GetDisplayText(attributeId);
            nodesToRead.Add(attributeToRead);
        }
        /// <summary>
        /// Add attribute for a particular node to ReadValueCollection
        /// </summary>
        /// <param name="node"></param>
        /// <param name="attributeId"></param>
        /// <param name="nodesToRead"></param>
        private void addAttribute(NodeId node, uint attributeId, ReadValueIdCollection nodesToRead)
        {
            // Get NodeId from tree node .
            ReadValueId attributeToRead = new ReadValueId();

            attributeToRead.NodeId      = node;
            attributeToRead.AttributeId = attributeId;
            attributeToRead.Handle      = m_Server.attributeIdToString(attributeId);
            nodesToRead.Add(attributeToRead);
        }
示例#25
0
        public LuaTable read(LuaTable ids)
        {
            var key = "__opcua__tmp";

            lua.NewTable(key);
            var tmp = lua[key] as LuaTable;

            lua[key] = null;

            if (this.session == null)
            {
                return(tmp);
            }

            var items = new ReadValueIdCollection();

            foreach (var k in ids.Keys)
            {
                var id = ids[k].ToString();

                if (string.IsNullOrEmpty(id))
                {
                    continue;
                }

                items.Add(new ReadValueId()
                {
                    NodeId       = new NodeId(id),
                    AttributeId  = Attributes.Value,
                    IndexRange   = null,
                    DataEncoding = null,
                });
            }

            var results         = new DataValueCollection();
            var diagnosticInfos = new DiagnosticInfoCollection();

            this.session.Read(
                null,
                0,
                TimestampsToReturn.Both,
                items,
                out results,
                out diagnosticInfos
                );

            for (int i = 0; i < items.Count; i++)
            {
                var id    = items[i].NodeId.ToString();
                var value = results[i].Value;
                tmp[id] = value;
            }

            return(tmp);
        }
示例#26
0
        /// <summary>
        /// Read Values of NodeIds, determine types, write back new random values.
        /// </summary>
        /// <param name="testSet">The nodeIds to modify.</param>
        private void UpdateValues(NodeId[] testSet)
        {
            // Read values
            var requestHeader = m_requestHeader;
            var nodesToRead   = new ReadValueIdCollection();

            foreach (NodeId nodeId in testSet)
            {
                nodesToRead.Add(new ReadValueId()
                {
                    NodeId = nodeId, AttributeId = Attributes.Value
                });
            }
            var response = m_server.Read(requestHeader, kMaxAge, TimestampsToReturn.Neither, nodesToRead,
                                         out var readDataValues, out var diagnosticInfos);

            ServerFixtureUtils.ValidateResponse(response);
            ServerFixtureUtils.ValidateDiagnosticInfos(diagnosticInfos, readDataValues);
            Assert.AreEqual(testSet.Length, readDataValues.Count);

            var modifiedValues = new DataValueCollection();

            foreach (var dataValue in readDataValues)
            {
                var typeInfo = TypeInfo.Construct(dataValue.Value);
                Assert.IsNotNull(typeInfo);
                var value = m_generator.GetRandom(typeInfo.BuiltInType);
                modifiedValues.Add(new DataValue()
                {
                    WrappedValue = new Variant(value)
                });
            }

            int ii           = 0;
            var nodesToWrite = new WriteValueCollection();

            foreach (NodeId nodeId in testSet)
            {
                nodesToWrite.Add(new WriteValue()
                {
                    NodeId = nodeId, AttributeId = Attributes.Value, Value = modifiedValues[ii]
                });
                ii++;
            }

            // Write Nodes
            requestHeader.Timestamp = DateTime.UtcNow;
            response = m_server.Write(requestHeader, nodesToWrite,
                                      out var writeDataValues, out diagnosticInfos);
            ServerFixtureUtils.ValidateResponse(response);
            ServerFixtureUtils.ValidateDiagnosticInfos(diagnosticInfos, writeDataValues);
        }
示例#27
0
        /// <summary>
        /// Handles a read request.
        /// </summary>
        public List <ServiceResult> Read(List <ReadRequest> requests)
        {
            if (m_session == null)
            {
                throw new ServiceResultException(StatusCodes.BadCommunicationError);
            }

            ReadValueIdCollection valuesToRead = new ReadValueIdCollection();

            for (int ii = 0; ii < requests.Count; ii++)
            {
                ReadValueId valueToRead = new ReadValueId();
                valueToRead.NodeId       = ExpandedNodeId.ToNodeId(requests[ii].RemoteId, m_session.NamespaceUris);
                valueToRead.AttributeId  = requests[ii].ReadValueId.AttributeId;
                valueToRead.IndexRange   = requests[ii].ReadValueId.IndexRange;
                valueToRead.DataEncoding = requests[ii].ReadValueId.DataEncoding;
                valuesToRead.Add(valueToRead);
            }

            DataValueCollection      results         = null;
            DiagnosticInfoCollection diagnosticInfos = null;

            ResponseHeader responseHeader = m_session.Read(
                null,
                0,
                TimestampsToReturn.Both,
                valuesToRead,
                out results,
                out diagnosticInfos);

            Session.ValidateResponse(results, valuesToRead);
            Session.ValidateDiagnosticInfos(diagnosticInfos, valuesToRead);

            List <ServiceResult> errors = new List <ServiceResult>();

            for (int ii = 0; ii < requests.Count; ii++)
            {
                requests[ii].Value = results[ii];

                if (results[ii].StatusCode != StatusCodes.Good)
                {
                    errors.Add(new ServiceResult(results[ii].StatusCode, ii, diagnosticInfos, responseHeader.StringTable));
                }
                else
                {
                    errors.Add(null);
                }
            }

            return(errors);
        }
示例#28
0
        /// <summary>
        /// Reads the values for a set of variables.
        /// </summary>
        static void Read(Session session)
        {
            IList <NodeOfInterest> results = GetNodeIds(session, Opc.Ua.Objects.ObjectsFolder,
                                                        VariableBrowsePaths.ToArray());
            // build list of nodes to read.
            ReadValueIdCollection nodesToRead = new ReadValueIdCollection();

            for (int ii = 0; ii < results.Count; ii++)
            {
                ReadValueId nodeToRead = new ReadValueId();

                nodeToRead.NodeId      = results[ii].NodeId;
                nodeToRead.AttributeId = Attributes.Value;

                nodesToRead.Add(nodeToRead);
            }

            // read values.
            DataValueCollection      values;
            DiagnosticInfoCollection diagnosticInfos;

            ResponseHeader responseHeader = session.Read(
                null,
                0,
                TimestampsToReturn.Both,
                nodesToRead,
                out values,
                out diagnosticInfos);

            // verify that the server returned the correct number of results.
            Session.ValidateResponse(values, nodesToRead);
            Session.ValidateDiagnosticInfos(diagnosticInfos, nodesToRead);

            // process results.
            for (int ii = 0; ii < values.Count; ii++)
            {
                // check for error.
                if (StatusCode.IsBad(values[ii].StatusCode))
                {
                    ServiceResult result =
                        Session.GetResult(values[ii].StatusCode, ii, diagnosticInfos, responseHeader);
                    Console.WriteLine("Read result for {0}: {1}", VariableBrowsePaths[ii], result.ToLongString());
                    continue;
                }

                // write value.
                Console.WriteLine("{0}: V={1}, Q={2}, SrvT={3}, SrcT={4}", nodesToRead[ii].NodeId,
                                  values[ii].Value.ToString(),
                                  values[ii].StatusCode.ToString(), values[ii].ServerTimestamp, values[ii].SourceTimestamp);
            }
        }
        /// <summary>
        /// Samples the values of the items.
        /// </summary>
        private void DoSample(object state)
        {
            try
            {
                List <ISampledDataChangeMonitoredItem> items = state as List <ISampledDataChangeMonitoredItem>;

                // read values for all enabled items.
                if (items != null && items.Count > 0)
                {
                    ReadValueIdCollection itemsToRead = new ReadValueIdCollection(items.Count);
                    DataValueCollection   values      = new DataValueCollection(items.Count);
                    List <ServiceResult>  errors      = new List <ServiceResult>(items.Count);

                    // allocate space for results.
                    for (int ii = 0; ii < items.Count; ii++)
                    {
                        ReadValueId readValueId = items[ii].GetReadValueId();
                        readValueId.Processed = false;
                        itemsToRead.Add(readValueId);

                        values.Add(null);
                        errors.Add(null);
                    }

                    OperationContext context = new OperationContext(m_session, m_diagnosticsMask);

                    // read values.
                    m_nodeManager.Read(
                        context,
                        0,
                        itemsToRead,
                        values,
                        errors);

                    // update monitored items.
                    for (int ii = 0; ii < items.Count; ii++)
                    {
                        if (values[ii] == null)
                        {
                            values[ii] = new DataValue(StatusCodes.BadInternalError, DateTime.UtcNow);
                        }

                        items[ii].QueueValue(values[ii], errors[ii]);
                    }
                }
            }
            catch (Exception e)
            {
                Utils.Trace(e, "Server: Unexpected error sampling values.");
            }
        }
示例#30
0
        private static ReadValueIdCollection CreateReadValueIdCollection(IEnumerable <DataItem> OPCItems)
        {
            ReadValueIdCollection nodesToRead = new ReadValueIdCollection();

            foreach (DataItem di in OPCItems)
            {
                ReadValueId nodeToRead = new ReadValueId();
                nodeToRead.NodeId      = di.Tag;
                nodeToRead.AttributeId = Attributes.Value;

                nodesToRead.Add(nodeToRead);
            }
            return(nodesToRead);
        }
示例#31
0
        /// <summary>
        /// Prompts the user to enter a value to write.
        /// </summary>
        /// <param name="session">The session to use.</param>
        /// <param name="nodeId">The identifier for the node to write to.</param>
        /// <param name="attributeId">The attribute being written.</param>
        /// <returns>True if successful. False if the operation was cancelled.</returns>
        public bool ShowDialog(Session session, NodeId nodeId, uint attributeId)
        {
            m_session = session;
            m_nodeId  = nodeId;
            m_attributeId = attributeId;

            ReadValueId nodeToRead = new ReadValueId();
            nodeToRead.NodeId = nodeId;
            nodeToRead.AttributeId = attributeId;

            ReadValueIdCollection nodesToRead = new ReadValueIdCollection();
            nodesToRead.Add(nodeToRead);
            
            // read current value.
            DataValueCollection results = null;
            DiagnosticInfoCollection diagnosticInfos = null;

            m_session.Read(
                null,
                0,
                TimestampsToReturn.Neither,
                nodesToRead,
                out results,
                out diagnosticInfos);

            ClientBase.ValidateResponse(results, nodesToRead);
            ClientBase.ValidateDiagnosticInfos(diagnosticInfos, nodesToRead);

            m_value = results[0];
            ValueTB.Text = Utils.Format("{0}", m_value.WrappedValue);
            
            // display the dialog.
            if (ShowDialog() != DialogResult.OK)
            {
                return false;
            }

            return true;
        }
示例#32
0
        /// <summary>
        /// Updates the aggregate descriptions.
        /// </summary>
        /// <param name="session">The session.</param>
        /// <param name="aggregates">The aggregates.</param>
        private void UpdateAggregateDescriptions(Session session, List<HdaAggregate> aggregates)
        {
            ReadValueIdCollection nodesToRead = new ReadValueIdCollection(); ;

            for (int ii = 0; ii < aggregates.Count; ii++)
            {
                HdaAggregate aggregate = aggregates[ii];

                ReadValueId nodeToRead = new ReadValueId();
                nodeToRead.NodeId = aggregate.RemoteId;
                nodeToRead.AttributeId = Attributes.Description;
                nodesToRead.Add(nodeToRead);
            }

            DataValueCollection values = null;
            DiagnosticInfoCollection diagnosticInfos = null;

            // read values from the UA server.
            ResponseHeader responseHeader = session.Read(
                null,
                0,
                TimestampsToReturn.Neither,
                nodesToRead,
                out values,
                out diagnosticInfos);

            // validate response from the UA server.
            ClientBase.ValidateResponse(values, nodesToRead);
            ClientBase.ValidateDiagnosticInfos(diagnosticInfos, nodesToRead);

            for (int ii = 0; ii < aggregates.Count; ii++)
            {
                HdaAggregate aggregate = aggregates[ii];

                if (StatusCode.IsBad(values[ii].StatusCode))
                {
                    aggregate.Description = null;
                    continue;
                }

                aggregate.Description = values[ii].WrappedValue.ToString();
            }
        }
示例#33
0
        /// <summary>
        /// Reads the values for a set of variables.
        /// </summary>
        static void Read(Session session)
        {
            IList<NodeOfInterest> results = GetNodeIds(session, Opc.Ua.Objects.ObjectsFolder,
                VariableBrowsePaths.ToArray());
            // build list of nodes to read.
            ReadValueIdCollection nodesToRead = new ReadValueIdCollection();

            for (int ii = 0; ii < results.Count; ii++)
            {
                ReadValueId nodeToRead = new ReadValueId();

                nodeToRead.NodeId = results[ii].NodeId;
                nodeToRead.AttributeId = Attributes.Value;
                
                nodesToRead.Add(nodeToRead);
            }

            // read values.
            DataValueCollection values;
            DiagnosticInfoCollection diagnosticInfos;

            ResponseHeader responseHeader = session.Read(
                null,
                0,
                TimestampsToReturn.Both,
                nodesToRead,
                out values,
                out diagnosticInfos);

            // verify that the server returned the correct number of results.
            Session.ValidateResponse(values, nodesToRead);
            Session.ValidateDiagnosticInfos(diagnosticInfos, nodesToRead);
                          
            // process results.
            for (int ii = 0; ii < values.Count; ii++)
            {

                // check for error.
                if (StatusCode.IsBad(values[ii].StatusCode))
                {
                    ServiceResult result = Session.GetResult(values[ii].StatusCode, ii, diagnosticInfos, responseHeader);
                    Console.WriteLine("Read result for {0}: {1}", VariableBrowsePaths[ii], result.ToLongString());
                    continue;
                }
                
                // write value.
                Console.WriteLine( "{0}: V={1}, Q={2}, SrvT={3}, SrcT={4}",nodesToRead[ii].NodeId, values[ii].Value.ToString(),
                    values[ii].StatusCode.ToString(), values[ii].ServerTimestamp, values[ii].SourceTimestamp);
            }
        }
示例#34
0
        private void RefreshBTN_Click(object sender, EventArgs e)
        {
            try
            {
                ReadValueId nodeToRead = new ReadValueId();
                nodeToRead.NodeId = m_variableId;
                nodeToRead.AttributeId = Attributes.Value;
                nodeToRead.DataEncoding = m_encodingName;


                ReadValueIdCollection nodesToRead = new ReadValueIdCollection();
                nodesToRead.Add(nodeToRead);

                // read the attributes.
                DataValueCollection results = null;
                DiagnosticInfoCollection diagnosticInfos = null;

                m_session.Read(
                    null,
                    0,
                    TimestampsToReturn.Neither,
                    nodesToRead,
                    out results,
                    out diagnosticInfos);

                ClientBase.ValidateResponse(results, nodesToRead);
                ClientBase.ValidateDiagnosticInfos(diagnosticInfos, nodesToRead);

                // check for error.
                if (StatusCode.IsBad(results[0].StatusCode))
                {
                    ValueTB.Text = results[0].StatusCode.ToString();
                    ValueTB.ForeColor = Color.Red;
                    ValueTB.Font = new Font(ValueTB.Font, FontStyle.Bold);
                    return;
                }

                SetValue(results[0].WrappedValue);
            }
            catch (Exception exception)
            {
                ClientUtils.HandleException(this.Text, exception);
            }
        }
示例#35
0
        /// <summary>
        /// Reads the log file path.
        /// </summary>
        private void ReadLogFilePath()
        {
            if (m_session == null)
            {
                return;
            }

            try
            {
                // want to get error text for this call.
                m_session.ReturnDiagnostics = DiagnosticsMasks.All;

                ReadValueId value = new ReadValueId();
                value.NodeId = m_logFileNodeId;
                value.AttributeId = Attributes.Value;

                ReadValueIdCollection valuesToRead = new ReadValueIdCollection();
                valuesToRead.Add(value);

                DataValueCollection results = null;
                DiagnosticInfoCollection diagnosticInfos = null;

                ResponseHeader responseHeader = m_session.Read(
                    null,
                    0,
                    TimestampsToReturn.Neither,
                    valuesToRead,
                    out results,
                    out diagnosticInfos);

                ClientBase.ValidateResponse(results, valuesToRead);
                ClientBase.ValidateDiagnosticInfos(diagnosticInfos, valuesToRead);

                if (StatusCode.IsBad(results[0].StatusCode))
                {
                    throw ServiceResultException.Create(results[0].StatusCode, 0, diagnosticInfos, responseHeader.StringTable);
                }

                LogFilePathTB.Text = results[0].GetValue<string>("");
            }
            catch (Exception exception)
            {
                ClientUtils.HandleException(this.Text, exception);
            }
            finally
            {
                m_session.ReturnDiagnostics = DiagnosticsMasks.None;
            }
        }
示例#36
0
        /// <summary>
        /// Finds the targets for the specified reference.
        /// </summary>
        private static void UpdateInstanceDescriptions(Session session, List<InstanceDeclaration> instances, bool throwOnError)
        {
            try
            {
                ReadValueIdCollection nodesToRead = new ReadValueIdCollection();

                for (int ii = 0; ii < instances.Count; ii++)
                {
                    ReadValueId nodeToRead = new ReadValueId();
                    nodeToRead.NodeId = instances[ii].NodeId;
                    nodeToRead.AttributeId = Attributes.Description;
                    nodesToRead.Add(nodeToRead);

                    nodeToRead = new ReadValueId();
                    nodeToRead.NodeId = instances[ii].NodeId;
                    nodeToRead.AttributeId = Attributes.DataType;
                    nodesToRead.Add(nodeToRead);

                    nodeToRead = new ReadValueId();
                    nodeToRead.NodeId = instances[ii].NodeId;
                    nodeToRead.AttributeId = Attributes.ValueRank;
                    nodesToRead.Add(nodeToRead);
                }

                // start the browse operation.
                DataValueCollection results = null;
                DiagnosticInfoCollection diagnosticInfos = null;

                session.Read(
                    null,
                    0,
                    TimestampsToReturn.Neither,
                    nodesToRead,
                    out results,
                    out diagnosticInfos);

                ClientBase.ValidateResponse(results, nodesToRead);
                ClientBase.ValidateDiagnosticInfos(diagnosticInfos, nodesToRead);

                // update the instances.
                for (int ii = 0; ii < nodesToRead.Count; ii += 3)
                {
                    InstanceDeclaration instance = instances[ii / 3];

                    instance.Description = results[ii].GetValue<LocalizedText>(LocalizedText.Null).Text;
                    instance.DataType = results[ii + 1].GetValue<NodeId>(NodeId.Null);
                    instance.ValueRank = results[ii + 2].GetValue<int>(ValueRanks.Any);

                    if (!NodeId.IsNull(instance.DataType))
                    {
                        instance.BuiltInType = DataTypes.GetBuiltInType(instance.DataType, session.TypeTree);
                        instance.DataTypeDisplayText = session.NodeCache.GetDisplayText(instance.DataType);

                        if (instance.ValueRank >= 0)
                        {
                            instance.DataTypeDisplayText += "[]";
                        }
                    }
                }
            }
            catch (Exception exception)
            {
                if (throwOnError)
                {
                    throw new ServiceResultException(exception, StatusCodes.BadUnexpectedError);
                }
            }
        }
示例#37
0
        /// <summary>
        /// Updates the local copy of the server's namespace uri and server uri tables.
        /// </summary>
        public void FetchNamespaceTables()
        {
            ReadValueIdCollection nodesToRead = new ReadValueIdCollection();

            // request namespace array.
            ReadValueId valueId = new ReadValueId();

            valueId.NodeId      = Variables.Server_NamespaceArray;
            valueId.AttributeId = Attributes.Value;

            nodesToRead.Add(valueId);

            // request server array.
            valueId = new ReadValueId();

            valueId.NodeId      = Variables.Server_ServerArray;
            valueId.AttributeId = Attributes.Value;

            nodesToRead.Add(valueId);
            
            // read from server.
            DataValueCollection values = null;
            DiagnosticInfoCollection diagnosticInfos = null;

            ResponseHeader responseHeader = this.Read(
                null,
                0,
                TimestampsToReturn.Both,
                nodesToRead,
                out values,
                out diagnosticInfos);

            ValidateResponse(values, nodesToRead);
            ValidateDiagnosticInfos(diagnosticInfos, nodesToRead);

            // validate namespace array.
            ServiceResult result = ValidateDataValue(values[0], typeof(string[]), 0, diagnosticInfos, responseHeader);

            if (ServiceResult.IsBad(result))
            {
                throw new ServiceResultException(result);
            }

            m_namespaceUris.Update((string[])values[0].Value);
                        
            // validate server array.
            result = ValidateDataValue(values[1], typeof(string[]), 1, diagnosticInfos, responseHeader);

            if (ServiceResult.IsBad(result))
            {
                throw new ServiceResultException(result);
            }

            m_serverUris.Update((string[])values[1].Value);
        }
示例#38
0
        /// <summary>
        /// Handles the AfterSelect event of the BrowseTV control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Windows.Forms.TreeViewEventArgs"/> instance containing the event data.</param>
        private void BrowseTV_AfterSelect(object sender, TreeViewEventArgs e)
        {
            try
            {
                EventFieldsLV.Items.Clear();

                FilterDefinition filter = m_newFilter = new FilterDefinition();
                filter.EventTypeId = null;
                filter.Fields = new List<FilterDefinitionField>();

                if (e.Node == null)
                {
                    OkBTN.Enabled = false;
                    return;
                }

                OkBTN.Enabled = true;

                // get the currently selected event.
                NodeId eventTypeId = Opc.Ua.ObjectTypeIds.BaseEventType;
                ReferenceDescription reference = e.Node.Tag as ReferenceDescription;

                if (reference != null)
                {
                    eventTypeId = (NodeId)reference.NodeId;
                }

                filter.EventTypeId = eventTypeId;

                // collect all of the fields defined for the event.
                SimpleAttributeOperandCollection fields = new SimpleAttributeOperandCollection();
                List<NodeId> declarationIds = new List<NodeId>();
                FormUtils.CollectFieldsForType(m_session, eventTypeId, fields, declarationIds);
                
                // need to read the description and datatype for each field. 
                ReadValueIdCollection valuesToRead = new ReadValueIdCollection();

                for (int ii = 0; ii < declarationIds.Count; ii++)
                {
                    ReadValueId valueToRead = new ReadValueId();
                    valueToRead.NodeId = declarationIds[ii];
                    valueToRead.AttributeId = Attributes.Description;
                    valuesToRead.Add(valueToRead);

                    valueToRead = new ReadValueId();
                    valueToRead.NodeId = declarationIds[ii];
                    valueToRead.AttributeId = Attributes.DataType;
                    valuesToRead.Add(valueToRead);

                    valueToRead = new ReadValueId();
                    valueToRead.NodeId = declarationIds[ii];
                    valueToRead.AttributeId = Attributes.ValueRank;
                    valuesToRead.Add(valueToRead);
                }

                DataValueCollection results = null;
                DiagnosticInfoCollection diagnosticInfos = null;

                m_session.Read(
                    null,
                    0,
                    TimestampsToReturn.Neither,
                    valuesToRead,
                    out results,
                    out diagnosticInfos);

                ClientBase.ValidateResponse(results, valuesToRead);
                ClientBase.ValidateDiagnosticInfos(diagnosticInfos, valuesToRead);

                // collect values. ignore errors since data used for display only.
                List<LocalizedText> descriptions = new List<LocalizedText>();
                List<NodeId> datatypes = new List<NodeId>();
                List<int> valueRanks = new List<int>();

                for (int ii = 0; ii < declarationIds.Count*3; ii += 3)
                {
                    descriptions.Add(results[ii].GetValue<LocalizedText>(LocalizedText.Null));
                    datatypes.Add(results[ii+1].GetValue<NodeId>(NodeId.Null));
                    valueRanks.Add(results[ii+2].GetValue<int>(ValueRanks.Any));
                }

                // populate the list box.
                for (int ii = 0; ii < fields.Count; ii++)
                {
                    FilterDefinitionField field = new FilterDefinitionField();
                    filter.Fields.Add(field);

                    field.Operand = fields[ii];

                    StringBuilder displayName = new StringBuilder();

                    for (int jj = 0; jj < field.Operand.BrowsePath.Count; jj++)
                    {
                        if (displayName.Length > 0)
                        {
                            displayName.Append('/');
                        }

                        displayName.Append(field.Operand.BrowsePath[jj].Name);
                    }

                    field.DisplayName = displayName.ToString();
                    field.DataType = datatypes[ii];
                    field.ValueRank = valueRanks[ii];
                    field.BuiltInType = DataTypes.GetBuiltInType(field.DataType, m_session.TypeTree);
                    field.Description = descriptions[ii].ToString();

                    // preserve previous settings.
                    for (int jj = 0; jj < m_filter.Fields.Count; jj++)
                    {
                        if (m_filter.Fields[jj].DisplayName == field.DisplayName)
                        {
                            field.ShowColumn = m_filter.Fields[jj].ShowColumn;
                            field.FilterValue = m_filter.Fields[jj].FilterValue;
                            break;
                        }
                    }

                    ListViewItem item = new ListViewItem(field.DisplayName);
                    item.SubItems.Add(String.Empty);
                    item.SubItems.Add(String.Empty);
                    item.Checked = field.ShowColumn;
                    item.Tag = field;

                    INode dataType = m_session.NodeCache.Find(datatypes[ii]);

                    if (dataType != null)
                    {
                        displayName = new StringBuilder();
                        displayName.Append(dataType.ToString());

                        if (valueRanks[ii] >= 0)
                        {
                            displayName.Append("[]");
                        }

                        field.DataTypeDisplayName = displayName.ToString();
                        item.SubItems[1].Text = field.DataTypeDisplayName;
                    }

                    item.SubItems[2].Text = descriptions[ii].ToString();
                    EventFieldsLV.Items.Add(item);
                }

                // resize columns to fit text.
                for (int ii = 0; ii < EventFieldsLV.Columns.Count; ii++)
                {
                    EventFieldsLV.Columns[ii].Width = -2;
                } 
            }
            catch (Exception exception)
            {
                MessageBox.Show(exception.Message, this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
示例#39
0
        /// <summary>
        /// Updates the values from the server.
        /// </summary>
        private void UpdateValues()
        {
            ReadValueIdCollection valuesToRead = new ReadValueIdCollection();

            foreach (ListViewItem item in ItemsLV.Items)
            {
                ItemInfo info = item.Tag as ItemInfo;

			    if (info == null)
			    {
                    continue;
                }

                ReadValueId valueToRead = new ReadValueId();

                valueToRead.NodeId = info.NodeId;
                valueToRead.AttributeId = info.AttributeId;
                valueToRead.Handle = item;

                valuesToRead.Add(valueToRead);
            }

            DataValueCollection results;
            DiagnosticInfoCollection diagnosticInfos;

            m_session.Read(
                null,
                0,
                TimestampsToReturn.Neither,
                valuesToRead,
                out results,
                out diagnosticInfos);

            ClientBase.ValidateResponse(results, valuesToRead);
            ClientBase.ValidateDiagnosticInfos(diagnosticInfos, valuesToRead);

            for (int ii = 0; ii < valuesToRead.Count; ii++)
            {
                ListViewItem item = (ListViewItem)valuesToRead[ii].Handle;
                ItemInfo info = (ItemInfo)item.Tag;
                info.Value = results[ii];
                UpdateItem(item, info);
            }

            AdjustColumns();
        }
示例#40
0
        /// <summary>
        /// Reads the arguments for the method.
        /// </summary>
        private void ReadArguments(NodeId nodeId)
        {
            m_inputArguments = null;
            m_outputArguments = null;

            // build list of references to browse.
            BrowseDescriptionCollection nodesToBrowse = new BrowseDescriptionCollection();

            BrowseDescription nodeToBrowse = new BrowseDescription();

            nodeToBrowse.NodeId = nodeId;
            nodeToBrowse.BrowseDirection = BrowseDirection.Forward;
            nodeToBrowse.ReferenceTypeId = Opc.Ua.ReferenceTypeIds.HasProperty;
            nodeToBrowse.IncludeSubtypes = true;
            nodeToBrowse.NodeClassMask = (uint)NodeClass.Variable;
            nodeToBrowse.ResultMask = (uint)BrowseResultMask.BrowseName;

            nodesToBrowse.Add(nodeToBrowse);

            // find properties.
            ReferenceDescriptionCollection references = ClientUtils.Browse(m_session, null, nodesToBrowse, false);

            // build list of properties to read.
            ReadValueIdCollection nodesToRead = new ReadValueIdCollection();

            for (int ii = 0; references != null && ii < references.Count; ii++)
            {
                ReferenceDescription reference = references[ii];

                // ignore out of server references.
                if (reference.NodeId.IsAbsolute)
                {
                    continue;
                }

                // ignore other properties.
                if (reference.BrowseName != Opc.Ua.BrowseNames.InputArguments && reference.BrowseName != Opc.Ua.BrowseNames.OutputArguments)
                {
                    continue;
                }

                ReadValueId nodeToRead = new ReadValueId();
                nodeToRead.NodeId = (NodeId)reference.NodeId;
                nodeToRead.AttributeId = Attributes.Value;
                nodeToRead.Handle = reference;
                nodesToRead.Add(nodeToRead);
            }

            // method has no arguments.
            if (nodesToRead.Count == 0)
            {
                return;
            }

            // read the arguments.
            DataValueCollection results = null;
            DiagnosticInfoCollection diagnosticInfos = null;

            m_session.Read(
                null,
                0,
                TimestampsToReturn.Neither,
                nodesToRead,
                out results,
                out diagnosticInfos);

            ClientBase.ValidateResponse(results, nodesToRead);
            ClientBase.ValidateDiagnosticInfos(diagnosticInfos, nodesToRead);

            // save the results.
            for (int ii = 0; ii < results.Count; ii++)
            {
                ReferenceDescription reference = (ReferenceDescription)nodesToRead[ii].Handle;

                if (StatusCode.IsGood(results[ii].StatusCode))
                {
                    if (reference.BrowseName == Opc.Ua.BrowseNames.InputArguments)
                    {
                        m_inputArguments = (Argument[])ExtensionObject.ToArray(results[ii].GetValue<ExtensionObject[]>(null), typeof(Argument));
                    }

                    if (reference.BrowseName == Opc.Ua.BrowseNames.OutputArguments)
                    {
                        m_outputArguments = (Argument[])ExtensionObject.ToArray(results[ii].GetValue<ExtensionObject[]>(null), typeof(Argument));
                    }
                }
            }

            // set default values for input arguments.
            if (m_inputArguments != null)
            {
                foreach (Argument argument in m_inputArguments)
                {
                    argument.Value = TypeInfo.GetDefaultValue(argument.DataType, argument.ValueRank, m_session.TypeTree);
                }
            }
        }
示例#41
0
        /// <summary>
        /// Starts a timer to check that the connection to the server is still available.
        /// </summary>
        private void StartKeepAliveTimer()
        {
            int keepAliveInterval = m_keepAliveInterval;

            lock (m_eventLock)
            {
                m_serverState = ServerState.Unknown;
                m_lastKeepAliveTime = DateTime.UtcNow;
            }
            
            ReadValueIdCollection nodesToRead = new ReadValueIdCollection();

            // read the server state.
            ReadValueId serverState = new ReadValueId();

            serverState.NodeId       = Variables.Server_ServerStatus_State;
            serverState.AttributeId  = Attributes.Value;
            serverState.DataEncoding = null;
            serverState.IndexRange   = null;

            nodesToRead.Add(serverState);

            // restart the publish timer.
            lock (SyncRoot)
            {
                if (m_keepAliveTimer != null)
                {
                    m_keepAliveTimer.Dispose();
                    m_keepAliveTimer = null;
                }

                // start timer.
                m_keepAliveTimer = new Timer(OnKeepAlive, nodesToRead, keepAliveInterval, keepAliveInterval);
            }

            // send initial keep alive.
            OnKeepAlive(nodesToRead);
        }
示例#42
0
        /// <summary>
        /// Reads the display name for a set of Nodes.
        /// </summary>
        public void ReadDisplayName(
            IList<NodeId> nodeIds,
            out List<string> displayNames,
            out List<ServiceResult> errors)
        {
            displayNames = new List<string>();
            errors = new List<ServiceResult>();

            // build list of values to read.
            ReadValueIdCollection valuesToRead = new ReadValueIdCollection();

            for (int ii = 0; ii < nodeIds.Count; ii++)
            {
                ReadValueId valueToRead = new ReadValueId();

                valueToRead.NodeId = nodeIds[ii];
                valueToRead.AttributeId = Attributes.DisplayName;
                valueToRead.IndexRange = null;
                valueToRead.DataEncoding = null;

                valuesToRead.Add(valueToRead);
            }

            // read the values.
            DataValueCollection results = null;
            DiagnosticInfoCollection diagnosticInfos = null;

            ResponseHeader responseHeader = Read(
                null,
                Int32.MaxValue,
                TimestampsToReturn.Both,
                valuesToRead,
                out results,
                out diagnosticInfos);

            // verify that the server returned the correct number of results.
            ClientBase.ValidateResponse(results, valuesToRead);
            ClientBase.ValidateDiagnosticInfos(diagnosticInfos, valuesToRead);

            for (int ii = 0; ii < nodeIds.Count; ii++)
            {
                displayNames.Add(String.Empty);
                errors.Add(ServiceResult.Good);

                // process any diagnostics associated with bad or uncertain data.
                if (StatusCode.IsNotGood(results[ii].StatusCode))
                {
                    errors[ii] = new ServiceResult(results[ii].StatusCode, ii, diagnosticInfos, responseHeader.StringTable);
                    continue;
                }

                // extract the name.
                LocalizedText displayName = results[ii].GetValue<LocalizedText>(null);

                if (!LocalizedText.IsNullOrEmpty(displayName))
                {
                    displayNames[ii] = displayName.Text;
                }
            }
        }
示例#43
0
        /// <summary>
        /// Reads the values for a set of variables.
        /// </summary>
        /// <param name="variableIds">The variable ids.</param>
        /// <param name="expectedTypes">The expected types.</param>
        /// <param name="values">The list of returned values.</param>
        /// <param name="errors">The list of returned errors.</param>
        public void ReadValues(
            IList<NodeId>           variableIds,
            IList<Type>             expectedTypes,
            out List<object>        values, 
            out List<ServiceResult> errors)
        {
            values = new List<object>();
            errors = new List<ServiceResult>();

            // build list of values to read.
            ReadValueIdCollection valuesToRead = new ReadValueIdCollection();

            for (int ii = 0; ii < variableIds.Count; ii++)
            {
                ReadValueId valueToRead = new ReadValueId();
                
                valueToRead.NodeId       = variableIds[ii];
                valueToRead.AttributeId  = Attributes.Value;
                valueToRead.IndexRange   = null;
                valueToRead.DataEncoding = null;

                valuesToRead.Add(valueToRead);
            }
            
            // read the values.
            DataValueCollection results = null;
            DiagnosticInfoCollection diagnosticInfos = null;

            ResponseHeader responseHeader = Read(
                null,
                Int32.MaxValue,
                TimestampsToReturn.Both,
                valuesToRead,
                out results,
                out diagnosticInfos);
            
            // verify that the server returned the correct number of results.
            ClientBase.ValidateResponse(results, valuesToRead);
            ClientBase.ValidateDiagnosticInfos(diagnosticInfos, valuesToRead);
            
            for (int ii = 0; ii < variableIds.Count; ii++)
            {
                values.Add(null);
                errors.Add(ServiceResult.Good);
                
                // process any diagnostics associated with bad or uncertain data.
                if (StatusCode.IsNotGood(results[ii].StatusCode))
                {
                    errors[ii] = new ServiceResult(results[ii].StatusCode, ii, diagnosticInfos, responseHeader.StringTable);
                    continue;
                }

                object value = results[ii].Value;
                
                // extract the body from extension objects.
                ExtensionObject extension = value as ExtensionObject;

                if (extension != null && extension.Body is IEncodeable)
                {
                    value = extension.Body;
                }

                // check expected type.
                if (expectedTypes[ii] != null && !expectedTypes[ii].IsInstanceOfType(value))
                {
                    errors[ii] = ServiceResult.Create(
                        StatusCodes.BadTypeMismatch, 
                        "Value {0} does not have expected type: {1}.", 
                        value, 
                        expectedTypes[ii].Name);
                    
                    continue;
                }

                // suitable value found.
                values[ii] = value;
            }            
        }
示例#44
0
        /// <summary>
        /// Reads the value for a node.
        /// </summary>
        /// <param name="nodeId">The node Id.</param>
        /// <returns></returns>
        public DataValue ReadValue(NodeId nodeId)
        {
            ReadValueId itemToRead = new ReadValueId();

            itemToRead.NodeId      = nodeId;
            itemToRead.AttributeId = Attributes.Value;

            ReadValueIdCollection itemsToRead = new ReadValueIdCollection();
            itemsToRead.Add(itemToRead);

            // read from server.
            DataValueCollection values = null;
            DiagnosticInfoCollection diagnosticInfos = null;

            ResponseHeader responseHeader = Read(
                null,
                0,
                TimestampsToReturn.Both,
                itemsToRead,
                out values, 
                out diagnosticInfos);
            
            ClientBase.ValidateResponse(values, itemsToRead);
            ClientBase.ValidateDiagnosticInfos(diagnosticInfos, itemsToRead);
            
            if (StatusCode.IsBad(values[0].StatusCode))
            {
                ServiceResult result = ClientBase.GetResult(values[0].StatusCode, 0, diagnosticInfos, responseHeader);
                throw new ServiceResultException(result);
            }

            return values[0];
        }
示例#45
0
        public Node ReadNode(NodeId nodeId)
        {
            // build list of attributes.
            SortedDictionary<uint,DataValue> attributes = new SortedDictionary<uint,DataValue>();
            
            attributes.Add(Attributes.NodeId, null);
            attributes.Add(Attributes.NodeClass, null);
            attributes.Add(Attributes.BrowseName, null);
            attributes.Add(Attributes.DisplayName, null);
            attributes.Add(Attributes.Description, null);
            attributes.Add(Attributes.WriteMask, null);
            attributes.Add(Attributes.UserWriteMask, null);
            attributes.Add(Attributes.DataType, null);
            attributes.Add(Attributes.ValueRank, null);
            attributes.Add(Attributes.ArrayDimensions, null);
            attributes.Add(Attributes.AccessLevel, null);
            attributes.Add(Attributes.UserAccessLevel, null);
            attributes.Add(Attributes.Historizing, null);
            attributes.Add(Attributes.MinimumSamplingInterval, null);
            attributes.Add(Attributes.EventNotifier, null);
            attributes.Add(Attributes.Executable, null);
            attributes.Add(Attributes.UserExecutable, null);
            attributes.Add(Attributes.IsAbstract, null);
            attributes.Add(Attributes.InverseName, null);
            attributes.Add(Attributes.Symmetric, null);
            attributes.Add(Attributes.ContainsNoLoops, null);

            // build list of values to read.
            ReadValueIdCollection itemsToRead = new ReadValueIdCollection();

            foreach (uint attributeId in attributes.Keys)
            {
                ReadValueId itemToRead = new ReadValueId();

                itemToRead.NodeId      = nodeId;
                itemToRead.AttributeId = attributeId;
                
                itemsToRead.Add(itemToRead);
            }

            // read from server.
            DataValueCollection values = null;
            DiagnosticInfoCollection diagnosticInfos = null;

            ResponseHeader responseHeader = Read(
                null,
                0,
                TimestampsToReturn.Neither,
                itemsToRead,
                out values, 
                out diagnosticInfos);
            
            ClientBase.ValidateResponse(values, itemsToRead);
            ClientBase.ValidateDiagnosticInfos(diagnosticInfos, itemsToRead);

            // process results.
            int? nodeClass = null;

            for (int ii = 0; ii < itemsToRead.Count; ii++)
            {
                uint attributeId = itemsToRead[ii].AttributeId;
                
                // the node probably does not exist if the node class is not found.
                if (attributeId == Attributes.NodeClass)
                {
                    if (!DataValue.IsGood(values[ii]))
                    {
                        throw ServiceResultException.Create(values[ii].StatusCode, ii, diagnosticInfos, responseHeader.StringTable);
                    }       
     
                    // check for valid node class.
                    nodeClass  = values[ii].Value as int?;

                    if (nodeClass == null)
                    {
                        throw ServiceResultException.Create(StatusCodes.BadUnexpectedError, "Node does not have a valid value for NodeClass: {0}.", values[ii].Value);
                    }
                }
                else
                {
                    if (!DataValue.IsGood(values[ii]))
                    {
                        // check for unsupported attributes.
                        if (values[ii].StatusCode == StatusCodes.BadAttributeIdInvalid)
                        {
                            continue;
                        }

                        // all supported attributes must be readable.
                        if (attributeId != Attributes.Value)
                        {
                            throw ServiceResultException.Create(values[ii].StatusCode, ii, diagnosticInfos, responseHeader.StringTable);
                        }
                    }      
                }

                attributes[attributeId] = values[ii];
            }

            Node node = null;
            DataValue value = null;

            switch ((NodeClass)nodeClass.Value)
            {
                default:
                {
                    throw ServiceResultException.Create(StatusCodes.BadUnexpectedError, "Node does not have a valid value for NodeClass: {0}.", nodeClass.Value);
                }

                case NodeClass.Object:
                {
                    ObjectNode objectNode = new ObjectNode();

                    value = attributes[Attributes.EventNotifier];

                    if (value == null)
                    {
                        throw ServiceResultException.Create(StatusCodes.BadUnexpectedError, "Object does not support the EventNotifier attribute.");
                    }

                    objectNode.EventNotifier = (byte)attributes[Attributes.EventNotifier].GetValue(typeof(byte));
                    node = objectNode;
                    break;
                }

                case NodeClass.ObjectType:
                {
                    ObjectTypeNode objectTypeNode = new ObjectTypeNode();

                    value = attributes[Attributes.IsAbstract];

                    if (value == null)
                    {
                        throw ServiceResultException.Create(StatusCodes.BadUnexpectedError, "ObjectType does not support the IsAbstract attribute.");
                    }

                    objectTypeNode.IsAbstract = (bool)attributes[Attributes.IsAbstract].GetValue(typeof(bool));
                    node = objectTypeNode;
                    break;
                }

                case NodeClass.Variable:
                {
                    VariableNode variableNode = new VariableNode();
                    
                    // DataType Attribute
                    value = attributes[Attributes.DataType];

                    if (value == null)
                    {
                        throw ServiceResultException.Create(StatusCodes.BadUnexpectedError, "Variable does not support the DataType attribute.");
                    }

                    variableNode.DataType = (NodeId)attributes[Attributes.DataType].GetValue(typeof(NodeId));     

                    // ValueRank Attribute
                    value = attributes[Attributes.ValueRank];

                    if (value == null)
                    {
                        throw ServiceResultException.Create(StatusCodes.BadUnexpectedError, "Variable does not support the ValueRank attribute.");
                    }

                    variableNode.ValueRank = (int)attributes[Attributes.ValueRank].GetValue(typeof(int));                                      
                    
                    // ArrayDimensions Attribute
                    value = attributes[Attributes.ArrayDimensions];

                    if (value != null)
                    {
                        if (value.Value == null)
                        {
                            variableNode.ArrayDimensions = new uint[0];
                        }
                        else
                        {
                            variableNode.ArrayDimensions = (uint[])value.GetValue(typeof(uint[]));
                        }
                    }
                    
                    // AccessLevel Attribute
                    value = attributes[Attributes.AccessLevel];

                    if (value == null)
                    {
                        throw ServiceResultException.Create(StatusCodes.BadUnexpectedError, "Variable does not support the AccessLevel attribute.");
                    }

                    variableNode.AccessLevel = (byte)attributes[Attributes.AccessLevel].GetValue(typeof(byte));     
                    
                    // UserAccessLevel Attribute
                    value = attributes[Attributes.UserAccessLevel];

                    if (value == null)
                    {
                        throw ServiceResultException.Create(StatusCodes.BadUnexpectedError, "Variable does not support the UserAccessLevel attribute.");
                    }

                    variableNode.UserAccessLevel = (byte)attributes[Attributes.UserAccessLevel].GetValue(typeof(byte));     
                    
                    // Historizing Attribute
                    value = attributes[Attributes.Historizing];

                    if (value == null)
                    {
                        throw ServiceResultException.Create(StatusCodes.BadUnexpectedError, "Variable does not support the Historizing attribute.");
                    }

                    variableNode.Historizing = (bool)attributes[Attributes.Historizing].GetValue(typeof(bool));    
                    
                    // MinimumSamplingInterval Attribute
                    value = attributes[Attributes.MinimumSamplingInterval];

                    if (value != null)
                    {
                        variableNode.MinimumSamplingInterval = Convert.ToDouble(attributes[Attributes.MinimumSamplingInterval].Value);
                    }

                    node = variableNode;
                    break;
                }
                    
                case NodeClass.VariableType:
                {
                    VariableTypeNode variableTypeNode = new VariableTypeNode();

                    // IsAbstract Attribute
                    value = attributes[Attributes.IsAbstract];

                    if (value == null)
                    {
                        throw ServiceResultException.Create(StatusCodes.BadUnexpectedError, "VariableType does not support the IsAbstract attribute.");
                    }

                    variableTypeNode.IsAbstract = (bool)attributes[Attributes.IsAbstract].GetValue(typeof(bool));
                    
                    // DataType Attribute
                    value = attributes[Attributes.DataType];

                    if (value == null)
                    {
                        throw ServiceResultException.Create(StatusCodes.BadUnexpectedError, "VariableType does not support the DataType attribute.");
                    }

                    variableTypeNode.DataType = (NodeId)attributes[Attributes.DataType].GetValue(typeof(NodeId));     

                    // ValueRank Attribute
                    value = attributes[Attributes.ValueRank];

                    if (value == null)
                    {
                        throw ServiceResultException.Create(StatusCodes.BadUnexpectedError, "VariableType does not support the ValueRank attribute.");
                    }

                    variableTypeNode.ValueRank = (int)attributes[Attributes.ValueRank].GetValue(typeof(int));                                      
                    
                    // ArrayDimensions Attribute
                    value = attributes[Attributes.ArrayDimensions];

                    if (value != null && value.Value != null)
                    {
                        variableTypeNode.ArrayDimensions = (uint[])attributes[Attributes.ArrayDimensions].GetValue(typeof(uint[]));
                    }
                    
                    node = variableTypeNode;
                    break;
                }
                    
                case NodeClass.Method:
                {
                    MethodNode methodNode = new MethodNode();

                    // Executable Attribute
                    value = attributes[Attributes.Executable];

                    if (value == null)
                    {
                        throw ServiceResultException.Create(StatusCodes.BadUnexpectedError, "Method does not support the Executable attribute.");
                    }

                    methodNode.Executable = (bool)attributes[Attributes.Executable].GetValue(typeof(bool));
                    
                    // UserExecutable Attribute
                    value = attributes[Attributes.UserExecutable];

                    if (value == null)
                    {
                        throw ServiceResultException.Create(StatusCodes.BadUnexpectedError, "Method does not support the UserExecutable attribute.");
                    }

                    methodNode.UserExecutable = (bool)attributes[Attributes.UserExecutable].GetValue(typeof(bool));

                    node = methodNode;
                    break;
                }
                    
                case NodeClass.DataType:
                {
                    DataTypeNode dataTypeNode = new DataTypeNode();

                    // IsAbstract Attribute
                    value = attributes[Attributes.IsAbstract];

                    if (value == null)
                    {
                        throw ServiceResultException.Create(StatusCodes.BadUnexpectedError, "DataType does not support the IsAbstract attribute.");
                    }

                    dataTypeNode.IsAbstract = (bool)attributes[Attributes.IsAbstract].GetValue(typeof(bool));

                    node = dataTypeNode;
                    break;
                }
                    
                case NodeClass.ReferenceType:
                {
                    ReferenceTypeNode referenceTypeNode = new ReferenceTypeNode();

                    // IsAbstract Attribute
                    value = attributes[Attributes.IsAbstract];

                    if (value == null)
                    {
                        throw ServiceResultException.Create(StatusCodes.BadUnexpectedError, "ReferenceType does not support the IsAbstract attribute.");
                    }

                    referenceTypeNode.IsAbstract = (bool)attributes[Attributes.IsAbstract].GetValue(typeof(bool));

                    // Symmetric Attribute
                    value = attributes[Attributes.Symmetric];

                    if (value == null)
                    {
                        throw ServiceResultException.Create(StatusCodes.BadUnexpectedError, "ReferenceType does not support the Symmetric attribute.");
                    }

                    referenceTypeNode.Symmetric = (bool)attributes[Attributes.IsAbstract].GetValue(typeof(bool));

                    // InverseName Attribute
                    value = attributes[Attributes.InverseName];

                    if (value != null && value.Value != null)
                    {
                        referenceTypeNode.InverseName = (LocalizedText)attributes[Attributes.InverseName].GetValue(typeof(LocalizedText));
                    }
                    
                    node = referenceTypeNode;
                    break;
                }
                    
                case NodeClass.View:
                {
                    ViewNode viewNode = new ViewNode();

                    // EventNotifier Attribute
                    value = attributes[Attributes.EventNotifier];

                    if (value == null)
                    {
                        throw ServiceResultException.Create(StatusCodes.BadUnexpectedError, "View does not support the EventNotifier attribute.");
                    }

                    viewNode.EventNotifier = (byte)attributes[Attributes.EventNotifier].GetValue(typeof(byte));
                    
                    // ContainsNoLoops Attribute
                    value = attributes[Attributes.ContainsNoLoops];

                    if (value == null)
                    {
                        throw ServiceResultException.Create(StatusCodes.BadUnexpectedError, "View does not support the ContainsNoLoops attribute.");
                    }

                    viewNode.ContainsNoLoops = (bool)attributes[Attributes.ContainsNoLoops].GetValue(typeof(bool));

                    node = viewNode;
                    break;
                }                    
            }
                
            // NodeId Attribute
            value = attributes[Attributes.NodeId];

            if (value == null)
            {
                throw ServiceResultException.Create(StatusCodes.BadUnexpectedError, "Node does not support the NodeId attribute.");
            }

            node.NodeId = (NodeId)attributes[Attributes.NodeId].GetValue(typeof(NodeId));
            node.NodeClass = (NodeClass)nodeClass.Value;

            // BrowseName Attribute
            value = attributes[Attributes.BrowseName];

            if (value == null)
            {
                throw ServiceResultException.Create(StatusCodes.BadUnexpectedError, "Node does not support the BrowseName attribute.");
            }

            node.BrowseName = (QualifiedName)attributes[Attributes.BrowseName].GetValue(typeof(QualifiedName));

            // DisplayName Attribute
            value = attributes[Attributes.DisplayName];

            if (value == null)
            {
                throw ServiceResultException.Create(StatusCodes.BadUnexpectedError, "Node does not support the DisplayName attribute.");
            }

            node.DisplayName = (LocalizedText)attributes[Attributes.DisplayName].GetValue(typeof(LocalizedText));
    
            // Description Attribute
            value = attributes[Attributes.Description];

            if (value != null && value.Value != null)
            {
                node.Description = (LocalizedText)attributes[Attributes.Description].GetValue(typeof(LocalizedText));
            }

            // WriteMask Attribute
            value = attributes[Attributes.WriteMask];

            if (value != null)
            {
                node.WriteMask = (uint)attributes[Attributes.WriteMask].GetValue(typeof(uint));
            }

            // UserWriteMask Attribute
            value = attributes[Attributes.UserWriteMask];

            if (value != null)
            {
                node.WriteMask = (uint)attributes[Attributes.UserWriteMask].GetValue(typeof(uint));
            }
                
            return node;
        }
示例#46
0
        /// <summary>
        /// Reads the application description from the GDS.
        /// </summary>
        private ApplicationDescription Read(NodeId nodeId)
        {
            NamespaceTable wellKnownNamespaceUris = new NamespaceTable();
            wellKnownNamespaceUris.Append(Namespaces.OpcUaGds);

            string[] browsePaths = new string[] 
            {
                "1:ApplicationName",
                "1:ApplicationType",
                "1:ApplicationUri",
                "1:ProductUri",
                "1:GatewayServerUri",
                "1:DiscoveryUrls"
            };

            List<NodeId> propertyIds = ClientUtils.TranslateBrowsePaths(
                ServerCTRL.Session,
                nodeId,
                wellKnownNamespaceUris,
                browsePaths);

            ReadValueIdCollection nodesToRead = new ReadValueIdCollection();

            foreach (NodeId propertyId in propertyIds)
            {
                ReadValueId nodeToRead = new ReadValueId();
                nodeToRead.NodeId = propertyId;
                nodeToRead.AttributeId = Attributes.Value;
                nodesToRead.Add(nodeToRead);
            }

            DataValueCollection results = null;
            DiagnosticInfoCollection diagnosticInfos = null;

            ServerCTRL.Session.Read(
                null,
                0,
                TimestampsToReturn.Neither,
                nodesToRead,
                out results,
                out diagnosticInfos);

            ClientBase.ValidateResponse(results, nodesToRead);
            ClientBase.ValidateDiagnosticInfos(diagnosticInfos, nodesToRead);

            ApplicationDescription application = new ApplicationDescription();

            application.ApplicationName = results[0].GetValue<LocalizedText>(null);
            application.ApplicationType = (ApplicationType)results[1].GetValue<int>((int)ApplicationType.Server);
            application.ApplicationUri = results[2].GetValue<string>(null);
            application.ProductUri = results[3].GetValue<string>(null);
            application.GatewayServerUri = results[4].GetValue<string>(null);

            string[] discoveryUrls = results[5].GetValue<string[]>(null);

            if (discoveryUrls != null)
            {
                application.DiscoveryUrls = new StringCollection(discoveryUrls);
            }

            return application;
        }
示例#47
0
        /// <summary>
        /// Returns the items in the control.
        /// </summary>
        public ReadValueIdCollection GetValueIds()
        {
            ReadValueIdCollection valueIds = new ReadValueIdCollection();

            foreach (ListViewItem item in ItemsLV.Items)
            {
                ReadValueId valueId = item.Tag as ReadValueId;

                if (valueId != null)
                {
                    valueIds.Add(valueId);
                }
            }

            return valueIds;
        }
示例#48
0
        private void ReadMI_Click(object sender, EventArgs e)
        {
            try
            {
                if (NodesTV.SelectedNode == null)
                {
                    return;
                }
                                    
                ReferenceDescription reference = NodesTV.SelectedNode.Tag as ReferenceDescription;
                
                if (reference == null || (reference.NodeClass & (NodeClass.Variable | NodeClass.VariableType)) == 0)
                {
                    return;
                }

                Session session = m_browser.Session;

                // build list of nodes to read.
                ReadValueIdCollection valueIds = new ReadValueIdCollection();

                ReadValueId valueId = new ReadValueId();

                valueId.NodeId       = (NodeId)reference.NodeId;
                valueId.AttributeId  = Attributes.Value;
                valueId.IndexRange   = null;
                valueId.DataEncoding = null;

                valueIds.Add(valueId);

                // show form.
                new ReadDlg().Show(session, valueIds);
            }
            catch (Exception exception)
            {
				GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception);
            }
        }
示例#49
0
        /// <summary>
        /// Tests the session keep alive when there are no errors. 
        /// </summary>
        private bool DoKeepAliveTest()
        {
            bool success = true;
            
            double increment = MaxProgress/3;
            double position  = 0;

            m_keepAliveCount = 0;

            int currentKeepAlive = Session.KeepAliveInterval;
            List<Subscription> subscriptions = new List<Subscription>();
            KeepAliveEventHandler handler = new KeepAliveEventHandler(Session_KeepAlive); 

            try
            {
                Session.KeepAlive += handler;

                // add several subscriptions with long publish intervals.
                for (int publishingInterval = 10000; publishingInterval <= 20000; publishingInterval += 1000)
                {
                    Subscription subscription = new Subscription();

                    subscription.MaxMessageCount = 100;
                    subscription.LifetimeCount = 100;
                    subscription.KeepAliveCount = 10;
                    subscription.PublishingEnabled = true;
                    subscription.PublishingInterval = publishingInterval;

                    MonitoredItem monitoredItem = new MonitoredItem();

                    monitoredItem.StartNodeId = VariableIds.Server_ServerStatus_CurrentTime;
                    monitoredItem.AttributeId = Attributes.Value;
                    monitoredItem.SamplingInterval = -1;
                    monitoredItem.QueueSize = 0;
                    monitoredItem.DiscardOldest = true;

                    subscription.AddItem(monitoredItem);
                    Session.AddSubscription(subscription);
                    subscription.Create();
                    subscriptions.Add(subscription);
                }
                
                // get a value to read.
                ReadValueId nodeToRead = new ReadValueId();
                nodeToRead.NodeId = VariableIds.Server_ServerStatus;
                nodeToRead.AttributeId = Attributes.Value;
                ReadValueIdCollection nodesToRead = new ReadValueIdCollection();
                nodesToRead.Add(nodeToRead);

                int testDuration = 5000;

                // make sure the keep alives come at the expected rate.
                for (int keepAliveInterval = 500; keepAliveInterval < 2000; keepAliveInterval += 500)
                {
                    m_keepAliveCount = 0;

                    DateTime start = DateTime.UtcNow;
                    
                    DataValueCollection results = null;
                    DiagnosticInfoCollection diagnosticsInfos = null;

                    Session.Read(
                        null,
                        0,
                        TimestampsToReturn.Neither,
                        nodesToRead,
                        out results,
                        out diagnosticsInfos);

                    ClientBase.ValidateResponse(results, nodesToRead);
                    ClientBase.ValidateDiagnosticInfos(diagnosticsInfos, nodesToRead);

                    ServerStatusDataType status = ExtensionObject.ToEncodeable(results[0].Value as ExtensionObject) as ServerStatusDataType;

                    if (status == null)
                    {
                        Log("Server did not return a valid ServerStatusDataType structure. Value={0}, Status={1}", results[0].WrappedValue, results[0].StatusCode);
                        return false;
                    }

                    if ((DateTime.UtcNow - start).TotalSeconds > 1)
                    {
                        Log("Unexpected delay reading the ServerStatus structure. Delay={0}s", (DateTime.UtcNow - start).TotalSeconds);
                        return false;
                    }

                    Log("Setting keep alive interval to {0}ms.", keepAliveInterval);

                    Session.KeepAliveInterval = keepAliveInterval;

                    if (m_errorEvent.WaitOne(testDuration, false))
                    {
                        Log("Unexpected error waiting for session keep alives. {0}", m_error.ToLongString());
                        return false;
                    }

                    if (m_keepAliveCount < testDuration / keepAliveInterval)
                    {
                        Log("Missing session keep alives. Expected={0}, Actual={1}", testDuration / keepAliveInterval, m_keepAliveCount);
                        return false;
                    }

                    Log("{0} keep alives received in {1}ms.", m_keepAliveCount, testDuration);

                    position += increment;
                    ReportProgress(position);
                }

                ReportProgress(MaxProgress);
            }
            finally
            {
                Session.RemoveSubscriptions(subscriptions);
                Session.KeepAliveInterval = currentKeepAlive;
                Session.KeepAlive -= handler;
            }

            return success;
        }
示例#50
0
        /// <summary>
        /// Reads the values displayed in the control and moves to the display results state.
        /// </summary>
        public void Read()
        {
            if (m_session == null)
            {
                throw new ServiceResultException(StatusCodes.BadNotConnected);
            }

            // build list of values to read.
            ReadValueIdCollection nodesToRead = new ReadValueIdCollection();

            foreach (DataGridViewRow row in ResultsDV.Rows)
            {
                DataRowView source = row.DataBoundItem as DataRowView;
                ReadValueId value = (ReadValueId)source.Row[0];
                row.Selected = false;
                nodesToRead.Add(value);
            }
            
            // read the values.
            DataValueCollection results = null;
            DiagnosticInfoCollection diagnosticInfos = null;

            m_session.Read(
                null,
                0,
                TimestampsToReturn.Both,
                nodesToRead,
                out results,
                out diagnosticInfos);

            ClientBase.ValidateResponse(results, nodesToRead);
            ClientBase.ValidateDiagnosticInfos(diagnosticInfos, nodesToRead);

            IndexRangeCH.Visible = false;
            DataEncodingCH.Visible = false;
            DataTypeCH.Visible = true;
            ValueCH.Visible = true;
            StatusCodeCH.Visible = true;
            SourceTimestampCH.Visible = true;
            ServerTimestampCH.Visible = true;
            m_showResults = true;

            // add the results to the display.
            for (int ii = 0; ii < results.Count; ii++)
            {
                DataRowView source = ResultsDV.Rows[ii].DataBoundItem as DataRowView;
                UpdateRow(source.Row, results[ii]);
            }
        }
        /// <summary>
        /// Adds the attributes to the control.
        /// </summary>
        private void AddAttributes()
        {
            // build list of attributes to read.
            ReadValueIdCollection nodesToRead = new ReadValueIdCollection();

            foreach (uint attributeId in Attributes.GetIdentifiers())
            {
                ReadValueId valueId = new ReadValueId();

                valueId.NodeId       = m_nodeId;
                valueId.AttributeId  = attributeId;
                valueId.IndexRange   = null;
                valueId.DataEncoding = null;

                nodesToRead.Add(valueId);
            }

            // read attributes.
            DataValueCollection values;
            DiagnosticInfoCollection diagnosticInfos;

            m_session.Read(
                null,
                0,
                TimestampsToReturn.Neither,
                nodesToRead,
                out values,
                out diagnosticInfos);

            ClientBase.ValidateResponse(values, nodesToRead);
            ClientBase.ValidateDiagnosticInfos(diagnosticInfos, nodesToRead);

            // update control.
            for (int ii = 0; ii < nodesToRead.Count; ii++)
            {
                // check if node supports attribute.
                if (values[ii].StatusCode == StatusCodes.BadAttributeIdInvalid)
                {
                    continue;
                }

                NodeField field = new NodeField();

                field.ValueId        = nodesToRead[ii];
                field.Name           = Attributes.GetBrowseName(nodesToRead[ii].AttributeId);
                field.Value          = values[ii].Value;
                field.StatusCode     = values[ii].StatusCode;

                if (diagnosticInfos != null && diagnosticInfos.Count > ii)
                {
                    field.DiagnosticInfo = diagnosticInfos[ii];
                }

                AddItem(field, "SimpleItem", -1);
            }
        }
        /// <summary>
        /// Adds the properties to the control.
        /// </summary>
        private void AddProperties()
        {
            // build list of properties to read.
            ReadValueIdCollection nodesToRead = new ReadValueIdCollection();

            Browser browser = new Browser(m_session);
            
            browser.BrowseDirection   = BrowseDirection.Forward;
            browser.ReferenceTypeId   = ReferenceTypeIds.HasProperty;
            browser.IncludeSubtypes   = true;
            browser.NodeClassMask     = (int)NodeClass.Variable;
            browser.ContinueUntilDone = true;

            ReferenceDescriptionCollection references = browser.Browse(m_nodeId);

            foreach (ReferenceDescription reference in references)
            {
                ReadValueId valueId = new ReadValueId();

                valueId.NodeId       = (NodeId)reference.NodeId;
                valueId.AttributeId  = Attributes.Value;
                valueId.IndexRange   = null;
                valueId.DataEncoding = null;

                nodesToRead.Add(valueId);
            }

            // check for empty list.
            if (nodesToRead.Count == 0)
            {
                return;
            }

            // read values.
            DataValueCollection values;
            DiagnosticInfoCollection diagnosticInfos;

            m_session.Read(
                null,
                0,
                TimestampsToReturn.Neither,
                nodesToRead,
                out values,
                out diagnosticInfos);

            ClientBase.ValidateResponse(values, nodesToRead);
            ClientBase.ValidateDiagnosticInfos(diagnosticInfos, nodesToRead);           

            // update control.
            for (int ii = 0; ii < nodesToRead.Count; ii++)
            {
                NodeField field = new NodeField();

                field.ValueId    = nodesToRead[ii];
                field.Name       = references[ii].ToString();
                field.Value      = values[ii].Value;
                field.StatusCode = values[ii].StatusCode;

                if (diagnosticInfos != null && diagnosticInfos.Count > ii)
                {
                    field.DiagnosticInfo = diagnosticInfos[ii];
                }

                AddItem(field, "Property", -1);
            }
        }
示例#53
0
        /// <summary>
        /// Reads the EU range for a variable.
        /// </summary>
        private void ReadEURanges(List<TestVariable> variables)
        {
            ReadValueIdCollection euRanges = new ReadValueIdCollection();

            for (int ii = 0; ii < m_variables.Count; ii++)
            {
                VariableNode variable = m_variables[ii].Variable;

                if (m_variables[ii].EURangeNode != null)
                {
                    ReadValueId rangeToRead = new ReadValueId();
                    rangeToRead.NodeId = m_variables[ii].EURangeNode.NodeId;
                    rangeToRead.AttributeId = Attributes.Value;
                    rangeToRead.Handle = m_variables[ii];
                    euRanges.Add(rangeToRead);
                }
            }

            // lookup the EU range.
            if (euRanges.Count > 0)
            {
                DataValueCollection results;
                DiagnosticInfoCollection diagnosticInfos;
                
                RequestHeader requestHeader = new RequestHeader();
                requestHeader.ReturnDiagnostics = 0;

                ResponseHeader responseHeader = Session.Read(
                    requestHeader,
                    0,
                    TimestampsToReturn.Neither,
                    euRanges,
                    out results,
                    out diagnosticInfos);
                
                ClientBase.ValidateResponse(results, euRanges);
                ClientBase.ValidateDiagnosticInfos(diagnosticInfos, euRanges);

                for (int ii = 0; ii < results.Count; ii++)
                {
                    Range range = ExtensionObject.ToEncodeable(results[ii].Value as ExtensionObject) as Range;
                    TestVariable variable = (TestVariable)euRanges[ii].Handle;
                    variable.EURange = range;
                }
            }
        }
        /// <see cref="BaseListCtrl.GetDataToDrag" />
        protected override object GetDataToDrag()
        {
            ReadValueIdCollection valueIds = new ReadValueIdCollection();

            foreach (ListViewItem listItem in ItemsLV.SelectedItems)
            {
                NodeField field = listItem.Tag as NodeField;

                if (field != null && field.ValueId != null)
                {
                    valueIds.Add(field.ValueId);
                }
            }

            return valueIds;
        }
示例#55
0
        /// <summary>
        /// Handles a read operations that fetch data from an external source.
        /// </summary>
        protected override void Read(
            ServerSystemContext context,
            IList<ReadValueId> nodesToRead,
            IList<DataValue> values,
            IList<ServiceResult> errors,
            List<NodeHandle> nodesToValidate,
            IDictionary<NodeId, NodeState> cache)
        {
            ReadValueIdCollection requests = new ReadValueIdCollection();
            List<int> indexes = new List<int>();

            for (int ii = 0; ii < nodesToValidate.Count; ii++)
            {
                NodeHandle handle = nodesToValidate[ii];
                ReadValueId nodeToRead = nodesToRead[ii];
                DataValue value = values[ii];

                lock (Lock)
                {
                    // validate node.
                    NodeState source = ValidateNode(context, handle, cache);

                    if (source == null)
                    {
                        continue;
                    }

                    // determine if a local node.
                    if (PredefinedNodes.ContainsKey(source.NodeId))
                    {
                        errors[handle.Index] = source.ReadAttribute(
                            context,
                            nodeToRead.AttributeId,
                            nodeToRead.ParsedIndexRange,
                            nodeToRead.DataEncoding,
                            value);

                        continue;
                    }

                    ReadValueId request = (ReadValueId)nodeToRead.Clone();
                    request.NodeId = m_mapper.ToRemoteId(nodeToRead.NodeId);
                    request.DataEncoding = m_mapper.ToRemoteName(nodeToRead.DataEncoding);
                    requests.Add(request);
                    indexes.Add(ii);
                }
            }

            // send request to external system.
            try
            {
                Opc.Ua.Client.Session client = GetClientSession(context);

                DataValueCollection results = null;
                DiagnosticInfoCollection diagnosticInfos = null;

                ResponseHeader responseHeader = client.Read(
                    null,
                    0,
                    TimestampsToReturn.Both,
                    requests,
                    out results,
                    out diagnosticInfos);

                // these do sanity checks on the result - make sure response matched the request.
                ClientBase.ValidateResponse(results, requests);
                ClientBase.ValidateDiagnosticInfos(diagnosticInfos, requests);

                // set results.
                for (int ii = 0; ii < requests.Count; ii++)
                {
                    values[indexes[ii]] = results[ii];
                    values[indexes[ii]].WrappedValue = m_mapper.ToLocalVariant(results[ii].WrappedValue);

                    errors[indexes[ii]] = ServiceResult.Good;

                    if (results[ii].StatusCode != StatusCodes.Good)
                    {
                        errors[indexes[ii]] = new ServiceResult(results[ii].StatusCode, ii, diagnosticInfos, responseHeader.StringTable);
                    }
                }
            }
            catch (Exception e)
            {
                // handle unexpected communication error.
                ServiceResult error = ServiceResult.Create(e, StatusCodes.BadUnexpectedError, "Could not access external system.");

                for (int ii = 0; ii < requests.Count; ii++)
                {
                    errors[indexes[ii]] = error;
                }
            }
        }
        /// <summary>
        /// Runs the test in a background thread.
        /// </summary>
        private void DoTest(ConfiguredEndpoint endpoint)
        {
            PerformanceTestResult result = new PerformanceTestResult(endpoint, 100);

            result.Results.Add(1, -1);
            result.Results.Add(10, -1);
            result.Results.Add(50, -1);
            result.Results.Add(100, -1);
            result.Results.Add(250, -1);
            result.Results.Add(500, -1);

            try
            {
                // update the endpoint.
                if (endpoint.UpdateBeforeConnect)
                {
                    endpoint.UpdateFromServer();
                }

                SessionClient client = null;

                Uri url = new Uri(endpoint.Description.EndpointUrl);

                ITransportChannel channel = SessionChannel.Create(
                    m_configuration,
                    endpoint.Description,
                    endpoint.Configuration,
                    m_clientCertificate,
                    m_messageContext);

                client = new SessionClient(channel);

                List<int> requestSizes = new List<int>(result.Results.Keys);

                for (int ii = 0; ii < requestSizes.Count; ii++)
                {
                    // update the progress indicator.
                    TestProgress((ii * 100) / requestSizes.Count);

                    lock (m_lock)
                    {
                        if (!m_running)
                        {
                            break;
                        }
                    }

                    int count = requestSizes[ii];

                    // initialize request.
                    RequestHeader requestHeader = new RequestHeader();
                    requestHeader.ReturnDiagnostics = 5000;

                    ReadValueIdCollection nodesToRead = new ReadValueIdCollection(count);

                    for (int jj = 0; jj < count; jj++)
                    {
                        ReadValueId item = new ReadValueId();

                        item.NodeId = new NodeId((uint)jj, 1);
                        item.AttributeId = Attributes.Value;

                        nodesToRead.Add(item);
                    }

                    // ensure valid connection.
                    DataValueCollection results = null;
                    DiagnosticInfoCollection diagnosticInfos = null;

                    client.Read(
                        requestHeader,
                        0,
                        TimestampsToReturn.Both,
                        nodesToRead,
                        out results,
                        out diagnosticInfos);

                    if (results.Count != count)
                    {
                        throw new ServiceResultException(StatusCodes.BadUnknownResponse);
                    }

                    // do test.
                    DateTime start = DateTime.UtcNow;

                    for (int jj = 0; jj < result.Iterations; jj++)
                    {
                        client.Read(
                            requestHeader,
                            0,
                            TimestampsToReturn.Both,
                            nodesToRead,
                            out results,
                            out diagnosticInfos);

                        if (results.Count != count)
                        {
                            throw new ServiceResultException(StatusCodes.BadUnknownResponse);
                        }
                    }

                    DateTime finish = DateTime.UtcNow;

                    long totalTicks = finish.Ticks - start.Ticks;
                    decimal averageMilliseconds = ((((decimal)totalTicks) / ((decimal)result.Iterations))) / ((decimal)TimeSpan.TicksPerMillisecond);
                    result.Results[requestSizes[ii]] = (double)averageMilliseconds;
                }
            }
            finally
            {
                TestComplete(result);
            }
        }
        /// <summary>
        /// Reads the contents of a data dictionary.
        /// </summary>
        private byte[] ReadDictionary(NodeId dictionaryId)
        {
            // create item to read.
            ReadValueId itemToRead = new ReadValueId();

            itemToRead.NodeId       = dictionaryId;
            itemToRead.AttributeId  = Attributes.Value;
            itemToRead.IndexRange   = null;
            itemToRead.DataEncoding = null;
            
            ReadValueIdCollection itemsToRead = new ReadValueIdCollection();
            itemsToRead.Add(itemToRead);
                        
            // read value.
            DataValueCollection values;
            DiagnosticInfoCollection diagnosticInfos;

            ResponseHeader responseHeader = m_session.Read(
                null,
                0,
                TimestampsToReturn.Neither,
                itemsToRead,
                out values,
                out diagnosticInfos);

            ClientBase.ValidateResponse(values, itemsToRead);
            ClientBase.ValidateDiagnosticInfos(diagnosticInfos, itemsToRead);      
      
            // check for error.
            if (StatusCode.IsBad(values[0].StatusCode))
            {
                ServiceResult result = ClientBase.GetResult(values[0].StatusCode, 0, diagnosticInfos, responseHeader);
                throw new ServiceResultException(result);
            }

            // return as a byte array.
            return values[0].Value as byte[];
        }
示例#58
0
        /// <summary>
        /// Reads the attributes for the node.
        /// </summary>
        public void ReadAttributes(NodeId nodeId, bool showProperties)
        {
            AttributesLV.Items.Clear();

            if (NodeId.IsNull(nodeId))
            {
                return;
            }

            // build list of attributes to read.
            ReadValueIdCollection nodesToRead = new ReadValueIdCollection();

            foreach (uint attributeId in Attributes.GetIdentifiers())
            {
                ReadValueId nodeToRead = new ReadValueId();
                nodeToRead.NodeId = nodeId;
                nodeToRead.AttributeId = attributeId;
                nodesToRead.Add(nodeToRead);
            }

            // read the attributes.
            DataValueCollection results = null;
            DiagnosticInfoCollection diagnosticInfos = null;

            m_session.Read(
                null,
                0,
                TimestampsToReturn.Neither,
                nodesToRead,
                out results,
                out diagnosticInfos);

            ClientBase.ValidateResponse(results, nodesToRead);
            ClientBase.ValidateDiagnosticInfos(diagnosticInfos, nodesToRead);

            // add the results to the display.
            for (int ii = 0; ii < results.Count; ii++)
            {
                // check for error.
                if (StatusCode.IsBad(results[ii].StatusCode))
                {
                    if (results[ii].StatusCode == StatusCodes.BadAttributeIdInvalid)
                    {
                        continue;
                    }
                }

                // add the metadata for the attribute.
                uint attributeId = nodesToRead[ii].AttributeId;
                ListViewItem item = new ListViewItem(Attributes.GetBrowseName(attributeId));
                item.SubItems.Add(Attributes.GetBuiltInType(attributeId).ToString());

                if (Attributes.GetValueRank(attributeId) >= 0)
                {
                    item.SubItems[0].Text += "[]";
                }

                // add the value.
                if (StatusCode.IsBad(results[ii].StatusCode))
                {
                    item.SubItems.Add(results[ii].StatusCode.ToString());
                }
                else
                {
                    item.SubItems.Add(ClientUtils.GetAttributeDisplayText(m_session, attributeId, results[ii].WrappedValue));
                }

                item.Tag = new AttributeInfo() { NodeToRead = nodesToRead[ii], Value = results[ii] };
                item.ImageIndex = ClientUtils.GetImageIndex(nodesToRead[ii].AttributeId, results[ii].Value);

                // display in list.
                AttributesLV.Items.Add(item);
            }

            if (showProperties)
            {
                ReadProperties(nodeId);
            }

            // set the column widths.
            for (int ii = 0; ii < AttributesLV.Columns.Count; ii++)
            {
                AttributesLV.Columns[ii].Width = -2;
            }
        }
示例#59
0
        /// <summary>
        /// Reads the values for the specified item ids.
        /// </summary>
        /// <param name="itemIds">The item ids.</param>
        /// <returns>The values.</returns>
        public DaValue[] Read(string[] itemIds)
        {
            ReadValueIdCollection valuesToRead = new ReadValueIdCollection();

            for (int ii = 0; ii < itemIds.Length; ii++)
            {
                ReadValueId valueToRead = new ReadValueId();

                valueToRead.NodeId = m_mapper.GetRemoteNodeId(itemIds[ii]);
                valueToRead.AttributeId = Attributes.Value;

                valuesToRead.Add(valueToRead);
            }

            return m_groupManager.Read(valuesToRead);
        }
示例#60
0
        /// <summary>
        /// Reads the properties for the node.
        /// </summary>
        private void ReadProperties(NodeId nodeId)
        {
            // build list of references to browse.
            BrowseDescriptionCollection nodesToBrowse = new BrowseDescriptionCollection();

            BrowseDescription nodeToBrowse = new BrowseDescription();

            nodeToBrowse.NodeId = nodeId;
            nodeToBrowse.BrowseDirection = BrowseDirection.Forward;
            nodeToBrowse.ReferenceTypeId = Opc.Ua.ReferenceTypeIds.HasProperty;
            nodeToBrowse.IncludeSubtypes = true;
            nodeToBrowse.NodeClassMask = (uint)NodeClass.Variable;
            nodeToBrowse.ResultMask = (uint)BrowseResultMask.All;

            nodesToBrowse.Add(nodeToBrowse);

            // find properties.
            ReferenceDescriptionCollection references = ClientUtils.Browse(m_session, View, nodesToBrowse, false);

            // build list of properties to read.
            ReadValueIdCollection nodesToRead = new ReadValueIdCollection();

            for (int ii = 0; references != null && ii < references.Count; ii++)
            {
                ReferenceDescription reference = references[ii];

                // ignore out of server references.
                if (reference.NodeId.IsAbsolute)
                {
                    continue;
                }

                ReadValueId nodeToRead = new ReadValueId();
                nodeToRead.NodeId = (NodeId)reference.NodeId;
                nodeToRead.AttributeId = Attributes.Value;
                nodeToRead.Handle = reference;
                nodesToRead.Add(nodeToRead);
            }

            if (nodesToRead.Count == 0)
            {
                return;
            }

            // read the properties.
            DataValueCollection results = null;
            DiagnosticInfoCollection diagnosticInfos = null;

            m_session.Read(
                null,
                0,
                TimestampsToReturn.Neither,
                nodesToRead,
                out results,
                out diagnosticInfos);

            ClientBase.ValidateResponse(results, nodesToRead);
            ClientBase.ValidateDiagnosticInfos(diagnosticInfos, nodesToRead);

            // add the results to the display.
            for (int ii = 0; ii < results.Count; ii++)
            {
                ReferenceDescription reference = (ReferenceDescription)nodesToRead[ii].Handle;

                TypeInfo typeInfo = TypeInfo.Construct(results[ii].Value);

                // add the metadata for the attribute.
                ListViewItem item = new ListViewItem(reference.ToString());
                item.SubItems.Add(typeInfo.BuiltInType.ToString());

                if (typeInfo.ValueRank >= 0)
                {
                    item.SubItems[1].Text += "[]";
                }

                // add the value.
                if (StatusCode.IsBad(results[ii].StatusCode))
                {
                    item.SubItems.Add(results[ii].StatusCode.ToString());
                }
                else
                {
                    item.SubItems.Add(results[ii].WrappedValue.ToString());
                }

                item.Tag = new AttributeInfo() { NodeToRead = nodesToRead[ii], Value = results[ii] };
                item.ImageIndex = ClientUtils.GetImageIndex(m_session, NodeClass.Variable, Opc.Ua.VariableTypeIds.PropertyType, false);

                // display in list.
                AttributesLV.Items.Add(item);
            }
        }