Example #1
0
        public Variant ReadVariable(RemoteVariable remoteVariable)
        {
            if (string.IsNullOrWhiteSpace(remoteVariable.Name))
            {
                throw new Exception("Method name is empty!");
            }

            if (_parentNode == null)
            {
                throw new Exception($"Parent node is null for method '{remoteVariable.Name}'!");
            }

            var readValue = new ReadValueId
            {
                NodeId      = BrowseNodeId(_parentNode, remoteVariable.Name),
                AttributeId = Attributes.Value
            };

            var result = _session.Read(new List <ReadValueId> {
                readValue
            }, 0, TimestampsToReturn.Both,
                                       new RequestSettings {
                OperationTimeout = 10000
            });

            if (result == null || result.Count < 1)
            {
                throw new Exception($"Cannot read UA Variable {_parentNode.Identifier}.{remoteVariable.Name} on server.");
            }

            return(result[0].WrappedValue);
        }
Example #2
0
        /// <see cref="BaseListCtrl.UpdateItem" />
        protected override void UpdateItem(ListViewItem listItem, object item)
        {
            ReadValueId valueId = item as ReadValueId;

            if (valueId == null)
            {
                base.UpdateItem(listItem, item);
                return;
            }

            INode node = m_session.NodeCache.Find(valueId.NodeId);

            if (node != null)
            {
                listItem.SubItems[0].Text = String.Format("{0}", node);
            }
            else
            {
                listItem.SubItems[0].Text = String.Format("{0}", valueId.NodeId);
            }

            listItem.SubItems[1].Text = String.Format("{0}", valueId.NodeId);
            listItem.SubItems[2].Text = String.Format("{0}", Attributes.GetBrowseName(valueId.AttributeId));
            listItem.SubItems[3].Text = String.Format("{0}", valueId.IndexRange);
            listItem.SubItems[4].Text = String.Format("{0}", valueId.DataEncoding);

            listItem.Tag      = item;
            listItem.ImageKey = "Method";
        }
Example #3
0
File: OPC.cs Project: krzyfre/HMI
        public static async Task <DataValue[]> ReadVar(int node, string[] VarNames)
        {
            try
            {
                ReadValueId[] valuesToRead = new ReadValueId[VarNames.Length];
                for (int i = 0; i < VarNames.Length; i++)
                {
                    valuesToRead[i] = new ReadValueId
                    {
                        // you can parse the nodeId from a string.
                        NodeId = NodeId.Parse("ns=" + node.ToString() + ";s=" + VarNames[i]),
                        // variable class nodes have a Value attribute.
                        AttributeId = AttributeIds.Value
                    };
                }

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

                return(readResult.Results);
            }
            catch (Exception ex)
            {
                //await channel.AbortAsync();
                return(null);
            }
        }
        /// <summary>
        /// Reads first/next level of tag tree.
        /// </summary>
        async Task <Tag> ReadTag(ReferenceDescription[] rds, UaTcpSessionChannel channel, Tag tag)
        {
            ReadValueId[] items = new ReadValueId[1];
            items[0] = new ReadValueId {
                NodeId = NodeId.Parse(rds.Last().NodeId.ToString()), AttributeId = AttributeIds.DataType
            };
            ReadRequest readRequest = new ReadRequest {
                NodesToRead = items
            };
            ReadResponse readResponse = await channel.ReadAsync(readRequest);

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

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

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

            return(tag);
        }
Example #5
0
 public string VariableRead(string node)
 {
     try
     {
         DataValueCollection      values          = null;
         DiagnosticInfoCollection diagnosticInfos = null;
         ReadValueIdCollection    nodesToRead     = new ReadValueIdCollection();
         ReadValueId valueId = new ReadValueId();
         valueId.NodeId       = new NodeId(node);
         valueId.AttributeId  = Attributes.Value;
         valueId.IndexRange   = null;
         valueId.DataEncoding = null;
         nodesToRead.Add(valueId);
         ResponseHeader responseHeader = session.Read(null, 0, TimestampsToReturn.Both, nodesToRead, out values, out diagnosticInfos);
         string         value          = "";
         if (values[0].Value != null)
         {
             var rawValue = values[0].WrappedValue.ToString();
             value = rawValue.Replace("|", "\r\n").Replace("{", "").Replace("}", "");
         }
         return(value);
     }
     catch
     {
         return(null);
     }
 }
Example #6
0
        /// <summary>
        /// read specified node data from server
        /// <summary>
        private object Read_Node(NodeId nodeid)
        {
            DataValueCollection      results;
            DiagnosticInfoCollection diagnosticInfos;
            ReadValueIdCollection    valuesToRead = new ReadValueIdCollection();

            ReadValueId valueToRead = new ReadValueId();

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

            valuesToRead.Add(valueToRead);

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

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

            if (!StatusCode.IsGood(results.Last().StatusCode))
            {
                string message_status = String.Format("Error! Read from node ({0}) status code: {1}", nodeid.ToString(), results.Last().StatusCode);
                Debug.WriteLine(message_status);
            }
            return(val);
        }
        /// <summary>
        /// Prompts the user to specify the browse options.
        /// </summary>
        public bool ShowDialog(Session session, ReadValueId valueId)
        {
            if (session == null) throw new ArgumentNullException("session");
            if (valueId == null) throw new ArgumentNullException("valueId");

            NodeIdCTRL.Browser = new Browser(session);

            INode node = session.NodeCache.Find(valueId.NodeId);

            if (node != null)
            {
                DisplayNameTB.Text = node.ToString();
            }

            NodeIdCTRL.Identifier      = valueId.NodeId;
            AttributeIdCB.SelectedItem = Attributes.GetBrowseName(valueId.AttributeId);
            IndexRangeTB.Text          = valueId.IndexRange;
            EncodingCB.Text            = (valueId.DataEncoding != null)?valueId.DataEncoding.Name:null;
         
            if (ShowDialog() != DialogResult.OK)
            {
                return false;
            }

            valueId.NodeId      = NodeIdCTRL.Identifier;
            valueId.AttributeId = Attributes.GetIdentifier((string)AttributeIdCB.SelectedItem);
            valueId.IndexRange  = IndexRangeTB.Text;            
         
            if (String.IsNullOrEmpty(EncodingCB.Text))
            {
                valueId.DataEncoding = new QualifiedName(EncodingCB.Text);
            }

            return true;
        }
