Ejemplo n.º 1
1
        public void Run()
        {
            PIServers piServers = new PIServers();
            PIServer  piServer  = piServers["<AFSERVER>"];

            // Use PICommonPointAttributes so we don't have to remember the strings for point attributes.

            string floatpoint = "sample_floatpoint";
            Dictionary <string, object> floatpoint_attributes = new Dictionary <string, object>();

            floatpoint_attributes.Add(PICommonPointAttributes.PointClassName, "classic");
            floatpoint_attributes.Add(PICommonPointAttributes.Descriptor, "Hello floating world");
            floatpoint_attributes.Add(PICommonPointAttributes.PointType, "float32");

            string digitalpoint = "sample_digitalpoint";
            Dictionary <string, object> digitalpoint_attributes = new Dictionary <string, object>();

            digitalpoint_attributes.Add(PICommonPointAttributes.PointClassName, "classic");
            digitalpoint_attributes.Add(PICommonPointAttributes.Descriptor, "Hello digital world");
            digitalpoint_attributes.Add(PICommonPointAttributes.PointType, "digital");
            digitalpoint_attributes.Add(PICommonPointAttributes.DigitalSetName, "modes");

            Dictionary <string, IDictionary <string, object> > pointDict = new Dictionary <string, IDictionary <string, object> >();

            pointDict.Add(floatpoint, floatpoint_attributes);
            pointDict.Add(digitalpoint, digitalpoint_attributes);

            AFListResults <string, PIPoint> results = piServer.CreatePIPoints(pointDict);
        }
Ejemplo n.º 2
0
        private static void CheckPipeEvents(PIDataPipe pipe, ref int counter)
        {
            if (counter++ % 15 == 0)
            {
                Console.WriteLine("{0}Press ESC to stop{0}", Environment.NewLine);
            }
            Console.WriteLine("Check data pipe events at {0}", DateTime.Now);
            AFListResults <PIPoint, AFDataPipeEvent> pipeContents = pipe.GetUpdateEvents(1000);

            if (pipeContents.Count == 0)
            {
                Console.WriteLine("   No new values");
            }
            foreach (AFDataPipeEvent pipeEvent in pipeContents)
            {
                //user-friendly string: [point] [timestamp]  [value]
                string s = string.Format("    {0} \t{1} \t{2}"
                                         , pipeEvent.Value.PIPoint.Name
                                         , pipeEvent.Value.Timestamp
                                         , pipeEvent.Value.Value);
                Console.WriteLine(s);
            }
            // You are to monitor every second.
            Thread.Sleep(TimeSpan.FromSeconds(1));
        }
Ejemplo n.º 3
0
        private void ReadEvents()
        {
            if ((object)m_dataPipe == null)
            {
                return;
            }

            #if DEBUG
            OnStatusMessage(MessageLevel.Debug, "DEBUG: Data pipe called for next 100 GetUpdateEvents...");
            #endif

            AFListResults <PIPoint, AFDataPipeEvent> updateEvents = m_dataPipe.GetUpdateEvents(100);

            #if DEBUG
            OnStatusMessage(MessageLevel.Debug, $"DEBUG: Update event count = {updateEvents.Count}...");
            #endif

            foreach (AFDataPipeEvent item in updateEvents.Results)
            {
                #if DEBUG
                OnStatusMessage(MessageLevel.Debug, "DEBUG: Found update event for action...");
                #endif

                if (item.Action != AFDataPipeAction.Delete)
                {
                    m_dataUpdateObserver_DataUpdated(this, new EventArgs <AFValue>(item.Value));
                }
            }
        }
        public void Start()
        {
            if (_disposed)
            {
                throw new ObjectDisposedException("AssetRankProvider was disposed.");
            }

            // Gets all attributes from the AttributeTemplate
            AFAttributeList attrList = GetAttributes();

            Console.WriteLine("{0} | Signing up for updates for {1} attributes", DateTime.Now, attrList.Count);
            DataPipe.Subscribe(this);

            // Throw exception on errors
            AFListResults <AFAttribute, AFDataPipeEvent> initEvents = DataPipe.AddSignupsWithInitEvents(attrList);

            if (initEvents.HasErrors)
            {
                throw new Exception("There was an error during signup.", new AggregateException(initEvents.Errors.Values));
            }

            // Initialize the dictionary cache
            foreach (AFDataPipeEvent dpEvent in initEvents)
            {
                OnNext(dpEvent);
            }

            Console.WriteLine("{0} | Signed up for updates for {1} attributes\n", DateTime.Now, attrList.Count);

            _mainTask = Task.Run(() =>
            {
                bool hasMoreEvents = false;

                while (true)
                {
                    if (_ct.IsCancellationRequested)
                    {
                        // The main task in AssetRankProvider is cancelled.
                        _ct.ThrowIfCancellationRequested();
                        // NOTE!!! A "OperationCanceledException was unhandled
                        // by user code" error will be raised here if "Just My Code"
                        // is enabled on your computer. On Express editions JMC is
                        // enabled and cannot be disabled. The exception is benign.
                        // Just press F5 to continue executing your code.
                    }

                    AFErrors <AFAttribute> results = DataPipe.GetObserverEvents(out hasMoreEvents);

                    if (results != null)
                    {
                        Console.WriteLine("Errors in GetObserverEvents: {0}", results.ToString());
                    }

                    if (!hasMoreEvents)
                    {
                        Thread.Sleep(_threadSleepTimeInMilliseconds);
                    }
                }
            }, _ct);
        }
        public void TimeSeriesUpdatesTest()
        {
            // Construct a unique PI Point name
            string pointNameFormat = $"TimeSeriesUpdateTestPoint{AFTime.Now}";

            bool signupCompleted = false;

            using (var myDataPipe = new PIDataPipe(AFDataPipeType.TimeSeries))
            {
                Output.WriteLine($"Create a PI Point on [{Settings.PIDataArchive}] with compression off.");
                var points = Fixture.CreatePIPoints(pointNameFormat, 1, true);

                try
                {
                    Output.WriteLine($"Sign up for time-series updates on PI Point [{pointNameFormat}].");
                    myDataPipe.AddSignups(points.ToList());
                    signupCompleted = true;

                    var startTime  = AFTime.Now.ToPIPrecision() + TimeSpan.FromDays(-1);
                    int eventCount = 1000;
                    int totalCount = 0;

                    // Send events to each PI Point, the event's value is calculated from the timestamp
                    Output.WriteLine($"Write {eventCount} events to the new PI Point.");
                    Fixture.SendTimeBasedPIEvents(startTime, eventCount, points.ToList());

                    // Checks if Update Events are retrieved a few times
                    Output.WriteLine($"Get the update events.");

                    var eventsRetrieved = new AFListResults <PIPoint, AFDataPipeEvent>();
                    AssertEventually.True(() =>
                    {
                        eventsRetrieved = myDataPipe.GetUpdateEvents(eventCount);
                        totalCount     += eventsRetrieved.Count();
                        return(totalCount == eventCount);
                    },
                                          TimeSpan.FromSeconds(60),
                                          TimeSpan.FromSeconds(1),
                                          $"Failed to retrieve {eventCount} update events, retrieved {totalCount} instead.");
                    Output.WriteLine("Retrieved update events successfully.");
                }
                finally
                {
                    if (signupCompleted)
                    {
                        myDataPipe.RemoveSignups(points.ToList());
                    }

                    Output.WriteLine("Delete all newly created PI Points.");
                    Fixture.DeletePIPoints(pointNameFormat, Output);
                }
            }
        }
        public void CreateAllPIPoints(List <string> newPIPointNames)
        {
            if (newPIPointNames.Count > 0)
            {
                List <string> filteredNewPIPointNames = newPIPointNames.Where(p => allPIPointNames.Contains(p) == false).ToList();

                if (filteredNewPIPointNames.Count > 0)
                {
                    IDictionary <string, object> attributes = new Dictionary <string, object>();
                    attributes.Add("pointtype", "int32");
                    AFListResults <string, PIPoint> results = piServer.CreatePIPoints(filteredNewPIPointNames.AsEnumerable(), attributes);
                }
            }
        }
