Ejemplo n.º 1
0
        private void OkBTN_Click(object sender, EventArgs e)
        {
            try
            {
                BrowsePathCollection browsePaths = new BrowsePathCollection();

                BrowsePath browsePath = new BrowsePath();

                browsePath.StartingNode = NodeId.Parse(StartNode.Text);
                browsePath.RelativePath = Opc.Ua.RelativePath.Parse(RelativePath.Text, m_session.TypeTree);

                browsePaths.Add(browsePath);

                BrowsePathResultCollection results         = null;
                DiagnosticInfoCollection   diagnosticInfos = null;

                m_session.TranslateBrowsePathsToNodeIds(
                    null,
                    browsePaths,
                    out results,
                    out diagnosticInfos);

                if (results != null && results.Count == 1)
                {
                    // NodesCTRL.SetNodeList(results[0].MatchingNodeIds);
                }
            }
            catch (Exception exception)
            {
                GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception);
            }
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Resolves all relative paths to nodes on the server.
        /// </summary>
        public async Task ResolveItemNodeIdsAsync(CancellationToken ct)
        {
            VerifySubscriptionState(true);

            // collect list of browse paths.
            BrowsePathCollection browsePaths   = new BrowsePathCollection();
            List <MonitoredItem> itemsToBrowse = new List <MonitoredItem>();

            PrepareResolveItemNodeIds(browsePaths, itemsToBrowse);

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

            // translate browse paths.
            var response = await m_session.TranslateBrowsePathsToNodeIdsAsync(
                null,
                browsePaths,
                ct).ConfigureAwait(false);

            BrowsePathResultCollection results = response.Results;

            ClientBase.ValidateResponse(results, browsePaths);
            ClientBase.ValidateDiagnosticInfos(response.DiagnosticInfos, browsePaths);

            // update results.
            for (int ii = 0; ii < results.Count; ii++)
            {
                itemsToBrowse[ii].SetResolvePathResult(results[ii], ii, response.DiagnosticInfos, response.ResponseHeader);
            }

            m_changeMask |= SubscriptionChangeMask.ItemsModified;
        }
        public async Task TranslateBrowsePathsToNodeIdsAsync()
        {
            var browsePaths = new BrowsePathCollection();
            var browsePath  = new BrowsePath()
            {
                StartingNode = ObjectIds.RootFolder,
                RelativePath = new RelativePath("Types")
            };

            for (int ii = 0; ii < kOperationLimit * 2; ii++)
            {
                browsePaths.Add(browsePath);
            }

            var requestHeader = new RequestHeader();
            var response      = await Session.TranslateBrowsePathsToNodeIdsAsync(requestHeader,
                                                                                 browsePaths, CancellationToken.None).ConfigureAwait(false);

            BrowsePathResultCollection results         = response.Results;
            DiagnosticInfoCollection   diagnosticInfos = response.DiagnosticInfos;

            ClientBase.ValidateResponse(results, browsePaths);
            ClientBase.ValidateDiagnosticInfos(diagnosticInfos, browsePaths);
            Assert.NotNull(response.ResponseHeader);
        }
Ejemplo n.º 4
0
        /// <summary>
        /// Worker method to translate the browse path.
        /// </summary>
        public static BrowsePathResultCollection TranslateBrowsePathWorker(
            IServerTestServices services,
            ReferenceDescriptionCollection referenceDescriptions,
            RequestHeader requestHeader,
            OperationLimits operationLimits)
        {
            // Browse template
            var startingNode = Objects.RootFolder;

            requestHeader.Timestamp = DateTime.UtcNow;

            // TranslateBrowsePath
            bool verifyMaxNodesPerBrowse = operationLimits.MaxNodesPerTranslateBrowsePathsToNodeIds > 0;
            var  browsePaths             = new BrowsePathCollection(
                referenceDescriptions.Select(r => new BrowsePath()
            {
                RelativePath = new RelativePath(r.BrowseName), StartingNode = startingNode
            })
                );
            BrowsePathResultCollection allBrowsePaths = new BrowsePathResultCollection();

            while (browsePaths.Any())
            {
                if (verifyMaxNodesPerBrowse &&
                    browsePaths.Count > operationLimits.MaxNodesPerTranslateBrowsePathsToNodeIds)
                {
                    verifyMaxNodesPerBrowse = false;
                    // Test if server responds with BadTooManyOperations
                    var sre = Assert.Throws <ServiceResultException>(() =>
                                                                     _ = services.TranslateBrowsePathsToNodeIds(requestHeader, browsePaths, out var results, out var infos));
                    Assert.AreEqual(StatusCodes.BadTooManyOperations, sre.StatusCode);
                }
                var browsePathSnippet = (operationLimits.MaxNodesPerTranslateBrowsePathsToNodeIds > 0) ?
                                        browsePaths.Take((int)operationLimits.MaxNodesPerTranslateBrowsePathsToNodeIds).ToArray() :
                                        browsePaths;
                ResponseHeader response = services.TranslateBrowsePathsToNodeIds(requestHeader, browsePathSnippet, out var browsePathResults, out var diagnosticInfos);
                ServerFixtureUtils.ValidateResponse(response);
                ServerFixtureUtils.ValidateDiagnosticInfos(diagnosticInfos, browsePathSnippet);
                allBrowsePaths.AddRange(browsePathResults);
                foreach (var result in browsePathResults)
                {
                    if (result.Targets?.Count > 0)
                    {
                        TestContext.Out.WriteLine("BrowsePath {0}", result.Targets[0].ToString());
                    }
                }

                if (operationLimits.MaxNodesPerTranslateBrowsePathsToNodeIds == 0)
                {
                    browsePaths.Clear();
                }
                else
                {
                    browsePaths = browsePaths.Skip((int)operationLimits.MaxNodesPerTranslateBrowsePathsToNodeIds).ToArray();
                }
            }
            return(allBrowsePaths);
        }