Example #8
0
        private void ReadMI_Click(object sender, EventArgs e)
        {
            try {
                if (NodesTV.SelectedNode == null)
                {
                    return;
                }

                ReferenceDescription reference = NodesTV.SelectedNode.Tag as ReferenceDescription;

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

                Session session = m_browser.Session;

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

                ReadValueId valueId = new ReadValueId();

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

                valueIds.Add(valueId);

                // show form.
                new ReadDlg().Show(session, valueIds);
            } catch (Exception exception) {
                GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception);
            }
        }
        private DataValueCollection Read_Value(string node)
        {
            //Read variables in the server’s address space
            ReadValueIdCollection nodesToRead = new ReadValueIdCollection();
            ReadValueId           nodeToRead  = new ReadValueId();

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

            DataValueCollection      results         = null;
            DiagnosticInfoCollection diagnosticInfos = null;

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

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

            return(results);
        }
Example #10
0
        /// <summary>
        /// Read a value node from server
        /// </summary>
        /// <typeparam name="T">type of value</typeparam>
        /// <param name="tag">node id</param>
        /// <returns></returns>
        public T ReadNode <T>(string tag)
        {
            ReadValueId nodeToRead = new ReadValueId()
            {
                NodeId      = new NodeId(tag),
                AttributeId = Attributes.Value
            };
            ReadValueIdCollection nodesToRead = new ReadValueIdCollection
            {
                nodeToRead
            };

            // read the current value
            m_session.Read(
                null,
                0,
                TimestampsToReturn.Neither,
                nodesToRead,
                out DataValueCollection results,
                out DiagnosticInfoCollection diagnosticInfos);

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

            return((T)results[0].Value);
        }
Example #11
0
        /// <summary>
        /// Adds a value to the control.
        /// </summary>
        public void AddValueId(ReferenceDescription reference)
        {
            Node node = m_session.NodeCache.Find(reference.NodeId) as Node;

            if (node == null)
            {
                return;
            }

            ReadValueId valueId = new ReadValueId();

            valueId.NodeId       = node.NodeId;
            valueId.AttributeId  = Attributes.Value;
            valueId.IndexRange   = null;
            valueId.DataEncoding = null;

            // read the display name for non-variables.
            if ((node.NodeClass & (NodeClass.Variable | NodeClass.VariableType)) == 0)
            {
                valueId.AttributeId = Attributes.DisplayName;
            }

            AddItem(valueId);
            AdjustColumns();
        }
        /// <summary>
        /// Reads the value for a node.
        /// </summary>
        /// <param name="nodeId">The node Id.</param>
        /// <param name="ct">The cancellation token for the request.</param>
        public async Task <DataValue> ReadValueAsync(
            NodeId nodeId,
            CancellationToken ct = default)
        {
            ReadValueId itemToRead = new ReadValueId {
                NodeId      = nodeId,
                AttributeId = Attributes.Value
            };

            ReadValueIdCollection itemsToRead = new ReadValueIdCollection {
                itemToRead
            };

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

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

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

            if (StatusCode.IsBad(values[0].StatusCode))
            {
                ServiceResult result = ClientBase.GetResult(values[0].StatusCode, 0, diagnosticInfos, readResponse.ResponseHeader);
                throw new ServiceResultException(result);
            }

            return(values[0]);
        }
Example #13
0
        /// <summary>
        /// Gets the result.
        /// </summary>
        /// <param name="context">The context.</param>
        /// <param name="source">The source.</param>
        /// <param name="nodeToRead">The node to read.</param>
        /// <param name="value">The value.</param>
        /// <param name="diagnosticsMasks">The diagnostics masks.</param>
        /// <returns></returns>
        public ServiceResult GetResult(
            ISystemContext context,
            NodeState source,
            ReadValueId nodeToRead,
            DataValue value,
            DiagnosticsMasks diagnosticsMasks)
        {
            HdaReadRequest request = nodeToRead.Handle as HdaReadRequest;

            if (request == null)
            {
                return(StatusCodes.Good);
            }

            // read item value.
            HdaItemState item = source as HdaItemState;

            if (item != null)
            {
                return(request.GetResult(context, item, nodeToRead, value, diagnosticsMasks));
            }

            // read vendor defined attribute value.
            HdaAttributeState attribute = source as HdaAttributeState;

            if (attribute != null)
            {
                return(request.GetResult(context, attribute, nodeToRead, value, diagnosticsMasks));
            }

            return(StatusCodes.Good);
        }
Example #14
0
        /// <summary>
        /// Queues the value to the monitored item.
        /// </summary>
        /// <param name="context">The context.</param>
        /// <param name="request">The request.</param>
        /// <param name="monitoredItem">The monitored item.</param>
        private void QueueValue(ServerSystemContext context, HdaReadRequest request, MonitoredItem monitoredItem)
        {
            NodeHandle handle = monitoredItem.ManagerHandle as NodeHandle;

            if (handle == null)
            {
                return;
            }

            ReadValueId   nodeToRead = monitoredItem.GetReadValueId();
            DataValue     value      = new DataValue();
            ServiceResult error      = null;

            HdaItemState      item      = handle.Node as HdaItemState;
            HdaAttributeState attribute = handle.Node as HdaAttributeState;

            if (item != null)
            {
                error = request.GetResult(context, item, nodeToRead, value, monitoredItem.DiagnosticsMasks);
            }
            else if (attribute != null)
            {
                error = request.GetResult(context, attribute, nodeToRead, value, monitoredItem.DiagnosticsMasks);
            }

            value.ServerTimestamp = DateTime.UtcNow;

            if (value.StatusCode != StatusCodes.BadNotFound)
            {
                monitoredItem.QueueValue(value, error);
            }
        }
Example #15
0
        /// <summary>
        /// Adds a read request for the specified item.
        /// </summary>
        /// <param name="item">The item.</param>
        /// <param name="nodeToRead">The node to read.</param>
        /// <param name="queued">if set to <c>true</c> if a request was created.</param>
        /// <returns>Any error.</returns>
        private StatusCode Add(HdaItemState item, ReadValueId nodeToRead, out bool queued)
        {
            queued = true;

            switch (nodeToRead.AttributeId)
            {
            case Attributes.Description:
            {
                nodeToRead.Handle = Add(item.ItemId, Constants.OPCHDA_DESCRIPTION);
                break;
            }

            case Attributes.DataType:
            case Attributes.ValueRank:
            {
                nodeToRead.Handle = Add(item.ItemId, Constants.OPCHDA_DATA_TYPE);
                break;
            }

            case Attributes.Historizing:
            {
                nodeToRead.Handle = Add(item.ItemId, Constants.OPCHDA_ARCHIVING);
                break;
            }

            default:
            {
                queued = false;
                break;
            }
            }

            return(StatusCodes.Good);
        }
