public static void GetValuesArray(AFValues afvalues, out object[] values, out int baddata) { int size = afvalues.Count; values = new object[size]; baddata = 0; int i = 0; foreach (AFValues afval in afvalues) { values[i] = afval.Value; if(afval.Status != AFValueStatus.Good) baddata = baddata + 1; i = i + 1; } return; }
public static void GetValuesArray(AFValues afvalues, out object[] values, out double[] timestamps, out int[] statuses, out int baddata) { int size = afvalues.Count; values = new object[size]; timestamps = new double[size]; statuses = new int[size]; baddata = 0; int i = 0; foreach (AFValues afval in afvalues) { values[i] = afval.Value; timestamps[i] = ((DateTime)afval.Timestamp).ToOADate() + 693960; statuses[i] = (int)afval.Status; if (afval.Status != AFValueStatus.Good) baddata = baddata + 1; i = i + 1; } return; }
private void btnRetrieveData_Click(object sender, EventArgs e) { try { lbData.Items.Clear(); AFAttribute selectedAttribute = lbAttributes.SelectedItem as AFAttribute; AFTimeRange timeRange = new AFTimeRange(tbStartTime.Text, tbEndTime.Text); AFValues vals = null; switch (cbDataMethod.Text) { case "Recorded Values": vals = selectedAttribute.Data.RecordedValues(timeRange, OSIsoft.AF.Data.AFBoundaryType.Inside, null, String.Empty, false, 0); break; case "Interpolated Values": var interval = new AFTimeSpan(); AFTimeSpan.TryParse(tbInterval.Text, out interval); vals = selectedAttribute.Data.InterpolatedValues(timeRange, interval, null, String.Empty, false); break; case "Snapshot": vals = new AFValues(); vals.Add(selectedAttribute.Data.EndOfStream(null)); break; default: throw new InvalidExpressionException(); } var valStrings = vals.Select(afv => String.Format("{0}\t{1}\t{2}\t{3}" , afv.Attribute.Name , afv.Timestamp.LocalTime , afv.Value , afv.UOM == null ? string.Empty : afv.UOM.Name)); lbData.Items.AddRange(valStrings.ToArray()); } catch (Exception ex) { MessageBox.Show("Error getting PI Data: " + ex.Message); } }
/// <summary> /// Converts FitFibt Time Series Data to AF Time Series Data /// </summary> /// <param name="tsDataList">FitBit Time Series data</param> /// <param name="type">Type of fit Bit data - this will determine the attribute name to write into. It can also influence the conversion logic.</param> /// <param name="element">The element that contains the attribute to write into</param> /// <param name="attributeName">Name of the AF Attribute in which time series data will be written into.</param> /// <returns></returns> public static AFValues ConvertToAFValues(TimeSeriesDataList tsDataList, TimeSeriesResourceType type, AFElement element, string attributeName) { // creates the list of values AFValues values = new AFValues(); foreach (var result in tsDataList.DataList) { AFValue val = null; if (type != TimeSeriesResourceType.TimeEnteredBed) { val = new AFValue(Convert.ToSingle(result.Value), new AFTime(result.DateTime)); } else { val = new AFValue(result.Value, new AFTime(result.DateTime)); } values.Add(val); } values.Attribute = element.Attributes[attributeName]; return values; }
public AFValues ConvertToAFValues(TimeSeriesDataList tsDataList, FitbitStream stream, FitbitUser fitbitUser) { AFValues values = new AFValues(); foreach (var result in tsDataList.DataList) { AFValue val = null; if (stream.FitbitSource != TimeSeriesResourceType.TimeEnteredBed) { val = new AFValue(Convert.ToSingle(result.Value), new AFTime(result.DateTime), stream.UnitsOfMeasure); } else { val = new AFValue(result.Value, new AFTime(result.DateTime), stream.UnitsOfMeasure); } values.Add(val); } values.Attribute = fitbitUser.UserElement.Elements["Fitbit"].Attributes[stream.AttributeName]; return values; }
static void PrintDailyAverageEnergyUsage(AFDatabase database, string startTime, string endTime) { Console.WriteLine(string.Format("Print Daily Energy Usage - Start: {0}, End: {1}", startTime, endTime)); AFAttributeList attrList = GetAttributes(database, "MeterBasic", "Energy Usage"); AFTime start = new AFTime(startTime); AFTime end = new AFTime(endTime); AFTimeRange timeRange = new AFTimeRange(start, end); // Ask for 100 PI Points at a time PIPagingConfiguration pagingConfig = new PIPagingConfiguration(PIPageType.TagCount, 100); IEnumerable <IDictionary <AFSummaryTypes, AFValues> > summaries = attrList.Data.Summaries( timeRange: timeRange, summaryDuration: new AFTimeSpan(TimeSpan.FromDays(1)), summaryTypes: AFSummaryTypes.Average, calculationBasis: AFCalculationBasis.TimeWeighted, timeType: AFTimestampCalculation.EarliestTime, pagingConfig: pagingConfig); // Loop through attributes foreach (IDictionary <AFSummaryTypes, AFValues> dict in summaries) { AFValues values = dict[AFSummaryTypes.Average]; Console.WriteLine("Averages for Meter: {0}", values.Attribute.Element.Name); // Loop through values per attribute foreach (AFValue val in dict[AFSummaryTypes.Average]) { Console.WriteLine("Timestamp (Local): {0:yyyy-MM-dd}, Avg. Value: {1:0.00} {2}", val.Timestamp.LocalTime, val.Value, val?.UOM.Abbreviation); } Console.WriteLine(); } Console.WriteLine(); }
protected override List <Action> GetActions() { if (string.IsNullOrEmpty(WindFarms)) { return(new List <Action>()); } var splittedWindFarms = WindFarms.Split(','); var actionz = new List <Action>(); foreach (var windFarm in splittedWindFarms) { var afEventFrameSearch = GetEventFramesFromAfEventFrameSearch("EFOutageClassification", $"{windFarm}*", "Deleted", false); var eventFramesGroupedByElement = afEventFrameSearch.GroupBy(ef => ef.PrimaryReferencedElement); foreach (var attributeName in _attributeNames) { actionz.AddRange(eventFramesGroupedByElement.Select(group => (Action)(() => { var actionStopwatch = new AFStopwatch(); actionStopwatch.Start(); AFValues afValues = GetRecordedValues(group.Key, attributeName, TimeRange); TestOutput.AddActionResult( new ActionPerformanceResult { ActionMillis = actionStopwatch.ElapsedMilliseconds, ResultCount = afValues?.Count ?? 0 }); }))); } } return(actionz); }
private AFValue Calculate(AFTime time, AFAttributeList inputAttributes, AFValues inputValues) { if (time == null) { throw new ArgumentException("No timestamp"); } if (inputAttributes == null || inputAttributes.Count == 0) { throw new ArgumentException("No input attributes"); } try { PIPoint tag = inputAttributes[0].PIPoint; if (tag == null) { throw new ArgumentException("No PI point"); } tag.LoadAttributes(PropertyName); object result = tag.GetAttribute(PropertyName); return new AFValue(base.Attribute, result, time, Attribute.DefaultUOM); } catch { throw new ArgumentException("Failed extracting tag property"); } }
/// <summary> /// Reads PI events from a list of PI Points with specified start time and maximum event count. /// </summary> /// <param name="pointList">List of PI Points from which to read events.</param> /// <param name="startTime">Start time used to read events.</param> /// <param name="maxEventCount">Maximum number of events to read.</param> /// <returns>Returns a dictionary where the key is the PI Point name and the value are the AFValues for the PI Point.</returns> public IDictionary <string, AFValues> ReadPIEvents(IEnumerable <PIPoint> pointList, AFTime startTime, int maxEventCount) { var results = new ConcurrentDictionary <string, AFValues>(); Parallel.ForEach( pointList, new ParallelOptions { MaxDegreeOfParallelism = MaxDegreeOfParallelism }, pt => { AFValues values = pt.RecordedValuesByCount( startTime, maxEventCount, true, AFBoundaryType.Inside, null, false); results.TryAdd(pt.Name, values); }); return(results.ToDictionary(kvp => kvp.Key, kvp => kvp.Value)); }
public void PIDataPipeTimeSeriesTest(PIPointType piPointType, object[] eventValues) { Contract.Requires(eventValues != null); const string PointName = "PIDataPipeTests_PIPoint"; AFDatabase db = AFFixture.AFDatabase; PIServer piServer = PIFixture.PIServer; var piDataPipe = new PIDataPipe(AFDataPipeType.TimeSeries); var piPointList = new PIPointList(); var now = AFTime.NowInWholeSeconds; try { Output.WriteLine("Create the Future PI Points with Zero Compression and specified PI Point type."); PIFixture.DeletePIPoints(PointName + "*", Output); var testPIPoints = PIFixture.CreatePIPoints(PointName + "###", eventValues.Length, new Dictionary <string, object> { { PICommonPointAttributes.PointType, piPointType }, { PICommonPointAttributes.ExceptionDeviation, 0 }, { PICommonPointAttributes.ExceptionMaximum, 0 }, { PICommonPointAttributes.Compressing, 0 }, { PICommonPointAttributes.DigitalSetName, "Phases" }, { PICommonPointAttributes.Future, true }, }); Assert.True(testPIPoints.Count() == eventValues.Length, $"Unable to create all the test PI Points."); piPointList.AddRange(testPIPoints); // Add the PI Point as sign up to the PIDataPipe. Output.WriteLine($"Sign up all PI Points with PIDataPipe."); var afErrors = piDataPipe.AddSignups(piPointList); var prefixErrorMessage = "Adding sign ups to the PIDataPipe was unsuccessful."; Assert.True(afErrors == null, userMessage: afErrors?.Errors.Aggregate(prefixErrorMessage, (msg, error) => msg += $" PI Point: [{error.Key.Name}] Error: [{error.Value.Message}] ")); // Write one data value to each PI Point. var expectedAFValues = new AFValues(); for (int i = 0; i < eventValues.Length; i++) { AFValue afValue = null; var timestamp = now + TimeSpan.FromMinutes(i - eventValues.Length); // Special Handling of Input Data for Digital and Timestamp switch (piPointType) { case PIPointType.Digital: afValue = new AFValue(new AFEnumerationValue("Phases", (int)eventValues[i]), timestamp); break; case PIPointType.Timestamp: afValue = new AFValue(new AFTime(eventValues[i], now), timestamp); break; default: afValue = new AFValue(eventValues[i], timestamp); break; } Output.WriteLine($"Writing Value [{eventValues[i]}] with Timestamp [{timestamp}] to PI Point [{piPointList[i].Name}]."); piPointList[i].UpdateValue(afValue, AFUpdateOption.InsertNoCompression); // If writing digital states, we need to save the corresponding value for verification. // Since we are using Phases, 0 ~ Phase1, 1 ~ Phase2, etc. if (piPointType == PIPointType.Digital) { int input = (int)eventValues[i]; afValue = new AFValue(new AFEnumerationValue($"Phase{input + 1}", input), timestamp); } afValue.PIPoint = piPointList[i]; expectedAFValues.Add(afValue); } // Retry assert to retrieve expected Update Events from the PIDataPipe var actualAFValues = new AFValues(); Output.WriteLine($"Reading Events from the PI DataPipe."); AssertEventually.True(() => { var updateEvents = piDataPipe.GetUpdateEvents(eventValues.Length); prefixErrorMessage = "Retrieving Update Events from the PIDataPipe was unsuccessful."; Assert.False(updateEvents.HasErrors, userMessage: updateEvents.Errors?.Aggregate(prefixErrorMessage, (msg, error) => msg += $" PI Point: [{error.Key.Name}] Error: [{error.Value.Message}] ")); actualAFValues.AddRange(updateEvents.Results.Select(update => update.Value)); if (actualAFValues.Count >= expectedAFValues.Count) { // Verify that all expected update events are received from the PIDataPipe Assert.True(expectedAFValues.Count == actualAFValues.Count, "PIDataPipe returned more events than expected. " + $"Expected Count: {expectedAFValues.Count}, Actual Count: {actualAFValues.Count}."); return(true); } return(false); }, TimeSpan.FromSeconds(5), TimeSpan.FromSeconds(0.5), "Unable to retrieve events within the time frame."); // Verify all received events. Output.WriteLine($"Verifying all {actualAFValues.Count} events from the PI DataPipe."); for (int i = 0; i < actualAFValues.Count; i++) { // Special handling of Output events for Timestamp if (piPointType == PIPointType.Timestamp) { actualAFValues[i].Value = new AFTime(actualAFValues[i].Value, now); } AFFixture.CheckAFValue(actualAFValues[i], expectedAFValues[i]); Assert.True(object.Equals(actualAFValues[i].PIPoint, expectedAFValues[i].PIPoint), $"Unexpected PI Point Association. Expected: [{expectedAFValues[i].PIPoint}], Actual: [{actualAFValues[i].PIPoint}]."); } // Remove all sign ups from the PIDataPipe Output.WriteLine($"Remove all PI Point sign ups from PIDataPipe."); afErrors = piDataPipe.RemoveSignups(piPointList); prefixErrorMessage = "Removing sign ups to the PIDataPipe was unsuccessful."; Assert.True(afErrors == null, userMessage: afErrors?.Errors.Aggregate(prefixErrorMessage, (msg, error) => msg += $" PI Point: [{error.Key.Name}] Error: [{error.Value.Message}] ")); // Write dummy values to the PI Points and confirm PI DataPipe receives none. Output.WriteLine($"Write dummy values to the PI Points."); for (int i = 0; i < eventValues.Length; i++) { piPointList[i].UpdateValue(new AFValue(eventValues[i], now), AFUpdateOption.InsertNoCompression); } Output.WriteLine($"Verify no events are received by the PIDataPipe."); var noEvents = piDataPipe.GetUpdateEvents(eventValues.Length); prefixErrorMessage = "Retrieving Update Events from the PIDataPipe was unsuccessful."; Assert.False(noEvents.HasErrors, userMessage: noEvents.Errors?.Aggregate(prefixErrorMessage, (msg, error) => msg += $" PI Point: [{error.Key.Name}] Error: [{error.Value.Message}] ")); Assert.True(noEvents.Count == 0, "PIDataPipe received events even after removing all sign ups."); } finally { piDataPipe.RemoveSignups(piPointList); piDataPipe.Dispose(); PIFixture.DeletePIPoints(PointName + "*", Output); } }
public override AFValue GetValue(object context, object timeContext, AFAttributeList inputAttributes, AFValues inputValues) { if (!fChecked) { CheckConfig(); } AFValue result; try { result = Calculate(inputValues); } catch { UnloadParameters(); fChecked = false; throw; } return(result); }
private void AddTrendButton_Click(object sender, EventArgs e) { if (EFListView.SelectedItems.Count >= 1 && EFAttrView.SelectedItems.Count >= 1) { for (int i = 0; i < EFListView.SelectedItems.Count; i++) { for (int j = 0; j < EFAttrView.SelectedItems.Count; j++) { ListViewItem SelectedEF = EFListView.SelectedItems[i]; ListViewItem SelectedEFattr = EFAttrView.SelectedItems[j]; //Get EFName and Attribute Name String EFName = SelectedEF.SubItems[0].Text; String EFattrName = SelectedEFattr.SubItems[0].Text; String title = num + "_" + EFName + " : " + EFattrName; //Create GUID for Selected Event Frame Guid myEFGUID = Guid.Empty; String myguidstring = SelectedEF.SubItems[4].Text; try { myEFGUID = Guid.Parse(myguidstring); } catch { MessageBox.Show("Cannot convert GUID"); } //Find Selected Event Frame AFEventFrame myEF = AFEventFrame.FindEventFrame(myAFServer, myEFGUID); AFTime startTime = myEF.StartTime; AFTime endTime = myEF.EndTime; //Set endtime as now for not finishing event frame if (endTime > new AFTime("2099/1/1")) { endTime = DateTime.Now; } AFTimeRange timerange = new AFTimeRange(startTime, endTime); //Find Selected Attribute AFAttribute myEFAttr = myEF.Attributes[SelectedEFattr.Text]; DateTime trendstarttime = new DateTime(0); //Check time difference between start time and end time TimeSpan timedif = endTime - startTime; try { AFValues vals = myEFAttr.Data.PlotValues(timerange, 100, null); Int32 chk = 0; foreach (AFValue val in vals) { //Sometimes System.InvalidOperationException happens. Type t = val.Value.GetType(); if (t.FullName != "System.InvalidOperationException") { if (chk == 0) { //Add line to chart1 try { //add trend to chart1 chart1.Series.Add(title); chart1.Series[title].ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Line; chart1.Series[title].BorderWidth = 2; // Line width chart1.Series[title].ToolTip = "#SERIESNAME\r\nValue : #VALY{N2}\r\nTime : #VALX{N0}"; chart1.ChartAreas[0].AxisX.Title = "Seconds"; //Zoom function chart1.ChartAreas[0].CursorX.IsUserSelectionEnabled = true; chart1.ChartAreas[0].CursorY.IsUserSelectionEnabled = true; } catch (Exception ex) { MessageBox.Show(ex.Message); return; } trendstarttime = val.Timestamp.LocalTime; } timedif = val.Timestamp.LocalTime - trendstarttime; //Displaying EnumerationSet value as number if (t.FullName == "OSIsoft.AF.Asset.AFEnumerationValue") { //Errchk = 1; AFEnumerationValue MyEnumerationValue = (AFEnumerationValue)val.Value; // last value will be returned as 248. So ignore it if (MyEnumerationValue.Value != 248) { chart1.Series[title].Points.AddXY(timedif.TotalSeconds, MyEnumerationValue.Value.ToString()); } } else { chart1.Series[title].Points.AddXY(timedif.TotalSeconds, val.Value.ToString()); } chk = 1; } else { Errchk = 1; //Write code for System.InvalidOperationException - Currently ignore it //AFValue val2 = myEFAttr.GetValue(endTime,null); //timedif = endTime - startTime; //chart1.Series[title].Points.AddXY(0, val2.Value.ToString()); //chart1.Series[title].Points.AddXY(timedif.TotalSeconds, val2.Value.ToString()); } } } catch { Errchk = 1; //If error happens, write code - Currently ignore it //AFValue val = myEFAttr.GetValue(endTime,null); //chart1.Series[title].Points.AddXY(0, val.Value.ToString()); //chart1.Series[title].Points.AddXY(timedif.TotalSeconds, val.Value.ToString()); } if (Errchk == 0) { //If there is no error, Set minimum and maximum time chart1.ChartAreas[0].AxisX.Minimum = 0; if (maxtimedif > timedif) { chart1.ChartAreas[0].AxisX.Maximum = maxtimedif.TotalSeconds; } else { chart1.ChartAreas[0].AxisX.Maximum = timedif.TotalSeconds; maxtimedif = timedif; } ++num; } Errchk = 0; } } } }
public void Run() { PISystems piSystems = new PISystems(); PISystem piSystem = piSystems["<AFSERVER>"]; AFDatabase afDatabase = piSystem.Databases["NuGreen"]; AFElementTemplate boilerTemplate = afDatabase.ElementTemplates["Boiler"]; const int pageSize = 1000; int startIndex = 0; int totalCount; do { // Find a collection of elements instantiated from the Boiler tempplate. // Only the Elements' header information (Name, Description, Template, Type, etc.) // are loaded from the AF Server by this call. AFNamedCollection <AFElement> elements = AFElement.FindElements( database: afDatabase, searchRoot: null, query: "Boiler", field: AFSearchField.Template, searchFullHierarchy: true, sortField: AFSortField.Name, sortOrder: AFSortOrder.Ascending, startIndex: startIndex, maxCount: pageSize, totalCount: out totalCount); if (elements == null) { break; } // Partially load the element by retrieving information only for the Water Flow attribute. AFElement.LoadAttributes(elements, new[] { boilerTemplate.AttributeTemplates["Water Flow"] }); Console.WriteLine("Found {0} Elements.", elements.Count); AFAttributeList attrList = new AFAttributeList(); // Because we are retrieving the Water Flow attribute which was previously loaded, // no additional server calls are made. // If LoadAttributes had not been called previously, then a server call would have been made for each element // in the loop below. foreach (AFElement item in elements) { attrList.Add(item.Attributes["Water Flow"]); } AFValues values = attrList.GetValue(); Console.WriteLine(" Water Flow values"); foreach (AFValue val in values) { Console.WriteLine(" Element: {0}, Timestamp: {1}, Value: {2}", val.Attribute.Element, val.Timestamp, val.Value.ToString()); } startIndex += pageSize; } while (startIndex < totalCount); }
public static void GetValuesArray(AFValues afvalues, out double[] values, out double[] timestamps, out int[] statuses, out int baddata) { int size = afvalues.Count; values = new double[size]; timestamps = new double[size]; statuses = new int[size]; baddata = 0; int i = 0; foreach (AFValue afval in afvalues) { if ((AFEnumerationValue)afval.Value != null) values[i] = ((AFEnumerationValue)afval.Value).Value; else double.TryParse(afval.Value.ToString(), out values[i]); timestamps[i] = ((DateTime)afval.Timestamp).ToOADate() + 693960; statuses[i] = (int)afval.Status; if (afval.Status != AFValueStatus.Good) baddata = baddata + 1; i = i + 1; } return; }
public override AFValue GetValue(object context, object timeContext, AFAttributeList inputAttributes, AFValues inputValues) { AFValue value = new AFValue(); AFValue result = new AFValue(); if (inputAttributes.Count != 0) //Checks if the attributes are set { switch (attributeType) //verifies the output type { case 0: value = GetAddressByCoordinates(inputValues[0].ToString(), inputValues[1].ToString()); //Gets data from Geocoding API break; case 1: value = GetAddressByAddress(inputValues[0].ToString()); //Gets data from Geocoding API CreateAttributes("Latitude", "Longitude"); try { currAttribute.Attributes["Latitude"].SetValue(GetLatitudeByAddress(value.Value.ToString())); currAttribute.Attributes["Longitude"].SetValue(GetLongitudeByAddress(value.Value.ToString())); } catch { } break; } result.Timestamp = inputValues[0].Timestamp; //Sets the attribute timestamp result.Value = value.Value; //Sets the attribute value } else//returns bad if the inputs are not set { result.Status = AFValueStatus.Bad; result.Value = AFSystemStateCode.BadInput; } return(result); }
public override AFValue GetValue(object context, object timeContext, AFAttributeList inputAttributes, AFValues inputValues) { AFValue value = new AFValue(); AFValue result = new AFValue(); if (inputAttributes.Count == 2) //Checks if both Latitude and Longitude attributes are set { value = GetAddressByCoordinates(inputValues[0].ToString(), inputValues[1].ToString()); //Gets data from Geocoding API result.Timestamp = inputValues[0].Timestamp; //Sets the attribute timestamp result.Value = value.Value; //Sets the attribute value } else //returns bad if the inputs are not set { result.Status = AFValueStatus.Bad; result.Value = AFSystemStateCode.BadInput; } return(result); }
/// <summary> /// This method gets the value based upon the data reference configuration within the specified context. /// <see cref="https://techsupport.osisoft.com/Documentation/PI-AF-SDK/html/M_OSIsoft_AF_Asset_AFDataReference_GetValue_1.htm"/> /// </summary> public override AFValue GetValue(object context, object timeContext, AFAttributeList inputAttributes, AFValues inputValues) { return new AFValue() { Timestamp = DateTime.Now, Value = 0 }; }
/// <summary> /// This method gets a collection of AFValue objects for an attribute based upon the data reference configuration within the specified AFTimeRange context. /// <see cref="https://techsupport.osisoft.com/Documentation/PI-AF-SDK/html/M_OSIsoft_AF_Asset_AFDataReference_GetValues.htm"/> /// </summary> public override AFValues GetValues(object context, AFTimeRange timeRange, int numberOfValues, AFAttributeList inputAttributes, AFValues[] inputValues) { var afvalues = new AFValues(); //insert logic to generate af values here afvalues.Add(new AFValue() { Value = 0, Timestamp = new AFTime(timeRange.StartTime) }); afvalues.Add(new AFValue() { Value = 1, Timestamp = new AFTime(timeRange.EndTime) }); return afvalues; }
private AFValue Calculate(AFValues inputValues) { double tempVal = 0.0; string calc = this.Calculation.ToUpperInvariant(); if (calc == null) { return(new AFValue(tempVal, this.Attribute.DefaultUOM)); } int count = 0; bool flag = false; foreach (AFValue current in inputValues) { if (current.IsGood && current.Value != null) { double curVal; if (current.UOM != null && this.Attribute.DefaultUOM != null && current.UOM != this.Attribute.DefaultUOM) { curVal = this.Attribute.DefaultUOM.Convert(current.Value, current.UOM); } else { curVal = Convert.ToDouble(current.Value); } if (calc == "AVG") { tempVal += curVal; count++; } else if (calc == "SUM") { tempVal += curVal; } else if (calc == "MIN") { if (!flag) { tempVal = curVal; flag = true; } else { tempVal = Math.Min(tempVal, curVal); } } else if (calc == "MAX") { if (!flag) { tempVal = curVal; flag = true; } else { tempVal = Math.Max(tempVal, curVal); } } } } if (calc == "AVG") { tempVal /= (double)count; } return(new AFValue(tempVal, this.Attribute.DefaultUOM)); }
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); } } } } } }
private void btnGetData(object sender, EventArgs e) { AFAttribute SelectedAttribute = lbAttributes.SelectedItem as AFAttribute; AFTime starTime = new AFTime(tbStart.Text); AFTime endTime = new AFTime(tbEnd.Text); AFTimeRange timeRange = new AFTimeRange(starTime, endTime); // get values from specified time range UOM desiredUOM = cbUOM.SelectedItem as UOM; // The desired consiulting mode AFValues values; switch (cbDataMethod.Text) { case "Recorded Values": values = SelectedAttribute.Data.RecordedValues(timeRange , AFBoundaryType.Interpolated , desiredUOM , null , true); break; case "Interpolated Values": values = SelectedAttribute.Data.InterpolatedValues(timeRange , AFTimeSpan.Parse("5m") , desiredUOM , null , true); break; case "Plot Values": values = SelectedAttribute.Data.PlotValues(timeRange , 300 , desiredUOM); break; default: values = new AFValues(); break; } //AFValues Values = SelectedAttribute.GetValues(timeRange, 0, desiredUOM); lbValues.Items.Clear(); if (values != null) { foreach (AFValue value in values) { String myStr = string.Format("{0} \t {1}, {2}" , value.Timestamp.LocalTime , value.Value , value.UOM != null ? value.UOM.Abbreviation : null); lbValues.Items.Add(myStr); } } }
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}"); } } } }
// https://techsupport.osisoft.com/Documentation/PI-AF-SDK/html/M_OSIsoft_AF_Asset_AFDataReference_GetValue_1.htm public override AFValue GetValue(object context, object timeContext, AFAttributeList inputAttributes, AFValues inputValues) { // Important to note that the order of inputValues matches the order of inputAttributes. // Note that timeContext is an object. // We need to examine it further in order to resolve it to an AFTime. var time = ToAFTime(timeContext); AFValue measurement = null; AFValue low = null; AFValue high = null; AFValue lowlow = null; AFValue highhigh = null; // https://techsupport.osisoft.com/Documentation/PI-AF-SDK/html/P_OSIsoft_AF_Asset_AFAttribute_Trait.htm // https://techsupport.osisoft.com/Documentation/PI-AF-SDK/html/T_OSIsoft_AF_Asset_AFAttributeTrait.htm for (var i = 0; i < inputAttributes.Count; i++) { if (i == 0) { measurement = inputValues[i]; } else if (inputAttributes[i].Trait == AFAttributeTrait.LimitLo) { low = inputValues[i]; } else if (inputAttributes[i].Trait == AFAttributeTrait.LimitHi) { high = inputValues[i]; } else if (inputAttributes[i].Trait == AFAttributeTrait.LimitLoLo) { lowlow = inputValues[i]; } else if (inputAttributes[i].Trait == AFAttributeTrait.LimitHiHi) { highhigh = inputValues[i]; } } // Remember any of the passed AFValues could be null if the limit trait is not defined. // This is a fact of life and reflects the many possibilities within a given process unit. return(Calculation(time, measurement , low , high , lowlow , highhigh)); }
public override AFValue GetValue(object context, object timeContext, AFAttributeList inputAttributes, AFValues inputValues) { // Evaluate AFTime timestamp = AFTime.MinValue; if (configString == null) { configString = String.Empty; } //StringBuilder sb = new StringBuilder(); string sValue = "No Data"; int decValue; string hexValue; int binValue; //string[] sValue; //sValue = new string[] { "N/A" }; string[] subStrings = configString.Split(';'); try { if (subStrings.Length > 2) { return(new AFValue("Too many arguments in the Config String property", timestamp, null, AFValueStatus.Bad)); } else { if (subStrings[0].StartsWith("\"")) { return(new AFValue("First argument must be a valid AF attribute", timestamp, null, AFValueStatus.Bad)); } else if (subStrings[0] != String.Empty) { if (inputValues != null) { if (subStrings[1] != String.Empty) { if (Int32.Parse(subStrings[1]) == 1) { // 1= Conversion from Hex to Bin binValue = Convert.ToInt32(subStrings[0], 2); sValue = binValue.ToString("X"); } else if (Int32.Parse(subStrings[1]) == 2) { // 2= Conversion from Hex to Dec decValue = Convert.ToInt32(subStrings[0], 16); sValue = decValue.ToString("X"); } else if (Int32.Parse(subStrings[1]) == 3) { // 3= Conversion from Bin to Hex ; } else if (Int32.Parse(subStrings[1]) == 4) { // 4= Conversion from Bin to Dec ; } else if (Int32.Parse(subStrings[1]) == 5) { // 5= Conversion from Dec to Hex hexValue = subStrings[0].ToString("X"); sValue = hexValue; } else if (Int32.Parse(subStrings[1]) == 6) { // 6= Conversion from Dec to Bin ; } else { return(new AFValue("Missing/Wrong argument for the convertion type (integer from 1 to 6)", timestamp, null, AFValueStatus.Bad)); } } /* if (myStringArray.Length > myArrayIndex) * sValue = myStringArray[myArrayIndex]; * else * return new AFValue("N/A", timestamp, null, AFValueStatus.Good);*/ else { return(new AFValue("Missing/Wrong argument for the convertion type (integer from 1 to 6)", timestamp, null, AFValueStatus.Bad)); } //sValue = myStringArray[0]; } else { return(new AFValue("Invalid data sent to GetValue", timestamp, null, AFValueStatus.Bad)); } } } // should be returning effective date as absolute minimum if (timestamp.IsEmpty && Attribute != null) { if (Attribute.Element is IAFVersionable) { timestamp = ((IAFVersionable)Attribute.Element).Version.EffectiveDate; } else if (Attribute.Element is AFEventFrame) { timestamp = ((AFEventFrame)Attribute.Element).StartTime; } } else if (timestamp.IsEmpty && timeContext is AFTime) { timestamp = (AFTime)timeContext; } return(new AFValue(sValue, timestamp)); } catch (Exception e) { return(new AFValue(string.Format("An error occurred: ", e.Message), timestamp)); throw; } }
public static AFValue GetNextRecordedValue(PIPoint tag, AFTime startTime, int lookAhead = 100) { AFValues values = tag.RecordedValuesByCount(startTime, lookAhead, forward: true, boundaryType: AFBoundaryType.Inside, filterExpression: null, includeFilteredValues: false); return(values.OrderBy(value => value.Timestamp).ToList()[0]); }
public override AFValue GetValue(object context, object timeContext, AFAttributeList inputAttributes, AFValues inputValues) { if (timeContext == null && inputAttributes == null) throw new ArgumentNullException("Time context and/or input attributes cannot be null"); AFTimeRange timeRange; try { timeRange = (AFTimeRange) timeContext; } catch (InvalidCastException) { throw new InvalidCastException("Cannot cast timeContext to AFTimeRange"); } IList<AFValues> vals = inputAttributes.Data.RecordedValues( timeRange: timeRange, boundaryType: AFBoundaryType.Inside, filterExpression: "", includeFilteredValues: false, pagingConfig: new PIPagingConfiguration(PIPageType.TagCount, 1000)).ToList(); if (vals[0].Count != vals[1].Count) throw new InvalidOperationException("Number of lat/long events do not match"); switch (SummaryType) { case "Distance": return GetDistance(vals, timeRange); case "MaxSpeed": return GetMaxSpeed(vals, timeRange); case "MinSpeed": return GetMinSpeed(vals, timeRange); default: throw new InvalidOperationException("Invalid summary type"); } }
private RouteInfo GetRouteInfo(AFElement element, List<TrackPoint> wayPoints, string activityName) { if (element == null) { PIFitnessLog.Write(TraceEventType.Warning, 0, "AF Element is null"); return null; } try { //update latitude, longitude, and elevation AFAttribute elevationAttribute = element.Elements["Routes"].Attributes["Elevation"]; AFAttribute latitudeAttribute = element.Elements["Routes"].Attributes["Latitude"]; AFAttribute longitudeAttribute = element.Elements["Routes"].Attributes["Longitude"]; AFValues listElevationValues = new AFValues(); AFValues listLatitudeValues = new AFValues(); AFValues listLongitudeValues = new AFValues(); foreach (TrackPoint point in wayPoints) { AFTime timestamp = new AFTime(point.Time); listElevationValues.Add(new AFValue(elevationAttribute, point.Elevation, timestamp)); listLatitudeValues.Add(new AFValue(latitudeAttribute, point.Latitude, timestamp)); listLongitudeValues.Add(new AFValue(longitudeAttribute, point.Longitude, timestamp)); } //now update the activity tag AFAttribute rkActivityAttribute = element.Elements["Routes"].Attributes["Activity"]; DateTime temp_time = (from pt in wayPoints orderby pt.Time ascending select pt.Time).FirstOrDefault(); AFValues listActivityValues = new AFValues(); listActivityValues.Add(new AFValue(rkActivityAttribute, activityName, temp_time)); temp_time = (from pt in wayPoints orderby pt.Time descending select pt.Time).FirstOrDefault(); temp_time = temp_time.AddSeconds((double)1.0); //increment by one second listActivityValues.Add(new AFValue(rkActivityAttribute, "Idle", temp_time)); //package all the results IList<AFValues> listAFValues = new List<AFValues>(); listAFValues.Add(listElevationValues); listAFValues.Add(listLatitudeValues); listAFValues.Add(listLongitudeValues); listAFValues.Add(listActivityValues); // get the EF info AFTime start = listLatitudeValues[0].Timestamp; AFTime end = listLatitudeValues[listLatitudeValues.Count - 1].Timestamp; string displayedTime = start.UtcTime.ToString(); string efName = string.Format("{0} - {1} - {2}", element.Name, activityName, displayedTime); return new RouteInfo { Element = element, Values = listAFValues, ActivityName = activityName, UniqueName = efName, UserName = element.Name, StartTime = start, EndTime = end }; } catch (Exception ex) { PIFitnessLog.Write(TraceEventType.Error, 0, ex); return null; } }
// Return latest value if timeContext is null, otherwise return latest value before a specific time public override AFValue GetValue(object context, object timeContext, AFAttributeList inputAttributes, AFValues inputValues) { AFValue currentVal = new AFValue(); DateTime time; if (timeContext != null) { time = ((AFTime)timeContext).LocalTime; } else { time = DateTime.Now; } using (SqlDataReader reader = SQLHelper.GetSQLData(SQLName, DBName, TableName, DateTime.MinValue, time)) { if (reader.Read()) { currentVal.Timestamp = AFTime.Parse(reader["pi_time"].ToString()); currentVal.Value = reader["pi_value"]; } } return currentVal; }
public override AFValue GetValue(object context, object timeContext, AFAttributeList inputAttributes, AFValues inputValues) { if (!fChecked) { CheckConfig(); } try { // Note that timeContext is an object. // We need to examine it further in order to resolve it to an AFTime. AFTime time; if (timeContext is AFTime) { time = (AFTime)timeContext; } else if (timeContext is AFTimeRange) { var timeRange = (AFTimeRange)timeContext; time = (Attribute.Element is AFEventFrame) ? timeRange.StartTime : timeRange.EndTime; } else { time = AFTime.NowInWholeSeconds; } // Important to note that the order of inputValues matches the order of inputAttributes. if (inputAttributes == null || inputAttributes.Count == 0) { throw new ArgumentException("No input attributes"); } if (inputValues == null || inputValues.Count == 0) { throw new ArgumentException(Resources.ERR_NoInputValues); } if (TimestampType == "Attribute") { if (inputValues.Count > 1) { AFValue tsVal = inputValues[1]; object objVal = tsVal.Value; if (objVal != null) { if (Extensions.IsDateTimeVal(objVal)) { time = new AFTime(objVal); } else { throw new ApplicationException(string.Format("Timestamp attribute must be datetime type {0}", objVal.ToString())); } } else { throw new ApplicationException("Timestamp value is null"); } } else { throw new ApplicationException(string.Format("Input value not found (#{0}", 2)); } } if (inputAttributes.Count > 0) { AFValue inVal = inputAttributes[0].GetValue(time); if (inVal == null) { throw new ApplicationException("Input value is null"); } else { AFEnumerationValue enumValue = inVal.Value as AFEnumerationValue; if (enumValue != null && enumValue.Value == 248) { // Attempting to handle an error when the output value is 248 instead of the NoData state return(AFValue.CreateSystemStateValue(Attribute, AFSystemStateCode.NoData, time)); } else { return(new AFValue(Attribute, inVal.Value, inVal.Timestamp, Attribute.DefaultUOM)); } } } else { throw new ApplicationException(string.Format("Input attribute not found (#{0}", 1)); } } catch (Exception) { UnloadParameters(); throw; } }
public override AFValue GetValue(object context, object timeContext, AFAttributeList inputAttributes, AFValues inputValues) { if (!fChecked) { CheckConfig(); } try { // Note that timeContext is an object. // We need to examine it further in order to resolve it to an AFTime. AFTime time; if (timeContext is AFTime) { time = (AFTime)timeContext; } else if (timeContext is AFTimeRange) { var timeRange = (AFTimeRange)timeContext; time = (Attribute.Element is AFEventFrame) ? timeRange.StartTime : timeRange.EndTime; } else { time = AFTime.NowInWholeSeconds; } // Important to note that the order of inputValues matches the order of inputAttributes. AFValue result = Calculate(time, inputAttributes, inputValues); return(result); } catch (Exception) { UnloadParameters(); throw; } }
/// <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); }
private static AFValues GenerateValueSequence(AFAttribute attribute, AFTime start, AFTime end, AFTimeSpan interval) { float zero = 100.0F; float span = 360.0F; AFValues values = new AFValues(); AFTime timestamp = start; Random rnd = new Random((int)DateTime.Now.Ticks % 86400); int idx = 1; while (timestamp <= end) { values.Add(new AFValue(attribute, zero + (float)rnd.NextDouble() * span, timestamp)); timestamp = interval.Multiply(start, idx++); } return values; }
public JsonResult LoadGraph(string PlantStartDateTime, string PlantEndDateTime, string SubRefinery) { var sessionObj = Session["SessionBO"] as UserModel; if (sessionObj != null) { string PlantStartDateTime1 = PlantStartDateTime; string PlantEndDateTime1 = PlantEndDateTime; BOMDetails objBOMDetails = new BOMDetails(); AFLocaleIndependentFormatProvider myTimeZone = new AFLocaleIndependentFormatProvider(); // DateTime StartDate = Convert.ToDateTime(PlantStartDateTime1); // DateTime EndDate = Convert.ToDateTime(PlantEndDateTime1); DateTime StartDate = Convert.ToDateTime(PlantStartDateTime1, System.Globalization.CultureInfo.CurrentCulture); DateTime EndDate = Convert.ToDateTime(PlantEndDateTime1, System.Globalization.CultureInfo.CurrentCulture); PIPoint feedInTag; PIPoint feedOutTag; AFValues feedInVal; AFValues feedOutVal; AFValues filteredfeedInVal = new AFValues(); AFValues filteredoutInVal = new AFValues(); try { PIServerDetails piServerDetails = new PIServerDetails(); PISystems myPISystems = new PISystems(); PISystem mypiSystem = myPISystems[piServerDetails.PIServerName]; PIServer myPiServer = PIServer.FindPIServer(mypiSystem, piServerDetails.PIServerName); NetworkCredential Credentials = new NetworkCredential(piServerDetails.UserName, piServerDetails.Password); mypiSystem.Connect(Credentials); StartDate = StartDate.AddMinutes(-330); AFTime sAFTime = new AFTime(StartDate); //DateTime endDT = Convert.ToDateTime(szDTend); EndDate = EndDate.AddMinutes(-330); AFTime eAFTime = new AFTime(EndDate); AFTimeRange GraphTimeRange = new AFTimeRange(sAFTime, eAFTime); // mypiSystem.Connect(Credentials); objBOMDetails = objBOMDetails.getFeedInFeedOutTag(SubRefinery); feedInTag = PIPoint.FindPIPoint(myPiServer, objBOMDetails.feedInTag); feedInVal = feedInTag.RecordedValues(GraphTimeRange, 0, null, true, 0); foreach (AFValue val in feedInVal) { if (val.IsGood) { filteredfeedInVal.Add(val); } else { val.Value = 0; filteredfeedInVal.Add(val); } } feedOutTag = PIPoint.FindPIPoint(myPiServer, objBOMDetails.feedOutTag); feedOutVal = feedOutTag.RecordedValues(GraphTimeRange, 0, null, true, 0); foreach (AFValue val in feedOutVal) { if (val.IsGood) { filteredoutInVal.Add(val); } else { val.Value = 0; filteredoutInVal.Add(val); } } int inLenArray = filteredfeedInVal.Count; object[] feedInValArr = new object[inLenArray]; DateTime[] feedInDateArr = new DateTime[inLenArray]; AFValueStatus[] feedInValStatus = new AFValueStatus[inLenArray]; filteredfeedInVal.GetValueArrays(out feedInValArr, out feedInDateArr, out feedInValStatus); int outLenArray = feedOutVal.Count; object[] feedOutValArr = new object[outLenArray]; DateTime[] feedOutDateArr = new DateTime[outLenArray]; AFValueStatus[] feedOutValStatus = new AFValueStatus[outLenArray]; filteredoutInVal.GetValueArrays(out feedOutValArr, out feedOutDateArr, out feedOutValStatus); List <KeyValuePair <string, double> > fInlist = new List <KeyValuePair <string, double> >(); List <KeyValuePair <string, double> > fOutlist = new List <KeyValuePair <string, double> >(); // double[] fInDateValdouble = new double[inLenArray]; double[] fOutDateVal = new double[outLenArray]; double[] fInDateVal = new double[inLenArray]; for (int i = 0; i < feedInValArr.Length; i++) { //string fIn = feedInValArr[i].ToString(); double fint = Convert.ToInt32(feedInValArr[i]); if (fint == 0.0) { fInDateVal[i] = -99999; } else if (fint < 0.0) { fInDateVal[i] = -99999; } else { fInDateVal[i] = Math.Round(Convert.ToDouble(feedInValArr[i]), 2); } } string[] fInDateArr = new string[inLenArray]; for (int i = 0; i < feedInDateArr.Length; i++) { fInDateArr[i] = feedInDateArr[i].ToString("MM-dd-yyyy HH:mm:ss"); var element = new KeyValuePair <string, double>(fInDateArr[i], fInDateVal[i]); fInlist.Add(element); } string[] fOutDateArr = new string[outLenArray]; for (int i = 0; i < feedOutDateArr.Length; i++) //feedOutDateArr { //string fOut = feedOutValArr[i].ToString(); //fOutDateArr double fout = Convert.ToInt32(feedOutValArr[i]); if (fout == 0.0) { fOutDateVal[i] = -99999; } else if (fout < 0.0) { fOutDateVal[i] = -99999; } else { fOutDateVal[i] = Math.Round(Convert.ToDouble(feedOutValArr[i]), 2); } } // string[] fOutDateArr = new string[inLenArray]; for (int i = 0; i < feedOutDateArr.Length; i++) { fOutDateArr[i] = feedOutDateArr[i].ToString("MM-dd-yyyy HH:mm:ss"); var element1 = new KeyValuePair <string, double>(fOutDateArr[i], fOutDateVal[i]); fOutlist.Add(element1); } Dictionary <string, List <KeyValuePair <string, double> > > dec = new Dictionary <string, List <KeyValuePair <string, double> > >(); dec.Add("feedIn", fInlist); dec.Add("feedOut", fOutlist); JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer(); // string json = javaScriptSerializer.Serialize(feedInDateArr); JsonResult js = Json(new { value = dec }, JsonRequestBehavior.AllowGet); return(js); // return Json(new { value = dec }, JsonRequestBehavior.AllowGet); } catch (Exception e) { return(Json(new { value = "Exception Occured" }, JsonRequestBehavior.AllowGet)); } } else { return(Json(new { status = false }, JsonRequestBehavior.AllowGet)); } }
/// <summary> /// /// </summary> /// <param name="inputValues"></param> /// <param name="defaultUOM"></param> /// <param name="comparisonValue"></param> /// <param name="comparisonOperator"></param> /// <returns></returns> public AFValue Count(AFValues inputValues, UOM defaultUOM, string comparisonValue, string comparisonOperator) { AFTime time = new AFTime(); time = inputValues[0].Timestamp; try { long _count = 0; double dComparisonValue; if (Double.TryParse(comparisonValue, out dComparisonValue)) { foreach (AFValue inputVal in inputValues) { if (inputVal.IsGood && inputVal != null) { double dCurrVal; // make sure we do all operations in same UOM, if applicable if (inputVal.UOM != null && defaultUOM != null && inputVal.UOM != defaultUOM) { dCurrVal = defaultUOM.Convert(inputVal.Value, inputVal.UOM); } else { dCurrVal = Convert.ToDouble(inputVal.Value); } switch (comparisonOperator) { case "LT": if (dCurrVal < dComparisonValue) { _count++; } break; case "LE": if (dCurrVal <= dComparisonValue) { _count++; } break; case "EQ": if (dCurrVal == dComparisonValue) { _count++; } break; case "GE": if (dCurrVal >= dComparisonValue) { _count++; } break; case "GT": if (dCurrVal > dComparisonValue) { _count++; } break; case "NE": if (dCurrVal != dComparisonValue) { _count++; } break; case "Is Good": if (inputVal.IsGood) { _count++; } break; case "Is Bad": if (!inputVal.IsGood) { _count++; } break; default: break; } } } } else { // comparison value is not numeric, only valid options should be equality or inequality, and value quality foreach (AFValue inputVal in inputValues) { if (inputVal.IsGood && inputVal != null) { switch (comparisonOperator) { case "EQ": if (String.Compare(inputVal.ToString(), comparisonValue, false) == 0) { _count++; } break; case "NE": if (String.Compare(inputVal.ToString(), comparisonValue, false) != 0) { _count++; } break; case "Is Good": if (inputVal.IsGood) { _count++; } break; case "Is Bad": if (!inputVal.IsGood) { _count++; } break; default: break; } } } } return(new AFValue(_count, time)); //return new AFValue(_count, (AFTime)DateTime.Now); } catch { return(new AFValue(Double.NaN, (AFTime)DateTime.Now, null, AFValueStatus.Bad)); } }
// Return all values (converted to AFValues) over a specific time interval public override AFValues GetValues(object context, AFTimeRange timeRange, int numberOfValues, AFAttributeList inputAttributes, AFValues[] inputValues) { AFValues values = new AFValues(); DateTime startTime = timeRange.StartTime.LocalTime; DateTime endTime = timeRange.EndTime.LocalTime; using (SqlDataReader reader = SQLHelper.GetSQLData(SQLName, DBName, TableName, startTime, endTime)) { while (reader.Read()) { AFValue newVal = new AFValue(); newVal.Timestamp = AFTime.Parse(reader["pi_time"].ToString()); newVal.Value = reader["pi_value"]; values.Add(newVal); } } return values; }
public override AFValue GetValue(object context, object timeContext, AFAttributeList inputAttributes, AFValues inputValues) { if (timeContext == null && inputAttributes == null) { throw new ArgumentNullException("Time context and/or input attributes cannot be null"); } AFTimeRange timeRange; try { timeRange = (AFTimeRange)timeContext; } catch (InvalidCastException) { throw new InvalidCastException("Cannot cast timeContext to AFTimeRange"); } IList <AFValues> vals = inputAttributes.Data.RecordedValues( timeRange: timeRange, boundaryType: AFBoundaryType.Inside, filterExpression: "", includeFilteredValues: false, pagingConfig: new PIPagingConfiguration(PIPageType.TagCount, 1000)).ToList(); if (vals[0].Count != vals[1].Count) { throw new InvalidOperationException("Number of lat/long events do not match"); } switch (SummaryType) { case "Distance": return(GetDistance(vals, timeRange)); case "MaxSpeed": return(GetMaxSpeed(vals, timeRange)); case "MinSpeed": return(GetMinSpeed(vals, timeRange)); default: throw new InvalidOperationException("Invalid summary type"); } }
public override AFValue GetValue(object context, object timeContext, AFAttributeList inputAttributes, AFValues inputValues) { if (!fChecked) { CheckConfig(); } try { AFTime time; if (timeContext is AFTime) { time = (AFTime)timeContext; } else if (timeContext is AFTimeRange) { var timeRange = (AFTimeRange)timeContext; time = (Attribute.Element is AFEventFrame) ? timeRange.StartTime : timeRange.EndTime; } else { time = AFTime.NowInWholeSeconds; } AFValue result = Calculate(time, inputAttributes, inputValues); return(result); } catch (Exception) { UnloadParameters(); fChecked = false; throw; } }
// Return latest value if timeContext is null, otherwise return latest value before a specific time public override AFValue GetValue(object context, object timeContext, AFAttributeList inputAttributes, AFValues inputValues) { AFValue currentVal = new AFValue(); DateTime time; if (timeContext != null) { time = ((AFTime)timeContext).LocalTime; } else { time = DateTime.Now; } using (SqlDataReader reader = SQLHelper.GetSQLData(SQLName, DBName, TableName, DateTime.MinValue, time)) { if (reader.Read()) { currentVal.Timestamp = AFTime.Parse(reader["pi_time"].ToString()); currentVal.Value = reader["pi_value"]; } } return(currentVal); }
static int Main(string[] args) { var options = new Options(); var errors = new List <Error>(); var result = Parser.Default.ParseArguments <Options>(args); result.WithParsed(opts => options = opts).WithNotParsed(errs => errors = errs.ToList()); if (errors.Any()) { foreach (var error in errors) { Console.WriteLine(error.Tag); } return(1); } NameValueCollection appSettings = ConfigurationManager.AppSettings; string accountId = appSettings["accountId"]; string namespaceId = appSettings["namespaceId"]; string clusterAddress = appSettings["address"]; string ingressServiceUrl = clusterAddress + @"/api/omf"; // Use a client secret, retrieved from the OSIsoft Cloud Services portal for your account, to // create a SecurityHandler used to authenticate this app. string resource = appSettings["resource"]; string clientId = appSettings["clientId"]; string clientSecret = appSettings["clientSecret"]; var securityHandler = new SdsSecurityHandler(resource, accountId, clientId, clientSecret); // Create a client to manage OSIsoft Cloud Services Ingress resources. using (var managementClient = new IngressManagementClient(clusterAddress, accountId, securityHandler)) { // Connect to a PI server and select PI points for which to move data to OCS. var piServerName = appSettings["PIDataArchive"]; var piServer = new PIServers()[piServerName]; var points = PIPoint.FindPIPoints(piServer, options.TagMask).ToList(); if (!points.Any()) { Console.WriteLine($"No PI points found matching the tagMask query!"); return(1); } // Create OCS data ingress objects. string publisherName = appSettings["publisherName"]; string topicName = appSettings["topicName"]; string subscriptionName = appSettings["subscriptionName"]; Console.WriteLine("Setting up OSIsoft Cloud Services OMF ingress objects."); string publisherId = managementClient.GetOrCreatePublisherAsync(publisherName).GetAwaiter().GetResult(); string producerToken = managementClient.GetOrCreateToken(publisherId).GetAwaiter().GetResult(); string topicId = managementClient.GetOrCreateTopic(topicName, publisherId).GetAwaiter().GetResult(); string subscriptionId = managementClient.GetOrCreateSubscription(subscriptionName, topicId, namespaceId).GetAwaiter().GetResult(); // Each PI point type will be written to an OSIsoft Cloud Services(OCS) SDSStream. // The structure of each stream is defined by an OCS SDSType. We create this SDSType // by posting an OSIsoft Message Format(OMF) type message to OCS. // PI point value types need to translate to OCS SDSTypes. We create a limited number // of SDSTypes in OCS and then map PI point value types to those SDSTypes. // A mapping between PI point value types and the Ids of the SDSType that represents // them in OCS is shown below. Dictionary <OmfTypeCode, string> typeIdsByOmfType = new Dictionary <OmfTypeCode, string>(); typeIdsByOmfType.Add(OmfTypeCode.Number, "numberValueAndTimestamp"); typeIdsByOmfType.Add(OmfTypeCode.Integer, "integerValueAndTimestamp"); typeIdsByOmfType.Add(OmfTypeCode.String, "stringValueAndTimestamp"); typeIdsByOmfType.Add(OmfTypeCode.Time, "timeValueAndTimestamp"); typeIdsByOmfType.Add(OmfTypeCode.ByteArray, "byteArrayValueAndTimestamp"); using (var client = new IngressClient(ingressServiceUrl, producerToken) { UseCompression = true }) { // Create and send OMF Type messages. Console.WriteLine("Creating basic types in OCS to represent the format of PI points."); List <OmfType> types = GetOmfTypes(typeIdsByOmfType); var omfTypeMessageContent = new OmfTypeMessageContent() { Types = types }; client.SendMessageAsync(omfTypeMessageContent.ToByteArray(), MessageType.Type, MessageAction.Create).GetAwaiter().GetResult(); // Generate containers for each of the point with the correct OMF message type. List <OmfContainer> containers = GetOmfContainers(points, typeIdsByOmfType); if (options.WriteMode == Options.DataWriteMode.clearExistingData) { // Deleting the OMF container deletes the underlying SDSStream and its data. Console.WriteLine("Deleting OMF containers corresponding to the selected PI points that existed before the sample was run."); var omfContainerMessageContent = new OmfContainerMessageContent() { Containers = containers }; client.SendMessageAsync(omfContainerMessageContent.ToByteArray(), MessageType.Container, MessageAction.Delete).GetAwaiter().GetResult(); } Console.WriteLine("Creating corresponding containers for the PI points whose data will be written to OCS."); // OSIsoft Cloud Services' OMF Ingress sets a size limit on the request accepted by its external endpoint. We may need to split, or chunk, // containers into multiple OMF messages sent to the endpoint. for (int chunkStartIndex = 0; chunkStartIndex < containers.Count; chunkStartIndex += MaxChunkSize) { int numberOfContainersToSendInThisChunk = Math.Min(containers.Count - chunkStartIndex, MaxChunkSize); var containersToSendInThisChunk = containers.GetRange(chunkStartIndex, numberOfContainersToSendInThisChunk).ToList(); var omfContainerMessageContent = new OmfContainerMessageContent() { Containers = containersToSendInThisChunk }; client.SendMessageAsync(omfContainerMessageContent.ToByteArray(), MessageType.Container, MessageAction.Create).GetAwaiter().GetResult(); } // Write data from each PI point to a SDSStream. foreach (PIPoint point in points) { Console.WriteLine($"Writing PI point data for point {point.Name} to OCS."); string containerId = GetContainerId(point); AFValues values = point.RecordedValues(new AFTimeRange(options.StartTime, options.EndTime), AFBoundaryType.Inside, null, true); // OSIsoft Cloud Services' OMF Ingress sets a size limit on the request accepted by its external endpoint. We may need to split, or chunk, // events into multiple OMF messages sent to the endpoint. for (int chunkStartIndex = 0; chunkStartIndex < values.Count; chunkStartIndex += MaxChunkSize) { int numberOfEventsToReadForThisChunk = Math.Min(values.Count - chunkStartIndex, MaxChunkSize); // If there are multiple events at a single timestamp for the PI point, the most recently added event will be written to OCS. List <AFValue> distinctValuesInChunk = values.GetRange(chunkStartIndex, numberOfEventsToReadForThisChunk).GroupBy(value => value.Timestamp).Select(valuesAtTimestamp => valuesAtTimestamp.Last()).ToList(); List <PIData> piDataEvents = GetPIData(distinctValuesInChunk, ToOmfTypeCode(point.PointType)); OmfDataMessageContent omfDataMessageContent = new OmfDataMessageContent(containerId, piDataEvents); Console.WriteLine($"Sending PI point data from index {distinctValuesInChunk.First().Timestamp} to index {distinctValuesInChunk.Last().Timestamp} to OCS ({distinctValuesInChunk.Count} values)."); client.SendMessageAsync(omfDataMessageContent.ToByteArray(), MessageType.Data, MessageAction.Create).GetAwaiter().GetResult(); } } } // Delete OCS data ingress objects. if (options.DeleteIngressObjects) { Console.WriteLine($"Deleting subscription with Id {subscriptionId}."); managementClient.DeleteSubscription(subscriptionId).GetAwaiter().GetResult(); Console.WriteLine($"Deleting topic with Id {topicId}."); managementClient.DeleteTopicAsync(topicId).GetAwaiter().GetResult(); Console.WriteLine($"Deleting publisher with Id {publisherId}."); managementClient.DeletePublisherAsync(publisherId).GetAwaiter().GetResult(); } } return(0); }
/// <summary> /// Runs a constant loop to pull data from PI /// </summary> private void QueryData() { DateTime currentTime = StartTimeConstraint; if (currentTime == DateTime.MinValue) // handle real-time IAON session { currentTime = DateTime.UtcNow; } while (currentTime <= StopTimeConstraint) { try { DateTime endTime = currentTime.AddSeconds(m_queryTimeSpan); if (endTime <= DateTime.UtcNow) { DateTime localCurrentTime = currentTime.ToLocalTime(); DateTime localEndTime = endTime.ToLocalTime(); List <IMeasurement> measToAdd = new List <IMeasurement>(); foreach (PIPoint point in m_points) { AFValues values = point.RecordedValues(new AFTimeRange(new AFTime(localCurrentTime), new AFTime(localEndTime)), AFBoundaryType.Inside, null, false); foreach (AFValue value in values) { Measurement measurement = new Measurement(); measurement.Key = m_tagKeyMap[point.Name]; measurement.Value = Convert.ToDouble(value.Value); measurement.Timestamp = value.Timestamp.UtcTime; measToAdd.Add(measurement); } } if (measToAdd.Any()) { lock (m_measurements) { foreach (IMeasurement meas in measToAdd) { m_measurements.Add(meas); m_processedMeasurements++; } } } currentTime = endTime; m_queryTime = currentTime; } } catch (ThreadAbortException) { throw; } catch (Exception e) { OnProcessException(e); } Thread.Sleep(33); } }
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(); }
// 2 shifts (2), 3 shifts (3), Unknown (0), Day (-1), Month (-2), Year (-3) public override AFValue GetValue(object context, object timeContext, AFAttributeList inputAttributes, AFValues inputValues) { AFTime time; if (timeContext is AFTime) { time = (AFTime)timeContext; } else if (timeContext is AFTimeRange) { var timeRange = (AFTimeRange)timeContext; time = (Attribute.Element is AFEventFrame) ? timeRange.StartTime : timeRange.EndTime; } else if (timeContext is DateTime) { time = new AFTime((DateTime)timeContext); } else { time = AFTime.NowInWholeSeconds; } int shiftMode = SRHelper.TryGetShiftMode(fShiftMode); if (shiftMode == 0) { try { var attr = AFAttribute.FindAttribute(fShiftMode, Attribute); if (attr == null) { throw new ArgumentException(string.Format(Resources.ERR_AttributeHasNotBeenFound, ShiftMode)); } else { object val = attr.GetValue().Value; if (SRHelper.IsIntVal(val)) { shiftMode = (int)SRHelper.ConvertToType(val, TypeCode.Int32); } else { shiftMode = 0; } } } catch { shiftMode = 0; } } if (shiftMode == 0) { throw new ArgumentException(Resources.ERR_SourceAttributeMustBeAnIntegerType); } DateTime localTime = time.LocalTime; string[] wsParams; if (shiftMode < 0) { wsParams = SRHelper.GetWorkMacroParams(localTime, shiftMode, fStartOffset); } else { wsParams = SRHelper.GetWorkShiftParams(localTime, shiftMode, fStartOffset); } wsParams[3] = SRHelper.GetPITimeStampStr(localTime); return(new AFValue(base.Attribute, wsParams, time, Attribute.DefaultUOM)); }
private static void WriteSummaryItem(AFValues summaryitems) { Console.WriteLine(" First total for {0}: {1}", summaryitems.Attribute.Name, AFValueToString(summaryitems[0])); }
public override AFValue GetValue(object context, object timeContext, AFAttributeList inputAttributes, AFValues inputValues) { if (!fChecked) { CheckConfig(); } try { AFTime time; if (timeContext is AFTime) { time = (AFTime)timeContext; } else if (timeContext is AFTimeRange) { var timeRange = (AFTimeRange)timeContext; time = (Attribute.Element is AFEventFrame) ? timeRange.StartTime : timeRange.EndTime; } else { time = AFTime.NowInWholeSeconds; } string timeOffset = string.IsNullOrEmpty(fTimeOffset) ? "*" : fTimeOffset; int result = 0; try { var fileInfo = new FileInfo(fFilePath); if (fileInfo.Length != 0) { // exists if (timeOffset == "*") { result = 1; } else { AFTime xtime = AFTime.Parse(timeOffset); result = (fileInfo.LastWriteTime >= xtime.LocalTime) ? 2 : 1; } } } catch (FileNotFoundException ex) { result = -1; } return(new AFValue(base.Attribute, result, time, Attribute.DefaultUOM)); } catch (Exception) { UnloadParameters(); fChecked = false; throw; } }
private AFValue Calculate(AFValues inputValues) { MethodEnum method; if (!Enum.TryParse(ConvertMethod, out method)) { throw new ArgumentException(Resources.ERR_NoBitSpecified); } if (inputValues == null || inputValues.Count == 0) { throw new ArgumentException(Resources.ERR_NoInputValues); } AFValue inVal = inputValues[0]; AFDatabase db = inVal.Attribute.Database; if (db == null) { throw new ArgumentException("No db found"); } object objVal = inVal.Value; if (inVal.IsGood && objVal != null) { if (TransformerCore.IsNumericVal(objVal)) { AFValue newVal; switch (method) { default: case MethodEnum.None: newVal = new AFValue(objVal, inVal.Timestamp, inVal.UOM); break; case MethodEnum.Simple: var targetUOMAttrS = AFAttribute.FindAttribute("UOM", Attribute); newVal = Convert(inVal, db, targetUOMAttrS); break; case MethodEnum.Full: var sourceUOMAttr = AFAttribute.FindAttribute("UOM", inVal.Attribute); newVal = Convert(inVal, db, sourceUOMAttr); var targetUOMAttrF = AFAttribute.FindAttribute("UOM", Attribute); newVal = Convert(newVal, db, targetUOMAttrF); break; } return(newVal); } else { throw new ArgumentException(Resources.ERR_SourceAttributeMustBeAnIntegerType); } } else { return(AFValue.CreateSystemStateValue(Attribute, AFSystemStateCode.BadInput, inVal.Timestamp)); } }
private AFValues GetActiveHours(IList<AFValues> valsList, FitbitUser fitbitUser) { try { IEnumerable<AFValues> filteredValues = from vals in valsList where vals != null select vals; AFValues veryActiveValues = QueryAFValuesByName(filteredValues, "Minutes very active"); AFValues fairlyActiveValues = QueryAFValuesByName(filteredValues, "Minutes fairly active"); AFValues lightlyActiveValues = QueryAFValuesByName(filteredValues, "Minutes lightly active"); var combined = from valsActive in veryActiveValues join valsFairly in fairlyActiveValues on valsActive.Timestamp equals valsFairly.Timestamp join valsLightly in lightlyActiveValues on valsFairly.Timestamp equals valsLightly.Timestamp select new AFValue((Convert.ToSingle(valsActive.Value) + Convert.ToSingle(valsFairly.Value) + Convert.ToSingle(valsLightly.Value)) / 60, valsActive.Timestamp); AFValues values = new AFValues(); foreach (var val in combined) { values.Add(val); } values.Attribute = fitbitUser.UserElement.Elements["Fitbit"].Attributes["Active hours"]; return values; } catch (Exception ex) { return null; } }