Exemple #1
1
 private void gameTimeButton_click(object sender, EventArgs e)
 {
     // Allow the user to set the appropriate properties.
     if (serialPort.IsOpen)
         serialPort.Close();
     serialPort.PortName = comComboBox.SelectedItem.ToString();
     serialPort.BaudRate = 9600;
     serialPort.Open();
     //send the Arduino an 'A' to get it going :)
     serialPort.Write("A");
     if (serialPort.IsOpen)
         Console.WriteLine(serialPort.PortName + " is open");
     serialPort.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);
     serverName = serverTextBox.Text;
     tagName = tagTextBox.Text;
     piSDK = new PISDK.PISDKClass();
     piServer = piSDK.Servers[serverName];
     if (piServer.Connected)
         Console.WriteLine("Connected to Server");
     piPoint = readPIPoint(piServer, tagName);
 }
        public void GetMultipleTest()
        {
            bool?         asParallel     = null;
            string        includeMode    = null;
            string        selectedFields = null;
            PIPoint       piPoint1       = instance.GetByPath(Constants.DATA_SERVER_PATH + @"\" + Constants.PIPOINT_CREATE_NAME);
            PIPoint       piPoint2       = instance.GetByPath(Constants.DATA_SERVER_PATH + @"\sinusoidu");
            List <string> webId          = new List <string>();

            webId.Add(piPoint1.WebId);
            webId.Add(piPoint2.WebId);
            var response = instance.GetMultiple(asParallel, includeMode, null, selectedFields, webId);

            Assert.IsInstanceOf <PIItemsItemPoint>(response, "response is PIItemsItemPoint");
            Assert.IsTrue(response.Items.Count == 2);
            Assert.IsTrue(response.Items[0].Object.WebId == piPoint1.WebId);

            List <string> path = new List <string>();

            path.Add(Constants.DATA_SERVER_PATH + @"\" + Constants.PIPOINT_CREATE_NAME);
            path.Add(Constants.DATA_SERVER_PATH + @"\sinusoid");
            var response2 = instance.GetMultiple(asParallel, includeMode, path, selectedFields, null);

            Assert.IsInstanceOf <PIItemsItemPoint>(response2, "response is PIItemsItemPoint");
            Assert.IsTrue(response2.Items.Count == 2);
            Assert.IsTrue(response.Items[0].Object.WebId == piPoint1.WebId);
        }
Exemple #3
0
        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();
        }
Exemple #4
0
 private void gameTimeButton_click(object sender, EventArgs e)
 {
     // Allow the user to set the appropriate properties.
     if (serialPort.IsOpen)
     {
         serialPort.Close();
     }
     serialPort.PortName = comComboBox.SelectedItem.ToString();
     serialPort.BaudRate = 9600;
     serialPort.Open();
     //send the Arduino an 'A' to get it going :)
     serialPort.Write("A");
     if (serialPort.IsOpen)
     {
         Console.WriteLine(serialPort.PortName + " is open");
     }
     serialPort.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);
     serverName = serverTextBox.Text;
     tagName    = tagTextBox.Text;
     piSDK      = new PISDK.PISDKClass();
     piServer   = piSDK.Servers[serverName];
     if (piServer.Connected)
     {
         Console.WriteLine("Connected to Server");
     }
     piPoint = readPIPoint(piServer, tagName);
 }
Exemple #5
0
        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);
        }
Exemple #6
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);
            }
        }
Exemple #7
0
        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();
        }
