示例#1
0
        /// <summary>
        /// Displays the dialog.
        /// </summary>
        public void Show(Session session, ReadValueIdCollection valueIds)
        {
            if (session == null) throw new ArgumentNullException("session");
            
            m_session = session;

            BrowseCTRL.SetView(m_session, BrowseViewType.Objects, null);
            ReadValuesCTRL.Initialize(session, valueIds);

            MoveBTN_Click(BackBTN, null);

            Show();
            BringToFront();
        }
        /// <summary>
        /// Sets the nodes in the control.
        /// </summary>
        public void Initialize(Session session, ReadValueIdCollection valueIds)
        {
            if (session == null)  throw new ArgumentNullException("session");
            
            Clear();
            
            m_session = session;

            foreach (ReadValueId valueId in valueIds)
            {
                AddItem(valueId);
            }

            AdjustColumns();
        }
        /// <summary>
        /// Sets the nodes in the control.
        /// </summary>
        public void Initialize(
            Session session,
            ReadValueIdCollection valueIds,
            DataValueCollection values,
            List <ServiceResult> results)
        {
            if (session == null)
            {
                throw new ArgumentNullException("session");
            }

            Clear();

            m_session = session;

            if (valueIds != null)
            {
                for (int ii = 0; ii < valueIds.Count; ii++)
                {
                    ValueItem item = new ValueItem();

                    item.Node        = m_session.NodeCache.Find(valueIds[ii].NodeId) as Node;
                    item.AttributeId = valueIds[ii].AttributeId;

                    if (values != null && ii < values.Count)
                    {
                        item.Value = values[ii];
                    }

                    if (results != null && ii < results.Count)
                    {
                        item.Result = results[ii];
                    }

                    AddItem(item, "DataType", -1);
                }
            }

            AdjustColumns();
        }
        public void ReadAllNodes()
        {
            var serverTestServices = new ServerTestServices(m_server);

            if (m_operationLimits == null)
            {
                GetOperationLimits();
            }
            if (m_referenceDescriptions == null)
            {
                m_referenceDescriptions = CommonTestWorkers.BrowseFullAddressSpaceWorker(serverTestServices, m_requestHeader, m_operationLimits);
            }

            // Read all variables
            var requestHeader = m_requestHeader;

            foreach (var reference in m_referenceDescriptions)
            {
                requestHeader.Timestamp = DateTime.UtcNow;
                var nodesToRead = new ReadValueIdCollection();
                var nodeId      = ExpandedNodeId.ToNodeId(reference.NodeId, m_server.CurrentInstance.NamespaceUris);
                foreach (var attributeId in ServerFixtureUtils.AttributesIds.Keys)
                {
                    nodesToRead.Add(new ReadValueId()
                    {
                        NodeId = nodeId, AttributeId = attributeId
                    });
                }
                TestContext.Out.WriteLine("NodeId {0} {1}", reference.NodeId, reference.BrowseName);
                var response = m_server.Read(requestHeader, kMaxAge, TimestampsToReturn.Both, nodesToRead,
                                             out var dataValues, out var diagnosticInfos);
                ServerFixtureUtils.ValidateResponse(response);
                ServerFixtureUtils.ValidateDiagnosticInfos(diagnosticInfos, dataValues);

                foreach (var dataValue in dataValues)
                {
                    TestContext.Out.WriteLine(" {0}", dataValue.ToString());
                }
            }
        }
示例#5
0
 /// <summary>
 /// 批量读取
 /// </summary>
 /// <param name="opcUaDataItems"></param>
 /// <returns></returns>
 public async Task <IList <OpcUaDataItem> > Reads(IList <OpcUaDataItem> opcUaDataItems)
 {
     return(await Task.Run(() =>
     {
         ReadValueIdCollection nodesToRead = new ReadValueIdCollection(opcUaDataItems.Count());
         foreach (var readNode in opcUaDataItems)
         {
             ReadValueId nodeToRead = new ReadValueId()
             {
                 NodeId = new NodeId(readNode.Name),
                 AttributeId = Attributes.Value
             };
             nodesToRead.Add(nodeToRead);
         }
         try
         {
             session.Read(null, 0, TimestampsToReturn.Neither, nodesToRead, out DataValueCollection results, out DiagnosticInfoCollection diagnosticInfos);
             ClientBase.ValidateResponse(results, nodesToRead);
             ClientBase.ValidateDiagnosticInfos(diagnosticInfos, nodesToRead);
             for (int i = 0; i < results.Count; i++)
             {
                 opcUaDataItems[i].OldValue = opcUaDataItems[i].NewValue;
                 opcUaDataItems[i].NewValue = results[i].Value;
                 opcUaDataItems[i].OpcUaStatusCodes = (OpcUaStatusCodes)results[i].StatusCode.Code;
                 //opcUaDataItems[i].ValueType = results[0].WrappedValue.TypeInfo.BuiltInType.GetTypeCode().ToType();
             }
             return opcUaDataItems;
         }
         catch (ServiceResultException e)
         {
             OnErrorHappened?.Invoke(this, new OpcUaErrorEventArgs((OpcUaStatusCodes)e.StatusCode, $"批量读取数据时错误", e));
             return null;
         }
         catch (Exception ex)
         {
             OnErrorHappened?.Invoke(this, new OpcUaErrorEventArgs(OpcUaStatusCodes.Uncertain, $"批量读取数据时发生未知错误", ex));
             return null;
         }
     }));
 }
示例#6
0
        /// <summary>
        /// Read a tag asynchronously
        /// </summary>
        /// <typeparam name="T">The type of tag to read</typeparam>
        /// <param name="tag">tag值</param>
        /// <returns>The value retrieved from the OPC</returns>
        public Task <T> ReadNodeAsync <T>(string tag)
        {
            var nodesToRead = new ReadValueIdCollection {
                new ReadValueId()
                {
                    NodeId      = new NodeId(tag),
                    AttributeId = Attributes.Value
                }
            };

            // Wrap the ReadAsync logic in a TaskCompletionSource, so we can use C# async/await syntax to call it:
            var taskCompletionSource = new TaskCompletionSource <T>();

            Session.BeginRead(
                requestHeader: null,
                maxAge: 0,
                timestampsToReturn: TimestampsToReturn.Neither,
                nodesToRead: nodesToRead,
                callback: ar => {
                DataValueCollection results;
                DiagnosticInfoCollection diag;
                var response = Session.EndRead(
                    result: ar,
                    results: out results,
                    diagnosticInfos: out diag);

                try {
                    CheckReturnValue(response.ServiceResult);
                    CheckReturnValue(results[0].StatusCode);
                    var val = results[0];
                    taskCompletionSource.TrySetResult((T)val.Value);
                } catch (Exception ex) {
                    taskCompletionSource.TrySetException(ex);
                }
            },
                asyncState: null);

            return(taskCompletionSource.Task);
        }
        private DataValueCollection Read(NodeId nodeId, uint attributeId)
        {
            ReadValueIdCollection nodeToRead = new ReadValueIdCollection(1);

            ReadValueId vId = new ReadValueId()
            {
                NodeId      = nodeId,
                AttributeId = attributeId
            };

            nodeToRead.Add(vId);

            var responseRead = m_session.Read(null,
                                              0,
                                              TimestampsToReturn.Both,
                                              nodeToRead,
                                              out var dataValueCollection,
                                              out var diagnCollection
                                              );

            return(dataValueCollection);
        }
