Beispiel #1
0
        private static void readData(String serverName, Func <String> tagNameSupplier, int[] daysToReadList)
        {
            PIServer server = new PIServers()
                              .Where(s => s.Name.Contains(serverName))
                              .First();

            server.Connect();

            foreach (int daysToRead in daysToReadList)
            {
                Console.Write("[{0} {1}d] ", serverName, daysToRead);

                Stopwatch roundTripStopwatch = Stopwatch.StartNew();
                PIPoint   tag = PIPoint.FindPIPoint(server, tagNameSupplier.Invoke());
                roundTripStopwatch.Stop();

                AFTimeRange timeRange = new AFTimeRange(new AFTime(readStart), new AFTime(readStart.Add(new TimeSpan(daysToRead, 0, 0, 0))));

                try {
                    Stopwatch readStopwatch = Stopwatch.StartNew();
                    AFValues  values        = tag.RecordedValues(timeRange, AFBoundaryType.Outside, "", true, 0);
                    readStopwatch.Stop();

                    Console.WriteLine("Read {0:n0} samples in {1:0.000}s (1m samples in {2:0.000}s) EstimatedRoundTripTime: {3}ms",
                                      values.Count,
                                      readStopwatch.ElapsedMilliseconds / 1000.0,
                                      ((double)readStopwatch.ElapsedMilliseconds) / values.Count * 1000.0,
                                      roundTripStopwatch.ElapsedMilliseconds);
                } catch (Exception e) {
                    Console.WriteLine("Exception: {0}", e.ToString());
                }
            }

            server.Disconnect();
        }
Beispiel #2
0
        public static void DeleteValues(PIPoint piPoint, AFTime st, AFTime et, bool forceUpdateValuesMethod = false)
        {
            var timerange = new AFTimeRange(st, et);

            if (piPoint.Server.Supports(PIServerFeature.DeleteRange) && forceUpdateValuesMethod == false)
            {
                var errors = piPoint.ReplaceValues(timerange, new List <AFValue>());

                if (errors != null && errors.HasErrors)
                {
                    _logger.Error(errors.Errors);
                    _logger.Error(errors.PIServerErrors);
                }
            }

            else
            {   // fallback on the old fashion way of doing the delete
                // if code goes here this may be much slower to delete the values.
                _logger.Warn("The ReplaceValues method is not implemented on the target PI DataArchive or the forceUpdateValuesMethod flag was used, falling back to the previous longer method ( read and remove)");

                var dataToDelete = piPoint.RecordedValues(timerange, AFBoundaryType.Inside, string.Empty, false);

                if (dataToDelete.Count > 0)
                {
                    piPoint.UpdateValues(dataToDelete, AFUpdateOption.Remove);
                }
            }
        }
Beispiel #3
0
        private void GetArchive_Click(object sender, EventArgs e)
        {
            ValuesListView.Items.Clear();
            if (TagList.SelectedIndices.Count < 1)
            {
                MessageBox.Show("Please select one tag from list");
                return;
            }
            string tagname = TagList.SelectedItems[0].Text;

            TagNameLabel.Text = tagname;
            PIPoint     pt        = PIPoint.FindPIPoint(myPIServer, tagname);
            AFTimeRange timerange = new AFTimeRange();

            timerange.StartTime = new AFTime(StartTimeTextBox.Text);
            timerange.EndTime   = new AFTime(EndTimeTextBox.Text);
            AFValues vals = pt.RecordedValues(timerange, OSIsoft.AF.Data.AFBoundaryType.Inside, "", true);

            foreach (AFValue val in vals)
            {
                string[] displayvalues = new string[2];
                displayvalues[0] = val.Timestamp.LocalTime.ToString();
                displayvalues[1] = val.Value.ToString();
                ListViewItem lvi = new ListViewItem(displayvalues);
                ValuesListView.Items.Add(lvi);
            }
        }