Ejemplo n.º 5
0
 public ResponseHeader TranslateBrowsePathsToNodeIds(
     RequestHeader requestHeader,
     BrowsePathCollection browsePaths,
     out BrowsePathResultCollection results,
     out DiagnosticInfoCollection diagnosticInfos)
 {
     return(m_session.TranslateBrowsePathsToNodeIds(requestHeader,
                                                    browsePaths,
                                                    out results, out diagnosticInfos));
 }
Ejemplo n.º 6
0
        /// <summary>
        /// Invokes the TranslateBrowsePathsToNodeIds service.
        /// </summary>
        public virtual ResponseHeader TranslateBrowsePathsToNodeIds(
            RequestHeader requestHeader,
            BrowsePathCollection browsePaths,
            out BrowsePathResultCollection results,
            out DiagnosticInfoCollection diagnosticInfos)
        {
            results         = null;
            diagnosticInfos = null;

            ValidateRequest(requestHeader);

            // Insert implementation.

            return(CreateResponse(requestHeader, StatusCodes.BadServiceUnsupported));
        }
Ejemplo n.º 7
0
        /// <summary>
        /// Invokes the TranslateBrowsePathsToNodeIds service.
        /// </summary>
        public virtual ResponseHeader TranslateBrowsePathsToNodeIds(
            RequestHeader                  requestHeader,
            BrowsePathCollection           browsePaths,
            out BrowsePathResultCollection results,
            out DiagnosticInfoCollection   diagnosticInfos)
        {
            results = null;
            diagnosticInfos = null;

            ValidateRequest(requestHeader);

            // Insert implementation.

            return CreateResponse(requestHeader, StatusCodes.BadServiceUnsupported);
        }
        /// <summary>
        /// Invokes the TranslateBrowsePathsToNodeIds service.
        /// </summary>
        /// <param name="requestHeader">The request header.</param>
        /// <param name="browsePaths">The list of browse paths for which NodeIds are being requested.</param>
        /// <param name="results">The list of results for the list of browse paths.</param>
        /// <param name="diagnosticInfos">The diagnostic information for the results.</param>
        /// <returns>
        /// Returns a <see cref="ResponseHeader"/> object
        /// </returns>
        public override ResponseHeader TranslateBrowsePathsToNodeIds(
            RequestHeader                  requestHeader, 
            BrowsePathCollection           browsePaths, 
            out BrowsePathResultCollection results, 
            out DiagnosticInfoCollection   diagnosticInfos)
        {
            results = null;
            diagnosticInfos = null;

            OperationContext context = ValidateRequest(requestHeader, RequestType.TranslateBrowsePathsToNodeIds);

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

                m_serverInternal.NodeManager.TranslateBrowsePathsToNodeIds(
                    context,
                    browsePaths,
                    out results,
                    out diagnosticInfos);

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

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

                throw TranslateException(context, e);
            }  
            finally
            {
                OnRequestComplete(context);
            } 
        }