示例#8
0
        public static DataValueCollection ReadNodeAttribute(this Session session, NodeId nodeId, uint attributeId)
        {
            var nodeToRead = new ReadValueIdCollection();

            var vId = new ReadValueId()
            {
                NodeId      = nodeId,
                AttributeId = attributeId
            };

            nodeToRead.Add(vId);

            session.Read(null,
                         0,
                         TimestampsToReturn.Both,
                         nodeToRead,
                         out var dataValueCollection,
                         out _
                         );

            return(dataValueCollection);
        }
示例#9
0
        /// <summary>
        /// Returns the expected data type.
        /// </summary>
        private TypeInfo GetExpectedType(Session session, NodeId nodeId)
        {
            // build list of attributes to read.
            ReadValueIdCollection nodesToRead = new ReadValueIdCollection();

            foreach (uint attributeId in new uint[] { Attributes.DataType, Attributes.ValueRank })
            {
                ReadValueId nodeToRead = new ReadValueId();
                nodeToRead.NodeId      = nodeId;
                nodeToRead.AttributeId = attributeId;
                nodesToRead.Add(nodeToRead);
            }

            // read the attributes.
            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);

            // this call checks for error and checks the data type of the value.
            // if an error or mismatch occurs the default value is returned.
            NodeId dataTypeId = results[0].GetValue <NodeId>(null);
            int    valueRank  = results[1].GetValue <int>(ValueRanks.Scalar);

            // use the local type cache to look up the base type for the data type.
            BuiltInType builtInType = DataTypes.GetBuiltInType(dataTypeId, session.NodeCache.TypeTree);

            // the type info object is used in cast and compare functions.
            return(new TypeInfo(builtInType, valueRank));
        }
        /// <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[]);
        }
示例#11
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;
        }
示例#12
0
        public void Read()
        {
            // Read
            var requestHeader = m_requestHeader;

            requestHeader.Timestamp = DateTime.UtcNow;
            var nodesToRead = new ReadValueIdCollection();
            var nodeId      = new NodeId("Scalar_Simulation_Int32", 2);

            foreach (var attributeId in ServerFixtureUtils.AttributesIds.Keys)
            {
                nodesToRead.Add(new ReadValueId()
                {
                    NodeId = nodeId, AttributeId = attributeId
                });
            }
            var response = m_server.Read(requestHeader, MaxAge, TimestampsToReturn.Neither, nodesToRead,
                                         out var dataValues, out var diagnosticInfos);

            ServerFixtureUtils.ValidateResponse(response);
            ServerFixtureUtils.ValidateDiagnosticInfos(diagnosticInfos, dataValues);
        }
示例#13
0
        public dynamic Read(IList nodeids)
        {
            try
            {
                var itemsToRead = new ReadValueIdCollection();

                foreach (string nodeid in nodeids)
                {
                    var rv = new ReadValueId()
                    {
                        NodeId       = new NodeId(nodeid),
                        AttributeId  = Attributes.Value,
                        IndexRange   = null,
                        DataEncoding = null,
                    };
                    itemsToRead.Add(rv);
                }


                DataValueCollection      values;
                DiagnosticInfoCollection diagnosticInfos;

                ResponseHeader responseHeader = client.Read(
                    itemsToRead,
                    out values,
                    out diagnosticInfos);

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

                return(values);
            }
            catch (Exception e)
            {
                System.Diagnostics.Trace.WriteLine(e.Message);
                return(null);
            }
        }
示例#14
0
        private void ReadMI_Click(object sender, EventArgs e)
        {
            try
            {
                if (NodesTV.SelectedItem == null)
                {
                    return;
                }

                ReferenceDescription reference = NodesTV.SelectedItem.Item 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(String.Empty, GuiUtils.CallerName(), exception);
            }
        }
示例#15
0
文件: UaClient.cs 项目: km001/h-opc
        private ReadValueIdCollection BuildReadValueIdCollectionUnderFolders(string[] folders, uint attributeId, ref List <string> tagList, bool needToGoDeeper = false)
        {
            ReadValueIdCollection _rtn = new ReadValueIdCollection();

            foreach (string folder in folders)
            {
                List <string> subFolders = new List <string>();
                var           subNodes   = ExploreFolder(folder);
                foreach (UaNode n in subNodes)
                {
                    if (n.NodeClass == NodeClass.Variable.ToString())
                    {
                        var readValue = new ReadValueId
                        {
                            NodeId      = n.NodeId,
                            AttributeId = attributeId
                        };
                        _rtn.Add(readValue);
                        tagList.Add(n.Tag);
                    }
                    else if (n.NodeClass == NodeClass.Object.ToString() && needToGoDeeper)
                    {
                        subFolders.Add(n.Tag);
                    }
                }
                var subResult = BuildReadValueIdCollectionUnderFolders(subFolders.ToArray(), attributeId, ref tagList);
                _rtn.AddRange(subResult);

                /*var n = FindNode(tag, RootNode);
                 * var readValue = new ReadValueId
                 * {
                 *  NodeId = n.NodeId,
                 *  AttributeId = attributeId
                 * };
                 * _rtn.Add(readValue);*/
            }
            return(_rtn);
        }
