public void CreateAndDeletePointTest() { // Construct a unique PI Point name same as the test name, followed by the current timestamp. // If the PI Point deletion doesn't go through, identifying the test that created the Point gets easy. string pointName = $"PointCreationAndDeletionTest{AFTime.Now}"; try { // Create a PI Point Output.WriteLine($"Create PI Point [{pointName}]."); PIPoint point = Fixture.PIServer.CreatePIPoint(pointName); // Assert that the PI Point creation was successful Assert.True(PIPoint.FindPIPoint(Fixture.PIServer, pointName) != null, $"Could not find PI Point [{pointName}] on Data Archive [{Fixture.PIServer.Name}] after creation."); } finally { // Delete the PI Point to cleanup Fixture.DeletePIPoints(pointName, Output); // Assert that the PI Point deletion was successful Exception ex = Assert.Throws <PIPointInvalidException>(() => PIPoint.FindPIPoint(Fixture.PIServer, pointName)); Assert.True(ex.Message.Contains("PI Point not found"), $"Expected to get an exception message saying that the [PI Point not found] " + $"when searching for PI Point [{pointName}] after deletion, but the actual message was [{ex.Message}]."); } }
static void Main(string[] args) { PIServers pIServers = new PIServers(); foreach (var server in pIServers) { Console.WriteLine("Server: {0}", server.Name); } PIServer piServer = pIServers.DefaultPIServer; Console.WriteLine("Default connection is: {0}", piServer.Name); piServer.Connect(); // do smth with the pi system // get a pi point var point = PIPoint.FindPIPoint(piServer, "PLCW00321500=S20NDD11BU900:XQ001"); var value = point.CurrentValue(); var timevalue = value.Timestamp; var valuevalue = value.Value; Console.WriteLine("Tag name: {0} and its Value is: {1}, {2}", point.Name, timevalue, valuevalue); var plotValues = point.PlotValues(new AFTimeRange("*-1w", "*"), 10); foreach (var pValue in plotValues) { Console.WriteLine("{0} {1}", pValue.Value, pValue.Timestamp); } piServer.Disconnect(); Console.ReadKey(); }
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); }
private void GetArchive_Click(object sender, EventArgs e) { ValuesListView.Items.Clear(); if (TagList.SelectedIndices.Count < 1) { MessageBox.Show("Please select one tag from list"); return; } string tagname = TagList.SelectedItems[0].Text; TagNameLabel.Text = tagname; PIPoint pt = PIPoint.FindPIPoint(myPIServer, tagname); AFTimeRange timerange = new AFTimeRange(); timerange.StartTime = new AFTime(StartTimeTextBox.Text); timerange.EndTime = new AFTime(EndTimeTextBox.Text); AFValues vals = pt.RecordedValues(timerange, OSIsoft.AF.Data.AFBoundaryType.Inside, "", true); foreach (AFValue val in vals) { string[] displayvalues = new string[2]; displayvalues[0] = val.Timestamp.LocalTime.ToString(); displayvalues[1] = val.Value.ToString(); ListViewItem lvi = new ListViewItem(displayvalues); ValuesListView.Items.Add(lvi); } }
private static void readData(String serverName, Func <String> tagNameSupplier, int[] daysToReadList) { PIServer server = new PIServers() .Where(s => s.Name.Contains(serverName)) .First(); server.Connect(); foreach (int daysToRead in daysToReadList) { Console.Write("[{0} {1}d] ", serverName, daysToRead); Stopwatch roundTripStopwatch = Stopwatch.StartNew(); PIPoint tag = PIPoint.FindPIPoint(server, tagNameSupplier.Invoke()); roundTripStopwatch.Stop(); AFTimeRange timeRange = new AFTimeRange(new AFTime(readStart), new AFTime(readStart.Add(new TimeSpan(daysToRead, 0, 0, 0)))); try { Stopwatch readStopwatch = Stopwatch.StartNew(); AFValues values = tag.RecordedValues(timeRange, AFBoundaryType.Outside, "", true, 0); readStopwatch.Stop(); Console.WriteLine("Read {0:n0} samples in {1:0.000}s (1m samples in {2:0.000}s) EstimatedRoundTripTime: {3}ms", values.Count, readStopwatch.ElapsedMilliseconds / 1000.0, ((double)readStopwatch.ElapsedMilliseconds) / values.Count * 1000.0, roundTripStopwatch.ElapsedMilliseconds); } catch (Exception e) { Console.WriteLine("Exception: {0}", e.ToString()); } } server.Disconnect(); }
/// <summary> /// Retrieves the PI Point history data from the data archive for the specified time range /// </summary> /// <returns> the frame containts the history data generated for the points as matrix</returns> public Object[,] getArchiveValues_new() { List <PIPoint> ptList = new List <PIPoint>(); DateTime starttime = AFTime.Parse("t"); DateTime endtime = AFTime.Parse("t-2d"); AFTimeRange timeRange = AFTimeRange.Parse(starttime.ToString(), endtime.ToString()); var boundaryType = AFBoundaryType.Inside; List <OSIsoft.AF.Asset.AFValues> recordList = new List <OSIsoft.AF.Asset.AFValues>(); ptList.Add(PIPoint.FindPIPoint(piServer, "BA:TEMP.1")); ptList.Add(PIPoint.FindPIPoint(piServer, "BA:CONC.1")); ptList.Add(PIPoint.FindPIPoint(piServer, "BA:LEVEL.1")); ptList.Add(PIPoint.FindPIPoint(piServer, "BA:PHASE.1")); ptList.Add(PIPoint.FindPIPoint(piServer, "BA:ACTIVE.1")); foreach (PIPoint pt in ptList) { recordList.Add(pt.RecordedValues(timeRange, boundaryType, "", false)); } //multi array with mixed objects List <Int32> mxl = new List <Int32>(); mxl.Add(recordList[0].Count); mxl.Add(recordList[1].Count); mxl.Add(recordList[2].Count); mxl.Add(recordList[3].Count); mxl.Add(recordList[4].Count); int mxl_max = mxl.Max(); Object[,] frame = new Object[ptList.Count + 1, mxl_max]; int i = 1; foreach (OSIsoft.AF.Asset.AFValues vals in recordList) { int j = 0; foreach (OSIsoft.AF.Asset.AFValue afval in vals) { if (i < ptList.Count + 1 && j < mxl_max) { if (afval.Timestamp != null) { frame[0, j] = DateTime.Parse(afval.Timestamp.LocalTime.ToString()); } if (afval.Value != null) { frame[i, j] = afval.Value; } j += 1; } } i += 1; } return(frame); }
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 async Task AsyncTask() { IList <PIPoint> list = new List <PIPoint>(); for (int i = 0; i < TagList.SelectedItems.Count; ++i) { string tagname = TagList.SelectedItems[i].Text; PIPoint pt = PIPoint.FindPIPoint(myPIServer, tagname); list.Add(pt); } PIDataPipe pipe = new PIDataPipe(AFDataPipeType.Snapshot); pipe.AddSignups(list); Action asyncJob = () => { while (updateval == 0) { var pipeContents = pipe.GetUpdateEvents(50000); foreach (AFDataPipeEvent pipeEvent in pipeContents) { string[] displayvalues = new string[3]; displayvalues[0] = pipeEvent.Value.PIPoint.Name; displayvalues[1] = pipeEvent.Value.Timestamp.LocalTime.ToString(); displayvalues[2] = pipeEvent.Value.Value.ToString(); ListViewItem lvi = new ListViewItem(displayvalues); UpdListView(lvi); } } }; await Task.Run(asyncJob); }
//Gets the array private void composeArray() { this.aFTimeRange = new AFTimeRange(this.startDateTime, this.endDateTime); //this.interval = new TimeSpan(0, 5, 0); this.span = new AFTimeSpan(this.samplingInterval); foreach (String windNodeTag in windNodePotentialTags) { PIPoint pi_point = PIPoint.FindPIPoint(this.piServer, windNodeTag); //tagList.Add(pi_point.RecordedValues(aFTimeRange, OSIsoft.AF.Data.AFBoundaryType.Inside, "", false).ToString()); AFValues interpolated = pi_point.InterpolatedValues(this.aFTimeRange, this.span, "", false); foreach (AFValue value in interpolated) { String[] temp = { windNodeTag, value.Value.ToString(), value.Timestamp.ToString() }; //Temp 0: Name of Wind Node Tag //Temp 1: Value of the tag //Temp 2: Time Stamp of the tag Console.WriteLine(temp[0] + ", " + temp[1] + ", " + temp[2]); this.valueList.Add(temp); } //this.rtu.setArray(this.valueList); } //this.rtu.sendToRTU(); }
/// <summary> /// Get the PIPoint data, uses AFSDK. /// </summary> /// <param name="MatlabName"> The variable name in Matlab workspace.</param> /// <param name="server"> The name of the server. </param> /// <param name="point"> The name of the Point.</param> /// <param name="start"> The start time of data collection.</param> /// <param name="end"> The end time of data collection.</param> /// <param name="addToListView">true: adds to the LogSystem ListView. (generally true)</param> public static void getPIData(string MatlabName, string server, string point, string start, string end, bool addToListView) { PIServer serv = PIServer.FindPIServer(server); PIPoint piPoint = PIPoint.FindPIPoint(serv, point); string server_database = "'" + server + "'-'PI.Point'"; getData(server_database, point, MatlabName, start, end, piPoint, true); }
public static List <AbstractRetrievePoints> LoadTagClassesRecorded( String inputFilePath, String outputDirectory, String timeResolution, int numYears, int pageSize, PIServer piServer, PISystem piSystem, int numParallelTasks, Logger logger) { var inputLines = LoadInputFile(inputFilePath); List <AbstractRetrievePoints> tagClasses = new List <AbstractRetrievePoints>(); Parallel.ForEach( inputLines, new ParallelOptions { MaxDegreeOfParallelism = numParallelTasks }, (String[] line) => { string tagName = line[0]; string startTimeString = line[1]; string endTimeString = line[2]; PIPoint tag; try { tag = PIPoint.FindPIPoint(piServer, tagName); AFTime startTime = new AFTime(startTimeString); AFTime endTime = new AFTime(endTimeString); AFTimeRange timeRange = new AFTimeRange(startTime, endTime); string startTimeStamp = startTime.UtcTime.ToString("yyyy/MM/dd HH:mm:ss"); string endTimeStamp = endTime.UtcTime.ToString("yyyy/MM/dd HH:mm:ss"); lock (logger) { logger.Log($"{startTimeStamp} : {endTimeStamp}, {tagName}"); } lock (tagClasses) { tagClasses.Add(new PIRecordedPointRetrievalClass( tag, timeRange, outputDirectory, PIRandomFunctionsUtil.ParseTimeResolutionString(timeResolution), numYears, pageSize, logger)); } } catch (Exception e) { logger.Log("Exception: could not FindPiPoint: " + e.ToString()); } }); return(tagClasses); }
public void ImplicitConnection() { PIServers piServers = new PIServers(); PIServer piServer = piServers["PIServerName"]; // At this point, no connection is made. PIPoint piPoint = PIPoint.FindPIPoint(piServer, "sinusoid"); // Now a connection is made by first data access. }
public async IAsyncEnumerable <IFrame> GetData(List <AdaptSignal> signals, DateTime start, DateTime end) { if (m_server is null || !m_server.ConnectionInfo.IsConnected) { ConnectPI(); } PIPointList pointList = new PIPointList(signals.Select(s => PIPoint.FindPIPoint(m_server, s.ID))); long startTicks = start.Ticks; double totalTicks = end.Ticks - startTicks; m_progress = 0.0D; TimeOrderedValueReader reader = new() { Points = pointList, StartTime = start, EndTime = end }; long currentTime = 0; Dictionary <string, ITimeSeriesValue> data = new Dictionary <string, ITimeSeriesValue>(); await foreach (AFValue value in reader.ReadAsync()) { if (value.Value is Exception ex) { throw ex; } if (currentTime != value.Timestamp.UtcTime.Ticks) { yield return(new Frame() { Published = true, Timestamp = currentTime, Measurements = new ConcurrentDictionary <string, ITimeSeriesValue>(data) }); m_progress = (currentTime - startTicks) / totalTicks; data = new Dictionary <string, ITimeSeriesValue>(); currentTime = value.Timestamp.UtcTime.Ticks; } if (data.ContainsKey(value.PIPoint.Name)) { continue; } data.Add(value.PIPoint.Name, new AdaptValue(value.PIPoint.Name, Convert.ToDouble(value.Value), currentTime)); } m_progress = 1.0D; }
public void DAReadWriteTest() { PIServer piServer = Fixture.PIFixture.PIServer; var piPointName = "OSIsoftTestPoint"; var piPointNameEdit = $"{piPointName}2"; // Get Data Archive object from PI Web API to extract its WebId var dataArchiveUrl = $"{Fixture.HomePageUrl}/dataservers?path=\\PIServers[{Settings.PIDataArchive}]"; Output.WriteLine($"Get Data Archive data through Web API using Url [{dataArchiveUrl}]."); var dataArchiveData = JObject.Parse(Fixture.Client.DownloadString(dataArchiveUrl)); // Skip Write/Update portion of test if writes are disabled if (Fixture.DisableWrites) { return; } // Create a test PI Point var createUrl = $"{Fixture.HomePageUrl}/dataservers/{(string)dataArchiveData["WebId"]}/points"; Output.WriteLine($"Create PI Point [{piPointName}] through Web API using Url [{createUrl}]"); Fixture.Client.UploadString(createUrl, "POST", $"{{\"Name\": \"{piPointName}\", \"PointClass\": \"classic\", \"PointType\": \"Float32\"}}"); // Check PI Point exists in DA var point = PIPoint.FindPIPoint(piServer, piPointName); Assert.True(point != null, $"Test PI Point [{piPointName}] was not found in Data Archive."); var location = string.Empty; try { // Extract new PI Point URL off create response headers location = Fixture.Client.ResponseHeaders["Location"]; // Change PI Point name Output.WriteLine($"Change PI Point name from [{piPointName}] to [{piPointNameEdit}]."); Fixture.Client.UploadString(location, "PATCH", $"{{\"Name\": \"{piPointNameEdit}\"}}"); // Check PI Point is renamed in DA point = PIPoint.FindPIPoint(piServer, piPointNameEdit); Assert.True(point != null, $"Test PI Point [{piPointNameEdit}] was not found in Data Archive."); // Request full PI Point object from PI Web API to test read, check name value var piPointData = JObject.Parse(Fixture.Client.DownloadString(location)); Output.WriteLine($"Read PI Point through Web API using Url [{location}]."); Assert.True(string.Equals((string)piPointData["Name"], piPointNameEdit, StringComparison.OrdinalIgnoreCase), $"Test PI Point has incorrect value for Name. Expected: [{piPointNameEdit}], Actual: [{(string)piPointData["Name"]}]"); } finally { // Delete test PI Point Fixture.Client.UploadString(location, "DELETE", string.Empty); } }
public void ExplicitConnection() { PIServers piServers = new PIServers(); PIServer piServer = piServers["PIServerName"]; // At this point, no connection is made. piServer.Connect(); // Now a connection is made by explicit call. PIPoint piPoint = PIPoint.FindPIPoint(piServer, "sinusoid"); }
//GET api/tsops/Point?server={serverName}&point={pointName} public List <string> GetPointConfig([FromUri] string server, [FromUri] string point) { PIServer srv; if (server != null) { try { srv = new PIServers()[server]; srv.Connect(); } catch { List <string> error = new List <string>(); error.Add("Error: Could not connect to PI Data Archive " + server); //Cannot connect to PI Data Archive return(error); } } else { List <string> error = new List <string>(); error.Add("Error: PI Data Archive name is null"); //Server is null return(error); } PIPoint requestedPoint; try { requestedPoint = PIPoint.FindPIPoint(srv, point); //Finds desired PI Point } catch { List <string> error = new List <string>(); error.Add("Error: PI Point " + point + " not found"); //PI Point not found return(error); } IDictionary <string, object> attributes = requestedPoint.GetAttributes(); //Gets all PI Point attributes List <string> attributeList = new List <string>(); attributeList.Add("Server : " + requestedPoint.Server.Name); //Adds the server name to the Result list foreach (KeyValuePair <string, object> pair in attributes) { attributeList.Add(pair.Key + ":" + pair.Value); //Converts Idictionary to List } return(attributeList); }
public void PIPointTest() { PIServer piServer = PIFixture.PIServer; string namePIPointTag = "PIPointTest_Point"; string[] myPtAttributes = { PICommonPointAttributes.Step, PICommonPointAttributes.PointType }; try { // If PI Point exists, delete it PIFixture.RemovePIPointIfExists(namePIPointTag, Output); // Create attribute values for the PI Point var attributeValues = new Dictionary <string, object> { { "pointtype", "float32" }, { "step", 0 }, { "compressing", 0 }, { "excmin", 0 }, { "excmax", 0 }, { "excdev", 0 }, { "excdevpercent", 0 }, { "shutdown", 0 }, }; // Create PI Point Output.WriteLine($"Creating PI Point {namePIPointTag} with custom attributes."); var point = piServer.CreatePIPoint(namePIPointTag, attributeValues); // Update Output.WriteLine($"Confirm PI Point [{namePIPointTag}] was created with correct custom attributes."); var returnedPoint = PIPoint.FindPIPoint(piServer, namePIPointTag); Assert.True(returnedPoint != null, $"Could not find PI Point [{namePIPointTag}] on Data Archive [{piServer}]."); var originalAttributes = returnedPoint.GetAttributes(myPtAttributes); Assert.True(originalAttributes.Count > 0, $"Could not find any attributes for PI Point [{namePIPointTag}]."); Assert.False(Convert.ToBoolean(originalAttributes[PICommonPointAttributes.Step], CultureInfo.InvariantCulture), $"Expected the Step PI Point attribute to be originally false for PI Point [{namePIPointTag}]."); var pointType = originalAttributes[PICommonPointAttributes.PointType].ToString(); Assert.True(pointType.Equals("Float32", StringComparison.OrdinalIgnoreCase), $"Expected the Point Type for PI Point [{namePIPointTag}] to be Float32, was actually [{pointType}]."); Output.WriteLine($"Setting Step PI Point attribute to true for {namePIPointTag}."); returnedPoint.SetAttribute(PICommonPointAttributes.Step, true); returnedPoint.SaveAttributes(new string[] { PICommonPointAttributes.Step }); Assert.True(returnedPoint.Step, $"Expected the Step PI Point attribute to be true for PI Point [{namePIPointTag}] after being set."); } finally { PIFixture.DeletePIPoints(namePIPointTag, Output); } }
public async Task AsyncTask_updateinfo() { IList <PIPointChangeInfo> clist = new List <PIPointChangeInfo>(); Action asyncJobupdateinfo = () => { PIPointChangesCookie cookie = null; while (updateval2 == 0) { if (myPIServer != null) { if (monitval == 0) { monitval = 1; cookie = null; UpdMonitorLabel("Monitoring ON (" + myPIServer.Name + ")"); } if (ReferenceEquals(cookie, null)) { clist = myPIServer.FindChangedPIPoints(int.MaxValue, null, out cookie); } else { clist = myPIServer.FindChangedPIPoints(int.MaxValue, cookie, out cookie); } if (clist != null) { foreach (PIPointChangeInfo change in clist) { //MessageBox.Show(change.ID + " : " + change.Action); string[] displayvalues = new string[3]; if (change.Action.ToString() == "Removed") { displayvalues[0] = change.ID.ToString(); } else { PIPoint mypt = PIPoint.FindPIPoint(myPIServer, change.ID); displayvalues[0] = mypt.Name; } displayvalues[1] = change.Action.ToString(); displayvalues[2] = DateTime.Now.ToString(); ListViewItem lvi = new ListViewItem(displayvalues); UpdListView2(lvi); } } } } }; await Task.Run(asyncJobupdateinfo); }
private void btnGetTagData_Click(object sender, EventArgs e) { //Set timerange AFTime startTime = new AFTime(piStartTime.Text); AFTime endTime = new AFTime(piEndTime.Text); AFTimeRange timeRange = new AFTimeRange(startTime, endTime); //Get tagname string tagname = tbEnterTag.Text; //Get pi server PIServers servers = new PIServers(); PIServer server = servers[piServerPicker1.PIServer.ToString()]; //Get pi point PIPoint point = PIPoint.FindPIPoint(server, tagname); //extract values for tag across timerange AFValues values = point.RecordedValues(timeRange, AFBoundaryType.Inside, null, false, 0); //Get current value and timestamp piCurrentValue.Text = point.CurrentValue().ToString(); piCurrentTimestamp.Text = point.CurrentValue().Timestamp.ToString(); //Clear data chart piDataChart.Series["dataSeries"].Points.Clear(); if (values != null) { foreach (AFValue value in values) { //Write data into list box string output = String.Format("{0} \t {1} {2}", value.Timestamp, value.Value, value.UOM != null ? value.UOM.Abbreviation : null); lbPIData.Items.Add(output); try { //chart data piDataChart.Series["dataSeries"].Points.AddXY(value.Timestamp.ToString(), value.Value); } catch (System.ArgumentException) { continue; } } } }
public void UpdatePointTest() { string pointName = $"UpdatePointTest{AFTime.Now}"; IDictionary <string, object> attributes = new Dictionary <string, object>() { { PICommonPointAttributes.Tag, pointName }, { PICommonPointAttributes.PointType, PIPointType.Float32 }, }; try { // Create a PI Point Output.WriteLine($"Create PI Point [{pointName}]."); PIPoint point = Fixture.PIServer.CreatePIPoint(pointName, attributes); // Assert that the PI Point creation was successful Assert.True(PIPoint.FindPIPoint(Fixture.PIServer, pointName) != null, $"Could not find PI Point [{pointName}] on Data Archive [{Fixture.PIServer.Name}] after creation."); IDictionary <string, object> attributesToEdit = new Dictionary <string, object>() { { PICommonPointAttributes.PointType, PIPointType.String }, }; Output.WriteLine($"Update PI Point [{pointName}] type from Float32 to String."); foreach (var attribute in attributesToEdit) { point.SetAttribute(attribute.Key, attribute.Value); } point.SaveAttributes(); // Refresh the server Fixture.PIServer.Refresh(); // Look for the PI Point var pipoint = PIPoint.FindPIPoint(Fixture.PIServer, pointName); // Assert that the attribute values have changed Assert.True(pipoint.GetAttribute(PICommonPointAttributes.PointType).Equals(PIPointType.String), $"Expected the Point Type of the PI Point [{pointName}] to be a [string], but it was actually [{pipoint.GetAttribute(PICommonPointAttributes.PointType)}]."); } finally { // Delete the PI Point to cleanup Fixture.DeletePIPoints(pointName, Output); } }
public PIValueModel GetPIValue(string piPointName) { PIValueModel returnVal = new PIValueModel(); bool piPointPresent = PIPointExists(piPointName); if (piPointPresent) { PIPoint myPoint = PIPoint.FindPIPoint(_pi, piPointName); AFValue piValue = myPoint.CurrentValue(); returnVal.PointName = piPointName; returnVal.datetime = piValue.Timestamp.ToString(); returnVal.value = piValue.Value.ToString(); } return(returnVal); }
public void RenamePointTest() { // Construct a unique PI Point name string pointName = $"RenamePointTest{AFTime.Now}"; string newName = pointName + "_Renamed"; try { // Create a PI Point Output.WriteLine($"Create PI Point [{pointName}]."); PIPoint point = Fixture.PIServer.CreatePIPoint(pointName); // Assert that the PI Point creation was successful Assert.True(PIPoint.FindPIPoint(Fixture.PIServer, pointName) != null, $"Could not find PI Point [{pointName}] on Data Archive [{Fixture.PIServer.Name}] after creation."); // Change the name of the PI Point IDictionary <string, object> attributesToEdit = new Dictionary <string, object>() { { PICommonPointAttributes.Tag, newName }, }; Output.WriteLine($"Rename PI Point [{pointName}] to [{newName}]."); foreach (var attribute in attributesToEdit) { point.SetAttribute(attribute.Key, attribute.Value); } point.SaveAttributes(); // Refresh the server Fixture.PIServer.Refresh(); // Look for the PI Point with the new name Assert.True(PIPoint.FindPIPoint(Fixture.PIServer, newName) != null, $"Could not find PI Point [{newName}] on Data Archive [{Fixture.PIServer.Name}] after rename from [{pointName}]."); } finally { // Delete the PI Point to cleanup Fixture.DeletePIPoints($"{pointName}*", Output); } }
// GET api/tsops/Snapshot?server={serverName}&point={pointName>} public IEnumerable <string> GetSnapshot([FromUri] string server, [FromUri] string point) { PIServer srv; if (server != null) { try { srv = new PIServers()[server]; srv.Connect(); } catch { List <string> error = new List <string>(); error.Add("Error: Could not connect to PI Data Archive " + server); //Cannot connect to PI Data Archive return(error); } } else { List <string> error = new List <string>(); error.Add("Error: PI Data Archive name is null"); //Server is null return(error); } //Finds PI Point and gets current value try { PIPoint requestedPoint = PIPoint.FindPIPoint(srv, point); //Finds desired PI Point AFValue val = requestedPoint.CurrentValue(); //Gets current value IEnumerable <string> result = new string[] { "Server: " + val.PIPoint.Server, "Point Name : " + val.PIPoint.Name, "Current Value: " + val.Value, "Timestamp: " + val.Timestamp }; return(result); } catch { List <string> error = new List <string>(); error.Add("Error: Could not get current value for " + point); return(error); } }
public override void Run() { try { PiConnectionHelper piConnectionHelper = new PiConnectionHelper(Server); piConnectionHelper.Connect(); PIServer pi = piConnectionHelper.GetPiServer(); PIPoint point = PIPoint.FindPIPoint(pi, Tag); AFValue value = point.CurrentValue(); Logger.InfoFormat("The current value for PI Point {0} is : {1} - {2}", Tag, value.Timestamp, value.Value); } catch (Exception ex) { Logger.Error(ex); } }
private void btnDeleteData_Click(object sender, EventArgs e) { List <int> indexToRemove = new List <int>(); foreach (DataGridViewRow row in dataGrid.Rows) { if (row.Cells["CheckBox"].Value != null && (bool)row.Cells["CheckBox"].Value == true) { try { // 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())); piPoint.UpdateValue(afValue, AFUpdateOption.Remove, AFBufferOption.BufferIfPossible); if (!row.IsNewRow) { indexToRemove.Add(row.Index); } } catch (Exception ex) { row.Cells["Message"].Value = ex.Message; } } } foreach (var index in indexToRemove.OrderByDescending(i => i)) { dataGrid.Rows.RemoveAt(index); } dataGrid.Refresh(); }
public bool AddPIValue(string piPoint, string dateString, string value) { bool piPointPresent = PIPointExists(piPoint); if (piPointPresent) { PIPoint myPoint = PIPoint.FindPIPoint(_pi, piPoint); PIPointType pointType = myPoint.PointType; object val = 0; try { val = ParseValue(pointType.ToString().ToLower(), value); } catch (Exception ex) { return(false); } DateTime dateValue; AFTime afTime; if (DateTime.TryParse(dateString, out dateValue)) { afTime = new AFTime(dateValue); } else { return(false); } AFValue piValue = new AFValue(val, afTime); myPoint.UpdateValue(piValue, AFUpdateOption.InsertNoCompression); return(true); } return(false); }
public void CheckPIPointWritePermissionTest() { using (var piFixture = new PIFixture()) { // Find the target a PI Point string manualInputPoint = @"OSIsoftTests.Region 1.Manual Input"; Output.WriteLine($"Search for PI Point [{manualInputPoint}]."); var point = PIPoint.FindPIPoint(piFixture.PIServer, manualInputPoint); // Prepare the event to be written var eventToWrite = new AFValue((float)Math.PI, (AFTime.Now + TimeSpan.FromSeconds(1)).ToPIPrecision()); // Send the event to be written Output.WriteLine($"Write an event to PI Point [{manualInputPoint}]."); point.UpdateValue(eventToWrite, AFUpdateOption.InsertNoCompression); // Read the current value to verify that the event was written successfully Output.WriteLine($"Verify the event has been sent to PI Point [{manualInputPoint}]."); AssertEventually.True( () => eventToWrite.Equals(point.CurrentValue()), $"Failed to send data to PI Point [{manualInputPoint}] on {piFixture.PIServer.Name}. Please check if the running user has write access to PI Data Archive. " + $"If buffering is configured, make sure PI Buffer Subsystem connects to PI Data Archive with appropriate PI mappings."); } }
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)); } }
public BOMMasterTag CheckIsManualBasedOnValue(string ActualStartDateTime, string ActualEndDateTime, BOMMasterTag objBOMMasterTag1) { DateTime ActualStartDate = Convert.ToDateTime(ActualStartDateTime); DateTime ActualEndDate = Convert.ToDateTime(ActualEndDateTime); BOMMasterTag objBOMMasterTag = new BOMMasterTag(); AFValue strtVal; AFValue endVal; PIPoint strtTag; string exceptionMsg = ""; List <string> lstString = new List <string>(); 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); ActualStartDate = ActualStartDate.AddMinutes(-330); AFTime sAFTime = new AFTime(ActualStartDate); ActualEndDate = ActualEndDate.AddMinutes(-330); AFTime eAFTime = new AFTime(ActualEndDate); mypiSystem.Connect(Credentials); IDictionary <AFSummaryTypes, AFValue> sm = null; IDictionary <AFSummaryTypes, AFValue> smin = null; List <string> lstComponent = new List <string>(); double resultValue = 0; strtTag = PIPoint.FindPIPoint(myPiServer, objBOMMasterTag1.PITag); strtVal = strtTag.RecordedValue(sAFTime, AFRetrievalMode.AtOrAfter); endVal = strtTag.RecordedValue(eAFTime, AFRetrievalMode.AtOrAfter); AFTimeRange graphTimeReange = new AFTimeRange(sAFTime, eAFTime); sm = strtTag.Summary(graphTimeReange, AFSummaryTypes.Maximum, 0, 0); smin = strtTag.Summary(graphTimeReange, AFSummaryTypes.Minimum, 0, 0); AFValue mx = sm[AFSummaryTypes.Maximum]; AFValue mn = smin[AFSummaryTypes.Minimum]; string strtValString = strtVal.Value.ToString(); string endValString = endVal.Value.ToString(); if (endValString.Equals("No Data") || mx.IsGood == false || strtValString.Equals("No Data") || mx.IsGood == false) { resultValue = 00000; objBOMMasterTag1.isManual = true; objBOMMasterTag1.isManualWithTag = true; lstString.Add(objBOMMasterTag1.component); } else { if (Convert.ToDouble(endVal.Value) < Convert.ToDouble(mx.Value)) { try { resultValue = Convert.ToDouble(mx.Value) - Convert.ToDouble(strtVal.Value) + Convert.ToDouble(endVal.Value) - Convert.ToDouble(mn.Value); } catch (Exception e) { objBOMMasterTag1.isManual = true; objBOMMasterTag1.isManualWithTag = true; exceptionMsg = "Bad value from PI Tag"; lstString.Add(objBOMMasterTag1.component); } } else if (Convert.ToDouble(endVal.Value) == Convert.ToDouble(strtVal.Value)) { resultValue = 00000; objBOMMasterTag1.isManual = true; objBOMMasterTag1.isManualWithTag = true; lstString.Add(objBOMMasterTag1.component); } else { resultValue = Convert.ToDouble(endVal.Value) - Convert.ToDouble(strtVal.Value); } // objBOMMasterTag1.quantity = (float)resultValue; } return(objBOMMasterTag1); } catch (Exception e) { return(null); } }
public JsonResult CalculateBill(string ActualStartDateTime, string ActualEndDateTime, string SubRefinery, string isSave_status, string PONO, int IDOCNumber) { var sessionObj = Session["SessionBO"] as UserModel; if (sessionObj != null) { BOMMasterTag objBOMMasterTag = new BOMMasterTag(); AFLocaleIndependentFormatProvider myTimeZone = new AFLocaleIndependentFormatProvider(); DateTime ActualStartDate = Convert.ToDateTime(ActualStartDateTime); DateTime ActualEndDate = Convert.ToDateTime(ActualEndDateTime); AFValue strtVal; AFValue endVal; PIPoint strtTag; string exceptionMsg = ""; try { List <BOMMasterTag> lstBOMMasterTag = new List <BOMMasterTag>(); if (isSave_status == "1") { lstBOMMasterTag = objBOMMasterTag.getIsSavedList(PONO, IDOCNumber); List <string> lslComponent = GetIsManualWithTag(ActualStartDateTime, ActualEndDateTime, SubRefinery, isSave_status, PONO, IDOCNumber); foreach (BOMMasterTag objBOMMasterTag1 in lstBOMMasterTag) { foreach (String component in lslComponent) { if (objBOMMasterTag1.component == component) { objBOMMasterTag1.isManual = true; objBOMMasterTag1.isManualWithTag = true; } } } //List<string> lstComponent1 = new List<string>(); //List<string> lstComponent2 = new List<string>(); //lstBOMMasterTag = objBOMMasterTag.getIsSavedList(PONO, IDOCNumber); //List<string> lslComponent = GetIsManualWithTag(ActualStartDateTime, ActualEndDateTime, SubRefinery, isSave_status, PONO, IDOCNumber); //foreach (BOMMasterTag objBOMMasterTag1 in lstBOMMasterTag) //{ // foreach (String component in lslComponent) { // if (objBOMMasterTag1.component == component) // { // objBOMMasterTag1.isManual = true; // objBOMMasterTag1.isManualWithTag = true; // } // } // lstComponent1.Add(objBOMMasterTag1.component); // lstComponent2.Add(objBOMMasterTag1.BOMCategory); //} //string duplicate = ""; //List<string> NonDuplicateList = new List<string>(); //foreach (string s in lstComponent2) //{ // if (!NonDuplicateList.Contains(s)) // NonDuplicateList.Add(s); // else // duplicate = s; //} //foreach (BOMMasterTag objBOMMasterTag1 in lstBOMMasterTag) //{ // if (duplicate != "") // { // if (objBOMMasterTag1.BOMCategory == "Raw-Material" || objBOMMasterTag1.BOMCategory == "Product") // { // if (duplicate == objBOMMasterTag1.BOMCategory) // { // // lstBOMMasterTag.Remove(objBOMMasterTag1); // objBOMMasterTag1.BOMCategory = "Product"; // } // } // } //} } else { 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); ActualStartDate = ActualStartDate.AddMinutes(-330); AFTime sAFTime = new AFTime(ActualStartDate); ActualEndDate = ActualEndDate.AddMinutes(-330); AFTime eAFTime = new AFTime(ActualEndDate); mypiSystem.Connect(Credentials); //Tag Mapping with BOMMaster. List <BOMMasterTag> lstBOMMasterTag1 = objBOMMasterTag.getMasterBOM(SubRefinery, PONO, IDOCNumber); IDictionary <AFSummaryTypes, AFValue> sm = null; IDictionary <AFSummaryTypes, AFValue> smin = null; List <string> lstComponent = new List <string>(); foreach (BOMMasterTag objBOMMasterTag1 in lstBOMMasterTag1) { lstComponent.Add(objBOMMasterTag1.component); } //string duplicate = ""; //List<string> NonDuplicateList = new List<string>(); //foreach (string s in lstComponent) //{ // if (!NonDuplicateList.Contains(s)) // NonDuplicateList.Add(s); // else // duplicate = s; //} foreach (BOMMasterTag objBOMMasterTag1 in lstBOMMasterTag1) { if (objBOMMasterTag1.isManual || objBOMMasterTag1.PITag == "") { //objBOMMasterTag1.quantity = 00; objBOMMasterTag1.isManual = true; if (objBOMMasterTag1.component == "") { } } else { double resultValue = 0; strtTag = PIPoint.FindPIPoint(myPiServer, objBOMMasterTag1.PITag); strtVal = strtTag.RecordedValue(sAFTime, AFRetrievalMode.AtOrAfter); endVal = strtTag.RecordedValue(eAFTime, AFRetrievalMode.AtOrAfter); AFTimeRange graphTimeReange = new AFTimeRange(sAFTime, eAFTime); sm = strtTag.Summary(graphTimeReange, AFSummaryTypes.Maximum, 0, 0); smin = strtTag.Summary(graphTimeReange, AFSummaryTypes.Minimum, 0, 0); AFValue mx = sm[AFSummaryTypes.Maximum]; AFValue mn = smin[AFSummaryTypes.Minimum]; Boolean isWrongValue = false; if (endVal.Value.ToString().Equals("No Data") || mx.IsGood == false || strtVal.Value.ToString().Equals("No Data") || mx.IsGood == false) { resultValue = 0.0; isWrongValue = true; } else { if (Convert.ToDouble(endVal.Value) < Convert.ToDouble(mx.Value)) { resultValue = Convert.ToDouble(mx.Value) - Convert.ToDouble(strtVal.Value) + Convert.ToDouble(endVal.Value) - Convert.ToDouble(mn.Value); } else if (Convert.ToDouble(endVal.Value) == Convert.ToDouble(strtVal.Value)) { resultValue = 0; isWrongValue = true; } else { resultValue = Convert.ToDouble(endVal.Value) - Convert.ToDouble(strtVal.Value); } } //if (objBOMMasterTag1.component == "power") //{ // BOMDetails bomDetails = new BOMDetails(); // List<MasterRefineryModel> lstMasterRefinery = bomDetails.getPlantWiseSubRefineries(SubRefinery); // double upTimeHours = 0; // double totalWeightIntoUptime = 0; // double weightIntoUptime = 0; // double weightIntoUptime1 = 0; // double effectiveWeight = 0; // foreach (MasterRefineryModel RefineryDetails in lstMasterRefinery) // { // Boolean flag = bomDetails.InsertForUpTime(ActualStartDate, ActualEndDate, RefineryDetails.SubRefineryCode, RefineryDetails.SubRefineryName); // if (flag) // { // strtTag = PIPoint.FindPIPoint(myPiServer, RefineryDetails.UpTimeTag); // strtVal = strtTag.RecordedValue(sAFTime, AFRetrievalMode.AtOrAfter); // endVal = strtTag.RecordedValue(eAFTime, AFRetrievalMode.AtOrAfter); // upTimeHours = Convert.ToDouble(endVal.Value); // weightIntoUptime = (upTimeHours * RefineryDetails.UpTimePercentage); // totalWeightIntoUptime = totalWeightIntoUptime + weightIntoUptime; // if (objBOMMasterTag1.SubRefinery == RefineryDetails.SubRefineryCode) // { // weightIntoUptime1 = weightIntoUptime; // } // } // } // effectiveWeight = weightIntoUptime1 / totalWeightIntoUptime; // resultValue = resultValue * effectiveWeight; //} if (resultValue <= 0 || isWrongValue) { objBOMMasterTag1.isManual = true; objBOMMasterTag1.isManualWithTag = true; } objBOMMasterTag1.quantity = (float)resultValue; } lstBOMMasterTag.Add(objBOMMasterTag1); //if (duplicate != "") //{ // if (objBOMMasterTag1.BOMCategory == "Raw-Material" || objBOMMasterTag1.BOMCategory == "Product") // { // if (duplicate == objBOMMasterTag1.component) // { // lstBOMMasterTag.Remove(objBOMMasterTag1); // } // } //} } } JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer(); string json = javaScriptSerializer.Serialize(lstBOMMasterTag); JsonResult js = Json(new { value = json }, JsonRequestBehavior.AllowGet); return(js); } catch (Exception e) { return(Json(new { value = exceptionMsg }, JsonRequestBehavior.AllowGet)); } } else { return(Json(new { status = false }, JsonRequestBehavior.AllowGet)); } }