Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 |
Expand Down
2 changes: 1 addition & 1 deletion documentation/CONFIGURATION.md
Original file line number Diff line number Diff line change
Expand Up @@ -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. |
Expand Down
6 changes: 6 additions & 0 deletions src/GarageStack.Core/Interfaces/INotificationRepository.cs
Original file line number Diff line number Diff line change
Expand Up @@ -34,4 +34,10 @@ public interface INotificationRepository
/// restart or another service's alert still holds back a repeat.
/// </summary>
Task<bool> WasSentSinceAsync(string category, int? vehicleId, DateTime cutoff, CancellationToken ct = default);

/// <summary>
/// When the newest notification of <paramref name="category"/> about <paramref name="vehicleId"/>
/// created after <paramref name="cutoff"/> went out, deleted ones included, or null when none did.
/// </summary>
Task<DateTime?> GetLastSentAtAsync(string category, int? vehicleId, DateTime cutoff, CancellationToken ct = default);
}
6 changes: 6 additions & 0 deletions src/GarageStack.Core/Interfaces/ITelemetryRepository.cs
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,12 @@ Task<IReadOnlyList<DateTime>> GetReportTimesAsync(
/// </summary>
Task<double?> GetOdometerAtAsync(int vehicleId, DateTime at, CancellationToken ct = default);

/// <summary>
/// The 12V battery voltage as last reported at or before <paramref name="at"/>, or null when
/// the vehicle had not reported one by then.
/// </summary>
Task<double?> GetBatteryVoltageAtAsync(int vehicleId, DateTime at, CancellationToken ct = default);

/// <summary>
/// The day counter's (powerUsageOfDay) readings over a trip, oldest first: the last one at or
/// before <paramref name="from"/>, then every one after it up to <paramref name="to"/>. Empty
Expand Down
6 changes: 6 additions & 0 deletions src/GarageStack.Data/Demo/DemoTelemetryRepository.cs
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,12 @@ public Task<IReadOnlyList<DateTime>> GetReportTimesAsync(
lock (_lock) { return Task.FromResult(Current(vehicleId).OdometerKm); }
}

// Only the Worker's 12V alert asks, and demo mode runs no Worker.
public Task<double?> 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<IReadOnlyList<double>> GetDayCounterReadingsAsync(
Expand Down
5 changes: 5 additions & 0 deletions src/GarageStack.Data/Repositories/NotificationRepository.cs
Original file line number Diff line number Diff line change
Expand Up @@ -81,4 +81,9 @@ private async Task SetAllAsync(

public Task<bool> 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<DateTime?> 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);
}
8 changes: 8 additions & 0 deletions src/GarageStack.Data/Repositories/TelemetryRepository.cs
Original file line number Diff line number Diff line change
Expand Up @@ -387,6 +387,14 @@ await db.TelemetrySnapshots
.Select(s => s.OdometerKm)
.FirstOrDefaultAsync(ct);

public Task<double?> 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<IReadOnlyList<double>> GetDayCounterReadingsAsync(
int vehicleId, DateTime from, DateTime to, CancellationToken ct = default)
{
Expand Down
21 changes: 21 additions & 0 deletions src/GarageStack.Tests/NotificationRepositoryTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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()
{
Expand Down
125 changes: 125 additions & 0 deletions src/GarageStack.Tests/PushNotificationCheckServiceTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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<Vehicle> 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
// ---------------------------------------------------------------------------
Expand Down
1 change: 1 addition & 0 deletions src/GarageStack.Tests/TelemetryHandlerTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ public Task MergeIntoAsync(long rowId, TelemetrySnapshot patch, CancellationToke
public Task<TripPoint?> GetLastGpsFixBeforeAsync(int vehicleId, DateTime before, CancellationToken ct = default) => throw new NotImplementedException();
public Task<IReadOnlyList<DateTime>> GetReportTimesAsync(int vehicleId, DateTime after, DateTime before, int limit, CancellationToken ct = default) => throw new NotImplementedException();
public Task<double?> GetOdometerAtAsync(int vehicleId, DateTime at, CancellationToken ct = default) => throw new NotImplementedException();
public Task<double?> GetBatteryVoltageAtAsync(int vehicleId, DateTime at, CancellationToken ct = default) => throw new NotImplementedException();
public Task<IReadOnlyList<double>> GetDayCounterReadingsAsync(int vehicleId, DateTime from, DateTime to, CancellationToken ct = default) => throw new NotImplementedException();
public Task<IReadOnlyList<ElevationReading>> GetElevationsAsync(int vehicleId, DateTime from, DateTime to, CancellationToken ct = default) => throw new NotImplementedException();
public Task<IReadOnlyList<StatusReading>> GetStatusReadingsAsync(int vehicleId, int count, CancellationToken ct = default) => throw new NotImplementedException();
Expand Down
23 changes: 23 additions & 0 deletions src/GarageStack.Tests/TelemetryRepositoryTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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()
{
Expand Down
38 changes: 35 additions & 3 deletions src/GarageStack.Worker/Services/PushNotificationCheckService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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 <see cref="Low12VRewarnDropVolt"/>). A car that left the spot it
/// parked on is warned about once per parking, unless its odometer says it was driven there.
/// </summary>
internal async Task CheckParkedAsync(
Vehicle vehicle, TelemetrySnapshot snapshot, ITelemetryRepository telemetry, IVehicleRepository vehicles,
Expand All @@ -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)>();
Expand Down Expand Up @@ -341,6 +343,36 @@ internal void CheckAuxBatteryWhileParked(IReadOnlyList<StatusReading> readings,
alerts.Add((NotificationCategories.Low12V, strings["Low12VTitle"], strings["Low12VBody", voltage]));
}

/// <summary>
/// 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.
/// </summary>
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<StatusReading> 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<StatusReading> readings, List<(string, string, string)> alerts) =>
CheckOpenWhileParked(readings, DoorPositions, alerts, NotificationCategories.DoorsOpenParked, "DoorsOpenTitle", "DoorsOpenBody");

Expand Down
Loading