From 70c73cc6b3b41cbc50d664ca7c1706f5a222a73c Mon Sep 17 00:00:00 2001 From: Chris Kaczor Date: Sat, 29 May 2021 22:30:11 -0400 Subject: [PATCH] Tweaks to aggregation --- Weather/Service/Controllers/ReadingsController.cs | 4 ++-- Weather/Service/Models/WeatherAggregate.cs | 9 ++++++--- 2 files changed, 8 insertions(+), 5 deletions(-) diff --git a/Weather/Service/Controllers/ReadingsController.cs b/Weather/Service/Controllers/ReadingsController.cs index 3a383ef..c33f16c 100644 --- a/Weather/Service/Controllers/ReadingsController.cs +++ b/Weather/Service/Controllers/ReadingsController.cs @@ -35,9 +35,9 @@ namespace ChrisKaczor.HomeMonitor.Weather.Service.Controllers [HttpGet("aggregate")] public async Task> 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")] diff --git a/Weather/Service/Models/WeatherAggregate.cs b/Weather/Service/Models/WeatherAggregate.cs index 8b4aad6..d4afe3f 100644 --- a/Weather/Service/Models/WeatherAggregate.cs +++ b/Weather/Service/Models/WeatherAggregate.cs @@ -3,6 +3,8 @@ using System.Collections.Generic; using System.Linq; using ChrisKaczor.HomeMonitor.Weather.Models; using JetBrains.Annotations; +using Newtonsoft.Json; +using Newtonsoft.Json.Converters; namespace ChrisKaczor.HomeMonitor.Weather.Service.Models { @@ -19,13 +21,14 @@ namespace ChrisKaczor.HomeMonitor.Weather.Service.Models public ReadingAggregate WindSpeed { get; set; } + [JsonConverter(typeof(StringEnumConverter))] public WindDirection WindDirectionAverage { get; set; } public decimal RainTotal { get; set; } - private static readonly List _windDirectionValues = ((WindDirection[])Enum.GetValues(typeof(WindDirection))).Select(e => (int)e).ToList(); + private static readonly List WindDirectionValues = ((WindDirection[])Enum.GetValues(typeof(WindDirection))).Select(e => (int)e).ToList(); - public WeatherAggregate(IEnumerable readings) + public WeatherAggregate(List readings) { if (!readings.Any()) return; @@ -41,7 +44,7 @@ namespace ChrisKaczor.HomeMonitor.Weather.Service.Models WindSpeed = new ReadingAggregate(readings, r => r.WindSpeed, 1); 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); }