예제 #1
0
        private void WorkerDoWork(object sender, EventArgs <ScheduledTaskRunningReason> eventArgs)
        {
            m_pointStream.Reset();

            try
            {
                if (m_database == null)
                {
                    m_database = m_getDatabase();
                }
                m_database.Write(m_pointStream);
            }
            catch (Exception)
            {
                m_database = null;
                m_worker.Start(1000);
                return;
            }

            if (m_pointStream.QuitOnPointCount)
            {
                m_worker.Start();
            }
            else
            {
                m_worker.Start(1000);
            }
        }
예제 #2
0
        void ScannerThread()
        {
            int threadId = Interlocked.Increment(ref ThreadNumber);

            try
            {
                //DateTime start = DateTime.FromBinary(Convert.ToDateTime("2/1/2014").Date.Ticks + Convert.ToDateTime("6:00:00PM").TimeOfDay.Ticks).ToUniversalTime();
                while (!StopReading)
                {
                    Stopwatch sw = new Stopwatch();
                    using (HistorianClient client = new HistorianClient("127.0.0.1", 12345))
                        using (ClientDatabaseBase <HistorianKey, HistorianValue> database = client.GetDatabase <HistorianKey, HistorianValue>(String.Empty))
                        {
                            HistorianKey   key   = new HistorianKey();
                            HistorianValue value = new HistorianValue();

                            sw.Start();
                            TreeStream <HistorianKey, HistorianValue> scan = database.Read(0, ulong.MaxValue, new ulong[] { 65, 953, 5562 });
                            while (scan.Read(key, value))
                            {
                                ;
                            }
                            sw.Stop();
                        }

                    //Console.WriteLine("Thread: " + threadId.ToString() + " " + "Run Number: " + myId.ToString() + " " + (pointCount / sw.Elapsed.TotalSeconds / 1000000).ToString());
                }
            }
            catch (Exception)
            {
                //Console.WriteLine(ex.ToString());
            }
            Console.WriteLine("Thread: " + threadId.ToString() + " Quit");
        }
예제 #3
0
            protected override List <TimeSeriesValues> QueryTimeSeriesValues(DateTime startTime, DateTime stopTime, int maxDataPoints, Dictionary <ulong, string> targetMap, CancellationToken cancellationToken)
            {
                Dictionary <ulong, TimeSeriesValues> queriedTimeSeriesValues = new Dictionary <ulong, TimeSeriesValues>();

                if (targetMap.Count > 0)
                {
                    SnapServer server = GetAdapterInstance(InstanceName)?.Server?.Host;

                    if ((object)server != null)
                    {
                        ulong[]    measurementIDs = targetMap.Keys.ToArray();
                        Resolution resolution     = TrendValueAPI.EstimatePlotResolution(InstanceName, startTime, stopTime, measurementIDs);

                        using (SnapClient connection = SnapClient.Connect(server))
                            using (ClientDatabaseBase <HistorianKey, HistorianValue> database = connection.GetDatabase <HistorianKey, HistorianValue>(InstanceName))
                            {
                                foreach (TrendValue trendValue in TrendValueAPI.GetHistorianData(database, startTime, stopTime, measurementIDs, resolution, maxDataPoints, false, (CompatibleCancellationToken)cancellationToken))
                                {
                                    queriedTimeSeriesValues.GetOrAdd((ulong)trendValue.ID, id => new TimeSeriesValues {
                                        target = targetMap[id], datapoints = new List <double[]>()
                                    })
                                    .datapoints.Add(new[] { trendValue.Value, trendValue.Timestamp });
                                }
                            }
                    }
                }

                return(queriedTimeSeriesValues.Values.ToList());
            }
예제 #4
0
        public void Test2()
        {
            Logger.Console.Verbose = VerboseLevel.All;

            NetworkStreamSimulator netStream = new NetworkStreamSimulator();

            HistorianServerDatabaseConfig dbcfg = new HistorianServerDatabaseConfig("DB", @"C:\Archive", true);
            HistorianServer server = new HistorianServer(dbcfg);
            SecureStreamServer <SocketUserPermissions> auth = new SecureStreamServer <SocketUserPermissions>();

            auth.SetDefaultUser(true, new SocketUserPermissions()
            {
                CanRead  = true,
                CanWrite = true,
                IsAdmin  = true
            });

            SnapStreamingServer netServer = new SnapStreamingServer(auth, netStream.ServerStream, server.Host);

            ThreadPool.QueueUserWorkItem(ProcessClient, netServer);

            SnapStreamingClient client = new SnapStreamingClient(netStream.ClientStream, new SecureStreamClientDefault(), true);

            ClientDatabaseBase <HistorianKey, HistorianValue> db = client.GetDatabase <HistorianKey, HistorianValue>("DB");
            long len = db.Read().Count();

            System.Console.WriteLine(len);

            client.Dispose();
            server.Dispose();
        }
