The description of a value to read.
예제 #1
0
        /// <summary>
        /// Validates a read value id parameter.
        /// </summary>
        public static ServiceResult Validate(ReadValueId valueId)
        {
            // check for null structure.
            if (valueId == null)
            {
                return(StatusCodes.BadStructureMissing);
            }

            // null node ids are always invalid.
            if (valueId.NodeId == null)
            {
                return(StatusCodes.BadNodeIdInvalid);
            }

            // must be a legimate attribute value.
            if (!Attributes.IsValid(valueId.AttributeId))
            {
                return(StatusCodes.BadAttributeIdInvalid);
            }

            // data encoding and index range is only valid for value attributes.
            if (valueId.AttributeId != Attributes.Value)
            {
                if (!String.IsNullOrEmpty(valueId.IndexRange))
                {
                    return(StatusCodes.BadIndexRangeNoData);
                }

                if (!QualifiedName.IsNull(valueId.DataEncoding))
                {
                    return(StatusCodes.BadDataEncodingInvalid);
                }
            }

            // initialize as empty.
            valueId.ParsedIndexRange = NumericRange.Empty;

            // parse the index range if specified.
            if (!String.IsNullOrEmpty(valueId.IndexRange))
            {
                try
                {
                    valueId.ParsedIndexRange = NumericRange.Parse(valueId.IndexRange);
                }
                catch (Exception e)
                {
                    return(ServiceResult.Create(e, StatusCodes.BadIndexRangeInvalid, String.Empty));
                }
            }
            else
            {
                valueId.ParsedIndexRange = NumericRange.Empty;
            }

            // passed basic validation.
            return(null);
        }
        /// <summary>
        /// Validates a read value id parameter.
        /// </summary>
        public static ServiceResult Validate(ReadValueId valueId)
        {
            // check for null structure.
            if (valueId == null)
            {
                return StatusCodes.BadStructureMissing;
            }

            // null node ids are always invalid.
            if (valueId.NodeId == null)
            {
                return StatusCodes.BadNodeIdInvalid;
            }
            
            // must be a legimate attribute value.
            if (!Attributes.IsValid(valueId.AttributeId))
            {
                return StatusCodes.BadAttributeIdInvalid;
            }
            
            // data encoding and index range is only valid for value attributes. 
            if (valueId.AttributeId != Attributes.Value)
            {
                if (!String.IsNullOrEmpty(valueId.IndexRange))
                {
                    return StatusCodes.BadIndexRangeNoData;
                }

                if (!QualifiedName.IsNull(valueId.DataEncoding))
                {
                    return StatusCodes.BadDataEncodingInvalid;
                }
            }

            // initialize as empty.
            valueId.ParsedIndexRange = NumericRange.Empty;

            // parse the index range if specified.
            if (!String.IsNullOrEmpty(valueId.IndexRange))
            {
                try
                {
                    valueId.ParsedIndexRange = NumericRange.Parse(valueId.IndexRange);
                }
                catch (Exception e)
                {
                    return ServiceResult.Create(e, StatusCodes.BadIndexRangeInvalid, String.Empty);
                }
            }
            else
            {
                valueId.ParsedIndexRange = NumericRange.Empty;
            }

            // passed basic validation.
            return null;
        }
		/// <summary>
		/// Initializes the object with its node type.
		/// </summary>
        public MemoryBufferMonitoredItem(
            IServerInternal     server,
            INodeManager        nodeManager,
            object              mangerHandle,
            uint                offset,
            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              minimumSamplingInterval)
        :
            base(
                server,
                nodeManager,
                mangerHandle,
                subscriptionId,
                id,
                session,
                itemToMonitor,
                diagnosticsMasks,
                timestampsToReturn,
                monitoringMode,
                clientHandle,
                originalFilter,
                filterToUse,
                range,
                samplingInterval,
                queueSize,
                discardOldest,
                minimumSamplingInterval)
		{
            m_offset = offset;
        }
예제 #4
0
        /// <summary>
        /// Prompts the user to enter a value to write.
        /// </summary>
        /// <param name="session">The session to use.</param>
        /// <param name="nodeId">The identifier for the node to write to.</param>
        /// <param name="attributeId">The attribute being written.</param>
        /// <returns>True if successful. False if the operation was cancelled.</returns>
        public bool ShowDialog(Session session, NodeId nodeId, uint attributeId)
        {
            m_session = session;
            m_nodeId  = nodeId;
            m_attributeId = attributeId;

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

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

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

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

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

            return true;
        }
예제 #5
0
        /// <summary>
        /// Finds the targets for the specified reference.
        /// </summary>
        private static void UpdateInstanceDescriptions(Session session, List<InstanceDeclaration> instances, bool throwOnError)
        {
            try
            {
                ReadValueIdCollection nodesToRead = new ReadValueIdCollection();

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

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

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

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

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

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

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

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

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

                        if (instance.ValueRank >= 0)
                        {
                            instance.DataTypeDisplayText += "[]";
                        }
                    }
                }
            }
            catch (Exception exception)
            {
                if (throwOnError)
                {
                    throw new ServiceResultException(exception, StatusCodes.BadUnexpectedError);
                }
            }
        }
예제 #6
0
        private void NewMI_Click(object sender, EventArgs e)
        {
            try
            {
                if (!m_showResults)
                {
                    ReadValueId nodeToRead = null;

                    // use the first selected row as a template.
                    foreach (DataGridViewRow row in ResultsDV.SelectedRows)
                    {
                        DataRowView source = row.DataBoundItem as DataRowView;
                        ReadValueId value = (ReadValueId)source.Row[0];
                        nodeToRead = (ReadValueId)value.Clone();
                        break;
                    }

                    if (nodeToRead == null)
                    {
                        nodeToRead = new ReadValueId() { AttributeId = Attributes.Value };
                    }

                    // edit the parameters.
                    ReadValueId[] results = new EditReadValueIdDlg().ShowDialog(m_session, nodeToRead);

                    if (results != null)
                    {
                        // add the new rows.
                        for (int ii = 0; ii < results.Length; ii++)
                        {
                            DataRow row = m_dataset.Tables[0].NewRow();
                            UpdateRow(row, results[ii]);
                            m_dataset.Tables[0].Rows.Add(row);
                        }
                    }
                }
            }
            catch (Exception exception)
            {
                ClientUtils.HandleException(this.Text, exception);
            }
        }
        /// <summary>
        /// Updates the values with the current values read from the server.
        /// </summary>
        public void Read(params WriteValue[] nodesToWrite)
        {
            if (m_session == null)
            {
                throw new ServiceResultException(StatusCodes.BadNotConnected);
            }
            
            // build list of values to read.
            ReadValueIdCollection nodesToRead = new ReadValueIdCollection();

            if (nodesToWrite == null || nodesToWrite.Length == 0)
            {
                foreach (DataGridViewRow row in ResultsDV.Rows)
                {
                    DataRowView source = row.DataBoundItem as DataRowView;
                    WriteValue value = (WriteValue)source.Row[0];
                    row.Selected = false;

                    ReadValueId nodeToRead = new ReadValueId();
                    nodeToRead.NodeId = value.NodeId;
                    nodeToRead.AttributeId = value.AttributeId;
                    nodeToRead.IndexRange = value.IndexRange;
                    nodeToRead.Handle = value;

                    nodesToRead.Add(nodeToRead);
                }
            }
            else
            {
                foreach (WriteValue value in nodesToWrite)
                {
                    ReadValueId nodeToRead = new ReadValueId();
                    nodeToRead.NodeId = value.NodeId;
                    nodeToRead.AttributeId = value.AttributeId;
                    nodeToRead.IndexRange = value.IndexRange;
                    nodeToRead.Handle = value;

                    nodesToRead.Add(nodeToRead);
                }
            }

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

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

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

            // add the results to the display.
            for (int ii = 0; ii < results.Count; ii++)
            {
                WriteValue nodeToWrite = nodesToRead[ii].Handle as WriteValue;
                DataRow row = nodeToWrite.Handle as DataRow;

                if (StatusCode.IsGood(results[ii].StatusCode))
                {
                    nodeToWrite.Value = results[ii];
                    UpdateRow(row, results[ii]);
                }
            }
        }
