Exemplo n.º 1
0
        private static void Timer_Elapsed(object sender, ElapsedEventArgs e)
        {
            int hour = DateTime.Now.Hour;

            if (hour != lastHour)
            {
                lastHour = hour;
                ReadingType rType = hour == 0 ? ReadingType.Daily : ReadingType.Hourly;

                //Try 3 times
                Output.Report("New Reading Started");

                for (int i = 0; i < 2; i++)
                {
                    try
                    {
                        if (i > 0)
                        {
                            Output.Report($"Retry atempt: {i}");
                        }
                        //Create tasks
                        PlcManager.CreateTasks();
                        //Start the tasks
                        PlcManager.StartReading(rType);
                        break;
                    }
                    catch (Exception ex)
                    {
                        Output.Report($"Reading failed: {ex.Message}");
                        //Wait a bit and try again
                        Thread.Sleep(2000);
                    }
                }
            }
        }
 public RandomSensor(decimal value, decimal deviation, string name, ReadingType readingType)
 {
     _value      = value;
     _deviation  = deviation;
     Name        = name;
     ReadingType = readingType;
 }
Exemplo n.º 3
0
        public void ReadingStopwatch(ReadingType readingType, User user)
        {
            Stopwatch stopwatch = new Stopwatch();

            stopwatch.Start();
            Console.WriteLine("Press ENTER to stop.");
            string stop = Console.ReadLine();

            if (stop == "")
            {
                stopwatch.Stop();
                TimeSpan time          = stopwatch.Elapsed;
                double   convertedTime = Convert.ToDouble(time.TotalSeconds);
                if (readingType == ReadingType.BellesLetres)
                {
                    user.TotalPages    += Pages;
                    user.BellesLettres += convertedTime / 60;
                }
                if (readingType == ReadingType.Fiction)
                {
                    user.TotalPages += Pages;
                    user.Fiction    += convertedTime / 60;
                }
                if (readingType == ReadingType.ProfessionalLiterature)
                {
                    user.TotalPages             += Pages;
                    user.ProfessionalLiterature += convertedTime / 60;
                }
                user.TimeReading += convertedTime / 60;
                Console.WriteLine($"Time spent on {Title}: {Math.Round(convertedTime / 60, 2)} minutes.");
                Console.WriteLine("Press any key to go back to the Main Menu.");
                Console.ReadKey();
            }
        }
Exemplo n.º 4
0
        public static async Task <bool> RecordSuccess(ReadingType t, WeatherInfoSource src, double x)
        {
            var rd = new WeatherRecord(CurrentDateTime, x, src, t);
            await Table.ExecuteAsync(TableOperation.Insert(rd));

            return(true);
        }
Exemplo n.º 5
0
 public static string GetDisplayValue(this long value, ReadingType readingType)
 {
     return(value.GetDisplayValue(
                readingType.Uom.Value,
                readingType.PowerOfTenMultiplier.Value,
                readingType.Scaler));
 }
Exemplo n.º 6
0
 public WeatherRecord(DateTime When, double Reading, WeatherInfoSource src, ReadingType type)
 {
     this.Reading           = Reading;
     this.WeatherInfoSource = src;
     this.When        = When;
     this.ReadingType = type;
     PartitionKey     = string.Format("{0}.{1}", When.Year, When.Month);
     RowKey           = string.Format("{0}-{1}:{2}.{3}.{4},{5}:{6}", src, type, When.Year, When.Month, When.Day, When.Hour, When.Minute);
 }
Exemplo n.º 7
0
 public override string ToString()
 {
     if (Meal is null)
     {
         return($"{TimeOfDay.ToLocalTime().ToShortDateString()}, {ReadingType.ToString()} Meal");
     }
     else
     {
         return($"{TimeOfDay.ToLocalTime().ToShortDateString()}, {Meal.FoodName}, {ReadingType.ToString()} {Meal.MealTime}");
     }
 }