예제 #5
0
        public void TestArchiveWriter()
        {
            Random r = new Random(3);

            _ = new EncodingDefinition(EncodingDefinition.FixedSizeIndividualGuid, EncodingDefinition.FixedSizeIndividualGuid);
            AdvancedServerDatabaseConfig <AmiKey, AmiKey> config = new AdvancedServerDatabaseConfig <AmiKey, AmiKey>("KV2CPQ", "C:\\Temp\\AMI", true);

            using (SnapServer server = new SnapServer(config))
            {
                using (SnapClient client = SnapClient.Connect(server))
                    using (ClientDatabaseBase <AmiKey, AmiKey> db = client.GetDatabase <AmiKey, AmiKey>("KV2CPQ"))
                    {
                        int       count = 10000000;
                        Stopwatch sw    = new Stopwatch();
                        sw.Start();
                        AmiKey key   = new AmiKey();
                        AmiKey value = new AmiKey();

                        for (int x = count; x >= 0; x--)
                        {
                            key.Timestamp = (ulong)r.Next();
                            key.TableId   = r.Next();
                            db.Write(key, value);
                        }

                        sw.Stop();

                        Console.WriteLine(count / sw.Elapsed.TotalSeconds / 1000000);

                        Console.WriteLine(count);
                    }
            }
        }
예제 #6
0
        private void StartStream(object args)
        {
            HistorianKey   key   = new HistorianKey();
            HistorianValue value = new HistorianValue();

            using (HistorianClient client = new HistorianClient("127.0.0.1", 54996))
                using (ClientDatabaseBase <HistorianKey, HistorianValue> database = client.GetDatabase <HistorianKey, HistorianValue>(string.Empty))
                {
                    using (SortedTreeTable <HistorianKey, HistorianValue> file = SortedTreeFile.OpenFile(@"H:\OGE 2009.d2", isReadOnly: true).OpenOrCreateTable <HistorianKey, HistorianValue>(EncodingDefinition.FixedSizeCombinedEncoding))
                    {
                        using (SortedTreeTableReadSnapshot <HistorianKey, HistorianValue> read = file.BeginRead())
                        {
                            SortedTreeScannerBase <HistorianKey, HistorianValue> scan = read.GetTreeScanner();
                            scan.SeekToStart();
                            long count = 0;
                            while (scan.Read(key, value))
                            {
                                count++;
                                database.Write(key, value);
                                if ((count % 10) == 1)
                                {
                                    Thread.Sleep(1);
                                }
                            }
                        }
                    }
                }
        }
예제 #7
0
        private void ExecuteWildCardFileOperation(ClientDatabaseBase <HistorianKey, HistorianValue> database, string fileName, Action <List <Guid> > fileOperation)
        {
            HashSet <string> sourceFiles = new HashSet <string>(FilePath.GetFileList(fileName).Select(Path.GetFullPath), StringComparer.OrdinalIgnoreCase);
            List <Guid>      files       = database.GetAllAttachedFiles().Where(file => sourceFiles.Contains(Path.GetFullPath(file.FileName))).Select(file => file.Id).ToList();

            fileOperation(files);
        }