예제 #8
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;
            }
        }
예제 #9
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;
 }
예제 #10
0
        /// <summary>
        /// Reads the arguments for the method.
        /// </summary>
        private void ReadArguments(NodeId nodeId)
        {
            m_inputArguments = null;
            m_outputArguments = null;

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

            BrowseDescription nodeToBrowse = new BrowseDescription();

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

            nodesToBrowse.Add(nodeToBrowse);

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

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

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

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

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

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

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

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

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

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

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

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

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

            // set default values for input arguments.
            if (m_inputArguments != null)
            {
                foreach (Argument argument in m_inputArguments)
                {
                    argument.Value = TypeInfo.GetDefaultValue(argument.DataType, argument.ValueRank, m_session.TypeTree);
                }
            }
        }
예제 #11
0
        /// <summary>
        /// Reads the historical configuration for the node.
        /// </summary>
        private HistoricalDataConfigurationState ReadConfiguration()
        {
            // load the defaults for the historical configuration object. 
            HistoricalDataConfigurationState configuration = new HistoricalDataConfigurationState(null);

            configuration.Definition = new PropertyState<string>(configuration);
            configuration.MaxTimeInterval = new PropertyState<double>(configuration);
            configuration.MinTimeInterval = new PropertyState<double>(configuration);
            configuration.ExceptionDeviation = new PropertyState<double>(configuration);
            configuration.ExceptionDeviationFormat = new PropertyState<ExceptionDeviationFormat>(configuration);
            configuration.StartOfArchive = new PropertyState<DateTime>(configuration);
            configuration.StartOfOnlineArchive = new PropertyState<DateTime>(configuration);

            configuration.Create(
                m_session.SystemContext,
                null,
                Opc.Ua.BrowseNames.HAConfiguration,
                null,
                false);
            
            // get the browse paths to query.
            RelativePathElement element = new RelativePathElement();
            element.ReferenceTypeId = Opc.Ua.ReferenceTypeIds.HasHistoricalConfiguration;
            element.IsInverse = false;
            element.IncludeSubtypes = false;
            element.TargetName = Opc.Ua.BrowseNames.HAConfiguration;

            RelativePath relativePath = new RelativePath();
            relativePath.Elements.Add(element);

            BrowsePathCollection pathsToTranslate = new BrowsePathCollection();

            GetBrowsePathFromNodeState(
                m_session.SystemContext,
                m_nodeId,
                configuration,
                relativePath,
                pathsToTranslate);

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

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

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

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

            for (int ii = 0; ii < pathsToTranslate.Count; ii++)
            {
                BaseVariableState variable = (BaseVariableState)pathsToTranslate[ii].Handle;
                variable.Value = null;
                variable.StatusCode = StatusCodes.BadNotSupported;

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

                if (results[ii].Targets[0].RemainingPathIndex == UInt32.MaxValue && !results[ii].Targets[0].TargetId.IsAbsolute)
                {
                    variable.NodeId = (NodeId)results[ii].Targets[0].TargetId;

                    ReadValueId valueToRead = new ReadValueId();
                    valueToRead.NodeId = variable.NodeId;
                    valueToRead.AttributeId = Attributes.Value;
                    valueToRead.Handle = variable;
                    valuesToRead.Add(valueToRead);
                }
            }
            
            // read the values.
            if (valuesToRead.Count > 0)
            {
                DataValueCollection values = null;

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

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

                for (int ii = 0; ii < valuesToRead.Count; ii++)
                {
                    BaseVariableState variable = (BaseVariableState)valuesToRead[ii].Handle;
                    variable.WrappedValue = values[ii].WrappedValue;
                    variable.StatusCode = values[ii].StatusCode;
                }
            }

            return configuration;
        }
예제 #12
0
		/// <summary>
        /// IOPCItemIO::Read - Reads one or more values, qualities and timestamps for the items specified. 
        ///                    This is functionally similar to the IOPCSyncIO::Read method.
		/// </summary>
		public void Read(
            int               dwCount, 
            string[]          pszItemIDs, 
            int[]             pdwMaxAge, 
            out System.IntPtr ppvValues,
            out System.IntPtr ppwQualities, 
            out System.IntPtr ppftTimeStamps, 
            out System.IntPtr ppErrors)
		{
			lock (m_lock)
			{
                if (m_session == null) throw ComUtils.CreateComException(ResultIds.E_FAIL);

				// validate arguments.
				if (dwCount == 0 || pszItemIDs == null || pdwMaxAge == null || dwCount != pszItemIDs.Length || dwCount != pdwMaxAge.Length)
				{
					throw ComUtils.CreateComException(ResultIds.E_INVALIDARG);
				}

				try
				{
                    object[] values = new object[dwCount];
                    short[] qualities = new short[dwCount];
                    DateTime[] timestamps = new DateTime[dwCount];
                    int[] errors = new int[dwCount];
                    
                    // use the minimum max age for all items.
                    int maxAge = Int32.MaxValue;

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

                    for (int ii = 0; ii < dwCount; ii++)
                    {
                        values[ii]     = null;
                        qualities[ii]  = OpcRcw.Da.Qualities.OPC_QUALITY_BAD;                            
                        timestamps[ii] = DateTime.MinValue;

                        NodeId nodeId = ItemIdToNodeId(pszItemIDs[ii]);
                        
                        if (nodeId == null)
                        { 
                            errors[ii] = ResultIds.E_INVALIDITEMID;
                            continue;
                        }

                        ReadValueId nodeToRead = new ReadValueId();

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

                        // needed to correlate results to input.
                        nodeToRead.Handle = ii;

                        nodesToRead.Add(nodeToRead);

                        // calculate max age.
                        if (maxAge > pdwMaxAge[ii])
                        {
                            maxAge = pdwMaxAge[ii];
                        }
                    }
                    
                    // read values from server.
                    DataValueCollection results = null;
                    DiagnosticInfoCollection diagnosticInfos = null;
                    
                    if (nodesToRead.Count > 0)
                    {
                        m_session.Read(
                            null,
                            maxAge,
                            TimestampsToReturn.Both,
                            nodesToRead,
                            out results,
                            out diagnosticInfos);
                    
                        // validate response from the UA server.
                        ClientBase.ValidateResponse(results, nodesToRead);
                        ClientBase.ValidateDiagnosticInfos(diagnosticInfos, nodesToRead);
                    }
                    
                    for (int ii = 0; ii < nodesToRead.Count; ii++)
                    {
                        // get index in original array.
                        int index = (int)nodesToRead[ii].Handle;

                        DataValue dataValue = results[ii];

                        if (dataValue == null)
                        {                            
                            errors[index] = ResultIds.E_FAIL;
                            continue;
                        }

                        errors[index] = MapReadStatusToErrorCode(dataValue.StatusCode);

                        if (errors[index] < 0)
                        {
                            continue;
                        }
                    
                        values[index]     = ValueToVariantValue(dataValue.Value);
                        qualities[index]  = ComUtils.GetQualityCode(dataValue.StatusCode);
                        timestamps[index] = dataValue.SourceTimestamp;
                        errors[index]     = ResultIds.S_OK;
                    }

					// marshal results.
					ppvValues      = ComUtils.GetVARIANTs(values, false);
					ppwQualities   = ComUtils.GetInt16s(qualities);
					ppftTimeStamps = ComUtils.GetFILETIMEs(timestamps);

                    // marshal error codes.
                    ppErrors = ComUtils.GetInt32s(errors);
				}
				catch (Exception e)
				{
					throw ComUtils.CreateComException(e);
				}
			}
		}