Example #16
0
        /// <summary>
        /// Adds a request for the specified source.
        /// </summary>
        /// <param name="source">The source.</param>
        /// <param name="nodeToRead">The node to read.</param>
        /// <param name="value">The value.</param>
        /// <param name="queued">if set to <c>true</c> [queued].</param>
        /// <returns></returns>
        public StatusCode Add(NodeState source, ReadValueId nodeToRead, DataValue value, out bool queued)
        {
            queued = true;

            // read item value.
            DaItemState item = source as DaItemState;

            if (item != null)
            {
                return(Add(item, nodeToRead, out queued));
            }

            // read vendor defined property value.
            DaPropertyState daProperty = source as DaPropertyState;

            if (daProperty != null)
            {
                return(Add(daProperty, nodeToRead, out queued));
            }

            // read UA defined property value.
            PropertyState uaProperty = source as PropertyState;

            if (uaProperty != null)
            {
                return(Add(uaProperty, nodeToRead, out queued));
            }

            queued = false;
            return(StatusCodes.Good);
        }
Example #17
0
        /// <summary>
        /// Adds the specified attribute read to the request list.
        /// </summary>
        /// <param name="attribute">The attribute.</param>
        /// <param name="nodeToRead">The node to read.</param>
        /// <param name="queued">if set to <c>true</c> [queued].</param>
        /// <returns></returns>
        private StatusCode Add(HdaAttributeState attribute, ReadValueId nodeToRead, out bool queued)
        {
            queued = false;

            if (nodeToRead.AttributeId != Attributes.Value && nodeToRead.AttributeId != Attributes.AccessLevel && nodeToRead.AttributeId != Attributes.UserAccessLevel)
            {
                return(StatusCodes.Good);
            }

            queued = true;

            switch (attribute.Attribute.Id)
            {
            case Constants.OPCHDA_NORMAL_MAXIMUM:
            {
                nodeToRead.Handle = Add(attribute.ItemId, Constants.OPCHDA_NORMAL_MAXIMUM, Constants.OPCHDA_NORMAL_MINIMUM);
                break;
            }

            case Constants.OPCHDA_HIGH_ENTRY_LIMIT:
            {
                nodeToRead.Handle = Add(attribute.ItemId, Constants.OPCHDA_HIGH_ENTRY_LIMIT, Constants.OPCHDA_LOW_ENTRY_LIMIT);
                break;
            }

            default:
            {
                nodeToRead.Handle = Add(attribute.ItemId, attribute.Attribute.Id);
                break;
            }
            }

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

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

                    nodesToRead.Add(nodeToRead);

                    nodeToRead = new ReadValueId();

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

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

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

                    nodesToRead.Add(nodeToRead);

                    nodeToRead = new ReadValueId();

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

                    nodesToRead.Add(nodeToRead);
                }
            }
        }
Example #20
0
        /// <summary>
        /// Gets the annotations property node id.
        /// </summary>
        /// <param name="session">The session.</param>
        /// <param name="itemHandle">The item handle.</param>
        /// <returns></returns>
        public NodeId GetAnnotationsPropertyNodeId(Session session, HdaItemHandle itemHandle)
        {
            // check handle.
            InternalHandle handle = itemHandle as InternalHandle;

            if (handle == null)
            {
                return(null);
            }

            // look up the supported attributes for an item.
            ReadValueIdCollection supportedAttributes = handle.Item.SupportedAttributes;

            if (supportedAttributes == null)
            {
                handle.Item.SupportedAttributes = supportedAttributes = GetAvailableAttributes(session, handle.NodeId);
            }

            // check if annotations are supported.
            ReadValueId valueToRead = GetReadValueId(supportedAttributes, ComHdaProxy.INTERNAL_ATTRIBUTE_ANNOTATION);

            if (valueToRead == null)
            {
                return(null);
            }

            // return node id.
            return(valueToRead.NodeId);
        }
        private void retriveNodeIdDataType(ref List <CommandActions> commandActionList)
        {
            ReadValueIdCollection nodesForRead = new ReadValueIdCollection();

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

            int index = 0;

            foreach (var msgCmd in commandActionList)
            {
                foreach (var action in msgCmd.actions)
                {
                    if (dataValueList[index] != null)
                    {
                        action.dataType = dataValueList[index].WrappedValue.TypeInfo.BuiltInType;
                    }
                    index++;
                }
            }
        }
        public async Task <ActionResult> VariableWriteFetch(string jstreeNode)
        {
            string[] delimiter       = { "__$__" };
            string[] jstreeNodeSplit = jstreeNode.Split(delimiter, 3, StringSplitOptions.None);
            string   node;
            var      actionResult = "";

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

            bool retry = true;

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

                    ResponseHeader responseHeader = session.Read(null, 0, TimestampsToReturn.Both, nodesToRead, out values,
                                                                 out diagnosticInfos);
                    if (values[0].Value != null)
                    {
                        if (values[0].WrappedValue.ToString().Length > 30)
                        {
                            actionResult  = values[0].WrappedValue.ToString().Substring(0, 30);
                            actionResult += "...";
                        }
                        else
                        {
                            actionResult = values[0].WrappedValue.ToString();
                        }
                    }
                    return(Content(actionResult));
                }
                catch (Exception exception)
                {
                    if (!retry)
                    {
                        return(Content(CreateOpcExceptionActionString(exception)));
                    }
                    retry = false;
                }
            }
        }
Example #23
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);
        }
Example #24
0
        /// <summary>
        /// Reads the attributes for the node.
        /// </summary>
        public Dictionary <string, string> ReadAttributes(NodeId nodeId)
        {
            Dictionary <string, string> re = new Dictionary <string, string>();

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

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

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

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

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

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

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

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

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

                re.Add(skey, sval);
            }

            return(re);
        }
Example #25
0
 public MonitoredItemCreateRequest(
     ReadValueId ItemToMonitor,
     MonitoringMode Mode,
     MonitoringParameters RequestedParameters)
 {
     this.ItemToMonitor       = ItemToMonitor;
     this.Mode                = Mode;
     this.RequestedParameters = RequestedParameters;
 }
Example #26
0
 /// <summary>
 /// Updates the row with the node to read.
 /// </summary>
 public void UpdateRow(DataRow row, ReadValueId nodeToRead)
 {
     row[0] = nodeToRead;
     row[1] = ImageList.Images[ClientUtils.GetImageIndex(nodeToRead.AttributeId, null)];
     row[2] = (m_session != null) ? m_session.NodeCache.GetDisplayText(nodeToRead.NodeId) : Utils.ToString(nodeToRead.NodeId);
     row[3] = Attributes.GetBrowseName(nodeToRead.AttributeId);
     row[4] = nodeToRead.IndexRange;
     row[5] = (nodeToRead.DataEncoding != null) ? nodeToRead.DataEncoding : QualifiedName.Null;
 }