Beispiel #4
0
        private void btnGetTagData_Click(object sender, EventArgs e)
        {
            //Set timerange
            AFTime startTime = new AFTime(piStartTime.Text);
            AFTime endTime = new AFTime(piEndTime.Text);
            AFTimeRange timeRange = new AFTimeRange(startTime, endTime);

            //Get tagname
            string tagname = tbEnterTag.Text;

            //Get pi server
            PIServers servers = new PIServers();
            PIServer server = servers[piServerPicker1.PIServer.ToString()];

            //Get pi point
            PIPoint point = PIPoint.FindPIPoint(server, tagname);

            //extract values for tag across timerange
            AFValues values = point.RecordedValues(timeRange, AFBoundaryType.Inside, null, false, 0);

            //Get current value and timestamp
            piCurrentValue.Text = point.CurrentValue().ToString();
            piCurrentTimestamp.Text = point.CurrentValue().Timestamp.ToString();

            //Clear data chart
            piDataChart.Series["dataSeries"].Points.Clear();

            if (values != null)
            {
                foreach (AFValue value in values)
                {
                    //Write data into list box
                    string output = String.Format("{0} \t {1} {2}", value.Timestamp, value.Value, 
                                                    value.UOM != null ? value.UOM.Abbreviation : null);
                    lbPIData.Items.Add(output);

                    try
                    {
                        //chart data
                        piDataChart.Series["dataSeries"].Points.AddXY(value.Timestamp.ToString(), value.Value);
                    } catch (System.ArgumentException)
                    {
                        continue;
                    }

                    
                }
            }
        }
Beispiel #5
0
        private async Task _RetrieveAlarmandUpdateAsync(Foo csvItem)
        {
            await _throttler.WaitAsync();

            // do search for all PI Points required for alarm processing
            var alarmSearch   = GetPIPoint(csvItem.AlarmTagInput, "");
            var sourceSearch  = GetPIPoint(csvItem.TagSuffixOutput, "SRC");
            var messageSearch = GetPIPoint(csvItem.TagSuffixOutput, "MSG");
            var countSearch   = GetPIPoint(csvItem.TagSuffixOutput, "COUNT");

            // If any of the search above fails, exit the operation
            if ((!alarmSearch.Item1) || (!sourceSearch.Item1) || (!messageSearch.Item1) || (!countSearch.Item1))
            {
                _logger.Error($"Some of the PI Points required for {csvItem.AlarmTagInput} don't exist");
                _throttler.Release();
                return;
            }

            // Else continue processing alarms and updating relevant PI Points
            PIPoint AlarmPoint     = alarmSearch.Item2;
            PIPoint SourceTagPoint = sourceSearch.Item2;
            PIPoint MSGTagPoint    = messageSearch.Item2;
            PIPoint CountTagPoint  = countSearch.Item2;

            //Retrive PI data with time range
            var valueList = AlarmPoint.RecordedValues(_queryRange, OSIsoft.AF.Data.AFBoundaryType.Inside, null, false);

            //Filter the list of PI Data with "|ACTIVE|"
            var filteredActiveList = valueList.Where((item) =>
            {
                return(item.Value.ToString().Contains("|ACTIVE|"));
            });

            //Choose the code to execute base on the mode
            IEnumerable <AFValue> sourceList;

            if (csvItem.Mode != "3")
            {
                sourceList = filteredActiveList.Select(item =>
                {
                    if (csvItem.Mode == "1")
                    {
                        return(createSource1(item));
                    }
                    else
                    {
                        return(createSource2(item));
                    }
                });
            }
            else
            {
                filteredActiveList = filteredActiveList.Where((item) =>
                {
                    return(item.Value.ToString().Split('|')[9].Contains(csvItem.Hierarchy));
                });

                sourceList = filteredActiveList.Select(item => createSource1(item));
            }

            _logger.Information($"Tag {csvItem.AlarmTagInput} has {sourceList.Count()} alarms in the past 10 Minutes");

            //Output message to a messagelist from item
            var messageList = filteredActiveList.Select((item) =>
            {
                return(new AFValue
                {
                    Timestamp = item.Timestamp,
                    Value = item.Value.ToString().Split('|')[3]
                });
            });

            //Find the Count tag and update values into the tag
            AFValue numActive = new AFValue(sourceList.Count(), _RoundDown(_signalTime));
            // Make numActive into an 1-member IEnumerable because TryUpdateValues require IEnumerable as a parameter
            IEnumerable <AFValue> numActiveList = new List <AFValue>()
            {
                numActive
            };

            // create a list of parallel PI Point UpdateValues Task
            var updateTasks = new List <Task>();

            updateTasks.Add(_TryUpdateValuesAsync(SourceTagPoint, sourceList, csvItem));
            updateTasks.Add(_TryUpdateValuesAsync(MSGTagPoint, messageList, csvItem));
            updateTasks.Add(_TryUpdateValuesAsync(CountTagPoint, numActiveList, csvItem));
            await Task.WhenAll(updateTasks);

            _throttler.Release();
        }