예제 #13
0
        /// <summary>
        /// Reads the log file path.
        /// </summary>
        private void ReadLogFilePath()
        {
            if (m_session == null)
            {
                return;
            }

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

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

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

                DataValueCollection results = null;
                DiagnosticInfoCollection diagnosticInfos = null;

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

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

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

                LogFilePathTB.Text = results[0].GetValue<string>("");
            }
            catch (Exception exception)
            {
                ClientUtils.HandleException(this.Text, exception);
            }
            finally
            {
                m_session.ReturnDiagnostics = DiagnosticsMasks.None;
            }
        }
예제 #14
0
        /// <summary>
        /// Updates the server status structure with the values from the server.
        /// </summary>
        private void UpdateServerStatus(ref OpcRcw.Da.OPCSERVERSTATUS status)
        {
            // read the current status.
            ReadValueId nodeToRead  = new ReadValueId();

            nodeToRead.NodeId       = Opc.Ua.Variables.Server_ServerStatus;
            nodeToRead.AttributeId  = Attributes.Value;
            nodeToRead.DataEncoding = null;
            nodeToRead.IndexRange   = null;

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

            DataValueCollection values = null;
            DiagnosticInfoCollection diagnosticInfos = null;

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

            // check for read error.
            if (StatusCode.IsBad(values[0].StatusCode))
            {
                return;
            }

            // get remote status.
            ServerStatusDataType remoteStatus = ExtensionObject.ToEncodeable(values[0].Value as ExtensionObject) as ServerStatusDataType;

            if (remoteStatus == null)
            {
                return;
            }

            // extract the times.
            status.ftStartTime   = ComUtils.GetFILETIME(remoteStatus.StartTime);
            status.ftCurrentTime = ComUtils.GetFILETIME(remoteStatus.CurrentTime);

            // convert the server state.          
            switch (remoteStatus.State)
            {
                case ServerState.Running:               { status.dwServerState = OPCSERVERSTATE.OPC_STATUS_RUNNING; break; }
                case ServerState.Suspended:             { status.dwServerState = OPCSERVERSTATE.OPC_STATUS_SUSPENDED; break; }
                case ServerState.CommunicationFault:    { status.dwServerState = OPCSERVERSTATE.OPC_STATUS_COMM_FAULT; break; }
                case ServerState.Failed:                { status.dwServerState = OPCSERVERSTATE.OPC_STATUS_FAILED; break; }
                case ServerState.NoConfiguration:       { status.dwServerState = OPCSERVERSTATE.OPC_STATUS_NOCONFIG; break; }
                case ServerState.Test:                  { status.dwServerState = OPCSERVERSTATE.OPC_STATUS_TEST; break; }
                default:                                { status.dwServerState = OPCSERVERSTATE.OPC_STATUS_FAILED; break; }
            }

            BuildInfo buildInfo = remoteStatus.BuildInfo;

            // construct the vendor info.
            status.szVendorInfo = String.Format("{0}, {1}", buildInfo.ProductName, buildInfo.ManufacturerName);

            // parse the software version.
            if (!String.IsNullOrEmpty(buildInfo.SoftwareVersion))
            {
                string[] fields = buildInfo.SoftwareVersion.Split(new char[] { '.' }, StringSplitOptions.RemoveEmptyEntries);

                if (fields.Length > 0)
                {
                    status.wMajorVersion = ExtractVersionFromString(fields[0]);
                }
                
                if (fields.Length > 1)
                {
                    status.wMinorVersion = ExtractVersionFromString(fields[1]);
                }
            }

            if (!String.IsNullOrEmpty(buildInfo.BuildNumber))
            {                        
                string[] fields = buildInfo.SoftwareVersion.Split(new char[] { '.' }, StringSplitOptions.RemoveEmptyEntries);

                if (fields.Length > 0)
                {
                    status.wBuildNumber = ExtractVersionFromString(fields[0]);
                }
            }
        }