Exemple #8
0
        static void Main(string[] args)
        {
            PIPoint pIPoint = new PIPoint();

            PropertyInfo[] propertys = pIPoint.GetType().GetProperties();
            string         jsonFile  = "D:/vs2019proj/PIData/PIDataSave/PIDataSave/tagName.json";

            using (System.IO.StreamReader file = System.IO.File.OpenText(jsonFile))
            {
                using (JsonTextReader reader = new JsonTextReader(file))
                {
                    JArray jArray = (JArray)JToken.ReadFrom(reader);

                    foreach (JObject o in jArray)
                    {
                        IEnumerable <JProperty> properties = o.Properties();
                        foreach (JProperty item in properties)
                        {
                            string  key = item.Name;
                            JToken  val = item.Value;
                            JObject obj = JObject.Parse(val.ToString());
                            foreach (PropertyInfo property in propertys)
                            {
                                if (property.Name != "id" && property.Name != "time" && obj.ContainsKey(property.Name))
                                {
                                    string a     = obj[property.Name].ToString();
                                    string value = WebService.PIRead(
                                        $"select value from piarchive..piavg where tag = '{a}'  and  time BETWEEN '*-1h' AND '*'",
                                        key);
                                    JArray arr = (JArray)JsonConvert.DeserializeObject(value);

                                    foreach (JObject jo in arr)
                                    {
                                        string joValue = jo.Value <string>("value");
                                        property.SetValue(pIPoint, double.Parse(joValue), null);
                                    }
                                }
                            }
                        }
                    }
                }
            }
            pIPoint.time = DateTime.Now.ToLocalTime().ToString();

            //Program.WebService.PIRead("", "");


            string dbPath = "Data Source =" + Environment.CurrentDirectory + "/test.db";

            //conn.Close();
            SimpleCRUD.SetDialect(SimpleCRUD.Dialect.SQLite);
            using (IDbConnection db = new SQLiteConnection(dbPath))
            {
                db.Open();
                IDbTransaction tran = db.BeginTransaction();

                db.Insert(pIPoint, transaction: tran);
                tran.Commit();
            }
        }
Exemple #9
0
        }//LoadPIPointsFromFile

        private static AFKeyedResults <string, PIPoint> LoadPIPointsFromServer(ServerType serverType)
        {
            //This method pulls a list of PI points from the designated server
            List <string> lstPIPoints_from_File = new List <string>();
            bool          isDestination         = false;

            //Load the points from the point configuration file
            switch (serverType)
            {
            case ServerType.Source:
                lstPIPoints_from_File = PIPoints_from_File.Select(x => @"\\" + ConfigurationParameters.SourcePIDataArchive.Name + @"\" + x).ToList();
                break;

            case ServerType.Destination:
                lstPIPoints_from_File = PIPoints_from_File.Select(x => @"\\" + ConfigurationParameters.DestinationPIDataArchive.Name + @"\" + x).ToList();
                isDestination         = true;
                break;
            }

            //Load the points from the target PI Data Archive
            AFKeyedResults <string, PIPoint> findPointsResult = PIPoint.FindPIPointsByPath(lstPIPoints_from_File);

            //Perform error checking/logging
            CheckPIPointsForErrors(findPointsResult, isDestination);

            return(findPointsResult);
        }//LoadPIPointsFromServer
        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}].");
            }
        }
        public void ConnectToPIDataArchive()
        {
            piServer.Connect();
            IEnumerable <PIPoint> allPIPoints = PIPoint.FindPIPoints(piServer, "CityBikes*");

            allPIPointNames = allPIPoints.Select(p => p.Name).ToList();
        }
Exemple #12
0
        /// <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);
        }
Exemple #13
0
        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);
        }
Exemple #14
0
        /// <summary>
        /// Starts threads and timers to poll the PI server for data
        /// </summary>
        /// <param name="state">Filter string which will get the desired points from PI</param>
        private void StartGettingData(object state)
        {
            try
            {
                string tagFilter = state.ToString();

                m_points = new PIPointList(PIPoint.FindPIPoints(m_connection.Server, tagFilter, true));

                m_dataThread = new Thread(QueryData);
                m_dataThread.IsBackground = true;
                m_dataThread.Start();

                m_publishTimer          = new System.Timers.Timer();
                m_publishTimer.Interval = ProcessingInterval > 0 ? ProcessingInterval : 33;
                m_publishTimer.Elapsed += m_publishTimer_Tick;
                m_publishTimer.Start();
            }
            catch (ThreadAbortException)
            {
                throw;
            }
            catch (Exception e)
            {
                OnProcessException(e);
            }
        }