示例#16
0
        ///// <summary>
        ///// 批量写入
        ///// </summary>
        ///// <typeparam name="Tin"></typeparam>
        ///// <typeparam name="Tout"></typeparam>
        ///// <param name="writeParams"></param>
        ///// <returns></returns>
        //public async Task<OpcUaStatusCodes[]> Writes(IList<OpcUaDataItem> opcUaDataItems, IList<object> newValues)
        //{
        //    return await Task.Run(() =>
        //    {
        //        //var writeNodes = writeParams as DeviceInputParamEntityBase[];
        //        //OpcUaDeviceOutParamEntity[] opcUaDeviceOutParamEntitys = new OpcUaDeviceOutParamEntity[writeNodes.Count()];
        //        if (Equals(opcUaDataItems, null) || Equals(opcUaDataItems, null))
        //        {
        //            return new OpcUaStatusCodes[1];
        //        }

        //        if (opcUaDataItems.Count != newValues.Count)
        //        {
        //            OnLogHappened?.Invoke(this, new OpcUaLogEventArgs($"写入节点和值的数量不匹配{opcUaDataItems.Count}/{ newValues.Count}"));
        //        }
        //        WriteValueCollection valuesToWrite = new WriteValueCollection(opcUaDataItems.Count());
        //        foreach (var writeNode in opcUaDataItems)
        //        {
        //            WriteValue valueToWrite = new WriteValue();
        //            valueToWrite.NodeId = new NodeId(writeNode.Name);
        //            valueToWrite.AttributeId = Attributes.Value;
        //            valueToWrite.Value.Value = Convert.ChangeType(writeNode.NewValue, writeNode.ValueType ?? typeof(object));
        //            valueToWrite.Value.StatusCode = StatusCodes.Good;
        //            valueToWrite.Value.ServerTimestamp = DateTime.MinValue;
        //            valueToWrite.Value.SourceTimestamp = DateTime.MinValue;
        //            valuesToWrite.Add(valueToWrite);
        //        }
        //        try
        //        {
        //            session.Write(null, valuesToWrite, out StatusCodeCollection results, out DiagnosticInfoCollection diagnosticInfos);
        //            ClientBase.ValidateResponse(results, valuesToWrite);
        //            ClientBase.ValidateDiagnosticInfos(diagnosticInfos, valuesToWrite);
        //            for (int i = 0; i < results.Count; i++)
        //            {


        //                opcUaDataItems[i].OpcUaStatusCodes = (OpcUaStatusCodes)results[i].Code;
        //                //opcUaDataItem.Message = results[0].StatusCode.ToString();
        //                opcUaDataItems[i].OldValue = opcUaDataItems[i].NewValue;
        //                if (results[i].Code == 0)
        //                {
        //                    opcUaDataItems[i].NewValue = newValues[i];
        //                }

        //                //return (OpcUaStatusCodes)results[0].Code;



        //                //OpcUaDeviceOutParamEntity opcUaDeviceOutParamEntity = new OpcUaDeviceOutParamEntity();
        //                //opcUaDeviceOutParamEntity.NodeId = writeNodes[i].NodeId;
        //                //opcUaDeviceOutParamEntity.Value = writeNodes[i].Value;
        //                //opcUaDeviceOutParamEntity.ValueType = valuesToWrite[i].Value.WrappedValue.TypeInfo.BuiltInType.GetTypeCode().ToType();
        //                //opcUaDeviceOutParamEntity.StatusCode = results[i].Code;
        //                //opcUaDeviceOutParamEntity.Message = OpcUaStatusCodes.GetBrowseName(results[i].Code);
        //                //opcUaDeviceOutParamEntitys[i] = opcUaDeviceOutParamEntity;



        //            }
        //            //return null;

        //        }
        //        catch (ServiceResultException e)
        //        {
        //            OnErrorHappened?.Invoke(this, new OpcUaErrorEventArgs((OpcUaStatusCodes)e.StatusCode, $"批量读取数据时错误", e));
        //            return new OpcUaStatusCodes[1];

        //        }
        //        catch (Exception ex)
        //        {
        //            OnErrorHappened?.Invoke(this, new OpcUaErrorEventArgs(OpcUaStatusCodes.Uncertain, $"批量读取数据时发生未知错误", ex));
        //            return new OpcUaStatusCodes[1];

        //        }
        //    });
        //}

        #endregion

        #region 读取数据

        /// <summary>
        /// 读取数据
        /// </summary>
        /// <param name="opcUaDataItem"></param>
        /// <returns></returns>
        public async Task <OpcUaDataItem> Read(OpcUaDataItem opcUaDataItem)
        {
            return(await Task.Run(() =>
            {
                ReadValueId nodeToRead = new ReadValueId()
                {
                    NodeId = new NodeId(opcUaDataItem.Name),
                    AttributeId = Attributes.Value
                };
                ReadValueIdCollection nodesToRead = new ReadValueIdCollection
                {
                    nodeToRead
                };
                try
                {
                    session.Read(null, 0, TimestampsToReturn.Neither, nodesToRead, out DataValueCollection results, out DiagnosticInfoCollection diagnosticInfos);
                    ClientBase.ValidateResponse(results, nodesToRead);
                    ClientBase.ValidateDiagnosticInfos(diagnosticInfos, nodesToRead);
                    opcUaDataItem.OpcUaStatusCodes = (OpcUaStatusCodes)results[0].StatusCode.Code;
                    //opcUaDataItem.Message = results[0].StatusCode.ToString();
                    opcUaDataItem.OldValue = opcUaDataItem.NewValue;
                    opcUaDataItem.NewValue = results[0].Value;
                    //opcUaDataItem.NodeId = readNode.NodeId;
                    //opcUaDataItem.ValueType = results[0].WrappedValue.TypeInfo.BuiltInType.GetTypeCode().ToType();
                    return opcUaDataItem;
                }
                catch (ServiceResultException e)
                {
                    OnErrorHappened?.Invoke(this, new OpcUaErrorEventArgs((OpcUaStatusCodes)e.StatusCode, $"读取数据时错误,{opcUaDataItem.ToString()}", e));
                    return null;
                }
                catch (Exception ex)
                {
                    OnErrorHappened?.Invoke(this, new OpcUaErrorEventArgs(OpcUaStatusCodes.Uncertain, $"读取数据时发生未知错误,{opcUaDataItem.ToString()}", ex));
                    return null;
                }
            }));
        }
示例#17
0
文件: Client.cs 项目: bamchoh/jupiter
        public void ReadBuiltInType(IList viList, out List <BuiltInType> types)
        {
            if (viList.Count == 0)
            {
                types = new List <BuiltInType>();
                return;
            }

            var nodesToRead = new ReadValueIdCollection();

            foreach (Interfaces.IVariableInfo r in viList)
            {
                var nodeToRead = new ReadValueId();
                nodeToRead.NodeId      = this.ToNodeId(r.NodeId);
                nodeToRead.AttributeId = Attributes.DataType;
                nodesToRead.Add(nodeToRead);
            }

            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);

            types = new List <BuiltInType>();
            foreach (var r in results)
            {
                types.Add(TypeInfo.GetBuiltInType((NodeId)r.Value));
            }
        }
示例#18
0
        internal 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);
            }
        }
示例#19
0
 public static Entry For(ReadValueIdCollection nodesToRead)
 {
     if (nodesToRead == null)
     {
         return(new NullEntry());
     }
     else
     {
         ArrayEntry array = new ArrayEntry();
         List <ReadValueId> .Enumerator e = nodesToRead.GetEnumerator();
         while (e.MoveNext())
         {
             ObjectEntry readValueEntry = new ObjectEntry();
             readValueEntry.Add("NodeId", For(e.Current.NodeId));
             readValueEntry.Add("AttributeId", For(e.Current.AttributeId));
             readValueEntry.Add("IndexRange", For(e.Current.IndexRange));
             readValueEntry.Add("DataEncoding", For(e.Current.DataEncoding));
             readValueEntry.Add("Range", For(e.Current.ParsedIndexRange));
             array.Add(readValueEntry);
         }
         return(array);
     }
 }