Example #27
0
        /// <summary>
        /// Constructs a ReadValueId for the specified UA attribute.
        /// </summary>
        /// <param name="handle">The handle.</param>
        /// <param name="uaAttributeId">The ua attribute id.</param>
        /// <returns></returns>
        private ReadValueId Construct(InternalHandle handle, uint uaAttributeId)
        {
            ReadValueId readValueId = new ReadValueId();

            readValueId.NodeId      = handle.NodeId;
            readValueId.AttributeId = uaAttributeId;
            readValueId.Handle      = handle;
            return(readValueId);
        }
Example #28
0
        /// <summary>
        /// Constructs a ReadValueId for the specified UA attribute.
        /// </summary>
        /// <param name="nodeId">The node id.</param>
        /// <param name="hdaAttributeId">The hda attribute id.</param>
        /// <param name="uaAttributeId">The ua attribute id.</param>
        /// <returns></returns>
        private ReadValueId Construct(NodeId nodeId, uint hdaAttributeId, uint uaAttributeId)
        {
            ReadValueId readValueId = new ReadValueId();

            readValueId.NodeId      = nodeId;
            readValueId.AttributeId = uaAttributeId;
            readValueId.Handle      = hdaAttributeId;
            return(readValueId);
        }
Example #29
0
        private void ReadMI_Click(object sender, EventArgs e)
        {
            try
            {
                // get the current session.
                Session session = Get <Session>(NodesTV.SelectedNode);

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

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

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

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

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

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

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

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

                            valueIds.Add(valueId);
                        }
                    }
                }

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

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

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

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

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

            CommonMethods.opcUaClient.Session.Read(
                null,
                0,
                TimestampsToReturn.Neither,
                nodesToRead,
                out results,
                out diagnosticInfos);
            ClientBase.ValidateResponse(results, nodesToRead);
            ClientBase.ValidateDiagnosticInfos(diagnosticInfos, nodesToRead);
            return(results[0]);
        }
Example #31
0
        /// <summary>
        /// Adds the attributes to the control.
        /// </summary>
        private void AddAttributes()
        {
            // build list of attributes to read.
            ReadValueIdCollection nodesToRead = new ReadValueIdCollection();

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

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

                nodesToRead.Add(valueId);
            }

            // read attributes.
            DataValueCollection      values;
            DiagnosticInfoCollection diagnosticInfos;

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

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

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

                NodeField field = new NodeField();

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

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

                AddItem(field, "SimpleItem", -1);
            }
        }
Example #32
0
 /// <summary>
 /// Initializes the object with its node type.
 /// </summary>
 public ComMonitoredItem(
     IServerInternal server,
     INodeManager nodeManager,
     object mangerHandle,
     uint subscriptionId,
     uint id,
     Session session,
     ReadValueId itemToMonitor,
     DiagnosticsMasks diagnosticsMasks,
     TimestampsToReturn timestampsToReturn,
     MonitoringMode monitoringMode,
     uint clientHandle,
     MonitoringFilter originalFilter,
     MonitoringFilter filterToUse,
     Range range,
     double samplingInterval,
     uint queueSize,
     bool discardOldest,
     double sourceSamplingInterval)
     : base(server,
             nodeManager,
             mangerHandle,
             subscriptionId,
             id,
             session,
             itemToMonitor,
             diagnosticsMasks,
             timestampsToReturn,
             monitoringMode,
             clientHandle,
             originalFilter,
             filterToUse,
             range,
             samplingInterval,
             queueSize,
             discardOldest,
             sourceSamplingInterval)
 {
 }
Example #33
0
        /// <summary>
        /// Get the local IDs from the server.
        /// </summary>
        internal List<int> GetLocaleIDs()
        {
            lock (m_lock)
            {
                string[] locales = null;
                List<int> localeList = new List<int>();
                DataValueCollection values = null;
                DiagnosticInfoCollection diagnosticInfos = null;

                try
                {
                    ReadValueIdCollection nodesToRead = new ReadValueIdCollection();
                    ReadValueId valueId = new ReadValueId();
                    valueId.NodeId = new NodeId(Opc.Ua.Variables.Server_ServerCapabilities_LocaleIdArray);
                    valueId.AttributeId = Attributes.Value;
                    nodesToRead.Add(valueId);

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

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

                    locales = ((string[])(values[0].Value));

                    // add the default locale
                    localeList.Add(ComUtils.LOCALE_SYSTEM_DEFAULT);
                    localeList.Add(ComUtils.LOCALE_USER_DEFAULT);

                    if (locales != null)
                    {
                        foreach (string locale in locales)
                        {
                            // cache the supported locales.
                            localeList.Add(ComUtils.GetLocale(locale));
                        }
                    }
                }
                catch (Exception e)
                {
                    Utils.Trace(e, "Unexpected error in GetLocaleIds");
                    throw ComUtils.CreateComException(e);
                }

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

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

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

            DataValueCollection values = null;
            DiagnosticInfoCollection diagnosticInfos = null;

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

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

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

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

                aggregate.Description = values[ii].WrappedValue.ToString();
            }
        }
Example #35
0
        /// <summary>
        /// Reads the EU range for a variable.
        /// </summary>
        private void ReadEURanges(List<TestVariable> variables)
        {
            ReadValueIdCollection euRanges = new ReadValueIdCollection();

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

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

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

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

                for (int ii = 0; ii < results.Count; ii++)
                {
                    Range range = ExtensionObject.ToEncodeable(results[ii].Value as ExtensionObject) as Range;
                    TestVariable variable = (TestVariable)euRanges[ii].Handle;
                    variable.EURange = range;
                }
            }
        }
Example #36
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;
        }
		/// <summary>
		/// Returns a description of the item being monitored. 
		/// </summary>
        public ReadValueId GetReadValueId()
        {
            lock (m_lock)
            {
                ReadValueId valueId = new ReadValueId();

                valueId.NodeId           = m_nodeId;
                valueId.AttributeId      = m_attributeId;
                valueId.IndexRange       = m_indexRange;
                valueId.ParsedIndexRange = m_parsedIndexRange;
                valueId.DataEncoding     = m_encoding;
                valueId.Handle           = m_managerHandle;

                return valueId;
            }
        }