Ejemplo n.º 7
0
        /// <summary>
        /// Creates a number of PI Points with the default attribute values unless specified.
        /// </summary>
        /// <param name="pointNameFormat">A PI Point naming string with the first group of consecutive '#' serving as the placeholder for digits.</param>
        /// <param name="pointCount">The number of PI Points to be created.</param>
        /// <param name="pointAttributes">List of PI Point attributes to be used when creating Points. If null, then default attribute values will be used.</param>
        /// <returns>Returns the list of created PI Points.</returns>
        public IEnumerable <PIPoint> CreatePIPoints(string pointNameFormat, int pointCount, Dictionary <string, object> pointAttributes)
        {
            // The first group of consecutive # will serve as the placeholder for digits.
            // If the maximum PI Point count is less than the specified Point count, an exception will be thrown.
            string hashSymbol    = Regex.Match(pointNameFormat, @"#+").Groups[0].Value;
            int    maxpointCount = (int)Math.Pow(10, hashSymbol.Length);

            if (pointCount > maxpointCount)
            {
                throw new InvalidOperationException($"The pointNameFormat of [{pointNameFormat}] does not support {pointCount} points.");
            }

            var pointNames = new List <string>();

            if (string.IsNullOrWhiteSpace(hashSymbol))
            {
                pointNames.Add(pointNameFormat);
            }
            else
            {
                string digitFormat = $"D{hashSymbol.Length}";
                for (int i = 0; i < pointCount; i++)
                {
                    pointNames.Add(pointNameFormat.Replace(hashSymbol, i.ToString(digitFormat, CultureInfo.InvariantCulture)));
                }
            }

            // Process PI Points in pages
            var points = new AFListResults <string, PIPoint>();
            int j      = 0;

            foreach (IList <string> pointGroup in pointNames.GroupBy(name => j++ / PointPageSize).Select(g => g.ToList()))
            {
                AFListResults <string, PIPoint> results = PIServer.CreatePIPoints(pointGroup, pointAttributes);
                if (results.Errors.Count > 0)
                {
                    throw results.Errors.First().Value;
                }
                points.AddResults(results);
            }

            return(points);
        }
Ejemplo n.º 8
0
        private void ReadEvents()
        {
            if ((object)m_dataPipe == null)
            {
                return;
            }

            OnStatusMessage("DEBUG: Data pipe called for next 100 GetUpdateEvents...");

            AFListResults <PIPoint, AFDataPipeEvent> updateEvents = m_dataPipe.GetUpdateEvents(100);

            OnStatusMessage("DEBUG: Update event count = {0}...", updateEvents.Count);

            foreach (AFDataPipeEvent item in updateEvents.Results)
            {
                OnStatusMessage("DEBUG: Found update event for action...", item.Action);

                if (item.Action != AFDataPipeAction.Delete)
                {
                    m_dataUpdateObserver_DataUpdated(this, new EventArgs <AFValue>(item.Value));
                }
            }
        }