예제 #15
0
        /// <summary>
        /// Reads a set of property values for a node.
        /// </summary>
        private object[] ReadPropertyValues(INode node, IList<int> propertyIds, out int[] errors)
        {
            errors = new int[propertyIds.Count];
            object[] values = new object[propertyIds.Count];

            VariableNode variable = node as VariableNode;

            if (variable == null)
            {
                throw ComUtils.CreateComException(ResultIds.E_INVALID_PID);
            }

            Dictionary<uint,DataValue> attributes = new Dictionary<uint,DataValue>();
            Dictionary<string,DataValue> properties = new Dictionary<string,DataValue>();

            for (int ii = 0; ii < propertyIds.Count; ii++)
            {
                switch (propertyIds[ii])
                {
                    case PropertyIds.DataType:
                    {
                        attributes[Attributes.DataType] = null;
                        attributes[Attributes.ValueRank] = null;
                        break;
                    }

                    case PropertyIds.Value:
                    case PropertyIds.Quality:
                    case PropertyIds.Timestamp:
                    {
                        attributes[Attributes.Value] = null;
                        break;
                    }

                    case PropertyIds.AccessRights:
                    {
                        attributes[Attributes.AccessLevel] = null;
                        break;
                    }
                        
                    case PropertyIds.ScanRate:
                    {
                        attributes[Attributes.MinimumSamplingInterval] = null;
                        break;
                    }
                        
                    case PropertyIds.EuType:
                    {
                        attributes[Attributes.DataType] = null;
                        properties[Opc.Ua.BrowseNames.EURange] = null;
                        properties[Opc.Ua.BrowseNames.EnumStrings] = null;
                        break;
                    }
                        
                    case PropertyIds.EuInfo:
                    {
                        properties[Opc.Ua.BrowseNames.EnumStrings] = null;
                        break;
                    }
                        
                    case PropertyIds.Description:
                    {
                        attributes[Attributes.Description] = null;
                        break;
                    }
                        
                    case PropertyIds.EngineeringUnits:
                    {
                        properties[Opc.Ua.BrowseNames.EngineeringUnits] = null;
                        break;
                    }                        
                            
                    case PropertyIds.HighEU:
                    case PropertyIds.LowEU:
                    {
                        properties[Opc.Ua.BrowseNames.EURange] = null;
                        break;
                    }
                        
                    case PropertyIds.HighIR:
                    case PropertyIds.LowIR:
                    {
                        properties[Opc.Ua.BrowseNames.InstrumentRange] = null;
                        break;
                    }
                        
                    case PropertyIds.OpenLabel:
                    {
                        properties[Opc.Ua.BrowseNames.FalseState] = null;
                        break;
                    }
                        
                    case PropertyIds.CloseLabel:
                    {
                        properties[Opc.Ua.BrowseNames.TrueState] = null;
                        break;
                    }

                    case PropertyIds.TimeZone:
                    {
                        properties[Opc.Ua.BrowseNames.LocalTime] = null;
                        break;
                    }
                }
            }

            ReadValueIdCollection valuesToRead = new ReadValueIdCollection();

            // build list of attributes to read.
            foreach (uint attributeId in attributes.Keys)
            {
                ReadValueId nodeToRead = new ReadValueId();

                nodeToRead.NodeId      = ExpandedNodeId.ToNodeId(node.NodeId, m_session.NamespaceUris);
                nodeToRead.AttributeId = attributeId;

                valuesToRead.Add(nodeToRead);

                // save a handle to correlate the results with the request.
                nodeToRead.Handle = attributeId;
            }
            
            // build list of properties to read.
            foreach (string propertyName in properties.Keys)
            {
                VariableNode propertyNode = m_session.NodeCache.Find(
                    node.NodeId, 
                    ReferenceTypeIds.HasProperty, 
                    false, 
                    true, 
                    new QualifiedName(propertyName)) as VariableNode;
                
                if (propertyNode == null)
                {
                    continue;
                }

                ReadValueId nodeToRead = new ReadValueId();

                nodeToRead.NodeId      = propertyNode.NodeId;
                nodeToRead.AttributeId = Attributes.Value;

                valuesToRead.Add(nodeToRead);

                // save a handle to correlate the results with the request.
                nodeToRead.Handle = propertyName;
            }

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

            if (valuesToRead.Count > 0)
            {
                m_session.Read(
                    null,
                    0,
                    TimestampsToReturn.Both,
                    valuesToRead,
                    out results,
                    out diagnosticInfos);

                // validate response from the UA server.
                ClientBase.ValidateResponse(results, valuesToRead);
                ClientBase.ValidateDiagnosticInfos(diagnosticInfos, valuesToRead);
            }

            // update tables.
            for (int ii = 0; ii < valuesToRead.Count; ii++)
            {
                ReadValueId valueToRead = valuesToRead[ii];

                string propertyName = valueToRead.Handle as string;

                if (propertyName != null)
                {
                    properties[propertyName] = results[ii];
                }

                uint? attributeId = valueToRead.Handle as uint?;

                if (attributeId != null)
                {
                    attributes[attributeId.Value] = results[ii];
                }
            }

            // calculate DA property values.
            for (int ii = 0; ii < propertyIds.Count; ii++)
            {
                int errorId = 0;
                int propertyId = propertyIds[ii];

                switch (propertyId)
                {
                    case PropertyIds.DataType:
                    {
                        NodeId datatypeId = (NodeId)DataValueToPropertyValue(attributes[Attributes.DataType], typeof(NodeId), out errorId);

                        if (errorId < 0)
                        {
                            errors[ii] = errorId;
                            break;
                        }
                        
                        int? valueRank = (int?)DataValueToPropertyValue(attributes[Attributes.ValueRank], typeof(int), out errorId);

                        if (errorId < 0)
                        {
                            valueRank = ValueRanks.Scalar;
                            break;
                        }

                        VarEnum varType = DataTypeToVarType(datatypeId, valueRank.Value);

                        if (varType == VarEnum.VT_VARIANT)
                        {
                            varType = VarEnum.VT_EMPTY;
                        }

                        values[ii] = (short)varType;
                        break;
                    }

                    case PropertyIds.Value:
                    case PropertyIds.Quality:
                    case PropertyIds.Timestamp:
                    {
                        DataValue dataValue = attributes[Attributes.Value];

                        if (dataValue == null)
                        {                            
                            errors[ii] = ResultIds.E_INVALID_PID;
                            break;
                        }

                        errors[ii] = MapPropertyReadStatusToErrorCode(dataValue.StatusCode);

                        if (errors[ii] < 0)
                        {
                            break;
                        }

                        if (propertyId == PropertyIds.Timestamp)
                        {
                            values[ii] = dataValue.SourceTimestamp;
                            errors[ii] = ResultIds.S_OK;
                            break;
                        }

                        if (propertyId == PropertyIds.Quality)
                        {
                            values[ii] = ComUtils.GetQualityCode(dataValue.StatusCode);
                            errors[ii] = ResultIds.S_OK;
                            break;
                        }
                        
                        values[ii] = ValueToVariantValue(dataValue.Value, out errorId);
                        errors[ii] = errorId;
                        break;
                    }

                    case PropertyIds.AccessRights:
                    {
                        byte? accessLevel = (byte?)DataValueToPropertyValue(attributes[Attributes.AccessLevel], typeof(byte), out errorId);

                        if (errorId < 0)
                        {
                            errors[ii] = errorId;
                            break;
                        }
                    
                        values[ii] = ComUtils.GetAccessRights(accessLevel.Value);
                        errors[ii] = ResultIds.S_OK;
                        break;
                    }
                        
                    case PropertyIds.ScanRate:
                    {
                        double? samplingInterval = (double?)DataValueToPropertyValue(attributes[Attributes.MinimumSamplingInterval], typeof(double), out errorId);

                        if (errorId < 0)
                        {
                            errors[ii] = errorId;
                            break;
                        }

                        if (samplingInterval.Value == MinimumSamplingIntervals.Indeterminate)
                        {
                            values[ii] = (float)0;
                        }
                        else
                        {
                            values[ii] = (float)samplingInterval.Value;
                        }

                        errors[ii] = ResultIds.S_OK;
                        break;
                    }
                        
                    case PropertyIds.EuType:
                    {
                        // check if datatype attribute supported.
                        DataValue dataValue = attributes[Attributes.DataType];

                        if (dataValue == null || StatusCode.IsBad(dataValue.StatusCode))
                        {                            
                            errors[ii] = ResultIds.E_INVALID_PID;
                            break;
                        }

                        errors[ii] = ResultIds.S_OK;

                        // check for analog items.
                        Range euRange = (Range)DataValueToPropertyValue(properties[Opc.Ua.BrowseNames.EURange], typeof(Range), out errorId);

                        if (errorId == 0)
                        {                            
                            values[ii] = (int)OpcRcw.Da.OPCEUTYPE.OPC_ANALOG;
                            break;
                        }
                        
                        // check for enumerated items.
                        LocalizedText[] enumStrings = (LocalizedText[])DataValueToPropertyValue(properties[Opc.Ua.BrowseNames.EnumStrings], typeof(LocalizedText[]), out errorId);

                        if (errorId == 0)
                        {                            
                            values[ii] = (int)OpcRcw.Da.OPCEUTYPE.OPC_ENUMERATED;
                            break;
                        }

                        // normal item.
                        values[ii] = (int)OpcRcw.Da.OPCEUTYPE.OPC_NOENUM;
                        break;
                    }
                        
                    case PropertyIds.EuInfo:
                    {
                        // check if datatype attribute supported.
                        DataValue dataValue = attributes[Attributes.DataType];

                        if (dataValue == null || StatusCode.IsBad(dataValue.StatusCode))
                        {                            
                            errors[ii] = ResultIds.E_INVALID_PID;
                            break;
                        }

                        errors[ii] = ResultIds.S_OK;

                        // check for enumerated items.
                        LocalizedText[] enumStrings = (LocalizedText[])DataValueToPropertyValue(properties[Opc.Ua.BrowseNames.EnumStrings], typeof(LocalizedText[]), out errorId);

                        if (errorId == 0)
                        {                            
                            values[ii] = ValueToVariantValue(enumStrings);
                            break;
                        }
                        break;
                    }
                        
                    case PropertyIds.Description:
                    {
                        LocalizedText description = (LocalizedText)DataValueToPropertyValue(attributes[Attributes.Description], typeof(LocalizedText), out errorId);

                        if (errorId < 0)
                        {
                            errors[ii] = errorId;
                            break;
                        }

                        values[ii] = ValueToVariantValue(description);
                        errors[ii] = ResultIds.S_OK;
                        break;
                    }
                        
                    case PropertyIds.EngineeringUnits:
                    {
                        EUInformation euInfo = (EUInformation)DataValueToPropertyValue(properties[Opc.Ua.BrowseNames.EngineeringUnits], typeof(EUInformation), out errorId);

                        if (errorId < 0)
                        {                            
                            errors[ii] = errorId;
                            break;
                        }                        

                        values[ii] = ValueToVariantValue(euInfo.DisplayName);
                        errors[ii] = ResultIds.S_OK;
                        break;
                    }                        
                            
                    case PropertyIds.HighEU:
                    case PropertyIds.LowEU:
                    {
                        Range euRange = (Range)DataValueToPropertyValue(properties[Opc.Ua.BrowseNames.EURange], typeof(Range), out errorId);

                        if (errorId < 0)
                        {                            
                            errors[ii] = errorId;
                            break;
                        }

                        if (propertyId == PropertyIds.HighEU)
                        {
                            values[ii] = euRange.High;
                        }
                        else
                        {
                            values[ii] = euRange.Low;
                        }

                        errors[ii] = ResultIds.S_OK;
                        break;
                    }
                        
                    case PropertyIds.HighIR:
                    case PropertyIds.LowIR:
                    {
                        Range euRange = (Range)DataValueToPropertyValue(properties[Opc.Ua.BrowseNames.InstrumentRange], typeof(Range), out errorId);

                        if (errorId < 0)
                        {                            
                            errors[ii] = errorId;
                            break;
                        }

                        if (propertyId == PropertyIds.HighIR)
                        {
                            values[ii] = euRange.High;
                        }
                        else
                        {
                            values[ii] = euRange.Low;
                        }

                        errors[ii] = ResultIds.S_OK;
                        break;
                    }
                        
                    case PropertyIds.OpenLabel:
                    {
                        LocalizedText label = (LocalizedText)DataValueToPropertyValue(properties[Opc.Ua.BrowseNames.FalseState], typeof(LocalizedText), out errorId);

                        if (errorId < 0)
                        {                            
                            errors[ii] = errorId;
                            break;
                        }
                        
                        values[ii] = ValueToVariantValue(label);
                        errors[ii] = ResultIds.S_OK;
                        break;
                    }
                        
                    case PropertyIds.CloseLabel:
                    {
                        LocalizedText label = (LocalizedText)DataValueToPropertyValue(properties[Opc.Ua.BrowseNames.TrueState], typeof(LocalizedText), out errorId);

                        if (errorId < 0)
                        {                            
                            errors[ii] = errorId;
                            break;
                        }

                        values[ii] = ValueToVariantValue(label);
                        errors[ii] = ResultIds.S_OK;
                        break;
                    }

                    case PropertyIds.TimeZone:
                    {
                        ExtensionObject extension = (ExtensionObject)DataValueToPropertyValue(
                            properties[Opc.Ua.BrowseNames.LocalTime], 
                            typeof(ExtensionObject), 
                            out errorId);

                        if (errorId < 0)
                        {                            
                            errors[ii] = errorId;
                            break;
                        }

                        TimeZoneDataType timezone = extension.Body as TimeZoneDataType;

                        if (timezone == null)
                        {
                            errors[ii] = ResultIds.DISP_E_TYPEMISMATCH;
                            break;
                        }

                        values[ii] = (int)timezone.Offset;
                        errors[ii] = ResultIds.S_OK;
                        break;
                    }

                    default:
                    {
                        errors[ii] = ResultIds.E_INVALID_PID;
                        break;
                    }
                }
            }           

            return values;
        }