Ejemplo n.º 9
0
        /// <summary>
        /// Gets the available attributes for an HDA item.
        /// </summary>
        /// <param name="session">The session.</param>
        /// <param name="nodeId">The node id.</param>
        /// <returns></returns>
        private ReadValueIdCollection GetAvailableAttributes(Session session, NodeId nodeId)
        {
            ReadValueIdCollection supportedAttributes = new ReadValueIdCollection();

            // add mandatory HDA attributes.
            supportedAttributes.Add(Construct(nodeId, OpcRcw.Hda.Constants.OPCHDA_ITEMID, Attributes.DisplayName));
            supportedAttributes.Add(Construct(nodeId, OpcRcw.Hda.Constants.OPCHDA_DATA_TYPE, Attributes.DataType));
            supportedAttributes.Add(Construct(nodeId, ComHdaProxy.INTERNAL_ATTRIBUTE_VALUE_RANK, Attributes.ValueRank));
            supportedAttributes.Add(Construct(nodeId, OpcRcw.Hda.Constants.OPCHDA_DESCRIPTION, Attributes.Description));
            supportedAttributes.Add(Construct(nodeId, OpcRcw.Hda.Constants.OPCHDA_ARCHIVING, Attributes.Historizing));

            // check if nodes are defined for all optional HDA attributes.
            BrowsePathCollection pathsToRead = new BrowsePathCollection();

            pathsToRead.Add(Construct(nodeId, ComHdaProxy.INTERNAL_ATTRIBUTE_ANNOTATION, Opc.Ua.BrowseNames.Annotations));
            pathsToRead.Add(Construct(nodeId, OpcRcw.Hda.Constants.OPCHDA_ENG_UNITS, Opc.Ua.BrowseNames.EngineeringUnits));;
            pathsToRead.Add(Construct(nodeId, OpcRcw.Hda.Constants.OPCHDA_DERIVE_EQUATION, Opc.Ua.BrowseNames.Definition));
            pathsToRead.Add(Construct(nodeId, OpcRcw.Hda.Constants.OPCHDA_NORMAL_MAXIMUM, Opc.Ua.BrowseNames.EURange));
            pathsToRead.Add(Construct(nodeId, OpcRcw.Hda.Constants.OPCHDA_NORMAL_MINIMUM, Opc.Ua.BrowseNames.EURange));
            pathsToRead.Add(Construct(nodeId, OpcRcw.Hda.Constants.OPCHDA_HIGH_ENTRY_LIMIT, Opc.Ua.BrowseNames.InstrumentRange));
            pathsToRead.Add(Construct(nodeId, OpcRcw.Hda.Constants.OPCHDA_LOW_ENTRY_LIMIT, Opc.Ua.BrowseNames.InstrumentRange));
            pathsToRead.Add(Construct(nodeId, OpcRcw.Hda.Constants.OPCHDA_STEPPED, Opc.Ua.BrowseNames.HAConfiguration, Opc.Ua.BrowseNames.Stepped));
            pathsToRead.Add(Construct(nodeId, OpcRcw.Hda.Constants.OPCHDA_MAX_TIME_INT, Opc.Ua.BrowseNames.HAConfiguration, Opc.Ua.BrowseNames.MaxTimeInterval));
            pathsToRead.Add(Construct(nodeId, OpcRcw.Hda.Constants.OPCHDA_MIN_TIME_INT, Opc.Ua.BrowseNames.HAConfiguration, Opc.Ua.BrowseNames.MinTimeInterval));
            pathsToRead.Add(Construct(nodeId, OpcRcw.Hda.Constants.OPCHDA_EXCEPTION_DEV, Opc.Ua.BrowseNames.HAConfiguration, Opc.Ua.BrowseNames.ExceptionDeviation));
            pathsToRead.Add(Construct(nodeId, OpcRcw.Hda.Constants.OPCHDA_EXCEPTION_DEV_TYPE, Opc.Ua.BrowseNames.HAConfiguration, Opc.Ua.BrowseNames.ExceptionDeviationFormat));

            BrowsePathResultCollection results         = null;
            DiagnosticInfoCollection   diagnosticInfos = null;

            session.TranslateBrowsePathsToNodeIds(
                null,
                pathsToRead,
                out results,
                out diagnosticInfos);

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

            for (int ii = 0; ii < pathsToRead.Count; ii++)
            {
                uint attributeId = (uint)pathsToRead[ii].Handle;

                // path does not exist.
                if (StatusCode.IsBad(results[ii].StatusCode))
                {
                    continue;
                }

                // nothing found.
                if (results[ii].Targets.Count == 0)
                {
                    continue;
                }

                // choose the first valid target.
                for (int jj = 0; jj < results[ii].Targets.Count; jj++)
                {
                    BrowsePathTarget target = results[ii].Targets[jj];

                    if (target.RemainingPathIndex == UInt32.MaxValue && !NodeId.IsNull(target.TargetId) && !target.TargetId.IsAbsolute)
                    {
                        supportedAttributes.Add(Construct((NodeId)target.TargetId, attributeId, Attributes.Value));
                        break;
                    }
                }
            }

            return(supportedAttributes);
        }