Exemplo n.º 8
0
        private void btnAdicionar_Click(object sender, EventArgs e)
        {
            if (cbReadingType.Items.Count <= 0)
            {
                errorProvider.SetError(cbReadingType, "Cannot insert parameter without reading type!");
                return;
            }

            string condition = cbParameterCondition.SelectedItem.ToString();

            ReadingType dataType = (ReadingType)cbReadingType.SelectedItem;



            string value = nrParameterValue.Value.ToString();
            string value2;
            string finalValue;

            if (condition.Equals("<>"))
            {
                value2     = nrParameterValue2.Value.ToString();
                finalValue = value + ":" + value2;
            }
            else
            {
                finalValue = value;
            }


            Parameter parameter = new Parameter
            {
                Condition   = condition,
                ReadingType = (ReadingType)cbReadingType.SelectedItem,
                Value       = finalValue
            };

            parameters.Add(parameter);

            ListViewItem item = null;



            lvParameters.Items.Clear();
            foreach (Parameter parameterI in parameters)
            {
                item = new ListViewItem(new string[] { parameterI.Condition, parameter.ReadingType.MeasureName, parameterI.Value.ToString() });
                lvParameters.Items.Add(item);
            }

            cbParameterCondition.SelectedIndex = 0;
            cbReadingType.SelectedIndex        = 0;
            nrParameterValue.Value             = 0;
            nrParameterValue2.Value            = 0;
        }
Exemplo n.º 9
0
        public List <ReadingType> GetAllReadingTypes()
        {
            List <ReadingType> readingTypes = new List <ReadingType>();

            try
            {
                SqlConnection sql = new SqlConnection(connectionString);
                sql.Open();
                SqlCommand    sqlCommand = new SqlCommand("SELECT * FROM t_sensor_reading_types", sql);
                SqlDataReader reader     = sqlCommand.ExecuteReader();

                while (reader.Read())
                {
                    ReadingType reading = new ReadingType
                    {
                        MeasureName = (string)reader["measure_name"],
                        MeasureType = (string)reader["measure_type"],
                        SensorId    = (int)reader["sensor_id"],
                        Timestamp   = (string)reader["timestamp"]
                    };
                    if (reader["min_value"] == DBNull.Value)
                    {
                        reading.MinValue = null;
                    }
                    else
                    {
                        reading.MinValue = (string)reader["min_value"];
                    }

                    if (reader["max_value"] == DBNull.Value)
                    {
                        reading.MaxValue = null;
                    }
                    else
                    {
                        reading.MaxValue = (string)reader["max_value"];
                    }
                    readingTypes.Add(reading);
                }
                ;
                sql.Close();
            }
            catch (Exception e)
            {
                Console.WriteLine("Failed retrieving sensor list! Reason:" + e.Message);
                Console.ReadKey();
                return(null);
            }



            return(readingTypes);
        }
Exemplo n.º 10
0
        public float GetStatisticReading(Reading reading, ReadingType type)
        {
            string value = type switch
            {
                ReadingType.NO2 => reading.NO2_Concentration,
                ReadingType.Fine => reading.Fine_PM_Concentration,
                ReadingType.Coarse => reading.Coarse_PM_Concentration,
                _ => "",
            };

            return(float.Parse(value));
        }
Exemplo n.º 11
0
        // Returns current (most recent) readings for the given reading type
        // but only within last 10 minutes.
        public static WeatherRecord[] GetCurrentReading(ReadingType type)
        {
            var data = (from z in WeatherDB.Table.CreateQuery <WeatherRecord>()
                        where z.When > DateTime.Now.AddMinutes(-10)
                        // where z.ReadingType == type
                        select z).ToList();
            var res = from z in data
                      where z.ReadingType == type
                      group z by z.WeatherInfoSource into g
                      select g.OrderByDescending(x => x.When).First();

            return(res.ToArray());
        }
Exemplo n.º 12
0
        public IEnumerable <IReading> GetReadings(ReadingType type, DateTimeOffset startDate, DateTimeOffset endDate)
        {
            var result      = Readings.Where(t => t.Type == type && t.Taken >= startDate.UtcDateTime && t.Taken <= endDate.UtcDateTime).OrderBy(t => t.Taken).ToList();
            var finalResult = new List <IReading>();

            foreach (var reading in result)
            {
                reading.UpdateCreatedToLocal(startDate);
                finalResult.Add((IReading)reading.ToType());
            }

            return(finalResult);
        }
Exemplo n.º 13
0
        public async Task <IEnumerable <IReading> > GetReadingsAsync(ReadingType type, DateTimeOffset startDate, DateTimeOffset endDate)
        {
            var result = await Readings.Where(t => t.Type == type && t.Taken >= startDate.UtcDateTime && t.Taken <= endDate.UtcDateTime).OrderBy(t => t.Taken).ToListAsync();

            var finalResult = new List <IReading>();

            result.ForEach(t =>
            {
                t.UpdateCreatedToLocal(startDate);
                finalResult.Add((IReading)t.ToType());
            });
            return(finalResult);
        }
 public SinglePointReading(float distance)
 {
     if (distance == float.MaxValue)
     {
         Type     = ReadingType.LostSignal;
         Distance = 0.0f;
     }
     else
     {
         Type     = ReadingType.Distance;
         Distance = distance;
     }
 }