Exemple #15
0
        }//StartHistoricalDataCollection

        private void CreateAllHistoricalTimeRanges()
        {
            //This method will calculate how many historical time ranges to use and what they are; then queue them.
            Logger.Log("Calculating time ranges for historical data recovery. This could take a minute but have no fear, data transfer will begin shortly!", System.Diagnostics.EventLogEntryType.Information);

            List <int> eventCounts        = new List <int>();
            int        fractionPointCount = (int)Math.Ceiling((double)(PIPoints.Count / 10) + 0.1);

            //Pull out a random selection of PI points
            Random         _random        = new Random();
            List <PIPoint> testerPIPoints = new List <PIPoint>();

            for (int i = 0; i < 10 || i < fractionPointCount; i++)
            {
                int     randomIndex   = _random.Next(PIPoints.Count - 1);
                PIPoint randomPIPoint = PIPoints.CurrentPIPoints_Source[randomIndex];
                testerPIPoints.Add(randomPIPoint);
            }

            //Find the event count for each of the selected test points
            foreach (PIPoint pt in testerPIPoints)
            {
                int cnt = FindEventCount(pt, ConfigurationParameters.HistoryRecoveryStart, ConfigurationParameters.HistoryRecoveryEnd);
                eventCounts.Add(cnt);
            }

            //Determine the average number of events over the whole time range
            double averageCount = eventCounts.Average();

            //Create the ranges and queue them
            CreateRanges(averageCount, ConfigurationParameters.HistoryRecoveryStart, ConfigurationParameters.HistoryRecoveryEnd);
        }//DetermineHistoricalTimeRanges
Exemple #16
0
        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);
        }
Exemple #17
0
        public void CreatePointTest()
        {
            PIPoint pointDTO = new PIPoint
            {
                Name             = Constants.PIPOINT_CREATE_NAME,
                Descriptor       = "Test for swagger",
                PointClass       = "classic",
                PointType        = "Float32",
                EngineeringUnits = "",
                Step             = false,
                Future           = false
            };

            instance.CreatePoint(webId, pointDTO);

            try
            {
                instance.CreatePoint(webId, pointDTO);
                Assert.IsTrue(false);
            }
            catch (Exception)
            {
                Assert.IsTrue(true);
            }


            OSIsoft.AF.PI.PIPoint piPoint = null;
            var pointFound = OSIsoft.AF.PI.PIPoint.TryFindPIPoint(StandardPIServer, Constants.PIPOINT_CREATE_NAME, out piPoint);

            Assert.IsTrue(pointFound);
        }
        public IEnumerable <PIPoint> Search(string query)
        {
            var queries = PIPointQuery.ParseQuery(_server, query);
            var points  = PIPoint.FindPIPoints(_server, queries);

            return(points);
        }
Exemple #19
0
        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();
        }
Exemple #20
0
        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);
        }
Exemple #21
0
        public static void DeleteValues(PIPoint piPoint, AFTime st, AFTime et, bool forceUpdateValuesMethod = false)
        {
            var timerange = new AFTimeRange(st, et);

            if (piPoint.Server.Supports(PIServerFeature.DeleteRange) && forceUpdateValuesMethod == false)
            {
                var errors = piPoint.ReplaceValues(timerange, new List <AFValue>());

                if (errors != null && errors.HasErrors)
                {
                    _logger.Error(errors.Errors);
                    _logger.Error(errors.PIServerErrors);
                }
            }

            else
            {   // fallback on the old fashion way of doing the delete
                // if code goes here this may be much slower to delete the values.
                _logger.Warn("The ReplaceValues method is not implemented on the target PI DataArchive or the forceUpdateValuesMethod flag was used, falling back to the previous longer method ( read and remove)");

                var dataToDelete = piPoint.RecordedValues(timerange, AFBoundaryType.Inside, string.Empty, false);

                if (dataToDelete.Count > 0)
                {
                    piPoint.UpdateValues(dataToDelete, AFUpdateOption.Remove);
                }
            }
        }