Ejemplo n.º 10
0
        /// <summary>
        /// Sets the filtering criteria to be used for the event subscription.
        /// </summary>
        /// <param name="dwEventType">Bit mask specifying which event types are of interest</param>
        /// <param name="dwNumCategories">Length of array of event categories. A length of 0 indicates all categories should be included in the filter.</param>
        /// <param name="pdwEventCategories">Array of event categories of interest.</param>
        /// <param name="dwLowSeverity">Lowest severity of interest (inclusive).</param>
        /// <param name="dwHighSeverity">Highest severity of interest (inclusive).</param>
        /// <param name="dwNumAreas">Length of array of areas. A length of 0 indicates all areas should be included in the filter.</param>
        /// <param name="pszAreaList">Array of process area strings of interest - only events or conditions in these areas will be reported.</param>
        /// <param name="dwNumSources">Length of array of event sources. A length of 0 indicates all sources should be included in the filter.</param>
        /// <param name="pszSourceList">Array of event sources of interest - only events from these sources will be reported.</param>
        public void SetFilter(int dwEventType, int dwNumCategories, int[] pdwEventCategories, int dwLowSeverity, int dwHighSeverity, int dwNumAreas, string[] pszAreaList, int dwNumSources, string[] pszSourceList)
        {
            try
            {
                if (dwEventType == 0 |
                    dwEventType > OpcRcw.Ae.Constants.ALL_EVENTS |
                    pdwEventCategories.Rank > 1 | dwNumCategories != pdwEventCategories.Length |
                    pszAreaList.Rank > 1 | dwNumAreas != pszAreaList.Length |
                    pszSourceList.Rank > 1 | dwNumSources != pszSourceList.Length |
                    dwLowSeverity < 1 | dwLowSeverity > 1000 | dwHighSeverity > 1000 | dwHighSeverity <1 |
                                                                                                       dwLowSeverity> dwHighSeverity)
                {
                    throw ComUtils.CreateComException("SetFilter", ResultIds.E_INVALIDARG);
                }

                if (dwNumCategories != 0)
                {
                    for (int i = 0; i < dwNumCategories; i++)
                    {
                        // Make sure we are passed a valid dwEventCategory
                        NodeId catNodeId = m_server.FindEventCatNodeId(pdwEventCategories[i]);
                        if (catNodeId == null)
                        {
                            throw ComUtils.CreateComException("SetFilter", ResultIds.E_INVALIDARG);
                        }
                    }
                }
                m_server.RemoveMonitoredItems(m_AreaVector);
                if (dwNumAreas != 0)
                {
                    List <string> szAreas = new List <string>();
                    for (int i = 0; i < dwNumAreas; i++)
                    {
                        szAreas.Add(pszAreaList[i]);
                    }
                    if (szAreas.Count > 0)
                    {
                        m_server.AddMonitoredItems(szAreas);
                    }
                }

                if (dwNumSources != 0)
                {
                    List <string> szSources = new List <string>();
                    for (int i = 0; i < dwNumSources; i++)
                    {
                        int wildCardLocation = 0;
                        if ((wildCardLocation = pszSourceList[i].IndexOfAny(new char[] { '*', '?', '#', '[', ']', '!', '-' })) != -1)
                        {
                            // The string contains wildcards
                            List <string> items = m_server.ProcessWildCardAreaName(pszSourceList[i], wildCardLocation);
                            if (items.Count == 0)
                            {
                                throw ComUtils.CreateComException("SetFilter", ResultIds.E_INVALIDARG);
                            }
                            foreach (string item in items)
                            {
                                szSources.Add(item);
                            }
                        }
                        else
                        {
                            szSources.Add(pszSourceList[i]);
                        }
                    }

                    //Translate the fully qualified source name to NodeId
                    BrowsePathResultCollection results = m_server.GetBrowseTargets(szSources);
                    for (int i = 0; i < dwNumSources; i++)
                    {
                        if (StatusCode.IsBad(results[i].StatusCode))
                        {
                            throw ComUtils.CreateComException("SetFilter", ResultIds.E_INVALIDARG);
                        }
                    }
                }

                m_dwEventType    = dwEventType;
                m_dwLowSeverity  = dwLowSeverity;
                m_dwHighSeverity = dwHighSeverity;
                m_EventCategoryVector.Clear();
                if (dwNumCategories != 0)
                {
                    for (int i = 0; i < dwNumCategories; i++)
                    {
                        m_EventCategoryVector.AddUnique(pdwEventCategories[i]);
                    }
                }

                m_server.RemoveMonitoredItems(m_AreaVector);
                m_AreaVector.Clear();
                if (dwNumAreas != 0)
                {
                    for (int i = 0; i < dwNumAreas; i++)
                    {
                        m_AreaVector.AddUnique(pszAreaList[i]);
                    }
                }

                m_SourceVector.Clear();
                if (dwNumSources != 0)
                {
                    for (int i = 0; i < dwNumSources; i++)
                    {
                        m_SourceVector.AddUnique(pszSourceList[i]);
                    }
                }
            }
            catch (COMException e)
            {
                throw ComUtils.CreateComException(e);
            }
            catch (Exception e)
            {
                Utils.Trace(e, "Unexpected error in SetFilter");
                throw ComUtils.CreateComException(e);
            }
        }
Ejemplo n.º 11
0
        /// <summary>
        /// Translates a start node id plus a relative paths into a node id.
        /// </summary>
        public virtual void TranslateBrowsePathsToNodeIds(
            OperationContext               context,
            BrowsePathCollection           browsePaths, 
            out BrowsePathResultCollection results, 
            out DiagnosticInfoCollection   diagnosticInfos)
        {
            if (browsePaths == null)throw new ArgumentNullException("browsePaths");
            
            bool diagnosticsExist = false;
            results = new BrowsePathResultCollection(browsePaths.Count);
            diagnosticInfos = new DiagnosticInfoCollection(browsePaths.Count);

            for (int ii = 0; ii < browsePaths.Count; ii++)
            {
                // check if request has timed out or been cancelled.
                if (StatusCode.IsBad(context.OperationStatus))
                {
                    throw new ServiceResultException(context.OperationStatus);
                }

                BrowsePath browsePath = browsePaths[ii];

                BrowsePathResult result = new BrowsePathResult();
                result.StatusCode = StatusCodes.Good;
                results.Add(result);
                
                ServiceResult error = null;
               
                // need to trap unexpected exceptions to handle bugs in the node managers.
                try
                {
                    error = TranslateBrowsePath(context, browsePath, result);
                }
                catch (Exception e)
                {
                    error = ServiceResult.Create(e, StatusCodes.BadUnexpectedError, "Unexpected error translating browse path.");
                }
                
                if (ServiceResult.IsGood(error))
                {                
                    // check for no match.
                    if (result.Targets.Count == 0)
                    {
                        error = StatusCodes.BadNoMatch;
                    }

                    // put a placeholder for diagnostics.
                    else if ((context.DiagnosticsMask & DiagnosticsMasks.OperationAll) != 0)
                    {
                        diagnosticInfos.Add(null);
                    }
                }

                // check for error.
                if (error != null && error.Code != StatusCodes.Good)
                {                
                    result.StatusCode = error.StatusCode;
                    
                    if ((context.DiagnosticsMask & DiagnosticsMasks.OperationAll) != 0)
                    {
                        DiagnosticInfo diagnosticInfo = ServerUtils.CreateDiagnosticInfo(m_server, context, error);
                        diagnosticInfos.Add(diagnosticInfo);
                        diagnosticsExist = true;
                    }
                }
            }

            // clear the diagnostics array if no diagnostics requested or no errors occurred.
            UpdateDiagnostics(context, diagnosticsExist, ref diagnosticInfos);
        }
