Tweaks to aggregation

This commit is contained in:
2021-05-29 22:30:11 -04:00
parent 4cb2ebe75a
commit 70c73cc6b3
2 changed files with 8 additions and 5 deletions

View File

@@ -35,9 +35,9 @@ namespace ChrisKaczor.HomeMonitor.Weather.Service.Controllers
[HttpGet("aggregate")] [HttpGet("aggregate")]
public async Task<ActionResult<WeatherAggregate>> GetHistoryAggregate(DateTimeOffset start, DateTimeOffset end) public async Task<ActionResult<WeatherAggregate>> GetHistoryAggregate(DateTimeOffset start, DateTimeOffset end)
{ {
var readings = await _database.GetReadingHistory(start, end); var readings = (await _database.GetReadingHistory(start, end)).ToList();
return new WeatherAggregate(readings); return readings.Any() ? new WeatherAggregate(readings) : null;
} }
[HttpGet("value-history")] [HttpGet("value-history")]

View File

@@ -3,6 +3,8 @@ using System.Collections.Generic;
using System.Linq; using System.Linq;
using ChrisKaczor.HomeMonitor.Weather.Models; using ChrisKaczor.HomeMonitor.Weather.Models;
using JetBrains.Annotations; using JetBrains.Annotations;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
namespace ChrisKaczor.HomeMonitor.Weather.Service.Models namespace ChrisKaczor.HomeMonitor.Weather.Service.Models
{ {
@@ -19,13 +21,14 @@ namespace ChrisKaczor.HomeMonitor.Weather.Service.Models
public ReadingAggregate WindSpeed { get; set; } public ReadingAggregate WindSpeed { get; set; }
[JsonConverter(typeof(StringEnumConverter))]
public WindDirection WindDirectionAverage { get; set; } public WindDirection WindDirectionAverage { get; set; }
public decimal RainTotal { get; set; } public decimal RainTotal { get; set; }
private static readonly List<int> _windDirectionValues = ((WindDirection[])Enum.GetValues(typeof(WindDirection))).Select(e => (int)e).ToList(); private static readonly List<int> WindDirectionValues = ((WindDirection[])Enum.GetValues(typeof(WindDirection))).Select(e => (int)e).ToList();
public WeatherAggregate(IEnumerable<WeatherReading> readings) public WeatherAggregate(List<WeatherReading> readings)
{ {
if (!readings.Any()) if (!readings.Any())
return; return;
@@ -41,7 +44,7 @@ namespace ChrisKaczor.HomeMonitor.Weather.Service.Models
WindSpeed = new ReadingAggregate(readings, r => r.WindSpeed, 1); WindSpeed = new ReadingAggregate(readings, r => r.WindSpeed, 1);
var windDirectionAverage = readings.Average(r => (decimal)r.WindDirection); var windDirectionAverage = readings.Average(r => (decimal)r.WindDirection);
WindDirectionAverage = (WindDirection)_windDirectionValues.Aggregate((x, y) => Math.Abs(x - windDirectionAverage) < Math.Abs(y - windDirectionAverage) ? x : y); WindDirectionAverage = (WindDirection)WindDirectionValues.Aggregate((x, y) => Math.Abs(x - windDirectionAverage) < Math.Abs(y - windDirectionAverage) ? x : y);
RainTotal = readings.Sum(r => r.Rain); RainTotal = readings.Sum(r => r.Rain);
} }