Ejemplo n.º 9
0
        public void Run()
        {
            PIServers piServers = new PIServers();
            PIServer  piServer  = piServers["<PISERVER>"];

            IList <PIPoint> points = PIPoint.FindPIPoints(piServer, new[] { "sinusoid", "sinusoidu", "cdt158", "cdm158" });

            // Create an PIPointList object in order to make the bulk call later.
            PIPointList pointList = new PIPointList(points);

            if (pointList == null)
            {
                return;
            }

            // MAKE A BULK CALL TO THE PI DATA ARCHIVE
            AFListResults <PIPoint, AFValue> values = pointList.CurrentValue(); // Requires AF SDK 2.7+

            foreach (AFValue val in values)
            {
                Console.WriteLine("Point: {0}, Timestamp: {1}, Value: {2}", val.PIPoint, val.Timestamp, val.Value.ToString());
            }
        }
Ejemplo n.º 10
0
        public override void Run()
        {
            try
            {
                PiConnectionMgr piConnectionMgr = new PiConnectionMgr(Server);
                piConnectionMgr.Connect();

                PIServer pi = piConnectionMgr.GetPiServer();

                PIPointList pointList = new PIPointList(PIPoint.FindPIPoints(pi, TagMask));

                AFListResults <PIPoint, AFValue> values = pointList.CurrentValue();

                foreach (AFValue val in values)
                {
                    Logger.InfoFormat("The current value for PI Point {0} is : {1} - {2}", val.PIPoint, val.Timestamp, val.Value);
                }
            }
            catch (Exception ex)
            {
                Logger.Error(ex);
            }
        }
Ejemplo n.º 11
0
        private void getSnapshot(object obj)
        {
            List <PIPoint> p = obj as List <PIPoint>;

            SetDataGridCallback _dataGridCallback = new SetDataGridCallback(SetDataTable);

            PIDataPipe pipe = new PIDataPipe(AFDataPipeType.Archive);

            pipe.AddSignups(p);

            //_dt.Rows.Clear();
            _dt = new DataTable();

            _dt.Columns.Add("Tag", typeof(string));
            _dt.Columns.Add("Timestamp", typeof(DateTime));
            _dt.Columns.Add("Value", typeof(object));
            _dt.Columns.Add("UOM", typeof(string));
            _dt.Columns.Add("Annotation", typeof(string));
            _dt.Columns.Add("CheckBox", typeof(bool));
            _dt.Columns.Add("Message", typeof(string));

            PIPointList piPointList = new PIPointList();

            piPointList.AddRange(p);

            AFValues afValues = new AFValues();

            foreach (var piPoint in piPointList)
            {
                afValues.Add(piPoint.CurrentValue());
            }


            foreach (var afValue in afValues)
            {
                _dt.Rows.Add(afValue.PIPoint.Name, (DateTime)afValue.Timestamp.LocalTime, afValue.Value, afValue.PIPoint.GetAttribute(PICommonPointAttributes.EngineeringUnits), afValue.GetAnnotation(), false, string.Empty);
            }


            this.Invoke(_dataGridCallback, _dt);


            while (chkShowSnapshot.Checked == true)
            {
                AFListResults <PIPoint, AFDataPipeEvent> pipeConstants = pipe.GetUpdateEvents(5000);

                foreach (AFDataPipeEvent pipeEvent in pipeConstants)
                {
                    foreach (DataRow row in _dt.Rows)
                    {
                        if (row["Tag"] == pipeEvent.Value.PIPoint.Name)
                        {
                            row["Timestamp"]  = pipeEvent.Value.Timestamp.LocalTime;
                            row["Value"]      = pipeEvent.Value.Value;
                            row["UOM"]        = pipeEvent.Value.PIPoint.GetAttribute(PICommonPointAttributes.EngineeringUnits);
                            row["Annotation"] = pipeEvent.Value.GetAnnotation();
                        }
                    }
                }

                if (this.dataGrid.InvokeRequired)
                {
                    this.Invoke(_dataGridCallback, _dt);
                }
                else
                {
                    dataGrid.DataSource = _dt;
                    dataGrid.Refresh();
                }
            }
            ;
            pipe.Close();
            pipe.Dispose();
        }
