/// <summary>
 /// Initializes a new instance of the <see cref="HdaHistoryReadRawModifiedRequest"/> class.
 /// </summary>
 /// <param name="itemId">The item id.</param>
 /// <param name="attributeId">The attribute id.</param>
 /// <param name="details">The details.</param>
 /// <param name="nodeToRead">The node to read.</param>
 public HdaHistoryReadAttributeRequest(string itemId, uint attributeId, ReadRawModifiedDetails details, HistoryReadValueId nodeToRead)
     :
     base(itemId, details, nodeToRead)
 {
     MaxReturnValues = (int)details.NumValuesPerNode;
     m_attributeId   = attributeId;
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="HdaHistoryReadRawModifiedRequest"/> class.
 /// </summary>
 /// <param name="itemId">The item id.</param>
 /// <param name="details">The details.</param>
 /// <param name="nodeToRead">The node to read.</param>
 public HdaHistoryReadRawModifiedRequest(string itemId, ReadRawModifiedDetails details, HistoryReadValueId nodeToRead)
     :
     base(itemId, details, nodeToRead)
 {
     StartTime       = details.StartTime;
     EndTime         = details.EndTime;
     MaxReturnValues = (int)details.NumValuesPerNode;
     ReturnBounds    = details.ReturnBounds;
     IsReadModified  = details.IsReadModified;
 }
        /// <summary>
        /// read History data
        /// </summary>
        /// <param name="tag">节点的索引</param>
        /// <param name="start">开始时间</param>
        /// <param name="end">结束时间</param>
        /// <param name="count">读取的个数</param>
        /// <param name="containBound">是否包含边界</param>
        /// <returns>读取的数据列表</returns>
        public IEnumerable <DataValue> ReadHistoryRawDataValues(string tag, DateTime start, DateTime end, uint count = 1, bool containBound = false)
        {
            HistoryReadValueId m_nodeToContinue = new HistoryReadValueId()
            {
                NodeId = new NodeId(tag),
            };

            RequestHeader requestHeader = new RequestHeader();

            ReadRawModifiedDetails m_details = new ReadRawModifiedDetails
            {
                StartTime        = start.ToUniversalTime(),
                EndTime          = end.ToUniversalTime(),
                NumValuesPerNode = count,
                IsReadModified   = false,
                ReturnBounds     = containBound
            };

            HistoryReadValueIdCollection nodesToRead = new HistoryReadValueIdCollection();

            nodesToRead.Add(m_nodeToContinue);


            m_session.HistoryRead(
                requestHeader,
                new ExtensionObject(m_details),
                TimestampsToReturn.Both,
                false,
                nodesToRead,
                out HistoryReadResultCollection results,
                out DiagnosticInfoCollection diagnosticInfos);

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

            if (StatusCode.IsBad(results[0].StatusCode))
            {
                throw new ServiceResultException(results[0].StatusCode);
            }

            if (results[0].HistoryData != null)
            {
                HistoryData values = ExtensionObject.ToEncodeable(results[0].HistoryData) as HistoryData;
                foreach (var value in values.DataValues)
                {
                    if (value.SourceTimestamp < m_details.StartTime || value.SourceTimestamp > m_details.EndTime)
                    {
                        var difference = (m_details.StartTime - value.SourceTimestamp).Hours;
                        value.SourceTimestamp = value.SourceTimestamp.AddHours(difference);
                    }
                    yield return(value);
                }
            }
        }
Beispiel #4
0
 public OpcHistoryReadAction(Uri endpointUrl, HistoryReadActionModel hrActionModel) : base(endpointUrl, hrActionModel.Id)
 {
     details = new ReadRawModifiedDetails
     {
         StartTime        = hrActionModel.StartTime,
         EndTime          = hrActionModel.EndTime,
         IsReadModified   = hrActionModel.IsReadModified,
         NumValuesPerNode = hrActionModel.NumValuesPerNode,
         ReturnBounds     = hrActionModel.ReturnBounds
     };
 }
Beispiel #5
0
        public async Task <TimeSeries> GetTimeSeriesAsync(DateTime dateTimeFrom, DateTime dateTimeTo,
                                                          double lessThen, double moreThen)
        {
            return(await Task.Run(() =>
            {
                var details = new ReadRawModifiedDetails
                {
                    StartTime = dateTimeFrom,
                    EndTime = dateTimeTo,
                    ReturnBounds = false
                };

                var nodesToRead = new HistoryReadValueIdCollection
                {
                    new HistoryReadValueId {
                        NodeId = NodeId
                    }
                };

                Client.Session.HistoryRead(
                    null,
                    new ExtensionObject(details),
                    TimestampsToReturn.Source,
                    false,
                    nodesToRead,
                    out var results,
                    out var diagnosticInfos);

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

                if (StatusCode.IsBad(results[0].StatusCode))
                {
                    throw new ServiceResultException(results[0].StatusCode);
                }

                var data = ExtensionObject.ToEncodeable(results[0].HistoryData) as HistoryData;

                var ts = new TimeSeries();

                if (data == null)
                {
                    return ts;
                }

                foreach (var result in data.DataValues)
                {
                    ts.Add(result.SourceTimestamp.ToLocalTime(), (double)result.Value);
                }

                return ts;
            }));
        }
        private ExtensionObject ReadRawModifiedDetails()
        {
            ReadRawModifiedDetails details = new ReadRawModifiedDetails {
                StartTime        = DateTime.MinValue,
                EndTime          = DateTime.UtcNow.AddDays(1),
                NumValuesPerNode = 1,
                IsReadModified   = false,
                ReturnBounds     = false
            };

            return(new ExtensionObject(details));
        }
Beispiel #7
0
 /// <summary>
 /// Reads the raw data for an item.
 /// </summary>
 protected override void HistoryReadRawModified(
     UaServerContext context,
     ReadRawModifiedDetails details,
     TimestampsToReturn timestampsToReturn,
     IList <HistoryReadValueId> nodesToRead,
     IList <HistoryReadResult> results,
     IList <ServiceResult> errors,
     List <UaNodeHandle> nodesToProcess,
     IDictionary <NodeId, NodeState> cache)
 {
     throw new NotImplementedException();
 }
Beispiel #8
0
        /// <summary>
        /// Initializes the control
        /// </summary>
        /// <param name="session"></param>
        /// <param name="details"></param>
        /// <param name="nodes"></param>
        public void Initialize(
            Session session,
            ReadRawModifiedDetails details,
            IList <ILocalNode> nodes)
        {
            m_session = session;
            m_details = details;

            StartTimeCTRL.Value           = ToControlDateTime(details.StartTime);
            StartTimeSpecifiedCHK.Checked = details.StartTime != DateTime.MinValue;
            EndTimeCTRL.Value             = ToControlDateTime(details.EndTime);
            EndTimeSpecifiedCHK.Checked   = details.EndTime != DateTime.MinValue;
            MaxValuesCTRL.Value           = details.NumValuesPerNode;
            IncludeBoundsCHK.Checked      = details.ReturnBounds;
            IsModifiedCHK.Checked         = details.IsReadModified;
        }
        /// <summary>
        /// Initializes the control
        /// </summary>
        /// <param name="session"></param>
        /// <param name="details"></param>
        /// <param name="nodes"></param>
        public void Initialize(
            Session session,
            ReadRawModifiedDetails details,
            IList<ILocalNode> nodes)
        {
            m_session = session;
            m_details = details;

            StartTimeCTRL.Value = ToControlDateTime(details.StartTime);
            StartTimeSpecifiedCHK.Checked = details.StartTime != DateTime.MinValue;
            EndTimeCTRL.Value = ToControlDateTime(details.EndTime);
            EndTimeSpecifiedCHK.Checked = details.EndTime != DateTime.MinValue;
            MaxValuesCTRL.Value = details.NumValuesPerNode;
            IncludeBoundsCHK.Checked = details.ReturnBounds;
            IsModifiedCHK.Checked = details.IsReadModified;
        }
        /// <summary>
        /// 读取一连串的历史数据,并将其转化成指定的类型
        /// </summary>
        /// <param name="tag">节点的索引</param>
        /// <param name="start">开始时间</param>
        /// <param name="end">结束时间</param>
        /// <param name="count">读取的个数</param>
        /// <param name="containBound">是否包含边界</param>
        /// <returns>读取的数据列表</returns>
        public IEnumerable <T> ReadHistoryRawDataValues <T>(string tag, DateTime start, DateTime end, uint count = 1, bool containBound = false)
        {
            HistoryReadValueId m_nodeToContinue = new HistoryReadValueId()
            {
                NodeId = new NodeId(tag),
            };

            ReadRawModifiedDetails m_details = new ReadRawModifiedDetails
            {
                StartTime        = start.ToUniversalTime(),
                EndTime          = end.ToUniversalTime(),
                NumValuesPerNode = count,
                IsReadModified   = false,
                ReturnBounds     = containBound
            };

            m_logger.Information("start {0}/end {0}", m_details.StartTime, m_details.EndTime);
            HistoryReadValueIdCollection nodesToRead = new HistoryReadValueIdCollection();

            nodesToRead.Add(m_nodeToContinue);


            m_session.HistoryRead(
                null,
                new ExtensionObject(m_details),
                TimestampsToReturn.Both,
                false,
                nodesToRead,
                out HistoryReadResultCollection results,
                out DiagnosticInfoCollection diagnosticInfos);

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

            if (StatusCode.IsBad(results[0].StatusCode))
            {
                throw new ServiceResultException(results[0].StatusCode);
            }

            HistoryData values = ExtensionObject.ToEncodeable(results[0].HistoryData) as HistoryData;

            m_logger.Information("values {0}", values);
            foreach (var value in values.DataValues)
            {
                yield return((T)value.Value);
            }
        }
Beispiel #11
0
        /// <summary>
        /// read History data
        /// </summary>
        /// <param name="tag">节点的索引</param>
        /// <param name="start">开始时间</param>
        /// <param name="end">结束时间</param>
        /// <param name="count">读取的个数</param>
        /// <param name="containBound">是否包含边界</param>
        /// <returns>读取的数据列表</returns>
        public IEnumerable <DataValue> ReadHistoryRawDataValues(string tag, DateTime start, DateTime end, uint count = 1,
                                                                bool containBound = false)
        {
            var m_nodeToContinue = new HistoryReadValueId()
            {
                NodeId = new NodeId(tag),
            };

            var m_details = new ReadRawModifiedDetails {
                StartTime        = start,
                EndTime          = end,
                NumValuesPerNode = count,
                IsReadModified   = false,
                ReturnBounds     = containBound
            };

            var nodesToRead = new HistoryReadValueIdCollection();

            nodesToRead.Add(m_nodeToContinue);

            Session.HistoryRead(
                null,
                new ExtensionObject(m_details),
                TimestampsToReturn.Both,
                false,
                nodesToRead,
                out var results,
                out var diagnosticInfos);

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

            if (StatusCode.IsBad(results[0].StatusCode))
            {
                throw new ServiceResultException(results[0].StatusCode);
            }

            var values = ExtensionObject.ToEncodeable(results[0].HistoryData) as HistoryData;

            foreach (var value in values.DataValues)
            {
                yield return(value);
            }
        }
        /// <summary>
        /// Fetches the recent history.
        /// </summary>
        private void ReadRaw(bool isReadModified)
        {
            ReadRawModifiedDetails details = new ReadRawModifiedDetails();

            details.StartTime        = (StartTimeCK.Checked)?StartTimeDP.Value.ToUniversalTime():DateTime.MinValue;
            details.EndTime          = (EndTimeCK.Checked)?EndTimeDP.Value.ToUniversalTime():DateTime.MinValue;
            details.NumValuesPerNode = (MaxReturnValuesCK.Checked)?(uint)MaxReturnValuesNP.Value:0;
            details.IsReadModified   = isReadModified;
            details.ReturnBounds     = (isReadModified)?false:ReturnBoundsCK.Checked;

            HistoryReadValueIdCollection nodesToRead = new HistoryReadValueIdCollection();
            HistoryReadValueId           nodeToRead  = new HistoryReadValueId();

            nodeToRead.NodeId = m_nodeId;
            nodesToRead.Add(nodeToRead);

            HistoryReadResultCollection results         = null;
            DiagnosticInfoCollection    diagnosticInfos = null;

            m_session.HistoryRead(
                null,
                new ExtensionObject(details),
                TimestampsToReturn.Both,
                false,
                nodesToRead,
                out results,
                out diagnosticInfos);

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

            if (StatusCode.IsBad(results[0].StatusCode))
            {
                throw new ServiceResultException(results[0].StatusCode);
            }

            HistoryData values = ExtensionObject.ToEncodeable(results[0].HistoryData) as HistoryData;

            DisplayResults(values);

            // save any continuation point.
            SaveContinuationPoint(details, nodeToRead, results[0].ContinuationPoint);
        }
Beispiel #13
0
        /// <summary>读取一连串的历史数据,并将其转化成指定的类型</summary>
        /// <param name="url">节点的索引</param>
        /// <param name="start">开始时间</param>
        /// <param name="end">结束时间</param>
        /// <param name="count">读取的个数</param>
        /// <param name="containBound">是否包含边界</param>
        /// <returns></returns>
        public IEnumerable <T> ReadHistoryRawDataValues <T>(string url, DateTime start, DateTime end, uint count = 1, bool containBound = false)
        {
            HistoryReadValueId m_nodeToContinue = new HistoryReadValueId()
            {
                NodeId = new NodeId(url)
            };
            ReadRawModifiedDetails rawModifiedDetails = new ReadRawModifiedDetails();

            rawModifiedDetails.StartTime        = start.ToUniversalTime();
            rawModifiedDetails.EndTime          = end.ToUniversalTime();
            rawModifiedDetails.NumValuesPerNode = count;
            int num1 = 0;

            rawModifiedDetails.IsReadModified = num1 != 0;
            int num2 = containBound ? 1 : 0;

            rawModifiedDetails.ReturnBounds = num2 != 0;
            ReadRawModifiedDetails       m_details   = rawModifiedDetails;
            HistoryReadValueIdCollection nodesToRead = new HistoryReadValueIdCollection();

            nodesToRead.Add(m_nodeToContinue);
            HistoryReadResultCollection results;
            DiagnosticInfoCollection    diagnosticInfos;

            this.m_session.HistoryRead((RequestHeader)null, new ExtensionObject((object)m_details), TimestampsToReturn.Both, false, nodesToRead, out results, out diagnosticInfos);
            ClientBase.ValidateResponse((IList)results, (IList)nodesToRead);
            ClientBase.ValidateDiagnosticInfos(diagnosticInfos, (IList)nodesToRead);
            if (StatusCode.IsBad(results[0].StatusCode))
            {
                throw new ServiceResultException((ServiceResult)results[0].StatusCode);
            }
            HistoryData values = ExtensionObject.ToEncodeable(results[0].HistoryData) as HistoryData;

            foreach (DataValue dataValue in (List <DataValue>)values.DataValues)
            {
                DataValue value = dataValue;
                yield return((T)value.Value);

                value = (DataValue)null;
            }
            List <DataValue> .Enumerator enumerator = new List <DataValue> .Enumerator();
        }
        /// <summary>
        /// Starts reading raw values.
        /// </summary>
        /// <param name="context">The context for the operation.</param>
        /// <param name="request">The request parameters.</param>
        /// <param name="timestampsToReturn">The timestamps to return with the value.</param>
        /// <param name="indexRange">The range to return for array values.</param>
        /// <param name="dataEncoding">The data encoding to use for structured values.</param>
        /// <param name="values">The values to return.</param>
        public void BeginReadRaw(
#pragma warning disable RECS0154 // Parameter is never used
#pragma warning disable IDE0060  // Remove unused parameter
            ServerSystemContext context,
#pragma warning restore IDE0060  // Remove unused parameter
#pragma warning restore RECS0154 // Parameter is never used
            ReadRawModifiedDetails request,
            TimestampsToReturn timestampsToReturn,
            NumericRange indexRange,
            QualifiedName dataEncoding,
            DataValueCollection values)
        {
            _request = request;

            // initialize start and end.
            _startTime = _request.StartTime;
            _endTime   = _request.EndTime;

            if (_endTime == DateTime.MinValue)
            {
                _endTime = DateTime.MaxValue;
            }

            // check the direction.
            _isForward = _startTime < _endTime;
            _position  = -1;

            DataValue value = null;

            // get first bound.
            if (_request.ReturnBounds)
            {
                value = _source.FirstRaw(_startTime, !_isForward, _request.IsReadModified, out _position);

                if (value != null)
                {
                    AddValue(timestampsToReturn, indexRange, dataEncoding, values, value);
                }
            }
        }
Beispiel #15
0
        private void ReleaseContinuationPoints()
        {
            ReadRawModifiedDetails details = new ReadRawModifiedDetails();

            HistoryReadValueId nodeToRead = new HistoryReadValueId();

            nodeToRead.NodeId = m_nodeId;

            if (m_result != null)
            {
                nodeToRead.ContinuationPoint = m_result.ContinuationPoint;
            }

            HistoryReadValueIdCollection nodesToRead = new HistoryReadValueIdCollection();

            nodesToRead.Add(nodeToRead);

            HistoryReadResultCollection results         = null;
            DiagnosticInfoCollection    diagnosticInfos = null;

            m_session.HistoryRead(
                null,
                new ExtensionObject(details),
                TimestampsToReturn.Source,
                true,
                nodesToRead,
                out results,
                out diagnosticInfos);

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

            m_result = null;

            ShowResults();
        }
Beispiel #16
0
        /// <summary>
        /// Starts reading raw values.
        /// </summary>
        /// <param name="context">The context for the operation.</param>
        /// <param name="request">The request parameters.</param>
        /// <param name="timestampsToReturn">The timestamps to return with the value.</param>
        /// <param name="indexRange">The range to return for array values.</param>
        /// <param name="dataEncoding">The data encoding to use for structured values.</param>
        /// <param name="values">The values to return.</param>
        public void BeginReadRaw(
            ServerSystemContext context,
            ReadRawModifiedDetails request,
            TimestampsToReturn timestampsToReturn,
            NumericRange indexRange,
            QualifiedName dataEncoding,
            DataValueCollection values)
        {
            m_request = request;

            // initialize start and end.
            m_startTime = m_request.StartTime;
            m_endTime   = m_request.EndTime;

            if (m_endTime == DateTime.MinValue)
            {
                m_endTime = DateTime.MaxValue;
            }

            // check the direction.
            m_isForward = m_startTime < m_endTime;
            m_position  = -1;

            DataValue value = null;

            // get first bound.
            if (m_request.ReturnBounds)
            {
                value = m_source.FirstRaw(m_startTime, !m_isForward, m_request.IsReadModified, out m_position);

                if (value != null)
                {
                    AddValue(timestampsToReturn, indexRange, dataEncoding, values, value);
                }
            }
        }
        /// <summary>
        /// Reads the history of an HDA item annotations.
        /// </summary>
        private ServiceResult HistoryReadAnnotations(
            ServerSystemContext context,
            ComHdaClient client,
            ReadRawModifiedDetails details,
            TimestampsToReturn timestampsToReturn,
            HistoryReadValueId nodeToRead,
            HdaParsedNodeId parsedNodeId,
            HistoryReadResult result)
        {
            // create the request or load it from a continuation point.
            HdaHistoryReadAnnotationRequest request = null;

            if (nodeToRead.ContinuationPoint == null)
            {
                // create a new request.
                request = new HdaHistoryReadAnnotationRequest(parsedNodeId.RootId, details, nodeToRead);

                // fetch all of the data at once.
                result.StatusCode = client.ReadAnnotationHistory(request);
            }
            else
            {
                request = LoadContinuationPoint(context, nodeToRead.ContinuationPoint) as HdaHistoryReadAnnotationRequest;

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

            // select a subset of the results.
            if (StatusCode.IsGood(result.StatusCode))
            {
                request.Results = new DataValueCollection();
                request.GetHistoryResults(context, nodeToRead, request.Results);
            }

            // fill in the results.
            if (request.Results != null)
            {
                HistoryData data = new HistoryData();
                data.DataValues = request.Results;
                result.HistoryData = new ExtensionObject(data);
            }

            // create a new continuation point.
            if (!request.Completed)
            {
                result.ContinuationPoint = SaveContinuationPoint(context, request);
            }

            return result.StatusCode;
        }
        /// <summary>
        /// Reads the raw data for a variable
        /// </summary>
        protected ServiceResult HistoryReadRaw(
            ISystemContext context,
            BaseVariableState source,
            ReadRawModifiedDetails details,
            TimestampsToReturn timestampsToReturn,
            bool releaseContinuationPoints,
            HistoryReadValueId nodeToRead,
            HistoryReadResult result)
        {
            ServerSystemContext serverContext = context as ServerSystemContext;

            HistoryDataReader reader = null;
            HistoryData       data   = new HistoryData();

            if (nodeToRead.ContinuationPoint != null && nodeToRead.ContinuationPoint.Length > 0)
            {
                // restore the continuation point.
                reader = RestoreDataReader(serverContext, nodeToRead.ContinuationPoint);

                if (reader == null)
                {
                    return(StatusCodes.BadContinuationPointInvalid);
                }

                // node id must match previous node id.
                if (reader.VariableId != nodeToRead.NodeId)
                {
                    Utils.SilentDispose(reader);
                    return(StatusCodes.BadContinuationPointInvalid);
                }

                // check if releasing continuation points.
                if (releaseContinuationPoints)
                {
                    Utils.SilentDispose(reader);
                    return(ServiceResult.Good);
                }
            }
            else
            {
                // get the source for the variable.
                IHistoryDataSource datasource = null;
                ServiceResult      error      = GetHistoryDataSource(serverContext, source, out datasource);

                if (ServiceResult.IsBad(error))
                {
                    return(error);
                }

                // create a reader.
                reader = new HistoryDataReader(nodeToRead.NodeId, datasource);

                // start reading.
                reader.BeginReadRaw(
                    serverContext,
                    details,
                    timestampsToReturn,
                    nodeToRead.ParsedIndexRange,
                    nodeToRead.DataEncoding,
                    data.DataValues);
            }

            // continue reading data until done or max values reached.
            bool complete = reader.NextReadRaw(
                serverContext,
                timestampsToReturn,
                nodeToRead.ParsedIndexRange,
                nodeToRead.DataEncoding,
                data.DataValues);

            // save continuation point.
            if (!complete)
            {
                SaveDataReader(serverContext, reader);
                result.StatusCode = StatusCodes.GoodMoreData;
            }

            // return the dat.
            result.HistoryData = new ExtensionObject(data);

            return(result.StatusCode);
        }
        /// <summary>
        /// Reads raw history data.
        /// </summary>
        protected virtual void HistoryReadRawModified(
            ServerSystemContext context,
            ReadRawModifiedDetails details,
            TimestampsToReturn timestampsToReturn,
            IList<HistoryReadValueId> nodesToRead,
            IList<HistoryReadResult> results,
            IList<ServiceResult> errors,
            List<NodeHandle> nodesToProcess,
            IDictionary<NodeId, NodeState> cache)
        {
            for (int ii = 0; ii < nodesToProcess.Count; ii++)
            {
                NodeHandle handle = nodesToProcess[ii];

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

                if (source == null)
                {
                    continue;
                }

                errors[handle.Index] = StatusCodes.BadHistoryOperationUnsupported;
            }
        }
        /// <summary>
        /// Reads the raw data for a variable
        /// </summary>
        protected ServiceResult HistoryReadRaw(
            ISystemContext context, 
            BaseVariableState source, 
            ReadRawModifiedDetails details, 
            TimestampsToReturn timestampsToReturn, 
            bool releaseContinuationPoints, 
            HistoryReadValueId nodeToRead, 
            HistoryReadResult result)
        {
            ServerSystemContext serverContext = context as ServerSystemContext;

            HistoryDataReader reader = null;
            HistoryData data = new HistoryData();

            if (nodeToRead.ContinuationPoint != null && nodeToRead.ContinuationPoint.Length > 0)
            {
                // restore the continuation point.
                reader = RestoreDataReader(serverContext, nodeToRead.ContinuationPoint);

                if (reader == null)
                {
                    return StatusCodes.BadContinuationPointInvalid;
                }

                // node id must match previous node id.
                if (reader.VariableId != nodeToRead.NodeId)
                {
                    Utils.SilentDispose(reader);
                    return StatusCodes.BadContinuationPointInvalid;
                }

                // check if releasing continuation points.
                if (releaseContinuationPoints)
                {
                    Utils.SilentDispose(reader);
                    return ServiceResult.Good;
                }
            }
            else
            {
                // get the source for the variable.
                IHistoryDataSource datasource = null;
                ServiceResult error = GetHistoryDataSource(serverContext, source, out datasource);

                if (ServiceResult.IsBad(error))
                {
                    return error;
                }

                // create a reader.
                reader = new HistoryDataReader(nodeToRead.NodeId, datasource);
                
                // start reading.
                reader.BeginReadRaw(
                    serverContext, 
                    details, 
                    timestampsToReturn, 
                    nodeToRead.ParsedIndexRange,
                    nodeToRead.DataEncoding,
                    data.DataValues);
            }
     
            // continue reading data until done or max values reached.
            bool complete = reader.NextReadRaw(
                serverContext, 
                timestampsToReturn, 
                nodeToRead.ParsedIndexRange,
                nodeToRead.DataEncoding,
                data.DataValues);

            // save continuation point.
            if (!complete)
            {
                SaveDataReader(serverContext, reader);
                result.StatusCode = StatusCodes.GoodMoreData;
            }

            // return the dat.
            result.HistoryData = new ExtensionObject(data);
            
            return result.StatusCode;
        }
        /// <summary>
        /// Reads the raw data for an item.
        /// </summary>
        protected override void HistoryReadRawModified(
            ServerSystemContext context, 
            ReadRawModifiedDetails details, 
            TimestampsToReturn timestampsToReturn, 
            IList<HistoryReadValueId> nodesToRead, 
            IList<HistoryReadResult> results, 
            IList<ServiceResult> errors,
            List<NodeHandle> nodesToProcess, 
            IDictionary<NodeId, NodeState> cache)
        {
            for (int ii = 0; ii < nodesToRead.Count; ii++)
            {
                NodeHandle handle = nodesToProcess[ii];
                HistoryReadValueId nodeToRead = nodesToRead[handle.Index];
                HistoryReadResult result = results[handle.Index];

                HistoryReadRequest request = null;

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

                    if (source == null)
                    {
                        continue;
                    }

                    // load an exising request.
                    if (nodeToRead.ContinuationPoint != null)
                    {
                        request = LoadContinuationPoint(context, nodeToRead.ContinuationPoint);

                        if (request == null)
                        {
                            errors[handle.Index] = StatusCodes.BadContinuationPointInvalid;
                            continue;
                        }
                    }

                    // create a new request.
                    else
                    {
                        request = CreateHistoryReadRequest(
                            context,
                            details,
                            handle,
                            nodeToRead);
                    }

                    // process values until the max is reached.
                    HistoryData data = (details.IsReadModified) ? new HistoryModifiedData() : new HistoryData();
                    HistoryModifiedData modifiedData = data as HistoryModifiedData;

                    while (request.NumValuesPerNode == 0 || data.DataValues.Count < request.NumValuesPerNode)
                    {
                        if (request.Values.Count == 0)
                        {
                            break;
                        }

                        DataValue value = request.Values.First.Value;
                        request.Values.RemoveFirst();
                        data.DataValues.Add(value);

                        if (modifiedData != null)
                        {
                            ModificationInfo modificationInfo = null;

                            if (request.ModificationInfos != null && request.ModificationInfos.Count > 0)
                            {
                                modificationInfo = request.ModificationInfos.First.Value;
                                request.ModificationInfos.RemoveFirst();
                            }

                            modifiedData.ModificationInfos.Add(modificationInfo);
                        }
                    }

                    errors[handle.Index] = ServiceResult.Good;

                    // check if a continuation point is requred.
                    if (request.Values.Count > 0)
                    {
                        // only set if both end time and start time are specified.
                        if (details.StartTime != DateTime.MinValue && details.EndTime != DateTime.MinValue)
                        {
                            result.ContinuationPoint = SaveContinuationPoint(context, request);
                        }
                    }

                    // check if no data returned.
                    else
                    {
                        errors[handle.Index] = StatusCodes.GoodNoData;
                    }

                    // return the data.
                    result.HistoryData = new ExtensionObject(data);
                }
                catch (Exception e)
                {
                    errors[handle.Index] = ServiceResult.Create(e, StatusCodes.BadUnexpectedError, "Unexpected error processing request.");
                }
            }
        }
        public async Task <List <OPCUATag> > ReadRaw(string serverUrl, bool bIsReadModified, DateTime dateStartDateTime, DateTime dateEndDateTime, int iMaxReturnVal, List <string> lstNodeId)
        {
            List <OPCUATag>             tags = new List <OPCUATag>();
            HistoryReadResultCollection objHistoryReadResult = new HistoryReadResultCollection();

            try
            {
                Session session = await GetSessionAsync(serverUrl);

                ReadRawModifiedDetails details = new ReadRawModifiedDetails();
                details.StartTime        = DateTime.MinValue;
                details.EndTime          = DateTime.MinValue;
                details.IsReadModified   = bIsReadModified;
                details.NumValuesPerNode = 0;

                details.StartTime = dateStartDateTime.ToUniversalTime();

                details.EndTime = dateEndDateTime.ToUniversalTime();

                details.NumValuesPerNode = (uint)iMaxReturnVal;

                HistoryReadValueIdCollection nodesToRead = new HistoryReadValueIdCollection();

                foreach (string strNodeId in lstNodeId)//OA-2018-03-13
                {
                    HistoryReadValueId nodeToRead = new HistoryReadValueId();

                    nodeToRead.NodeId = (NodeId)strNodeId;//_reference.NodeId;

                    nodesToRead.Add(nodeToRead);
                }
                HistoryReadResultCollection HistoryResults  = null;
                DiagnosticInfoCollection    diagnosticInfos = null;

                session.HistoryRead(
                    null,
                    new ExtensionObject(details),
                    TimestampsToReturn.Source,
                    false,
                    nodesToRead,
                    out HistoryResults,
                    out diagnosticInfos);

                Session.ValidateResponse(HistoryResults, nodesToRead);
                Session.ValidateDiagnosticInfos(diagnosticInfos, nodesToRead);

                #region Prepare result
                objHistoryReadResult = HistoryResults;
                if (objHistoryReadResult.Count > 0)
                {
                    var m_index = 0;
                    foreach (var result in objHistoryReadResult)
                    {
                        HistoryData results = ExtensionObject.ToEncodeable(result.HistoryData) as HistoryData;
                        if (results == null)
                        {
                            return(tags);
                        }
                        for (int ii = 0; ii < results.DataValues.Count; ii++)
                        {
                            StatusCode status      = results.DataValues[ii].StatusCode;
                            string     index       = Utils.Format("[{0}]", m_index++);
                            var        timestamp   = results.DataValues[ii].SourceTimestamp.ToLocalTime();
                            var        sec         = results.DataValues[ii].SourceTimestamp.Millisecond;
                            string     value       = Utils.Format("{0}", results.DataValues[ii].WrappedValue);
                            string     quality     = Utils.Format("{0}", (StatusCode)status.CodeBits);
                            string     historyInfo = Utils.Format("{0:X2}", (int)status.AggregateBits);
                            var        date        = String.Format("{0}.{1}", timestamp.ToString("MM/dd/yyyy HH:mm:ss"), sec.ToString().PadLeft(3, '0'));
                            OPCUATag   tag         = new OPCUATag(index, date, value, quality);

                            tags.Add(tag);
                        }
                    }
                }
                #endregion

                return(tags);
            }
            catch (Exception e)
            {
                return(tags);
            }
        }
        /// <summary>
        /// Creates a new history request.
        /// </summary>
        private HistoryReadRequest CreateHistoryReadRequest(
            ServerSystemContext context,
            ReadRawModifiedDetails details,
            NodeHandle handle,
            HistoryReadValueId nodeToRead)
        {
            bool sizeLimited = (details.StartTime == DateTime.MinValue || details.EndTime == DateTime.MinValue);
            bool applyIndexRangeOrEncoding = (nodeToRead.ParsedIndexRange != NumericRange.Empty || !QualifiedName.IsNull(nodeToRead.DataEncoding));
            bool returnBounds = !details.IsReadModified && details.ReturnBounds;
            bool timeFlowsBackward = (details.StartTime == DateTime.MinValue) || (details.EndTime != DateTime.MinValue && details.EndTime < details.StartTime);

            // find the archive item.
            ArchiveItemState item = Reload(context, handle);

            if (item == null)
            {
                throw new ServiceResultException(StatusCodes.BadNotSupported);
            }

            LinkedList<DataValue> values = new LinkedList<DataValue>();
            LinkedList<ModificationInfo> modificationInfos = null;

            if (details.IsReadModified)
            {
                modificationInfos = new LinkedList<ModificationInfo>();
            }

            // read history. 
            DataView view = item.ReadHistory(details.StartTime, details.EndTime, details.IsReadModified, handle.Node.BrowseName);

            int startBound = -1;
            int endBound = -1;
            int ii = (timeFlowsBackward)?view.Count-1:0;

            while (ii >= 0 && ii < view.Count)
            {
                try
                {
                    DateTime timestamp = (DateTime)view[ii].Row[0];

                    // check if looking for start of data.
                    if (values.Count == 0)
                    {
                        if (timeFlowsBackward)
                        {
                            if ((details.StartTime != DateTime.MinValue && timestamp >= details.StartTime) || (details.StartTime == DateTime.MinValue &&  timestamp >= details.EndTime))
                            {
                                startBound = ii;

                                if (timestamp > details.StartTime)
                                {
                                    continue;
                                }
                            }
                        }
                        else
                        {
                            if (timestamp <= details.StartTime)
                            {
                                startBound = ii;

                                if (timestamp < details.StartTime)
                                {
                                    continue;
                                }
                            }
                        }
                    }

                    // check if absolute max values specified.
                    if (sizeLimited)
                    {
                        if (details.NumValuesPerNode > 0 && details.NumValuesPerNode < values.Count)
                        {
                            break;
                        }
                    }

                    // check for end bound.
                    if (details.EndTime != DateTime.MinValue && timestamp >= details.EndTime)
                    {
                        if (timeFlowsBackward)
                        {
                            if (timestamp <= details.EndTime)
                            {
                                endBound = ii;
                                break;
                            }
                        }
                        else
                        {
                            if (timestamp >= details.EndTime)
                            {
                                endBound = ii;
                                break;
                            }
                        }
                    }

                    // check if the start bound needs to be returned.
                    if (returnBounds && values.Count == 0 && startBound != ii && details.StartTime != DateTime.MinValue)
                    {
                        // add start bound.
                        if (startBound == -1)
                        {
                            values.AddLast(new DataValue(Variant.Null, StatusCodes.BadBoundNotFound, details.StartTime, details.StartTime));
                        }
                        else
                        {
                            values.AddLast(RowToDataValue(context, nodeToRead, view[startBound], applyIndexRangeOrEncoding));
                        }

                        // check if absolute max values specified.
                        if (sizeLimited)
                        {
                            if (details.NumValuesPerNode > 0 && details.NumValuesPerNode < values.Count)
                            {
                                break;
                            }
                        }
                    }

                    // add value.
                    values.AddLast(RowToDataValue(context, nodeToRead, view[ii], applyIndexRangeOrEncoding));

                    if (modificationInfos != null)
                    {
                        modificationInfos.AddLast((ModificationInfo)view[ii].Row[6]);
                    }
                }
                finally
                {
                    if (timeFlowsBackward)
                    {
                        ii--;
                    }
                    else
                    {
                        ii++;
                    }
                }
            }

            // add late bound.
            while (returnBounds && details.EndTime != DateTime.MinValue)
            {
                // add start bound.
                if (values.Count == 0)
                {
                    if (startBound == -1)
                    {
                        values.AddLast(new DataValue(Variant.Null, StatusCodes.BadBoundNotFound, details.StartTime, details.StartTime));
                    }
                    else
                    {
                        values.AddLast(RowToDataValue(context, nodeToRead, view[startBound], applyIndexRangeOrEncoding));
                    }
                }

                // check if absolute max values specified.
                if (sizeLimited)
                {
                    if (details.NumValuesPerNode > 0 && details.NumValuesPerNode < values.Count)
                    {
                        break;
                    }
                }

                // add end bound.
                if (endBound == -1)
                {
                    values.AddLast(new DataValue(Variant.Null, StatusCodes.BadBoundNotFound, details.EndTime, details.EndTime));
                }
                else
                {
                    values.AddLast(RowToDataValue(context, nodeToRead, view[endBound], applyIndexRangeOrEncoding));
                }

                break;
            }

            HistoryReadRequest request = new HistoryReadRequest();
            request.Values = values;
            request.ModificationInfos = modificationInfos;
            request.NumValuesPerNode = details.NumValuesPerNode;
            request.Filter = null;
            return request;
        }
Beispiel #24
0
        /// <summary>
        /// Starts reading raw values.
        /// </summary>
        /// <param name="context">The context for the operation.</param>
        /// <param name="request">The request parameters.</param>
        /// <param name="timestampsToReturn">The timestamps to return with the value.</param>
        /// <param name="indexRange">The range to return for array values.</param>
        /// <param name="dataEncoding">The data encoding to use for structured values.</param>
        /// <param name="values">The values to return.</param>
        public void BeginReadRaw(
            ServerSystemContext context,
            ReadRawModifiedDetails request, 
            TimestampsToReturn timestampsToReturn, 
            NumericRange indexRange,
            QualifiedName dataEncoding,
            DataValueCollection values)
        {
            m_request = request;

            // initialize start and end.
            m_startTime = m_request.StartTime;
            m_endTime = m_request.EndTime;

            if (m_endTime == DateTime.MinValue)
            {
                m_endTime = DateTime.MaxValue;
            }

            // check the direction.
            m_isForward = m_startTime < m_endTime;
            m_position = -1;
                        
            DataValue value = null;
            
            // get first bound.
            if (m_request.ReturnBounds)
            {
                value = m_source.FirstRaw(m_startTime, !m_isForward, m_request.IsReadModified, out m_position);
               
                if (value != null)
                {
                    AddValue(timestampsToReturn, indexRange, dataEncoding, values, value);
                }
            }
        }
Beispiel #25
0
        /// <summary>
        /// Encode historic values
        /// </summary>
        /// <param name="ct"></param>
        /// <returns></returns>
        private async Task EncodeHistoricValuesAsync(CancellationToken ct)
        {
            var details = new ReadRawModifiedDetails {
                IsReadModified   = false,
                NumValuesPerNode = (uint)_maxValues,
                // Return bounding values
                ReturnBounds = true,
                // Read from today backward
                EndTime   = _startTime,
                StartTime = _endTime
            };

            //
            // Read first and retry with lower number of nodes to fix issues with
            // misbehaving servers such as reference stack server.
            //
            byte[] continuationToken = null;
            while (true)
            {
                ct.ThrowIfCancellationRequested();
                try {
                    var result = await ReadHistoryAsync <HistoryData>(details, ct);

                    if (result.history?.DataValues != null)
                    {
                        _logger.Verbose("  {count} values...",
                                        result.history.DataValues.Count);
                        foreach (var data in result.history.DataValues)
                        {
                            _encoder.WriteDataValue(null, data);
                            _count++;
                        }
                    }
                    continuationToken = result.continuationToken;
                    break;
                }
                catch (FormatException) {
                    if (details.NumValuesPerNode == 0)
                    {
                        details.NumValuesPerNode = ushort.MaxValue;
                    }
                    else
                    {
                        details.NumValuesPerNode /= 2;
                    }
                    _logger.Information("Reduced number of values to read to {count}.",
                                        details.NumValuesPerNode);
                }
            }
            // Continue reading
            while (continuationToken != null && _count < _maxValues)
            {
                // Continue reading history
                ct.ThrowIfCancellationRequested();
                var result = await ReadHistoryAsync <HistoryData>(details, ct,
                                                                  continuationToken);

                if (result.history?.DataValues != null)
                {
                    _logger.Verbose("+ {count} values...",
                                    result.history.DataValues.Count);
                    foreach (var data in result.history.DataValues)
                    {
                        _encoder.WriteDataValue(null, data);
                        _count++;
                    }
                }
                continuationToken = result.continuationToken;
            }
        }
Beispiel #26
0
        public static void GetData(TimeSeriesBlock tsb)
        {
            if (session != null)
            {
                ReadRawModifiedDetails details = new ReadRawModifiedDetails();
                details.StartTime        = startTime;
                details.EndTime          = endTime;
                details.NumValuesPerNode = 0;
                details.IsReadModified   = false;
                details.ReturnBounds     = true;

                var nodesToRead = new HistoryReadValueIdCollection();
                for (int i = 0; i < tsb.opcNodes.Count; i++)
                {
                    var      nodeToRead = new HistoryReadValueId();
                    string[] split      = tsb.opcNodes[i].Split(',');
                    nodeToRead.NodeId = new NodeId(split[1], (ushort)Convert.ToInt32(split[0]));
                    nodesToRead.Add(nodeToRead);
                }

                table = new List <List <object> >();

                HistoryReadResultCollection results         = null;
                DiagnosticInfoCollection    diagnosticInfos = null;

                bool loop = true;
                while (loop)
                {
                    session.HistoryRead(
                        null,
                        new ExtensionObject(details),
                        TimestampsToReturn.Both,
                        false,
                        nodesToRead,
                        out results,
                        out diagnosticInfos);

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

                    foreach (var res in results)
                    {
                        if (StatusCode.IsBad(res.StatusCode))
                        {
                            throw new ServiceResultException(res.StatusCode);
                        }
                    }

                    var historyData1 = ExtensionObject.ToEncodeable(results[0].HistoryData) as HistoryData;
                    var historyData2 = ExtensionObject.ToEncodeable(results[1].HistoryData) as HistoryData;
                    for (int i = 0; i < historyData1.DataValues.Count; i++)
                    {
                        var row = new List <object>();
                        row.Add(historyData1.DataValues[i].SourceTimestamp);
                        row.Add(historyData1.DataValues[i].Value);
                        row.Add(historyData2.DataValues[i].Value);
                        table.Add(row);
                    }

                    for (int i = 0; i < results.Count; i++)
                    {
                        if (results[i].ContinuationPoint == null || results[i].ContinuationPoint.Length == 0)
                        {
                            loop = false;
                            break;
                        }
                        nodesToRead[i].ContinuationPoint = results[i].ContinuationPoint;
                    }
                }
            }
        }
Beispiel #27
0
        /// <summary>
        /// Fetches the recent history.
        /// </summary>
        private void ReadRaw(bool isReadModified)
        {
            ReadRawModifiedDetails details = new ReadRawModifiedDetails();
            details.StartTime =(StartTimeCK.Checked)?StartTimeDP.Value.ToUniversalTime():DateTime.MinValue;
            details.EndTime = (EndTimeCK.Checked)?EndTimeDP.Value.ToUniversalTime():DateTime.MinValue;
            details.NumValuesPerNode = (MaxReturnValuesCK.Checked)?(uint)MaxReturnValuesNP.Value:0;
            details.IsReadModified = isReadModified;
            details.ReturnBounds = (isReadModified)?false:ReturnBoundsCK.Checked;

            HistoryReadValueIdCollection nodesToRead = new HistoryReadValueIdCollection();
            HistoryReadValueId nodeToRead = new HistoryReadValueId();
            nodeToRead.NodeId = m_nodeId;
            nodesToRead.Add(nodeToRead);

            HistoryReadResultCollection results = null;
            DiagnosticInfoCollection diagnosticInfos = null;

            m_session.HistoryRead(
                null,
                new ExtensionObject(details),
                TimestampsToReturn.Both,
                false,
                nodesToRead,
                out results,
                out diagnosticInfos);

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

            if (StatusCode.IsBad(results[0].StatusCode))
            {
                throw new ServiceResultException(results[0].StatusCode);
            }

            HistoryData values = ExtensionObject.ToEncodeable(results[0].HistoryData) as HistoryData;
            DisplayResults(values);

            // save any continuation point.
            SaveContinuationPoint(details, nodeToRead, results[0].ContinuationPoint);
        }
Beispiel #28
0
        /// <summary>
        /// Reads the first date in the archive (truncates milliseconds and converts to local).
        /// </summary>
        private DateTime ReadFirstDate()
        {
            // use the historical data configuration if available.
            if (m_configuration != null)
            {
                if (StatusCode.IsGood(m_configuration.StartOfOnlineArchive.StatusCode))
                {
                    return m_configuration.StartOfOnlineArchive.Value.ToLocalTime();
                }

                if (StatusCode.IsGood(m_configuration.StartOfArchive.StatusCode))
                {
                    return m_configuration.StartOfArchive.Value.ToLocalTime();
                }
            }

            // do it the hard way (may take a long time with some servers).
            ReadRawModifiedDetails details = new ReadRawModifiedDetails();
            details.StartTime = new DateTime(1970, 1, 1);
            details.EndTime = DateTime.MinValue;
            details.NumValuesPerNode = 1;
            details.IsReadModified = false;
            details.ReturnBounds = false;

            HistoryReadValueId nodeToRead = new HistoryReadValueId();
            nodeToRead.NodeId = m_nodeId;

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

            HistoryReadResultCollection results = null;
            DiagnosticInfoCollection diagnosticInfos = null;

            m_session.HistoryRead(
                null,
                new ExtensionObject(details),
                TimestampsToReturn.Source,
                false,
                nodesToRead,
                out results,
                out diagnosticInfos);

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

            if (StatusCode.IsBad(results[0].StatusCode))
            {
                return DateTime.MinValue;
            }

            HistoryData data = ExtensionObject.ToEncodeable(results[0].HistoryData) as HistoryData;

            if (results == null)
            {
                return DateTime.MinValue;
            }

            DateTime startTime = data.DataValues[0].SourceTimestamp;

            if (results[0].ContinuationPoint != null && results[0].ContinuationPoint.Length > 0)
            {
                nodeToRead.ContinuationPoint = results[0].ContinuationPoint;

                m_session.HistoryRead(
                    null,
                    new ExtensionObject(details),
                    TimestampsToReturn.Source,
                    true,
                    nodesToRead,
                    out results,
                    out diagnosticInfos);

                Session.ValidateResponse(results, nodesToRead);
                Session.ValidateDiagnosticInfos(diagnosticInfos, nodesToRead);
            }
            
            startTime = new DateTime(startTime.Year, startTime.Month, startTime.Day, startTime.Hour, startTime.Minute, startTime.Second, 0, DateTimeKind.Utc);
            startTime = startTime.ToLocalTime();

            return startTime;
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="HdaHistoryReadRawModifiedRequest"/> class.
 /// </summary>
 /// <param name="itemId">The item id.</param>
 /// <param name="details">The details.</param>
 /// <param name="nodeToRead">The node to read.</param>
 public HdaHistoryReadAnnotationRequest(string itemId, ReadRawModifiedDetails details, HistoryReadValueId nodeToRead)
     :
     base(itemId, details, nodeToRead)
 {
     MaxReturnValues = (int)details.NumValuesPerNode;
 }
Beispiel #30
0
        /// <summary>
        /// Creates the read requests.
        /// </summary>
        private List<HdaReadRequest> CreateReadRequests(
            Session session,
            DateTime startTime,
            DateTime endTime,
            int[] serverHandles, 
            ReadRawModifiedDetails details)
        {
            if (startTime == DateTime.MinValue || endTime == DateTime.MinValue)
            {
                throw ComUtils.CreateComException(ResultIds.E_INVALIDARG);
            }

            // specify the parameters for the request.
            details.StartTime = startTime;
            details.EndTime = endTime;
            details.IsReadModified = false;
            details.NumValuesPerNode = 0;
            details.ReturnBounds = false;

            // build the list of requests.
            List<HdaReadRequest> requests = new List<HdaReadRequest>();

            for (int ii = 0; ii < serverHandles.Length; ii++)
            {
                HdaReadRequest request = new HdaReadRequest();
                requests.Add(request);

                // initialize request.
                request.AttributeId = INTERNAL_ATTRIBUTE_ANNOTATION;
                
                // look up server handle.
                request.Handle = m_itemManager.LookupHandle(serverHandles[ii]);

                if (request.Handle == null)
                {
                    request.Error = ResultIds.E_INVALIDHANDLE;
                    continue;
                }

                request.ClientHandle = request.Handle.ClientHandle;
                
                // look up annotation property.
                NodeId annotationsId = m_itemManager.GetAnnotationsPropertyNodeId(session, request.Handle);

                if (NodeId.IsNull(annotationsId))
                {
                    request.Error = ResultIds.S_NODATA;
                    continue;
                }

                // set node id.
                request.NodeId = annotationsId;
            }

            return requests;
        }
        /// <summary>
        /// Reads the last date in the archive (truncates milliseconds and converts to local).
        /// </summary>
        private DateTime ReadLastDate()
        {
            ReadRawModifiedDetails details = new ReadRawModifiedDetails();

            details.StartTime        = DateTime.MinValue;
            details.EndTime          = DateTime.UtcNow.AddDays(1);
            details.NumValuesPerNode = 1;
            details.IsReadModified   = false;
            details.ReturnBounds     = false;

            HistoryReadValueId nodeToRead = new HistoryReadValueId();

            nodeToRead.NodeId = m_nodeId;

            HistoryReadValueIdCollection nodesToRead = new HistoryReadValueIdCollection();

            nodesToRead.Add(nodeToRead);

            HistoryReadResultCollection results         = null;
            DiagnosticInfoCollection    diagnosticInfos = null;

            m_session.HistoryRead(
                null,
                new ExtensionObject(details),
                TimestampsToReturn.Source,
                false,
                nodesToRead,
                out results,
                out diagnosticInfos);

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

            if (StatusCode.IsBad(results[0].StatusCode))
            {
                return(DateTime.MinValue);
            }

            HistoryData data = ExtensionObject.ToEncodeable(results[0].HistoryData) as HistoryData;

            if (results == null)
            {
                return(DateTime.MinValue);
            }

            DateTime endTime = data.DataValues[0].SourceTimestamp;

            if (results[0].ContinuationPoint != null && results[0].ContinuationPoint.Length > 0)
            {
                nodeToRead.ContinuationPoint = results[0].ContinuationPoint;

                m_session.HistoryRead(
                    null,
                    new ExtensionObject(details),
                    TimestampsToReturn.Source,
                    true,
                    nodesToRead,
                    out results,
                    out diagnosticInfos);

                Session.ValidateResponse(results, nodesToRead);
                Session.ValidateDiagnosticInfos(diagnosticInfos, nodesToRead);
            }

            endTime = new DateTime(endTime.Year, endTime.Month, endTime.Day, endTime.Hour, endTime.Minute, endTime.Second, 0, DateTimeKind.Utc);
            endTime = endTime.AddSeconds(1);
            endTime = endTime.ToLocalTime();

            return(endTime);
        }
Beispiel #32
0
        /// <summary>
        /// Reads the attributes.
        /// </summary>
        public List<HdaReadRequest> ReadAttributes(
            DateTime startTime,
            DateTime endTime,
            int serverHandle,
            uint[] attributeIds)
        {
            Session session = ThrowIfNotConnected();
            
            // create the read requests.
            ReadRawModifiedDetails details = new ReadRawModifiedDetails();

            List<HdaReadRequest> requests = CreateReadRequests(
                session,
                startTime,
                endTime,
                serverHandle,
                attributeIds,
                details);

            ExtensionObject extension = new ExtensionObject(details);

            // fetch all of the values.
            if (ReadAttributes(session, extension, requests, false))
            {
                ReadNext(session, extension, requests, true);
            }
            
            return requests;
        }
Beispiel #33
0
        private void ReadRaw(bool isReadModified)
        {
            ReadRawModifiedDetails details = new ReadRawModifiedDetails();
            details.StartTime = DateTime.MinValue;
            details.EndTime = DateTime.MinValue;
            details.IsReadModified = isReadModified;
            details.NumValuesPerNode = 0;
            details.ReturnBounds = ReturnBoundsCK.Checked;

            if (StartTimeCK.Checked)
            {
                details.StartTime = StartTimeDP.Value.ToUniversalTime();
            }

            if (EndTimeCK.Checked)
            {
                details.EndTime = EndTimeDP.Value.ToUniversalTime();
            }

            if (MaxReturnValuesCK.Checked)
            {
                details.NumValuesPerNode = (uint)MaxReturnValuesNP.Value;
            }

            HistoryReadValueId nodeToRead = new HistoryReadValueId();
            nodeToRead.NodeId = m_nodeId;

            if (m_result != null)
            {
                nodeToRead.ContinuationPoint = m_result.ContinuationPoint;
            }

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

            HistoryReadResultCollection results = null;
            DiagnosticInfoCollection diagnosticInfos = null;

            m_session.HistoryRead(
                null,
                new ExtensionObject(details),
                TimestampsToReturn.Source,
                false,
                nodesToRead,
                out results,
                out diagnosticInfos);

            Session.ValidateResponse(results, nodesToRead);
            Session.ValidateDiagnosticInfos(diagnosticInfos, nodesToRead);
            
            if (StatusCode.IsBad(results[0].StatusCode))
            {
                throw new ServiceResultException(results[0].StatusCode);
            }

            m_result = results[0];
       
            ShowResults();
        }
Beispiel #34
0
        /// <summary>
        /// Reads the attributes.
        /// </summary>
        public int[] ReadAttributes(
            int transactionId,
            DateTime startTime,
            DateTime endTime,
            int serverHandle,
            uint[] attributeIds,
            out int cancelId)
        {
            Session session = ThrowIfNotConnected();

            // create the read requests.
            ReadRawModifiedDetails details = new ReadRawModifiedDetails();

            List<HdaReadRequest> requests = CreateReadRequests(
                session,
                startTime,
                endTime,
                serverHandle,
                attributeIds,
                details);

            // queue the transaction.
            int[] errors = CreateTransaction(
                TransationType.ReadAttribute,
                transactionId, 
                new ExtensionObject(details),
                requests,
                true,
                out cancelId);

            // return the initial results.
            return errors;
        }
Beispiel #35
0
        /// <summary>
        /// Reads the history of attributes for Bucket Brigade.Int1.
        /// </summary>
        static void HistoryReadAttributes(Session session)
        {
            List <string> VariableBrowsePaths = new List <string>();

            VariableBrowsePaths.Add("/7:MatrikonOpc Sim Server/7:Simulation Items/7:Bucket Brigade/7:Int1/7:Description");
            VariableBrowsePaths.Add("/7:MatrikonOpc Sim Server/7:Simulation Items/7:Bucket Brigade/7:Int1/7:DataType");
            VariableBrowsePaths.Add("/7:MatrikonOpc Sim Server/7:Simulation Items/7:Bucket Brigade/7:Int1/7:ITEMID");

            // translate browse paths.
            IList <NodeOfInterest> nodeIds = GetNodeIds(session, Opc.Ua.Objects.ObjectsFolder,
                                                        VariableBrowsePaths.ToArray());


            DiagnosticInfoCollection diagnosticInfos;

            ReadRawModifiedDetails readDetails = new ReadRawModifiedDetails();

            readDetails.StartTime        = DateTime.MinValue;
            readDetails.EndTime          = DateTime.Now;
            readDetails.IsReadModified   = false;
            readDetails.NumValuesPerNode = 100;
            readDetails.ReturnBounds     = false;

            ExtensionObject eo = new ExtensionObject(readDetails.TypeId, readDetails);

            HistoryReadValueIdCollection idCollection = new HistoryReadValueIdCollection();

            for (int ii = 0; ii < nodeIds.Count; ii++)
            {
                HistoryReadValueId readValueId = new HistoryReadValueId();
                readValueId.NodeId    = nodeIds[ii].NodeId;
                readValueId.Processed = false;
                idCollection.Add(readValueId);
            }

            HistoryReadResultCollection historyReadResults;

            ResponseHeader responseHeader =
                session.HistoryRead(null, eo, TimestampsToReturn.Both, true,
                                    idCollection, out historyReadResults, out diagnosticInfos);

            // process results.

            for (int ii = 0; ii < historyReadResults.Count; ii++)
            {
                HistoryReadResult   historyReadResult = historyReadResults[ii];
                HistoryData         historyData       = null;
                DataValueCollection dataValues        = null;
                if (historyReadResult.HistoryData != null)
                {
                    historyData = ExtensionObject.ToEncodeable(historyReadResult.HistoryData) as HistoryData;
                    dataValues  = historyData.DataValues;
                }

                ServiceResult result = Session.GetResult(historyReadResult.StatusCode, ii, diagnosticInfos, responseHeader);

                Console.WriteLine("\nHistoryRead result code for {0}:  {1}", VariableBrowsePaths[ii], result.StatusCode.ToString());

                if (StatusCode.IsBad(historyReadResult.StatusCode))
                {
                    continue;
                }

                if (dataValues == null)
                {
                    Console.WriteLine("dataValues == null");
                    continue;
                }

                for (int jj = 0; jj < dataValues.Count; jj++)
                {
                    DataValue dataValue = dataValues[jj];

                    // write value.
                    Console.WriteLine("\t{0}: V={1}", jj, dataValue.Value == null ? "null" : dataValue.Value.ToString());
                    Console.WriteLine("\t Q={0}, SrvT={1}, SrcT={2}\n",
                                      dataValue.StatusCode.ToString(), dataValue.ServerTimestamp, dataValue.SourceTimestamp);
                }
            }
        }
Beispiel #36
0
        /// <summary>
        /// Creates the read requests.
        /// </summary>
        private List<HdaReadRequest> CreateReadRequests(
            Session session,
            DateTime startTime,
            DateTime endTime,
            int serverHandle, 
            uint[] attributeIds, 
            ReadRawModifiedDetails details)
        {
            if (startTime == DateTime.MinValue)
            {
                throw ComUtils.CreateComException(ResultIds.E_INVALIDARG);
            }

            // check for the special case where current values are requested.
            if (endTime == DateTime.MinValue && startTime.AddSeconds(10) < DateTime.UtcNow)
            {
                throw ComUtils.CreateComException(ResultIds.E_INVALIDARG);
            }

            // specify the parameters for the request.
            details.StartTime = startTime;
            details.EndTime = endTime;
            details.IsReadModified = false;
            details.NumValuesPerNode = 0;
            details.ReturnBounds = true;
            
            // look up server handle.
            HdaItemHandle handle = m_itemManager.LookupHandle(serverHandle);

            if (handle == null)
            {
                throw ComUtils.CreateComException(ResultIds.E_INVALIDHANDLE);
            }
            
            // get the node ids for the requested attributes.
            NodeId[] nodeIds = null;
            
            int[] errors = m_itemManager.GetAttributeHistoryNodeIds(
                session, 
                handle, 
                attributeIds,
                out nodeIds);

            // build the list of requests.
            List<HdaReadRequest> requests = new List<HdaReadRequest>();

            for (int ii = 0; ii < attributeIds.Length; ii++)
            {
                HdaReadRequest request = new HdaReadRequest();
                requests.Add(request);

                // initialize request.
                request.Handle = handle;
                request.AttributeId = attributeIds[ii];

                if (request.Handle == null)
                {
                    request.Error = ResultIds.E_INVALIDHANDLE;
                    continue;
                }

                request.ClientHandle = request.Handle.ClientHandle;
                
                // check for errors.
                if (errors[ii] != ResultIds.S_OK)
                {
                    request.Error = errors[ii];
                    request.IsComplete = true;
                    continue;
                }

                request.NodeId = nodeIds[ii];
            }

            return requests;
        }
Beispiel #37
0
        /// <summary>
        /// Reads the history of attributes for Bucket Brigade.Int1.
        /// </summary>
        static void HistoryReadAttributes(Session session)
        {

            List<string> VariableBrowsePaths = new List<string>();
                VariableBrowsePaths.Add("/7:MatrikonOpc Sim Server/7:Simulation Items/7:Bucket Brigade/7:Int1/7:Description");
                VariableBrowsePaths.Add("/7:MatrikonOpc Sim Server/7:Simulation Items/7:Bucket Brigade/7:Int1/7:DataType");
                VariableBrowsePaths.Add("/7:MatrikonOpc Sim Server/7:Simulation Items/7:Bucket Brigade/7:Int1/7:ITEMID");

            // translate browse paths.
            IList<NodeOfInterest> nodeIds = GetNodeIds(session, Opc.Ua.Objects.ObjectsFolder, 
                VariableBrowsePaths.ToArray());


            DiagnosticInfoCollection diagnosticInfos;

            ReadRawModifiedDetails readDetails = new ReadRawModifiedDetails();
            readDetails.StartTime = DateTime.MinValue;
            readDetails.EndTime = DateTime.Now;
            readDetails.IsReadModified = false;
            readDetails.NumValuesPerNode = 100;
            readDetails.ReturnBounds = false;

            ExtensionObject eo = new ExtensionObject(readDetails.TypeId, readDetails);

            HistoryReadValueIdCollection idCollection = new HistoryReadValueIdCollection();
            for (int ii = 0; ii < nodeIds.Count; ii++)
            {
                HistoryReadValueId readValueId = new HistoryReadValueId();
                readValueId.NodeId = nodeIds[ii].NodeId;
                readValueId.Processed = false;
                idCollection.Add(readValueId);
            }

            HistoryReadResultCollection historyReadResults;

            ResponseHeader responseHeader =
                session.HistoryRead(null, eo, TimestampsToReturn.Both, true,
                idCollection, out historyReadResults, out diagnosticInfos);

            // process results.

            for (int ii = 0; ii < historyReadResults.Count; ii++)
            {
                HistoryReadResult historyReadResult = historyReadResults[ii];
                HistoryData historyData = null;
                DataValueCollection dataValues = null;
                if (historyReadResult.HistoryData != null)
                {
                    historyData = ExtensionObject.ToEncodeable(historyReadResult.HistoryData) as HistoryData;
                    dataValues = historyData.DataValues;
                }

                ServiceResult result = Session.GetResult(historyReadResult.StatusCode, ii, diagnosticInfos, responseHeader);
                
                Console.WriteLine("\nHistoryRead result code for {0}:  {1}", VariableBrowsePaths[ii], result.StatusCode.ToString());

                if (StatusCode.IsBad(historyReadResult.StatusCode))
                {
                    continue;
                }

                if (dataValues == null)
                {
                    Console.WriteLine("dataValues == null");
                    continue;
                }

                for (int jj = 0; jj < dataValues.Count; jj++)
                {

                    DataValue dataValue = dataValues[jj];

                    // write value.
                    Console.WriteLine("\t{0}: V={1}",jj, dataValue.Value == null ? "null" : dataValue.Value.ToString());
                    Console.WriteLine("\t Q={0}, SrvT={1}, SrcT={2}\n",
                        dataValue.StatusCode.ToString(), dataValue.ServerTimestamp, dataValue.SourceTimestamp);
                }
            }
        }
Beispiel #38
0
        /// <summary>
        /// Deletes the raw data.
        /// </summary>
        public int[] DeleteRaw(
            int transactionId,
            DateTime startTime,
            DateTime endTime,
            int[] serverHandles,
            out int cancelId)
        {
            Session session = ThrowIfNotConnected();
            
            ReadRawModifiedDetails details = new ReadRawModifiedDetails();

            // create the delete requests.
            List<HdaUpdateRequest> requests = CreateUpdateRequests(
                session,
                startTime,
                endTime,
                serverHandles);
            
            // queue the transaction.
            int[] errors = CreateTransaction(
                TransationType.DeleteRaw,
                transactionId, 
                requests,
                out cancelId);

            // return the initial results.
            return errors;
        }
Beispiel #39
0
        private void ReadRaw(bool isReadModified)
        {
            ReadRawModifiedDetails details = new ReadRawModifiedDetails();

            details.StartTime        = DateTime.MinValue;
            details.EndTime          = DateTime.MinValue;
            details.IsReadModified   = isReadModified;
            details.NumValuesPerNode = 0;
            details.ReturnBounds     = ReturnBoundsCK.Checked;

            if (StartTimeCK.Checked)
            {
                details.StartTime = StartTimeDP.Value.ToUniversalTime();
            }

            if (EndTimeCK.Checked)
            {
                details.EndTime = EndTimeDP.Value.ToUniversalTime();
            }

            if (MaxReturnValuesCK.Checked)
            {
                details.NumValuesPerNode = (uint)MaxReturnValuesNP.Value;
            }

            HistoryReadValueId nodeToRead = new HistoryReadValueId();

            nodeToRead.NodeId = m_nodeId;

            if (m_result != null)
            {
                nodeToRead.ContinuationPoint = m_result.ContinuationPoint;
            }

            HistoryReadValueIdCollection nodesToRead = new HistoryReadValueIdCollection();

            nodesToRead.Add(nodeToRead);

            HistoryReadResultCollection results         = null;
            DiagnosticInfoCollection    diagnosticInfos = null;

            m_session.HistoryRead(
                null,
                new ExtensionObject(details),
                TimestampsToReturn.Source,
                false,
                nodesToRead,
                out results,
                out diagnosticInfos);

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

            if (StatusCode.IsBad(results[0].StatusCode))
            {
                throw new ServiceResultException(results[0].StatusCode);
            }

            m_result = results[0];

            ShowResults();
        }
Beispiel #40
0
        private void ReadHistory(DateTime StartTime, DateTime EndTime, NodeId node, uint HCount, String DriverName)
        {
            ReadRawModifiedDetails details = new ReadRawModifiedDetails();
            details.StartTime = DateTime.MinValue;
            details.EndTime = DateTime.MinValue;
            details.IsReadModified = false;
            details.NumValuesPerNode = HCount;
            details.ReturnBounds = true;
            details.StartTime = StartTime.ToUniversalTime();
            details.EndTime = EndTime.ToUniversalTime();

            HistoryReadValueId nodeToRead = new HistoryReadValueId();
            nodeToRead.NodeId = node;

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

            HistoryReadResultCollection results = null;
            DiagnosticInfoCollection diagnosticInfos = null;

            m_session.HistoryRead(
                null,
                new ExtensionObject(details),
                TimestampsToReturn.Source,
                false,
                nodesToRead,
                out results,
                out diagnosticInfos);

            for (int i = 0; i < results.Count; i++)
            {

                HistoryData hd_results = ExtensionObject.ToEncodeable(results[i].HistoryData) as HistoryData;

                if (hd_results != null)
                {

                    for (int ii = 0; ii < hd_results.DataValues.Count; ii++)
                    {
                        StatusCode status = hd_results.DataValues[ii].StatusCode;


                        string timestamp = hd_results.DataValues[ii].SourceTimestamp.ToLocalTime().ToString("yyyy-MM-dd HH:mm:ss");
                        string value = Utils.Format("{0}", hd_results.DataValues[ii].WrappedValue);
                        string quality = Utils.Format("{0}", (StatusCode)status.CodeBits);
                        string historyInfo = Utils.Format("{0:X2}", (int)status.AggregateBits);
                        Log("UID:" + S80(node.ToString()) + " \tTime: " + timestamp + "\tValue: " + value); // + ", Q:" + quality + ", histInfo:" + historyInfo);
                        dr = dt.NewRow();
                        dr["UID"] = node.ToString();
                        dr["SourceTime"] = timestamp;
                        dr["Value"] = value;
                        dr["Name"] = DriverName;
                        dt.Rows.Add(dr);
                    }
                }



            }

        }
        /// <summary>
        /// Reads the history of an HDA item.
        /// </summary>
        private ServiceResult HistoryReadItem(
            ServerSystemContext context,
            ComHdaClient client,
            ReadRawModifiedDetails details,
            TimestampsToReturn timestampsToReturn,
            HistoryReadValueId nodeToRead,
            HdaParsedNodeId parsedNodeId,
            HistoryReadResult result)
        { 
            // create the request or load it from a continuation point.
            HdaHistoryReadRawModifiedRequest request = null;

            if (nodeToRead.ContinuationPoint == null)
            {
                request = new HdaHistoryReadRawModifiedRequest(parsedNodeId.RootId, details, nodeToRead);
            }
            else
            {
                request = LoadContinuationPoint(context, nodeToRead.ContinuationPoint) as HdaHistoryReadRawModifiedRequest;

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

            // fetch the data.
            result.StatusCode = client.ReadHistory(request);

            // fill in the results.
            if (request.Results != null)
            {
                HistoryData data = (request.IsReadModified)?new HistoryModifiedData():new HistoryData();

                if (request.IsReadModified)
                {
                    ((HistoryModifiedData)data).ModificationInfos = request.ModificationInfos;
                }

                data.DataValues = request.Results;
                result.HistoryData = new ExtensionObject(data);
            }

            // create a new continuation point.
            if (!request.Completed)
            {
                result.ContinuationPoint = SaveContinuationPoint(context, request);
            }

            return result.StatusCode;
        }
Beispiel #42
0
        /// <summary>
        /// Reads the raw data.
        /// </summary>
        public int[] ReadRaw(
            int transactionId,
            DateTime startTime,
            DateTime endTime,
            uint numValues,
            bool returnBounds,
            int[] serverHandles,
            out int cancelId)
        {
            Session session = ThrowIfNotConnected();
            
            ReadRawModifiedDetails details = new ReadRawModifiedDetails();

            // create the read requests.
            List<HdaReadRequest> requests = CreateReadRequests(
                session,
                startTime,
                endTime,
                numValues,
                returnBounds,
                serverHandles,
                details);

            // queue the transaction.
            int[] errors = CreateTransaction(
                TransationType.Read,
                transactionId, 
                new ExtensionObject(details), 
                requests,
                false,
                out cancelId);

            // return the initial results.
            return errors;
        }
        /// <summary>
        /// Reads raw history data.
        /// </summary>
        protected override void HistoryReadRawModified(
            ServerSystemContext context,
            ReadRawModifiedDetails details,
            TimestampsToReturn timestampsToReturn,
            IList<HistoryReadValueId> nodesToRead,
            IList<HistoryReadResult> results,
            IList<ServiceResult> errors,
            List<NodeHandle> nodesToProcess,
            IDictionary<NodeId, NodeState> cache)
        {
            ComHdaClientManager system = (ComHdaClientManager)this.SystemContext.SystemHandle;
            ComHdaClient client = (ComHdaClient)system.SelectClient((ServerSystemContext)SystemContext, false);

            for (int ii = 0; ii < nodesToProcess.Count; ii++)
            {
                NodeHandle handle = nodesToProcess[ii];
                HistoryReadValueId nodeToRead = nodesToRead[handle.Index];
                HistoryReadResult result = results[handle.Index];

                // check if the node id has been parsed.
                HdaParsedNodeId parsedNodeId = handle.ParsedNodeId as HdaParsedNodeId;

                if (parsedNodeId == null)
                {
                    errors[handle.Index] = StatusCodes.BadNodeIdInvalid;
                    continue;
                }

                // read the history of an item.
                if (parsedNodeId.RootType == HdaModelUtils.HdaItem)
                {
                    errors[handle.Index] = HistoryReadItem(
                        context,
                        client,
                        details,
                        timestampsToReturn,
                        nodeToRead,
                        parsedNodeId,
                        result);

                    continue;
                }

                // read the history of an attribute.
                if (parsedNodeId.RootType == HdaModelUtils.HdaItemAttribute)
                {
                    errors[handle.Index] = HistoryReadAttribute(
                        context,
                        client,
                        details,
                        timestampsToReturn,
                        nodeToRead,
                        parsedNodeId,
                        result);

                    continue;
                }

                // read the annotations of an item.
                if (parsedNodeId.RootType == HdaModelUtils.HdaItemAnnotations)
                {
                    errors[handle.Index] = HistoryReadAnnotations(
                        context,
                        client,
                        details,
                        timestampsToReturn,
                        nodeToRead,
                        parsedNodeId,
                        result);

                    continue;
                }

                errors[handle.Index] = StatusCodes.BadHistoryOperationUnsupported;
            }
        }
Beispiel #44
0
        /// <summary>
        /// Creates the read requests.
        /// </summary>
        private List<HdaReadRequest> CreateReadRequests(
            Session session,
            DateTime startTime,
            DateTime endTime,
            uint numValues,
            bool returnBounds,
            int[] serverHandles,
            ReadRawModifiedDetails details)
        {
            // start time or end time must be specified.
            if (startTime == DateTime.MinValue && endTime == DateTime.MinValue)
            {
                throw ComUtils.CreateComException(ResultIds.E_INVALIDARG);
            }

            // num values must be specified if start or end time is missing.
            if (numValues == 0 && (startTime == DateTime.MinValue || endTime == DateTime.MinValue))
            {
                throw ComUtils.CreateComException(ResultIds.E_INVALIDARG);
            }

            // can't exceed the limits imposed by the server configuration.
            if (m_configuration.MaxReturnValues > 0 && numValues > m_configuration.MaxReturnValues)
            {
                throw ComUtils.CreateComException(ResultIds.E_MAXEXCEEDED);
            }
            
            details.StartTime = startTime;
            details.EndTime = endTime;
            details.IsReadModified = false;
            details.NumValuesPerNode = numValues;
            details.ReturnBounds = returnBounds;

            // build the list of requests.
            List<HdaReadRequest> requests = new List<HdaReadRequest>();

            for (int ii = 0; ii < serverHandles.Length; ii++)
            {
                HdaReadRequest request = new HdaReadRequest();
                requests.Add(request);

                // look up server handle.
                request.Handle = m_itemManager.LookupHandle(serverHandles[ii]);

                if (request.Handle == null)
                {
                    request.Error = ResultIds.E_INVALIDHANDLE;
                    continue;
                }

                // initialize request.
                request.NodeId = request.Handle.NodeId;
                request.ClientHandle = request.Handle.ClientHandle;
            }

            return requests;
        }
 public BoundingValueTestResult()
 {
     Details = new ReadRawModifiedDetails();
 }
Beispiel #46
0
        /// <summary>
        /// Reads the modified data.
        /// </summary>
        public List<HdaReadRequest> ReadModified(
            DateTime startTime, 
            DateTime endTime, 
            uint numValues, 
            int[] serverHandles)
        {
            Session session = ThrowIfNotConnected();

            ReadRawModifiedDetails details = new ReadRawModifiedDetails();

            // create the read requests.
            List<HdaReadRequest> requests = CreateReadRequests(
                session,
                startTime,
                endTime,
                numValues,
                false,
                serverHandles,
                details);

            details.IsReadModified = true;

            for (int ii = 0; ii < requests.Count; ii++)
            {
                requests[ii].ModificationInfos = new List<ModificationInfo>();
            }

            ExtensionObject extension = new ExtensionObject(details);

            // fetch all of the values.
            if (ReadNext(session, extension, requests, false))
            {
                ReadNext(session, extension, requests, true);
            }
            
            return requests;
        }
 /// <summary>
 /// Reads the raw history for the variable value.
 /// </summary>
 protected virtual ServiceResult HistoryReadRaw(
     ISystemContext context, 
     BaseVariableState      source,
     ReadRawModifiedDetails details, 
     TimestampsToReturn     timestampsToReturn, 
     bool                   releaseContinuationPoints, 
     HistoryReadValueId     nodeToRead, 
     HistoryReadResult      result)
 {
     return StatusCodes.BadHistoryOperationUnsupported;
 }
Beispiel #48
0
        /// <summary>
        /// Reads the modified data.
        /// </summary>
        public int[] ReadModified(
            int transactionId,
            DateTime startTime,
            DateTime endTime,
            uint numValues,
            int[] serverHandles,
            out int cancelId)
        {
            Session session = ThrowIfNotConnected();
            
            ReadRawModifiedDetails details = new ReadRawModifiedDetails();

            // create the read requests.
            List<HdaReadRequest> requests = CreateReadRequests(
                session,
                startTime,
                endTime,
                numValues,
                false,
                serverHandles,
                details);

            details.IsReadModified = true;

            for (int ii = 0; ii < requests.Count; ii++)
            {
                requests[ii].ModificationInfos = new List<ModificationInfo>();
            }

            // queue the transaction.
            int[] errors = CreateTransaction(
                TransationType.ReadModified,
                transactionId, 
                new ExtensionObject(details),
                requests,
                false,
                out cancelId);

            // return the initial results.
            return errors;
        }
Beispiel #49
0
        private void ReleaseContinuationPoints()
        {
            ReadRawModifiedDetails details = new ReadRawModifiedDetails();

            HistoryReadValueId nodeToRead = new HistoryReadValueId();
            nodeToRead.NodeId = m_nodeId;

            if (m_result != null)
            {
                nodeToRead.ContinuationPoint = m_result.ContinuationPoint;
            }

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

            HistoryReadResultCollection results = null;
            DiagnosticInfoCollection diagnosticInfos = null;

            m_session.HistoryRead(
                null,
                new ExtensionObject(details),
                TimestampsToReturn.Source,
                true,
                nodesToRead,
                out results,
                out diagnosticInfos);

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

            m_result = null;

            ShowResults();
        }
Beispiel #50
0
        private DateTime ReadFirstDate()
        {
            ReadRawModifiedDetails details = new ReadRawModifiedDetails();
            details.StartTime = new DateTime(1970, 1, 1);
            details.EndTime = DateTime.UtcNow.AddDays(1);
            details.IsReadModified = false;
            details.NumValuesPerNode = 1;
            details.ReturnBounds = false;

            HistoryReadValueId nodeToRead = new HistoryReadValueId();
            nodeToRead.NodeId = m_nodeId;

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

            HistoryReadResultCollection results = null;
            DiagnosticInfoCollection diagnosticInfos = null;

            m_session.HistoryRead(
                null,
                new ExtensionObject(details),
                TimestampsToReturn.Source,
                false,
                nodesToRead,
                out results,
                out diagnosticInfos);

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

            if (StatusCode.IsBad(results[0].StatusCode))
            {
                return DateTime.MinValue;
            }

            HistoryData data = ExtensionObject.ToEncodeable(results[0].HistoryData) as HistoryData;

            if (results == null)
            {
                return DateTime.MinValue;
            }

            DateTime startTime = data.DataValues[0].SourceTimestamp;

            if (results[0].ContinuationPoint != null && results[0].ContinuationPoint.Length > 0)
            {
                nodeToRead.ContinuationPoint = results[0].ContinuationPoint;

                m_session.HistoryRead(
                    null,
                    new ExtensionObject(details),
                    TimestampsToReturn.Source,
                    true,
                    nodesToRead,
                    out results,
                    out diagnosticInfos);

                Session.ValidateResponse(results, nodesToRead);
                Session.ValidateDiagnosticInfos(diagnosticInfos, nodesToRead);
            }

            return startTime;
        }
Beispiel #51
0
        /// <summary>
        /// Reads the raw data.
        /// </summary>
        /// <param name="startTime">The start time.</param>
        /// <param name="endTime">The end time.</param>
        /// <param name="numValues">The num values.</param>
        /// <param name="returnBounds">if set to <c>true</c> the bounds should be returned.</param>
        /// <param name="serverHandles">The server handles.</param>
        /// <returns>The results.</returns>
        public List<HdaReadRequest> ReadRaw(
            DateTime startTime, 
            DateTime endTime, 
            uint numValues, 
            bool returnBounds, 
            int[] serverHandles)
        {
            Session session = ThrowIfNotConnected();

            ReadRawModifiedDetails details = new ReadRawModifiedDetails();

            // create the read requests.
            List<HdaReadRequest> requests = CreateReadRequests(
                session,
                startTime,
                endTime,
                numValues,
                returnBounds,
                serverHandles,
                details);

            ExtensionObject extension = new ExtensionObject(details);

            // fetch all of the values.
            if (ReadNext(session, extension, requests, false))
            {
                ReadNext(session, extension, requests, true);
            }
            
            return requests;
        }
        /// <summary>
        /// Reads the initial value for a monitored item.
        /// </summary>
        /// <param name="context">The context.</param>
        /// <param name="handle">The item handle.</param>
        /// <param name="monitoredItem">The monitored item.</param>
        protected override void ReadInitialValue(
            ServerSystemContext context,
            NodeHandle handle,
            MonitoredItem monitoredItem)
        {
            ArchiveItemState item = handle.Node as ArchiveItemState;

            if (item == null || monitoredItem.AttributeId != Attributes.Value)
            {
                base.ReadInitialValue(context, handle, monitoredItem);
                return;
            }

            AggregateFilter filter = monitoredItem.Filter as AggregateFilter;

            if (filter == null || filter.StartTime >= DateTime.UtcNow.AddMilliseconds(-filter.ProcessingInterval))
            {
                base.ReadInitialValue(context, handle, monitoredItem);
                return;
            }

            ReadRawModifiedDetails details = new ReadRawModifiedDetails();

            details.StartTime = filter.StartTime;
            details.EndTime = DateTime.UtcNow;
            details.ReturnBounds = true;
            details.IsReadModified = false;
            details.NumValuesPerNode = 0;

            HistoryReadValueId nodeToRead = new HistoryReadValueId();
            nodeToRead.NodeId = handle.NodeId;
            nodeToRead.ParsedIndexRange = NumericRange.Empty;

            try
            {
                HistoryReadRequest request = CreateHistoryReadRequest(
                    context,
                    details,
                    handle,
                    nodeToRead);

                while (request.Values.Count > 0)
                {
                    if (request.Values.Count == 0)
                    {
                        break;
                    }

                    DataValue value = request.Values.First.Value;
                    request.Values.RemoveFirst();
                    monitoredItem.QueueValue(value, null);
                }
            }
            catch (Exception e)
            {
                ServiceResult error = ServiceResult.Create(e, StatusCodes.BadUnexpectedError, "Unexpected error fetching initial values.");
                monitoredItem.QueueValue(null, error);
            }
        }