예제 #8
0
        public void TestReadPoints()
        {
            Stopwatch sw         = new Stopwatch();
            int       pointCount = 0;

            HistorianKey   key   = new HistorianKey();
            HistorianValue value = new HistorianValue();

            HistorianServerDatabaseConfig settings = new HistorianServerDatabaseConfig("PPA", @"C:\Program Files\openHistorian\Archive\", true);

            using (HistorianServer server = new HistorianServer(settings))
            {
                using (HistorianClient client = new HistorianClient("127.0.0.1", 12345))
                    using (ClientDatabaseBase <HistorianKey, HistorianValue> database = client.GetDatabase <HistorianKey, HistorianValue>(String.Empty))
                    {
                        TreeStream <HistorianKey, HistorianValue> stream = database.Read(0, (ulong)DateTime.MaxValue.Ticks, new ulong[] { 1 });
                        while (stream.Read(key, value))
                        {
                            ;
                        }

                        sw.Start();
                        stream = database.Read(0, (ulong)DateTime.MaxValue.Ticks, new ulong[] { 65, 953, 5562 });
                        while (stream.Read(key, value))
                        {
                            pointCount++;
                        }

                        sw.Stop();
                    }
            }
            Console.WriteLine(pointCount);
            Console.WriteLine(sw.Elapsed.TotalSeconds.ToString());
        }
        public void CreateScadaDatabase()
        {
            Array.ForEach(Directory.GetFiles(@"c:\temp\Scada\", "*.d2", SearchOption.AllDirectories), File.Delete);

            HistorianKey   key   = new HistorianKey();
            HistorianValue value = new HistorianValue();

            HistorianServerDatabaseConfig settings = new HistorianServerDatabaseConfig("DB", @"c:\temp\Scada\", true);

            using (HistorianServer server = new HistorianServer(settings, 12345))
            {
                using (HistorianClient client = new HistorianClient("127.0.0.1", 12345))
                    using (ClientDatabaseBase <HistorianKey, HistorianValue> database = client.GetDatabase <HistorianKey, HistorianValue>("DB"))
                    {
                        for (ulong x = 0; x < 1000; x++)
                        {
                            key.Timestamp = x;
                            database.Write(key, value);
                        }

                        database.HardCommit();
                        System.Threading.Thread.Sleep(1200);
                    }
            }
        }
 public SnapDBClient(SnapDBEngine engine, string instanceName)
 {
     m_client   = SnapClient.Connect(engine.ServerHost);
     m_database = m_client.GetDatabase <HistorianKey, HistorianValue>(instanceName);
     m_key      = new HistorianKey();
     m_value    = new HistorianValue();
     m_lastKey  = new HistorianKey();
 }
예제 #11
0
        public void TestWriteSpeed()
        {
            //Logger.ReportToConsole(VerboseLevel.All ^ VerboseLevel.DebugLow);
            //Logger.SetLoggingPath("c:\\temp\\");

            Globals.MemoryPool.SetMaximumBufferSize(4000 * 1024 * 1024L);

            //Thread th = new Thread(WriteSpeed);
            //th.IsBackground = true;
            //th.Start();

            //Quit = false;
            foreach (string file in Directory.GetFiles("c:\\temp\\benchmark\\", "*.*", SearchOption.AllDirectories))
            {
                File.Delete(file);
            }

            //PointCount = 0;

            HistorianServerDatabaseConfig settings = new HistorianServerDatabaseConfig("DB", "c:\\temp\\benchmark\\", true);

            using (SnapServer engine = new SnapServer(settings))
                using (SnapClient client = SnapClient.Connect(engine))
                    using (ClientDatabaseBase <HistorianKey, HistorianValue> db = client.GetDatabase <HistorianKey, HistorianValue>("DB"))
                    {
                        Thread.Sleep(100);
                        HistorianKey   key   = new HistorianKey();
                        HistorianValue value = new HistorianValue();

                        Stopwatch sw = new Stopwatch();
                        sw.Start();

                        for (int x = 0; x < PointsToArchive; x++)
                        {
                            key.PointID = (ulong)x;
                            //PointCount = x;
                            db.Write(key, value);
                        }

                        double totalTime = sw.Elapsed.TotalSeconds;
                        Console.WriteLine("Completed write test in {0:#,##0.00} seconds at {1:#,##0.00} points per second", totalTime, PointsToArchive / totalTime);
                    }
            //Quit = true;
            //th.Join();

            //Console.WriteLine("Time (sec)\tPoints");
            //foreach (var kvp in PointSamples)
            //{
            //    Console.WriteLine(kvp.Key.ToString() + "\t" + kvp.Value.ToString());
            //}

            GC.Collect();
            GC.WaitForPendingFinalizers();
            Thread.Sleep(100);
        }
예제 #12
0
        public SnapDBClient(string hostAddress, int port, string instanceName, ulong startTime, ulong endTime, int frameRate, IEnumerable <ulong> pointIDs)
        {
            m_client   = new HistorianClient(hostAddress, port);
            m_database = m_client.GetDatabase <HistorianKey, HistorianValue>(instanceName);
            m_key      = new HistorianKey();
            m_value    = new HistorianValue();

            SeekFilterBase <HistorianKey> timeFilter = TimestampSeekFilter.CreateFromRange <HistorianKey>(DataPoint.RoundTimestamp(startTime, frameRate), DataPoint.RoundTimestamp(endTime, frameRate));
            MatchFilterBase <HistorianKey, HistorianValue> pointFilter = PointIdMatchFilter.CreateFromList <HistorianKey, HistorianValue>(pointIDs);

            m_stream = m_database.Read(SortedTreeEngineReaderOptions.Default, timeFilter, pointFilter);
        }
예제 #13
0
 public IDictionary <Guid, SignalDataBase> GetQueryResult(DateTime startTime, DateTime endTime, int zoomLevel, IEnumerable <ISignalCalculation> signals)
 {
     using (ClientDatabaseBase <HistorianKey, HistorianValue> db = m_historian.GetDatabase <HistorianKey, HistorianValue>("PPA"))
     {
         //var db = m_historian.ConnectToDatabase("Full Resolution Synchrophasor");
         PeriodicScanner scanner = new PeriodicScanner(m_samplesPerSecond);
         SeekFilterBase <HistorianKey>      timestamps = scanner.GetParser(startTime, endTime, 1500u);
         SortedTreeEngineReaderOptions      options    = new SortedTreeEngineReaderOptions(TimeSpan.FromSeconds(1));
         IDictionary <Guid, SignalDataBase> results    = db.GetSignalsWithCalculations(timestamps, signals, options);
         return(results);
     }
 }
예제 #14
0
        /// <summary>
        /// Gets the database that matches <see cref="databaseName"/>
        /// </summary>
        /// <param name="databaseName">the case insensitive name of the databse</param>
        /// <returns></returns>
        public override ClientDatabaseBase GetDatabase(string databaseName)
        {
            DatabaseInfo info   = m_databaseInfos[databaseName.ToUpper()];
            Type         type   = typeof(SnapStreamingClient);
            MethodInfo   method = type.GetMethod("InternalGetDatabase", BindingFlags.NonPublic | BindingFlags.Instance);

            // ReSharper disable once PossibleNullReferenceException
            MethodInfo         reflectionMethod = method.MakeGenericMethod(info.KeyType, info.ValueType);
            ClientDatabaseBase db = (ClientDatabaseBase)reflectionMethod.Invoke(this, new object[] { databaseName });

            return(db);
        }
예제 #15
0
        /// <summary>
        /// Creates a new <see cref="ReportHistorianReader"/>.
        /// </summary>
        /// <param name="server">Snapserver to connect to <see cref="SnapServer"/>.</param>
        /// <param name="instanceName">Name of the instance to connect to.</param>
        /// <param name="startTime">Starttime.</param>
        /// <param name="endTime">Endtime.</param>
        /// <param name="frameRate">SamplingRate of the signal.</param>
        /// <param name="pointIDs">PointIDs to be collected.</param>
        public ReportHistorianReader(SnapServer server, string instanceName, DateTime startTime, DateTime endTime, int frameRate, IEnumerable <ulong> pointIDs)
        {
            m_client   = SnapClient.Connect(server);
            m_database = m_client.GetDatabase <HistorianKey, HistorianValue>(instanceName);
            m_key      = new HistorianKey();
            m_value    = new HistorianValue();

            SeekFilterBase <HistorianKey> timeFilter = TimestampSeekFilter.CreateFromRange <HistorianKey>(DataPoint.RoundTimestamp(startTime, frameRate), DataPoint.RoundTimestamp(endTime, frameRate));
            MatchFilterBase <HistorianKey, HistorianValue> pointFilter = PointIdMatchFilter.CreateFromList <HistorianKey, HistorianValue>(pointIDs);

            m_stream = m_database.Read(SortedTreeEngineReaderOptions.Default, timeFilter, pointFilter);
        }
    public static IEnumerable GetHistorianDataSampled(SqlString historianServer, SqlString instanceName, DateTime startTime, DateTime stopTime, TimeSpan interval, [SqlFacet(MaxSize = -1)] SqlString measurementIDs)
    {
        const int DefaultHistorianPort = 38402;

        if (historianServer.IsNull || string.IsNullOrEmpty(historianServer.Value))
        {
            throw new ArgumentNullException("historianServer", "Missing historian server parameter");
        }

        if (instanceName.IsNull || string.IsNullOrEmpty(instanceName.Value))
        {
            throw new ArgumentNullException("instanceName", "Missing historian instance name parameter");
        }

        if (startTime > stopTime)
        {
            throw new ArgumentException("Invalid time range specified", "startTime");
        }

        string[] parts    = historianServer.Value.Split(':');
        string   hostName = parts[0];
        int      port;

        if (parts.Length < 2 || !int.TryParse(parts[1], out port))
        {
            port = DefaultHistorianPort;
        }

        using (HistorianClient client = new HistorianClient(hostName, port))
            using (ClientDatabaseBase <HistorianKey, HistorianValue> reader = client.GetDatabase <HistorianKey, HistorianValue>(instanceName.Value))
            {
                var timeFilter = interval.Ticks == 0 ? TimestampSeekFilter.CreateFromRange <HistorianKey>(startTime, stopTime) :
                                 TimestampSeekFilter.CreateFromIntervalData <HistorianKey>(startTime, stopTime, interval, new TimeSpan(TimeSpan.TicksPerMillisecond));

                MatchFilterBase <HistorianKey, HistorianValue> pointFilter = null;
                HistorianKey   key   = new HistorianKey();
                HistorianValue value = new HistorianValue();

                if (!measurementIDs.IsNull && !string.IsNullOrEmpty(measurementIDs.Value))
                {
                    pointFilter = PointIdMatchFilter.CreateFromList <HistorianKey, HistorianValue>(measurementIDs.Value.Split(',').Select(ulong.Parse));
                }

                // Start stream reader for the provided time window and selected points
                using (TreeStream <HistorianKey, HistorianValue> stream = reader.Read(SortedTreeEngineReaderOptions.Default, timeFilter, pointFilter))
                {
                    while (stream.Read(key, value))
                    {
                        yield return(new Measurement(key.PointID, key.TimestampAsDate, value.AsSingle));
                    }
                }
            }
    }
예제 #17
0
        public void DeleteFile(string fileName)
        {
            ClientDatabaseBase <HistorianKey, HistorianValue> database = GetClientDatabase();

            if (fileName.Contains('*'))
            {
                ExecuteWildCardFileOperation(database, Path.GetFullPath(fileName), database.DeleteFiles);
            }
            else
            {
                ExecuteFileOperation(database, Path.GetFullPath(fileName), database.DeleteFiles);
            }
        }
예제 #18
0
        public void ReadData()
        {
            Logger.Console.Verbose = VerboseLevel.All;

            using (SnapServer server = CreateServer())
            {
                using (SnapClient client = SnapClient.Connect(server))
                    using (ClientDatabaseBase <HistorianKey, HistorianValue> db = client.GetDatabase <HistorianKey, HistorianValue>("PPA"))
                        using (TreeStream <HistorianKey, HistorianValue> stream = db.Read(null, null, null))
                        {
                            Console.WriteLine(stream.Count());
                        }
            }
        }
예제 #19
0
        /// <summary>
        /// Queries the provided signals within a the provided time window [Inclusive]
        /// </summary>
        /// <param name="database"></param>
        /// <param name="startTime">the lower bound of the time</param>
        /// <param name="endTime">the upper bound of the time. [Inclusive]</param>
        /// <param name="signals">an IEnumerable of all of the signals to query as part of the results set.</param>
        /// <returns></returns>
        public static Dictionary <ulong, RawSignalTimeValue> GetRawSignals(this ClientDatabaseBase <HistorianKey, HistorianValue> database, DateTime startTime, DateTime endTime, IEnumerable <ulong> signals)
        {
            HistorianKey   key   = new HistorianKey();
            HistorianValue value = new HistorianValue();

            Dictionary <ulong, RawSignalTimeValue> results = signals.ToDictionary((x) => x, (x) => new RawSignalTimeValue());

            TreeStream <HistorianKey, HistorianValue> stream = database.Read((ulong)startTime.Ticks, (ulong)endTime.Ticks, signals);

            while (stream.Read(key, value))
            {
                results[key.PointID].Signals.Add(key.TimestampAsDate, value.ToStruct());
            }
            return(results);
        }
예제 #20
0
        private void m_dailyTimer_Elapsed(object sender, ElapsedEventArgs e)
        {
            try
            {
                ClientDatabaseBase <HistorianKey, HistorianValue> database = GetClientDatabase();

                // Get list of files that have both a start time and an end time that are greater than the maximum archive days. We check both start and end times
                // since PMUs can provide bad time (not currently being filtered) and you don't want to accidentally delete a file with otherwise in-range data.
                ArchiveDetails[] filesToDelete = database.GetAllAttachedFiles().Where(file => (DateTime.UtcNow - file.StartTime).TotalDays > MaximumArchiveDays && (DateTime.UtcNow - file.EndTime).TotalDays > MaximumArchiveDays).ToArray();
                database.DeleteFiles(filesToDelete.Select(file => file.Id).ToList());
                OnStatusMessage("Deleted the following old archive files:\r\n    {0}", filesToDelete.Select(file => FilePath.TrimFileName(file.FileName, 75)).ToDelimitedString(Environment.NewLine + "    "));
            }
            catch (Exception ex)
            {
                OnProcessException(new InvalidOperationException($"Failed to limit maximum archive size: {ex.Message}", ex));
            }
        }
예제 #21
0
 public void TestReadData()
 {
     using (HistorianServer server = new HistorianServer(new HistorianServerDatabaseConfig("DB", @"c:\temp\Scada\", false), 1234))
     {
         using (SnapClient client = SnapClient.Connect(server.Host))
         {
             ClientDatabaseBase <HistorianKey, HistorianValue> database = client.GetDatabase <HistorianKey, HistorianValue>("DB");
             TreeStream <HistorianKey, HistorianValue>         stream   = database.Read(10, 800 - 1);
             HistorianKey   key   = new HistorianKey();
             HistorianValue value = new HistorianValue();
             while (stream.Read(key, value))
             {
                 Console.WriteLine(key.Timestamp);
             }
         }
     }
 }
예제 #22
0
        public void TestReadData()
        {
            HistorianKey   key   = new HistorianKey();
            HistorianValue value = new HistorianValue();

            var settings = new HistorianServerDatabaseConfig("PPA", @"c:\temp\Scada\", true);

            using (HistorianServer server = new HistorianServer(settings))
            {
                double count = 0;

                DebugStopwatch sw   = new DebugStopwatch();
                double         time = sw.TimeEvent(() =>
                {
                    count = 0;
                    using (HistorianClient client = new HistorianClient("127.0.0.1", 12345))
                        using (ClientDatabaseBase <HistorianKey, HistorianValue> database = client.GetDatabase <HistorianKey, HistorianValue>(String.Empty))
                        {
                            //IHistorianDatabase<HistorianKey, HistorianValue> database = server.GetDefaultDatabase();//.GetDatabase();
                            //TreeStream<HistorianKey, HistorianValue> stream = reader.Read(0, ulong.MaxValue, new ulong[] { 2 });
                            TreeStream <HistorianKey, HistorianValue> stream = database.Read(0, ulong.MaxValue);
                            while (stream.Read(key, value))
                            {
                                count++;
                            }
                        }
                });

                Console.WriteLine((count / 1000000 / time).ToString() + " Million PPS");
            }

            //Console.WriteLine("KeyMethodsBase calls");
            //for (int x = 0; x < 23; x++)
            //{
            //    Console.WriteLine(TreeKeyMethodsBase<HistorianKey>.CallMethods[x] + "\t" + ((TreeKeyMethodsBase<HistorianKey>.Method)(x)).ToString());
            //}
            //Console.WriteLine("ValueMethodsBase calls");
            //for (int x = 0; x < 5; x++)
            //{
            //    Console.WriteLine(TreeValueMethodsBase<HistorianValue>.CallMethods[x] + "\t" + ((TreeValueMethodsBase<HistorianValue>.Method)(x)).ToString());
            //}
            //for (int x = 0; x < 15; x++)
            //{
            //    Console.WriteLine(BinaryStreamBase.CallMethods[x] + "\t" + ((BinaryStreamBase.Method)(x)).ToString());
            //}
        }
예제 #23
0
        public void WriteData()
        {
            Logger.Console.Verbose = VerboseLevel.All;

            using (SnapServer server = CreateServer())
            {
                using (SnapClient client = SnapClient.Connect(server))
                    using (ClientDatabaseBase <HistorianKey, HistorianValue> db = client.GetDatabase <HistorianKey, HistorianValue>("PPA"))
                    {
                        HistorianKey   key   = new HistorianKey();
                        HistorianValue value = new HistorianValue();
                        key.TimestampAsDate = DateTime.Now;
                        key.PointID         = LittleEndian.ToUInt64(Guid.NewGuid().ToByteArray(), 0);
                        db.Write(key, value);
                    }
            }
        }
예제 #24
0
        public void GetAllFiles()
        {
            Logger.Console.Verbose = VerboseLevel.All;

            using (SnapServer server = CreateServer())
            {
                using (SnapClient client = SnapClient.Connect(server))
                    using (ClientDatabaseBase db = client.GetDatabase("PPA"))
                    {
                        foreach (ArchiveDetails f in db.GetAllAttachedFiles())
                        {
                            Console.WriteLine("{0}MB {1} TO {2}; ID:{3} Name: {4}",
                                              (f.FileSize / 1024d / 1024d).ToString("0.0"),
                                              f.FirstKey, f.LastKey, f.Id, f.FileName);
                        }
                    }
            }
        }
예제 #25
0
        /// <summary>
        /// Releases the unmanaged resources used by the <see cref="SnapNetworkClient"/> object and optionally releases the managed resources.
        /// </summary>
        /// <param name="disposing">true to release both managed and unmanaged resources; false to release only unmanaged resources.</param>
        protected override void Dispose(bool disposing)
        {
            if (m_disposed)
            {
                return;
            }

            try
            {
                if (!disposing)
                {
                    return;
                }

                if (m_sortedTreeEngine != null)
                {
                    m_sortedTreeEngine.Dispose();
                }

                m_sortedTreeEngine = null;

                try
                {
                    m_stream.Write((byte)ServerCommand.Disconnect);
                    m_stream.Flush();
                }
                catch (Exception ex)
                {
                    Logger.SwallowException(ex);
                }

                if (m_rawStream != null)
                {
                    m_rawStream.Dispose();
                }

                m_rawStream = null;
            }
            finally
            {
                m_disposed = true;       // Prevent duplicate dispose.
                base.Dispose(disposing); // Call base class Dispose().
            }
        }
예제 #26
0
        public void TestWriteSpeedRandom()
        {
            Logger.Console.Verbose = VerboseLevel.All;

            Random r  = new Random(1);
            Thread th = new Thread(WriteSpeed);

            th.IsBackground = true;
            th.Start();

            Quit = false;
            foreach (string file in Directory.GetFiles("c:\\temp\\benchmark\\"))
            {
                File.Delete(file);
            }

            PointCount = 0;

            HistorianServerDatabaseConfig settings = new HistorianServerDatabaseConfig("DB", "c:\\temp\\benchmark\\", true);

            using (SnapServer engine = new SnapServer(settings))
                using (SnapClient client = SnapClient.Connect(engine))
                    using (ClientDatabaseBase <HistorianKey, HistorianValue> db = client.GetDatabase <HistorianKey, HistorianValue>("DB"))
                    {
                        Thread.Sleep(100);
                        HistorianKey   key   = new HistorianKey();
                        HistorianValue value = new HistorianValue();
                        for (int x = 0; x < 10000000; x++)
                        {
                            key.Timestamp = (ulong)r.Next();
                            key.PointID   = (ulong)x;
                            PointCount    = x;
                            db.Write(key, value);
                        }
                    }
            Quit = true;
            th.Join();
            Console.WriteLine("Time (sec)\tPoints");
            foreach (KeyValuePair <double, int> kvp in PointSamples)
            {
                Console.WriteLine(kvp.Key.ToString() + "\t" + kvp.Value.ToString());
            }
        }
예제 #27
0
        public HistorianDataPointReader(ClientDatabaseBase <HistorianKey, HistorianValue> database, DateTime start, DateTime stop, TableDefinition tableDefinition)
        {
            HashSet <ulong> allPoints = new HashSet <ulong>();

            m_tableDefinition = tableDefinition;

            foreach (KeyValuePair <object, int?[]> signal in tableDefinition.m_signalGroups)
            {
                foreach (int?point in signal.Value)
                {
                    if (point.HasValue)
                    {
                        allPoints.Add((ulong)point.Value);
                    }
                }
            }
            //m_results = database.GetFrames((ulong)start.Ticks, (ulong)stop.Ticks, allPoints);
            m_currentFrame = -1;
        }
예제 #28
0
        private void btnPlot_Click(object sender, EventArgs e)
        {
            List <ulong> keys = new List <ulong>(chkAllPoints.CheckedItems.OfType <ulong>());

            plot.Clear();

            plot.AddInteraction(new PlotSurface2D.Interactions.HorizontalDrag());
            plot.AddInteraction(new PlotSurface2D.Interactions.VerticalDrag());
            plot.AddInteraction(new PlotSurface2D.Interactions.AxisDrag(false));

            if (keys.Count == 0)
            {
                return;
            }
            SnapClient client = SnapClient.Connect(m_archiveFile.Host);
            ClientDatabaseBase <HistorianKey, HistorianValue> db = client.GetDatabase <HistorianKey, HistorianValue>("");

            Dictionary <ulong, SignalDataBase> results = db.GetSignals(0, ulong.MaxValue, keys, TypeSingle.Instance);

            foreach (ulong point in keys)
            {
                List <double>  y    = new List <double>();
                List <double>  x    = new List <double>();
                SignalDataBase data = results[point];

                for (int i = 0; i < data.Count; i++)
                {
                    data.GetData(i, out ulong time, out double value);

                    x.Add(time);
                    y.Add(value);
                }

                LinePlot lines = new LinePlot(y, x);

                plot.Add(lines);
            }

            plot.Refresh();
            db.Dispose();
            client.Dispose();
        }
예제 #29
0
        public void TestRollover()
        {
            Logger.Console.Verbose = VerboseLevel.All;

            Globals.MemoryPool.SetMaximumBufferSize(4000 * 1024 * 1024L);

            foreach (string file in Directory.GetFiles("c:\\temp\\Test\\", "*.*", SearchOption.AllDirectories))
            {
                File.Delete(file);
            }

            PointCount = 0;

            HistorianServerDatabaseConfig settings = new HistorianServerDatabaseConfig("DB", "c:\\temp\\Test\\Main\\", true);

            settings.FinalWritePaths.Add("c:\\temp\\Test\\Rollover\\");

            ulong time = (ulong)DateTime.Now.Ticks;

            using (SnapServer engine = new SnapServer(settings))
                using (SnapClient client = SnapClient.Connect(engine))
                    using (ClientDatabaseBase <HistorianKey, HistorianValue> db = client.GetDatabase <HistorianKey, HistorianValue>("DB"))
                    {
                        Thread.Sleep(100);
                        HistorianKey   key   = new HistorianKey();
                        HistorianValue value = new HistorianValue();
                        for (int x = 0; x < 100000000; x++)
                        {
                            if (x % 100 == 0)
                            {
                                Thread.Sleep(10);
                            }
                            key.Timestamp = time;
                            time         += TimeSpan.TicksPerMinute;
                            db.Write(key, value);
                        }
                    }

            GC.Collect();
            GC.WaitForPendingFinalizers();
            Thread.Sleep(100);
        }
        public void TestReadData()
        {
            HistorianKey   key   = new HistorianKey();
            HistorianValue value = new HistorianValue();

            HistorianServerDatabaseConfig settings = new HistorianServerDatabaseConfig("DB", @"c:\temp\Scada\", true);

            using (HistorianServer server = new HistorianServer(settings, 12345))
            {
                using (HistorianClient client = new HistorianClient("127.0.0.1", 12345))
                    using (ClientDatabaseBase <HistorianKey, HistorianValue> database = client.GetDatabase <HistorianKey, HistorianValue>("DB"))
                    {
                        TreeStream <HistorianKey, HistorianValue> stream = database.Read(0, 1000);
                        while (stream.Read(key, value))
                        {
                            Console.WriteLine(key.Timestamp);
                        }
                    }
            }
        }