Beispiel #6
0
        private void DeleteEvents_Click(object sender, EventArgs e)
        {
            //Check TagList's count
            Int32 pointnumber = TagList.Items.Count;

            if (pointnumber < 1)
            {
                MessageBox.Show("Please search PI tags");
                return;
            }
            else
            {
                if (radioButton_AllEvents.Checked)
                {
                    //Delete all events
                    for (int i = 1; i <= pointnumber; ++i)
                    {
                        PIPoint     pt        = PIPoint.FindPIPoint(myPIServer, TagList.Items[i - 1].Text);
                        AFTimeRange timerange = new AFTimeRange();
                        timerange.StartTime = new AFTime(StartTimeTextBox.Text);
                        timerange.EndTime   = new AFTime(EndTimeTextBox.Text);
                        AFValues vals = pt.RecordedValues(timerange, OSIsoft.AF.Data.AFBoundaryType.Inside, "", true);

                        //delete all events within AFValues object
                        if (vals.Count > 0)
                        {
                            pt.UpdateValues(vals, AFUpdateOption.Remove);
                            string[] displayvalues = new string[3];
                            displayvalues[0] = pt.Name;
                            displayvalues[1] = timerange.ToString();
                            displayvalues[2] = "-";
                            ListViewItem lvi = new ListViewItem(displayvalues);
                            UpdateView.Items.Add(lvi);
                        }
                    }
                }
                else
                {
                    //Delete specific events
                    String deletestring = DeleteValueTextBox.Text.ToString();
                    for (int i = 1; i <= pointnumber; ++i)
                    {
                        PIPoint     pt        = PIPoint.FindPIPoint(myPIServer, TagList.Items[i - 1].Text);
                        AFTimeRange timerange = new AFTimeRange();
                        timerange.StartTime = new AFTime(StartTimeTextBox.Text);
                        timerange.EndTime   = new AFTime(EndTimeTextBox.Text);
                        AFValues vals       = pt.RecordedValues(timerange, OSIsoft.AF.Data.AFBoundaryType.Inside, "", true);
                        String   Checktime  = null;
                        String   Checkvalue = null;
                        foreach (AFValue val in vals)
                        {
                            Checktime  = val.Timestamp.LocalTime.ToString();
                            Checkvalue = ReadPIValueString(val);
                            if (Checkvalue == deletestring)
                            {
                                pt.UpdateValue(val, AFUpdateOption.Remove);
                                string[] displayvalues = new string[3];
                                displayvalues[0] = pt.Name;
                                displayvalues[1] = Checktime;
                                displayvalues[2] = Checkvalue;
                                ListViewItem lvi = new ListViewItem(displayvalues);
                                UpdateView.Items.Add(lvi);
                            }
                        }
                    }
                }
            }
        }
        /// <summary>
        ///  Common calls of getting Data from AFServer
        /// </summary>
        /// <param name="server_database">String representing the server and database</param>
        /// <param name="AttributeName"> name of the attribute</param>
        /// <param name="MatlabName">variable name for the Matlab Workspace</param>
        /// <param name="start">Start time of data collection.</param>
        /// <param name="end">End time of the data collection.</param>
        /// <param name="afobject"> AF object - AFAttribute, AFEventFrame, or PIPoint</param>
        /// <param name="addToListView"> Whether to add to the Listview (generally true)</param>
        public static void getData(string server_database, string AttributeName, string MatlabName, string start, string end, Object afobject, bool addToListView)
        {
            MatlabName = MatlabAccess.modifyMatlabName(MatlabName);
            LogInput    logInput = null;
            AFValues    Values   = new AFValues();
            AFAttribute attribute;

            object[] vals;
            double[] dbVals;
            double[] timestamps = null;
            int[]    statuses;
            int      baddata;

            //TIME RANGE
            AFTimeRange aftr;

            try { aftr = checkAFTimeRange(start, end); }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                throw ex;
            }

            /// Get Object
            Type   type       = afobject.GetType();
            string typestring = type.ToString();

            //  LogInput logInput = new LogInput(MatlabName, Element.Name, attribute.Name, path, aftr);
            switch (type.ToString())
            {
            case "OSIsoft.AF.Asset.AFAttribute":
                attribute = (AFAttribute)afobject;
                logInput  = new LogInput(MatlabName, attribute.Element.Name, attribute.Name, attribute.Element.GetPath(), aftr);
                if (attribute.PIPoint == null)         // Constant Value
                {
                    aftr = new AFTimeRange("*", "*");
                    logInput.setAFTimeRange(aftr);
                    Values = attribute.GetValues(aftr, dataPref, null);
                }
                else         // PI Point - Time Matters!!
                {
                    /* Summary: Attribute.GetValues - Important Call!
                     * Parameter Int32 => DataPref
                     *          = 0 :  All Values returned
                     *          < 0 :  Evenly spaced values, including start and end
                     *          > 0 :  # of intervals, for each interval 5 points are given (first, last, high, low, and exceptional)
                     */
                    Values = attribute.GetValues(aftr, dataPref, null);         // FULLY UNDERSTAND THIS !!! Important Call!!!!
                }
                break;

            case "OSIsoft.AF.EventFrame.AFEventFrame":
                AFEventFrame frame = (AFEventFrame)afobject;
                logInput  = new LogInput(MatlabName, frame.Name, frame.Attributes[AttributeName].Name, frame.GetPath(), aftr);
                attribute = frame.Attributes[AttributeName];
                logInput.setAFTimeRange(aftr);
                AFValue val = attribute.GetValue(aftr);
                Values = new AFValues()
                {
                    val
                };
                break;

            case "OSIsoft.AF.PI.PIPoint":
                PIPoint piPoint = (PIPoint)afobject;
                string  path    = piPoint.GetPath();
                logInput = new LogInput(MatlabName, "PI.Point", piPoint.Name, "PI.Point", aftr);
                Values   = piPoint.RecordedValues(aftr, AFBoundaryType.Interpolated, "", true, Int32.MaxValue);
                break;
            }



            //Determine if AFTIME Absolute String
            isAbsoluteTimeString(start, end, logInput);

            logInput.setAttributeGetValueFormat(dataPref);
            logInput.setTimespaceFormat(dataFormat);

            ConvertAFValues.GetValuesArray(Values, false, out vals, out timestamps, out statuses, out baddata);
            try
            {
                MatlabAccess.sendDataToMatlab(MatlabName, AFValuesToArray(vals));

                if (Timestamp)
                {
                    MatlabAccess.sendDataToMatlab(MatlabName + "Time", timestamps);
                }
            }
            catch
            {
                logInput.setServerDatabase(server_database);
                LogSystem.addLogInput(server_database, logInput, addToListView);
                throw new NullReferenceException();
            }

            logInput.setServerDatabase(server_database);
            LogSystem.addLogInput(server_database, logInput, addToListView);
        }