示例#20
0
        public DataValueCollection                      readAttribute(NodeId aNodeId, uint aAttribute)
        {
            var lAttributeToRead = new ReadValueId();

            lAttributeToRead.NodeId      = aNodeId;
            lAttributeToRead.AttributeId = aAttribute;

            var lValueIdsToRead = new ReadValueIdCollection();

            lValueIdsToRead.Add(lAttributeToRead);

            DataValueCollection      lResults         = null;
            DiagnosticInfoCollection lDiagnosticInfos = null;

            var lResponse = mSession.Read(null, 0, TimestampsToReturn.Neither, lValueIdsToRead, out lResults, out lDiagnosticInfos);

            if ((lResults.Count != 1) || (lResults[0].Value == null))
            {
                return(null);
            }

            return(lResults);
        }
示例#21
0
        public DataValueCollection Read(ReadValueIdCollection nodesToRead)
        {
            if (nodesToRead == null || nodesToRead.Count == 0)
            {
                return(null);
            }

            DataValueCollection      values          = null;
            DiagnosticInfoCollection diagnosticInfos = null;

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

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

            return(values);
        }
        /// <summary>
        /// Reads any attribute of one or more nodes.
        /// </summary>
        /// <param name="nodesToRead">A list of nodes to read.</param>
        /// <param name="results">A list of read results.</param>
        /// <exception cref="Exception">Throws and forwards any exception with short error description.</exception>
        public void Read(
            ReadValueIdCollection nodesToRead,
            out DataValueCollection results)
        {
            results = null;
            DiagnosticInfoCollection diagnosticInfos = null;

            try
            {
                // The actual call to the server.
                m_Session.Read(
                    null,
                    0,
                    TimestampsToReturn.Both,
                    nodesToRead,
                    out results,
                    out diagnosticInfos);
            }
            catch (Exception e)
            {
                throw e;
            }
        }
        /// <summary>
        /// Reads the value attribute of one or more nodes.
        /// </summary>
        /// <param name="nodesToRead">A list of nodes to read.</param>
        /// <param name="results">A list of data values.</param>
        /// <exception cref="Exception">Throws and forwards any exception with short error description.</exception>
        public ResponseHeader ReadValues(
            NodeIdCollection nodesToRead,
            out DataValueCollection results)
        {
            ResponseHeader response = null;

            results = null;
            DiagnosticInfoCollection diagnosticInfos;

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

            try
            {
                for (int i = 0; i < nodesToRead.Count; i++)
                {
                    ReadValueId attributeToRead = new ReadValueId();
                    attributeToRead.NodeId      = nodesToRead[i];
                    attributeToRead.AttributeId = Attributes.Value;
                    attributeToRead.Handle      = attributeIdToString(Attributes.Value);
                    valueIdsToRead.Add(attributeToRead);
                }

                response = m_Session.Read(
                    null,
                    0,
                    TimestampsToReturn.Both,
                    valueIdsToRead,
                    out results,
                    out diagnosticInfos);
            }
            catch (Exception e)
            {
                throw e;
            }
            return(response);
        }
示例#24
0
        /// <summary>
        /// Read a value node from server
        /// </summary>
        /// <param name="nodeId">node id</param>
        /// <returns>DataValue</returns>
        public DataValue ReadNode(NodeId nodeId)
        {
            var nodesToRead = new ReadValueIdCollection {
                new ReadValueId()
                {
                    NodeId      = nodeId,
                    AttributeId = Attributes.Value
                }
            };

            // read the current value
            Session.Read(
                null,
                0,
                TimestampsToReturn.Neither,
                nodesToRead,
                out var results,
                out var diagnosticInfos);

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

            return(results[0]);
        }
示例#25
0
        protected override void ItemsLV_DragDrop(object sender, DragEventArgs e)
        {
            try
            {
                ReferenceDescription reference = e.Data.GetData(typeof(ReferenceDescription)) as ReferenceDescription;

                if (reference != null)
                {
                    AddNodeId(reference);
                }

                ReferenceDescriptionCollection references = e.Data.GetData(typeof(ReferenceDescriptionCollection)) as ReferenceDescriptionCollection;

                if (references != null)
                {
                    foreach (ReferenceDescription current in references)
                    {
                        AddNodeId(current);
                    }
                }

                ReadValueIdCollection valueIds = e.Data.GetData(typeof(ReadValueIdCollection)) as ReadValueIdCollection;

                if (valueIds != null)
                {
                    foreach (ReadValueId valueId in valueIds)
                    {
                        AddItem(valueId.NodeId);
                    }
                }
            }
            catch (Exception exception)
            {
                GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception);
            }
        }
示例#26
0
        /// <summary>
        /// Read using value collection
        /// </summary>
        /// <param name="session"></param>
        /// <param name="requestHeader"></param>
        /// <param name="readValueCollection"></param>
        /// <param name="operations"></param>
        /// <param name="skipAttributeIdInvalid"></param>
        /// <param name="traceOnly"></param>
        /// <returns></returns>
        internal async Task ReadAsync(Session session, RequestHeader requestHeader,
                                      ReadValueIdCollection readValueCollection, List <OperationResultModel> operations,
                                      bool skipAttributeIdInvalid, bool traceOnly)
        {
            var readResponse = await session.ReadAsync(requestHeader, 0,
                                                       TimestampsToReturn.Both, readValueCollection);

            OperationResultEx.Validate("Read_" + LocalId, operations,
                                       readResponse.Results
                                       .Select(v => skipAttributeIdInvalid &&
                                               v.StatusCode == StatusCodes.BadAttributeIdInvalid  ?
                                               StatusCodes.Good : v.StatusCode),
                                       readResponse.DiagnosticInfos, readValueCollection
                                       .Select(v => AttributeMap.GetBrowseName(v.AttributeId)), traceOnly);

            for (var i = 0; i < readValueCollection.Count; i++)
            {
                var attributeId = readValueCollection[i].AttributeId;
                if (readResponse.Results[i].StatusCode != StatusCodes.BadAttributeIdInvalid)
                {
                    _attributes[attributeId] = readResponse.Results[i];
                }
            }
        }
        /// <summary>
        /// Reads the values for the node attributes and returns a node object.
        /// </summary>
        /// <remarks>
        /// If the nodeclass is known, only the supported attribute values are read.
        /// </remarks>
        /// <param name="nodeId">The nodeId.</param>
        /// <param name="nodeClass">The nodeclass of the node to read.</param>
        /// <param name="optionalAttributes">Read optional attributes.</param>
        /// <param name="ct">The cancellation token for the request.</param>
        public async Task <Node> ReadNodeAsync(
            NodeId nodeId,
            NodeClass nodeClass,
            bool optionalAttributes = true,
            CancellationToken ct    = default)
        {
            // build list of attributes.
            var attributes = CreateAttributes(nodeClass, optionalAttributes);

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

            foreach (uint attributeId in attributes.Keys)
            {
                ReadValueId itemToRead = new ReadValueId {
                    NodeId      = nodeId,
                    AttributeId = attributeId
                };
                itemsToRead.Add(itemToRead);
            }

            // read from server.
            ReadResponse readResponse = await ReadAsync(
                null,
                0,
                TimestampsToReturn.Neither,
                itemsToRead, ct).ConfigureAwait(false);

            DataValueCollection      values          = readResponse.Results;
            DiagnosticInfoCollection diagnosticInfos = readResponse.DiagnosticInfos;

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

            return(ProcessReadResponse(readResponse.ResponseHeader, attributes, itemsToRead, values, diagnosticInfos));
        }