Exemple #22
0
        private PIPoint GetPIPoint(PIServer server, string tagName)
        {
            PIPoint point;

            PIPoint.TryFindPIPoint(server, tagName, out point);
            return(point);
        }
        public void ArchiveQueryTest(string pointMask, string startTime, string endTime, double minValue, double maxValue)
        {
            var now = AFTime.Now;
            var st  = new AFTime(startTime, now);
            var et  = new AFTime(endTime, now);

            Output.WriteLine($"Start to execute PI Data Archive queries on PI Points matching [{pointMask}] " +
                             $"between [{st}] and [{et}].");

            IList <IEnumerable <PIPointQuery> > queries = PIPointQuery.ParseQuery(Fixture.PIServer, pointMask);
            IEnumerable <PIPoint>          pointList    = PIPoint.FindPIPoints(Fixture.PIServer, queries).ToList();
            IDictionary <string, AFValues> events       = Fixture.ReadPIEvents(pointList, st, et);

            // Verify all event values are in the expected range
            foreach (var ptvaluespair in events)
            {
                foreach (var val in ptvaluespair.Value.Where(val => val.IsGood))
                {
                    var convertedValue = Convert.ToDouble(val.Value, CultureInfo.InvariantCulture);
                    Assert.True(convertedValue >= minValue && convertedValue <= maxValue,
                                $"[{ptvaluespair.Key}] has a value [{val.Value}] outside of expected data range of " +
                                $"[{minValue} ~ {maxValue}]");
                }
            }

            Output.WriteLine($"Found {events.Sum(kvp => kvp.Value.Count)} PI events.");
        }
Exemple #24
0
        /// <summary>
        /// Deletes the PI Points matching the name filter.
        /// </summary>
        /// <param name="nameFilter">Name filter to use when deleting PI Points.</param>
        /// <param name="output">The output logger used for writing messages.</param>
        public void DeletePIPoints(string nameFilter, ITestOutputHelper output)
        {
            Contract.Requires(output != null);

            var pointList = new List <PIPoint>();

            pointList.AddRange(PIPoint.FindPIPoints(PIServer, nameFilter));

            if (pointList.Count <= 0)
            {
                output.WriteLine($"Did not find any PI Points to delete with name filter [{nameFilter}].");
            }
            else
            {
                output.WriteLine($"PI Points with name filter [{nameFilter}] found. Removing from [{PIServer.Name}].");
            }

            // Process PI Points in pages
            int i = 0;

            foreach (IList <PIPoint> pointGroup in pointList.GroupBy(name => i++ / PointPageSize).Select(g => g.ToList()))
            {
                AFErrors <string> errors = PIServer.DeletePIPoints(pointGroup.Select(pt => pt.Name));
                if (errors != null)
                {
                    throw errors.Errors.First().Value;
                }
            }
        }
Exemple #25
0
        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();
        }
Exemple #26
0
        //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();
        }
Exemple #27
0
        private async void WriteRangeAsync(PIPoint tag, SortedList <DateTime, int> values)
        {
            var status = await Task <bool> .Run(() =>
            {
                foreach (var iteam in values)
                {
                    try
                    {
                        tag.Data.UpdateValue(iteam.Value, iteam.Key);
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message, "Ошибка записи данных", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return(false);
                    }
                }
                return(true);
            });

            if (status)
            {
                notify("Запись выполнена успешно!");
                btWriteValues.Enabled = true;
            }
            else
            {
                btWriteValues.Enabled = true;
            }
        }
