diff --git a/README.md b/README.md index 52230041..e57d5279 100644 --- a/README.md +++ b/README.md @@ -382,7 +382,7 @@ GarageStack checks your vehicle's state every 5 minutes and sends both a browser | Possible slow puncture | One tyre lost `TYRE_PRESSURE_DROP_BAR` (default 0.15 bar) or more that the other three kept, over the last two weeks. Comparing the tyres with each other leaves out the weather, which moves all four together. Sent at most once every three days; tap a tyre on the dashboard's diagram for its history | | Low EV battery | EV state-of-charge below `LOW_EV_PERCENT` (default 20 %, plug-in vehicles) | | Low fuel | Fuel level below `LOW_FUEL_PERCENT` (default 15 %, hybrids and plug-in hybrids) | -| Low 12V battery | 12V battery below `AUX_BATTERY_LOW_VOLT` (default 12.0 V) on several polls in a row while the engine is off | +| Low 12V battery | 12V battery below `AUX_BATTERY_LOW_VOLT` (default 12.0 V) on several polls in a row while the engine is off. Sent once per parking, and again only when the voltage has dropped another 0.3 V since the last warning | | No data from the car | Nothing reported for `STALE_DATA_HOURS` (default 48 hours): the MG session, the gateway or the car's connection needs a look | | MG sign-in failed | The gateway could not sign in to the MG account, so no new data arrives (sent once per outage, as it happens) | | Car left unlocked | `doors/locked = false` while engine is off | diff --git a/documentation/CONFIGURATION.md b/documentation/CONFIGURATION.md index d180bd54..84c575ff 100644 --- a/documentation/CONFIGURATION.md +++ b/documentation/CONFIGURATION.md @@ -131,7 +131,7 @@ Each car can also have its own battery size, tyre pressures and warning levels, | --- | --- | --- | | `TYRE_PRESSURE_LOW_BAR` / `TYRE_PRESSURE_GOOD_BAR` / `TYRE_PRESSURE_HIGH_BAR` | `2.2` / `2.6` / `3.2` | Tyre pressure bands in bar, for the diagram's colours and the tyre notifications. Set them from your car's placard. | | `TYRE_PRESSURE_DROP_BAR` | `0.15` | How far, in bar, one tyre may fall behind the other three over two weeks before it is reported as a possible slow puncture. `0` switches the alert off. | -| `AUX_BATTERY_LOW_VOLT` | `12.0` | 12V battery voltage a parked car is warned below, once several polls in a row show it. `0` switches the alert off. | +| `AUX_BATTERY_LOW_VOLT` | `12.0` | 12V battery voltage a parked car is warned below, once several polls in a row show it. Sent once per parking, and again when it has dropped another 0.3 V. `0` switches the alert off. | | `LOW_FUEL_PERCENT` | `15` | Fuel level, in percent, a hybrid or plug-in hybrid is warned below. `0` switches the alert off. | | `LOW_EV_PERCENT` | `20` | Charge level, in percent, a plug-in car is warned below. `0` switches the alert off. | | `STALE_DATA_HOURS` | `48` | Hours without a report from the car before GarageStack warns that data has stopped arriving. Keep it above the gateway's poll of a sleeping car, once a day by default. `0` switches the alert off. | diff --git a/src/GarageStack.Core/Interfaces/INotificationRepository.cs b/src/GarageStack.Core/Interfaces/INotificationRepository.cs index 8e093e4f..d5cf942f 100644 --- a/src/GarageStack.Core/Interfaces/INotificationRepository.cs +++ b/src/GarageStack.Core/Interfaces/INotificationRepository.cs @@ -34,4 +34,10 @@ public interface INotificationRepository /// restart or another service's alert still holds back a repeat. /// Task WasSentSinceAsync(string category, int? vehicleId, DateTime cutoff, CancellationToken ct = default); + + /// + /// When the newest notification of about + /// created after went out, deleted ones included, or null when none did. + /// + Task GetLastSentAtAsync(string category, int? vehicleId, DateTime cutoff, CancellationToken ct = default); } diff --git a/src/GarageStack.Core/Interfaces/ITelemetryRepository.cs b/src/GarageStack.Core/Interfaces/ITelemetryRepository.cs index 483dda4b..ad1f1c6e 100644 --- a/src/GarageStack.Core/Interfaces/ITelemetryRepository.cs +++ b/src/GarageStack.Core/Interfaces/ITelemetryRepository.cs @@ -72,6 +72,12 @@ Task> GetReportTimesAsync( /// Task GetOdometerAtAsync(int vehicleId, DateTime at, CancellationToken ct = default); + /// + /// The 12V battery voltage as last reported at or before , or null when + /// the vehicle had not reported one by then. + /// + Task GetBatteryVoltageAtAsync(int vehicleId, DateTime at, CancellationToken ct = default); + /// /// The day counter's (powerUsageOfDay) readings over a trip, oldest first: the last one at or /// before , then every one after it up to . Empty diff --git a/src/GarageStack.Data/Demo/DemoTelemetryRepository.cs b/src/GarageStack.Data/Demo/DemoTelemetryRepository.cs index bbdb99df..42f919c6 100644 --- a/src/GarageStack.Data/Demo/DemoTelemetryRepository.cs +++ b/src/GarageStack.Data/Demo/DemoTelemetryRepository.cs @@ -74,6 +74,12 @@ public Task> GetReportTimesAsync( lock (_lock) { return Task.FromResult(Current(vehicleId).OdometerKm); } } + // Only the Worker's 12V alert asks, and demo mode runs no Worker. + public Task GetBatteryVoltageAtAsync(int vehicleId, DateTime at, CancellationToken ct = default) + { + lock (_lock) { return Task.FromResult(Current(vehicleId).BatteryVoltage); } + } + // Only the Worker's recorder reads a trip's counter, and demo mode runs no Worker: DemoTrips // carries what each trip used. public Task> GetDayCounterReadingsAsync( diff --git a/src/GarageStack.Data/Repositories/NotificationRepository.cs b/src/GarageStack.Data/Repositories/NotificationRepository.cs index 47a8abf9..288cbc89 100644 --- a/src/GarageStack.Data/Repositories/NotificationRepository.cs +++ b/src/GarageStack.Data/Repositories/NotificationRepository.cs @@ -81,4 +81,9 @@ private async Task SetAllAsync( public Task WasSentSinceAsync(string category, int? vehicleId, DateTime cutoff, CancellationToken ct = default) => db.AppNotifications.AnyAsync(n => n.Category == category && n.VehicleId == vehicleId && n.CreatedAt > cutoff, ct); + + public Task GetLastSentAtAsync(string category, int? vehicleId, DateTime cutoff, CancellationToken ct = default) => + db.AppNotifications + .Where(n => n.Category == category && n.VehicleId == vehicleId && n.CreatedAt > cutoff) + .MaxAsync(n => (DateTime?)n.CreatedAt, ct); } diff --git a/src/GarageStack.Data/Repositories/TelemetryRepository.cs b/src/GarageStack.Data/Repositories/TelemetryRepository.cs index 25852f14..f90a7dcf 100644 --- a/src/GarageStack.Data/Repositories/TelemetryRepository.cs +++ b/src/GarageStack.Data/Repositories/TelemetryRepository.cs @@ -387,6 +387,14 @@ await db.TelemetrySnapshots .Select(s => s.OdometerKm) .FirstOrDefaultAsync(ct); + public Task GetBatteryVoltageAtAsync(int vehicleId, DateTime at, CancellationToken ct = default) => + db.TelemetrySnapshots + .AsNoTracking() + .Where(s => s.VehicleId == vehicleId && s.RecordedAt <= at && s.BatteryVoltage != null) + .OrderByDescending(s => s.RecordedAt) + .Select(s => s.BatteryVoltage) + .FirstOrDefaultAsync(ct); + public async Task> GetDayCounterReadingsAsync( int vehicleId, DateTime from, DateTime to, CancellationToken ct = default) { diff --git a/src/GarageStack.Tests/NotificationRepositoryTests.cs b/src/GarageStack.Tests/NotificationRepositoryTests.cs index 79d77eb2..571f1894 100644 --- a/src/GarageStack.Tests/NotificationRepositoryTests.cs +++ b/src/GarageStack.Tests/NotificationRepositoryTests.cs @@ -52,6 +52,27 @@ public async Task WasSentSinceAsync_NotificationBeforeCutoff_ReturnsFalse() Assert.False(result); } + [Fact] + public async Task GetLastSentAtAsync_IsTheNewestMatchAfterTheCutoff() + { + var ct = TestContext.Current.CancellationToken; + await using var db = CreateDb(); + var t0 = new DateTime(2026, 11, 25, 8, 0, 0, DateTimeKind.Utc); + AppNotification Sent(string category, int vehicleId, DateTime at) => + new() { Category = category, VehicleId = vehicleId, CreatedAt = at, Title = "12V", Body = "..." }; + db.AppNotifications.AddRange( + Sent("low-12v", 1, t0.AddHours(-2)), + Sent("low-12v", 1, t0.AddHours(1)), + Sent("low-12v", 1, t0.AddHours(3)), + Sent("low-12v", 2, t0.AddHours(4)), + Sent("low-tyre", 1, t0.AddHours(5))); + await db.SaveChangesAsync(ct); + var repo = new NotificationRepository(db); + + Assert.Equal(t0.AddHours(3), await repo.GetLastSentAtAsync("low-12v", 1, t0, ct)); + Assert.Null(await repo.GetLastSentAtAsync("low-12v", 1, t0.AddHours(3), ct)); + } + [Fact] public async Task WasSentSinceAsync_DifferentVehicle_ReturnsFalse() { diff --git a/src/GarageStack.Tests/PushNotificationCheckServiceTests.cs b/src/GarageStack.Tests/PushNotificationCheckServiceTests.cs index feb76e1f..658b41a9 100644 --- a/src/GarageStack.Tests/PushNotificationCheckServiceTests.cs +++ b/src/GarageStack.Tests/PushNotificationCheckServiceTests.cs @@ -598,6 +598,131 @@ public void CheckAuxBatteryWhileParked_UsesTheConfiguredVoltage() Assert.Equal("low-12v", Assert.Single(alerts).Item1); } + [Theory] + [InlineData(11.6, 11.9, true)] + [InlineData(11.7, 12.0, true)] + [InlineData(11.7, 11.9, false)] + [InlineData(11.9, 11.9, false)] + [InlineData(12.1, 11.9, false)] + [InlineData(11.0, null, false)] + public void HasDroppedFurther_CountsADropOfAtLeastThreeTenths(double voltage, double? warnedAbout, bool expected) + { + Assert.Equal(expected, PushNotificationCheckService.HasDroppedFurther(voltage, warnedAbout)); + } + + // --------------------------------------------------------------------------- + // CheckParkedAsync and the 12V battery: once per parking, again when it drops further + // --------------------------------------------------------------------------- + + // A car that parked at parkedAt with its 12V battery at the given voltages, one poll each, + // two and a half minutes apart. + private static async Task ParkedWithVoltagesAsync( + AppDbContext db, DateTime parkedAt, CancellationToken ct, params (TimeSpan After, double Volts)[] polls) + { + var vehicle = new Vehicle { Vin = "FAKEVN00000000001", LastParkedAt = parkedAt }; + db.Vehicles.Add(vehicle); + await db.SaveChangesAsync(ct); + + db.TelemetrySnapshots.AddRange(polls.Select(p => new TelemetrySnapshot + { + VehicleId = vehicle.Id, + RecordedAt = parkedAt + p.After, + LastVehicleStateAt = parkedAt + p.After, + IsLocked = true, + EngineRunning = false, + BatteryVoltage = p.Volts, + })); + await db.SaveChangesAsync(ct); + return vehicle; + } + + private static (TimeSpan, double)[] PollsFrom(TimeSpan start, double volts) => + [.. Enumerable.Range(0, 4).Select(i => (start + TimeSpan.FromSeconds(150 * i), volts))]; + + private static void AddLow12VSentAt(AppDbContext db, Vehicle vehicle, DateTime at) => + db.AppNotifications.Add(new AppNotification + { + Title = "Weak 12V battery", + Category = NotificationCategories.Low12V, + VehicleId = vehicle.Id, + CreatedAt = at, + }); + + private static Task CheckParkedAsync(FakePushSender push, Vehicle vehicle, AppDbContext db, DateTime now, CancellationToken ct) => + CreateService(push: push).CheckParkedAsync( + vehicle, Parked(), new TelemetryRepository(db), new VehicleRepository(db), new NotificationRepository(db), now, ct); + + [Fact] + public async Task CheckParkedAsync_Low12V_SendsTheAlert() + { + var ct = TestContext.Current.CancellationToken; + var now = DateTime.UtcNow; + await using var db = CreateDb(); + var vehicle = await ParkedWithVoltagesAsync(db, now.AddHours(-1), ct, PollsFrom(TimeSpan.Zero, 11.9)); + var push = new FakePushSender(); + + await CheckParkedAsync(push, vehicle, db, now, ct); + + Assert.Equal(NotificationCategories.Low12V, Assert.Single(push.Sent).Category); + } + + // The cold-weather case: woken now and then, the car is still as low as when it was warned + // about hours ago. The cooldown has run out, but there is nothing new to report. + [Fact] + public async Task CheckParkedAsync_Low12VAlreadyWarnedThisParkingAndNoLower_SendsNothing() + { + var ct = TestContext.Current.CancellationToken; + var now = DateTime.UtcNow; + var parkedAt = now.AddHours(-8); + await using var db = CreateDb(); + var vehicle = await ParkedWithVoltagesAsync( + db, parkedAt, ct, [.. PollsFrom(TimeSpan.Zero, 11.9), .. PollsFrom(TimeSpan.FromHours(7), 11.8)]); + AddLow12VSentAt(db, vehicle, parkedAt.AddMinutes(15)); + await db.SaveChangesAsync(ct); + var push = new FakePushSender(); + + await CheckParkedAsync(push, vehicle, db, now, ct); + + Assert.Empty(push.Sent); + } + + [Fact] + public async Task CheckParkedAsync_Low12VDroppedFurtherSinceTheWarning_SendsAgain() + { + var ct = TestContext.Current.CancellationToken; + var now = DateTime.UtcNow; + var parkedAt = now.AddHours(-8); + await using var db = CreateDb(); + var vehicle = await ParkedWithVoltagesAsync( + db, parkedAt, ct, [.. PollsFrom(TimeSpan.Zero, 11.9), .. PollsFrom(TimeSpan.FromHours(7), 11.6)]); + AddLow12VSentAt(db, vehicle, parkedAt.AddMinutes(15)); + await db.SaveChangesAsync(ct); + var push = new FakePushSender(); + + await CheckParkedAsync(push, vehicle, db, now, ct); + + Assert.Equal(NotificationCategories.Low12V, Assert.Single(push.Sent).Category); + } + + // A warning from before the car last parked belongs to another parking: a drive in between + // should have charged the battery, so still being low is news. + [Fact] + public async Task CheckParkedAsync_Low12VWarnedOnlyInAnEarlierParking_SendsTheAlert() + { + var ct = TestContext.Current.CancellationToken; + var now = DateTime.UtcNow; + var parkedAt = now.AddHours(-1); + await using var db = CreateDb(); + var vehicle = await ParkedWithVoltagesAsync(db, parkedAt, ct, PollsFrom(TimeSpan.Zero, 11.9)); + AddLow12VSentAt(db, vehicle, parkedAt.AddHours(-5)); + await db.SaveChangesAsync(ct); + var push = new FakePushSender(); + + await CheckParkedAsync(push, vehicle, db, now, ct); + + Assert.Equal(NotificationCategories.Low12V, Assert.Single(push.Sent).Category); + } + // --------------------------------------------------------------------------- // CheckLevelsAsync: one alert per report, however long the car sleeps // --------------------------------------------------------------------------- diff --git a/src/GarageStack.Tests/TelemetryHandlerTests.cs b/src/GarageStack.Tests/TelemetryHandlerTests.cs index dc896571..9dfcf51c 100644 --- a/src/GarageStack.Tests/TelemetryHandlerTests.cs +++ b/src/GarageStack.Tests/TelemetryHandlerTests.cs @@ -47,6 +47,7 @@ public Task MergeIntoAsync(long rowId, TelemetrySnapshot patch, CancellationToke public Task GetLastGpsFixBeforeAsync(int vehicleId, DateTime before, CancellationToken ct = default) => throw new NotImplementedException(); public Task> GetReportTimesAsync(int vehicleId, DateTime after, DateTime before, int limit, CancellationToken ct = default) => throw new NotImplementedException(); public Task GetOdometerAtAsync(int vehicleId, DateTime at, CancellationToken ct = default) => throw new NotImplementedException(); + public Task GetBatteryVoltageAtAsync(int vehicleId, DateTime at, CancellationToken ct = default) => throw new NotImplementedException(); public Task> GetDayCounterReadingsAsync(int vehicleId, DateTime from, DateTime to, CancellationToken ct = default) => throw new NotImplementedException(); public Task> GetElevationsAsync(int vehicleId, DateTime from, DateTime to, CancellationToken ct = default) => throw new NotImplementedException(); public Task> GetStatusReadingsAsync(int vehicleId, int count, CancellationToken ct = default) => throw new NotImplementedException(); diff --git a/src/GarageStack.Tests/TelemetryRepositoryTests.cs b/src/GarageStack.Tests/TelemetryRepositoryTests.cs index d6c021fe..33c7df2f 100644 --- a/src/GarageStack.Tests/TelemetryRepositoryTests.cs +++ b/src/GarageStack.Tests/TelemetryRepositoryTests.cs @@ -114,6 +114,29 @@ public async Task GetReportTimes_AreEveryRowBetweenTheTimes_NewestFirstAndCapped Assert.Equal([t0.AddMinutes(2)], await repo.GetReportTimesAsync(vehicle.Id, t0, t0.AddMinutes(3), 1, ct)); } + [Fact] + public async Task GetBatteryVoltageAt_IsTheCarsLastVoltageAtOrBeforeTheTime() + { + var ct = TestContext.Current.CancellationToken; + await using var db = CreateDb(); + var vehicle = new Vehicle { Vin = "FAKEVN00000000001" }; + db.Vehicles.Add(vehicle); + await db.SaveChangesAsync(ct); + + var t0 = new DateTime(2026, 1, 1, 10, 0, 0, DateTimeKind.Utc); + var repo = new TelemetryRepository(db); + db.TelemetrySnapshots.AddRange( + new TelemetrySnapshot { VehicleId = vehicle.Id, RecordedAt = t0, BatteryVoltage = 12.4 }, + new TelemetrySnapshot { VehicleId = vehicle.Id, RecordedAt = t0.AddMinutes(1), OdometerKm = 100 }, + new TelemetrySnapshot { VehicleId = vehicle.Id, RecordedAt = t0.AddMinutes(5), BatteryVoltage = 11.9 }, + new TelemetrySnapshot { VehicleId = vehicle.Id + 1, RecordedAt = t0.AddMinutes(2), BatteryVoltage = 10.5 }); + await db.SaveChangesAsync(ct); + + Assert.Null(await repo.GetBatteryVoltageAtAsync(vehicle.Id, t0.AddMinutes(-1), ct)); + Assert.Equal(12.4, await repo.GetBatteryVoltageAtAsync(vehicle.Id, t0.AddMinutes(3), ct)); + Assert.Equal(11.9, await repo.GetBatteryVoltageAtAsync(vehicle.Id, t0.AddMinutes(5), ct)); + } + [Fact] public async Task GetChargeSessions_ReconstructsCompletedAndOngoingSessionsFromTransitions() { diff --git a/src/GarageStack.Worker/Services/PushNotificationCheckService.cs b/src/GarageStack.Worker/Services/PushNotificationCheckService.cs index e3a838a0..cc56c2a8 100644 --- a/src/GarageStack.Worker/Services/PushNotificationCheckService.cs +++ b/src/GarageStack.Worker/Services/PushNotificationCheckService.cs @@ -124,8 +124,9 @@ internal static DateTime NewestReportAt(TelemetrySnapshot s) => /// Warns about a car parked unlocked, with a door or window open, or with a low 12V battery, /// once its polls have shown it for a while. Every warning rests on the newest poll and goes /// out once for it: a car asleep overnight would otherwise be reported every hour on the one - /// poll it last sent. A car that left the spot it parked on is warned about once per parking, - /// unless its odometer says it was driven there. + /// poll it last sent. A low 12V battery is warned about once per parking, and again only when + /// it has dropped further (see ). A car that left the spot it + /// parked on is warned about once per parking, unless its odometer says it was driven there. /// internal async Task CheckParkedAsync( Vehicle vehicle, TelemetrySnapshot snapshot, ITelemetryRepository telemetry, IVehicleRepository vehicles, @@ -141,10 +142,11 @@ internal async Task CheckParkedAsync( CheckUnlockedWhileParked(readings, alerts); CheckDoorsOpenWhileParked(readings, alerts); CheckWindowsOpenWhileParked(readings, alerts); - CheckAuxBatteryWhileParked(readings, VehicleSettingsResolver.Resolve(vehicle, defaults).Alerts, alerts); if (alerts.Count > 0) await SendAsync(vehicle, alerts, notifications, ct, onceSince: readings[0].ArrivedAt); + await CheckAuxBatteryOncePerParkingAsync(vehicle, readings, telemetry, notifications, ct); + if (await ParkAfterUnseenDriveAsync(vehicle, telemetry, vehicles, now, ct)) return; var moved = new List<(string key, string title, string body)>(); @@ -341,6 +343,36 @@ internal void CheckAuxBatteryWhileParked(IReadOnlyList readings, alerts.Add((NotificationCategories.Low12V, strings["Low12VTitle"], strings["Low12VBody", voltage])); } + /// + /// How far the 12V battery has to drop below the voltage it was last warned about, in the same + /// parking, before it is warned about again. A battery that stays low in the cold is news once; + /// one that keeps draining is news again. + /// + internal const double Low12VRewarnDropVolt = 0.3; + + // A car seen parking is warned about once from then; one never seen parking, once per poll. + private async Task CheckAuxBatteryOncePerParkingAsync( + Vehicle vehicle, IReadOnlyList readings, ITelemetryRepository telemetry, + INotificationRepository notifications, CancellationToken ct) + { + var alerts = new List<(string key, string title, string body)>(); + CheckAuxBatteryWhileParked(readings, VehicleSettingsResolver.Resolve(vehicle, defaults).Alerts, alerts); + if (alerts.Count == 0) return; + + var parkingStart = vehicle.LastParkedAt ?? readings[0].ArrivedAt; + if (await notifications.GetLastSentAtAsync(NotificationCategories.Low12V, vehicle.Id, parkingStart, ct) is { } warnedAt) + { + var warnedAbout = await telemetry.GetBatteryVoltageAtAsync(vehicle.Id, warnedAt, ct); + if (!HasDroppedFurther(readings[0].State.BatteryVoltage!.Value, warnedAbout)) return; + } + + await SendAsync(vehicle, alerts, notifications, ct); + } + + // Rounded to the tenth the alert shows, so 12.0 to 11.7 counts as the 0.3 it reads as. + internal static bool HasDroppedFurther(double voltage, double? warnedAbout) => + warnedAbout is { } before && Math.Round(before - voltage, 1) >= Low12VRewarnDropVolt; + internal void CheckDoorsOpenWhileParked(IReadOnlyList readings, List<(string, string, string)> alerts) => CheckOpenWhileParked(readings, DoorPositions, alerts, NotificationCategories.DoorsOpenParked, "DoorsOpenTitle", "DoorsOpenBody");