示例#28
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];
        }
示例#29
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;
                }
            }
        }
        /// <summary>
        /// Invokes the Read service.
        /// </summary>
        public virtual ResponseHeader Read(
            RequestHeader                requestHeader,
            double                       maxAge,
            TimestampsToReturn           timestampsToReturn,
            ReadValueIdCollection        nodesToRead,
            out DataValueCollection      results,
            out DiagnosticInfoCollection diagnosticInfos)
        {
            results = null;
            diagnosticInfos = null;

            ValidateRequest(requestHeader);

            // Insert implementation.

            return CreateResponse(requestHeader, StatusCodes.BadServiceUnsupported);
        }
示例#31
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;
        }
        /// <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);
            }
        }
示例#34
0
        /// <summary>
        /// Reads the attributes, verifies the results and updates the nodes.
        /// </summary>
        private bool Write(WriteValueCollection nodesToWrite)
        {
            bool success = true;

            StatusCodeCollection     results         = null;
            DiagnosticInfoCollection diagnosticInfos = null;

            RequestHeader requestHeader = new RequestHeader();

            requestHeader.ReturnDiagnostics = 0;

            try
            {
                Session.Write(
                    requestHeader,
                    nodesToWrite,
                    out results,
                    out diagnosticInfos);
            }
            catch (System.ServiceModel.CommunicationException e)
            {
                Log("WARNING: Communication error (random data may have resulted in a message that is too large). {0}", e.Message);
                return(true);
            }
            catch (System.Xml.XmlException e)
            {
                Log("WARNING: XML parsing error (random data may have resulted in a message that is too large). {0}", e.Message);
                return(true);
            }
            catch (ServiceResultException e)
            {
                if (e.StatusCode == StatusCodes.BadEncodingLimitsExceeded)
                {
                    Log("WARNING: Communication error (random data may have resulted in a message that is too large). {0}", e.Message);
                    return(true);
                }

                throw new ServiceResultException(new ServiceResult(e));
            }

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

            // check diagnostics.
            if (diagnosticInfos != null && diagnosticInfos.Count > 0)
            {
                Log("Returned non-empty DiagnosticInfos array during Write.");
                return(false);
            }

            // check results.
            ReadValueIdCollection nodesToRead = new ReadValueIdCollection();

            for (int ii = 0; ii < nodesToWrite.Count; ii++)
            {
                WriteValue   request  = nodesToWrite[ii];
                TestVariable variable = (TestVariable)request.Handle;

                if (results[ii] == StatusCodes.BadUserAccessDenied)
                {
                    continue;
                }

                if (results[ii] == StatusCodes.BadNotWritable)
                {
                    Log(
                        "Write failed when writing a writeable value '{0}'. NodeId = {1}, Value = {2}, StatusCode = {3}",
                        variable.Variable,
                        variable.Variable.NodeId,
                        request.Value.WrappedValue,
                        results[ii]);

                    success = false;
                    break;
                }

                if (StatusCode.IsBad(results[ii]))
                {
                    if (request.Value.StatusCode != StatusCodes.Good)
                    {
                        if (results[ii] != StatusCodes.BadWriteNotSupported)
                        {
                            Log(
                                "Unexpected error when writing the StatusCode for a Value '{0}'. NodeId = {1}, Value = {2}, StatusCode = {3}",
                                variable.Variable,
                                variable.Variable.NodeId,
                                request.Value.WrappedValue,
                                results[ii]);

                            success = false;
                            break;
                        }

                        continue;
                    }

                    if (request.Value.SourceTimestamp != DateTime.MinValue || request.Value.ServerTimestamp != DateTime.MinValue)
                    {
                        if (results[ii] != StatusCodes.BadWriteNotSupported)
                        {
                            Log(
                                "Unexpected error when writing the Timestamp for a Value '{0}'. NodeId = {1}, Value = {2}, StatusCode = {3}",
                                variable.Variable,
                                variable.Variable.NodeId,
                                request.Value.WrappedValue,
                                results[ii]);

                            success = false;
                            break;
                        }

                        continue;
                    }

                    if (results[ii] != StatusCodes.BadTypeMismatch && results[ii] != StatusCodes.BadOutOfRange)
                    {
                        Log(
                            "Unexpected error when writing a valid value '{0}'. NodeId = {1}, Value = {2}, StatusCode = {3}",
                            variable.Variable,
                            variable.Variable.NodeId,
                            request.Value.WrappedValue,
                            results[ii]);

                        success = false;
                        break;
                    }

                    continue;
                }

                ReadValueId nodeToRead = new ReadValueId();

                nodeToRead.NodeId      = request.NodeId;
                nodeToRead.AttributeId = request.AttributeId;
                nodeToRead.IndexRange  = request.IndexRange;
                nodeToRead.Handle      = request.Handle;

                nodesToRead.Add(nodeToRead);
            }

            // skip read back on failed.
            if (!success)
            {
                return(success);
            }

            // check if nothing more do to.
            if (nodesToRead.Count == 0)
            {
                return(true);
            }

            requestHeader = new RequestHeader();
            requestHeader.ReturnDiagnostics = 0;

            DataValueCollection values = new DataValueCollection();

            try
            {
                Session.Read(
                    requestHeader,
                    0,
                    TimestampsToReturn.Both,
                    nodesToRead,
                    out values,
                    out diagnosticInfos);
            }
            catch (System.ServiceModel.CommunicationException e)
            {
                Log("WARNING: Communication error (random data may have resulted in a message that is too large). {0}", e.Message);
                return(true);
            }
            catch (System.Xml.XmlException e)
            {
                Log("WARNING: XML parsing error (random data may have resulted in a message that is too large). {0}", e.Message);
                return(true);
            }
            catch (ServiceResultException e)
            {
                if (e.StatusCode == StatusCodes.BadEncodingLimitsExceeded)
                {
                    Log("WARNING: Communication error (random data may have resulted in a message that is too large). {0}", e.Message);
                    return(true);
                }

                throw new ServiceResultException(new ServiceResult(e));
            }

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

            // check diagnostics.
            if (diagnosticInfos != null && diagnosticInfos.Count > 0)
            {
                Log("Returned non-empty DiagnosticInfos array during Read.");
                return(false);
            }

            for (int ii = 0; ii < nodesToRead.Count; ii++)
            {
                ReadValueId  request      = nodesToRead[ii];
                TestVariable variable     = (TestVariable)request.Handle;
                DataValue    valueWritten = variable.Values[variable.Values.Count - 1];

                if (StatusCode.IsBad(values[ii].StatusCode) && StatusCode.IsNotBad(valueWritten.StatusCode))
                {
                    Log(
                        "Could not read back the value written '{0}'. NodeId = {1}, Value = {2}, StatusCode = {3}",
                        variable.Variable,
                        variable.Variable.NodeId,
                        valueWritten.WrappedValue,
                        values[ii].StatusCode);

                    success = false;
                    break;
                }

                Opc.Ua.Test.DataComparer comparer = new Opc.Ua.Test.DataComparer(Session.MessageContext);
                comparer.ThrowOnError = false;

                if (!comparer.CompareVariant(values[ii].WrappedValue, valueWritten.WrappedValue))
                {
                    Log(
                        "Read back value does not match the value written '{0}'. NodeId = {1}, Value = {2}, ReadValue = {3}",
                        variable.Variable,
                        variable.Variable.NodeId,
                        valueWritten.WrappedValue,
                        values[ii].WrappedValue);

                    success = false;
                    break;
                }

                if (valueWritten.StatusCode != StatusCodes.Good)
                {
                    if (values[ii].StatusCode != valueWritten.StatusCode)
                    {
                        Log(
                            "Read back StatusCode does not match the StatusCode written '{0}'. NodeId = {1}, StatusCode = {2}, ReadStatusCode = {3}",
                            variable.Variable,
                            variable.Variable.NodeId,
                            valueWritten.StatusCode,
                            values[ii].StatusCode);

                        success = false;
                        break;
                    }
                }

                if (valueWritten.SourceTimestamp != DateTime.MinValue)
                {
                    if (values[ii].SourceTimestamp != valueWritten.SourceTimestamp)
                    {
                        Log(
                            "Read back ServerTimestamp does not match the ServerTimestamp written '{0}'. NodeId = {1}, Timestamp = {2}, ReadTimestamp = {3}",
                            variable.Variable,
                            variable.Variable.NodeId,
                            valueWritten.SourceTimestamp,
                            values[ii].SourceTimestamp);

                        success = false;
                        break;
                    }
                }
            }

            return(success);
        }