Example #38
0
        /// <summary>
        /// Updates the EUInfo for the items.
        /// </summary>
        /// <param name="group">The group.</param>
        /// <param name="items">The items. Null entries are ignored.</param>
        public void UpdateItemEuInfo(
            ComDaGroup group,
            IList<ComDaGroupItem> items)
        {
            // get the session to use for the operation.
            Session session = m_session;

            if (session == null)
            {
                throw ComUtils.CreateComException(ResultIds.E_FAIL);
            }

            // build list of properties that need to be read.
            BrowsePathCollection browsePaths = new BrowsePathCollection();

            for (int ii = 0; ii < items.Count; ii++)
            {
                ComDaGroupItem item = (ComDaGroupItem)items[ii];

                // ignore invalid items or items which have already checked their EU type.
                if (item == null || item.EuType >= 0)
                {
                    continue;
                }

                BrowsePath browsePath = new BrowsePath();
                browsePath.StartingNode = item.NodeId;
                RelativePathElement element = new RelativePathElement();
                element.ReferenceTypeId = ReferenceTypeIds.HasProperty;
                element.IsInverse = false;
                element.IncludeSubtypes = false;
                element.TargetName = Opc.Ua.BrowseNames.EURange;
                browsePath.RelativePath.Elements.Add(element);
                browsePath.Handle = item;
                browsePaths.Add(browsePath);

                browsePath = new BrowsePath();
                browsePath.StartingNode = item.NodeId;
                element = new RelativePathElement();
                element.ReferenceTypeId = ReferenceTypeIds.HasProperty;
                element.IsInverse = false;
                element.IncludeSubtypes = false;
                element.TargetName = Opc.Ua.BrowseNames.EnumStrings;
                browsePath.RelativePath.Elements.Add(element);
                browsePath.Handle = item;
                browsePaths.Add(browsePath);
            }

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

            // translate browse paths.
            BrowsePathResultCollection results = null;
            DiagnosticInfoCollection diagnosticInfos = null;

            try
            {
                session.TranslateBrowsePathsToNodeIds(
                    null,
                    browsePaths,
                    out results,
                    out diagnosticInfos);

                ClientBase.ValidateResponse(results, browsePaths);
                ClientBase.ValidateDiagnosticInfos(diagnosticInfos, browsePaths);
            }
            catch (Exception)
            {
                for (int ii = 0; ii < browsePaths.Count; ii++)
                {
                    ComDaGroupItem item = (ComDaGroupItem)browsePaths[ii].Handle;
                    item.EuType = 0;
                }

                return;
            }

            // build list of properties that need to be read.
            ReadValueIdCollection propertiesToRead = new ReadValueIdCollection();

            for (int ii = 0; ii < results.Count; ii++)
            {
                ComDaGroupItem item = (ComDaGroupItem)browsePaths[ii].Handle;
                BrowsePathResult result = results[ii];

                if (StatusCode.IsBad(result.StatusCode))
                {
                    if (item.EuType < 0 && result.StatusCode == StatusCodes.BadNoMatch)
                    {
                        item.EuType = (int)OpcRcw.Da.OPCEUTYPE.OPC_NOENUM;
                    }

                    continue;
                }

                if (result.Targets.Count == 0 || result.Targets[0].TargetId.IsAbsolute)
                {
                    if (item.EuType < 0)
                    {
                        item.EuType = (int)OpcRcw.Da.OPCEUTYPE.OPC_NOENUM;
                    }

                    continue;
                }

                ReadValueId propertyToRead = new ReadValueId();
                propertyToRead.NodeId = (NodeId)result.Targets[0].TargetId;
                propertyToRead.AttributeId = Attributes.Value;
                propertyToRead.Handle = item;
                propertiesToRead.Add(propertyToRead);

                if (browsePaths[ii].RelativePath.Elements[0].TargetName.Name == Opc.Ua.BrowseNames.EURange)
                {
                    item.EuType = (int)OpcRcw.Da.OPCEUTYPE.OPC_ANALOG;
                }
                else
                {
                    item.EuType = (int)OpcRcw.Da.OPCEUTYPE.OPC_ENUMERATED;
                }
            }

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

            // read attribute values from the server.
            DataValueCollection values = null;

            try
            {
                session.Read(
                    null,
                    0,
                    TimestampsToReturn.Neither,
                    propertiesToRead,
                    out values,
                    out diagnosticInfos);

                ClientBase.ValidateResponse(values, propertiesToRead);
                ClientBase.ValidateDiagnosticInfos(diagnosticInfos, propertiesToRead);
            }
            catch (Exception)
            {
                for (int ii = 0; ii < propertiesToRead.Count; ii++)
                {
                    ComDaGroupItem item = (ComDaGroupItem)propertiesToRead[ii].Handle;
                    item.EuType = 0;
                }

                return;
            }

            // process results.
            for (int ii = 0; ii < values.Count; ii++)
            {
                ComDaGroupItem item = (ComDaGroupItem)propertiesToRead[ii].Handle;

                if (StatusCode.IsBad(values[ii].StatusCode))
                {
                    item.EuType = 0;
                    continue;
                }

                if (item.EuType == (int)OpcRcw.Da.OPCEUTYPE.OPC_ANALOG)
                {
                    Range range = (Range)values[ii].GetValue<Range>(null);

                    if (range == null)
                    {
                        item.EuType = 0;
                        continue;
                    }

                    item.EuInfo = new double[] { range.Low, range.High };
                    continue;
                }

                if (item.EuType == (int)OpcRcw.Da.OPCEUTYPE.OPC_ENUMERATED)
                {
                    LocalizedText[] texts = (LocalizedText[])values[ii].GetValue<LocalizedText[]>(null);

                    if (texts == null)
                    {
                        item.EuType = 0;
                        continue;
                    }

                    string[] strings = new string[texts.Length];

                    for (int jj = 0; jj < strings.Length; jj++)
                    {
                        if (!LocalizedText.IsNullOrEmpty(texts[jj]))
                        {
                            strings[jj] = texts[jj].Text;
                        }
                    }

                    item.EuInfo = strings;
                    continue;
                }
            }
        }
        private void NewMI_Click(object sender, EventArgs e)
        {
            try
            {
                ReadValueId valueId = new ReadValueId();

                if (new ReadValueEditDlg().ShowDialog(m_session, valueId))
                {
                    AddItem(valueId);
                }

                AdjustColumns();
            }
            catch (Exception exception)
            {
				GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception);
            }
        }
Example #40
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;
                }
            }
        }
Example #41
0
        /// <summary>
        /// Starts a timer to check that the connection to the server is still available.
        /// </summary>
        private void StartKeepAliveTimer()
        {
            int keepAliveInterval = m_keepAliveInterval;

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

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

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

            nodesToRead.Add(serverState);

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

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

            // send initial keep alive.
            OnKeepAlive(nodesToRead);
        }
Example #42
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];
        }
