public void Run() { PIServers piServers = new PIServers(); PIServer piServer = piServers["<AFSERVER>"]; // Use PICommonPointAttributes so we don't have to remember the strings for point attributes. string floatpoint = "sample_floatpoint"; Dictionary<string, object> floatpoint_attributes = new Dictionary<string, object>(); floatpoint_attributes.Add(PICommonPointAttributes.PointClassName, "classic"); floatpoint_attributes.Add(PICommonPointAttributes.Descriptor, "Hello floating world"); floatpoint_attributes.Add(PICommonPointAttributes.PointType, "float32"); string digitalpoint = "sample_digitalpoint"; Dictionary<string, object> digitalpoint_attributes = new Dictionary<string, object>(); digitalpoint_attributes.Add(PICommonPointAttributes.PointClassName, "classic"); digitalpoint_attributes.Add(PICommonPointAttributes.Descriptor, "Hello digital world"); digitalpoint_attributes.Add(PICommonPointAttributes.PointType, "digital"); digitalpoint_attributes.Add(PICommonPointAttributes.DigitalSetName, "modes"); Dictionary<string, IDictionary<string, object>> pointDict = new Dictionary<string, IDictionary<string, object>>(); pointDict.Add(floatpoint, floatpoint_attributes); pointDict.Add(digitalpoint, digitalpoint_attributes); AFListResults<string, PIPoint> results = piServer.CreatePIPoints(pointDict); }
public void Run() { PIServers piServers = new PIServers(); PIServer piServer = piServers["<AFSERVER>"]; // Use PICommonPointAttributes so we don't have to remember the strings for point attributes. string floatpoint = "sample_floatpoint"; Dictionary <string, object> floatpoint_attributes = new Dictionary <string, object>(); floatpoint_attributes.Add(PICommonPointAttributes.PointClassName, "classic"); floatpoint_attributes.Add(PICommonPointAttributes.Descriptor, "Hello floating world"); floatpoint_attributes.Add(PICommonPointAttributes.PointType, "float32"); string digitalpoint = "sample_digitalpoint"; Dictionary <string, object> digitalpoint_attributes = new Dictionary <string, object>(); digitalpoint_attributes.Add(PICommonPointAttributes.PointClassName, "classic"); digitalpoint_attributes.Add(PICommonPointAttributes.Descriptor, "Hello digital world"); digitalpoint_attributes.Add(PICommonPointAttributes.PointType, "digital"); digitalpoint_attributes.Add(PICommonPointAttributes.DigitalSetName, "modes"); Dictionary <string, IDictionary <string, object> > pointDict = new Dictionary <string, IDictionary <string, object> >(); pointDict.Add(floatpoint, floatpoint_attributes); pointDict.Add(digitalpoint, digitalpoint_attributes); AFListResults <string, PIPoint> results = piServer.CreatePIPoints(pointDict); }
static void Main(string[] args) { var system = new PISystems().DefaultPISystem; var db = system.Databases.DefaultDatabase; var dataArchive = new PIServers().DefaultPIServer; StopService("PIAnalysisManager", 10000); var archiveAttr = db.Elements["PI Data Archive"].Attributes["Name"]; if (archiveAttr != null) { archiveAttr.SetValue(new AFValue(dataArchive.Name)); } archiveAttr = db.Elements["PI Data Archive"].Attributes["名"]; if (archiveAttr != null) { archiveAttr.SetValue(new AFValue(dataArchive.Name)); } db.CheckIn(); foreach (var elem in db.Elements) { createConfig(elem); } db.CheckIn(); Thread.Sleep(1000); foreach (var category in new List <string> { "Random Data", "Usage", "Cost", "Downtime" }) { ProgrammaticAnalysisRecalculation(system, db, db.AnalysisCategories[category]); } StartService("PIAnalysisManager", 10000); }
static void Main(string[] args) { try { PISystems piSystems = new PISystems(); string AFServer = ConfigurationManager.AppSettings.Get("AFServer"); PISystem assetServer = piSystems[AFServer]; PIServers piServers = new PIServers(); string PIServer = ConfigurationManager.AppSettings.Get("DataArchiveServer"); PIServer piServer = piServers[PIServer]; //AFElement.LoadAttributes() if (assetServer == null) { Console.WriteLine("Cannot Find AF Server: {0}", AFServer); Console.ReadLine(); Environment.Exit(0); } if (piServer == null) { Console.WriteLine("Cannot Find PI Data Server: {0}", PIServer); Console.ReadLine(); Environment.Exit(0); } if (assetServer != null && piServer != null) { //AFDatabase database = assetServer.Databases["Demo UOG Well Drilling & Completion Monitoring"]; //AFDatabase database = assetServer.Databases["AARA OEE Demo"]; // PrintElementTemplates(database); // PrintAttributeTemplates(database, "Batch Context Template"); // PrintEnergyUOMs(assetServer); // PrintEnumerationSets(database); // PrintCategories(database); // FindMetersBYTemplate(database, "Line"); // TimeSpan test = new TimeSpan(0, 1, 0); //Program6.PrintInterpolated(database, "Inlet Pump", "14-Nov-18 16:15:00", "14-Nov-18 17:15:00.000000", test); //Program6.CreateFeedersRootElement(database); // Program6.CreateFeederElements(database); //DataPipeSubscribeExample.Run(piServer); Console.WriteLine("Connected Successfully to PI Server: {0} and AF Server: {1}", PIServer, AFServer); //Subscribe.DataPipeSubscribeExample.Run1(); UseCase_DataPipe.Run(piServer); Console.ReadLine(); } } catch (Exception ex) { Logs Err = new Logs(); Err.MyLogFile(ex); Console.WriteLine("An Error has occured for details please check the Log File: '" + ex.Message + "'"); Console.ReadLine(); } }
public void Run() { PIServers piServers = new PIServers(); PIServer piServer = piServers["<PISERVER>"]; IList<PIPoint> points = PIPoint.FindPIPoints(piServer, new[] { "sample_floatpoint", "sample_digitalpoint" }); PIPoint floatingPIPoint = points[0]; PIPoint digitalPIPoint = points[1]; AFEnumerationSet digSet = piServer.StateSets["Modes"]; IList<AFValue> valuesToWrite = new List<AFValue>(); for (int i = 0; i < 10; i++) { AFTime time = new AFTime(new DateTime(2015, 1, 1, i, 0, 0, DateTimeKind.Local)); AFValue afValueFloat = new AFValue(i, time); // Associate the AFValue to a PI Point so we know where to write to. afValueFloat.PIPoint = floatingPIPoint; AFEnumerationValue digSetValue = i % 2 == 0 ? digSet["Auto"] : digSet["Manual"]; AFValue afValueDigital = new AFValue(digSetValue, time); afValueDigital.PIPoint = digitalPIPoint; valuesToWrite.Add(afValueFloat); valuesToWrite.Add(afValueDigital); } // Perform a bulk write. Use a single local call to PI Buffer Subsystem if possible. // Otherwise, make a single call to the PI Data Archive. // We use no compression just so we can check all the values are written. piServer.UpdateValues(valuesToWrite, AFUpdateOption.InsertNoCompression, AFBufferOption.BufferIfPossible); }
public override void Run() { try { PIServers piServers = new PIServers(); PIServer piServer = piServers[Server]; if (piServer == null) throw new PIServerNotFoundException(); Logger.InfoFormat("Found server connection: {0}",piServer.Name); if (OperationTimeout > 0) { ChangeOperationTimeOut(piServer,OperationTimeout); } if (ConnectionTimeout > 0) { ChangeConnectionTimeOut(piServer, ConnectionTimeout); } } catch (Exception ex) { Logger.Error(ex); } }
static void Main(string[] args) { var dataArchive = new PIServers().DefaultPIServer; var points = GetOrCreatePIPoints(dataArchive, new string[] { "New York_Pressure", "New York_Temperature", "New York_Humidity" }, "AFSDKWS_"); //Create data pipe PIDataPipe pipe = new PIDataPipe(AFDataPipeType.Snapshot); pipe.AddSignups(points); var counter = 0; do { while (!Console.KeyAvailable) { CheckPipeEvents(pipe, ref counter); } ; } while (Console.ReadKey(true).Key != ConsoleKey.Escape); pipe.Close(); pipe.Dispose(); }
public ActionResult PIPointsAttribute(int id) { PIServer piServer = new PIServers().DefaultPIServer; PIPoint piPoint = PIPoint.FindPIPoint(piServer, id); IDictionary<string, object> attributes = piPoint.GetAttributes(); return View(attributes); }
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(); }
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(); }
private static void Main(string[] args) { PIServer server = new PIServers().DefaultPIServer; server.Connect(); List <PIPoint> points = PIPoint.FindPIPoints(server, "testSinusoid_*").ToList(); if (points.Count == 0) { server.CreatePIPoints(Enumerable.Range(1, 6000).Select(x => "testSinusoid_" + x), new Dictionary <String, Object>() { { "compressing", 0 } }); points = PIPoint.FindPIPoints(server, "testSinusoid_*").ToList(); } Console.WriteLine("Found {0} points", points.Count); TimeSpan chunkSize = new TimeSpan(5, 0, 0); for (DateTime start = new DateTime(2017, 1, 1); start < new DateTime(2018, 1, 1); start = start.Add(chunkSize)) { Console.WriteLine("Writing chunk starting at: " + start); List <AFValue> values = getSinusoidData(start, start.Add(chunkSize), new TimeSpan(0, 0, 15)); Parallel.ForEach(points, point => { point.UpdateValues(values, AFUpdateOption.Replace); }); } server.Disconnect(); }
public override void Run() { try { PIServers piServers = new PIServers(); PIServer piServer = piServers[Server]; if (piServer == null) { throw new PIServerNotFoundException(); } Logger.InfoFormat("Found server connection: {0}", piServer.Name); if (OperationTimeout > 0) { ChangeOperationTimeOut(piServer, OperationTimeout); } if (ConnectionTimeout > 0) { ChangeConnectionTimeOut(piServer, ConnectionTimeout); } } catch (Exception ex) { Logger.Error(ex); } }
public void Run() { PIServers piServers = new PIServers(); PIServer piServer = piServers["<PISERVER>"]; IList <PIPoint> points = PIPoint.FindPIPoints(piServer, new[] { "sample_floatpoint", "sample_digitalpoint" }); PIPoint floatingPIPoint = points[0]; PIPoint digitalPIPoint = points[1]; AFEnumerationSet digSet = piServer.StateSets["Modes"]; IList <AFValue> valuesToWrite = new List <AFValue>(); for (int i = 0; i < 10; i++) { AFTime time = new AFTime(new DateTime(2015, 1, 1, i, 0, 0, DateTimeKind.Local)); AFValue afValueFloat = new AFValue(i, time); // Associate the AFValue to a PI Point so we know where to write to. afValueFloat.PIPoint = floatingPIPoint; AFEnumerationValue digSetValue = i % 2 == 0 ? digSet["Auto"] : digSet["Manual"]; AFValue afValueDigital = new AFValue(digSetValue, time); afValueDigital.PIPoint = digitalPIPoint; valuesToWrite.Add(afValueFloat); valuesToWrite.Add(afValueDigital); } // Perform a bulk write. Use a single local call to PI Buffer Subsystem if possible. // Otherwise, make a single call to the PI Data Archive. // We use no compression just so we can check all the values are written. piServer.UpdateValues(valuesToWrite, AFUpdateOption.InsertNoCompression, AFBufferOption.BufferIfPossible); }
private PIServer ConnectMember(string collectiveName, string memberName) { var servers = new PIServers(); var server = servers[collectiveName]; if (server.Collective == null) { throw new Exception("This server is not a collective"); } var member = server.Collective.Members[memberName]; if (member != null) { server = member.ConnectDirect(); var currentUser = server.CurrentUserName; Console.WriteLine(currentUser); } else { throw new Exception("Failed to find the server member in the collective's servers list. Veryfy that the name is correct"); } return(server); }
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. }
//Constructor public piGetter() { Console.WriteLine("End Date: " + endDateTime); Console.WriteLine("State Date: " + startDateTime); //initate the server shit this.pIServers = new PIServers(); this.piServer = pIServers.DefaultPIServer; this.valueList = new List <String[]>(); }
// GET: Home public ActionResult Index() { PIServer piServer = new PIServers().DefaultPIServer; piServer.Connect(); IEnumerable<PIPoint> piPointList = PIPoint.FindPIPoints(piServer, "*"); PIPointList pointList = new PIPointList(); pointList.AddRange(piPointList); AFListResults<PIPoint, AFValue> results = pointList.EndOfStream(); IEnumerable<PIPointData> pointListData = results.Select(m => new PIPointData(m.PIPoint.Name, m.Value, m.Timestamp.LocalTime, m.PIPoint.ID)); return View(pointListData); }
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 PIServer Connect(string server) { PIServers piServers = new PIServers(); PIServer piServer = piServers[server]; if (piServer == null) throw new PIServerNotFoundException(); // the connect signature:(true, null) will force a password dialog to appear. // you should not use this option for a service or an executable that runs outside a user windows session. // instead use the empty constructor and make sure that the user that runs the application have an account that allows it to connect. piServer.Connect(true, null); return piServer; }
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; } } } }
/// <summary> /// Find the target PI Data Archive /// </summary> /// <param name="PIDataArchiveName"></param> /// <returns></returns> private static PIServer FindTargetPIServer(string PIDataArchiveName) { PIServer targetPI = null; if (PIDataArchiveName.Equals(@"%Server%", StringComparison.OrdinalIgnoreCase)) { targetPI = new PIServers().DefaultPIServer; } else { targetPI = new PIServers()[PIDataArchiveName]; } return(targetPI); }
public PIServer Connect(string server) { PIServers piServers = new PIServers(); PIServer piServer = piServers[server]; if (piServer == null) { throw new PIServerNotFoundException(); } // the connect signature:(true, null) will force a password dialog to appear. // you should not use this option for a service or an executable that runs outside a user windows session. // instead use the empty constructor and make sure that the user that runs the application have an account that allows it to connect. piServer.Connect(true, null); return(piServer); }
public PIPointOperations(string piServerName) { PIServers piServers = new PIServers(); _pi = piServers[piServerName]; try { _pi.Connect(); Console.WriteLine("Connected"); } catch (Exception ex) { Console.WriteLine(ex.Message); } piPointList = this.GetPIPoints(); }
/// <summary> /// Attempts to open <see cref="PIConnection"/>. /// </summary> public void Open() { if (m_connected || ((object)m_server != null && m_server.ConnectionInfo.IsConnected)) { throw new InvalidOperationException("OSI-PI server connection is already open."); } if (string.IsNullOrWhiteSpace(m_serverName)) { throw new InvalidOperationException("Cannot open OSI-PI server connection without a defined server name."); } m_connected = false; try { // Locate configured PI server PIServers servers = new PIServers(); m_server = servers[m_serverName]; if ((object)m_server == null) { throw new InvalidOperationException("Server not found in the PI servers collection."); } m_server.ConnectChanged += PIConnection_ConnectChanged; } catch (Exception ex) { throw new InvalidOperationException(string.Format("Failed to connect to PI server \"{0}\": {1}", m_serverName, ex.Message)); } if (!m_server.ConnectionInfo.IsConnected) { // Attempt to open OSI-PI connection if (!string.IsNullOrEmpty(m_userName) && !string.IsNullOrEmpty(m_password)) { m_server.Connect(new NetworkCredential(m_userName, m_password)); } else { m_server.Connect(true); } } m_connected = true; }
/// <summary> /// Creates an instance of the PIFixture class. /// </summary> public PIFixture() { var dataArchiveName = Settings.PIDataArchive; var servers = PIServers.GetPIServers(); PIServer = servers[dataArchiveName]; if (PIServer != null) { PIServer.Connect(); } else { throw new InvalidOperationException( $"The specific PI Data Archive [{dataArchiveName}] does not exist or is not configured."); } }
// 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); } }
static void Main(string[] args) { var username = Environment.GetEnvironmentVariable("PI_USER"); var password = Environment.GetEnvironmentVariable("PI_PASSWORD"); var domain = Environment.GetEnvironmentVariable("PI_DOMAIN"); var afname = Environment.GetEnvironmentVariable("AF_NAME") ?? "empty"; var piname = Environment.GetEnvironmentVariable("PI_NAME") ?? "empty"; try { Console.WriteLine("Hostname of AF Server:" + afname); PISystem sys = new PISystems()[afname]; if (sys == null) { throw new Exception("PI System is null"); } var cred = new NetworkCredential(username, password, domain); sys.Connect(cred); Console.WriteLine("AF version:" + sys.ServerVersion + "\tAF name:" + sys.Name); Console.WriteLine("User:"******"\tIdentity:" + sys.CurrentUserIdentityString); } catch (Exception ex) { Console.WriteLine("Can't connect to PI Server"); Console.WriteLine(ex); } try { Console.WriteLine("Hostname of PI Data Archive:" + piname); PIServer srv = new PIServers()[piname]; srv.Connect(); Console.WriteLine("PI version:" + srv.ServerVersion + "\tPI name:" + srv.Name); Console.WriteLine("User:"******"\tIdentity:" + srv.CurrentUserIdentityString); } catch (Exception ex) { Console.WriteLine("Can't connect to PI Data Archive"); Console.WriteLine(ex); } }
public void Run() { PIServers piServers = new PIServers(); PIServer piServer = piServers["<PISERVER>"]; IList<PIPoint> points = PIPoint.FindPIPoints(piServer, new[] { "sinusoid", "sinusoidu", "cdt158", "cdm158" }); // Create an PIPointList object in order to make the bulk call later. PIPointList pointList = new PIPointList(points); if (pointList == null) return; // MAKE A BULK CALL TO THE PI DATA ARCHIVE AFListResults<PIPoint,AFValue> values = pointList.CurrentValue(); // Requires AF SDK 2.7+ foreach (AFValue val in values) { Console.WriteLine("Point: {0}, Timestamp: {1}, Value: {2}", val.PIPoint, val.Timestamp, val.Value.ToString()); } }
private void ConnectPI() { InitializeHost(); // Locate configured PI server PIServers servers = new PIServers(); m_server = servers[m_settings.ServerName]; if (m_server is null) { throw new InvalidOperationException("Server not found in the PI servers collection."); } if (!m_server.ConnectionInfo.IsConnected) { // Attempt to open OSI-PI connection m_server.Connect(true); } }
public void Run() { PIServers piServers = new PIServers(); PIServer piServer = piServers["<PISERVER>"]; // Use PICommonPointAttributes so we don't have to remember the strings for point attributes. PIPointQuery compressionFilter = new PIPointQuery { AttributeName = PICommonPointAttributes.Compressing, AttributeValue = "1", Operator = AFSearchOperator.Equal }; PIPointQuery nameFilter = new PIPointQuery { AttributeName = PICommonPointAttributes.PointSource, AttributeValue = "R", Operator = AFSearchOperator.Equal }; IEnumerable <string> attributesToLoad = new[] { PICommonPointAttributes.Compressing, PICommonPointAttributes.Descriptor, PICommonPointAttributes.PointSource, PICommonPointAttributes.Span, PICommonPointAttributes.Zero }; IEnumerable <PIPoint> points = PIPoint.FindPIPoints(piServer, new[] { compressionFilter, nameFilter }, attributesToLoad); foreach (PIPoint pt in points) { Console.WriteLine("Name: {0}", pt.GetAttribute(PICommonPointAttributes.Tag)); Console.WriteLine("Compressing: {0}", pt.GetAttribute(PICommonPointAttributes.Compressing)); Console.WriteLine("Descriptor: {0}", pt.GetAttribute(PICommonPointAttributes.Descriptor)); Console.WriteLine("PointSource: {0}", pt.GetAttribute(PICommonPointAttributes.PointSource)); Console.WriteLine("Span: {0}", pt.GetAttribute(PICommonPointAttributes.Span)); Console.WriteLine("Zero: {0}", pt.GetAttribute(PICommonPointAttributes.Zero)); Console.WriteLine(); } }
// Connect to PI Data Archive public static void Connect(string PIServerName) { //connections PIServers allPIServers = new PIServers(); PIServer aPIServer = allPIServers[PIServerName]; try { aPIServer.Connect(); } catch (Exception e) { Console.WriteLine("{0}\nPIServer '{1}' was not found. List of PI Servers in KST:", e.Message, PIServerName); foreach (var it in allPIServers) { Console.WriteLine("\t" + it.Name); } Environment.Exit(0); return; } }
public void Run() { PIServers piServers = new PIServers(); PIServer piServer = piServers["<PISERVER>"]; // Use PICommonPointAttributes so we don't have to remember the strings for point attributes. PIPointQuery compressionFilter = new PIPointQuery { AttributeName = PICommonPointAttributes.Compressing, AttributeValue = "1", Operator = AFSearchOperator.Equal }; PIPointQuery nameFilter = new PIPointQuery { AttributeName = PICommonPointAttributes.PointSource, AttributeValue = "R", Operator = AFSearchOperator.Equal }; IEnumerable<string> attributesToLoad = new[] { PICommonPointAttributes.Compressing, PICommonPointAttributes.Descriptor, PICommonPointAttributes.PointSource, PICommonPointAttributes.Span, PICommonPointAttributes.Zero }; IEnumerable<PIPoint> points = PIPoint.FindPIPoints(piServer, new[] { compressionFilter, nameFilter }, attributesToLoad); foreach (PIPoint pt in points) { Console.WriteLine("Name: {0}", pt.GetAttribute(PICommonPointAttributes.Tag)); Console.WriteLine("Compressing: {0}", pt.GetAttribute(PICommonPointAttributes.Compressing)); Console.WriteLine("Descriptor: {0}", pt.GetAttribute(PICommonPointAttributes.Descriptor)); Console.WriteLine("PointSource: {0}", pt.GetAttribute(PICommonPointAttributes.PointSource)); Console.WriteLine("Span: {0}", pt.GetAttribute(PICommonPointAttributes.Span)); Console.WriteLine("Zero: {0}", pt.GetAttribute(PICommonPointAttributes.Zero)); Console.WriteLine(); } }
public void GetPIData(string piDataArchiveName, string piPointName1, string piPointName2, string piPointName3, string startTime, string endTime, string interval) { IEnumerable <string> piPointNames = new List <string> { piPointName1, piPointName2, piPointName3 }; PIServer piServer = new PIServers()[piDataArchiveName]; if (piServer == null) { return; } IList <PIPoint> points = PIPoint.FindPIPoints(piServer, piPointNames); PIPointList pointList = new PIPointList(points); AFTimeRange timeRange = new AFTimeRange(new AFTime(startTime), new AFTime(endTime)); AFTimeSpan timeSpan; bool result = AFTimeSpan.TryParse(interval, out timeSpan); if (result == false) { AFTimeSpan.TryParse("1h", out timeSpan); } IEnumerable <AFValues> valuesList = pointList.InterpolatedValues(timeRange, timeSpan, string.Empty, false, new PIPagingConfiguration(PIPageType.TagCount, 100)); foreach (AFValues values in valuesList) { if (values.PIPoint.Name == piPointName1) { values1 = values.Where(m => m.ValueTypeCode == TypeCode.Single || m.ValueTypeCode == TypeCode.Double).Select(m => m.ValueAsDouble()).ToArray(); } else if (values.PIPoint.Name == piPointName2) { values2 = values.Where(m => m.ValueTypeCode == TypeCode.Single || m.ValueTypeCode == TypeCode.Double).Select(m => m.ValueAsDouble()).ToArray(); } else if (values.PIPoint.Name == piPointName3) { values3 = values.Where(m => m.ValueTypeCode == TypeCode.Single || m.ValueTypeCode == TypeCode.Double).Select(m => m.ValueAsDouble()).ToArray(); } } }
public void Run() { PIServers piServers = new PIServers(); PIServer piServer = piServers["<PISERVER>"]; IList <PIPoint> points = PIPoint.FindPIPoints(piServer, new[] { "sinusoid", "sinusoidu", "cdt158", "cdm158" }); // Create an PIPointList object in order to make the bulk call later. PIPointList pointList = new PIPointList(points); if (pointList == null) { return; } // MAKE A BULK CALL TO THE PI DATA ARCHIVE AFListResults <PIPoint, AFValue> values = pointList.CurrentValue(); // Requires AF SDK 2.7+ foreach (AFValue val in values) { Console.WriteLine("Point: {0}, Timestamp: {1}, Value: {2}", val.PIPoint, val.Timestamp, val.Value.ToString()); } }
public PIData_PIAFSDK() { MyPISystems = new PISystems(); MyPIServers = new PIServers(); }
private static async Task MainAsync() { string accountId = ConfigurationManager.AppSettings["accountId"]; string namespaceId = ConfigurationManager.AppSettings["namespaceId"]; string address = ConfigurationManager.AppSettings["address"]; string resource = ConfigurationManager.AppSettings["resource"]; string clientId = ConfigurationManager.AppSettings["clientId"]; string clientSecret = ConfigurationManager.AppSettings["clientSecret"]; string piServerName = ConfigurationManager.AppSettings["PIDataArchive"]; var qiService = new QiService(new Uri(address), new QiSecurityHandler(resource, accountId, clientId, clientSecret)); var metadataService = qiService.GetMetadataService(accountId, namespaceId); var dataService = qiService.GetDataService(accountId, namespaceId); var piServer = new PIServers()[piServerName]; piServer.Connect(); PIPointQuery nameFilter = new PIPointQuery { AttributeName = PICommonPointAttributes.Tag, AttributeValue = _options.TagMask, Operator = OSIsoft.AF.Search.AFSearchOperator.Equal }; IEnumerable <string> attributesToRetrieve = new[] { PICommonPointAttributes.Descriptor, PICommonPointAttributes.EngineeringUnits, PICommonPointAttributes.PointSource }; var piPoints = (await PIPoint.FindPIPointsAsync(piServer, new[] { nameFilter }, attributesToRetrieve)).ToList(); if (!piPoints.Any()) { Console.WriteLine($"No points found matching the tagMask query!"); return; } Console.WriteLine($"Found {piPoints.Count} points matching mask: {_options.TagMask}"); //create types await PIQiTypes.CreateOrUpdateTypesInOcsAsync(metadataService); //delete existing streams if requested if (_options.Mode == CommandLineOptions.DataWriteModes.clearExistingData) { Parallel.ForEach(piPoints, piPoint => DeleteStreamBasedOnPIPointAsync(piPoint, metadataService).Wait()); } Parallel.ForEach(piPoints, piPoint => CreateStreamBasedOnPIPointAsync(piPoint, attributesToRetrieve, metadataService).Wait()); Console.WriteLine($"Created or updated {piPoints.Count()} streams."); //for each PIPoint, get the data of interest and write it to OCS Parallel.ForEach(piPoints, piPoint => { //Indices must be unique in OCS so we get rid of duplicate values for a given timestamp var timeRange = new AFTimeRange(_options.StartTime, _options.EndTime); var afValues = piPoint.RecordedValues(timeRange, AFBoundaryType.Inside, null, true) .GroupBy(value => value.Timestamp) .Select(valuesAtTimestamp => valuesAtTimestamp.Last()) //last event for particular timestamp .Where(val => val.IsGood) //System Digital States (e.g. Shutdown, IO Timeout, etc...) are ignored .ToList(); WriteDataToOcsAsync(piPoint, afValues, dataService).Wait(); }); }
public Application() { myPIServers = new PIServers(); myPIServer = myPIServers["MARC-PI2016"]; myPIServer.Connect(); }
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); }
public void setAFValue(string Timestamp, string Value, string TagName, string PIServerName) { AFTime aftTime; if (AFTime.TryParse(Timestamp, out aftTime)) { PIServers svrs = new PIServers(); PIServer piSrv = svrs[PIServerName]; PIPoint pipt = PIPoint.FindPIPoint(piSrv, TagName); m_AFVal = new AFValue(Value, aftTime); m_AFVal.PIPoint = pipt; } }
public WPIPoint() { PIServers srvrs = new PIServers(); m_piSrv = srvrs.DefaultPIServer; }
/// <summary> /// Find the target PI Data Archive /// </summary> /// <param name="PIDataArchiveName"></param> /// <returns></returns> private static PIServer FindTargetPIServer(string PIDataArchiveName) { PIServer targetPI = null; if (PIDataArchiveName.Equals(@"%Server%", StringComparison.OrdinalIgnoreCase)) targetPI = new PIServers().DefaultPIServer; else targetPI = new PIServers()[PIDataArchiveName]; return targetPI; }