示例#35
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);
            }
        }
示例#36
0
        /// <summary>
        /// Read a list of nodes from Server
        /// </summary>
        public void ReadNodes()
        {
            if (m_session == null || m_session.Connected == false)
            {
                m_output.WriteLine("Session not connected!");
                return;
            }

            try
            {
                #region Read a node by calling the Read Service

                // build a list of nodes to be read
                ReadValueIdCollection nodesToRead = new ReadValueIdCollection()
                {
                    // Value of ServerStatus
                    new ReadValueId()
                    {
                        NodeId = Variables.Server_ServerStatus, AttributeId = Attributes.Value
                    },
                    // BrowseName of ServerStatus_StartTime
                    new ReadValueId()
                    {
                        NodeId = Variables.Server_ServerStatus_StartTime, AttributeId = Attributes.BrowseName
                    },
                    // Value of ServerStatus_StartTime
                    new ReadValueId()
                    {
                        NodeId = Variables.Server_ServerStatus_StartTime, AttributeId = Attributes.Value
                    }
                };

                // Read the node attributes
                m_output.WriteLine("Reading nodes...");

                // Call Read Service
                m_session.Read(
                    null,
                    0,
                    TimestampsToReturn.Both,
                    nodesToRead,
                    out DataValueCollection resultsValues,
                    out DiagnosticInfoCollection diagnosticInfos);

                // Validate the results
                m_validateResponse(resultsValues, nodesToRead);

                // Display the results.
                foreach (DataValue result in resultsValues)
                {
                    m_output.WriteLine("Read Value = {0} , StatusCode = {1}", result.Value, result.StatusCode);
                }
                #endregion

                #region Read the Value attribute of a node by calling the Session.ReadValue method
                // Read Server NamespaceArray
                m_output.WriteLine("Reading Value of NamespaceArray node...");
                DataValue namespaceArray = m_session.ReadValue(Variables.Server_NamespaceArray);
                // Display the result
                m_output.WriteLine($"NamespaceArray Value = {namespaceArray}");
                #endregion
            }
            catch (Exception ex)
            {
                // Log Error
                m_output.WriteLine($"Read Nodes Error : {ex.Message}.");
            }
        }
示例#37
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);
                }
            }
        }
示例#38
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);
        }
示例#39
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);
            }
        }
        /// <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;
        }
示例#41
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;
                }
            }
        }
示例#42
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;
            }
        }
示例#43
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);
                }
            }
        }
示例#44
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);
            }
        }
        /// <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);
            }
        }
示例#46
0
        /// <summary>
        /// 读取一个节点的所有属性
        /// </summary>
        /// <param name="tag">节点信息</param>
        /// <returns>节点的特性值</returns>
        public OpcNodeAttribute[] ReadNoteAttributes(string tag)
        {
            NodeId sourceId = new NodeId(tag);
            ReadValueIdCollection nodesToRead = new ReadValueIdCollection( );

            // attempt to read all possible attributes.
            // 尝试着去读取所有可能的特性
            for (uint ii = Attributes.NodeClass; ii <= Attributes.UserExecutable; ii++)
            {
                ReadValueId nodeToRead = new ReadValueId( );
                nodeToRead.NodeId      = sourceId;
                nodeToRead.AttributeId = ii;
                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(m_session, nodesToBrowse, false);

            if (references == null)
            {
                return(new OpcNodeAttribute[0]);
            }

            for (int ii = 0; ii < references.Count; ii++)
            {
                // ignore external references.
                if (references[ii].NodeId.IsAbsolute)
                {
                    continue;
                }

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

            // read all values.
            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);

            // process results.


            List <OpcNodeAttribute> nodeAttribute = new List <OpcNodeAttribute>( );

            for (int ii = 0; ii < results.Count; ii++)
            {
                OpcNodeAttribute item = new OpcNodeAttribute( );

                // process attribute value.
                if (ii < startOfProperties)
                {
                    // ignore attributes which are invalid for the node.
                    if (results[ii].StatusCode == StatusCodes.BadAttributeIdInvalid)
                    {
                        continue;
                    }

                    // get the name of the attribute.
                    item.Name = Attributes.GetBrowseName(nodesToRead[ii].AttributeId);

                    // display any unexpected error.
                    if (StatusCode.IsBad(results[ii].StatusCode))
                    {
                        item.Type  = Utils.Format("{0}", Attributes.GetDataTypeId(nodesToRead[ii].AttributeId));
                        item.Value = Utils.Format("{0}", results[ii].StatusCode);
                    }

                    // display the value.
                    else
                    {
                        TypeInfo typeInfo = TypeInfo.Construct(results[ii].Value);

                        item.Type = typeInfo.BuiltInType.ToString( );

                        if (typeInfo.ValueRank >= ValueRanks.OneOrMoreDimensions)
                        {
                            item.Type += "[]";
                        }

                        item.Value = results[ii].Value;//Utils.Format("{0}", results[ii].Value);
                    }
                }

                // process property value.
                else
                {
                    // ignore properties which are invalid for the node.
                    if (results[ii].StatusCode == StatusCodes.BadNodeIdUnknown)
                    {
                        continue;
                    }

                    // get the name of the property.
                    item.Name = Utils.Format("{0}", references[ii - startOfProperties]);

                    // display any unexpected error.
                    if (StatusCode.IsBad(results[ii].StatusCode))
                    {
                        item.Type  = String.Empty;
                        item.Value = Utils.Format("{0}", results[ii].StatusCode);
                    }

                    // display the value.
                    else
                    {
                        TypeInfo typeInfo = TypeInfo.Construct(results[ii].Value);

                        item.Type = typeInfo.BuiltInType.ToString( );

                        if (typeInfo.ValueRank >= ValueRanks.OneOrMoreDimensions)
                        {
                            item.Type += "[]";
                        }

                        item.Value = results[ii].Value; //Utils.Format("{0}", results[ii].Value);
                    }
                }

                nodeAttribute.Add(item);
            }

            return(nodeAttribute.ToArray( ));
        }
示例#47
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();
        }
        /// <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[];
        }