Example #43
0
        /// <summary>
        /// Reads the values for a set of variables.
        /// </summary>
        /// <param name="variableIds">The variable ids.</param>
        /// <param name="expectedTypes">The expected types.</param>
        /// <param name="values">The list of returned values.</param>
        /// <param name="errors">The list of returned errors.</param>
        public void ReadValues(
            IList<NodeId>           variableIds,
            IList<Type>             expectedTypes,
            out List<object>        values, 
            out List<ServiceResult> errors)
        {
            values = new List<object>();
            errors = new List<ServiceResult>();

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

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

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

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

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

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

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

                // suitable value found.
                values[ii] = value;
            }            
        }
Example #44
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;
        }
Example #45
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);
        }
        /// <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);
            }
        }
Example #47
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;
        }
Example #48
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;
        }
Example #49
0
        /// <summary>
        /// Validates the items by reading the attributes required to add them to the group.
        /// </summary>
        /// <param name="session">The session.</param>
        /// <param name="group">The group.</param>
        /// <param name="requests">The requests.</param>
        /// <param name="items">The items.</param>
        /// <param name="start">The start index.</param>
        /// <param name="count">The number of items to process.</param>
        private void ValidateItems(
            Session session,
            ComDaGroup group,
            ComDaCreateItemRequest[] requests,
            ComDaGroupItem[] items,
            int start,
            int count)
        {
            // build list of the UA attributes that need to be read.
            ReadValueIdCollection attributesToRead = new ReadValueIdCollection();

            for (int ii = start; ii < start + count && ii < requests.Length; ii++)
            {
                // create the group item.
                ComDaCreateItemRequest request = requests[ii];
                ComDaGroupItem item = items[ii] = new ComDaGroupItem(group, request.ItemId);

                item.NodeId = m_mapper.GetRemoteNodeId(request.ItemId);
                item.Active = request.Active;
                item.ClientHandle = request.ClientHandle;
                item.RequestedDataType = request.RequestedDataType;
                item.SamplingRate = -1;
                item.Deadband = -1;

                // add attributes.
                ReadValueId attributeToRead;

                attributeToRead = new ReadValueId();
                attributeToRead.NodeId = item.NodeId;
                attributeToRead.AttributeId = Attributes.NodeClass;
                attributesToRead.Add(attributeToRead);

                attributeToRead = new ReadValueId();
                attributeToRead.NodeId = item.NodeId;
                attributeToRead.AttributeId = Attributes.DataType;
                attributesToRead.Add(attributeToRead);

                attributeToRead = new ReadValueId();
                attributeToRead.NodeId = item.NodeId;
                attributeToRead.AttributeId = Attributes.ValueRank;
                attributesToRead.Add(attributeToRead);

                attributeToRead = new ReadValueId();
                attributeToRead.NodeId = item.NodeId;
                attributeToRead.AttributeId = Attributes.UserAccessLevel;
                attributesToRead.Add(attributeToRead);
            }

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

            try
            {
                session.Read(
                    null,
                    0,
                    TimestampsToReturn.Neither,
                    attributesToRead,
                    out results,
                    out diagnosticInfos);

                ClientBase.ValidateResponse(results, attributesToRead);
                ClientBase.ValidateDiagnosticInfos(diagnosticInfos, attributesToRead);
            }
            catch (Exception e)
            {
                Utils.Trace(e, "Unexpected error reading attributes for items.");

                // set default values on error.
                for (int ii = start; ii < start + count && ii < requests.Length; ii++)
                {
                    requests[ii].Error = ResultIds.E_INVALIDITEMID;
                }

                return;
            }

            // process results.
            int first = 0;

            for (int ii = start; ii < start + count && ii < requests.Length; ii++, first += 4)
            {
                ComDaGroupItem item = items[ii];

                // verify node class.
                NodeClass nodeClass = (NodeClass)results[first].GetValue<int>((int)NodeClass.Unspecified);

                if (nodeClass != NodeClass.Variable)
                {
                    requests[ii].Error = ResultIds.E_INVALIDITEMID;
                    continue;
                }

                // verify data type.
                NodeId dataTypeId = results[first+1].GetValue<NodeId>(null);

                if (dataTypeId == null)
                {
                    requests[ii].Error = ResultIds.E_INVALIDITEMID;
                    continue;
                }

                // get value rank.
                int valueRank = results[first+2].GetValue<int>(ValueRanks.Scalar);

                // update datatypes.
                BuiltInType builtInType = DataTypes.GetBuiltInType(dataTypeId, session.TypeTree);
                item.RemoteDataType = new TypeInfo(builtInType, valueRank);
                item.CanonicalDataType = (short)ComUtils.GetVarType(item.RemoteDataType);

                // update access rights.
                byte userAccessLevel = results[first+3].GetValue<byte>(0);

                if ((userAccessLevel & AccessLevels.CurrentRead) != 0)
                {
                    item.AccessRights |= OpcRcw.Da.Constants.OPC_READABLE;
                }

                if ((userAccessLevel & AccessLevels.CurrentWrite) != 0)
                {
                    item.AccessRights |= OpcRcw.Da.Constants.OPC_WRITEABLE;
                }
            }
        }
        /// <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>
        /// 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[];
        }
        /// <summary>
        /// Adds a value to the control.
        /// </summary>
        public void AddValueId(ReferenceDescription reference)
        {
            Node node = m_session.NodeCache.Find(reference.NodeId) as Node;

            if (node == null)
            {
                return;
            }

            ReadValueId valueId = new ReadValueId();

            valueId.NodeId       = node.NodeId;
            valueId.AttributeId  = Attributes.Value;
            valueId.IndexRange   = null;
            valueId.DataEncoding = null;

            // read the display name for non-variables.
            if ((node.NodeClass & (NodeClass.Variable | NodeClass.VariableType)) == 0)
            {
                valueId.AttributeId  = Attributes.DisplayName;
            }

            AddItem(valueId);
            AdjustColumns();
        }
Example #54
0
        private void ReadMI_Click(object sender, EventArgs e)
        {
            try
            {
                if (NodesTV.SelectedNode == null)
                {
                    return;
                }
                                    
                ReferenceDescription reference = NodesTV.SelectedNode.Tag as ReferenceDescription;
                
                if (reference == null || (reference.NodeClass & (NodeClass.Variable | NodeClass.VariableType)) == 0)
                {
                    return;
                }

                Session session = m_browser.Session;

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

                ReadValueId valueId = new ReadValueId();

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

                valueIds.Add(valueId);

                // show form.
                new ReadDlg().Show(session, valueIds);
            }
            catch (Exception exception)
            {
				GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception);
            }
        }
        /// <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);
            }
        }