예제 #16
0
 /// <summary>
 /// Creates a request to read a value from an external source.
 /// </summary>
 private ServiceResult AddReadRequest(ISystemContext context, NodeHandle handle, ReadValueId nodeToRead, List<ReadWriteRequest> requests)
 {
     requests.Add(new ReadWriteRequest() { Handle = handle, UserIdentity = context.UserIdentity });
     return ServiceResult.Good;
 }
예제 #17
0
        private void ReadNode(NodeId nodeid, bool ignoreroot, bool ignorechildren, String DriverName)
        {
            INode node = m_session.NodeCache.Find(nodeid);
            if (node != null)
            {
                //TreeNode root = new TreeNode(node.ToString());
                //root.ImageIndex = ClientUtils.GetImageIndex(m_session, node.NodeClass, node.TypeDefinitionId, false);
                //root.SelectedImageIndex = ClientUtils.GetImageIndex(m_session, node.NodeClass, node.TypeDefinitionId, true);

                ReferenceDescription reference = new ReferenceDescription();

                reference.NodeId = node.NodeId;
                reference.NodeClass = node.NodeClass;
                reference.BrowseName = node.BrowseName;
                reference.DisplayName = node.DisplayName;
                reference.TypeDefinition = node.TypeDefinitionId;


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

                foreach (uint attributeId in Attributes.GetIdentifiers())
                {
                    ReadValueId nodeToRead = new ReadValueId();
                    nodeToRead.NodeId = (NodeId)reference.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);
                if (ignoreroot == false)
                {
                    //Log(results[0].ToString() + " \t| " + results[3].ToString() + " \t| "+ results[4].ToString() + " \t| " + results[12].ToString());
                    Log("UID:" + S80(results[(int)Attributes.NodeId - 1].ToString()) + " \tBrowseName: " + s40(results[(int)Attributes.BrowseName - 1].ToString()) + " \tDisplayName:  " + s40(results[(int)Attributes.DisplayName - 1].ToString()) + " \tDescription:  " + S80(results[(int)Attributes.Description - 1].ToString()) + " \tValue:  " + results[(int)Attributes.Value - 1].ToString());

                    dr = dt.NewRow();
                    dr["UID"] = results[(int)Attributes.NodeId - 1].ToString();
                    dr["BrowseName"] = results[(int)Attributes.BrowseName - 1].ToString();
                    dr["DisplayName"] = results[(int)Attributes.DisplayName - 1].ToString();
                    dr["Description"] = results[(int)Attributes.Description - 1].ToString();
                    dr["Value"] = results[(int)Attributes.Value - 1].ToString();
                    dr["Name"] = DriverName;
                    dt.Rows.Add(dr);
                    if (results[(int)Attributes.AccessLevel - 1].Value != null)
                    {
                        if (((byte)(results[(int)Attributes.AccessLevel - 1].GetValue(typeof(byte))) & AccessLevels.HistoryRead) == AccessLevels.HistoryRead)
                        {
                            //gv.DataSource = dt;
                            ReadHistory(DateTime.Now.AddDays(-1), DateTime.Now, new NodeId(results[0].ToString()), 25, "");
                        }
                    }
                }

                if (ignorechildren == false)
                {
                    BrowseDescriptionCollection nodesToBrowse = new BrowseDescriptionCollection();


                    BrowseDescription nodeToBrowse = new BrowseDescription();

                    nodeToBrowse.NodeId = nodeid;
                    nodeToBrowse.BrowseDirection = BrowseDirection.Forward;
                    nodeToBrowse.ReferenceTypeId = Opc.Ua.ReferenceTypeIds.HierarchicalReferences;
                    nodeToBrowse.IncludeSubtypes = true;
                    nodeToBrowse.NodeClassMask = 0;
                    nodeToBrowse.ResultMask = (uint)BrowseResultMask.All;

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

                    nodesToBrowse.Add(nodeToBrowse);

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

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


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

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

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

                        m_session.Read(
                         null,
                         0,
                         TimestampsToReturn.Neither,
                         nodesToRead,
                         out results,
                         out diagnosticInfos);
                        //    Log("UID:"+results[0].ToString() + " \tBrowseName: " + results[(int)Attributes.BrowseName].ToString() + " \tDisplayName:  " + results[(int)Attributes.DisplayName].ToString() + " \tDescription:  " + results[(int)Attributes.Description].ToString() + " \t|  " + results[(int)Attributes.Value].ToString());
                        //Log("UID:" + S80(results[(int)Attributes.NodeId - 1].ToString()) + " \tBrowseName: " + results[(int)Attributes.BrowseName - 1].ToString() + " \tDisplayName:  " + results[(int)Attributes.DisplayName - 1].ToString() + " \tDescription:  " + results[(int)Attributes.Description - 1].ToString() + " \tValue:  " + results[(int)Attributes.Value - 1].ToString());
                        Log("UID:" + S80(results[(int)Attributes.NodeId - 1].ToString()) + " \tBrowseName: " + s40(results[(int)Attributes.BrowseName - 1].ToString()) + " \tDisplayName:  " + s40(results[(int)Attributes.DisplayName - 1].ToString()) + " \tDescription:  " + S80(results[(int)Attributes.Description - 1].ToString()) + " \tValue:  " + results[(int)Attributes.Value - 1].ToString());
                        dr = dt.NewRow();
                        dr["UID"] = results[(int)Attributes.NodeId - 1].ToString();
                        dr["BrowseName"] = results[(int)Attributes.BrowseName - 1].ToString();
                        dr["DisplayName"] = results[(int)Attributes.DisplayName - 1].ToString();
                        dr["Description"] = results[(int)Attributes.Description - 1].ToString();
                        dr["Value"] = results[(int)Attributes.Value - 1].ToString();
                        dt.Rows.Add(dr);
                        try
                        {
                            if (results[(int)Attributes.AccessLevel - 1].Value != null)
                            {
                                if (((byte)(results[(int)Attributes.AccessLevel - 1].GetValue(typeof(byte))) & AccessLevels.HistoryRead) == AccessLevels.HistoryRead)
                                {
                                    //gv.DataSource = dt;
                                    ReadHistory(DateTime.Today, DateTime.Now, new NodeId(results[0].ToString()), 25, "");
                                }
                            }
                            else
                            {
                                if (results[(int)Attributes.Value - 1].Value == null)
                                {
                                   // gv.DataSource = dt;
                                    ReadNode(new NodeId(results[(int)Attributes.NodeId - 1].ToString()), true, false, "");
                                }

                            }
                        }
                        catch
                        {
                            Log("V=" + results[17].ToString());
                        }

                    }
                }

            }

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

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

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

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

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

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

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

            // the type info object is used in cast and compare functions.
            return new TypeInfo(builtInType, valueRank);
        }
