/// <summary> /// Create any non-existing PI points based on a list of point definitions on a given PI Data Archive /// </summary> /// <param name="targetPI"></param> /// <param name="pointDefinitions"></param> private static void CreatePIPoints(PIServer targetPI, IDictionary<string, IDictionary<string, object>> pointDefinitions) { IEnumerable<string> pointNames = pointDefinitions.Keys; // See what points exist var resolvedPoints = new HashSet<string>(PIPoint.FindPIPoints(targetPI, pointNames) .Select(pt => pt.Name)); // Filter out existing points var pointsToCreate = pointDefinitions .Where(p => !resolvedPoints.Contains(p.Key)) .ToDictionary(p => p.Key, p => p.Value); // Create any points with default PI point attributes IEnumerable<string> pointsWithDefaultAttributes = pointsToCreate .Where(p => p.Value == null) .Select(p => p.Key) .ToList(); targetPI.CreatePIPoints(pointsWithDefaultAttributes); // Create other PI points foreach (var pt in pointsWithDefaultAttributes) { pointsToCreate.Remove(pt); } targetPI.CreatePIPoints(pointsToCreate); }
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 override void Run() { PIServer server = null; try { ValidateParameters(); PiConnectionHelper.ConnectAndGetServer(Server, out server); if (Delete) { DeleteTags(server); } else { var newPoints = CreatePoints(server); if (DataSt != null) { GenerateData(newPoints); } } } catch (Exception ex) { Logger.Error(ex); } }
public TagsLoader(PIServer server, string[] queries, int tagChunkSize, Orchestrator orchestrator) { _server = server; _queries = queries; _tagChunkSize = tagChunkSize; _orchestrator = orchestrator; }
private PIPoint GetPIPoint(PIServer server, Guid signalID, out string cachedTagName) { PIPoint point = null; // See if cached mapping exists between guid and tag name - tag name lookups are faster than GetPoints query if (m_tagMap.TryGetValue(signalID, out cachedTagName)) { point = GetPIPoint(server, cachedTagName); } if ((object)point == null) { // Point was not previously cached, lookup tag using signal ID stored in extended description field IEnumerable <PIPoint> points = PIPoint.FindPIPoints(server, string.Format("EXDESC='{0}'", signalID), false, new[] { PICommonPointAttributes.ExtendedDescriptor }); point = points.FirstOrDefault(); if ((object)point != null) { cachedTagName = point.Name; } } return(point); }
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(); } }
static void Main(string[] args) { Options arguments = Parser.Default.ParseArguments <Options>(args).MapResult(options => options, _ => null); Logger logger = new Logger(true, arguments.LogFile != null ? arguments.LogFile : null); logger.Log("Started"); // Server logger.Log($"Connecting to server {arguments.ServerName}"); PIServer piServer = PIUtil.GetPIServer(arguments.ServerName); logger.Log($"Connecting to system {arguments.SystemName}"); PISystem piSystem = AFUtil.GetPISystem(arguments.SystemName); logger.Log("Connected"); // Database logger.Log($"Listing tags"); PIUtil.WriteTags(piServer, arguments.TagOutputFile); logger.Log("Finished - press Enter to close terminal"); logger.Close(); Console.ReadLine(); }
public bool Connect() { try { if (_memberName == null) { _logger.InfoFormat("Trying to connect to PI Data Archive {0}. As {1}", _piServer.Name, _piServer.CurrentUserName); _piServer.Connect(); } else { _logger.InfoFormat("Connecting to member: {0}", _memberName); _piServer = ConnectMember(_piServer.Name, _memberName); } _logger.InfoFormat("Connected to {0}. As {1}", _piServer.Name, _piServer.CurrentUserName); return(true); } catch (Exception ex) { _logger.Error(ex); } return(false); }
/// <summary> /// This method deletes the data stored in specified tags of the PI Data Archive /// To delete data, it is required to first read the values that you want to delete, and then /// Call the update values method with the AFUpdateOption.Remove option /// <remarks> /// </remarks> /// </summary> private void DeleteData() { try { ValidateParameters(); piConnectionMgr = new PiConnectionMgr(Server); piConnectionMgr.Connect(); PIServer server = piConnectionMgr.GetPiServer(); var timer = Stopwatch.StartNew(); // Gets the tags and creates a point list with the tags, to prepare for bulk read call var points = PIPoint.FindPIPoints(server, TagList); var pointList = new PIPointList(points); Logger.InfoFormat("Initialized PI Points for deletion: {0}", string.Join(", ", points.Select(p => p.Name))); // converts strings to AFTime objects this will throw an error if invalid var startTime = new AFTime(StartTime); var endTime = new AFTime(EndTime); if (startTime > endTime) { throw new PIDeleteUtilInvalidParameterException("Start Time must be smaller than End Time"); } // defines the data eraser task that will work in parallel as the data querying task dataEraser = new DataProcessor(EraseData); var eraseTask = Task.Run(() => dataEraser.Run()); // splits iterates the period, over foreach (var period in Library.Helpers.EachNDay(startTime, endTime, Days)) { Logger.InfoFormat("Getting tags information for period {0} to {1} ({2} Days chunk)", startTime, endTime, Days); // makes the first data call var data = pointList.RecordedValues(period, AFBoundaryType.Inside, null, false, new PIPagingConfiguration(PIPageType.TagCount, 100)); Logger.InfoFormat("Adding the data to the queue for deletion. ({0} to {1})", startTime, endTime); // we push this data into the data processor queue so we can continue to query for the rest of the data. dataEraser.DataQueue.Add(data); } dataEraser.DataQueue.CompleteAdding(); // // this will tell the data eraser that no more data will be added and allow it to complete eraseTask.Wait(); // waiting for the data processor to complete Logger.InfoFormat( "Deletion process completed in {0} seconds. With {1} events deleted (assuming there was no errors).", Math.Round(timer.Elapsed.TotalSeconds, 0), dataEraser.TotalEventProcessed); } catch (Exception ex) { Logger.Error(ex); } }
/// <summary> /// Multiple steps. 1) gets PIPoints fo the Server /// 2) Checks AFSecurity, for admin access and removes ability to import. /// 3) Initializes Database and EventFrameFindCtrl. /// </summary> private void initializeAfServerPicker() { PISystem sys = afServerPicker.PISystem; //PI System != AF Server _curServer = sys.Name; PIServer serv = PIServer.FindPIServer(sys, sys.Name); List <PIPoint> piPoints = control.getPIPoints(sys, serv); avcPIPoints.AFSetObject(piPoints, afDatabasePicker1.AFDatabase, null, null); // Decides if you can import or not. Hides the UI. //TODO: Check AFSecurity security = sys.Security; if (security.HasAdmin) { isAdministrator = true; InformationDirectionPanel.Visible = true; } else { InformationDirectionPanel.Visible = false; } if (_curDatabase == null) { afDatabasePicker1.SetAFDatabase(sys.Databases[1], sys.Databases[1]); afEventFrameFindCtrl.Database = afDatabasePicker1.AFDatabase; } }
// Another way to list the point attributes is to query all attributes for the "classic" point class. // This will return some that you don't want to copy with new tags, such as the Tag name, point ID, // create date, etc. Therefore you will need another method that lists the point attributes to exclude. private static IList <string> GetPointAttributes(PIServer dataArchive, string ptClassName = "classic") { var ptclass = dataArchive.PointClasses[ptClassName]; var dict = ptclass.GetAttributes(); return(dict.Keys.ToList()); }
private PIPoint GetPIPoint(PIServer server, string tagName) { PIPoint point; PIPoint.TryFindPIPoint(server, tagName, out point); return(point); }
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 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); }
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 static PiConnectionMgr ConnectAndGetServer(string server, out PIServer piServer) { var manager=new PiConnectionMgr(server); manager.Connect(); piServer = manager.GetPiServer(); return manager; }
public void PIPointSearchTest() { PIServer piServer = PIFixture.PIServer; int numberOfPointsToCreate = 10; var pointPrefix = "PIPointSearchTest_Point"; try { // Create PI Points Output.WriteLine($"Creating PI Points with prefix [{pointPrefix}]."); var points = PIFixture.CreatePIPoints($"{pointPrefix}#", numberOfPointsToCreate); // Assign range of values to defined tags for (int i = 0; i < points.Count(); i++) { points.ElementAt(i).UpdateValue(new AFValue(Math.Pow(-1, i + 1), null), 0); // Set the Step attribute of half of the PI Points to true and half to false points.ElementAt(i).SetAttribute(PICommonPointAttributes.Step, Convert.ToBoolean(1 * ((i + 1) % 2))); points.ElementAt(i).SaveAttributes(); } // Search PI Points with queries var searchQuery = $"Name:'{pointPrefix}*' value:>0"; Output.WriteLine($"Searching for PI Points with query [{searchQuery}]."); var parsedQuery = PIPointQuery.ParseQuery(piServer, searchQuery); var searchPointsCount = PIPoint.FindPIPoints(piServer, parsedQuery).Count(); AssertEventually.True( () => PIPoint.FindPIPoints(piServer, parsedQuery).Count() == (numberOfPointsToCreate / 2), TimeSpan.FromSeconds(10), TimeSpan.FromSeconds(0.5), $"The PI Points count do not match. Expected: {numberOfPointsToCreate / 2}, Actual: {searchPointsCount}."); searchQuery = $"Name:'{pointPrefix}*'"; Output.WriteLine($"Searching for PI Points with query [{searchQuery}]."); parsedQuery = PIPointQuery.ParseQuery(piServer, searchQuery); searchPointsCount = PIPoint.FindPIPoints(piServer, parsedQuery).Count(); AssertEventually.True( () => PIPoint.FindPIPoints(piServer, parsedQuery).Count() == numberOfPointsToCreate, TimeSpan.FromSeconds(10), TimeSpan.FromSeconds(0.5), $"The PI Points count do not match. Expected: {numberOfPointsToCreate}, Actual: {searchPointsCount}."); searchQuery = $"Name:'{pointPrefix}*' step:=0"; Output.WriteLine($"Searching for PI Points with query [{searchQuery}]."); parsedQuery = PIPointQuery.ParseQuery(piServer, searchQuery); searchPointsCount = PIPoint.FindPIPoints(piServer, parsedQuery).Count(); AssertEventually.True( () => PIPoint.FindPIPoints(piServer, parsedQuery).Count() == (numberOfPointsToCreate / 2), TimeSpan.FromSeconds(10), TimeSpan.FromSeconds(0.5), $"The PI Points count do not match. Expected: {numberOfPointsToCreate / 2}, Actual: {searchPointsCount}."); } finally { PIFixture.DeletePIPoints("PIPointSearchTest_Point*", Output); } }
public static PiConnectionMgr ConnectAndGetServer(string server, out PIServer piServer) { var manager = new PiConnectionMgr(server); manager.Connect(); piServer = manager.GetPiServer(); return(manager); }
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. }
/// <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 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); } }
private static IList <PIPoint> GetOrCreatePIPoints(PIServer dataArchive, IEnumerable <string> inputTagNames, string prefix) { // Build a set of output tag names by sticking the prefix on each input tag name. var outputTagNames = inputTagNames.Select(name => $"{prefix}{name}"); // Let's see if the output tags already exist. Part of the exercise is to notify the end-user. // It'd be nice to have this as a List instead of IList so we can later use AddRange. var outputTags = GetPIPoints(dataArchive, outputTagNames).ToList(); foreach (var tag in outputTags) { Console.WriteLine($"Tag '{tag}' already exists."); } // Let's not think in terms of All Or None, as in either all are missing or none are. // Where's the fun in that? Instead we challenge outselves to check to see if any // individual names are missing and only create that subset. var missingTagNames = outputTagNames.Except(outputTags.Select(tag => tag.Name)); if (missingTagNames.Count() == 0) { // None were missing so we can return now. return(outputTags); } // We have at least one, if not all, to create. // When we fetch the input tag, e.g. "New York_Temperature", we want to also fetch its point attributes. // Since all known inputs are "classic", we will work with that. // But we don't need the Tag (Name) since we must use brand new names to create the output tags. var classicAttrs = GetPointAttributes(dataArchive, "classic").Except(ExcludedPointAttributes).ToArray(); // Simultaneously find tags and load the point attributes. // Note the points we want to find are those input tags where we do not have an existing output tag. var inputTags = GetPIPoints(dataArchive, missingTagNames.Select(name => name.Substring(prefix.Length)), classicAttrs); // Prep a dictionary of tag definitions var definitions = new Dictionary <string, IDictionary <string, object> >(); foreach (var tag in inputTags) { definitions[$"{prefix}{tag.Name}"] = tag.GetAttributes(classicAttrs); } // Make a bulk call to create all missing tags in one call. var createdPoints = dataArchive.CreatePIPoints(definitions); // Add the new tags to our output list. outputTags.AddRange(createdPoints.Results); return(outputTags); }
private void GetServer(string server) { if (_piServers.Contains(server)) { _piServer = _piServers[server]; } else { throw new KeyNotFoundException("Specified PI System does not exist"); } }
public PIPointsProvider(string query, PIServer server) { var queries = PIPointQuery.ParseQuery(server, query); if (queries == null || queries.Count < 1) { throw new Exception("The query passed was invalid, it would not find any PI Point"); } Points = PIPoint.FindPIPoints(server, queries); }
//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[]>(); }
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"); }
// Tag level public static void WriteTags(PIServer piServer, string outputFile) { using (StreamWriter outputStreamWriter = new StreamWriter(outputFile)) { foreach (PIPoint tag in PIPoint.FindPIPoints(piServer, "*")) { string path = tag.GetPath(); //Console.WriteLine(path); outputStreamWriter.WriteLine(path); } } }
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); } }
static void Main(string[] args) { Options arguments = Parser.Default.ParseArguments<Options>(args).MapResult(options => options, _ => null); Logger logger = new Logger(true, arguments.LogFile != null ? arguments.LogFile : null); logger.Log("Started"); // Server logger.Log($"Connecting to server {arguments.ServerName}"); PIServer piServer = PIUtil.GetPIServer(arguments.ServerName); logger.Log($"Connecting to system {arguments.SystemName}"); PISystem piSystem = AFUtil.GetPISystem(arguments.SystemName); logger.Log("Connected"); logger.Log($"Listing databases: system {arguments.SystemName}"); AFUtil.WriteDatabases(piSystem, arguments.DatabaseOutputFile); // Database if (arguments.DatabaseName != null) { AFDatabase database = AFUtil.GetDatabase(piSystem, arguments.DatabaseName); logger.Log($"Listing attributes for database {database.Name}"); AFUtil.WriteAttributes(database, arguments.AttributeOutputFile); } else { var outputFileExtension = Path.GetExtension(arguments.AttributeOutputFile); var outputFileName = Path.ChangeExtension(arguments.AttributeOutputFile, null); AFDatabases databases = piSystem.Databases; Parallel.ForEach( databases, new ParallelOptions { MaxDegreeOfParallelism = arguments.NumParallelTasks }, (AFDatabase database) => { logger.Log($"Listing attributes: database {database.Name}"); AFUtil.WriteAttributes(database, $"{outputFileName} {database.Name}{outputFileExtension}"); }); } logger.Log("Finished - press Enter to close terminal"); logger.Close(); Console.ReadLine(); }
/// <summary> /// Initialize a PI Server Connnection object. /// You should call the Connect method before access data with the PIServer property /// </summary> /// <param name="server">Name of the PI System (AF Server) to connect to</param> public PiConnectionMgr(string server) { // if the server does not exist in the local KST we throw an exception. This is a choice made, you could decide to connect anyway. // to do so you'll need to look at the PIServers.DirectoryOptions Property: https://techsupport.osisoft.com/Documentation/PI-AF-SDK/html/P_OSIsoft_AF_PI_PIServers_DirectoryOptions.htm // ex: //PIServers.DirectoryOptions=PISystems.AFDirectoryOptions.AutoAdd; if (_piServers.Contains(server)) _piServer = _piServers[server]; else { throw new KeyNotFoundException("Specified PI System does not exist"); } }
private PIPoint GetPIPoint(PIServer server, Guid signalID, string tagName) { string cachedTagName; PIPoint point = GetPIPoint(server, signalID, out cachedTagName); // If point was not found in cache or cached tag name does not match current tag name, attempt to lookup using current tag name if ((object)point == null || string.Compare(cachedTagName, tagName, StringComparison.OrdinalIgnoreCase) != 0) { point = GetPIPoint(server, tagName); } return(point); }
private void DeleteTags(PIServer server) { var tagNames = GeneratePointNames(NameSuffix, NumStart, NumEnd); Logger.Warn("Are you sure you want to delete the PI Points? PRESS 'y' to continue. Any other key to abort."); var input = Console.ReadKey(); if (input.KeyChar == 'y' || input.KeyChar == 'Y') { Logger.Warn("Deleting tags"); var result = server.DeletePIPoints(tagNames); if (result != null && result.HasErrors) result.Errors.ToList().ForEach(e => Logger.Error("Error with: " + e.Key, e.Value)); Logger.Info("operation completed."); return; } Logger.Info("operation aborted."); }
public TagsLoader(PIServer server) { _server = server; }
public Application() { myPIServers = new PIServers(); myPIServer = myPIServers["MARC-PI2016"]; myPIServer.Connect(); }
private PIPoint GetPIPoint(PIServer server, string tagName) { PIPoint point; PIPoint.TryFindPIPoint(server, tagName, out point); return point; }
private void ChangeConnectionTimeOut(PIServer server,int timeout) { if (server.Collective != null) { PICollective collective = server.Collective; // to change connection properties, in case of a collective foreach (PICollectiveMember member in collective.Members) { Logger.InfoFormat("Changing collective member {0} {1} from {2}s to {3}s", member.Name, "connection timeout", member.ConnectionTimeOut.TotalSeconds, timeout); member.ConnectionTimeOut = new TimeSpan(0, 0, timeout); } } else { Logger.InfoFormat("Changing server {0} {1} from {2}s to {3}s", server.Name, "connection timeout", server.ConnectionInfo.ConnectionTimeOut.TotalSeconds, timeout); server.ConnectionInfo.ConnectionTimeOut = new TimeSpan(0, 0, timeout); } }
private PIPoint GetPIPoint(PIServer server, Guid signalID, string tagName) { string cachedTagName; PIPoint point = GetPIPointBySignalID(server, signalID, out cachedTagName); // If point was not found in cache and cached tag name does not match current tag name, attempt to lookup using current tag name if ((object)point == null && string.Compare(cachedTagName, tagName, StringComparison.OrdinalIgnoreCase) != 0) point = GetPIPoint(server, tagName); return point; }
public WPIPoint() { PIServers srvrs = new PIServers(); m_piSrv = srvrs.DefaultPIServer; }
private PIPoint GetPIPointBySignalID(PIServer server, Guid signalID) { string cachedTagName; return GetPIPointBySignalID(server, signalID, out cachedTagName); }
//PIPoints /// <summary> /// Accesses the PIServer to get the PIPoints that are available. /// </summary> /// <param name="sys"> The current PISystem</param> /// <param name="serv"> The current PIServer</param> /// <returns></returns> public List<PIPoint> getPIPoints(PISystem sys, PIServer serv) { mainForm.Status("Getting PIPoints..."); currentSystem = sys; currentPIServer = serv; List<PIPoint> list; try { List<string> query = new List<string>() { "*" }; list = (List<PIPoint>)PIPoint.FindPIPoints(serv, query, null); return list; } catch { mainForm.Status("ERROR: Unable to attach to " + serv.Name); return null; } }
private IList<PIPoint> CreatePoints(PIServer server) { var tagNames = GeneratePointNames(NameSuffix, NumStart, NumEnd); Logger.Info("Creating the PI Points on the server"); var result = server.CreatePIPoints(tagNames, GetPointAttributes()); if (result != null && result.HasErrors) result.Errors.ToList().ForEach(e => Logger.Error("Error with: " + e.Key, e.Value)); Logger.Info("operation completed."); // if results are not nul returns the results, otherwise, returns null return result?.Results; }
private PIPoint GetPIPointBySignalID(PIServer server, Guid signalID, out string cachedTagName) { PIPoint point = null; // See if cached mapping exists between guid and tag name - tag name lookups are faster than GetPoints query if (m_tagMap.TryGetValue(signalID, out cachedTagName)) point = GetPIPoint(server, cachedTagName); if ((object)point == null) { // Point was not previously cached, lookup tag using signal ID stored in extended description field IEnumerable<PIPoint> points = PIPoint.FindPIPoints(server, $"EXDESC:='{signalID}'", false); point = points.FirstOrDefault(); if ((object)point != null) cachedTagName = point.Name; } return point; }
private void PITagSearch_Click(object sender, EventArgs e) { try { myPIServer = (PIServer)piServerPicker1.AFSelection; List<PIPoint> ptlist = AFOperations.FindPIPoints(this, myPIServer.Name, "", true, false); if (ptlist != null) { foreach (PIPoint pt in ptlist) { string[] displayvalues = new string[2]; displayvalues[0] = pt.Name; displayvalues[1] = pt.GetAttribute("Descriptor").ToString(); ListViewItem lvi = new ListViewItem(displayvalues); TagList.Items.Add(lvi); } } } catch (Exception ex) { MessageBox.Show(ex.Message + " : Have not connected PI Data Archive"); } }
private void piServerPicker1_ConnectionChange(object sender, SelectionChangeEventArgs e) { myPIServer = (PIServer)piServerPicker1.AFSelection; }