Example #56
0
        /// <summary>
        /// Finds the targets for the specified reference.
        /// </summary>
        private static void UpdateInstanceDescriptions(Session session, List<AeEventAttribute> 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)
                {
                    AeEventAttribute 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);
                    }
                }
            }
            catch (Exception exception)
            {
                if (throwOnError)
                {
                    throw new ServiceResultException(exception, StatusCodes.BadUnexpectedError);
                }
            }
        }
		/// <summary>
		/// Initializes the object with its node type.
		/// </summary>
        public MonitoredItem(
            IServerInternal     server,
            INodeManager        nodeManager,
            object              mangerHandle,
            uint                subscriptionId,
            uint                id,
            Session             session,
            ReadValueId         itemToMonitor,
            DiagnosticsMasks    diagnosticsMasks,
            TimestampsToReturn  timestampsToReturn,
            MonitoringMode      monitoringMode,
            uint                clientHandle,
            MonitoringFilter    originalFilter,
            MonitoringFilter    filterToUse,
            Range               range,
            double              samplingInterval,
            uint                queueSize,
            bool                discardOldest,
            double              sourceSamplingInterval)
		{
            if (itemToMonitor == null) throw new ArgumentNullException("itemToMonitor");
            
			Initialize();
            
            m_server                  = server;
            m_nodeManager             = nodeManager;
            m_managerHandle           = mangerHandle;
            m_subscriptionId          = subscriptionId;
            m_id                      = id;
            m_session                 = session;
            m_nodeId                  = itemToMonitor.NodeId;
            m_attributeId             = itemToMonitor.AttributeId;
            m_indexRange              = itemToMonitor.IndexRange;
            m_parsedIndexRange        = itemToMonitor.ParsedIndexRange;
            m_encoding                = itemToMonitor.DataEncoding;
            m_diagnosticsMasks        = diagnosticsMasks;
            m_timestampsToReturn      = timestampsToReturn;
            m_monitoringMode          = monitoringMode;
            m_clientHandle            = clientHandle;
            m_originalFilter          = originalFilter;
            m_filterToUse             = filterToUse;
            m_range                   = 0;
            m_samplingInterval        = samplingInterval;
            m_queueSize               = queueSize;
            m_discardOldest           = discardOldest;
            m_sourceSamplingInterval  = (int)sourceSamplingInterval;
            m_calculator              = null;
            m_nextSamplingTime        = DateTime.UtcNow.Ticks;
            m_alwaysReportUpdates     = false;
            
            m_typeMask = MonitoredItemTypeMask.DataChange;

            if (originalFilter is EventFilter)
            {
                m_typeMask = MonitoredItemTypeMask.Events;

                if (itemToMonitor.NodeId == Objects.Server)
                {
                    m_typeMask |= MonitoredItemTypeMask.AllEvents;
                }
            }

            // create aggregate calculator.
            ServerAggregateFilter aggregateFilter = filterToUse as ServerAggregateFilter;

            if (filterToUse is ServerAggregateFilter)
            {
                m_calculator = m_server.AggregateManager.CreateCalculator(
                    aggregateFilter.AggregateType,
                    aggregateFilter.StartTime,
                    DateTime.MaxValue,
                    aggregateFilter.ProcessingInterval,
                    aggregateFilter.Stepped,
                    aggregateFilter.AggregateConfiguration);
            }

            if (range != null)
            {
                m_range = range.High - range.Low;
            }

            // report change to item state.
            ServerUtils.ReportCreateMonitoredItem(
                m_nodeId,
                m_id,
                m_samplingInterval,
                m_queueSize,
                m_discardOldest,
                m_filterToUse,
                m_monitoringMode);

            InitializeQueue();
		}
Example #58
0
        /// <summary>
        /// Reads the attribute values for the current node and displays them.
        /// </summary>
        public void ReadAttributes(TreeNode parent)
        {
            ReferenceDescription start = parent.Tag as ReferenceDescription;

            ListOfReadValueId nodesToRead = new ListOfReadValueId();

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

                nodeToRead.NodeId = new NodeId(start.NodeId);
                nodeToRead.AttributeId = attributeId;
                
                nodesToRead.Add(nodeToRead);
            }

            ListOfDataValue results;
            ListOfDiagnosticInfo diagnosticInfos;

            m_client.Read(
                m_client.CreateRequestHeader(),
                0,
                TimestampsToReturn.Both_2,
                nodesToRead,
                out results,
                out diagnosticInfos);

            if (results != null)
            {
                AttributesLV.Items.Clear();

                for (int ii = 0; ii < nodesToRead.Count; ii++)
                {
                    ReadValueId nodeToRead = nodesToRead[ii];
                    DataValue dataValue = results[ii];

                    if (dataValue.StatusCode == StatusCodes.BadAttributeIdInvalid)
                    {
                        continue;
                    }

                    ListViewItem item = new ListViewItem(Attributes.GetBrowseName(nodeToRead.AttributeId));

                    item.SubItems.Add(new ListViewItem.ListViewSubItem());
                    item.SubItems[1].Text = dataValue.ToString();

                    AttributesLV.Items.Add(item);
                }
            }
        }
Example #59
0
        /// <summary>
        /// Reads the values for the specified item ids.
        /// </summary>
        /// <param name="itemIds">The item ids.</param>
        /// <returns>The values.</returns>
        public DaValue[] Read(string[] itemIds)
        {
            ReadValueIdCollection valuesToRead = new ReadValueIdCollection();

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

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

                valuesToRead.Add(valueToRead);
            }

            return m_groupManager.Read(valuesToRead);
        }