예제 #19
0
        /// <summary>
        /// Reads the attributes for the node.
        /// </summary>
        public void ReadAttributes(NodeId nodeId, bool showProperties)
        {
            AttributesLV.Items.Clear();

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

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

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

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

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

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

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

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

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

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

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

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

            if (showProperties)
            {
                ReadProperties(nodeId);
            }

            // set the column widths.
            for (int ii = 0; ii < AttributesLV.Columns.Count; ii++)
            {
                AttributesLV.Columns[ii].Width = -2;
            }
        }
예제 #20
0
        /// <summary>
        /// Displays the attributes and properties in the attributes view.
        /// </summary>
        /// <param name="sourceId">The NodeId of the Node to browse.</param>
        private void DisplayAttributes(NodeId sourceId)
        {
            try
            {
                AttributesLV.Items.Clear();

                ReadValueIdCollection nodesToRead = new ReadValueIdCollection();

                // attempt to read all possible attributes.
                for (uint ii = Attributes.NodeClass; ii <= Attributes.UserExecutable; ii++)
                {
                    ReadValueId nodeToRead = new ReadValueId();
                    nodeToRead.NodeId = sourceId;
                    nodeToRead.AttributeId = ii;
                    nodesToRead.Add(nodeToRead);
                }

                int startOfProperties = nodesToRead.Count;

                // find all of the pror of the node.
                BrowseDescription nodeToBrowse1 = new BrowseDescription();

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

                BrowseDescriptionCollection nodesToBrowse = new BrowseDescriptionCollection();
                nodesToBrowse.Add(nodeToBrowse1);

                // fetch property references from the server.
                ReferenceDescriptionCollection references = FormUtils.Browse(m_session, nodesToBrowse, false);

                if (references == null)
                {
                    return;
                }

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

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

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

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

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

                // process results.
                for (int ii = 0; ii < results.Count; ii++)
                {
                    string name = null;
                    string datatype = null;
                    string value = null;

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

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

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

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

                            datatype = typeInfo.BuiltInType.ToString();

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

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

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

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

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

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

                            datatype = typeInfo.BuiltInType.ToString();

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

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

                    // add the attribute name/value to the list view.
                    ListViewItem item = new ListViewItem(name);
                    item.SubItems.Add(datatype);
                    item.SubItems.Add(value);
                    AttributesLV.Items.Add(item);
                }

                // adjust width of all columns.
                for (int ii = 0; ii < AttributesLV.Columns.Count; ii++)
                {
                    AttributesLV.Columns[ii].Width = -2;
                }
            }
            catch (Exception exception)
            {
                ClientUtils.HandleException(this.Text, exception);
            }
        }
예제 #21
0
        /// <summary>
        /// Reads the properties for the node.
        /// </summary>
        private void ReadProperties(NodeId nodeId)
        {
            // build list of references to browse.
            BrowseDescriptionCollection nodesToBrowse = new BrowseDescriptionCollection();

            BrowseDescription nodeToBrowse = new BrowseDescription();

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

            nodesToBrowse.Add(nodeToBrowse);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

                // display in list.
                AttributesLV.Items.Add(item);
            }
        }
