Exemplo n.º 1
0
        static void SensorList(String filename)
        {
            // try to open it for reading...
            Console.Write("Opening " + filename + " data-store for reading...");
            TinyOnDiskStorage data_store = new TinyOnDiskStorage(filename, false, 100000);

            Console.WriteLine("done");

            Dictionary <String, XS1_DataObject> Sensors = new Dictionary <string, XS1_DataObject>();

            foreach (OnDiscAdress ondisc in data_store.InMemoryIndex)
            {
                XS1_DataObject dataobject = new XS1_DataObject();
                dataobject.Deserialize(data_store.Read(ondisc));
                if (!Sensors.ContainsKey(dataobject.Name))
                {
                    Sensors.Add(dataobject.Name, dataobject);
                }
                //Console.WriteLine(dataobject.Timecode.ToLongTimeString()+";"+dataobject.Timecode.ToShortDateString()+";"+dataobject.Name+";"+dataobject.Type+";"+dataobject.TypeName+";"+dataobject.Value+";"+dataobject.OriginalXS1Statement);
            }

            foreach (XS1_DataObject dataobject in Sensors.Values)
            {
                Console.WriteLine(dataobject.Name + ";" + dataobject.Type + ";" + dataobject.TypeName + ";" + dataobject.Value + ";" + dataobject.OriginalXS1Statement);
            }
        }
Exemplo n.º 2
0
        /// <summary>
        /// generates JSON dataset from sensor data
        /// </summary>
        /// <returns></returns>
        public String GenerateDataJSONOutput_LastEntryOnly(ObjectTypes DataType, String ObjectTypeName, String ObjectName)
        {
            StringBuilder Output = new StringBuilder();

            //ConsoleOutputLogger.WriteLineToScreenOnly("...");

            Output.Append("{ \"label\": \"" + ObjectName + "\", \"data\": [");
            UInt64 SerializerCounter = 0;
            long   TimeCode          = DateTime.Now.JavaScriptTimestamp();
            String Value             = "0.0";

            // TODO: there should be an appropriate caching algorithm in the sensor data...
            lock (sensor_data.InMemoryIndex)
            {
                foreach (OnDiscAdress ondisc in sensor_data.InMemoryIndex.Reverse <OnDiscAdress>())
                {
                    XS1_DataObject dataobject = ReadFromCache(ondisc);
                    //Console.WriteLine(">>> "+dataobject.Name);
                    SerializerCounter++;

                    if (dataobject.Type == DataType)
                    {
                        if (dataobject.TypeName == ObjectTypeName)
                        {
                            if (dataobject.Name == ObjectName)
                            {
                                //ConsoleOutputLogger.WriteLineToScreenOnly(dataobject.Name);
                                TimeCode = dataobject.Timecode.JavaScriptTimestamp();
                                Value    = dataobject.Value.ToString().Replace(',', '.');
                                break;
                            }
                        }
                    }
                }
            }

            Output.Append("[");
            Output.Append(TimeCode);
            Output.Append(",");
            Output.Append(Value);
            Output.Append("]");
            Output.Append("]}");

            //ConsoleOutputLogger_.WriteLine("lastentry");
            ConsoleOutputLogger_.WriteLineToScreenOnly("Generated JSON Dataset with " + SerializerCounter + " Elements");

            return(Output.ToString());
        }
Exemplo n.º 3
0
        private XS1_DataObject ReadFromCache(OnDiscAdress adress)
        {
            XS1_DataObject dataobject = new XS1_DataObject();

            object cacheditem = sensor_data.Cache.ReadFromCache(adress);

            if (cacheditem == null)
            {
                // not found in cache, read from disk and add to cache
                dataobject.Deserialize(sensor_data.Read(adress));
                sensor_data.Cache.AddToCache(adress, dataobject);
            }
            else
            {
                // found in cache, take it...
                dataobject = (XS1_DataObject)cacheditem;
            }

            return(dataobject);
        }
Exemplo n.º 4
0
        public static string Generate(MAXMonitoringThread ELVMAX, TinyOnDiskStorage SensorDataStore, String ObjectName, String ObjectTypeName, DateTime StartDateTime, DateTime EndDateTime)
        {
            SwimLaneRootObject _root = new SwimLaneRootObject();

            _root.items = new System.Collections.Generic.List <ItemJSON>();
            _root.lanes = new System.Collections.Generic.List <LaneJSON>();
            #region fill the lanes
            // we need to have the data here
            // we shall have a cache (it's private for the other json methods... what about it?)
            // we need to have a selector which sensors need to be outputted...
            lock (SensorDataStore.InMemoryIndex)
            {
                foreach (OnDiscAdress ondisc in SensorDataStore.InMemoryIndex)
                {
                    if (ondisc.CreationTime >= StartDateTime.Ticks)
                    {
                        if (ondisc.CreationTime <= EndDateTime.Ticks)
                        {
                            // we are in the right timespan
                            // is this the right sensor?
                            XS1_DataObject dataobject = ReadFromCache(SensorDataStore, ondisc);

                            if (dataobject.TypeName == ObjectTypeName)
                            {
                                if (dataobject.Name == ObjectName)
                                {
                                    // okay we got what we want...
                                }
                            }
                        }
                    }
                }
            }
            #endregion

            return("");
        }
Exemplo n.º 5
0
        static void Main(string[] args)
        {
            Console.WriteLine("hacs storage performance tuning project: benchmark");
            Console.WriteLine("(C) 2013 Daniel Kirstenpfad - http://technology-ninja.com");
            Console.WriteLine();

            int       number      = 100000;
            int       cachefactor = 1;
            Stopwatch sw          = new Stopwatch();

            #region Generating benchmark data set
            if (Directory.Exists("benchmark-data"))
            {
                Directory.Delete("benchmark-data", true);
                Directory.CreateDirectory("benchmark-data");
            }
            else
            {
                Directory.CreateDirectory("benchmark-data");
            }
            sw.Start();
            TinyOnDiskStorage benchmark_storage = new TinyOnDiskStorage("benchmark-data" + Path.DirectorySeparatorChar + "benchmark-data", false, number / cachefactor);
            sw.Stop();
            Console.WriteLine("Initialized benchmark-data storage in " + sw.ElapsedMilliseconds + " ms");

            sw.Reset();

            Console.Write("Generating data (" + number + ") - ");

            int CursorLeft = Console.CursorLeft;
            int CursorTop  = Console.CursorTop;

            sw.Start();
            for (int i = 0; i <= number; i++)
            {
                //Console.SetCursorPosition(CursorLeft,CursorTop);
                //Console.Write(i+"/"+number);

                // now generating the file...
                XS1_DataObject data = new XS1_DataObject("ServerName", "Name", ObjectTypes.Actor, "TypeName", DateTime.Now, i, i);

                benchmark_storage.Write(data.Serialize());
            }
            sw.Stop();
            Console.WriteLine("done in " + sw.ElapsedMilliseconds + " ms");

            sw.Reset();
            Console.WriteLine("Resetting...");

            benchmark_storage.Shutdown();

            sw.Start();
            benchmark_storage = new TinyOnDiskStorage("benchmark-data" + Path.DirectorySeparatorChar + "benchmark-data", false, number / 2);
            sw.Stop();
            Console.WriteLine("Initialized benchmark-data storage in " + sw.ElapsedMilliseconds + " ms");
            sw.Reset();

            Console.Write("Reading (" + number + ") - ");
            int o = 0;
            sw.Start();
            foreach (OnDiscAdress addr in benchmark_storage.InMemoryIndex)
            {
                XS1_DataObject data = new XS1_DataObject();
                data.Deserialize(benchmark_storage.Read(addr));
                if (data.XS1ObjectID != o)
                {
                    Console.WriteLine(data.Timecode.ToString());
                }
                o++;
            }
            o--;
            sw.Stop();
            Console.WriteLine("done (" + o + ") in " + sw.ElapsedMilliseconds + " ms");
            sw.Reset();
            #endregion
        }