Ejemplo n.º 12
0
        private void SubscribeToPointUpdates(MeasurementKey[] keys)
        {
            OnStatusMessage(MessageLevel.Info, $"Subscribing to updates for {keys.Length} measurements...");

            var query = from row in DataSource.Tables["ActiveMeasurements"].AsEnumerable()
                        from key in keys
                        where row["ID"].ToString() == key.ToString()
                        select new
            {
                Key          = key,
                AlternateTag = row["AlternateTag"].ToString(),
                PointTag     = row["PointTag"].ToString()
            };

            List <PIPoint> dataPoints = new List <PIPoint>();

            foreach (var row in query)
            {
                string tagName = row.PointTag;

                if (!string.IsNullOrWhiteSpace(row.AlternateTag))
                {
                    tagName = row.AlternateTag;
                }

                OnStatusMessage(MessageLevel.Debug, $"DEBUG: Looking up point tag '{tagName}'...");

                PIPoint point = GetPIPoint(m_connection.Server, tagName);

                if ((object)point != null)
                {
                    OnStatusMessage(MessageLevel.Debug, $"DEBUG: Found point tag '{tagName}'...");
                    dataPoints.Add(point);
                    m_tagKeyMap[point.ID] = row.Key;
                }
                else
                {
                    OnStatusMessage(MessageLevel.Debug, $"DEBUG: Failed to find point tag '{tagName}'...");
                }
            }

            // Remove sign-ups for any existing point list
            if ((object)m_dataPoints != null)
            {
                m_dataPipe.RemoveSignups(m_dataPoints);
            }

            // Sign up for updates on selected points
            AFListResults <PIPoint, AFDataPipeEvent> initialEvents = m_dataPipe.AddSignupsWithInitEvents(dataPoints);

            OnStatusMessage(MessageLevel.Debug, $"DEBUG: Initial event count = {initialEvents.Results.Count}...");

            foreach (AFDataPipeEvent item in initialEvents.Results)
            {
                OnStatusMessage(MessageLevel.Debug, "DEBUG: Found initial event for action...");

                if (item.Action != AFDataPipeAction.Delete)
                {
                    m_dataUpdateObserver_DataUpdated(this, new EventArgs <AFValue>(item.Value));
                }
            }

            m_dataPoints = dataPoints;

            m_eventTimer.Enabled = true;
        }