示例#49
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;
        }
示例#50
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;
        }
示例#51
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;
            }
        }
示例#52
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;
            }            
        }
示例#53
0
        /// <summary>
        /// 读取一个节点的所有属性
        /// </summary>
        /// <param name="tag">节点值</param>
        /// <returns>所有的数据</returns>
        public DataValue[] ReadNoteDataValueAttributes(string tag)
        {
            NodeId sourceId = new NodeId(tag);
            ReadValueIdCollection nodesToRead = new ReadValueIdCollection( );

            // attempt to read all possible attributes.
            // 尝试着去读取所有可能的特性
            for (uint ii = Attributes.NodeId; ii <= Attributes.UserExecutable; ii++)
            {
                ReadValueId nodeToRead = new ReadValueId( );
                nodeToRead.NodeId      = sourceId;
                nodeToRead.AttributeId = ii;
                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(m_session, nodesToBrowse, false);

            if (references == null)
            {
                return(new DataValue[0]);
            }

            for (int ii = 0; ii < references.Count; ii++)
            {
                // ignore external references.
                if (references[ii].NodeId.IsAbsolute)
                {
                    continue;
                }

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

            // read all values.
            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.ToArray( ));
        }
        /// <summary>
        /// Invokes the Read service.
        /// </summary>
        /// <param name="requestHeader">The request header.</param>
        /// <param name="maxAge">The Maximum age of the value to be read in milliseconds.</param>
        /// <param name="timestampsToReturn">The type of timestamps to be returned for the requested Variables.</param>
        /// <param name="nodesToRead">The list of Nodes and their Attributes to read.</param>
        /// <param name="results">The list of returned Attribute values</param>
        /// <param name="diagnosticInfos">The diagnostic information for the results.</param>
        /// <returns>
        /// Returns a <see cref="ResponseHeader"/> object
        /// </returns>
        public override ResponseHeader Read(
            RequestHeader                requestHeader, 
            double                       maxAge, 
            TimestampsToReturn           timestampsToReturn, 
            ReadValueIdCollection        nodesToRead, 
            out DataValueCollection      results, 
            out DiagnosticInfoCollection diagnosticInfos)
        {
            OperationContext context = ValidateRequest(requestHeader, RequestType.Read);

            try
            {
                if (nodesToRead == null || nodesToRead.Count == 0)
                {
                    throw new ServiceResultException(StatusCodes.BadNothingToDo);
                }

                m_serverInternal.NodeManager.Read(
                    context,
                    maxAge,
                    timestampsToReturn,
                    nodesToRead,
                    out results,
                    out diagnosticInfos);

                return CreateResponse(requestHeader, context.StringTable);  
            }
            catch (ServiceResultException e)
            {
                lock (ServerInternal.DiagnosticsLock)
                {
                    ServerInternal.ServerDiagnostics.RejectedRequestsCount++;

                    if (IsSecurityError(e.StatusCode))
                    {
                        ServerInternal.ServerDiagnostics.SecurityRejectedRequestsCount++;
                    }
                }

                throw TranslateException(context, e);
            }  
            finally
            {
                OnRequestComplete(context);
            } 
        }
        /// <summary>
        /// Create read request.
        /// </summary>
        /// <param name="refDescription"></param>
        /// <param name="nodesToRead"></param>
        private void buildAttributeList(ReferenceDescription refDescription, out ReadValueIdCollection nodesToRead)
        {
            // Build list of attributes to read.
            nodesToRead = new ReadValueIdCollection();

            // Add default attributes (for all nodeclasses)
            addAttribute(refDescription.NodeId.ToNodeId(Session.NamespaceUris), Attributes.NodeId, nodesToRead);
            addAttribute(refDescription.NodeId.ToNodeId(Session.NamespaceUris), Attributes.NodeClass, nodesToRead);
            addAttribute(refDescription.NodeId.ToNodeId(Session.NamespaceUris), Attributes.BrowseName, nodesToRead);
            addAttribute(refDescription.NodeId.ToNodeId(Session.NamespaceUris), Attributes.DisplayName, nodesToRead);
            addAttribute(refDescription.NodeId.ToNodeId(Session.NamespaceUris), Attributes.Description, nodesToRead);
            addAttribute(refDescription.NodeId.ToNodeId(Session.NamespaceUris), Attributes.WriteMask, nodesToRead);
            addAttribute(refDescription.NodeId.ToNodeId(Session.NamespaceUris), Attributes.UserWriteMask, nodesToRead);

            // Add nodeclass specific attributes
            switch (refDescription.NodeClass)
            {
            case NodeClass.Object:
                addAttribute(refDescription.NodeId.ToNodeId(Session.NamespaceUris), Attributes.EventNotifier, nodesToRead);
                break;

            case NodeClass.Variable:
                addAttribute(refDescription.NodeId.ToNodeId(Session.NamespaceUris), Attributes.Value, nodesToRead);
                addAttribute(refDescription.NodeId.ToNodeId(Session.NamespaceUris), Attributes.DataType, nodesToRead);
                addAttribute(refDescription.NodeId.ToNodeId(Session.NamespaceUris), Attributes.ValueRank, nodesToRead);
                addAttribute(refDescription.NodeId.ToNodeId(Session.NamespaceUris), Attributes.ArrayDimensions, nodesToRead);
                addAttribute(refDescription.NodeId.ToNodeId(Session.NamespaceUris), Attributes.AccessLevel, nodesToRead);
                addAttribute(refDescription.NodeId.ToNodeId(Session.NamespaceUris), Attributes.UserAccessLevel, nodesToRead);
                addAttribute(refDescription.NodeId.ToNodeId(Session.NamespaceUris), Attributes.MinimumSamplingInterval, nodesToRead);
                addAttribute(refDescription.NodeId.ToNodeId(Session.NamespaceUris), Attributes.Historizing, nodesToRead);
                break;

            case NodeClass.Method:
                addAttribute(refDescription.NodeId.ToNodeId(Session.NamespaceUris), Attributes.Executable, nodesToRead);
                addAttribute(refDescription.NodeId.ToNodeId(Session.NamespaceUris), Attributes.UserExecutable, nodesToRead);
                break;

            case NodeClass.ObjectType:
                addAttribute(refDescription.NodeId.ToNodeId(Session.NamespaceUris), Attributes.IsAbstract, nodesToRead);
                break;

            case NodeClass.VariableType:
                addAttribute(refDescription.NodeId.ToNodeId(Session.NamespaceUris), Attributes.Value, nodesToRead);
                addAttribute(refDescription.NodeId.ToNodeId(Session.NamespaceUris), Attributes.DataType, nodesToRead);
                addAttribute(refDescription.NodeId.ToNodeId(Session.NamespaceUris), Attributes.ValueRank, nodesToRead);
                addAttribute(refDescription.NodeId.ToNodeId(Session.NamespaceUris), Attributes.ArrayDimensions, nodesToRead);
                addAttribute(refDescription.NodeId.ToNodeId(Session.NamespaceUris), Attributes.IsAbstract, nodesToRead);
                break;

            case NodeClass.ReferenceType:
                addAttribute(refDescription.NodeId.ToNodeId(Session.NamespaceUris), Attributes.IsAbstract, nodesToRead);
                addAttribute(refDescription.NodeId.ToNodeId(Session.NamespaceUris), Attributes.Symmetric, nodesToRead);
                addAttribute(refDescription.NodeId.ToNodeId(Session.NamespaceUris), Attributes.InverseName, nodesToRead);
                break;

            case NodeClass.DataType:
                addAttribute(refDescription.NodeId.ToNodeId(Session.NamespaceUris), Attributes.IsAbstract, nodesToRead);
                break;

            case NodeClass.View:
                addAttribute(refDescription.NodeId.ToNodeId(Session.NamespaceUris), Attributes.ContainsNoLoops, nodesToRead);
                addAttribute(refDescription.NodeId.ToNodeId(Session.NamespaceUris), Attributes.EventNotifier, nodesToRead);
                break;

            default:
                break;
            }
        }
示例#56
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);
        }