Exemplo n.º 6
0
        /// <summary>
        /// generates JSON dataset from sensor data
        /// </summary>
        /// <returns></returns>
        public String GenerateJSONDataActorStatistics(ObjectTypes DataType, String ObjectTypeName, String ObjectName, DateTime StartDateTime, DateTime EndDateTime)
        {
            /* Example:
             *
             * {    label: 'Europe (EU27)',
             *       data: [[1999, 3.0], [2000, 3.9], [2001, 2.0], [2002, 1.2], [2003, 1.3], [2004, 2.5], [2005, 2.0], [2006, 3.1], [2007, 2.9], [2008, 0.9]]
             * }
             *
             * */

            StringBuilder Output = new StringBuilder();

            Output.Append("{ \"label\": \"" + ObjectName + "\", \"data\": [");
            bool   firstdataset      = true;
            UInt64 SerializerCounter = 0;
            UInt64 OutputCounter     = 0;
            double LastValue         = double.NaN;

            // TODO: there should be an appropriate caching algorithm in the sensor data...

            lock (sensor_data.InMemoryIndex)
            {
                foreach (OnDiscAdress ondisc in sensor_data.InMemoryIndex)
                {
                    if (ondisc.CreationTime >= StartDateTime.Ticks)
                    {
                        if (ondisc.CreationTime <= EndDateTime.Ticks)
                        {
                            XS1_DataObject dataobject = ReadFromCache(ondisc);
                            SerializerCounter++;

                            if (dataobject.Type == DataType)
                            {
                                if (dataobject.TypeName == ObjectTypeName)
                                {
                                    if (dataobject.Name == ObjectName)
                                    {
                                        if (!firstdataset)
                                        {
                                            Output.Append(",");
                                        }
                                        else
                                        {
                                            firstdataset = false;
                                        }

                                        if (LastValue == double.NaN)
                                        {
                                            LastValue = dataobject.Value;
                                            Output.Append("[");
                                            Output.Append(dataobject.Timecode.JavaScriptTimestamp());
                                            Output.Append(",");
                                            Output.Append(dataobject.Value.ToString().Replace(',', '.'));
                                            Output.Append("]");
                                            OutputCounter++;
                                        }
                                        else
                                        {
                                            if (LastValue != dataobject.Value)
                                            {
                                                Output.Append("[");
                                                Output.Append(dataobject.Timecode.JavaScriptTimestamp());
                                                Output.Append(",");
                                                Output.Append(dataobject.Value.ToString().Replace(',', '.'));
                                                Output.Append("]");
                                                OutputCounter++;
                                            }
                                            LastValue = dataobject.Value;
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            Output.Append("]}");

            ConsoleOutputLogger_.WriteLineToScreenOnly("Generated JSON Dataset with " + SerializerCounter + " Elements and outputted " + OutputCounter + " Elements.");

            return(Output.ToString());
        }
Exemplo n.º 7
0
        public String GeneratePowerSensorJSONOutput(PowerSensorOutputs OutputType, String ObjectName, DateTime StartDateTime, DateTime EndDateTime)
        {
            StringBuilder Output  = new StringBuilder();
            StringBuilder Output2 = new StringBuilder();

            // TODO: there should be an appropriate caching algorithm in the sensor data...
            if (OutputType == PowerSensorOutputs.HourkWh)
            {
                #region Hour kWh
                Output.Append("{ \"label\": \"" + ObjectName + "\", \"data\": [");
                UInt64 SerializerCounter = 0;

                lock (sensor_data.InMemoryIndex)
                {
                    foreach (OnDiscAdress ondisc in sensor_data.InMemoryIndex)
                    {
                        if (ondisc.CreationTime >= StartDateTime.Ticks)
                        {
                            if (ondisc.CreationTime <= EndDateTime.Ticks)
                            {
                                XS1_DataObject dataobject = ReadFromCache(ondisc);
                                SerializerCounter++;

                                if (dataobject.Type == ObjectTypes.Sensor)
                                {
                                    if (dataobject.TypeName == "pwr_consump")
                                    {
                                        if (dataobject.Name == ObjectName)
                                        {
                                            // only up to a certain amount we consider this a valid value...
                                            if (dataobject.Value < 15000)
                                            {
                                                Output2.Clear();
                                                Output2.Append("[");
                                                Output2.Append(dataobject.Timecode.JavaScriptTimestamp());
                                                Output2.Append(",");
                                                //Double Value = dataobject.Value / 1000;
                                                Output2.Append(dataobject.Value.ToString().Replace(',', '.'));
                                                Output2.Append("]");
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                Output.Append(Output2.ToString());
                #endregion
            }

            if (OutputType == PowerSensorOutputs.HourPeakkWh)
            {
                #region Hour Peak kWh
                Output.Append("{ \"label\": \"" + ObjectName + "\", \"data\": [");
                UInt64 SerializerCounter = 0;

                lock (sensor_data.InMemoryIndex)
                {
                    foreach (OnDiscAdress ondisc in sensor_data.InMemoryIndex)
                    {
                        if (ondisc.CreationTime >= StartDateTime.Ticks)
                        {
                            if (ondisc.CreationTime <= EndDateTime.Ticks)
                            {
                                XS1_DataObject dataobject = ReadFromCache(ondisc);
                                SerializerCounter++;

                                if (dataobject.Type == ObjectTypes.Sensor)
                                {
                                    if (dataobject.TypeName == "pwr_peak")
                                    {
                                        if (dataobject.Name == ObjectName)
                                        {
                                            // only up to a certain amount we consider this a valid value...
                                            if (dataobject.Value < 15000)
                                            {
                                                Output2.Clear();
                                                Output2.Append("[");
                                                Output2.Append(dataobject.Timecode.JavaScriptTimestamp());
                                                Output2.Append(",");
                                                //Double Value = dataobject.Value / 1000;

                                                Output2.Append(dataobject.Value.ToString().Replace(',', '.'));
                                                Output2.Append("]");
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                Output.Append(Output2.ToString());
                #endregion
            }

            if (OutputType == PowerSensorOutputs.CalculatedkWhCounterTotal)
            {
                #region Calculated kWh Counter (based on last known manual reading)
                UInt64 SerializerCounter = 0;

                // find the right sensor manual reading...
                foreach (PowerConsumptionSensor _manual_reading in PowerSensorConfiguration.PowerConsumptionSensors)
                {
                    DateTime ManualMeasurementDate  = DateTime.MinValue;
                    Double   ManualMeasurementValue = Double.MinValue;

                    Output.Append("{ \"label\": \"" + ObjectName + "\", \"data\": [");


                    if (_manual_reading.PowerSensorName == ObjectName)
                    {
                        ManualMeasurementDate  = _manual_reading.InitialPowerSensorDate;
                        ManualMeasurementValue = _manual_reading.InitialPowerSensorValue;

                        // here comes the fun
                        StartDateTime = ManualMeasurementDate;
                        Double   PowerSensorCalculatedValue = ManualMeasurementValue;
                        DateTime CurrentHourStart           = StartDateTime;
                        Double   CurrentHourMeanValue       = Double.MinValue;
                        #region the lock
                        lock (sensor_data.InMemoryIndex)
                        {
                            foreach (OnDiscAdress ondisc in sensor_data.InMemoryIndex)
                            {
                                if (ondisc.CreationTime >= StartDateTime.Ticks)
                                {
                                    if (ondisc.CreationTime <= EndDateTime.Ticks)
                                    {
                                        XS1_DataObject dataobject = ReadFromCache(ondisc);
                                        SerializerCounter++;

                                        if (dataobject.Type == ObjectTypes.Sensor)
                                        {
                                            if (dataobject.TypeName == "pwr_consump")
                                            {
                                                if (dataobject.Name == ObjectName)
                                                {
                                                    // only up to a certain amount we consider this a valid value...
                                                    if (dataobject.Value < 15000)
                                                    {
                                                        // okay, we got the right sensor data element type with the right name...

                                                        // calculate the time difference between hour start and current data object
                                                        TimeSpan ts = new TimeSpan(dataobject.Timecode.Ticks - CurrentHourStart.Ticks);

                                                        if (ts.TotalMinutes >= 60)
                                                        {
                                                            // we have a full hour...add to the calculated value and reset hour values
                                                            CurrentHourStart            = dataobject.Timecode;
                                                            PowerSensorCalculatedValue += CurrentHourMeanValue / 1000;
                                                            //Console.WriteLine(" -> " + PowerSensorCalculatedValue + " : "+CurrentHourMeanValue + "("+dataobject.Timecode.ToShortDateString()+")");
                                                            CurrentHourMeanValue = Double.MinValue;
                                                        }
                                                        else
                                                        {
                                                            if (CurrentHourMeanValue == Double.MinValue)
                                                            {
                                                                CurrentHourMeanValue = dataobject.Value;
                                                            }
                                                            else
                                                            {
                                                                CurrentHourMeanValue = (CurrentHourMeanValue + dataobject.Value) / 2;
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        #endregion
                        // add the corrector value
                        PowerSensorCalculatedValue = PowerSensorCalculatedValue + _manual_reading.Corrector;

                        Output.Append("[");
                        Output.Append(DateTime.Now.JavaScriptTimestamp());
                        Output.Append(",");
                        Output.Append(PowerSensorCalculatedValue.ToString().Replace(',', '.'));
                        Output.Append("]");
                    }
                }
                #endregion
            }

            if (OutputType == PowerSensorOutputs.CalculatedDailykWh)
            {
                #region Calculated Daily kWh Counter
                Output.Append("{ \"label\": \"" + ObjectName + "\", \"data\": [");
                bool     firstdataset         = true;
                UInt64   SerializerCounter    = 0;
                DateTime CurrentHourStart     = StartDateTime;
                Double   CurrentHourMeanValue = Double.MinValue;

                // TODO: there should be an appropriate caching algorithm in the sensor data...
                lock (sensor_data.InMemoryIndex)
                {
                    Double DailyMeanValue = Double.MinValue;
                    Int32  HourNumber     = 0;

                    foreach (OnDiscAdress ondisc in sensor_data.InMemoryIndex)
                    {
                        if (ondisc.CreationTime >= StartDateTime.Ticks)
                        {
                            if (ondisc.CreationTime <= EndDateTime.Ticks)
                            {
                                XS1_DataObject dataobject = ReadFromCache(ondisc);
                                SerializerCounter++;

                                if (dataobject.Type == ObjectTypes.Sensor)
                                {
                                    if (dataobject.TypeName == "pwr_consump")
                                    {
                                        if (dataobject.Name == ObjectName)
                                        {
                                            // only up to a certain amount we consider this a valid value...
                                            if (dataobject.Value < 15000)
                                            {
                                                // calculate the time difference between hour start and current data object
                                                TimeSpan ts = new TimeSpan(dataobject.Timecode.Ticks - CurrentHourStart.Ticks);

                                                if (ts.TotalMinutes >= 60)
                                                {
                                                    // we have a full hour...add to the calculated value and reset hour values
                                                    CurrentHourStart = dataobject.Timecode;

                                                    HourNumber++;

                                                    if (HourNumber >= 24)
                                                    {
                                                        if (!firstdataset)
                                                        {
                                                            Output.Append(",");
                                                        }
                                                        else
                                                        {
                                                            firstdataset = false;
                                                        }

                                                        // we have 24 hours completed
                                                        Output.Append("[");
                                                        Output.Append(dataobject.Timecode.JavaScriptTimestamp());
                                                        Output.Append(",");
                                                        //CurrentHourMeanValue = CurrentHourMeanValue / 100;
                                                        Output.Append(CurrentHourMeanValue.ToString().Replace(',', '.'));
                                                        Output.Append("]");
                                                        HourNumber = 0;
                                                    }
                                                    else
                                                    {
                                                        if (DailyMeanValue == Double.MinValue)
                                                        {
                                                            DailyMeanValue = CurrentHourMeanValue;
                                                        }
                                                        else
                                                        {
                                                            DailyMeanValue = (DailyMeanValue + CurrentHourMeanValue) / 2;
                                                        }
                                                    }

                                                    CurrentHourMeanValue = Double.MinValue;
                                                }
                                                else
                                                {
                                                    if (CurrentHourMeanValue == Double.MinValue)
                                                    {
                                                        CurrentHourMeanValue = dataobject.Value;
                                                    }
                                                    else
                                                    {
                                                        CurrentHourMeanValue = (CurrentHourMeanValue + dataobject.Value) / 2;
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                    ConsoleOutputLogger_.WriteLineToScreenOnly("Generated JSON Dataset with " + SerializerCounter + " Elements");
                }

                #endregion
            }

            if (OutputType == PowerSensorOutputs.CalculatedHourlykWh)
            {
                #region Calculated Hourly kWh Counter
                Output.Append("{ \"label\": \"" + ObjectName + "\", \"data\": [");
                bool     firstdataset         = true;
                UInt64   SerializerCounter    = 0;
                DateTime CurrentHourStart     = StartDateTime;
                Double   CurrentHourMeanValue = Double.MinValue;

                // TODO: there should be an appropriate caching algorithm in the sensor data...
                lock (sensor_data.InMemoryIndex)
                {
                    foreach (OnDiscAdress ondisc in sensor_data.InMemoryIndex)
                    {
                        if (ondisc.CreationTime >= StartDateTime.Ticks)
                        {
                            if (ondisc.CreationTime <= EndDateTime.Ticks)
                            {
                                XS1_DataObject dataobject = ReadFromCache(ondisc);
                                SerializerCounter++;

                                if (dataobject.Type == ObjectTypes.Sensor)
                                {
                                    if (dataobject.TypeName == "pwr_consump")
                                    {
                                        if (dataobject.Name == ObjectName)
                                        {
                                            // only up to a certain amount we consider this a valid value...
                                            if (dataobject.Value < 15000)
                                            {
                                                // calculate the time difference between hour start and current data object
                                                TimeSpan ts = new TimeSpan(dataobject.Timecode.Ticks - CurrentHourStart.Ticks);

                                                if (ts.TotalMinutes >= 60)
                                                {
                                                    // we have a full hour...add to the calculated value and reset hour values
                                                    CurrentHourStart = dataobject.Timecode;

                                                    if (CurrentHourMeanValue > 0)
                                                    {
                                                        if (!firstdataset)
                                                        {
                                                            Output.Append(",");
                                                        }
                                                        else
                                                        {
                                                            firstdataset = false;
                                                        }

                                                        // we have 24 hours completed
                                                        Output.Append("[");
                                                        Output.Append(dataobject.Timecode.JavaScriptTimestamp());
                                                        Output.Append(",");
                                                        //CurrentHourMeanValue = CurrentHourMeanValue / 100;
                                                        Output.Append(CurrentHourMeanValue.ToString().Replace(',', '.'));
                                                        Output.Append("]");
                                                    }
                                                    CurrentHourMeanValue = Double.MinValue;
                                                }
                                                else
                                                {
                                                    if (CurrentHourMeanValue == Double.MinValue)
                                                    {
                                                        CurrentHourMeanValue = dataobject.Value;
                                                    }
                                                    else
                                                    {
                                                        CurrentHourMeanValue = (CurrentHourMeanValue + dataobject.Value) / 2;
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                    ConsoleOutputLogger_.WriteLineToScreenOnly("Generated JSON Dataset with " + SerializerCounter + " Elements");
                }

                #endregion
            }

            if (OutputType == PowerSensorOutputs.CalculateWeeklykWh)
            {
                #region Calculated Weekly kWh Counter
                Output.Append("{ \"label\": \"" + ObjectName + "\", \"data\": [");
                bool     firstdataset         = true;
                UInt64   SerializerCounter    = 0;
                DateTime CurrentHourStart     = StartDateTime;
                Double   CurrentHourMeanValue = Double.MinValue;

                // TODO: there should be an appropriate caching algorithm in the sensor data...
                lock (sensor_data.InMemoryIndex)
                {
                    Double DailyMeanValue = Double.MinValue;
                    Int32  HourNumber     = 0;

                    foreach (OnDiscAdress ondisc in sensor_data.InMemoryIndex)
                    {
                        if (ondisc.CreationTime >= StartDateTime.Ticks)
                        {
                            if (ondisc.CreationTime <= EndDateTime.Ticks)
                            {
                                XS1_DataObject dataobject = ReadFromCache(ondisc);
                                SerializerCounter++;

                                if (dataobject.Type == ObjectTypes.Sensor)
                                {
                                    if (dataobject.TypeName == "pwr_consump")
                                    {
                                        if (dataobject.Name == ObjectName)
                                        {
                                            // only up to a certain amount we consider this a valid value...
                                            if (dataobject.Value < 15000)
                                            {
                                                // calculate the time difference between hour start and current data object
                                                TimeSpan ts = new TimeSpan(dataobject.Timecode.Ticks - CurrentHourStart.Ticks);

                                                if (ts.TotalMinutes >= 60)
                                                {
                                                    // we have a full hour...add to the calculated value and reset hour values
                                                    CurrentHourStart = dataobject.Timecode;

                                                    HourNumber++;

                                                    if (HourNumber >= 168)
                                                    {
                                                        if (!firstdataset)
                                                        {
                                                            Output.Append(",");
                                                        }
                                                        else
                                                        {
                                                            firstdataset = false;
                                                        }

                                                        // we have 24 hours completed
                                                        Output.Append("[");
                                                        Output.Append(dataobject.Timecode.JavaScriptTimestamp());
                                                        Output.Append(",");
                                                        //CurrentHourMeanValue = CurrentHourMeanValue / 100;
                                                        Output.Append(CurrentHourMeanValue.ToString().Replace(',', '.'));
                                                        Output.Append("]");
                                                        HourNumber = 0;
                                                    }
                                                    else
                                                    {
                                                        if (DailyMeanValue == Double.MinValue)
                                                        {
                                                            DailyMeanValue = CurrentHourMeanValue;
                                                        }
                                                        else
                                                        {
                                                            DailyMeanValue = (DailyMeanValue + CurrentHourMeanValue) / 2;
                                                        }
                                                    }

                                                    CurrentHourMeanValue = Double.MinValue;
                                                }
                                                else
                                                {
                                                    if (CurrentHourMeanValue == Double.MinValue)
                                                    {
                                                        CurrentHourMeanValue = dataobject.Value;
                                                    }
                                                    else
                                                    {
                                                        CurrentHourMeanValue = (CurrentHourMeanValue + dataobject.Value) / 2;
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                    ConsoleOutputLogger_.WriteLineToScreenOnly("Generated JSON Dataset with " + SerializerCounter + " Elements");
                }

                #endregion
            }


            Output.Append("]}");

            //ConsoleOutputLogger.WriteLineToScreenOnly("Generated JSON Dataset with " + SerializerCounter + " Elements");

            return(Output.ToString());
        }
Exemplo n.º 8
0
        // this is providing us with XS1 data objects in result of XS1 events
        public void Run()
        {
            while (running)
            {
                try
                {
                    byte[] buf = new byte[8192];

                    String HacsURL = "http://" + ServerName + "/control?callback=cname&cmd=subscribe&format=tsv";

                    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(HacsURL);
                    request.Timeout     = 60000;
                    request.Credentials = new NetworkCredential(UserName, Password);

                    String _UsernameAndPassword = UserName + ":" + Password;
                    Uri    _URI = new Uri(HacsURL);

                    CredentialCache _CredentialCache = new CredentialCache();
                    _CredentialCache.Remove(_URI, "Basic");
                    _CredentialCache.Add(_URI, "Basic", new NetworkCredential(UserName, Password));
                    String _AuthorizationHeader = "Basic " + Convert.ToBase64String(new ASCIIEncoding().GetBytes(_UsernameAndPassword));

                    request.Headers.Add("Authorization", _AuthorizationHeader);

                    // execute the request
                    HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                    if (response.StatusCode == HttpStatusCode.OK)
                    {
                        AcceptingCommands = true;
                        ConsoleOutputLogger.WriteLineToScreenOnly("XS1 successfully connected!");
                    }
                    // we will read data via the response stream
                    Stream resStream = response.GetResponseStream();

                    string tempString = null;
                    int    count      = 0;

                    do
                    {
                        #region XS1 Receiving and Queue stuffing
                        // fill the buffer with data
                        count = resStream.Read(buf, 0, buf.Length);

                        // make sure we read some data
                        if (count != 0)
                        {
                            // translate from bytes to ASCII text
                            tempString = Encoding.ASCII.GetString(buf, 0, count);
                            XS1_DataObject dataobject = HandleXS1_TSV.HandleValue(tempString);
                            dataobject.ServerName           = ServerName;
                            dataobject.OriginalXS1Statement = tempString;

                            iQueue.Enqueue(dataobject);                                 // add it to the queue
                        }
                        #endregion
                    }while (count > 0);                    // any more data to read?
                }
                catch (Exception)
                {
                    AcceptingCommands = false;
                    Thread.Sleep(1);
                }
            }
        }
Exemplo n.º 9
0
        public void Run()
        {
            // initialize XS1 Configuration
            XS1_Configuration = new XS1Configuration(ConfigurationCacheMinutes);
            MAXMonitoringThread      ELVMax   = null;
            SolarLogMonitoringThread SolarLog = null;
            // Start Sensor-Check Thread
            SensorCheck Sensorcheck       = new SensorCheck(ConsoleOutputLogger);
            Thread      SensorCheckThread = new Thread(new ThreadStart(Sensorcheck.Run));

            SensorCheckThread.Start();

            // Start Actor Re-Switching Thread
            ActorReswitching ActorReSwitch_      = new ActorReswitching(XS1_Configuration, ConsoleOutputLogger, TemporaryBlacklist, OnWaitOffLIst);
            Thread           ActorReswitchThread = new Thread(new ThreadStart(ActorReSwitch_.Run));

            ActorReswitchThread.Start();

            // Start the SolarLog Thread (if enabled)
            // TODO: make it switchable / configurable
            if (Properties.Settings.Default.SolarLogEnabled)
            {
                SolarLog = new SolarLogMonitoringThread(Properties.Settings.Default.SolarLogURLDomain, ConsoleOutputLogger, SolarLog_DataQueue, Properties.Settings.Default.SolarLogUpdateIntervalMsec);
                Thread SolarLogThread = new Thread(new ThreadStart(SolarLog.Run));
                SolarLogThread.Start();
            }

            // Start the ELVMax Thread
            if (Properties.Settings.Default.ELVMAXEnabled)
            {
                ELVMax = new MAXMonitoringThread(Properties.Settings.Default.ELVMAXIP, Properties.Settings.Default.ELVMAXPort, ConsoleOutputLogger, MAX_DataQueue, Properties.Settings.Default.ELVMAXUpdateIntervalMsec);
                Thread ELVMaxThread = new Thread(new ThreadStart(ELVMax.Run));
                ELVMaxThread.Start();
            }

            XS1MonitoringThread XS1 = new XS1MonitoringThread(ServerName, ConsoleOutputLogger, UserName, Password, XS1_DataQueue);
            Thread XS1Thread        = new Thread(new ThreadStart(XS1.Run));

            XS1Thread.Start();

            // Start integrated HTTP Server
            HttpServer httpServer         = new HttpServer(Properties.Settings.Default.HTTPPort, Properties.Settings.Default.HTTPIP, Properties.Settings.Default.HTTPDocumentRoot, sensor_data_store, miataru_data_store, XS1_Configuration, ConsoleOutputLogger, ELVMax, Properties.Settings.Default.HTTPAuthEnabled, Properties.Settings.Default.HTTPAuthUsername, Properties.Settings.Default.HTTPAuthPassword, Properties.Settings.Default.HTTPAuthDisabledAdressStartsWith);
            Thread     http_server_thread = new Thread(new ThreadStart(httpServer.listen));

            http_server_thread.Start();

            // Start Service Monitorng thread
            if (Properties.Settings.Default.NetworkMonitorEnabled)
            {
                NetworkMonitoring monitor       = new NetworkMonitoring(ConsoleOutputLogger, NetworkMonitor_Queue, Properties.Settings.Default.NetworkMonitorUpdateIntervalMsec);
                Thread            monitorThread = new Thread(new ThreadStart(monitor.Run));
                monitorThread.Start();
            }

            // Start Alarming thread
            if (Properties.Settings.Default.AlarmingEnabled)
            {
                AlarmingThread alarmThread     = new AlarmingThread(ConsoleOutputLogger, Alarming_Queue, sensor_data_store, actor_data_store, miataru_data_store);
                Thread         alarming_thread = new Thread(new ThreadStart(alarmThread.Run));
                alarming_thread.Start();
            }

            // Start Miataru Thread
            if (Properties.Settings.Default.MiataruEnabled)
            {
                MiataruThread miataruThread  = new MiataruThread(ConsoleOutputLogger, miataru_data_store, Properties.Settings.Default.MiataruUpdateTime);
                Thread        miataru_Thread = new Thread(new ThreadStart(miataruThread.Run));
                miataru_Thread.Start();
            }

            // Start MQTT Thread
            if (Properties.Settings.Default.MQTTBindingEnabled)
            {
                MQTT_Binding = new MQTT_Handling(ConsoleOutputLogger);
                Thread mqtt_Thread = new Thread(new ThreadStart(MQTT_Binding.Run));
                mqtt_Thread.Start();
            }

            while (!Shutdown)
            {
                try
                {
                    #region Handle XS1 events
                    XS1_DataObject dataobject = null;
                    if (XS1_DataQueue.TryDequeue(out dataobject))
                    {
                        if (dataobject.Type == ObjectTypes.Actor)
                        {
                            // Write to Disk
                            lock (actor_data_store)
                            {
                                actor_data_store.Write(dataobject.Serialize());
                            }

                            lock (KnownActorStates.KnownActorStatuses)
                            {
                                bool usethisactor = true;
                                // check if this actor is on temporary blacklist (like when it was handled)
                                lock (TemporaryBlacklist)
                                {
                                    if (TemporaryBlacklist.Contains(dataobject.Name))
                                    {
                                        usethisactor = false;
                                    }
                                    TemporaryBlacklist.Remove(dataobject.Name);
                                }

                                if (usethisactor)
                                {
                                    // if Alarming is enabled, queue this XS1 Event up for alarming...
                                    if (Properties.Settings.Default.AlarmingEnabled)
                                    {
                                        Alarming_Queue.Enqueue(dataobject);
                                    }

                                    // this actor action did not result in any action hacs made - so we try to make the best out of it
                                    #region Scripting Handling
                                    // check if this sensor is something we should act uppon
                                    foreach (ScriptingActorElement Element in ScriptingActorConfiguration.ScriptingActorActions)
                                    {
                                        if (dataobject.Name == Element.SensorToWatchName)
                                        {
                                            if (dataobject.Value == Element.SensorValue)
                                            {
                                                // obviously there is a ScriptingActorConfiguration entry
                                                // so we execute the actor preset

                                                set_state_actuator.set_state_actuator ssa = new set_state_actuator.set_state_actuator();
                                                ConsoleOutputLogger.WriteLineToScreenOnly("detected actor scripting action on actor " + Element.SensorToWatchName + " - " + Element.ActorToSwitchName + " to " + Element.ActionToRunName);

                                                if (Element.isCurrentlyWithinStartEndHours())
                                                {
                                                    #region Scripting Actor Actions
                                                    if (Element.ActionToRunName == actor_status.URL)
                                                    {
                                                        ConsoleOutputLogger.WriteLine("Scripting Actor URL");
                                                        // handle URLs -> the ActorToSwitch Name will be the URL to trigger


                                                        try
                                                        {
                                                            WebClient client = new WebClient();
                                                            client.Encoding = System.Text.Encoding.UTF8;
                                                            String JSONInput = client.DownloadString(Element.ActorToSwitchName);

                                                            ConsoleOutputLogger.WriteLine("Doing HTTP GET on: " + Element.ActorToSwitchName);
                                                        }
                                                        catch (Exception e)
                                                        {
                                                            ConsoleOutputLogger.WriteLine("Exception on URL Actor Scripting: " + e.Message);
                                                        }
                                                    }

                                                    // check what action is going to happen now...
                                                    if (Element.ActionToRunName == actor_status.On)
                                                    {
                                                        ssa.SetStateActuatorPreset(hacs.Properties.Settings.Default.XS1, hacs.Properties.Settings.Default.Username, hacs.Properties.Settings.Default.Password, Element.ActorToSwitchName, "ON", XS1_Configuration);
                                                    }

                                                    if (Element.ActionToRunName == actor_status.Off)
                                                    {
                                                        ssa.SetStateActuatorPreset(hacs.Properties.Settings.Default.XS1, hacs.Properties.Settings.Default.Username, hacs.Properties.Settings.Default.Password, Element.ActorToSwitchName, "OFF", XS1_Configuration);

                                                        // remove from OnWaitOffList
                                                        lock (OnWaitOffLIst)
                                                        {
                                                            if (OnWaitOffLIst.Contains(Element.ActorToSwitchName))
                                                            {
                                                                OnWaitOffLIst.Remove(Element.ActorToSwitchName);
                                                            }
                                                        }
                                                    }

                                                    if (Element.ActionToRunName == actor_status.OnOff)
                                                    {
                                                        // look for the current status in the known actors table
                                                        lock (KnownActorStates.KnownActorStatuses)
                                                        {
                                                            if (KnownActorStates.KnownActorStatuses.ContainsKey(Element.ActorToSwitchName))
                                                            {
                                                                current_actor_status Status = KnownActorStates.KnownActorStatuses[Element.ActorToSwitchName];
                                                                if (Status.Status == actor_status.On)
                                                                {
                                                                    ssa.SetStateActuatorPreset(hacs.Properties.Settings.Default.XS1, hacs.Properties.Settings.Default.Username, hacs.Properties.Settings.Default.Password, Element.ActorToSwitchName, "OFF", XS1_Configuration);
                                                                }
                                                                else
                                                                if (Status.Status == actor_status.Off)
                                                                {
                                                                    ssa.SetStateActuatorPreset(hacs.Properties.Settings.Default.XS1, hacs.Properties.Settings.Default.Username, hacs.Properties.Settings.Default.Password, Element.ActorToSwitchName, "ON", XS1_Configuration);
                                                                }
                                                            }
                                                            else
                                                            {
                                                                ssa.SetStateActuatorPreset(hacs.Properties.Settings.Default.XS1, hacs.Properties.Settings.Default.Username, hacs.Properties.Settings.Default.Password, Element.ActorToSwitchName, "ON", XS1_Configuration);
                                                            }
                                                        }
                                                    }
                                                    if (Element.ActionToRunName == actor_status.OnWaitOff)
                                                    {
                                                        lock (OnWaitOffLIst)
                                                        {
                                                            ConsoleOutputLogger.WriteLine("Adding " + Element.ActorToSwitchName + " to ActorReSwitching OnWaitOff List");
                                                            OnWaitOffLIst.Add(Element.ActorToSwitchName);
                                                        }
                                                        ssa.SetStateActuatorPreset(hacs.Properties.Settings.Default.XS1, hacs.Properties.Settings.Default.Username, hacs.Properties.Settings.Default.Password, Element.ActorToSwitchName, "ON_WAIT_OFF", XS1_Configuration);
                                                    }
                                                    #endregion
                                                }
                                            }
                                        }
                                    }
                                    #endregion

                                    #region MQTT Handling Actor
                                    if (Properties.Settings.Default.MQTTBindingEnabled)
                                    {
                                        MQTT_Binding.MQTT_Handle_Actor(dataobject);
                                    }
                                    #endregion

                                    if (KnownActorStates.KnownActorStatuses.ContainsKey(dataobject.Name))
                                    {
                                        // is contained
                                        if (dataobject.Value == 100)
                                        {
                                            KnownActorStates.KnownActorStatuses[dataobject.Name] = new current_actor_status(dataobject.Name, actor_status.On);
                                        }
                                        else
                                        {
                                            KnownActorStates.KnownActorStatuses[dataobject.Name] = new current_actor_status(dataobject.Name, actor_status.Off);
                                        }
                                    }
                                    else
                                    {
                                        if (dataobject.Value == 100)
                                        {
                                            KnownActorStates.KnownActorStatuses.Add(dataobject.Name, new current_actor_status(dataobject.Name, actor_status.On));
                                        }
                                        else
                                        {
                                            KnownActorStates.KnownActorStatuses.Add(dataobject.Name, new current_actor_status(dataobject.Name, actor_status.Off));
                                        }
                                    }
                                }
                                else
                                {
                                    ConsoleOutputLogger.WriteLine("Actor " + dataobject.Name + " is on the blacklist (ActorReSwitching) and therefore is ignored this time.");
                                }
                            }
                        }
                        else
                        if (dataobject.Type == ObjectTypes.Sensor)
                        {
                            lock (sensor_data_store)
                            {
                                sensor_data_store.Write(dataobject.Serialize());
                            }
                            // update the sensor in the sensor check
                            Sensorcheck.UpdateSensor(dataobject.Name);

                            // if Alarming is enabled, queue this XS1 Event up for alarming...
                            if (Properties.Settings.Default.AlarmingEnabled)
                            {
                                if (!dataobject.IgnoreForAlarming)                                              // this if for those events which get re-queued as xs1 events despite being for example elvmax events
                                {
                                    Alarming_Queue.Enqueue(dataobject);
                                }
                            }

                            #region Scripting
                            // check if this sensor is something we should act uppon
                            foreach (ScriptingActorElement Element in ScriptingActorConfiguration.ScriptingActorActions)
                            {
                                if (dataobject.Name == Element.SensorToWatchName)
                                {
                                    if (dataobject.Value == Element.SensorValue)
                                    {
                                        // obviously there is a ScriptingActorConfiguration entry
                                        // so we execute the actor preset

                                        set_state_actuator.set_state_actuator ssa = new set_state_actuator.set_state_actuator();
                                        ConsoleOutputLogger.WriteLineToScreenOnly("detected actor scripting action on sensor " + Element.SensorToWatchName + " - " + Element.ActorToSwitchName + " to " + Element.ActionToRunName);
                                        if (Element.isCurrentlyWithinStartEndHours())
                                        {
                                            #region Scripting Actor actions
                                            if (Element.ActionToRunName == actor_status.URL)
                                            {
                                                ConsoleOutputLogger.WriteLine("Scripting Actor URL");
                                                // handle URLs -> the ActorToSwitch Name will be the URL to trigger

                                                try
                                                {
                                                    WebClient client = new WebClient();
                                                    client.Encoding = System.Text.Encoding.UTF8;
                                                    String JSONInput = client.DownloadString(Element.ActorToSwitchName);

                                                    ConsoleOutputLogger.WriteLine("Doing HTTP GET on: " + Element.ActorToSwitchName);
                                                }
                                                catch (Exception e)
                                                {
                                                    ConsoleOutputLogger.WriteLine("Exception on URL Actor Scripting: " + e.Message);
                                                }
                                            }

                                            // check what action is going to happen now...
                                            if (Element.ActionToRunName == actor_status.On)
                                            {
                                                ssa.SetStateActuatorPreset(hacs.Properties.Settings.Default.XS1, hacs.Properties.Settings.Default.Username, hacs.Properties.Settings.Default.Password, Element.ActorToSwitchName, "ON", XS1_Configuration);
                                            }

                                            if (Element.ActionToRunName == actor_status.Off)
                                            {
                                                ssa.SetStateActuatorPreset(hacs.Properties.Settings.Default.XS1, hacs.Properties.Settings.Default.Username, hacs.Properties.Settings.Default.Password, Element.ActorToSwitchName, "OFF", XS1_Configuration);

                                                // remove from OnWaitOffList
                                                lock (OnWaitOffLIst)
                                                {
                                                    if (OnWaitOffLIst.Contains(Element.ActorToSwitchName))
                                                    {
                                                        OnWaitOffLIst.Remove(Element.ActorToSwitchName);
                                                    }
                                                }
                                            }

                                            if (Element.ActionToRunName == actor_status.OnOff)
                                            {
                                                // look for the current status in the known actors table
                                                lock (KnownActorStates.KnownActorStatuses)
                                                {
                                                    if (KnownActorStates.KnownActorStatuses.ContainsKey(Element.ActorToSwitchName))
                                                    {
                                                        current_actor_status Status = KnownActorStates.KnownActorStatuses[Element.ActorToSwitchName];
                                                        if (Status.Status == actor_status.On)
                                                        {
                                                            ssa.SetStateActuatorPreset(hacs.Properties.Settings.Default.XS1, hacs.Properties.Settings.Default.Username, hacs.Properties.Settings.Default.Password, Element.ActorToSwitchName, "OFF", XS1_Configuration);
                                                        }
                                                        else
                                                        if (Status.Status == actor_status.Off)
                                                        {
                                                            ssa.SetStateActuatorPreset(hacs.Properties.Settings.Default.XS1, hacs.Properties.Settings.Default.Username, hacs.Properties.Settings.Default.Password, Element.ActorToSwitchName, "ON", XS1_Configuration);
                                                        }
                                                    }
                                                    else
                                                    {
                                                        ssa.SetStateActuatorPreset(hacs.Properties.Settings.Default.XS1, hacs.Properties.Settings.Default.Username, hacs.Properties.Settings.Default.Password, Element.ActorToSwitchName, "ON", XS1_Configuration);
                                                    }
                                                }
                                            }
                                            if (Element.ActionToRunName == actor_status.OnWaitOff)
                                            {
                                                lock (OnWaitOffLIst)
                                                {
                                                    ConsoleOutputLogger.WriteLine("Adding " + Element.ActorToSwitchName + " to ActorReSwitching OnWaitOff List");
                                                    OnWaitOffLIst.Add(Element.ActorToSwitchName);
                                                }
                                                ssa.SetStateActuatorPreset(hacs.Properties.Settings.Default.XS1, hacs.Properties.Settings.Default.Username, hacs.Properties.Settings.Default.Password, Element.ActorToSwitchName, "ON_WAIT_OFF", XS1_Configuration);
                                            }
                                            #endregion
                                        }
                                        else
                                        {
                                            ConsoleOutputLogger.WriteLine("Actorswitching Action not triggered since it's out of timespan. (" + Element.StartHour + "-" + Element.EndHour + ")");
                                        }
                                    }
                                }
                            }
                            #endregion

                            #region MQTT Handling Sensor
                            if (Properties.Settings.Default.MQTTBindingEnabled)
                            {
                                MQTT_Binding.MQTT_Handle_Sensor(dataobject);
                            }
                            #endregion
                        }
                        else
                        if (dataobject.Type == ObjectTypes.Unknown)
                        {
                            unknown_data_store.Write(dataobject.Serialize());
                        }

                        ConsoleOutputLogger.WriteLine(ServerName + " - " + dataobject.OriginalXS1Statement);
                    }
                    #endregion

                    #region Handle MAX events
                    // the strategy for MAX events is quite easy: emulate XS1 events and stuff the XS1 queue with those faked events
                    // that takes care of the storage and the
                    if (Properties.Settings.Default.ELVMAXEnabled)
                    {
                        IDeviceDiffSet max_dataobject = null;

                        if (MAX_DataQueue.TryDequeue(out max_dataobject))
                        {
                            // if Alarming is enabled, queue this ELV MAX up for alarming...
                            if (Properties.Settings.Default.AlarmingEnabled)
                            {
                                Alarming_Queue.Enqueue(max_dataobject);
                            }

                            StringBuilder sb = new StringBuilder();

                            sb.Append("S\t" + max_dataobject.DeviceName + "\t" + max_dataobject.DeviceType);

                            if (max_dataobject.DeviceType == DeviceTypes.HeatingThermostat)
                            {
                                HeatingThermostatDiff _heating = (HeatingThermostatDiff)max_dataobject;

                                // this is what is different on the heating thermostats
                                //ConsoleOutputLogger.WriteLine(_heating.ToString());

                                // first the temperature data
                                XS1_DataObject maxdataobject = new XS1_DataObject(Properties.Settings.Default.ELVMAXIP, _heating.RoomName + "-" + _heating.DeviceName, ObjectTypes.Sensor, "heating_thermostat", DateTime.Now, _heating.RoomID, _heating.Temperature, _heating.ToString(), true);
                                SensorCheckIgnoreConfiguration.AddToIgnoreList(maxdataobject.Name);
                                XS1_DataQueue.Enqueue(maxdataobject);

                                // then the low battery if exists
                                if (_heating.LowBattery == BatteryStatus.lowbattery)
                                {
                                    XS1_DataObject lowbatteryobject = new XS1_DataObject(Properties.Settings.Default.ELVMAXIP, _heating.RoomName + "-" + _heating.DeviceName, ObjectTypes.Sensor, "low_battery", DateTime.Now, _heating.RoomID, _heating.Temperature, _heating.ToString() + ", LowBattery", true);
                                    SensorCheckIgnoreConfiguration.AddToIgnoreList(lowbatteryobject.Name);
                                    XS1_DataQueue.Enqueue(lowbatteryobject);
                                }

                                if (_heating.Mode == ThermostatModes.boost)
                                {
                                    XS1_DataObject boostmodeobject = new XS1_DataObject(Properties.Settings.Default.ELVMAXIP, _heating.RoomName + "-" + _heating.DeviceName, ObjectTypes.Sensor, "boost", DateTime.Now, _heating.RoomID, _heating.Temperature, _heating.ToString() + ", Boost", true);
                                    SensorCheckIgnoreConfiguration.AddToIgnoreList(boostmodeobject.Name);
                                    XS1_DataQueue.Enqueue(boostmodeobject);
                                }
                            }

                            if (max_dataobject.DeviceType == DeviceTypes.ShutterContact)
                            {
                                ShutterContactDiff _shutter = (ShutterContactDiff)max_dataobject;

                                // this is what is different on the ShutterContacts
                                //ConsoleOutputLogger.WriteLine(_shutter.ToString());

                                // first the open/close status
                                if (_shutter.ShutterState == ShutterContactModes.open)
                                {
                                    XS1_DataObject maxdataobject = new XS1_DataObject(Properties.Settings.Default.ELVMAXIP, _shutter.RoomName + "-" + _shutter.DeviceName, ObjectTypes.Sensor, "shutter_contact", DateTime.Now, _shutter.RoomID, 1.0, _shutter.ToString(), true);
                                    SensorCheckIgnoreConfiguration.AddToIgnoreList(maxdataobject.Name);
                                    XS1_DataQueue.Enqueue(maxdataobject);
                                }
                                else
                                {
                                    XS1_DataObject maxdataobject = new XS1_DataObject(Properties.Settings.Default.ELVMAXIP, _shutter.RoomName + "-" + _shutter.DeviceName, ObjectTypes.Sensor, "shutter_contact", DateTime.Now, _shutter.RoomID, 0.0, _shutter.ToString(), true);
                                    SensorCheckIgnoreConfiguration.AddToIgnoreList(maxdataobject.Name);
                                    XS1_DataQueue.Enqueue(maxdataobject);
                                }

                                // then the low battery if exists
                                if (_shutter.LowBattery == BatteryStatus.lowbattery)
                                {
                                    if (_shutter.ShutterState == ShutterContactModes.open)
                                    {
                                        XS1_DataObject lowbatteryobject = new XS1_DataObject(Properties.Settings.Default.ELVMAXIP, _shutter.RoomName + "-" + _shutter.DeviceName, ObjectTypes.Sensor, "low_battery", DateTime.Now, _shutter.RoomID, 1.0, _shutter.ToString() + ",LowBattery", true);
                                        SensorCheckIgnoreConfiguration.AddToIgnoreList(lowbatteryobject.Name);
                                        XS1_DataQueue.Enqueue(lowbatteryobject);
                                    }
                                    else
                                    {
                                        XS1_DataObject lowbatteryobject = new XS1_DataObject(Properties.Settings.Default.ELVMAXIP, _shutter.RoomName + "-" + _shutter.DeviceName, ObjectTypes.Sensor, "low_battery", DateTime.Now, _shutter.RoomID, 0.0, _shutter.ToString() + ",LowBattery", true);
                                        SensorCheckIgnoreConfiguration.AddToIgnoreList(lowbatteryobject.Name);
                                        XS1_DataQueue.Enqueue(lowbatteryobject);
                                    }
                                }
                            }
                        }
                    }
                    #endregion

                    #region Handle SolarLog events
                    if (Properties.Settings.Default.SolarLogEnabled)
                    {
                        SolarLogDataSet solarlog_dataobject = null;

                        if (SolarLog_DataQueue.TryDequeue(out solarlog_dataobject))
                        {
                            // Pac
                            XS1_DataQueue.Enqueue(new XS1_DataObject(Properties.Settings.Default.SolarLogURLDomain, "Pac", ObjectTypes.Sensor, "Pac", solarlog_dataobject.DateAndTime, 1, solarlog_dataobject.Pac, "solarlog," + Properties.Settings.Default.SolarLogURLDomain + ",Pac," + solarlog_dataobject.Pac + "," + solarlog_dataobject.DateAndTime.Ticks, true));
                            // aPdc
                            XS1_DataQueue.Enqueue(new XS1_DataObject(Properties.Settings.Default.SolarLogURLDomain, "aPdc", ObjectTypes.Sensor, "aPdc", solarlog_dataobject.DateAndTime, 1, solarlog_dataobject.aPdc, "solarlog," + Properties.Settings.Default.SolarLogURLDomain + ",aPdc," + solarlog_dataobject.aPdc + "," + solarlog_dataobject.DateAndTime.Ticks, true));

                            // if Alarming is enabled, queue this SolarLog Event up for alarming...
                            if (Properties.Settings.Default.AlarmingEnabled)
                            {
                                Alarming_Queue.Enqueue(solarlog_dataobject);
                            }
                        }
                    }
                    #endregion

                    #region Handle Network Monitor events
                    if (Properties.Settings.Default.NetworkMonitorEnabled)
                    {
                        NetworkMonitoringDataSet networkmonitor_dataobject = null;

                        if (NetworkMonitor_Queue.TryDequeue(out networkmonitor_dataobject))
                        {
                            if (networkmonitor_dataobject.Status == Org.Mentalis.Network.ICMP_Status.Success)
                            {
                                XS1_DataQueue.Enqueue(new XS1_DataObject(networkmonitor_dataobject.Descriptor, networkmonitor_dataobject.HostnameIP, ObjectTypes.Sensor, "Ping", networkmonitor_dataobject.TimeOfMeasurement, 2, 1, "OnlineCheck," + networkmonitor_dataobject.HostnameIP + "," + networkmonitor_dataobject.Descriptor + ",Online", true));
                            }
                            else
                            {
                                XS1_DataQueue.Enqueue(new XS1_DataObject(networkmonitor_dataobject.Descriptor, networkmonitor_dataobject.HostnameIP, ObjectTypes.Sensor, "Ping", networkmonitor_dataobject.TimeOfMeasurement, 2, 0, "OnlineCheck," + networkmonitor_dataobject.HostnameIP + "," + networkmonitor_dataobject.Descriptor + ",Offline", true));
                            }

                            // if Alarming is enabled, queue this Network Monitor Event up for alarming...
                            if (Properties.Settings.Default.AlarmingEnabled)
                            {
                                Alarming_Queue.Enqueue(networkmonitor_dataobject);
                            }
                        }
                    }
                    #endregion
                }
                catch (Exception)
                {
                    AcceptingCommands = false;
                    //Thread.Sleep(1);
                }
                Thread.Sleep(1);
            }
            if (ELVMax != null)
            {
                ELVMax.running = false;
            }
            XS1.running = false;

            Thread.Sleep(200);                  // ... msecs period to wait for new input...
        }
Exemplo n.º 10
0
        public void Run()
        {
            ConsoleOutputLogger.WriteLine("Alarming Thread started");
            while (!Shutdown)
            {
                try
                {
                    IAlarmingEvent dataobject = null;
                    if (Alarming_Queue.TryDequeue(out dataobject))
                    {
                        // we should get events from all sorts of devices here - let's take them and check if they
                        // are eventually matching the activators - if they do we check against the other
                        // data storages to follow up with the alarms...

                        // check if we find this in the alarms...
                        foreach (Alarm _alarm in AlarmingConfiguration.Alarms.Alarms)
                        {
                            foreach (Activator _activator in _alarm.activators)
                            {
                                // activator names are case sensitive!!!
                                if (dataobject.AlarmingName() == _activator.name)
                                {
                                    // we got a positive activator match here!
                                    // now check further circumstances...
                                    #region XS1 Events
                                    if ((_activator.device.ToUpper() == "XS1") && (dataobject.AlarmingType() == AlarmingEventType.XS1Event))
                                    {
                                        // now we got an alarm triggering this activator and device...
                                        // check if the type matches...
                                        XS1_DataObject xs1_data = (XS1_DataObject)dataobject;

                                        if (_activator.type.ToUpper() == xs1_data.TypeName.ToUpper())
                                        {
                                            // for the value comparison convert the given value to a double...
                                            double comp_value = Convert.ToDouble(_activator.value);
                                            // it's the right typename...
                                            // now we gotta check for the right value there...
                                            Boolean alarm_activated = false;
                                            #region Activator Value Comparison
                                            switch (_activator.comparison)
                                            {
                                            case "==":
                                                if (comp_value == xs1_data.Value)
                                                {
                                                    // hurray, everything matches! Activate this event!!!
                                                    alarm_activated = true;
                                                }
                                                break;

                                            case "<=":
                                                if (comp_value <= xs1_data.Value)
                                                {
                                                    // hurray, everything matches! Activate this event!!!
                                                    alarm_activated = true;
                                                }
                                                break;

                                            case ">=":
                                                if (comp_value >= xs1_data.Value)
                                                {
                                                    // hurray, everything matches! Activate this event!!!
                                                    alarm_activated = true;
                                                }
                                                break;
                                            }
                                            #endregion

                                            #region do the sensor and actor checks...
                                            // TODO: this is very rough - needs to be worked out more later on...
                                            // for the moment it is just a actor check - MORE HERE !!!!!!!!
                                            if (alarm_activated)
                                            {
                                                foreach (Actorcheck _actor in _alarm.actorchecks)
                                                {
                                                    #region XS1 actors...
                                                    if (_actor.device.ToUpper() == "XS1")
                                                    {
                                                        if (KnownActorStates.KnownActorStatuses.ContainsKey(_actor.name))
                                                        {
                                                            // there's an actor...
                                                            current_actor_status status = (current_actor_status)KnownActorStates.KnownActorStatuses[_actor.name];
                                                            // TODO: what about actor types!?

                                                            if (_actor.value.ToUpper() == "ON")
                                                            {
                                                                // so it should be on...
                                                                if (status.Status != actor_status.On)
                                                                {
                                                                    alarm_activated = false;
                                                                }
                                                            }
                                                            if (_actor.value.ToUpper() == "OFF")
                                                            {
                                                                // so it should be off...
                                                                if (status.Status != actor_status.Off)
                                                                {
                                                                    alarm_activated = false;
                                                                }
                                                            }
                                                        }
                                                    }
                                                    #endregion
                                                }
                                            }
                                            #endregion

                                            if (alarm_activated)
                                            {
                                                ConsoleOutputLogger.WriteLine("!!!! ALARM - " + _alarm.name + " - ALARM !!!!");

                                                // authenticate Telekom
                                                if (Properties.Settings.Default.UseTelekomSMSInsteadofSMS77)
                                                {
                                                    TelekomSMSGateway = new TelekomSendSMSGateway(Properties.Settings.Default.TelekomSMSClientID, Properties.Settings.Default.TelekomSMSClientSecret);
                                                }

                                                // send out the SMS...
                                                foreach (Smsrecipient recipient in _alarm.smsrecipients)
                                                {
                                                    ConsoleOutputLogger.WriteLine("Sending Alarm SMS to " + recipient.number + " for alarm " + _alarm.name);

                                                    try
                                                    {
                                                        if (!Properties.Settings.Default.UseTelekomSMSInsteadofSMS77)
                                                        {
                                                            SMSGateway.SendSMS(recipient.number, _alarm.message, Properties.Settings.Default.AlarmingSMS77SenderNumber, false, false, SMSType.quality);
                                                        }
                                                        else
                                                        {
                                                            TelekomSMSGateway.Send(recipient.number, _alarm.message, Properties.Settings.Default.AlarmingSMS77SenderNumber);
                                                        }
                                                    }
                                                    catch (Exception e)
                                                    {
                                                        ConsoleOutputLogger.WriteLine("SMS Sending Exception: " + e.Message);
                                                    }
                                                }
                                            }
                                        }
                                    }
                                    #endregion

                                    #region ELVMAX Events
                                    if ((_activator.device.ToUpper() == "ELVMAX") && (dataobject.AlarmingType() == AlarmingEventType.ELVMAXEvent))
                                    {
                                        //ConsoleOutputLogger.WriteLine("ELVMAX: " + _activator.device);

                                        // now we got an alarm triggering this activator and device...
                                        // check if the type matches...
                                        IDeviceDiffSet diffset = (IDeviceDiffSet)dataobject;

                                        //ConsoleOutputLogger.WriteLine("ELVMAX: " + diffset.DeviceName);
                                        //ConsoleOutputLogger.WriteLine("ELVMAX: " + diffset.RoomName);
                                        //ConsoleOutputLogger.WriteLine("ELVMAX: " + _activator.type);
                                        //ConsoleOutputLogger.WriteLine("ELVMAX: " + _activator.name);


                                        // for now only shuttercontacts are interesting
                                        if ((_activator.type.ToUpper() == "SHUTTERCONTACT") && (diffset.DeviceType == DeviceTypes.ShutterContact) &&
                                            (_activator.name == diffset.DeviceName))
                                        {
                                            //ConsoleOutputLogger.WriteLine("ELVMAX Shuttercontact");

                                            ShutterContactDiff shutterdiff = (ShutterContactDiff)diffset;

                                            //ConsoleOutputLogger.WriteLine("ELVMAX: "+shutterdiff.ToString());

                                            ShutterContactModes activatorstate  = ShutterContactModes.unchanged;
                                            Boolean             alarm_activated = false;

                                            if (_activator.value.ToUpper() == "OPEN")
                                            {
                                                activatorstate = ShutterContactModes.open;
                                            }

                                            if (_activator.value.ToUpper() == "CLOSED")
                                            {
                                                activatorstate = ShutterContactModes.closed;
                                            }

                                            if (activatorstate == shutterdiff.ShutterState)
                                            {
                                                alarm_activated = true;
                                            }

                                            #region do the sensor and actor checks...
                                            // TODO: this is very rough - needs to be worked out more later on...
                                            // for the moment it is just a actor check - MORE HERE !!!!!!!!
                                            if (alarm_activated)
                                            {
                                                foreach (Actorcheck _actor in _alarm.actorchecks)
                                                {
                                                    #region XS1 actors...
                                                    if (_actor.device.ToUpper() == "XS1")
                                                    {
                                                        if (KnownActorStates.KnownActorStatuses.ContainsKey(_actor.name))
                                                        {
                                                            // there's an actor...
                                                            current_actor_status status = (current_actor_status)KnownActorStates.KnownActorStatuses[_actor.name];
                                                            // TODO: what about actor types!?

                                                            if (_actor.value.ToUpper() == "ON")
                                                            {
                                                                // so it should be on...
                                                                if (status.Status != actor_status.On)
                                                                {
                                                                    alarm_activated = false;
                                                                }
                                                            }
                                                            if (_actor.value.ToUpper() == "OFF")
                                                            {
                                                                // so it should be off...
                                                                if (status.Status != actor_status.Off)
                                                                {
                                                                    alarm_activated = false;
                                                                }
                                                            }
                                                        }
                                                    }
                                                    #endregion
                                                }
                                            }
                                            #endregion

                                            if (alarm_activated)
                                            {
                                                ConsoleOutputLogger.WriteLine("!!!! ALARM - " + _alarm.name + " - ALARM !!!!");

                                                // authenticate Telekom
                                                if (Properties.Settings.Default.UseTelekomSMSInsteadofSMS77)
                                                {
                                                    TelekomSMSGateway = new TelekomSendSMSGateway(Properties.Settings.Default.TelekomSMSClientID, Properties.Settings.Default.TelekomSMSClientSecret);
                                                }

                                                // send out the SMS...
                                                foreach (Smsrecipient recipient in _alarm.smsrecipients)
                                                {
                                                    ConsoleOutputLogger.WriteLine("Sending Alarm SMS to " + recipient.number + " for alarm " + _alarm.name);
                                                    try
                                                    {
                                                        if (!Properties.Settings.Default.UseTelekomSMSInsteadofSMS77)
                                                        {
                                                            SMSGateway.SendSMS(recipient.number, _alarm.message, Properties.Settings.Default.AlarmingSMS77SenderNumber, false, false, SMSType.quality);
                                                        }
                                                        else
                                                        {
                                                            TelekomSMSGateway.Send(recipient.number, _alarm.message, Properties.Settings.Default.AlarmingSMS77SenderNumber);
                                                        }
                                                    }
                                                    catch (Exception e)
                                                    {
                                                        ConsoleOutputLogger.WriteLine("SMS Sending Exception: " + e.Message);
                                                    }
                                                }
                                            }
                                        }
                                    }
                                    #endregion
                                    // TODO: ------------------------------
                                    #region SolarLog Events
                                    if ((_activator.device.ToUpper() == "SOLARLOG") && (dataobject.AlarmingType() == AlarmingEventType.SolarLogEvent))
                                    {
                                        // now we got an alarm triggering this activator and device...
                                    }
                                    #endregion
                                    #region Network Monitor Events
                                    if ((_activator.device.ToUpper() == "NETWORKMONITOR") && (dataobject.AlarmingType() == AlarmingEventType.NetworkingEvent))
                                    {
                                        // now we got an alarm triggering this activator and device...
                                    }
                                    #endregion
                                    #region Google Latitude Events
                                    if ((_activator.device.ToUpper() == "GOOGLELATITUDE") && (dataobject.AlarmingType() == AlarmingEventType.GoogleLatitudeEvent))
                                    {
                                        // now we got an alarm triggering this activator and device...
                                    }
                                    #endregion
                                }
                            }
                        }
                    }
                }
                catch (Exception e)
                {
                    //Shutdown = true;
                    ConsoleOutputLogger.WriteLine("Alarming Exception: " + e.Message);
                    ConsoleOutputLogger.WriteLine("Stopping Alarming Execution!");
                    Thread.Sleep(100);
                }

                Thread.Sleep(10);
            }
        }
Exemplo n.º 11
0
        // implemented
        #region GenerateDataNumericsJSONOutput
        /// <summary>
        /// generates JSON dataset from sensor data
        /// </summary>
        /// <returns></returns>
        public String GenerateDataNumericsJSONOutput(ObjectTypes DataType, String ObjectTypeName, String ObjectName, DateTime StartDateTime, DateTime EndDateTime)
        {
            /* Example:
             *
             * {    label: 'Europe (EU27)',
             *       data: [[1999, 3.0], [2000, 3.9], [2001, 2.0], [2002, 1.2], [2003, 1.3], [2004, 2.5], [2005, 2.0], [2006, 3.1], [2007, 2.9], [2008, 0.9]]
             * }
             *
             * */

            StringBuilder Output = new StringBuilder();

            Output.Append(" {\n");
            Output.Append("  \"postfix\": \"" + ObjectName + "\",\n");
            Output.Append("\"data\": [\n");

            bool   firstdataset      = true;
            UInt64 SerializerCounter = 0;

            // TODO: there should be an appropriate caching algorithm in the sensor data...
            lock (sensor_data.InMemoryIndex)
            {
                foreach (OnDiscAdress ondisc in sensor_data.InMemoryIndex)
                {
                    if (ondisc.CreationTime >= StartDateTime.Ticks)
                    {
                        if (ondisc.CreationTime <= EndDateTime.Ticks)
                        {
                            XS1_DataObject dataobject = ReadFromCache(ondisc);
                            SerializerCounter++;

                            if (dataobject.Type == DataType)
                            {
                                if (dataobject.TypeName == ObjectTypeName)
                                {
                                    if (dataobject.Name == ObjectName)
                                    {
                                        if (!firstdataset)
                                        {
                                            Output.Append(",\n");
                                        }
                                        else
                                        {
                                            firstdataset = false;
                                        }

                                        Output.Append("{");
                                        //"value": 1450
                                        Output.Append("\"value\": " + dataobject.Value.ToString().Replace(',', '.') + "\n");
                                        Output.Append("}\n");
                                    }
                                }
                            }
                        }
                    }
                }
            }
            Output.Append("\n]\n}");

            ConsoleOutputLogger_.WriteLineToScreenOnly("Generated Numerics JSON Dataset with " + SerializerCounter + " Elements");

            return(Output.ToString());
        }