Exemple #28
0
        private void buttonWrite_Click(object sender, EventArgs e)
        {
            if (!isConnect)
            {
                return;
            }

            string tagName = textBoxTag.Text;
            double value;

            if (!double.TryParse(textBoxValue.Text, out value))
            {
                MessageBox.Show(string.Format("Не удалось распознать формат данных поля Value!!!"), "Ошибка ввода данных", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            ;
            DateTime date = dateTimePicker1.Value;

            PIPoint tag = searchPoint(tagName);

            if (tag == null)
            {
                return;
            }

            try
            {
                tag.Data.UpdateValue(value, date);
                notify(string.Format("Запись значения в {0} успешно выполнена!", tagName));
            }catch (Exception ex)
            {
                MessageBox.Show(string.Format("Не удалось записать значение в архив тега {0}\n\n {1}", tagName, ex.Message), "Ошибка данных", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
Exemple #29
0
        //<<<<<<<<<<Retrieve all the values from existing PI Point>>>>>>>>>>
        //NOTE: does not work
        public List <string> getValues(String tagName, DateTime startTime, DateTime endTime, TimeSpan span)
        {
            List <string>  Svalues  = new List <string>();
            List <PIValue> values   = new List <PIValue>();       // Create List instance
            PIPoint        point    = piServer.PIPoints[tagName]; // Create point instance
            DateTime       tempTime = startTime;                  // Set a temp start time for while loop

            while (tempTime < endTime)                            // Loop until endtime is reached
            {
                //Add data to values and increase the tempTime by the timespan
                values.Add(point.Data.ArcValue(tempTime, RetrievalTypeConstants.rtAtOrBefore));
                tempTime += span;
            }

            //Transfer to String list
            foreach (PIValue value in values)
            {
                if (value.ValueAttributes.GetType().IsCOMObject)
                {
                    Svalues.Add((value.Value as DigitalState).Name.ToString());
                }
                else
                {
                    Svalues.Add((value.Value).ToString());
                }
            }
            return(Svalues);
        }
Exemple #30
0
        /// <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);
            }
        }
        private void MonitorPITags()
        {
            DataPipeHandler archiveDataPipeHandler  = null;
            DataPipeHandler snapshotDataPipeHandler = null;

            try
            {
                if (string.IsNullOrEmpty(PIServerName))
                {
                    throw new PIServerNotFoundException();
                }

                else
                {
                    PIServer piserver;
                    var      piConnectionManager = PiConnectionMgr.ConnectAndGetServer(PIServerName, out piserver);

                    // get the tag we want to monitor
                    var pointList = PIPoint.FindPIPoints(piserver, TagList).ToList();

                    // event pipe for archive modifications
                    var archive = AFDataPipeType.Archive;

                    archiveDataPipeHandler = new DataPipeHandler(new PIConsoleDataObserver(archive), archive);
                    archiveDataPipeHandler.AddSignupsWithInitEvents(pointList);

                    // event pipe for snpshot modifications
                    var snapshot = AFDataPipeType.Snapshot;

                    snapshotDataPipeHandler = new DataPipeHandler(new PIConsoleDataObserver(snapshot), snapshot);
                    snapshotDataPipeHandler.AddSignupsWithInitEvents(pointList);


                    // archive data pipe is for demonstrative use
                    // you may only need the snapshot in your application, this depends on your use case
                    archiveDataPipeHandler.StartListening(TimeSpan.FromSeconds(Interval));

                    snapshotDataPipeHandler.StartListening(TimeSpan.FromSeconds(Interval));

                    Logger.InfoFormat("Listening for data changes started. Checking every {0}s", Interval);
                }
            }
            catch (Exception ex)
            {
                Logger.Error(ex);
            }


            finally
            {
                // here the method will wait until _terminateRequest.Set() before terminating
                _terminateRequest.WaitOne();

                // in case you don't know this is called null propagation
                // its equivalent to if x!=null x.Dispose()
                archiveDataPipeHandler?.Dispose();
                snapshotDataPipeHandler?.Dispose();
            }
        }
Exemple #32
0
 private void writePI(PIPoint piPoint, int data)
 {
     if (piPoint != null)
     {
         piPoint.Data.UpdateValue(data, 0, DataMergeConstants.dmReplaceDuplicates);
         Console.WriteLine("Sent " + data + " over PI System");
     }
 }
Exemple #33
-1
        public List<AFValue> GetRandomValues(PIPoint point, AFTime startTime, AFTime endTime, TimeSpan interval)
        {
            var newValues=new List<AFValue>();

            var currentTime = startTime.LocalTime;
            while (currentTime <= endTime.LocalTime)
            {

                newValues.Add(new AFValue()
                {
                    PIPoint = point,
                    Timestamp = currentTime,
                    Value = 1000*_random.NextDouble()
                });

                currentTime = currentTime.Add(interval);
            }

            return newValues;
        }