Ejemplo n.º 13
0
        internal void Execute(string command, PIPointList pointsList, AFTime st, AFTime et,
                              AFTimeSpan summaryDuration, string[] times, string addlparam1, PIServer myServer)
        {
            try
            {
                Console.WriteLine();
                switch (command)
                {
                case "snap":
                {
                    var sb = new StringBuilder();
                    sb.AppendLine($"Point Name(Point Id), Timestamp, Current Value");
                    sb.AppendLine(new string('-', 45));
                    AFListResults <PIPoint, AFValue> results = pointsList.EndOfStream();
                    if (results.HasErrors)
                    {
                        foreach (var e in results.Errors)
                        {
                            sb.AppendLine($"{e.Key}: {e.Value}");
                        }
                    }
                    foreach (var v in results.Results)
                    {
                        if (!results.Errors.ContainsKey(v.PIPoint))
                        {
                            sb.AppendLine($"{string.Concat($"{v.PIPoint.Name} ({v.PIPoint.ID})"),-15}," +
                                          $" {v.Timestamp}, {v.Value}");
                        }
                    }
                    sb.AppendLine();
                    Console.Write(sb.ToString());
                    break;
                }

                case "arclist":
                {
                    AFTimeRange timeRange = new AFTimeRange(st, et);
                    if (!Int32.TryParse(addlparam1, out int maxcount))
                    {
                        maxcount = 0;
                    }

                    // Holds the results keyed on the associated point
                    var resultsMap   = new Dictionary <PIPoint, AFValues>();
                    var pagingConfig = new PIPagingConfiguration(PIPageType.TagCount, GlobalConfig.PageSize);
                    IEnumerable <AFValues> listResults = pointsList.RecordedValues(timeRange: timeRange,
                                                                                   boundaryType: AFBoundaryType.Inside,
                                                                                   filterExpression: null,
                                                                                   includeFilteredValues: false,
                                                                                   pagingConfig: pagingConfig,
                                                                                   maxCount: maxcount
                                                                                   );
                    foreach (var pointResults in listResults)
                    {
                        resultsMap[pointResults.PIPoint] = pointResults;
                    }
                    foreach (var pointValues in resultsMap)
                    {
                        var sb = new StringBuilder();
                        sb.AppendLine($"Point: {pointValues.Key} Archive Values " +
                                      $"Count: {pointValues.Value.Count}");
                        sb.AppendLine(new string('-', 45));
                        pointValues.Value.ForEach(v => sb.AppendLine($"{v.Timestamp}, {v.Value}"));
                        sb.AppendLine();
                        Console.Write(sb.ToString());
                    }
                    break;
                }

                case "plot":
                {
                    AFTimeRange timeRange = new AFTimeRange(st, et);
                    if (!Int32.TryParse(addlparam1, out int intervals))
                    {
                        intervals = 640;         //horizontal pixels in the trend
                    }
                    var resultsMap   = new Dictionary <PIPoint, AFValues>();
                    var pagingConfig = new PIPagingConfiguration(PIPageType.TagCount, GlobalConfig.PageSize);
                    IEnumerable <AFValues> listResults = pointsList.PlotValues(timeRange: timeRange,
                                                                               intervals: intervals,
                                                                               pagingConfig: pagingConfig
                                                                               );
                    foreach (var pointResults in listResults)
                    {
                        resultsMap[pointResults.PIPoint] = pointResults;
                    }
                    foreach (var pointValues in resultsMap)
                    {
                        var sb = new StringBuilder();
                        sb.AppendLine($"Point: {pointValues.Key} Plot Values Interval: {intervals}" +
                                      $" Count: {pointValues.Value.Count}");
                        sb.AppendLine(new string('-', 45));
                        pointValues.Value.ForEach(v => sb.AppendLine($"{v.Timestamp}, {v.Value}"));
                        sb.AppendLine();
                        Console.Write(sb.ToString());
                    }
                    break;
                }

                case "interp":
                {
                    AFTimeRange timeRange    = new AFTimeRange(st, et);
                    var         resultsMap   = new Dictionary <PIPoint, AFValues>();
                    var         pagingConfig = new PIPagingConfiguration(PIPageType.TagCount, GlobalConfig.PageSize);

                    if (addlparam1.StartsWith("c="))
                    {
                        if (!Int32.TryParse(addlparam1.Substring(2), out int count))
                        {
                            count = 10;         //default count
                        }
                        IEnumerable <AFValues> listResults = pointsList.InterpolatedValuesByCount(timeRange: timeRange,
                                                                                                  numberOfValues: count,
                                                                                                  filterExpression: null,
                                                                                                  includeFilteredValues: false,
                                                                                                  pagingConfig: pagingConfig
                                                                                                  );
                        foreach (var pointResults in listResults)
                        {
                            resultsMap[pointResults.PIPoint] = pointResults;
                        }
                        foreach (var pointValues in resultsMap)
                        {
                            var sb = new StringBuilder();
                            sb.AppendLine($"Point: {pointValues.Key} Interpolated Values " +
                                          $"Count: {pointValues.Value.Count}");
                            sb.AppendLine(new string('-', 45));
                            pointValues.Value.ForEach(v => sb.AppendLine($"{v.Timestamp}, {v.Value}"));
                            sb.AppendLine();
                            Console.Write(sb.ToString());
                        }
                    }
                    else
                    {
                        if (!AFTimeSpan.TryParse(addlparam1, out AFTimeSpan interval) || interval == new AFTimeSpan(0))
                        {
                            interval = summaryDuration;
                        }

                        IEnumerable <AFValues> listResults = pointsList.InterpolatedValues(timeRange: timeRange,
                                                                                           interval: interval,
                                                                                           filterExpression: null,
                                                                                           includeFilteredValues: false,
                                                                                           pagingConfig: pagingConfig
                                                                                           );
                        foreach (var pointResults in listResults)
                        {
                            resultsMap[pointResults.PIPoint] = pointResults;
                        }
                        foreach (var pointValues in resultsMap)
                        {
                            var sb = new StringBuilder();
                            sb.AppendLine($"Point: {pointValues.Key} Interpolated Values " +
                                          $"Interval: {interval.ToString()}");
                            sb.AppendLine(new string('-', 45));
                            pointValues.Value.ForEach(v => sb.AppendLine($"{v.Timestamp}, {v.Value}"));
                            sb.AppendLine();
                            Console.Write(sb.ToString());
                        }
                    }
                    break;
                }

                case "summaries":
                {
                    var resultsMap   = new Dictionary <PIPoint, AFValues>();
                    var pagingConfig = new PIPagingConfiguration(PIPageType.TagCount, GlobalConfig.PageSize);
                    if (st > et)         //summaries cannot handle reversed times
                    {
                        var temp = st;
                        st = et;
                        et = temp;
                    }
                    AFTimeRange        timeRange           = new AFTimeRange(st, et);
                    var                intervalDefinitions = new AFTimeIntervalDefinition(timeRange, 1);
                    AFCalculationBasis calculationBasis    = AFCalculationBasis.EventWeighted;
                    if (addlparam1 == "t")
                    {
                        calculationBasis = AFCalculationBasis.TimeWeighted;
                    }

                    foreach (var pt in pointsList)
                    {
                        var summaryType = AFSummaryTypes.All;
                        if (pt.PointType == PIPointType.Digital ||
                            pt.PointType == PIPointType.Timestamp ||
                            pt.PointType == PIPointType.Blob ||
                            pt.PointType == PIPointType.String ||
                            pt.PointType == PIPointType.Null)
                        {
                            summaryType = AFSummaryTypes.AllForNonNumeric;
                        }
                        IDictionary <AFSummaryTypes, AFValues> summaries = pt.Summaries(new List <AFTimeIntervalDefinition>()
                            {
                                intervalDefinitions
                            },
                                                                                        reverseTime: false,
                                                                                        summaryType: summaryType,
                                                                                        calcBasis: calculationBasis,
                                                                                        timeType: AFTimestampCalculation.Auto
                                                                                        );
                        var sb = new StringBuilder();
                        sb.AppendLine($"Point: {pt.Name} {calculationBasis} Summary");
                        sb.AppendLine(new string('-', 45));
                        foreach (var s in summaries)
                        {
                            AFValues vals = s.Value;
                            foreach (var v in vals)
                            {
                                if (v.Value.GetType() != typeof(PIException))
                                {
                                    if (string.Compare(s.Key.ToString(), "Minimum", true) == 0 ||
                                        string.Compare(s.Key.ToString(), "Maximum", true) == 0)
                                    {
                                        sb.AppendLine($"{s.Key,-16}: {v.Value,-20} {v.Timestamp}");
                                    }
                                    else
                                    {
                                        sb.AppendLine($"{s.Key,-16}: {v.Value}");
                                    }
                                }
                                else
                                {
                                    sb.AppendLine($"{s.Key,-16}: {v}");
                                }
                            }
                        }
                        sb.AppendLine();
                        Console.Write(sb.ToString());
                    }

                    /*
                     * Non numeric tags in pointsList requires splitting of queries so the above is preferred.
                     * The below implementation works when there are no non-numeric types or one particular summary needs to be run
                     */
                    //var listResults = pointsList.Summaries(new List<AFTimeIntervalDefinition>() {
                    //                                                               intervalDefinitions },
                    //                                                               reverseTime: false,
                    //                                                               summaryTypes: AFSummaryTypes.All,
                    //                                                               calculationBasis: calculationBasis,
                    //                                                               timeType: AFTimestampCalculation.Auto,
                    //                                                               pagingConfig: pagingConfig
                    //                                                               );
                    //foreach (IDictionary<AFSummaryTypes, AFValues> summaries in listResults)
                    //{
                    //     foreach (IDictionary<AFSummaryTypes, AFValues> pointResults in listResults)
                    //    {
                    //            AFValues pointValues = pointResults[AFSummaryTypes.Average];
                    //            PIPoint point = pointValues.PIPoint;
                    //           //Map the results back to the point
                    //           resultsMap[point] = pointValues;
                    //     }
                    //}
                    break;
                }

                case "update":
                case "annotate":
                {
                    string         addlparam2   = string.Empty;
                    AFUpdateOption updateOption = AFUpdateOption.Replace;
                    AFBufferOption bufOption    = AFBufferOption.BufferIfPossible;
                    AFValue        val;
                    if (times.Length > 0)
                    {
                        addlparam1 = times[0];
                        if (times.Length > 1)
                        {
                            addlparam2 = times[1];
                        }
                    }
                    switch (addlparam1)
                    {
                    case "i":
                        updateOption = AFUpdateOption.Insert;
                        break;

                    case "nr":
                        updateOption = AFUpdateOption.NoReplace;
                        break;

                    case "ro":
                        updateOption = AFUpdateOption.ReplaceOnly;
                        break;

                    case "inc":
                        updateOption = AFUpdateOption.InsertNoCompression;
                        break;

                    case "rm":
                        updateOption = AFUpdateOption.Remove;
                        break;
                    }
                    switch (addlparam2)
                    {
                    case "dnb":
                        bufOption = AFBufferOption.DoNotBuffer;
                        break;

                    case "buf":
                        bufOption = AFBufferOption.Buffer;
                        break;
                    }
                    foreach (var pt in pointsList)
                    {
                        Console.WriteLine($"Point: {pt.Name} {command} ({updateOption} {bufOption})");
                        Console.WriteLine(new string('-', 45));
                        Console.Write("Enter timestamp: ");
                        var time = Console.ReadLine();

                        if (!AFTime.TryParse(time, out AFTime ts))
                        {
                            ParseArgs.PrintHelp("Invalid Timestamp");
                            break;
                        }
                        if (command == "update" ||
                            !(pt.RecordedValuesAtTimes(new List <AFTime>()
                            {
                                ts
                            }, AFRetrievalMode.Exact)[0].IsGood))
                        {
                            Console.Write("Enter new value: ");
                            var data = Console.ReadLine();
                            if (!Double.TryParse(data, out var value))
                            {
                                ParseArgs.PrintHelp("Invalid data");
                                break;
                            }
                            val = new AFValue(value, ts);
                        }
                        else
                        {
                            val = pt.RecordedValuesAtTimes(new List <AFTime>()
                                {
                                    ts
                                }, AFRetrievalMode.Exact)[0];
                        }
                        if (command == "annotate")
                        {
                            Console.Write("Enter annotation: ");
                            var ann = Console.ReadLine();
                            pt.SetAnnotation(val, ann);
                        }
                        pt.UpdateValue(value: val, option: updateOption, bufferOption: bufOption);
                        Console.WriteLine($"Successfully {command}d");
                    }
                    Console.WriteLine();
                    break;
                }

                case "delete":
                {
                    AFTimeRange timeRange = new AFTimeRange(st, et);

                    if (myServer.Supports(PIServerFeature.DeleteRange))
                    {
                        foreach (var pt in pointsList)
                        {
                            int delcount            = 0;
                            var sb                  = new StringBuilder();
                            var intervalDefinitions = new AFTimeIntervalDefinition(timeRange, 1);
                            //getting the count of events - optional
                            IDictionary <AFSummaryTypes, AFValues> summaries = pt.Summaries(new List <AFTimeIntervalDefinition>()
                                {
                                    intervalDefinitions
                                },
                                                                                            reverseTime: false,
                                                                                            summaryType: AFSummaryTypes.Count,
                                                                                            calcBasis: AFCalculationBasis.EventWeighted,
                                                                                            timeType: AFTimestampCalculation.Auto
                                                                                            );
                            foreach (var s in summaries)
                            {
                                AFValues vals = s.Value;
                                vals = s.Value;
                                foreach (var v in vals)
                                {
                                    if (v.Value.GetType() != typeof(PIException))
                                    {
                                        delcount = v.ValueAsInt32();         //count
                                    }
                                }
                            }
                            if (delcount > 0)
                            {
                                var errs = pt.ReplaceValues(timeRange, new List <AFValue>()
                                    {
                                    });
                                if (errs != null)
                                {
                                    foreach (var e in errs.Errors)
                                    {
                                        sb.AppendLine($"{e.Key}: {e.Value}");
                                        delcount--;
                                    }
                                }
                            }
                            sb.AppendLine($"Point: {pt.Name} Deleted {delcount} events");
                            sb.AppendLine(new string('-', 45));
                            sb.AppendLine();
                            Console.Write(sb.ToString());
                        }
                    }
                    else
                    {
                        foreach (var pt in pointsList)
                        {
                            int      delcount = 0;
                            var      sb       = new StringBuilder();
                            AFValues vals     = pt.RecordedValues(timeRange: timeRange,
                                                                  boundaryType: AFBoundaryType.Inside,
                                                                  filterExpression: null,
                                                                  includeFilteredValues: false,
                                                                  maxCount: 0
                                                                  );
                            delcount = vals.Count;
                            if (delcount > 0)
                            {
                                var errs = pt.UpdateValues(values: vals,
                                                           updateOption: AFUpdateOption.Remove,
                                                           bufferOption: AFBufferOption.BufferIfPossible);
                                if (errs != null)
                                {
                                    foreach (var e in errs.Errors)
                                    {
                                        sb.AppendLine($"{e.Key}: {e.Value}");
                                        delcount--;
                                    }
                                }
                            }
                            sb.AppendLine($"Point: {pt.Name} Deleted {delcount} events");
                            sb.AppendLine(new string('-', 45));
                            sb.AppendLine();
                            Console.Write(sb.ToString());
                        }
                    }
                    break;
                }

                case "sign,t":
                {
                    Dictionary <PIPoint, int> errPoints = pointsList.ToDictionary(key => key, value => 0);
                    //if (Int32.TryParse(myServer.ServerVersion.Substring(4, 3), out int srvbuild) && srvbuild >= 395);
                    if (myServer.Supports(PIServerFeature.TimeSeriesDataPipe))
                    {
                        PIDataPipe timeSeriesDatapipe = new PIDataPipe(AFDataPipeType.TimeSeries);
                        Console.WriteLine("Signing up for TimeSeries events");
                        var errs = timeSeriesDatapipe.AddSignups(pointsList);
                        if (errs != null)
                        {
                            foreach (var e in errs.Errors)
                            {
                                Console.WriteLine($"Failed timeseries signup: {e.Key}, {e.Value.Message}");
                                errPoints[e.Key]++;
                            }
                            foreach (var ep in errPoints)
                            {
                                if (ep.Value >= 1)
                                {
                                    pointsList.Remove(ep.Key);
                                }
                            }
                            if (pointsList.Count == 0)
                            {
                                ParseArgs.PrintHelp("No valid PI Points");
                                if (timeSeriesDatapipe != null)
                                {
                                    timeSeriesDatapipe.Close();
                                    timeSeriesDatapipe.Dispose();
                                }
                                return;
                            }
                        }
                        timeSeriesDatapipe.Subscribe(new DataPipeObserver("TimeSeries"));
                        Console.WriteLine("Subscribed Points (current value): ");
                        AFListResults <PIPoint, AFValue> results = pointsList.EndOfStream();
                        if (results.HasErrors)
                        {
                            foreach (var e in results.Errors)
                            {
                                Console.WriteLine($"{e.Key}: {e.Value}");
                            }
                        }
                        foreach (var v in results.Results)
                        {
                            if (!results.Errors.ContainsKey(v.PIPoint))
                            {
                                Console.WriteLine($"{v.PIPoint.Name,-12}, {v.Timestamp}, {v.Value}");
                            }
                        }
                        Console.WriteLine(new string('-', 45));

                        //Fetch timeseries events till user termination
                        while (!GlobalConfig.CancelSignups)
                        {
                            timeSeriesDatapipe.GetObserverEvents(GlobalConfig.PipeMaxEvtCount, out bool hasMoreEvents);
                            Thread.Sleep(GlobalConfig.PipeCheckFreq);
                        }
                        Console.WriteLine("Cancelling signups ...");
                        if (timeSeriesDatapipe != null)
                        {
                            timeSeriesDatapipe.Close();
                            timeSeriesDatapipe.Dispose();
                        }
                    }
                    else
                    {
                        ParseArgs.PrintHelp($"Time series not supported in Archive version {myServer.ServerVersion}");
                    }
                    break;
                }

                case "sign,as":
                case "sign,sa":
                case "sign,a":
                case "sign,s":
                {
                    bool       snapSubscribe            = false;
                    bool       archSubscribe            = false;
                    PIDataPipe snapDatapipe             = null;
                    PIDataPipe archDatapipe             = null;
                    Dictionary <PIPoint, int> errPoints = pointsList.ToDictionary(key => key, value => 0);
                    if (command.Substring(5).Contains("s"))
                    {
                        snapSubscribe = true;
                        snapDatapipe  = new PIDataPipe(AFDataPipeType.Snapshot);

                        Console.WriteLine("Signing up for Snapshot events");
                        var errs = snapDatapipe.AddSignups(pointsList);
                        snapDatapipe.Subscribe(new DataPipeObserver("Snapshot"));
                        if (errs != null)
                        {
                            foreach (var e in errs.Errors)
                            {
                                Console.WriteLine($"Failed snapshot signup: {e.Key}, {e.Value.Message}");
                                errPoints[e.Key]++;
                            }
                        }
                    }
                    if (command.Substring(5).Contains("a"))
                    {
                        archSubscribe = true;
                        archDatapipe  = new PIDataPipe(AFDataPipeType.Archive);
                        Console.WriteLine("Signing up for Archive events");
                        var errs = archDatapipe.AddSignups(pointsList);
                        if (errs != null)
                        {
                            foreach (var e in errs.Errors)
                            {
                                Console.WriteLine($"Failed archive signup: {e.Key}, {e.Value.Message}");
                                errPoints[e.Key]++;
                            }
                        }
                        archDatapipe.Subscribe(new DataPipeObserver("Archive "));
                    }

                    //remove unsubscribable points
                    int errorLimit = snapSubscribe ? 1 : 0;
                    if (archSubscribe)
                    {
                        errorLimit++;
                    }
                    foreach (var ep in errPoints)
                    {
                        if (ep.Value >= errorLimit)
                        {
                            pointsList.Remove(ep.Key);
                        }
                    }
                    if (pointsList.Count == 0)
                    {
                        ParseArgs.PrintHelp("No valid PI Points");
                        if (snapDatapipe != null)
                        {
                            snapDatapipe.Close();
                            snapDatapipe.Dispose();
                        }
                        if (archDatapipe != null)
                        {
                            archDatapipe.Close();
                            archDatapipe.Dispose();
                        }
                        return;
                    }
                    Console.WriteLine("Subscribed Points (current value): ");
                    //foreach (var p in pointsList)
                    //{
                    //    Console.WriteLine($"{p.Name,-12}, {p.EndOfStream().Timestamp}, {p.EndOfStream()}");
                    //}
                    AFListResults <PIPoint, AFValue> results = pointsList.EndOfStream();
                    if (results.HasErrors)
                    {
                        foreach (var e in results.Errors)
                        {
                            Console.WriteLine($"{e.Key}: {e.Value}");
                        }
                    }
                    foreach (var v in results.Results)
                    {
                        if (!results.Errors.ContainsKey(v.PIPoint))
                        {
                            Console.WriteLine($"{v.PIPoint.Name,-12}, {v.Timestamp}, {v.Value}");
                        }
                    }
                    Console.WriteLine(new string('-', 45));

                    //Fetch events from the data pipes
                    while (!GlobalConfig.CancelSignups)
                    {
                        if (snapSubscribe)
                        {
                            snapDatapipe.GetObserverEvents(GlobalConfig.PipeMaxEvtCount, out bool hasMoreEvents1);
                        }
                        if (archSubscribe)
                        {
                            archDatapipe.GetObserverEvents(GlobalConfig.PipeMaxEvtCount, out bool hasMoreEvents2);
                        }
                        Thread.Sleep(GlobalConfig.PipeCheckFreq);
                    }
                    Console.WriteLine("Cancelling signups ...");
                    if (snapDatapipe != null)
                    {
                        snapDatapipe.Close();
                        snapDatapipe.Dispose();
                    }
                    if (archDatapipe != null)
                    {
                        archDatapipe.Close();
                        archDatapipe.Dispose();
                    }
                }
                break;
                }
                Console.WriteLine(new string('~', 45));
            }
            catch (Exception ex)
            {
                ParseArgs.PrintHelp(ex.Message);
                if (myServer != null)
                {
                    myServer.Disconnect();
                    if (GlobalConfig.Debug)
                    {
                        Console.WriteLine($"Disconnecting from {myServer.Name}");
                    }
                }
            }
        }