Exemplo n.º 15
0
        protected void Page_Load(object sender, EventArgs e)
        {
            ReadingType t  = ReadingType.Temperature;
            DateTime    fr = DateTime.Now.AddYears(-1);

            switch (ddTimePeriod.SelectedValue)
            {
            case "Day":
                fr = DateTime.Now.AddDays(-1); break;

            case "Month":
                fr = DateTime.Now.AddMonths(-1); break;

            case "Year":
                fr = DateTime.Now.AddYears(-1); break;

            case "Week":
                fr = DateTime.Now.AddDays(-7); break;
            }
            switch (ddDispType.SelectedValue)
            {
            case "Temperature":
                t = ReadingType.Temperature; break;

            case "Pressure":
                t = ReadingType.Pressure; break;

            case "Humidity":
                t = ReadingType.Humidity; break;

            case "Luminocity":
                t = ReadingType.Luminocity; break;
            }
            var db   = WeatherDB.GetDataAfter(fr);
            var data = from z in db
                       where z.WeatherInfoSource == WeatherInfoSource.WeatherService
                       where z.ReadingType == t
                       where z.When > fr
                       orderby z.When descending
                       select new { When = z.When, Data = z.Reading };

            MainChart.Series[0].Points.DataBind(data, "When", "Data", "");
            var rdata = from z in db
                        where z.WeatherInfoSource == WeatherInfoSource.Device
                        where z.ReadingType == t
                        where z.When > fr
                        orderby z.When descending
                        select new { When = z.When, Data = z.Reading };

            MainChart.Series[1].Points.DataBind(rdata, "When", "Data", "");
        }