예제 #22
0
        /// <summary>
        /// Creates a new data change monitored item.
        /// </summary>
        public MemoryBufferMonitoredItem CreateDataChangeItem(
            ServerSystemContext context,
            MemoryTagState      tag,
            uint                subscriptionId,
            uint                monitoredItemId,
            ReadValueId         itemToMonitor,
            DiagnosticsMasks    diagnosticsMasks,
            TimestampsToReturn  timestampsToReturn,
            MonitoringMode      monitoringMode,
            uint                clientHandle,
            double              samplingInterval)

            /*
            ISystemContext context,
            MemoryTagState tag,
            uint monitoredItemId,
            uint attributeId,
            DiagnosticsMasks diagnosticsMasks,
            TimestampsToReturn timestampsToReturn,
            MonitoringMode monitoringMode,
            uint clientHandle,
            double samplingInterval)*/
        {
            lock (m_dataLock)
            {
                MemoryBufferMonitoredItem monitoredItem = new MemoryBufferMonitoredItem(
                    m_server,
                    m_nodeManager,
                    this,
                    tag.Offset,
                    0,
                    monitoredItemId,
                    context.OperationContext.Session,
                    itemToMonitor,
                    diagnosticsMasks,
                    timestampsToReturn,
                    monitoringMode,
                    clientHandle,
                    null,
                    null,
                    null,
                    samplingInterval,
                    0,
                    false,
                    0);

                /*
                MemoryBufferMonitoredItem monitoredItem = new MemoryBufferMonitoredItem(
                    this,
                    monitoredItemId,
                    tag.Offset,
                    attributeId,
                    diagnosticsMasks,
                    timestampsToReturn,
                    monitoringMode,
                    clientHandle,
                    samplingInterval);
                */

                if (itemToMonitor.AttributeId != Attributes.Value)
                {
                    m_nonValueMonitoredItems.Add(monitoredItem.Id, monitoredItem);
                    return monitoredItem;
                }

                int elementCount = (int)(SizeInBytes.Value / ElementSize);

                if (m_monitoringTable == null)
                {
                    m_monitoringTable = new MemoryBufferMonitoredItem[elementCount][];
                    m_scanTimer = new Timer(DoScan, null, 100, 100);
                }

                int elementOffet = (int)(tag.Offset / ElementSize);

                MemoryBufferMonitoredItem[] monitoredItems = m_monitoringTable[elementOffet];

                if (monitoredItems == null)
                {
                    monitoredItems = new MemoryBufferMonitoredItem[1];
                }
                else
                {
                    monitoredItems = new MemoryBufferMonitoredItem[monitoredItems.Length + 1];
                    m_monitoringTable[elementOffet].CopyTo(monitoredItems, 0);
                }

                monitoredItems[monitoredItems.Length - 1] = monitoredItem;
                m_monitoringTable[elementOffet] = monitoredItems;
                m_itemCount++;

                return monitoredItem;
            }
        }
예제 #23
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);

                    // add the default locale
                    localeList.Add(ComUtils.LOCALE_SYSTEM_DEFAULT);
                    localeList.Add(ComUtils.LOCALE_USER_DEFAULT);
                    
                    // cache the supported locales.
                    locales = values[0].Value as string[];

                    if (locales != null)
                    {
                        foreach (string locale in locales)
                        {
                            localeList.Add(ComUtils.GetLocale(locale));
                        }
                    }
                }
                catch (Exception e)
                {
                    throw ComUtils.CreateComException(e);
                }

                return localeList;
            }
        }
예제 #24
0
        /// <summary>
        /// Reads the historical configuration for the node.
        /// </summary>
        private List<PropertyWithHistory> FindPropertiesWithHistory()
        {
            BrowseDescription nodeToBrowse = new BrowseDescription();
            nodeToBrowse.NodeId = m_nodeId;
            nodeToBrowse.ReferenceTypeId = Opc.Ua.ReferenceTypeIds.HasProperty;
            nodeToBrowse.IncludeSubtypes = true;
            nodeToBrowse.BrowseDirection = BrowseDirection.Forward;
            nodeToBrowse.NodeClassMask = 0;
            nodeToBrowse.ResultMask = (uint)(BrowseResultMask.DisplayName | BrowseResultMask.BrowseName);

            ReferenceDescriptionCollection references = ClientUtils.Browse(m_session, nodeToBrowse, false);

            ReadValueIdCollection nodesToRead = new ReadValueIdCollection();

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

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

            List<PropertyWithHistory> properties = new List<PropertyWithHistory>();
            properties.Add(new PropertyWithHistory() { DisplayText = "(none)", NodeId = m_nodeId, AccessLevel = AccessLevels.HistoryReadOrWrite });

            if (nodesToRead.Count > 0)
            {
                DataValueCollection values = null;
                DiagnosticInfoCollection diagnosticInfos = null;

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

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

                for (int ii = 0; ii < nodesToRead.Count; ii++)
                {
                    byte accessLevel = values[ii].GetValue<byte>(0);

                    if ((accessLevel & AccessLevels.HistoryRead) != 0)
                    {
                        properties.Add(new PropertyWithHistory((ReferenceDescription)nodesToRead[ii].Handle, accessLevel));
                    }
                }
            }

            return properties;
        }
예제 #25
0
        private void RefreshBTN_Click(object sender, EventArgs e)
        {
            try
            {
                ReadValueId nodeToRead = new ReadValueId();
                nodeToRead.NodeId = m_variableId;
                nodeToRead.AttributeId = Attributes.Value;
                nodeToRead.DataEncoding = m_encodingName;


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

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

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

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

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

                SetValue(results[0].WrappedValue);
            }
            catch (Exception exception)
            {
                ClientUtils.HandleException(this.Text, exception);
            }
        }
        /// <summary>
        /// Reads the values displayed in the control and moves to the display results state.
        /// </summary>
        public void Read()
        {
            if (m_session == null)
            {
                throw new ServiceResultException(StatusCodes.BadNotConnected);
            }

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

            foreach (DataGridViewRow row in ResultsDV.Rows)
            {
                DataRowView source = row.DataBoundItem as DataRowView;
                InstanceDeclaration value = (InstanceDeclaration)source.Row[0];
                row.Selected = false;

                ReadValueId nodeToRead = new ReadValueId();
                nodeToRead.NodeId = value.NodeId;
                nodeToRead.AttributeId = (value.NodeClass == NodeClass.Variable) ? Attributes.Value : Attributes.NodeId;
                nodesToRead.Add(nodeToRead);
            }
            
            // read the values.
            DataValueCollection results = null;
            DiagnosticInfoCollection diagnosticInfos = null;

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

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

            DescriptionCH.Visible = false;
            ValueCH.Visible = true;

            // add the results to the display.
            for (int ii = 0; ii < results.Count; ii++)
            {
                DataRowView source = ResultsDV.Rows[ii].DataBoundItem as DataRowView;
                UpdateRow(source.Row, results[ii]);
            }
        }
예제 #27
0
파일: Program.cs 프로젝트: yuriik83/UA-.NET
        /// <summary>
        /// Reads the values for a set of variables.
        /// </summary>
        static void Read(Session session)
        {
            IList<NodeOfInterest> results = GetNodeIds(session, Opc.Ua.Objects.ObjectsFolder,
                VariableBrowsePaths.ToArray());
            // build list of nodes to read.
            ReadValueIdCollection nodesToRead = new ReadValueIdCollection();

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

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

            // read values.
            DataValueCollection values;
            DiagnosticInfoCollection diagnosticInfos;

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

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

                // check for error.
                if (StatusCode.IsBad(values[ii].StatusCode))
                {
                    ServiceResult result = Session.GetResult(values[ii].StatusCode, ii, diagnosticInfos, responseHeader);
                    Console.WriteLine("Read result for {0}: {1}", VariableBrowsePaths[ii], result.ToLongString());
                    continue;
                }
                
                // write value.
                Console.WriteLine( "{0}: V={1}, Q={2}, SrvT={3}, SrcT={4}",nodesToRead[ii].NodeId, values[ii].Value.ToString(),
                    values[ii].StatusCode.ToString(), values[ii].ServerTimestamp, values[ii].SourceTimestamp);
            }
        }