Ejemplo n.º 14
0
        public static Service GetInputTagValueFromPi(Service unit)
        {
            var unitTagList = GetTagArray(unit);
            AFListResults <PIPoint, AFValue> PiDataValues = ReadValuesFromPi(unitTagList);

            foreach (var piValue in PiDataValues)
            {
                if (unit.EngineSpeed.Name == piValue.PIPoint.Name)
                {
                    unit.EngineSpeed.Value = piValue.Value;
                }
                if (unit.DischargePressure.Name == piValue.PIPoint.Name)
                {
                    unit.DischargePressure.Value = piValue.Value;
                }

                if (unit.StageSuctionPressure.Ps1.Name == piValue.PIPoint.Name)
                {
                    unit.StageSuctionPressure.Ps1.Value = piValue.Value;
                }
                //if (unit.StageSuctionPressure.Ps2.Name == piValue.PIPoint.Name)
                //{
                //    unit.StageSuctionPressure.Ps2.Value = piValue.Value;
                //}
                if (unit.StageSuctionTemperature.Ts1.Name == piValue.PIPoint.Name)
                {
                    unit.StageSuctionTemperature.Ts1.Value = piValue.Value;
                }
                //if (unit.StageSuctionTemperature.Ts2.Name == piValue.PIPoint.Name
                //{
                //    unit.StageSuctionTemperature.Ts2.Value = piValue.Value;
                //}
                if (unit.StageSuctionTemperature.Ts2 != null)
                {
                    if (unit.StageSuctionTemperature.Ts2.Name == piValue.PIPoint.Name)
                    {
                        unit.StageSuctionTemperature.Ts2.Value = piValue.Value;
                    }
                }

                if (unit.StageSuctionTemperature.Ts3 != null)
                {
                    if (unit.StageSuctionTemperature.Ts3.Name == piValue.PIPoint.Name)
                    {
                        unit.StageSuctionTemperature.Ts3.Value = piValue.Value;
                    }
                }

                if (unit.StageSuctionTemperature.Ts4 != null)
                {
                    if (unit.StageSuctionTemperature.Ts4.Name == piValue.PIPoint.Name)
                    {
                        unit.StageSuctionTemperature.Ts4.Value = piValue.Value;
                    }
                }
                if (unit.StageSuctionTemperature.Ts5 != null)
                {
                    if (unit.StageSuctionTemperature.Ts5.Name == piValue.PIPoint.Name)
                    {
                        unit.StageSuctionTemperature.Ts5.Value = piValue.Value;
                    }
                }
                if (unit.StageSuctionTemperature.Ts6 != null)
                {
                    if (unit.StageSuctionTemperature.Ts6.Name == piValue.PIPoint.Name)
                    {
                        unit.StageSuctionTemperature.Ts6.Value = piValue.Value;
                    }
                }
                foreach (var stage in unit.Stages)
                {
                    if (stage.Pd.Name == piValue.PIPoint.Name)
                    {
                        stage.Pd.Value = piValue.Value;
                    }
                }
            }

            return(unit);
        }