Ejemplo n.º 12
0
        /// <summary>
        /// Finishes an asynchronous invocation of the TranslateBrowsePathsToNodeIds service.
        /// </summary>
        public ResponseHeader EndTranslateBrowsePathsToNodeIds(
            IAsyncResult                   result,
            out BrowsePathResultCollection results,
            out DiagnosticInfoCollection   diagnosticInfos)
        {
            TranslateBrowsePathsToNodeIdsResponse response = null;

            try
            {
                if (UseTransportChannel)
                {
                    IServiceResponse genericResponse = TransportChannel.EndSendRequest(result);

                    if (genericResponse == null)
                    {
                        throw new ServiceResultException(StatusCodes.BadUnknownResponse);
                    }

                    ValidateResponse(genericResponse.ResponseHeader);
                    response = (TranslateBrowsePathsToNodeIdsResponse)genericResponse;
                }
                else
                {
                    TranslateBrowsePathsToNodeIdsResponseMessage responseMessage = InnerChannel.EndTranslateBrowsePathsToNodeIds(result);

                    if (responseMessage == null || responseMessage.TranslateBrowsePathsToNodeIdsResponse == null)
                    {
                        throw new ServiceResultException(StatusCodes.BadUnknownResponse);
                    }

                    response = responseMessage.TranslateBrowsePathsToNodeIdsResponse;
                    ValidateResponse(response.ResponseHeader);
                }

                results         = response.Results;
                diagnosticInfos = response.DiagnosticInfos;
            }
            finally
            {
                RequestCompleted(null, response, "TranslateBrowsePathsToNodeIds");
            }

            return response.ResponseHeader;
        }
Ejemplo n.º 13
0
        /// <summary>
        /// Invokes the TranslateBrowsePathsToNodeIds service.
        /// </summary>
        public virtual ResponseHeader TranslateBrowsePathsToNodeIds(
            RequestHeader                  requestHeader,
            BrowsePathCollection           browsePaths,
            out BrowsePathResultCollection results,
            out DiagnosticInfoCollection   diagnosticInfos)
        {
            TranslateBrowsePathsToNodeIdsRequest request = new TranslateBrowsePathsToNodeIdsRequest();
            TranslateBrowsePathsToNodeIdsResponse response = null;

            request.RequestHeader = requestHeader;
            request.BrowsePaths   = browsePaths;

            UpdateRequestHeader(request, requestHeader == null, "TranslateBrowsePathsToNodeIds");

            try
            {
                if (UseTransportChannel)
                {
                    IServiceResponse genericResponse = TransportChannel.SendRequest(request);

                    if (genericResponse == null)
                    {
                        throw new ServiceResultException(StatusCodes.BadUnknownResponse);
                    }

                    ValidateResponse(genericResponse.ResponseHeader);
                    response = (TranslateBrowsePathsToNodeIdsResponse)genericResponse;
                }
                else
                {
                    TranslateBrowsePathsToNodeIdsResponseMessage responseMessage = InnerChannel.TranslateBrowsePathsToNodeIds(new TranslateBrowsePathsToNodeIdsMessage(request));

                    if (responseMessage == null || responseMessage.TranslateBrowsePathsToNodeIdsResponse == null)
                    {
                        throw new ServiceResultException(StatusCodes.BadUnknownResponse);
                    }

                    response = responseMessage.TranslateBrowsePathsToNodeIdsResponse;
                    ValidateResponse(response.ResponseHeader);
                }

                results         = response.Results;
                diagnosticInfos = response.DiagnosticInfos;
            }
            finally
            {
                RequestCompleted(request, response, "TranslateBrowsePathsToNodeIds");
            }

            return response.ResponseHeader;
        }