示例#57
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);
        }
示例#58
0
        /// <summary>
        /// Used by the performance test.
        /// </summary>
        public override ResponseHeader Read(
            RequestHeader                requestHeader, 
            double                       maxAge, 
            TimestampsToReturn           timestampsToReturn, 
            ReadValueIdCollection        nodesToRead, 
            out DataValueCollection      values, 
            out DiagnosticInfoCollection diagnosticInfos)
        {
            if (requestHeader.ReturnDiagnostics != 5000)
            {
                return base.Read(requestHeader, maxAge, timestampsToReturn, nodesToRead, out values, out diagnosticInfos);
            }

            diagnosticInfos = null;

            DataValue value = new DataValue();
            
            value.WrappedValue    = new Variant((int)1);
            value.SourceTimestamp = DateTime.UtcNow;

            values = new DataValueCollection(nodesToRead.Count);

            foreach (ReadValueId valueId in nodesToRead)
            {
                values.Add(value);
            }
            
            return new ResponseHeader();
        }                    
示例#59
0
        /// <summary>
        /// Reads the attributes, verifies the results and updates the nodes.
        /// </summary>
        private bool WriteBadValues(WriteValueCollection nodesToWrite)
        {
            bool success = true;

            StatusCodeCollection     results;
            DiagnosticInfoCollection diagnosticInfos;

            RequestHeader requestHeader = new RequestHeader();

            requestHeader.ReturnDiagnostics = 0;

            try
            {
                Session.Write(
                    requestHeader,
                    nodesToWrite,
                    out results,
                    out diagnosticInfos);
            }
            catch (System.ServiceModel.CommunicationException e)
            {
                Log("WARNING: Communication error (random data may have resulted in a message that is too large). {0}", e.Message);
                return(true);
            }
            catch (System.Xml.XmlException e)
            {
                Log("WARNING: XML parsing error (random data may have resulted in a message that is too large). {0}", e.Message);
                return(true);
            }
            catch (ServiceResultException e)
            {
                if (e.StatusCode == StatusCodes.BadEncodingLimitsExceeded)
                {
                    Log("WARNING: Communication error (random data may have resulted in a message that is too large). {0}", e.Message);
                    return(true);
                }

                throw new ServiceResultException(new ServiceResult(e));
            }

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

            // check diagnostics.
            if (diagnosticInfos != null && diagnosticInfos.Count > 0)
            {
                Log("Returned non-empty DiagnosticInfos array during Write.");
                return(false);
            }

            // check results.
            ReadValueIdCollection nodesToRead = new ReadValueIdCollection();

            for (int ii = 0; ii < nodesToWrite.Count; ii++)
            {
                WriteValue   request  = nodesToWrite[ii];
                TestVariable variable = (TestVariable)request.Handle;

                // allow access denied even if the node was theorectically writeable.
                if (results[ii] == StatusCodes.BadUserAccessDenied)
                {
                    continue;
                }

                if (results[ii] == StatusCodes.BadNotWritable)
                {
                    Log(
                        "Write failed when writing a writeable value '{0}'. NodeId = {1}, Value = {2}, StatusCode = {3}",
                        variable.Variable,
                        variable.Variable.NodeId,
                        request.Value.WrappedValue,
                        results[ii]);

                    success = false;
                    break;
                }

                TypeInfo typeInfo = TypeInfo.IsInstanceOfDataType(
                    request.Value.Value,
                    variable.Variable.DataType,
                    variable.Variable.ValueRank,
                    Session.NamespaceUris,
                    Session.TypeTree);

                if (typeInfo != null)
                {
                    if (results[ii] != StatusCodes.Good && results[ii] != StatusCodes.BadTypeMismatch && results[ii] != StatusCodes.BadOutOfRange)
                    {
                        Log(
                            "Unexpected error when writing a valid value for a Variable '{0}'. NodeId = {1}, Value = {2}, StatusCode = {3}",
                            variable.Variable,
                            variable.Variable.NodeId,
                            request.Value.WrappedValue,
                            results[ii]);

                        success = false;
                        break;
                    }

                    continue;
                }

                if (results[ii] != StatusCodes.BadTypeMismatch && results[ii] != StatusCodes.BadOutOfRange)
                {
                    Log(
                        "Unexpected error when writing a bad value for a Variable '{0}'. NodeId = {1}, Value = {2}, StatusCode = {3}",
                        variable.Variable,
                        variable.Variable.NodeId,
                        request.Value.WrappedValue,
                        results[ii]);

                    success = false;
                    break;
                }
            }

            return(success);
        }
示例#60
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;
        }