Example #60
0
        /// <summary>
        /// Returns the value of an attribute.
        /// </summary>
        public void Read(
            ReadValueId request,
            DataValue result,
            DiagnosticInfo diagnosticInfo)
        {
            lock (m_lock)
            {
                // find the node to read.
                Node source = m_nodes.Find(request.NodeId);

                result.ServerTimestamp = DateTime.UtcNow;

                if (source == null)
                {
                    result.StatusCode = new StatusCode(StatusCodes.BadNodeIdUnknown);
                    return;
                }

                result.Value = Variant.Null;

                // switch on the attribute value.
                switch (request.AttributeId)
                {
                    case Attributes.NodeId:
                    {
                        result.Value = new Variant(source.NodeId);
                        break;
                    }

                    case Attributes.NodeClass:
                    {
                        result.Value = new Variant(DataTypes.EnumToMask(source.NodeClass));
                        break;
                    }

                    case Attributes.BrowseName:
                    {
                        result.Value = new Variant(source.BrowseName);
                        break;
                    }

                    case Attributes.DisplayName:
                    {
                        result.Value = new Variant(source.DisplayName);
                        break;
                    }

                    case Attributes.Description:
                    {
                        result.Value = new Variant(source.Description);
                        break;
                    }

                    case Attributes.WriteMask:
                    {
                        result.Value = new Variant(source.WriteMask);
                        break;
                    }

                    case Attributes.UserWriteMask:
                    {
                        result.Value = new Variant(source.UserWriteMask);
                        break;
                    }

                    case Attributes.Value:
                    {
                        // check if another component has installed a read callback.
                        ReadValueEventHandler callback = null;

                        if (m_callbacks.TryGetValue(source.NodeId.Identifier, out callback))
                        {
                            result.Value = new Variant(callback());
                            break;
                        }

                        // use the value cached in the node otherwise.
                        VariableNode variable = source as VariableNode;

                        if (variable != null)
                        {
                            result.Value = variable.Value;
                            result.SourceTimestamp = DateTime.UtcNow; // The Value attribute requires a SourceTimestamp.
                            break;
                        }

                        VariableTypeNode variableType = source as VariableTypeNode;

                        if (variableType != null)
                        {
                            result.Value = variableType.Value;
                            result.SourceTimestamp = DateTime.UtcNow; // The Value attribute requires a SourceTimestamp.
                            break;
                        }

                        result.StatusCode = new StatusCode(StatusCodes.BadAttributeIdInvalid);
                        break;
                    }

                    case Attributes.DataType:
                    {
                        VariableNode variable = source as VariableNode;

                        if (variable != null)
                        {
                            result.Value = new Variant(variable.DataType);
                            break;
                        }

                        VariableTypeNode variableType = source as VariableTypeNode;

                        if (variableType != null)
                        {
                            result.Value = new Variant(variableType.DataType);
                            break;
                        }

                        result.StatusCode = new StatusCode(StatusCodes.BadAttributeIdInvalid);
                        break;
                    }

                    case Attributes.ValueRank:
                    {
                        VariableNode variable = source as VariableNode;

                        if (variable != null)
                        {
                            result.Value = new Variant(variable.ValueRank);
                            break;
                        }

                        VariableTypeNode variableType = source as VariableTypeNode;

                        if (variableType != null)
                        {
                            result.Value = new Variant(variableType.ValueRank);
                            break;
                        }

                        result.StatusCode = new StatusCode(StatusCodes.BadAttributeIdInvalid);
                        break;
                    }

                    case Attributes.MinimumSamplingInterval:
                    {
                        VariableNode variable = source as VariableNode;

                        if (variable != null)
                        {
                            result.Value = new Variant(variable.MinimumSamplingInterval);
                            break;
                        }

                        result.StatusCode = new StatusCode(StatusCodes.BadAttributeIdInvalid);
                        break;
                    }
                        
                    case Attributes.Historizing:
                    {
                        VariableNode variable = source as VariableNode;

                        if (variable != null)
                        {
                            result.Value = new Variant(variable.Historizing);
                            break;
                        }

                        result.StatusCode = new StatusCode(StatusCodes.BadAttributeIdInvalid);
                        break;
                    }

                    case Attributes.AccessLevel:
                    {
                        VariableNode variable = source as VariableNode;

                        if (variable != null)
                        {
                            result.Value = new Variant(variable.AccessLevel);
                            break;
                        }

                        result.StatusCode = new StatusCode(StatusCodes.BadAttributeIdInvalid);
                        break;
                    }

                    case Attributes.UserAccessLevel:
                    {
                        VariableNode variable = source as VariableNode;

                        if (variable != null)
                        {
                            result.Value = new Variant(variable.UserAccessLevel);
                            break;
                        }

                        result.StatusCode = new StatusCode(StatusCodes.BadAttributeIdInvalid);
                        break;
                    }

                    case Attributes.EventNotifier:
                    {
                        ObjectNode objectn = source as ObjectNode;

                        if (objectn != null)
                        {
                            result.Value = new Variant(objectn.EventNotifier);
                            break;
                        }

                        ViewNode view = source as ViewNode;

                        if (view != null)
                        {
                            result.Value = new Variant(view.EventNotifier);
                            break;
                        }

                        result.StatusCode = new StatusCode(StatusCodes.BadAttributeIdInvalid);
                        break;
                    }

                    case Attributes.Executable:
                    {
                        MethodNode method = source as MethodNode;

                        if (method != null)
                        {
                            result.Value = new Variant(method.Executable);
                            break;
                        }

                        result.StatusCode = new StatusCode(StatusCodes.BadAttributeIdInvalid);
                        break;
                    }

                    case Attributes.UserExecutable:
                    {
                        MethodNode method = source as MethodNode;

                        if (method != null)
                        {
                            result.Value = new Variant(method.UserExecutable);
                            break;
                        }

                        result.StatusCode = new StatusCode(StatusCodes.BadAttributeIdInvalid);
                        break;
                    }

                    case Attributes.ContainsNoLoops:
                    {
                        ViewNode view = source as ViewNode;

                        if (view != null)
                        {
                            result.Value = new Variant(view.ContainsNoLoops);
                            break;
                        }

                        result.StatusCode = new StatusCode(StatusCodes.BadAttributeIdInvalid);
                        break;
                    }

                    case Attributes.InverseName:
                    {
                        ReferenceTypeNode referenceType = source as ReferenceTypeNode;

                        if (referenceType != null)
                        {
                            result.Value = new Variant(referenceType.InverseName);
                            break;
                        }

                        result.StatusCode = new StatusCode(StatusCodes.BadAttributeIdInvalid);
                        break;
                    }

                    case Attributes.IsAbstract:
                    {
                        DataTypeNode dataType = source as DataTypeNode;

                        if (dataType != null)
                        {
                            result.Value = new Variant(dataType.IsAbstract);
                            break;
                        }

                        ReferenceTypeNode referenceType = source as ReferenceTypeNode;

                        if (referenceType != null)
                        {
                            result.Value = new Variant(referenceType.IsAbstract);
                            break;
                        }

                        ObjectTypeNode objectType = source as ObjectTypeNode;

                        if (objectType != null)
                        {
                            result.Value = new Variant(objectType.IsAbstract);
                            break;
                        }

                        VariableTypeNode variableType = source as VariableTypeNode;

                        if (variableType != null)
                        {
                            result.Value = new Variant(variableType.IsAbstract);
                            break;
                        }

                        result.StatusCode = new StatusCode(StatusCodes.BadAttributeIdInvalid);
                        break;
                    }

                    case Attributes.Symmetric:
                    {
                        ReferenceTypeNode referenceType = source as ReferenceTypeNode;

                        if (referenceType != null)
                        {
                            result.Value = new Variant(referenceType.Symmetric);
                            break;
                        }

                        result.StatusCode = new StatusCode(StatusCodes.BadAttributeIdInvalid);
                        break;
                    }

                    default:
                    {
                        result.StatusCode = new StatusCode(StatusCodes.BadAttributeIdInvalid);
                        break;
                    }
                }
            }
        }