Ejemplo n.º 14
0
        /// <summary>
        /// Updates the list of references.
        /// </summary>
        private void UpdateArguments(Session session, NodeId nodeId)
        {
            ArgumentsLV.Items.Clear();

            // need to fetch the node ids for the argument properties.
            BrowsePathCollection browsePaths = new BrowsePathCollection();

            foreach (string browseName in new string[] { BrowseNames.InputArguments, BrowseNames.OutputArguments })
            {
                BrowsePath browsePath = new BrowsePath();
                browsePath.StartingNode = nodeId;
                browsePath.Handle       = browseName;

                RelativePathElement element = new RelativePathElement();
                element.ReferenceTypeId = ReferenceTypeIds.HasProperty;
                element.IsInverse       = false;
                element.IncludeSubtypes = true;
                element.TargetName      = browseName;

                browsePath.RelativePath.Elements.Add(element);
                browsePaths.Add(browsePath);
            }

            // translate property names.
            BrowsePathResultCollection results         = null;
            DiagnosticInfoCollection   diagnosticInfos = null;

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

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

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

            for (int ii = 0; ii < results.Count; ii++)
            {
                if (StatusCode.IsBad(results[ii].StatusCode) || results[ii].Targets.Count <= 0)
                {
                    continue;
                }

                ReadValueId valueToRead = new ReadValueId();
                valueToRead.NodeId      = (NodeId)results[ii].Targets[0].TargetId;
                valueToRead.AttributeId = Attributes.Value;
                valueToRead.Handle      = browsePaths[ii].Handle;
                valuesToRead.Add(valueToRead);
            }

            // read the values.
            if (valuesToRead.Count > 0)
            {
                DataValueCollection values = null;

                session.Read(
                    null,
                    0,
                    TimestampsToReturn.Neither,
                    valuesToRead,
                    out values,
                    out diagnosticInfos);

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

                // update the list control.
                for (int ii = 0; ii < values.Count; ii++)
                {
                    // all structures are wrapped in extension objects.
                    ExtensionObject[] extensions = values[ii].GetValue <ExtensionObject[]>(null);

                    if (extensions != null)
                    {
                        // convert to an argument structure.
                        Argument[] arguments = (Argument[])ExtensionObject.ToArray(extensions, typeof(Argument));
                        UpdateList(session, arguments, (string)valuesToRead[ii].Handle);
                    }
                }
            }

            // auto size the columns.
            for (int ii = 0; ii < ArgumentsLV.Columns.Count; ii++)
            {
                ArgumentsLV.Columns[ii].Width = -2;
            }
        }
