public int ValidateTagNames(string pitag1, string pitag2, string pitag3, string pitag4, string pitag5, int NumTags) { try { MyTag1 = PIPoint.FindPIPoint(MyPiServer, pitag1); MyAtrbTag1 = AFAttribute.FindAttribute(@"\\" + PIServerName + @"\" + MyTag1.Name, null); if (NumTags > 1) { MyTag2 = PIPoint.FindPIPoint(MyPiServer, pitag2); MyAtrbTag2 = AFAttribute.FindAttribute(@"\\" + PIServerName + @"\" + MyTag2.Name, null); } if (NumTags > 2) { MyTag3 = PIPoint.FindPIPoint(MyPiServer, pitag3); MyAtrbTag3 = AFAttribute.FindAttribute(@"\\" + PIServerName + @"\" + MyTag3.Name, null); } if (NumTags > 3) { MyTag4 = PIPoint.FindPIPoint(MyPiServer, pitag4); MyAtrbTag4 = AFAttribute.FindAttribute(@"\\" + PIServerName + @"\" + MyTag4.Name, null); } if (NumTags > 4) { MyTag5 = PIPoint.FindPIPoint(MyPiServer, pitag5); MyAtrbTag5 = AFAttribute.FindAttribute(@"\\" + PIServerName + @"\" + MyTag5.Name, null); } } catch { return(1); } return(0); }
// Writing Data to the AFServer /// <summary> /// Writes to AF, and checks in the element. /// </summary> /// <param name="element"> AFElement being written to.</param> /// <param name="attribute"> AFAttribute being changed.</param> /// <param name="value"> The new value being imported.</param> public static void writeToAF(AFElement element, AFAttribute attribute, double value) { AFValue input = new AFValue(attribute, value, AFTime.Now); attribute.SetValue(input); element.CheckIn(); }
static void PrintInterpolated(AFDatabase database, string meterName, string startTime, string endTime, TimeSpan timeSpan) { Console.WriteLine(string.Format("Print Interpolated Values - Meter: {0}, Start: {1}, End: {2}", meterName, startTime, endTime)); AFAttribute attr = AFAttribute.FindAttribute(@"\Meters\" + meterName + @"|Energy Usage", database); AFTime start = new AFTime(startTime); AFTime end = new AFTime(endTime); AFTimeRange timeRange = new AFTimeRange(start, end); AFTimeSpan interval = new AFTimeSpan(timeSpan); AFValues vals = attr.Data.InterpolatedValues( timeRange: timeRange, interval: interval, desiredUOM: null, filterExpression: null, includeFilteredValues: false); foreach (AFValue val in vals) { Console.WriteLine("Timestamp (Local): {0}, Value: {1:0.00} {2}", val.Timestamp.LocalTime, val.Value, val?.UOM.Abbreviation); } Console.WriteLine(); }
private void configurationTreeView_AfterSelect(object sender, TreeViewEventArgs e) { AFTreeNode node = (AFTreeNode)e.Node; AFElement selectedCalculation = (AFElement)node.AFObject; if (!selectedCalculation.IsRoot) { calculationName.Text = selectedCalculation.Name; CalculationPreference preference = CalculationPreference.CalculationPreferenceFromJSON((string)selectedCalculation.Attributes["configuration"].GetValue().Value); queryTextBox.Text = preference.eventFrameQuery; Dictionary <AFAttributeTrait, string> limitCalculations = preference.getTraitDictionary(); foreach (AFAttributeTrait trait in AFAttributeTrait.AllLimits) { ComboBox comboBox = (ComboBox)panel1.Controls[trait.Name]; comboBox.Text = "None"; } foreach (KeyValuePair <AFAttributeTrait, string> pair in limitCalculations) { ComboBox comboBox = (ComboBox)panel1.Controls[pair.Key.Name]; comboBox.Text = pair.Value; } offsetSetting.Text = preference.offset.ToString(); AFAttribute sensor = AFAttribute.FindAttribute(preference.sensorPath, db); afDatabasePicker.AFDatabase = sensor.Database; afTreeView.AFRoot = sensor.Database.Elements; afTreeView.AFSelect(sensor, db, preference.sensorPath); afTreeView.SelectedNode.EnsureVisible(); afTreeView.Focus(); } }
private void btnUpdateData_Click(object sender, EventArgs e) { foreach (DataGridViewRow row in dataGrid.Rows) { try { if (row.Cells["CheckBox"].Value != null && (bool)row.Cells["CheckBox"].Value == true) { // Connect PIServerAFSDK PIServer _PIServerAFSDK = piPointTagSearchPage1.PIServer; // Find PIPoint PIPoint piPoint = PIPoint.FindPIPoint(_PIServerAFSDK, (string)row.Cells["tag"].Value); AFAttribute afAttribute = new AFAttribute(piPoint); AFValue afValue = new AFValue(afAttribute, row.Cells["Value"].Value, AFTime.Parse(row.Cells["Timestamp"].Value.ToString())); if (row.Cells["Annotation"].Value.ToString() != string.Empty) { afValue.SetAnnotation(row.Cells["Annotation"].Value.ToString()); } piPoint.UpdateValue(afValue, AFUpdateOption.Replace, AFBufferOption.BufferIfPossible); } } catch (Exception ex) { row.Cells["Message"].Value = ex.Message; } } dataGrid.Refresh(); }
public static void PrintHistorical(AFDatabase database, string meterName, string startTime, string endTime) { if (database == null) { throw new ArgumentNullException(nameof(database)); } Console.WriteLine(string.Format("Print Historical Values - Meter: {0}, Start: {1}, End: {2}", meterName, startTime, endTime)); AFAttribute attr = AFAttribute.FindAttribute(@"\Meters\" + meterName + @"|Energy Usage", database); AFTime start = new AFTime(startTime); AFTime end = new AFTime(endTime); AFTimeRange timeRange = new AFTimeRange(start, end); AFValues vals = attr.Data.RecordedValues( timeRange: timeRange, boundaryType: AFBoundaryType.Inside, desiredUOM: database.PISystem.UOMDatabase.UOMs["kilojoule"], filterExpression: null, includeFilteredValues: false); foreach (AFValue val in vals) { Console.WriteLine("Timestamp (UTC): {0}, Value (kJ): {1}", val.Timestamp.UtcTime, val.Value); } Console.WriteLine(); }
static AFAttributeList GetAttributes(AFDatabase database) { int startIndex = 0; int pageSize = 1000; int totalCount; AFAttributeList attrList = new AFAttributeList(); do { AFAttributeList results = AFAttribute.FindElementAttributes( database: database, searchRoot: null, nameFilter: null, elemCategory: null, elemTemplate: database.ElementTemplates["MeterBasic"], elemType: AFElementType.Any, attrNameFilter: "Energy Usage", attrCategory: null, attrType: TypeCode.Empty, searchFullHierarchy: true, sortField: AFSortField.Name, sortOrder: AFSortOrder.Ascending, startIndex: startIndex, maxCount: pageSize, totalCount: out totalCount); attrList.AddRange(results); startIndex += pageSize; } while (startIndex < totalCount); return(attrList); }
private AFAttributeList LoadParameters() { if (Attribute == null || Attribute.Element == null) { throw new ApplicationException("Attribute and/or element is null"); } var paramAttributes = new AFAttributeList(); if (!string.IsNullOrEmpty(fPointAttribute)) { AFDatabase db = Attribute.Database; if (db == null) { throw new ApplicationException("No database found"); } // find Attribute's object by it name from parameters var ptAttr = AFAttribute.FindAttribute(fPointAttribute, Attribute); if (ptAttr == null) { throw new ApplicationException(string.Format(Resources.ERR_AttributeHasNotBeenFound, fPointAttribute)); } paramAttributes.Add(ptAttr); } else { throw new ApplicationException("Name of PI Point attribute is null or empty"); } return paramAttributes; }
public LimitCalculation(CalculationPreference preference, string calculationName) { this.calculationName = calculationName; try { logger.Info($"Starting calculations for {calculationName}"); string afattributepath = preference.sensorPath; string eventQuery = preference.eventFrameQuery; calculationsToPerform = preference.getTraitDictionary(); offset = preference.offset; this.preference = preference; sensor = AFAttribute.FindAttribute(afattributepath, null); pisystem = sensor.PISystem; afdatabase = sensor.Database; foreach (KeyValuePair <AFAttributeTrait, string> pair in calculationsToPerform) { bounds[pair.Key] = new AFValues(); AFAttribute possibleAttribute = sensor.GetAttributeByTrait(pair.Key); boundAttributes[pair.Key] = possibleAttribute; logger.Info($"Will perform calculation for limit: {pair.Key}"); if (possibleAttribute == null) { logger.Error($"{calculationName}: The limit {pair.Key} is not defined yet is used."); } } eventFrameQuery = new AFEventFrameSearch(afdatabase, "eventFrameSearch", eventQuery); } catch (System.Exception e) { logger.Error($"{calculationName} the following error occured: {e.Message}"); } logger.Info($"{calculationName}: Doing the initial run"); InitialRun(); }
public static void ConfirmValuesAtRangeEndpoints(this AFValues values, AFAttribute Attribute, AFTimeRange TimeRange) { AFTime StartTime = TimeRange.StartTime.ToPIPrecision(); AFTime EndTime = TimeRange.EndTime.ToPIPrecision(); // Don't merely add a StartTime and EndTime. // First you must check to make sure they aren't already there. // Corner case: where EndTime == StartTime. if (values.Count == 0) { values.Add(CreateBadValue(Attribute, StartTime)); } else if (values[0].Timestamp > StartTime) { // This will probably never happen but in extremely rare // case that it does, set a dummy value. values.Insert(0, CreateBadValue(Attribute, StartTime)); } var last = values[values.Count - 1]; if (last.Timestamp < EndTime) { // Carry the last value to the end of the range, including its status, etc. AFValue val = new AFValue(last); // Except we want to change its Timestamp val.Timestamp = EndTime; values.Add(val); } }
static void CreateFeederElements(AFDatabase database) { AFElementTemplate template = database.ElementTemplates["FeederTemplate"]; AFElement feeders = database.Elements["Feeders"]; if (template == null || feeders == null) { return; } if (feeders.Elements.Contains("Feeder001")) { return; } AFElement feeder001 = feeders.Elements.Add("Feeder001", template); AFAttribute city = feeder001.Attributes["City"]; if (city != null) { city.SetValue(new AFValue("London")); } AFAttribute power = feeder001.Attributes["Power"]; power.ConfigString = @"%@\Configuration|PIDataArchiveName%\SINUSOID"; if (database.IsDirty) { database.CheckIn(); } }
static void CreateFeederElements(AFDatabase database) { AFElementTemplate template = database.ElementTemplates["FeederTemplate"]; AFElement feeders = database.Elements["Feeders"]; if (template == null || feeders == null) { return; } if (feeders.Elements.Contains("Feeder001")) { return; } AFElement feeder001 = feeders.Elements.Add("Feeder001", template); AFAttribute district = feeder001.Attributes["District"]; if (district != null) { district.SetValue(new AFValue("Hogwarts")); } AFAttribute power = feeder001.Attributes["Power"]; power.ConfigString = @"\\PISRV01\SINUSOID"; database.CheckIn(); }
public AFInterpolatedAttributeRetrievalClass( AFAttribute attribute, AFTimeRange timeRange, AFTimeSpan timeSpan, string outputDirectory, PIRandomFunctionsUtil.TimeResolution timeResolution, int numYears, int pageSize = 200000, Logger logger = null) { this.attribute = attribute; this.tag = attribute.PIPoint; if (tag == null) { throw new ArgumentException($"attribute PIPoint must be not null"); } this.desiredUOM = attribute.DefaultUOM; this.timeRange = timeRange; this.timeSpan = timeSpan; this.outputDirectory = outputDirectory; this.timeResolution = timeResolution; this.numYears = numYears; this.pageSize = pageSize; this.nextStartTime = timeRange.StartTime; if (logger == null) { logger = new Logger(); } this.logger = logger; }
public LimitCalculation(CalculationPreference preference) { this.preference = preference; string afattributepath = preference.sensorPath; string eventQuery = preference.eventFrameQuery; calculationsToPerform = preference.getTraitDictionary(); foreach (KeyValuePair <AFAttributeTrait, string> pair in calculationsToPerform) { bounds[pair.Key] = new AFValues(); } sensor = AFAttribute.FindAttribute(afattributepath, null); pisystem = sensor.PISystem; afdatabse = sensor.Database; foreach (KeyValuePair <AFAttributeTrait, string> pair in calculationsToPerform) { boundAttributes[pair.Key] = sensor.GetAttributeByTrait(pair.Key); } eventFrameQuery = new AFEventFrameSearch(afdatabse, "eventFrameSearch", eventQuery); List <AFSearchToken> tokens = eventFrameQuery.Tokens.ToList(); tokens.RemoveAll(t => t.Filter == AFSearchFilter.InProgress || t.Filter == AFSearchFilter.Start || t.Filter == AFSearchFilter.End); timeLessQuery = new AFEventFrameSearch(afdatabse, "AllEventFrames", tokens); InitialRun(); }
private AFAttributeList GetAttributes() { int startIndex = 0; int totalCount; int pageSize = 1000; AFAttributeList attrList = new AFAttributeList(); do { AFAttributeList attrListTemp = AFAttribute.FindElementAttributes( database: AttributeTemplate.Database, searchRoot: null, nameFilter: "*", elemCategory: null, elemTemplate: AttributeTemplate.ElementTemplate, elemType: AFElementType.Any, attrNameFilter: AttributeTemplate.Name, attrCategory: null, attrType: TypeCode.Empty, searchFullHierarchy: true, sortField: AFSortField.Name, sortOrder: AFSortOrder.Ascending, startIndex: startIndex, maxCount: pageSize, totalCount: out totalCount); attrList.AddRange(attrListTemp); startIndex += pageSize; } while (startIndex < totalCount); return(attrList); }
static void PrintHourlyAverage(AFDatabase database, string meterName, string startTime, string endTime) { Console.WriteLine(string.Format("Print Hourly Average - Meter: {0}, Start: {1}, End: {2}", meterName, startTime, endTime)); AFAttribute attr = AFAttribute.FindAttribute(@"\Meters\" + meterName + @"|Energy Usage", database); AFTime start = new AFTime(startTime); AFTime end = new AFTime(endTime); AFTimeRange timeRange = new AFTimeRange(start, end); IDictionary <AFSummaryTypes, AFValues> vals = attr.Data.Summaries( timeRange: timeRange, summaryDuration: new AFTimeSpan(TimeSpan.FromHours(1)), summaryType: AFSummaryTypes.Average, calcBasis: AFCalculationBasis.TimeWeighted, timeType: AFTimestampCalculation.EarliestTime); foreach (AFValue val in vals[AFSummaryTypes.Average]) { Console.WriteLine("Timestamp (Local): {0:yyyy-MM-dd HH\\h}, Value: {1:0.00} {2}", val.Timestamp.LocalTime, val.Value, val?.UOM.Abbreviation); } Console.WriteLine(); }
private void btnInspectTag_Click(object sender, EventArgs e) { AFAttribute selectedAttribute = afTreeView2.AFSelection as AFAttribute; //Change tab to Data Archive tab tabControl1.SelectedIndex = 1; //Prefill tagname field tbEnterTag.Text = lbTagName.Text; //Prefill timerange piStartTime.Text = "*-12h"; piEndTime.Text = "*"; //Prefill server picker piServerPicker1.Text = piSystemPicker1.AFSelection.ToString(); //Perform button actions btnGetTagInfo.PerformClick(); try { btnGetTagData.PerformClick(); } catch (System.InvalidOperationException) { //Sometimes data does not correctly prefill on Data Archive tab (not sure why) and //so this catch operation attempts to fillout the data again. tbEnterTag.Text = lbTagName.Text; piStartTime.Text = "*-12h"; piEndTime.Text = "*"; piServerPicker1.Text = piSystemPicker1.AFSelection.ToString(); btnGetTagInfo.PerformClick(); btnGetTagData.PerformClick(); } }
static void FindBuildingInfo(AFDatabase database, string templateName) { Console.WriteLine("Find Building Info: {0}", templateName); AFElementTemplate elemTemp = database.ElementTemplates[templateName]; AFCategory buildingInfoCat = database.AttributeCategories["Building Info"]; AFElement root = database.Elements["Wizarding World"]; AFNamedCollectionList <AFAttribute> foundAttributes = AFAttribute.FindElementAttributes( database: database, searchRoot: root, nameFilter: "*", elemCategory: null, elemTemplate: elemTemp, elemType: AFElementType.Any, attrNameFilter: "*", attrCategory: buildingInfoCat, attrType: TypeCode.Empty, searchFullHierarchy: true, sortField: AFSortField.Name, sortOrder: AFSortOrder.Ascending, maxCount: 100); Console.WriteLine("Found {0} attributes.", foundAttributes.Count); Console.WriteLine(); }
// Import to AF /// <summary> /// Gets value from Matlab and writes it to AF. /// </summary> /// <remarks> Will not write, if the Attribute is read-only. A Matlab Variable Name must be input.</remarks> /// <param name="path"> The path to the Element to search with.</param> /// <param name="workspaceVariableName">The variable name in Matlab being used.</param> /// <param name="AFName">The attribute name in AF being written to.</param> public void ImportToAF(string path, string workspaceVariableName, string AFName) { object val = null; double dbVal; //LOGIC: A variable name must be entered. try { MatlabAccess.GetWorkspaceData(workspaceVariableName, "base", out val); } catch { mainForm.Status("Couldn't find the variable in the Matlab Workspace"); } List <string> searchPaths = new List <string>() { path }; AFKeyedResults <string, AFElement> results = AFElement.FindElementsByPath(searchPaths, null); AFElement Element = results[path]; AFAttribute Attribute = Element.Attributes[AFName]; double.TryParse(val.ToString(), out dbVal); try { AFAccess.writeToAF(Element, Attribute, dbVal); } catch { mainForm.Status("Cannot Write to this Attribute"); } }
public override AFAttributeList GetInputs(object context) { // Loop through the config string, looking for attributes // The Config string is semicolon separated list of attributes and strings // Strings must be enclosed in " " // Will also handle standard AF substitions (%ELEMENT%, %TIME%, etc.) AFAttributeList paramAttributes = null; string[] subStrings = ConfigString.Split(';'); string s = subStrings[0].Trim(); String subst = SubstituteParameters(s, this, context, null); if (!String.IsNullOrEmpty(subst)) { // Get attribute will resolve attribute references AFAttribute attr = GetAttribute(subst); if (attr == null || attr.IsDeleted) { throw new ApplicationException(String.Format("Unknown attribute '{0}'", s)); } if (paramAttributes == null) { paramAttributes = new AFAttributeList(); } paramAttributes.Add(attr); } return(paramAttributes); }
static void storeAllAttribute(AFAttribute attr, DataTable dt) { addNameAndDescription(dt, attr, attr); foreach (AFAttribute attribute in attr.Attributes) { storeAllAttribute(attribute, dt); } }
public void GetCurrentObjectPaths() { int pathIndex = Path.IndexOf('|'); String elemetPath = Path.Substring(0, pathIndex); String attributePath = Path.Substring(pathIndex + 1, Path.Length - pathIndex - 1); currElement = Database.Elements[elemetPath]; currAttribute = currElement.Attributes[attributePath]; }
private void ImplicitConnection() { PISystems piSystems = new PISystems(); PISystem piSystem = piSystems["<AFSERVER>"]; // At this point, no connection is made. AFAttribute afAttribute = AFAttribute.FindAttribute(@"NuGreen\NuGreen\Houston|Environment", piSystem); // Now a connection is made by first data access. }
public GraphQlAfAttribute(AFAttribute aAfAttribute, Field afAttributesField = null, Field tsPlotValuesField = null) { AFValue aAfValue = aAfAttribute.GetValue(); name = aAfAttribute.Name; ThisAfAttribute = aAfAttribute; value = aAfValue.Value?.ToString(); uom = aAfAttribute.DisplayUOM?.Abbreviation; if (aAfAttribute.DataReference?.Name == "PI Point") { timeStamp = aAfValue.Timestamp.UtcTime.ToString("yyyy-MM-ddTHH:mm:ssZ"); } if (afAttributesField != null) { var afAttributesNameFilterStrings = GraphQlHelpers.GetArgumentStrings(afAttributesField, "nameFilter"); var afAttributesChildField = GraphQlHelpers.GetFieldFromSelectionSet(afAttributesField, "afAttributes"); var returnAttributesObject = new ConcurrentBag <GraphQlAfAttribute>(); var afAttributeList = aAfAttribute.Attributes.ToList <AFAttribute>(); Parallel.ForEach(afAttributeList, aAfChildAttribute => { if (afAttributesNameFilterStrings.Count == 0 || afAttributesNameFilterStrings.Contains(aAfChildAttribute.Name)) { returnAttributesObject.Add(new GraphQlAfAttribute(aAfAttribute, afAttributesChildField)); } }); afAttributes = returnAttributesObject.OrderBy(x => x.name).ToList(); } if (tsPlotValuesField != null) { if (aAfAttribute.DataReference?.Name == "PI Point") { var plotDensity = GraphQlHelpers.GetArgumentDouble(tsPlotValuesField, "plotDensity"); var startDateTime = GraphQlHelpers.GetArgumentDateTime(tsPlotValuesField, "startDateTime"); var endDateTime = GraphQlHelpers.GetArgumentDateTime(tsPlotValuesField, "endDateTime"); var timeRange = new AFTimeRange(startDateTime, endDateTime); AFValues asdf = ThisAfAttribute.GetValues(timeRange, (int)plotDensity, null); var returnObject = new ConcurrentBag <GraphQlTsValue>(); foreach (AFValue aAfTsValue in asdf) { returnObject.Add(new GraphQlTsValue() { timeStamp = aAfTsValue.Timestamp.UtcTime.ToString("yyyy-MM-ddTHH:mm:ssZ"), value = aAfTsValue.Value.ToString() }); } tsPlotValues = returnObject.OrderBy(x => x.timeStamp).ToList(); } } }
static void PrintInterpolated(AFDatabase database, string meterName, string start, string end, TimeSpan interval) { AFTime startTime = new AFTime(start); AFTime endTime = new AFTime(end); AFTimeRange timeRange = new AFTimeRange(startTime, endTime); AFAttribute att = AFAttribute.FindAttribute(@"\Meters\" + meterName + @"|Energy Usage", database); AFTimeSpan intervalNew = new AFTimeSpan(interval); AFValues values = att.Data.InterpolatedValues(timeRange: timeRange, interval: intervalNew, desiredUOM: null, filterExpression: null, includeFilteredValues: false); }
private void cbUOM_SelectedIndexChanged(object sender, EventArgs e) { UOM selectedUOM = cbUOM.SelectedItem as UOM; AFAttribute selectedAttribute = afTreeView2.AFSelection as AFAttribute; //Clear list of values lbData.Items.Clear(); //Convert current value to new UoM lbCurrentVal.Text = selectedAttribute.GetValue().Convert(selectedUOM).ToString(); lbTimestamp.Text = selectedAttribute.GetValue().Timestamp.ToString(); //Clear chart afDataChart.Series["dataSeries"].Points.Clear(); if (lbData.Items != null) { //Get time-range AFTime startTime = new AFTime(afStartDate.Text); AFTime endTime = new AFTime(afEndTime.Text); AFTimeRange timeRange = new AFTimeRange(startTime, endTime); AFValues vals; if (selectedAttribute != null) { //Convert to new Uom if required if (selectedAttribute.DefaultUOM != null) { vals = selectedAttribute.GetValues(timeRange, 0, null).Convert(selectedUOM); } else { vals = selectedAttribute.GetValues(timeRange, 0, null); } //Fill out list and chart foreach (AFValue val in vals) { string s = String.Format("{0} \t {1} {2}", val.Timestamp.LocalTime, val.Value, selectedUOM != null ? selectedUOM.Abbreviation : null); lbData.Items.Add(s); try { afDataChart.Series["dataSeries"].Points.AddXY(val.Timestamp.ToString(), val.Value); } catch (System.ArgumentException) { continue; } } } } }
public void Init() { PIWebApiClient client = PIWebApiClientGenerator.GenerateInstance(); instance = client.Configuration; configElement = AFObject.FindObject(Constants.PIWEBAPI_CONFIGURATION_ELEMENT_PATH) as AFElement; corsExpHeaders = configElement.Attributes[Constants.PIWEBAPI_CONFIGURATION_CORSEXPHEADERS].GetValue().Value.ToString(); corsMethods = configElement.Attributes[Constants.PIWEBAPI_CONFIGURATION_CORSMETHODS].GetValue().Value.ToString(); scanSearchInterval = configElement.Attributes[Constants.PIWEBAPI_CONFIGURATION_CORSEACHSCANINTERVALS].GetValue().ValueAsInt32(); corsMethodsAttribute = configElement.Attributes[Constants.PIWEBAPI_CONFIGURATION_CORSMETHODS]; }
private AFAttributeList CreateBrandNewInputList(object context) { // PRO TIP: // See comments in GetInputs where you want to avoid _cachedInputAttrs.Add or AddRange. // For thread safety, use a brand new list that is local to this method. // Start with a brand new list var brandNewList = new AFAttributeList(); AFAttribute measurement = null; // First and foremost we need a measurement attribute, which is the centerpoint to compare against limits. if (UseParentAttribute) { // https://techsupport.osisoft.com/Documentation/PI-AF-SDK/html/P_OSIsoft_AF_Asset_AFDataReference_Attribute.htm // https://techsupport.osisoft.com/Documentation/PI-AF-SDK/html/P_OSIsoft_AF_Asset_AFAttribute_Parent.htm measurement = Attribute.Parent; if (measurement == null) { throw new Exception("Root-level attribute does not have a parent. You must define 'MeasAttr=something' in the ConfigString."); } } else { // Let's offer some bit of name substitution. // However, the GetInputs method lacks any timeContext, which restricts @value substitution // to current values only. This restriction is fine for static attributes. // https://techsupport.osisoft.com/Documentation/PI-AF-SDK/html/T_OSIsoft_AF_AFNameSubstitutionType.htm var path = SubstituteParameters(_measAttrName, this, context, timeContext: null); // Note that the final fetch of the measurement attribute is *relative* to the current Attribute. // https://techsupport.osisoft.com/Documentation/PI-AF-SDK/html/P_OSIsoft_AF_Asset_AFAttribute_Attributes.htm measurement = Attribute.Attributes[path]; if (measurement == null) { throw new Exception($"MeasAttr '{_measAttrName}' not found. Check your ConfigString."); } } if (!IsNumericType(Type.GetTypeCode(measurement.Type))) { throw new Exception($"MeasAttr does not have a numeric Type."); } // If the list will have any items, the measurement will always be at Index 0. brandNewList.Add(measurement); // Let the CDR automatically fetch the associated limits. // These could come back in any order, plus some or all may be missing! // Geez, doesn't that make it fun and challenging! // https://techsupport.osisoft.com/Documentation/PI-AF-SDK/html/M_OSIsoft_AF_Asset_AFAttribute_GetAttributesByTrait.htm brandNewList.AddRange(measurement.GetAttributesByTrait(AllowedTraits)); return(brandNewList); }
public void CreateAttribute() { AFElement element = new AFElement(); string name = "Test Element 1"; element.Name = name; Assert.Equals(element.Name, name); string desc = "Lazy PI Unit Test Element"; element.Description = desc; Assert.Equals(element.Description, desc); Console.WriteLine("Test element creation."); Assert.IsTrue(_db.CreateElement(element), "Assert creation passed"); element = _db.Elements[element.Name]; //Check that the the element can be found through the AFDB Assert.IsNotNull(element, "Check AFDB element collection for new element."); AFAttribute attr = new AFAttribute(); attr.Name = "Test Attribute"; attr.Description = "Created by WebAPI tests"; element.Attributes.Add(attr); element.CheckIn(); Assert.Equals(element.Attributes.Count, 1); attr = element.Attributes[attr.Name]; Assert.IsNotNull(attr); Assert.IsNotNull(attr.ID); Assert.IsNotNull(attr.Name); Assert.IsNotNull(attr.Description); Assert.IsNotNull(attr.Path); string val = "Test string"; // Test set and get of AFValue object attr.SetValue(new AFValue(val)); AFValue valObj = attr.GetValue(); Assert.Equals(valObj.Value, val); element.Delete(); Assert.IsTrue(element.IsDeleted); element.CheckIn(); Assert.IsNull(AFElement.Find(_conn, element.WebID)); }
public bool TryGetTimeSeries(string name, out AFAttribute timeseries) { if (!PIPoint.TryFindPIPoint(server, name, out PIPoint point)) { timeseries = null; return(false); } timeseries = new AFAttribute(point); return(true); }
private void ShowAttribute(AFAttribute attr) { WriteAttributeDepthString(); Console.WriteLine("-Name:{0}", attr.Name); WriteAttributeDepthString(); Console.WriteLine("Value:{0}", attr.GetValue()); WriteAttributeDepthString(); Console.WriteLine("Type: {0}", attr.Type); if (attr.DataReference != null) { WriteAttributeDepthString(); Console.WriteLine("DataReference: {0}", attr.DataReference.Name); WriteAttributeDepthString(); Console.WriteLine("DataReference ConfigString: {0}", attr.ConfigString); } }
private static AFValue GenerateValue(AFAttribute attribute, Random rnd, float zero, float span, AFTime timestamp) { return new AFValue(attribute, zero + (float)rnd.NextDouble() * span, timestamp); }
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; }
/// <summary> /// Compose a PIPointInfo object based on an AF Attribute /// </summary> /// <param name="attribute"></param> /// <returns></returns> private static PIPointInfo ParseConfigString(AFAttribute attribute) { string configStringInput = attribute.ConfigString; var configStringSplits = configStringInput.Split(new Char[] { '\\', ';' }, StringSplitOptions.RemoveEmptyEntries); string PIDataArchiveName = configStringSplits[0]; PIDataArchiveName = PIDataArchiveName.Split(new Char[] { '?' }, StringSplitOptions.RemoveEmptyEntries)[0]; string pointNameFormat = configStringSplits[1]; string pointName = GetSubstitutedPIPointName(pointNameFormat, attribute.Element, attribute.Name); int ci = configStringInput.IndexOf(';'); IDictionary<string, object> pointAttributes = ci != -1 ? GetPointAttributes(configStringInput.Substring(ci + 1)) : null; return new PIPointInfo { PointName = pointName, PIDataArchiveName = PIDataArchiveName, PointAttributes = pointAttributes }; }