예제 #28
0
        /// <summary>
        /// Handles the AfterSelect event of the BrowseTV control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Windows.Forms.TreeViewEventArgs"/> instance containing the event data.</param>
        private void BrowseTV_AfterSelect(object sender, TreeViewEventArgs e)
        {
            try
            {
                EventFieldsLV.Items.Clear();

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

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

                OkBTN.Enabled = true;

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

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

                filter.EventTypeId = eventTypeId;

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

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

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

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

                DataValueCollection results = null;
                DiagnosticInfoCollection diagnosticInfos = null;

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

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

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

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

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

                    field.Operand = fields[ii];

                    StringBuilder displayName = new StringBuilder();

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

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

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

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

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

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

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

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

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

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

                // resize columns to fit text.
                for (int ii = 0; ii < EventFieldsLV.Columns.Count; ii++)
                {
                    EventFieldsLV.Columns[ii].Width = -2;
                } 
            }
            catch (Exception exception)
            {
                MessageBox.Show(exception.Message, this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
예제 #29
0
        /// <summary>
        /// Prompts the user to edit the read request parameters for the set of nodes provided.
        /// </summary>
        public ReadValueId[] ShowDialog(Session session, params ReadValueId[] nodesToRead)
        {
            NodeBTN.Session = session;
            NodeBTN.SelectedReference = null;

            bool editNode = true;
            bool editAttribute = true;
            bool editIndexRange = true;
            bool editDataEncoding = true;

            // populate the controls.
            if (nodesToRead != null && nodesToRead.Length > 0)
            {
                bool nonValueAttribute = false;

                for (int ii = 0; ii < nodesToRead.Length; ii++)
                {
                    if (nodesToRead[ii] == null)
                    {
                        continue;
                    }

                    // only show the node if all have the same node id.
                    if (editNode)
                    {
                        if (NodeBTN.SelectedNode != null && nodesToRead[ii].NodeId != NodeBTN.SelectedNode)
                        {
                            NodeTB.Visible = false;
                            NodeLB.Visible = false;
                            NodeBTN.Visible = false;
                            editNode = false;
                        }
                        else
                        {
                            NodeBTN.SelectedNode = nodesToRead[ii].NodeId;
                        }
                    }

                    // only show the attribute if all have the same attribute id.
                    if (editAttribute)
                    {
                        // check if any non-value attributes are present.
                        if (nodesToRead[ii].AttributeId != Attributes.Value)
                        {
                            nonValueAttribute = true;
                        }

                        int index = (int)nodesToRead[ii].AttributeId - 1;

                        if (AttributeCB.SelectedIndex != -1 && index != AttributeCB.SelectedIndex)
                        {
                            AttributeCB.Visible = false;
                            AttributeLB.Visible = false;
                            editAttribute = false;
                        }
                        else
                        {
                            AttributeCB.SelectedIndex = index;
                        }
                    }
                }

                DataEncodingCB.Items.Clear();
                editIndexRange = !nonValueAttribute;

                IndexRangeLB.Visible = editIndexRange;
                IndexRangeTB.Visible = editIndexRange;

                if (!nonValueAttribute)
                {
                    // use the index range for the first node as template.
                    IndexRangeTB.Text = nodesToRead[0].IndexRange;

                    // fetch the available encodings for the first node in the list from the server.
                    IVariableBase variable = session.NodeCache.Find(nodesToRead[0].NodeId) as IVariableBase;

                    if (variable != null)
                    {
                        if (session.NodeCache.IsTypeOf(variable.DataType, Opc.Ua.DataTypeIds.Structure))
                        {
                            DataEncodingCB.Items.Add(new EncodingInfo());
                            DataEncodingCB.SelectedIndex = 0;

                            foreach (INode encoding in session.NodeCache.Find(variable.DataType, Opc.Ua.ReferenceTypeIds.HasEncoding, false, true))
                            {
                                DataEncodingCB.Items.Add(new EncodingInfo() { EncodingName = encoding.BrowseName });

                                if (nodesToRead[0].DataEncoding == encoding.BrowseName)
                                {
                                    DataEncodingCB.SelectedIndex = DataEncodingCB.Items.Count - 1;
                                }
                            }
                        }
                    }
                }

                // hide the data encodings if none to select.
                if (DataEncodingCB.Items.Count == 0)
                {
                    DataEncodingCB.Visible = false;
                    DataEncodingLB.Visible = false;
                    editDataEncoding = false;
                }
            }

            if (!editNode && !editAttribute && !editIndexRange && !editDataEncoding)
            {
                throw new ArgumentException("nodesToRead", "It is not possible to edit the current selection as a group.");
            }

            if (base.ShowDialog() != DialogResult.OK)
            {
                return null;
            }

            // create the list of results.
            ReadValueId[] results = null;

            if (nodesToRead == null || nodesToRead.Length == 0)
            {
                results = new ReadValueId[1];
            }
            else
            {
                results = new ReadValueId[nodesToRead.Length];
            }

            // copy the controls into the results.
            for (int ii = 0; ii < results.Length; ii++)
            {
                // preserve the existing settings if they are not being changed.
                if (nodesToRead != null && nodesToRead.Length > 0)
                {
                    results[ii] = (ReadValueId)nodesToRead[ii].Clone();
                }
                else
                {
                    results[ii] = new ReadValueId();
                }

                // only copy results that were actually being edited. 
                if (editNode)
                {
                    results[ii].NodeId = NodeBTN.SelectedNode;
                }

                if (editAttribute)
                {
                    results[ii].AttributeId = (uint)(AttributeCB.SelectedIndex + 1);
                }

                if (editIndexRange)
                {
                    results[ii].ParsedIndexRange = NumericRange.Parse(IndexRangeTB.Text);

                    if (NumericRange.Empty != results[ii].ParsedIndexRange)
                    {
                        results[ii].IndexRange = results[ii].ParsedIndexRange.ToString();
                    }
                    else
                    {
                        results[ii].IndexRange = String.Empty;
                    }
                }

                if (editDataEncoding)
                {
                    results[ii].DataEncoding = null;

                    EncodingInfo encoding = DataEncodingCB.SelectedItem as EncodingInfo;

                    if (encoding != null)
                    {
                        results[ii].DataEncoding = encoding.EncodingName;
                    }
                }
            }

            return results;
        }
예제 #30
0
        /// <summary>
        /// Handles a read request.
        /// </summary>
        public List<ServiceResult> Read(List<ReadRequest> requests)
        {
            if (m_session == null)
            {
                throw new ServiceResultException(StatusCodes.BadCommunicationError);
            }

            ReadValueIdCollection valuesToRead = new ReadValueIdCollection();

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

            DataValueCollection results = null;
            DiagnosticInfoCollection diagnosticInfos = null;

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

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

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

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

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

            return errors;
        }