Ejemplo n.º 15
0
        public static void BrowseNode(String currentNode, String browseName)
        {
            BrowseResultCollection      browseResultCollection = null;
            DiagnosticInfoCollection    diagnosticInfos;
            BrowseDescriptionCollection browseDescriptionCollection = null;
            List <NodeClass>            nodeClasses = new List <NodeClass>()
            {
                NodeClass.Unspecified
            };

            foreach (NodeClass nodeClass in nodeClasses)
            {
                browseDescriptionCollection = PrepareBrowseDescriptionCollection(currentNode, (uint)nodeClass);
                clientSession.Browse(
                    null,
                    null,
                    100,
                    browseDescriptionCollection,
                    out browseResultCollection,
                    out diagnosticInfos);

                if (browseResultCollection.Where(br => br.References.Count > 0).FirstOrDefault() == null)
                {
                    continue;
                }
                int    browseResultCounter = browseResultCollection.FindIndex(br => br.References.Count > 0);
                String referenceType       = String.Empty;

                foreach (BrowseResult browseResult in browseResultCollection)
                {
                    switch (browseResultCounter)
                    {
                    case 0:
                        referenceType = "Organizes";
                        break;

                    case 1:
                        referenceType = "HasComponent";
                        break;

                    case 2:
                        referenceType = "HasChild";
                        break;

                    case 3:
                        referenceType = "HasDescription";
                        break;

                    case 4:
                        referenceType = "HasProperty";
                        break;

                    default:
                        referenceType = "HasProperty";
                        break;
                    }

                    if (browseResult.References.Count > 0)
                    {
                        foreach (ReferenceDescription referenceDescription in browseResult.References)
                        {
                            if (referenceDescription.BrowseName.NamespaceIndex != UaDefaultNamespaceIndex)
                            {
                                BrowseNode(referenceDescription.NodeId.ToString(), referenceDescription.BrowseName.ToString());
                            }

                            //TBD - If a node id has different relations with its parent node, the additional "relation" should be added
                            //OpcuaNodeList opcuaNodeSubStructure = new OpcuaNodeList();
                            //opcuaNodeSubStructure.nodeId = referenceDescription.NodeId.ToString();
                            //opcuaNodeSubStructure.browseName = referenceDescription.BrowseName.ToString();

                            OpcuaNodeLink opcuaNodeLink = new OpcuaNodeLink();

                            opcuaNodeLink.nodeID               = referenceDescription.NodeId.ToString();
                            opcuaNodeLink.browseName           = referenceDescription.BrowseName.ToString();
                            opcuaNodeLink.parentNodeId         = currentNode;
                            opcuaNodeLink.parentNodebrowseName = browseName;

                            opcuaNodeLink.referenceType = referenceType;
                            if (referenceDescription.IsForward)
                            {
                                opcuaNodeLink.BrowseDirection = BrowseDirection.Forward.ToString("G");
                            }
                            opcuaNodeLink.NodeClassMask    = nodeClass.ToString("G");
                            opcuaNodeLink.browseResultMask = BrowseResultMask.All.ToString("G");

                            //if (!opcuaNodeStructure.IsChildPresent(referenceDescription.NodeId.ToString()))
                            if (opcuaNodeStructure.ChildrenNodes == null)
                            {
                                opcuaNodeStructure.ChildrenNodes = new List <OpcuaNodeLink>();
                            }

                            addNode(opcuaNodeLink);

                            if (referenceDescription.NodeClass == NodeClass.Method)
                            {
                                Node methodNode = clientSession.ReadNode((NodeId)(referenceDescription.NodeId.ToString()));

                                browseDescriptionCollection = PrepareBrowseDescriptionCollection(referenceDescription.NodeId.ToString(), (uint)nodeClass);
                                clientSession.Browse(
                                    null,
                                    null,
                                    100,
                                    browseDescriptionCollection,
                                    out browseResultCollection,
                                    out diagnosticInfos);

                                if (browseResultCollection.Where(br => br.References.Count > 0).FirstOrDefault() == null)
                                {
                                    continue;
                                }

                                String inputArgumentsNodeId = String.Empty, outputArgumentsNodeId = String.Empty;
                                foreach (BrowseResult br in browseResultCollection)
                                {
                                    foreach (ReferenceDescription rd in br.References)
                                    {
                                        OpcuaNodeLink nodeLink = new OpcuaNodeLink();

                                        nodeLink.nodeID     = rd.NodeId.ToString();
                                        nodeLink.browseName = rd.BrowseName.ToString();

                                        if (nodeLink.browseName == "InputArguments")
                                        {
                                            inputArgumentsNodeId = nodeLink.nodeID;
                                        }
                                        else if (nodeLink.browseName == "OutputArguments")
                                        {
                                            outputArgumentsNodeId = nodeLink.nodeID;
                                        }

                                        nodeLink.parentNodeId         = referenceDescription.NodeId.ToString();
                                        nodeLink.parentNodebrowseName = referenceDescription.BrowseName.ToString();

                                        nodeLink.referenceType = referenceType;
                                        if (rd.IsForward)
                                        {
                                            opcuaNodeLink.BrowseDirection = BrowseDirection.Forward.ToString("G");
                                        }
                                        nodeLink.NodeClassMask    = nodeClass.ToString("G");
                                        nodeLink.browseResultMask = BrowseResultMask.All.ToString("G");

                                        //if (!opcuaNodeStructure.IsChildPresent(referenceDescription.NodeId.ToString()))
                                        if (opcuaNodeStructure.ChildrenNodes == null)
                                        {
                                            opcuaNodeStructure.ChildrenNodes = new List <OpcuaNodeLink>();
                                        }

                                        addNode(nodeLink);
                                    }
                                }

                                opcuaNodeLink.isMethod = true;

                                BrowsePathCollection pathsToArgs     = new BrowsePathCollection();
                                BrowsePath           pathToInputArgs = new BrowsePath();
                                pathToInputArgs.StartingNode = methodNode.NodeId;
                                pathToInputArgs.RelativePath = new RelativePath(ReferenceTypeIds.HasProperty, false, true, new QualifiedName("InputArguments"));
                                pathsToArgs.Add(pathToInputArgs);

                                BrowsePath pathToOutputArgs = new BrowsePath();
                                pathToOutputArgs.StartingNode = methodNode.NodeId;
                                pathToOutputArgs.RelativePath = new RelativePath(ReferenceTypeIds.HasProperty, false, true, new QualifiedName("OutputArguments"));
                                pathsToArgs.Add(pathToOutputArgs);

                                BrowsePathResultCollection results = null;
                                // Get the nodeId of the input argument
                                ResponseHeader responseHeader = clientSession.TranslateBrowsePathsToNodeIds(
                                    null,
                                    pathsToArgs,
                                    out results,
                                    out diagnosticInfos
                                    );

                                ArgumentCollection[] arguments = new ArgumentCollection[2];
                                for (int i = 0; i < 2; i++)
                                {
                                    arguments[i] = new ArgumentCollection();
                                    foreach (BrowsePathTarget bptarget in results[i].Targets)
                                    {
                                        DataValueCollection readResults = null;

                                        ReadValueId nodeToRead = new ReadValueId();
                                        nodeToRead.NodeId      = (NodeId)bptarget.TargetId;
                                        nodeToRead.AttributeId = Attributes.Value;
                                        ReadValueIdCollection nodesToRead = new ReadValueIdCollection();
                                        nodesToRead.Add(nodeToRead);

                                        DiagnosticInfoCollection readDiagnoistcInfos = null;

                                        clientSession.Read(
                                            null,
                                            0,
                                            TimestampsToReturn.Neither,
                                            nodesToRead,
                                            out readResults,
                                            out readDiagnoistcInfos
                                            );

                                        ExtensionObject[] exts = (ExtensionObject[])readResults[0].Value;
                                        for (int j = 0; j < exts.Length; ++j)
                                        {
                                            ExtensionObject ext = exts[j];
                                            arguments[i].Add((Argument)ext.Body);

                                            OpcuaNodeLink nl = new OpcuaNodeLink();

                                            nl.nodeID     = ((Opc.Ua.Argument)ext.Body).BinaryEncodingId.ToString();
                                            nl.browseName = ((Opc.Ua.Argument)ext.Body).Name;

                                            if (((Opc.Ua.Argument)ext.Body).Description.Text.Equals("Input argument"))
                                            {
                                                nl.parentNodeId = inputArgumentsNodeId;
                                            }
                                            else if (((Opc.Ua.Argument)ext.Body).Description.Text.Equals("Output argument"))
                                            {
                                                nl.parentNodeId = outputArgumentsNodeId;
                                            }

                                            nl.parentNodebrowseName = referenceDescription.BrowseName.ToString();

                                            nl.referenceType = referenceType;
                                            if (referenceDescription.IsForward)
                                            {
                                                opcuaNodeLink.BrowseDirection = BrowseDirection.Forward.ToString("G");
                                            }
                                            nl.NodeClassMask    = NodeClass.Variable.ToString("G");
                                            nl.browseResultMask = BrowseResultMask.All.ToString("G");
                                            nl.isArgument       = true;

                                            //if (!opcuaNodeStructure.IsChildPresent(referenceDescription.NodeId.ToString()))
                                            if (opcuaNodeStructure.ChildrenNodes == null)
                                            {
                                                opcuaNodeStructure.ChildrenNodes = new List <OpcuaNodeLink>();
                                            }

                                            addNode(nl);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
Ejemplo n.º 16
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;
                }
            }
        }
Ejemplo n.º 17
0
        /// <summary>
        /// Provides a way to move �up� or �down� in a hierarchical space from the current position, or a way to move to a specific position in the area space tree. The target szString must represent an area, rather than a source.
        /// </summary>
        /// <param name="dwBrowseDirection">OPCAE_BROWSE_UP, OPCAE_BROWSE_DOWN, or OPCAE_BROWSE_TO</param>
        /// <param name="szString">
        /// For DOWN, the partial area name of the area to move into. This would be one of the strings returned from BrowseOPCAreas.
        /// For UP this parameter is ignored and should point to a NULL string.
        /// For BROWSE_TO, the fully qualified area name (as obtained from GetQualifiedAreaName method) or a pointer to a NUL string to go to the root.
        /// </param>
        public void ChangeBrowsePosition(OPCAEBROWSEDIRECTION dwBrowseDirection, string szString)
        {
            lock (m_lock)
            {
                try
                {
                    switch (dwBrowseDirection)
                    {
                    // move to a specified position or root.
                    case OPCAEBROWSEDIRECTION.OPCAE_BROWSE_TO:
                    {
                        try
                        {
                            // move to root.
                            if (String.IsNullOrEmpty(szString))
                            {
                                m_browseStack.Clear();
                                m_browseStack.Push(m_session.NodeCache.Find(Objects.Server));
                                break;
                            }

                            // Translate the fully qualified area name to NodeId
                            List <string> szAreas = new List <string>();
                            szAreas.Add(szString);
                            BrowsePathResultCollection results = m_server.GetBrowseTargets(szAreas);
                            if (StatusCode.IsBad(results[0].StatusCode))
                            {
                                throw ComUtils.CreateComException(ResultIds.E_INVALIDBRANCHNAME);
                            }

                            BrowsePathTarget target = results[0].Targets[0];
                            INode            node   = m_session.NodeCache.Find(target.TargetId);
                            if (node == null)
                            {
                                throw ComUtils.CreateComException(ResultIds.E_INVALIDBRANCHNAME);
                            }

                            // build a new browse stack.
                            Stack <INode> browseStack = new Stack <INode>();

                            if (!FindPathToNode(node, browseStack))
                            {
                                throw ComUtils.CreateComException(ResultIds.E_INVALIDBRANCHNAME);
                            }

                            // push target node onto stack.
                            browseStack.Push(node);

                            m_browseStack = browseStack;
                        }
                        catch
                        {
                            throw ComUtils.CreateComException(ResultIds.E_INVALIDBRANCHNAME);
                        }
                        break;
                    }

                    // move to a child branch.
                    case OPCAEBROWSEDIRECTION.OPCAE_BROWSE_DOWN:
                    {
                        // check for invalid name.
                        if (String.IsNullOrEmpty(szString))
                        {
                            throw ComUtils.CreateComException(ResultIds.E_INVALIDBRANCHNAME);
                        }

                        // find the current node.
                        INode parent = m_browseStack.Peek();

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

                        // find the child.
                        INode child = FindChildByName(parent.NodeId, szString);

                        if (child == null)
                        {
                            throw ComUtils.CreateComException(ResultIds.E_INVALIDBRANCHNAME);
                        }
                        // save the new position.
                        m_browseStack.Push(child);
                        break;
                    }

                    // move to a parent branch.
                    case OPCAEBROWSEDIRECTION.OPCAE_BROWSE_UP:
                    {
                        // check for invalid name.
                        if (!String.IsNullOrEmpty(szString))
                        {
                            throw ComUtils.CreateComException(ResultIds.E_FAIL);
                        }

                        // can't move up from root.
                        if (m_browseStack.Count <= 1)
                        {
                            throw ComUtils.CreateComException(ResultIds.E_FAIL);
                        }

                        // move up the stack.
                        m_browseStack.Pop();
                        break;
                    }

                    default:
                    {
                        throw ComUtils.CreateComException(ResultIds.E_INVALIDARG);
                    }
                    }
                }
                catch (COMException e)
                {
                    throw ComUtils.CreateComException(e);
                }
                catch (Exception e)
                {
                    Utils.Trace(e, "Unexpected error in ChangeBrowsePosition");
                    throw ComUtils.CreateComException(e);
                }
            }
        }