Exemplo n.º 16
0
 public static string ReadingColor(ReadingType type)
 {
     return(type switch
     {
         ReadingType.PH => "#5fa8a1",
         ReadingType.Nitrate => "#a11726",
         ReadingType.Nitrite => "#7f207a",
         ReadingType.FishFeed => "#9e8e5e",
         ReadingType.Alkalinity => "#fbde16",
         ReadingType.Ammonia => "#0c7950",
         ReadingType.DisolvedOxygen => "#41a1e7",
         ReadingType.TotalHardness => "#934d35",
         ReadingType.WaterTemp => "#71b1d7",
         _ => "#000"
     });
Exemplo n.º 17
0
        /// <summary>
        /// Read data from the database
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void ReadDataAsync(ReadingType dataBaseAction)
        {
            // Update student array
            var(status, tempClasse) = await Task.Run(() => ReadData());

            if (status == Status.Successful)
            {
                // Clear the list of student
                Class.Clear();

                // Update the list of student
                tempClasse.ForEach(val => Class.Add(val));
            }

            // Get focus to the appropriete item
            GetFocus(dataBaseAction);
        }
Exemplo n.º 18
0
        public ReadingType GetReadingType(int sensor_id, string name)
        {
            ReadingType readingType = null;

            try
            {
                SqlConnection sql = new SqlConnection(connectionString);
                sql.Open();
                SqlCommand command = new SqlCommand("SELECT * FROM t_sensor_reading_types WHERE sensor_id=@id AND measure_name=@name", sql);
                command.Parameters.AddWithValue("@id", sensor_id);
                command.Parameters.AddWithValue("@name", name);
                SqlDataReader reader = command.ExecuteReader();
                if (reader.Read())
                {
                    readingType = new ReadingType
                    {
                        Id          = (int)reader["id"],
                        MeasureType = (string)reader["measure_type"],
                        MeasureName = (string)reader["measure_name"],
                        SensorId    = (int)reader["sensor_id"],
                        Timestamp   = (string)reader["timestamp"]
                    };
                    switch (readingType.MeasureType.ToUpper())
                    {
                    case "INT":
                        readingType.MaxValue = reader["max_value"] != DBNull.Value ? (string)reader["max_value"] : int.MaxValue.ToString();
                        readingType.MinValue = reader["min_value"] == DBNull.Value ? int.MinValue.ToString() : (string)reader["min_value"];
                        break;

                    case "FLOAT":
                        readingType.MaxValue = reader["max_value"] != DBNull.Value ? (string)reader["max_value"] : float.MaxValue.ToString();
                        readingType.MinValue = reader["min_value"] == DBNull.Value ? float.MinValue.ToString() : (string)reader["min_value"];
                        break;
                    }
                    return(readingType);
                }
                ;
            }
            catch (Exception e)
            {
                Console.WriteLine("Error fetching reading type!" + " Reason:" + e.Message);
            }
            return(readingType);
        }
Exemplo n.º 19
0
        public ReadService(ReadingType readingType, object[] args)
            : base()
        {
            if (readingType != ReadingType.PartialReadDefault)
            {
                if ((args == null) || (args.Length == 0))
                {
                    throw new ArgumentNullException("args", "Debe especificar los parámetros requeridos para la lectura de la Tabla.");
                }

                if ((readingType == ReadingType.PartialReadWithIndex) && !Enum.IsDefined(typeof(IndexType), args[0]))
                {
                    throw new InvalidCastException("El parámetro para especificar el tipo de índice de lectura no tiene un formato válido.");
                }

                if (((readingType == ReadingType.FullRead) && (args.Length != 1)) ||
                    ((readingType != ReadingType.FullRead) && (args.Length != 3)))
                {
                    //((readingType == ReadingType.PartialReadWithOffset) && (args.Length != 3)) ||
                    //((readingType == ReadingType.PartialReadWithIndex) && ((args.Length < 4) && ((((byte)args[0] + 1) * 2) != (args.Length - 2)))))
                    throw new ArgumentOutOfRangeException("args", "Los parámetros especificados no coinciden con la cantidad esperada.");
                }

                int index = (readingType == ReadingType.PartialReadWithIndex) ? 1 : 0;
                Table = args[index] as Table;

                if (Table == null)
                {
                    throw new ArgumentOutOfRangeException("args", string.Format("El parámetro que define la tabla no tiene un valor válido. Valor {0}", args[index]));
                }
            }
            else
            {
                if (args != null)
                {
                    throw new ArgumentException("Table, args", "El tipo de lectura solicitado no requiere de parámetros adicionales.");
                }
            }

            _readingType = readingType;
            _parameters  = args;
            TableData    = new List <byte>();
        }
Exemplo n.º 20
0
 public IReading this[ReadingType type]
 {
     get
     {
         return(entries.FirstOrDefault(t => t.Type == type));
     }
     set
     {
         for (int x = 0; x < entries.Count; x++)
         {
             if (entries[x].Type == type)
             {
                 entries[x] = value;
                 if (value.Type == type)
                 {
                     break; // don't look any further
                 }
             }
         }
     }
 }
Exemplo n.º 21
0
        /// <summary>
        /// Calling this method will reconfigure some of the settings in this class to try to optimize them for better performances
        /// </summary>
        /// <param name="estimatedEventsPerDay">Estimation of the average number of events per day, per tag</param>
        /// <param name="estimatedTagsCount"> Estimation of the total amount of tags that needs to be processed.</param>
        /// <param name="eventsPerRead">Defines the number of events that should be read per data call.  somewhere between 10000 and 50000 is a good start.</param>
        /// <param name="readType">Type of read that you want to perform.  Bulk performs better if network has latency.  Paralell can outperform bulk if latency is low.</param>
        public void AutoTune(ReadingType readType, int estimatedEventsPerDay, int estimatedTagsCount, int eventsPerRead)
        {
            double daysPerRead = 1;


            // tag group size is the amount of tags that are loaded at once from the PI DA
            // once loaded, the tags are send to processing in blocks of Tag GroupSize
            if (estimatedTagsCount < 200000)
            {
                TagGroupSize = estimatedTagsCount / 10;
                TagGroupSize = TagGroupSize <= 0 ? 1 : TagGroupSize;
            }
            else
            {
                TagGroupSize = 50000;
            }

            if (readType == ReadingType.Bulk)
            {
                // bulkPageSize is the number of tags that will be queried per page.
                // here we adjust the bulk page size with the estimated tags count.
                BulkPageSize = estimatedTagsCount < 1000 ? estimatedTagsCount : 1000;

                // days Per Read is high= when eventsPerRead is high, and estimated events per day is low, --> many days per read
                // days per Read is low = when eventsPerRead is low, and estimated events per day is high, -->many read per day (fraction number)
                daysPerRead           = ((double)eventsPerRead / ((double)estimatedEventsPerDay * (double)BulkPageSize)); // if > 1 -> need to split the day // if <1 need to read in many days
                BulkParallelChunkSize = (TagGroupSize / 5) <= 1 ? 1 : (TagGroupSize / 5);


                _logger.DebugFormat("Autotune calculated: daysPerRead {0} - BulkParallelChunkSize {1}", daysPerRead, BulkParallelChunkSize);
            }
            else
            {
                // in case we do parallel, we target 10 000 events per read
                daysPerRead = ((double)eventsPerRead / estimatedEventsPerDay);
            }

            // set a time span that will give us approximately "eventsPerRead" events per call
            TimeIntervalPerDataRequest = TimeSpan.FromDays(daysPerRead);
        }
Exemplo n.º 22
0
        private void GetFocus(ReadingType dataBaseAction)
        {
            if (Class.Count == 0)
            {
                return;
            }

            /* Set the selected index */

            switch (dataBaseAction)
            {
            case ReadingType.Inserting:

                ClassSelectedIndex = Class.Count - 1;
                break;

            default:

                ClassSelectedIndex = FindIndexfromId(FocusDict[dataBaseAction]);
                break;
            }
        }
Exemplo n.º 23
0
        /// <summary>
        /// 开始读取
        /// </summary>
        /// <param name="readingType">读取操作类型</param>
        /// <param name="aPollInterval">暂时无用  主要为适配Intermec设备</param>
        /// <param name="aReadInterval">暂时无用  主要为适配Intermec设备 连续读取定时</param>
        /// <returns></returns>
        public ReturnMessage StartReading(ReadingType readingType, int aPollInterval, int aReadInterval)
        {
            ReturnMessage returnMsg = new ReturnMessage();

            //连续读取标识  设置为  True
            if (readingType == ReadingType.EventReading)
            {
                IsContinuousRead = true;
            }

            //是否已经开启连接
            if (m_RFIDReader.IsConnected)
            {
                if (m_RFIDReader.Actions.TagAccess.OperationSequence.Length > 0)
                {
                    m_RFIDReader.Actions.TagAccess.OperationSequence.PerformSequence(GetAccessFilter(),
                                                                                     GetTriggerInfo(), GetAntennaInfo());
                }
                else
                {
                    m_RFIDReader.Actions.Inventory.Perform(GetPostFilter(), GetTriggerInfo(), GetAntennaInfo());
                }
                //标记开始读取
                m_IsReading = true;
                m_TagTable.Clear();//标签去重存储区

                returnMsg.CallMessage = "开启读取。";
                returnMsg.CallStatus  = true;
            }
            else
            {
                returnMsg.CallMessage = "请先连接读取器后开始读取。";
                returnMsg.CallStatus  = false;
                //日志记录
                DeclaimerReaderLog.Error("[" + returnMsg.CallMessage + "] ==== [" + DateTime.Now.ToString() + "]");
            }
            return(returnMsg);
        }
Exemplo n.º 24
0
        // Validation of a ReadingType instance
        private static void ValidateReadingType(ReadingType readingType, List <Exception> exceptions)
        {
            if (string.IsNullOrWhiteSpace(readingType.ObisCode))
            {
                exceptions.Add(new InvalidOperationException("Das Element \"ObisCode\" innerhalb des Elements \"ReadingType\" enthält keinen gültigen Wert."));
            }
            else
            {
                if (!readingType.ObisCode.ValidateHexString())
                {
                    exceptions.Add(new InvalidOperationException("Das Element \"ObisCode\" innerhalb des Elements \"ReadingType\" enthält keinen gültigen Wert."));
                }
            }

            if (string.IsNullOrEmpty(readingType.QualifiedLogicalName))
            {
                exceptions.Add(new InvalidOperationException("Das Element \"QualifiedLogicalName\" innerhalb des Elements \"ReadingType\" enthält keinen gültigen Wert."));
            }

            if (readingType.PowerOfTenMultiplier.HasValue)
            {
                ValidateReadingTypePowerOfTenMultiplier(readingType.PowerOfTenMultiplier, exceptions);
            }
            else
            {
                exceptions.Add(new InvalidOperationException("Das Element \"PowerOfTenMultiplier\" innerhalb des Elements \"ReadingType\" enthält keinen gültigen Wert."));
            }

            if (readingType.Uom.HasValue)
            {
                ValidateReadingTypeUom(readingType.Uom, exceptions);
            }
            else
            {
                exceptions.Add(new InvalidOperationException("Das Element \"Uom\" innerhalb des Elements \"ReadingType\" enthält keinen gültigen Wert."));
            }
        }
Exemplo n.º 25
0
        /// <summary>
        /// 开始读取
        /// </summary>
        /// <param name="readingType"></param>
        /// <returns></returns>
        public ReturnMessage StartReading(ReadingType readingType, int aPollInterval, int aReadInterval)
        {
            ReturnMessage returnMsg = new ReturnMessage();

            switch (readingType)
            {
            case ReadingType.OnceReading:
                SingleShotRead();
                break;

            case ReadingType.PollReading:
                PollRead(aPollInterval, aReadInterval);
                break;

            case ReadingType.EventReading:
                EventRead(aReadInterval);
                break;

            default:
                //log [TODO]
                break;
            }
            return(returnMsg);
        }
Exemplo n.º 26
0
 public static async void Record(ReadingType t, WeatherInfoSource src, double x)
 {
     var rd = new WeatherRecord(CurrentDateTime, x, src, t);
     await Table.ExecuteAsync(TableOperation.Insert(rd));
 }
Exemplo n.º 27
0
	/* S T R I N G  F R O M  R E A D I N G  T Y P E */
	/*----------------------------------------------------------------------------
		%%Function: StringFromReadingType
		%%Qualified: bg.BGE.StringFromReadingType
		%%Contact: rlittle

		
	----------------------------------------------------------------------------*/
	public static string StringFromReadingType(ReadingType type)
	{
		switch (type)
			{
			case ReadingType.Breakfast:
				return "Breakfast";
			case ReadingType.Lunch:
				return "Lunch";
			case ReadingType.Snack:
				return "Snack";
			case ReadingType.Dinner:
				return "Dinner";
			case ReadingType.New:
				return "*NEW*";
			case ReadingType.Control:
				return "Control";
			default:
				return "SpotTest";
			}
	}
 public SinglePointReading()
 {
     Type     = ReadingType.LostSignal;
     Distance = 0.0f;
 }
        /// <summary>
        /// Calling this method will reconfigure some of the settings in this class to try to optimize them for better performances
        /// </summary>
        /// <param name="estimatedEventsPerDay">Estimation of the average number of events per day, per tag</param>
        /// <param name="estimatedTagsCount"> Estimation of the total amount of tags that needs to be processed.</param>
        /// <param name="eventsPerRead">Defines the number of events that should be read per data call.  somewhere between 10000 and 50000 is a good start.</param>
        /// <param name="readType">Type of read that you want to perform.  Bulk performs better if network has latency.  Paralell can outperform bulk if latency is low.</param>
        public void AutoTune(ReadingType readType, int estimatedEventsPerDay, int estimatedTagsCount, int eventsPerRead)
        {
            double days = 1;

            if (estimatedTagsCount < 200000)
            {
                TagGroupSize = estimatedTagsCount/10;
                TagGroupSize = TagGroupSize <= 0 ? 1 : TagGroupSize;

            }
            else
            {
                TagGroupSize = 50000;
            }

            if (readType == ReadingType.Bulk)
            {
                // eventsWanted / Total events per day
                // bulkPageSize is the number of tags that will be queried per page.
                BulkPageSize = 1000;
                days = ((double)eventsPerRead / ((double)estimatedEventsPerDay*BulkPageSize));
                BulkParallelChunkSize = (TagGroupSize/5) <=1 ? 1 : (TagGroupSize / 5);

            }
            else
            {
                // in case we do parallel, we target 10 000 events per read
                days = ((double)eventsPerRead / estimatedEventsPerDay);
            }

            // set a time span that will give us approximately "eventsPerRead" events per call
            TimeIntervalPerDataRequest = TimeSpan.FromDays(days);
        }
Exemplo n.º 30
0
        private ChartData GetChartData(List <Reading> locationReadings, ReadingType readingType, string location)
        {
            // Build chart data object
            var chartData = new ChartData
            {
                Title  = $"{location}: {readingType}",
                Labels = GetChartLabels(DateTime.Today - TimeSpan.FromDays(7)),
                YAxis  = new Axis($"{readingType} per microgram"),
                XAxis  = new Axis("Day of the week")
            };

            var statReadingsSet = GetStatisticReadingList(locationReadings, readingType);

            var minSet = new DataSet
            {
                Label = $"{readingType}: Minimum"
            };

            var maxSet = new DataSet
            {
                Label = $"{readingType}: Maximum"
            };

            var avgSet = new DataSet
            {
                Label = $"{readingType}: Average"
            };

/*
 *          var timestampGroups = statReadingsSet
 *              .GroupBy(i => i.timestamp)
 *              .ToList();
 *
 *          foreach (var item in timestampGroups)
 *          {
 *              var valuesList = item.Select(groupValues => groupValues.value).DefaultIfEmpty();
 *
 *              var minValue = valuesList.Min();
 *              minSet.Values.Add(minValue);
 *
 *              var maxValue = valuesList.Max();
 *              maxSet.Values.Add(maxValue);
 *
 *              var avgValue = valuesList.Average();
 *              avgSet.Values.Add(avgValue);
 *          }*/

            var currDate = DateTime.Today - TimeSpan.FromDays(6);

            while (currDate <= DateTime.Today)
            {
                var currDateTimestamp = GetTimestampFromDateTime(currDate);
                var dayData           = statReadingsSet.Where(i => i.timestamp == currDateTimestamp);

                var valuesList = dayData.Select(groupValues => groupValues.value).DefaultIfEmpty();

                var minValue = valuesList.Min();
                minSet.Values.Add(minValue);

                var maxValue = valuesList.Max();
                maxSet.Values.Add(maxValue);

                var avgValue = valuesList.Average();
                avgSet.Values.Add(avgValue);

                currDate += TimeSpan.FromDays(1);
            }


            chartData.DataSets.Add(minSet);
            chartData.DataSets.Add(maxSet);
            chartData.DataSets.Add(avgSet);

            return(chartData);
        }
Exemplo n.º 31
0
	/* B  G  E */
	/*----------------------------------------------------------------------------
		%%Function: BGE
		%%Qualified: bg.BGE.BGE
		%%Contact: rlittle

		
	----------------------------------------------------------------------------*/
	public BGE(string sDate, string sTime, ReadingType type, int bg, int nCarbs, string sComment, string sMeal)
	{
		m_dttm = DateTime.Parse(sDate + " " + sTime);
		m_nBg = bg;
		m_type = type;
		m_nCarbs = nCarbs;
		m_sComment = sComment;
		m_sMeal = sMeal;
		m_fInterp = false;
	}
Exemplo n.º 32
0
        private Reading AddSensorReading(List <Reading> readings, DateTimeOffset dateTimeOffset, Config.Sensor sensor, string value, ReadingType readingType)
        {
            var reading = AddReading(readings, dateTimeOffset, sensor.ParameterId, sensor.UnitId, value);

            if (reading != null)
            {
                reading.ReadingType = readingType;
            }

            return(reading);
        }
Exemplo n.º 33
0
	public void SetTo(BGE bge)
	{
		m_type = bge.Type;
		m_dttm = bge.Date;
		m_nBg = bge.Reading;
		m_nCarbs = bge.Carbs;
		m_sComment = bge.Comment;
		m_sMeal = bge.Meal;
	}
Exemplo n.º 34
0
	public BGE(BGE bge)
	{
		m_dttm = bge.m_dttm;
		m_nBg = bge.m_nBg;
		m_type = bge.m_type;
		m_nCarbs = bge.m_nCarbs;
		m_sComment = bge.m_sComment;
		m_sMeal = bge.m_sMeal;
		m_fInterp = bge.m_fInterp;
		m_nMinutesSinceLastCarb = bge.m_nMinutesSinceLastCarb;
		m_nCarbsInLast4Hours = bge.m_nCarbsInLast4Hours;
		m_nWgtAvg = bge.m_nWgtAvg;
	}
Exemplo n.º 35
0
        private List <StatisticReading> GetStatisticReadingList(List <Reading> locationReadings, ReadingType readingType)
        {
            return(locationReadings
                   .Select(i =>
            {
                // get date timestamp
                var dateTime = GetDateTimeFromTimestamp(i.Timestamp);
                long dateTimestamp = GetTimestampFromDateTime(dateTime);

                return new StatisticReading
                {
                    timestamp = dateTimestamp,
                    value = GetStatisticReading(i, readingType)
                };
            })
                   .ToList());
        }