From 26dea704ccee6da43cc32fcbd886d4014fab36c0 Mon Sep 17 00:00:00 2001 From: arthur-lzrs <55158951+arthur-lzrs@users.noreply.github.com> Date: Fri, 27 Nov 2026 15:03:06 -0300 Subject: [PATCH 1/4] feat: work out the distance since the last charge for cars that do not report it Some cars send a distance-since-last-charge counter and some never do, so the Since Charge card on the dashboard simply never appears for the latter, although the readings GarageStack has already stored hold everything needed to count it. For a car whose merged snapshot has no mileageSinceLastCharge, GetMergedLatestAsync now fills it in: the odometer now, less the odometer where the car's last charge ended. The end of the last charge is the later of the end time the car reports (charging/lastEnd) and the last reading that showed it charging; a charge still going counts as ending now, so it reads 0. A charging reading is dated by its poll's own stamp when that is older than its row, so a gateway that starts again and sends an old charge state in a new row does not move the end of the last charge. A time from the future is not believed, an odometer that went backwards gives no distance, and a car with no charge in its readings (its first charge since GarageStack began recording has not happened) gets none, so the card stays out of sight until there is one to count from. A car that reports the counter keeps its own value untouched. The figure comes through /status, the widget endpoint and the live updates alike, since they all read the merged snapshot, so the existing card shows up on its own. A worked-out figure is not passed off as a measured one: the snapshot carries mileageSinceLastChargeCalculated (not stored, merged or exported: it is [NotMapped] and kept out of the field merge and the data export), and the dashboard shows the distance, and the efficiency since the last charge that rests on it, with an approximate sign in front. The card's info text says how the figure is worked out, in every locale. The odometer at the last charge is remembered for a minute (an absent charge too), as it is found by reading back through the readings, up to 400 days. Checked against a car that does report the counter: from the odometer alone, 94 of 102 readings came out exactly the same and the rest one kilometre under, from rounding. Co-Authored-By: Claude Sonnet 5.5 --- README.md | 2 +- documentation/WIDGET.md | 2 +- documentation/openapi.json | 6 +- .../src/components/DashboardCardContent.vue | 19 +- .../__tests__/DashboardCardContent.spec.ts | 42 +++ frontend/src/locales/en.json | 2 +- frontend/src/locales/es.json | 2 +- frontend/src/locales/nl.json | 2 +- frontend/src/locales/pt-PT.json | 2 +- frontend/src/locales/pt.json | 2 +- frontend/src/services/vehicleApi.ts | 2 + .../Endpoints/VehicleEndpoints.cs | 2 +- src/GarageStack.Api/Services/ZipExport.cs | 6 +- .../Helpers/DistanceSinceCharge.cs | 62 ++++ .../Helpers/TelemetryFields.cs | 2 + .../Models/TelemetrySnapshot.cs | 8 + .../Repositories/TelemetryRepository.cs | 63 ++++ .../DistanceSinceChargeTests.cs | 282 ++++++++++++++++++ .../TelemetryRepositoryPostgresTests.cs | 21 ++ 19 files changed, 517 insertions(+), 12 deletions(-) create mode 100644 src/GarageStack.Core/Helpers/DistanceSinceCharge.cs create mode 100644 src/GarageStack.Tests/DistanceSinceChargeTests.cs diff --git a/README.md b/README.md index e57d5279..e9e661b4 100644 --- a/README.md +++ b/README.md @@ -117,7 +117,7 @@ Cards are shown or hidden automatically based on vehicle type (HEV / PHEV / BEV) | Lights | Main beam, low beam, sidelights | All | | Daily Distance | Distance driven today | All | | Daily Energy | Energy used today (kWh), or fuel burned today (L) on an HEV. On a PHEV the kWh show once `HV_BATTERY_CAPACITY_KWH` is set | All | -| Since Charge | Distance since last charge session | PHEV, BEV | +| Since Charge | Distance since last charge session. A car that does not report this itself gets it worked out from the odometer at the end of the last recorded charge | PHEV, BEV | | Efficiency | Energy consumption in the chosen unit, or fuel consumption (L/100 km) on an HEV | All | | Speed | Current vehicle speed | All (off by default) | | Top Speed | Highest speed recorded in the most recent completed trip | All | diff --git a/documentation/WIDGET.md b/documentation/WIDGET.md index 47145fe2..02512a37 100644 --- a/documentation/WIDGET.md +++ b/documentation/WIDGET.md @@ -56,7 +56,7 @@ The endpoint returns a flat JSON object. Numeric fields are `null` when the vehi | `electricRangeKm` | number | Distance the car estimates it can drive on the battery alone (km), on a BEV or PHEV. Never reported as 0, so an empty battery keeps its last value | | `isCharging` | string | Charging state: `"Charging"` or `"Not charging"` | | `chargerConnected` | string | Charger connection state: `"Plugged in"` or `"Unplugged"` | -| `mileageSinceLastCharge` | number | Distance driven since last full charge (km) | +| `mileageSinceLastCharge` | number | Distance driven since the last charge (km). Where the car does not report it, worked out from the odometer at the end of the last recorded charge, and null until one has been recorded | | `hvSocKwh` | number | HV battery energy (kWh), as the gateway reports it | | `hvTotalCapacityKwh` | number | HV battery total capacity (kWh), as the gateway reports it | | `hvVoltage` | number | HV system voltage (V) | diff --git a/documentation/openapi.json b/documentation/openapi.json index a33483e2..6eb2b855 100644 --- a/documentation/openapi.json +++ b/documentation/openapi.json @@ -1724,7 +1724,7 @@ "tags": [ "Vehicles" ], - "summary": "Get latest telemetry for a vehicle (204 before the car has reported anything). Doors, their windows and a sunroof the car's configuration codes say it lacks are null", + "summary": "Get latest telemetry for a vehicle (204 before the car has reported anything). Doors, their windows and a sunroof the car's configuration codes say it lacks are null. A car that does not report its distance since the last charge gets it worked out from the odometer, once a charge has been recorded", "responses": { "200": { "description": "OK", @@ -9518,6 +9518,10 @@ ], "format": "double" }, + "mileageSinceLastChargeCalculated": { + "type": "boolean", + "description": "True when the distance since the last charge was worked out from the odometer rather than reported by the car. Only the current-state view sets it; it is not stored, merged or exported." + }, "hvVoltage": { "type": [ "null", diff --git a/frontend/src/components/DashboardCardContent.vue b/frontend/src/components/DashboardCardContent.vue index 686a9d9f..6dadb7bc 100644 --- a/frontend/src/components/DashboardCardContent.vue +++ b/frontend/src/components/DashboardCardContent.vue @@ -78,6 +78,15 @@ function measured( return { value: m?.value ?? null, unit: m?.unit ?? units.value.symbol(quantity) } } +// A figure the API worked out rather than the car reported is shown with an approximate sign, so a +// calculated distance since the last charge is not taken for a measured one. +function approximate( + card: Pick, + calculated: boolean, +): Pick { + return calculated && card.value !== null ? { ...card, value: `≈ ${card.value}` } : card +} + // The trip being driven, or when parked the last one, which then opens on the map. const activeTripCard = computed(() => { const journeyKm = status.value?.currentJourneyDistance ?? null @@ -191,12 +200,18 @@ const simpleCards = computed((): SimpleCardConfig[] => { { id: 'efficiencyCharge', label: t('vehicle.efficiency.sinceCharge'), - ...measured('distance', s.mileageSinceLastCharge), + ...approximate( + measured('distance', s.mileageSinceLastCharge), + s.mileageSinceLastChargeCalculated === true, + ), }, { id: 'efficiencySinceCharge', label: t('vehicle.efficiency.efficiencySinceCharge'), - ...measured('energyPerDistance', sinceChargeWhPerKm(s, ctx.vehicleType, ctx.counterScale)), + ...approximate( + measured('energyPerDistance', sinceChargeWhPerKm(s, ctx.vehicleType, ctx.counterScale)), + s.mileageSinceLastChargeCalculated === true, + ), }, // efficiencyRatio - measured fuel consumption on a hybrid, which beats the estimate below { diff --git a/frontend/src/components/__tests__/DashboardCardContent.spec.ts b/frontend/src/components/__tests__/DashboardCardContent.spec.ts index c8238eec..891409dc 100644 --- a/frontend/src/components/__tests__/DashboardCardContent.spec.ts +++ b/frontend/src/components/__tests__/DashboardCardContent.spec.ts @@ -122,6 +122,48 @@ describe('DashboardCardContent', () => { ) }) + // The API works the distance out from the odometer for a car that does not report it, and says + // so: it is shown approximate, where the car's own figure is not. + it('shows the distance since the last charge as the car reports it', () => { + const card = render('efficiencyCharge', status({ mileageSinceLastCharge: 46 }), 'bev') + + expect(card.text).toBe(`${en.vehicle.efficiency.sinceCharge}|46.0|km`) + }) + + it('shows a distance the API worked out as approximate', () => { + const card = render( + 'efficiencyCharge', + status({ mileageSinceLastCharge: 46, mileageSinceLastChargeCalculated: true }), + 'bev', + ) + + expect(card.text).toBe(`${en.vehicle.efficiency.sinceCharge}|≈ 46.0|km`) + }) + + it('shows a calculated distance of nothing as nothing, not as approximately nothing', () => { + const card = render( + 'efficiencyCharge', + status({ mileageSinceLastCharge: null, mileageSinceLastChargeCalculated: true }), + 'bev', + ) + + expect(card.text).toBeNull() + }) + + it('shows the efficiency since the last charge as approximate when its distance was worked out', () => { + const card = render( + 'efficiencySinceCharge', + status({ + powerUsageSinceLastCharge: 11.12, + mileageSinceLastCharge: 46, + mileageSinceLastChargeCalculated: true, + }), + 'bev', + ) + + expect(card.text).toBe(`${en.vehicle.efficiency.efficiencySinceCharge}|≈ 24.2|kWh/100 km`) + }) + it('is also shown since the last charge, off the since-last-charge counters', () => { const card = render( 'efficiencySinceCharge', diff --git a/frontend/src/locales/en.json b/frontend/src/locales/en.json index 63da8496..62a01302 100644 --- a/frontend/src/locales/en.json +++ b/frontend/src/locales/en.json @@ -98,7 +98,7 @@ "lights": "On or off status of high beam, low beam and sidelights.", "efficiencyDistance": "Total distance driven so far today.", "efficiencyEnergy": "What the car has used since midnight. On a BEV or PHEV that is electrical energy through the high-voltage battery, in kilowatt-hours. On an HEV the same counter carries the trip computer's fuel total instead, so it is shown in litres.", - "efficiencyCharge": "Distance driven since the last charge session.", + "efficiencyCharge": "Distance driven since the last charge ended. Where the car reports this itself, that figure is shown. Where it does not, GarageStack works it out: the odometer now, less the odometer where the last charge it recorded ended. It appears once a charge has been recorded for the car, and a charge so short that no reading caught it is missed unless the car says when it ended. A figure worked out this way is shown with ≈ in front of it. Only relevant for PHEV and BEV.", "efficiencySinceCharge": "Energy used per distance since the last charge, in {energyPerDistance}, where {energyBetter}. It comes from the battery's own since-last-charge counters, which start again at every charge. Only relevant for PHEV and BEV.", "efficiencyRatio": "How much the car used for the distance driven today. On a BEV or PHEV that is {energyPerDistance}, where {energyBetter}, and it translates directly to electricity cost per {distance}. On an HEV it is fuel consumption in {fuelConsumption}, where {fuelBetter}: motorway driving gives a better figure than short stop-start trips from cold. When no driving data is available yet, HEV and PHEV fall back to estimated fuel economy ({distancePerPercent}) derived from the car's own range computer, where higher is more efficient.", "speed": "Current vehicle speed as reported by the gateway.", diff --git a/frontend/src/locales/es.json b/frontend/src/locales/es.json index a14e8a3f..ef5805e1 100644 --- a/frontend/src/locales/es.json +++ b/frontend/src/locales/es.json @@ -98,7 +98,7 @@ "lights": "Estado de encendido o apagado de las luces altas, bajas y de posición.", "efficiencyDistance": "Distancia total recorrida hasta el momento hoy.", "efficiencyEnergy": "Lo que ha usado el coche desde medianoche. En un BEV o PHEV que es energía eléctrica a través de la batería de alto voltaje, en kilovatios-hora. En un HEV, el mismo contador lleva el total de combustible de la computadora de viaje, por lo que se muestra en litros.", - "efficiencyCharge": "Distancia recorrida desde la última sesión de carga.", + "efficiencyCharge": "Distancia recorrida desde que terminó la última carga. Si el coche la informa por sí mismo, se muestra esa cifra. Si no, GarageStack la calcula: el cuentakilómetros actual menos el cuentakilómetros en el que terminó la última carga registrada. Aparece cuando se ha registrado una carga del coche, y una carga tan corta que ninguna lectura la captó se pierde, salvo que el coche indique cuándo terminó. Una cifra calculada así se muestra con ≈ delante. Solo relevante para PHEV y BEV.", "efficiencySinceCharge": "Energía consumida por distancia desde la última carga, en {energyPerDistance}; un valor {energyBetter}. Procede de los contadores propios de la batería desde la última carga, que empiezan de nuevo en cada carga. Solo aplica a PHEV y BEV.", "efficiencyRatio": "Consumo de energía o combustible para la distancia recorrida hoy. En BEV y PHEV se muestra como {energyPerDistance}; un valor {energyBetter} y permite calcular el coste eléctrico por {distance}. En HEV se muestra el consumo de combustible como {fuelConsumption}; {fuelBetter}: conducir por autopista suele dar un consumo mejor que los trayectos cortos con paradas y arranques, especialmente con el motor frío. Si aún no hay datos de conducción, los HEV y PHEV muestran una estimación del consumo ({distancePerPercent}) calculada a partir de la autonomía que indica el coche.", "speed": "Velocidad actual del vehículo según lo informado por la puerta de enlace.", diff --git a/frontend/src/locales/nl.json b/frontend/src/locales/nl.json index bb54f4d7..c40beaff 100644 --- a/frontend/src/locales/nl.json +++ b/frontend/src/locales/nl.json @@ -98,7 +98,7 @@ "lights": "Aan/uit-status van groot licht, dimlicht en stadslichten.", "efficiencyDistance": "Totale afstand gereden vandaag.", "efficiencyEnergy": "Wat de auto sinds middernacht heeft verbruikt. Op een BEV of PHEV is dat elektrische energie door de hoogspanningsaccu, in kilowattuur. Op een HEV bevat diezelfde teller het brandstoftotaal van de boordcomputer en wordt die dus in liters getoond.", - "efficiencyCharge": "Afstand gereden sinds de laatste laadsessie.", + "efficiencyCharge": "Afstand gereden sinds het einde van de laatste lading. Meldt de auto dit zelf, dan wordt die waarde getoond. Doet de auto dat niet, dan rekent GarageStack het uit: de kilometerstand nu, min de kilometerstand waar de laatste vastgelegde lading eindigde. Het verschijnt zodra een lading voor de auto is vastgelegd, en een lading die zo kort is dat geen enkele meting haar zag, wordt gemist, tenzij de auto meldt wanneer ze eindigde. Een zo uitgerekende waarde wordt getoond met ≈ ervoor. Alleen relevant voor PHEV en BEV.", "efficiencySinceCharge": "Het verbruik per afstand sinds de laatste lading, in {energyPerDistance}, waarbij {energyBetter}. Het komt uit de eigen tellers van de accu sinds de laatste lading, die bij elke lading opnieuw beginnen. Alleen relevant voor PHEV en BEV.", "efficiencyRatio": "Hoeveel de auto verbruikte voor de afstand van vandaag. Op een BEV of PHEV is dat {energyPerDistance}, waarbij {energyBetter}, en dat vertaalt zich direct naar elektriciteitskosten per {distance}. Op een HEV is het brandstofverbruik in {fuelConsumption}, waarbij {fuelBetter}: snelwegrijden geeft een betere waarde dan korte ritjes vanuit koude start. Als er nog geen rijgegevens beschikbaar zijn, vallen HEV en PHEV terug op een geschat brandstofverbruik ({distancePerPercent}) afgeleid van de rangecalculator van de auto, waarbij hoger zuiniger is.", "speed": "Actuele rijsnelheid zoals gerapporteerd door de gateway.", diff --git a/frontend/src/locales/pt-PT.json b/frontend/src/locales/pt-PT.json index 6c373372..b5eab6e9 100644 --- a/frontend/src/locales/pt-PT.json +++ b/frontend/src/locales/pt-PT.json @@ -98,7 +98,7 @@ "lights": "Estado ligado ou desligado dos máximos, dos médios e dos mínimos.", "efficiencyDistance": "Distância total percorrida até agora hoje.", "efficiencyEnergy": "O que o carro consumiu desde a meia-noite. Num BEV ou PHEV, é energia elétrica da bateria de alta tensão, em quilowatts-hora. Num HEV, o mesmo contador traz o total de combustível do computador de bordo, por isso aparece em litros.", - "efficiencyCharge": "Distância percorrida desde o último carregamento.", + "efficiencyCharge": "Distância percorrida desde o fim do último carregamento. Se o carro comunica este valor, é esse que se mostra. Se não, o GarageStack calcula-o: o conta-quilómetros atual menos o conta-quilómetros em que terminou o último carregamento registado. Aparece quando um carregamento do carro foi registado, e um carregamento tão curto que nenhuma leitura o apanhou não é contado, a menos que o carro indique quando terminou. Um valor calculado assim aparece com ≈ à frente. Só relevante para PHEV e BEV.", "efficiencySinceCharge": "Energia consumida por distância desde o último carregamento, em {energyPerDistance}, onde {energyBetter}. Vem dos próprios contadores da bateria desde o último carregamento, que recomeçam a cada carga. Relevante apenas para PHEV e BEV.", "efficiencyRatio": "Quanto o carro consumiu na distância percorrida hoje. Num BEV ou PHEV, é {energyPerDistance}, onde {energyBetter}, e isso traduz-se diretamente no custo de eletricidade por {distance}. Num HEV, é o consumo de combustível em {fuelConsumption}, onde {fuelBetter}: conduzir em autoestrada dá um resultado melhor do que trajetos curtos em pára-arranca com o motor frio. Quando ainda não há dados de condução, HEV e PHEV usam a economia de combustível estimada ({distancePerPercent}), calculada pelo computador de autonomia do próprio carro, onde quanto maior, mais eficiente.", "speed": "Velocidade atual do veículo, conforme comunicada pelo gateway.", diff --git a/frontend/src/locales/pt.json b/frontend/src/locales/pt.json index 531e82dd..33e8318b 100644 --- a/frontend/src/locales/pt.json +++ b/frontend/src/locales/pt.json @@ -98,7 +98,7 @@ "lights": "Estado ligado ou desligado do farol alto, do farol baixo e das lanternas.", "efficiencyDistance": "Distância total percorrida até agora hoje.", "efficiencyEnergy": "O que o carro consumiu desde a meia-noite. Em um BEV ou PHEV, é energia elétrica da bateria de alta tensão, em quilowatts-hora. Em um HEV, o mesmo contador traz o total de combustível do computador de bordo, por isso aparece em litros.", - "efficiencyCharge": "Distância percorrida desde o último carregamento.", + "efficiencyCharge": "Distância percorrida desde o fim do último carregamento. Se o carro informa esse valor por conta própria, ele é mostrado. Se não, o GarageStack calcula: o hodômetro de agora menos o hodômetro em que terminou o último carregamento registrado. Aparece quando um carregamento do carro foi registrado, e um carregamento tão curto que nenhuma leitura o captou não é contado, a menos que o carro informe quando ele terminou. Um valor calculado assim aparece com ≈ na frente. Só relevante para PHEV e BEV.", "efficiencySinceCharge": "Energia consumida por distância desde o último carregamento, em {energyPerDistance}, onde {energyBetter}. Vem dos próprios contadores da bateria desde o último carregamento, que recomeçam a cada carga. Relevante apenas para PHEV e BEV.", "efficiencyRatio": "Quanto o carro consumiu na distância percorrida hoje. Em um BEV ou PHEV, é {energyPerDistance}, onde {energyBetter}, e isso se traduz diretamente no custo de eletricidade por {distance}. Em um HEV, é o consumo de combustível em {fuelConsumption}, onde {fuelBetter}: rodar na rodovia dá um resultado melhor do que trajetos curtos de anda e para com o motor frio. Quando ainda não há dados de condução, HEV e PHEV usam a economia de combustível estimada ({distancePerPercent}), calculada pelo computador de autonomia do próprio carro, onde quanto maior, mais eficiente.", "speed": "Velocidade atual do veículo, conforme informada pelo gateway.", diff --git a/frontend/src/services/vehicleApi.ts b/frontend/src/services/vehicleApi.ts index e5aa8827..58bc3696 100644 --- a/frontend/src/services/vehicleApi.ts +++ b/frontend/src/services/vehicleApi.ts @@ -78,6 +78,8 @@ export interface TelemetrySnapshot { mileageOfTheDay: number | null powerUsageOfDay: number | null mileageSinceLastCharge: number | null + /** True when the car does not report that distance and the API worked it out from the odometer. */ + mileageSinceLastChargeCalculated?: boolean hvVoltage: number | null hvCurrent: number | null hvPower: number | null diff --git a/src/GarageStack.Api/Endpoints/VehicleEndpoints.cs b/src/GarageStack.Api/Endpoints/VehicleEndpoints.cs index 67bb052a..3b04eb46 100644 --- a/src/GarageStack.Api/Endpoints/VehicleEndpoints.cs +++ b/src/GarageStack.Api/Endpoints/VehicleEndpoints.cs @@ -91,7 +91,7 @@ public static IEndpointRouteBuilder MapVehicleEndpoints(this IEndpointRouteBuild }) .Produces() .Produces(StatusCodes.Status204NoContent) - .WithSummary("Get latest telemetry for a vehicle (204 before the car has reported anything). Doors, their windows and a sunroof the car's configuration codes say it lacks are null"); + .WithSummary("Get latest telemetry for a vehicle (204 before the car has reported anything). Doors, their windows and a sunroof the car's configuration codes say it lacks are null. A car that does not report its distance since the last charge gets it worked out from the odometer, once a charge has been recorded"); // A plain hybrid gets none: see ChargeSessionHistory.Applies. vehicleGroup.MapGet("/charge-sessions", async ( diff --git a/src/GarageStack.Api/Services/ZipExport.cs b/src/GarageStack.Api/Services/ZipExport.cs index 09d46f42..fc1b1df7 100644 --- a/src/GarageStack.Api/Services/ZipExport.cs +++ b/src/GarageStack.Api/Services/ZipExport.cs @@ -1,3 +1,4 @@ +using System.ComponentModel.DataAnnotations.Schema; using System.Globalization; using System.IO.Compression; using System.Reflection; @@ -25,7 +26,10 @@ internal static class ZipExport /// Every column of a telemetry row, in declaration order, without the car it belongs to. public static readonly IReadOnlyList TelemetryColumns = - [.. typeof(TelemetrySnapshot).GetProperties().Where(p => p.Name != nameof(TelemetrySnapshot.Vehicle) && IsScalar(p.PropertyType))]; + [.. typeof(TelemetrySnapshot).GetProperties() + .Where(p => p.Name != nameof(TelemetrySnapshot.Vehicle) + && p.GetCustomAttribute() is null + && IsScalar(p.PropertyType))]; /// The version this build was made as, with its commit. public static string? AppVersion => diff --git a/src/GarageStack.Core/Helpers/DistanceSinceCharge.cs b/src/GarageStack.Core/Helpers/DistanceSinceCharge.cs new file mode 100644 index 00000000..ffeef834 --- /dev/null +++ b/src/GarageStack.Core/Helpers/DistanceSinceCharge.cs @@ -0,0 +1,62 @@ +namespace GarageStack.Core.Helpers; + +/// +/// The distance driven since the last charge ended, worked out from the odometer for a car that does +/// not report its own distance-since-last-charge counter. Some cars send that counter (it starts +/// again from zero when a charge ends) and some never do; the odometer a charge ended at is in the +/// stored readings either way, and the distance is the odometer now less that one. +/// +public static class DistanceSinceCharge +{ + /// How far back the last charge is looked for: more than a year, so a car that is rarely plugged in still has one. + public static readonly TimeSpan Lookback = TimeSpan.FromDays(400); + + /// + /// How long the odometer at the last charge is reused before it is looked up again. A charge + /// ends rarely and the lookup reads far back, so a minute's delay in noticing one costs nothing. + /// + public static readonly TimeSpan CacheFor = TimeSpan.FromMinutes(1); + + /// How many of the newest readings that show the car charging are compared, to find the latest charge. + public const int ChargingReadingsCompared = 20; + + /// + /// How far ahead of now a time may be and still be believed. A car's own clock is not ours, and + /// an end time from the future would otherwise put the end of the last charge past every reading. + /// + private static readonly TimeSpan ClockSlack = TimeSpan.FromMinutes(5); + + /// + /// When a reading that shows the car charging was true of the car. A row's own time, unless the + /// poll it carries is older than the row: a gateway that starts again sends its retained topics + /// again, in a row of their own, which says "charging" about a charge that is long over (see + /// ). + /// + public static DateTime ChargingReadingAt(DateTime recordedAt, DateTime? chargeStateAt) => + chargeStateAt is { } stamp && stamp < recordedAt ? stamp : recordedAt; + + /// + /// When the last charge ended, as far as the readings show: the later of the end time the car + /// reported and the last time it was seen charging (a charge still going counts as ending now, + /// so nothing has been driven since it). Null when neither is known. + /// + public static DateTime? LastChargeAt(DateTime now, DateTime? reportedEndAt, DateTime? lastSeenChargingAt) + { + var limit = now + ClockSlack; + var reported = reportedEndAt is { } end && end <= limit ? end : (DateTime?)null; + var seen = lastSeenChargingAt is { } at && at <= limit ? at : (DateTime?)null; + return reported is { } r && seen is { } s ? (r > s ? r : s) : reported ?? seen; + } + + /// + /// The kilometres between the odometer at the end of the last charge and the odometer now, to a + /// tenth. Null when either is unknown, or when the odometer went backwards: a reading that says + /// so is wrong somewhere, and nothing is better than a negative distance. + /// + public static double? Between(double? odometerKm, double? odometerAtChargeKm) + { + if (odometerKm is not { } now || odometerAtChargeKm is not { } then) return null; + if (!double.IsFinite(now) || !double.IsFinite(then) || now < then) return null; + return Math.Round(now - then, 1); + } +} diff --git a/src/GarageStack.Core/Helpers/TelemetryFields.cs b/src/GarageStack.Core/Helpers/TelemetryFields.cs index 2f94e625..ea0a57a3 100644 --- a/src/GarageStack.Core/Helpers/TelemetryFields.cs +++ b/src/GarageStack.Core/Helpers/TelemetryFields.cs @@ -17,6 +17,8 @@ public static class TelemetryFields [ nameof(TelemetrySnapshot.Id), nameof(TelemetrySnapshot.VehicleId), nameof(TelemetrySnapshot.Vehicle), nameof(TelemetrySnapshot.RecordedAt), + // Worked out when the current state is read, never a reading of its own. + nameof(TelemetrySnapshot.MileageSinceLastChargeCalculated), ]; /// Every property that carries telemetry, in declaration order. diff --git a/src/GarageStack.Core/Models/TelemetrySnapshot.cs b/src/GarageStack.Core/Models/TelemetrySnapshot.cs index 4f456756..1fd4b62c 100644 --- a/src/GarageStack.Core/Models/TelemetrySnapshot.cs +++ b/src/GarageStack.Core/Models/TelemetrySnapshot.cs @@ -1,3 +1,5 @@ +using System.ComponentModel.DataAnnotations.Schema; + namespace GarageStack.Core.Models; public class TelemetrySnapshot @@ -56,6 +58,12 @@ public class TelemetrySnapshot public double? PowerUsageOfDay { get; set; } public double? MileageSinceLastCharge { get; set; } + /// + /// True when the distance since the last charge was worked out from the odometer rather than reported by the car. Only the current-state view sets it; it is not stored, merged or exported. + /// + [NotMapped] + public bool MileageSinceLastChargeCalculated { get; set; } + // HV drivetrain (hybrid/EV high-voltage system) public double? HvVoltage { get; set; } public double? HvCurrent { get; set; } diff --git a/src/GarageStack.Data/Repositories/TelemetryRepository.cs b/src/GarageStack.Data/Repositories/TelemetryRepository.cs index f90a7dcf..9376f522 100644 --- a/src/GarageStack.Data/Repositories/TelemetryRepository.cs +++ b/src/GarageStack.Data/Repositories/TelemetryRepository.cs @@ -173,6 +173,15 @@ private async Task NotifyUpdatedAsync(int vehicleId, CancellationToken ct) if (merged.MileageOfTheDay is > 0 && merged.OdometerKm is { } odometer) merged.MileageOfTheDay = await CheckDayDistanceAsync(vehicleId, merged.MileageOfTheDay.Value, odometer, todayStart, ct); + // Not every car reports the distance since its last charge. For one that does not, it is the + // odometer now less the odometer where the last charge ended, which the readings hold. + if (merged.MileageSinceLastCharge is null && merged.OdometerKm is { } odometerNow) + { + merged.MileageSinceLastCharge = DistanceSinceCharge.Between( + odometerNow, await GetOdometerAtLastChargeAsync(vehicleId, ct)); + merged.MileageSinceLastChargeCalculated = merged.MileageSinceLastCharge is not null; + } + // If the MG API still reports a journey distance but the engine is off, // the trip has ended and the firmware just hasn't cleared the field yet. // The 5-minute guard on speed handles the red-light case (speed=0 but @@ -236,6 +245,60 @@ private async Task NotifyUpdatedAsync(int vehicleId, CancellationToken ct) return merged; } + private static string OdometerAtChargeCacheKey(int vehicleId) => $"odometer-at-last-charge/{vehicleId}"; + + // Kept apart from the odometer itself so that "no charge found" is remembered too: a car that + // was never plugged in would otherwise be searched for again on every read. + private sealed record OdometerAtCharge(double? Km); + + /// + /// The odometer where the car's last charge ended, or null when no charge is in the readings + /// (a car's first charge after GarageStack began recording has not happened yet). Remembered for + /// . + /// + private async Task GetOdometerAtLastChargeAsync(int vehicleId, CancellationToken ct) + { + var key = OdometerAtChargeCacheKey(vehicleId); + if (cache is not null && cache.TryGetValue(key, out OdometerAtCharge? known) && known is not null) + return known.Km; + + var km = await ReadOdometerAtLastChargeAsync(vehicleId, ct); + cache?.Set(key, new OdometerAtCharge(km), DistanceSinceCharge.CacheFor); + return km; + } + + private async Task ReadOdometerAtLastChargeAsync(int vehicleId, CancellationToken ct) + { + var now = UtcNow; + var since = now - DistanceSinceCharge.Lookback; + + // The newest readings that show the car charging. Compared by when each was true of the car + // rather than by when its row landed, as a gateway that starts again sends an old charge + // state in a new row. + var charging = await db.TelemetrySnapshots + .AsNoTracking() + .Where(s => s.VehicleId == vehicleId && s.RecordedAt >= since && s.IsCharging == true) + .OrderByDescending(s => s.RecordedAt) + .Take(DistanceSinceCharge.ChargingReadingsCompared) + .Select(s => new { s.RecordedAt, s.LastChargeStateAt }) + .ToListAsync(ct); + DateTime? lastSeenCharging = charging.Count == 0 + ? null + : charging.Max(r => DistanceSinceCharge.ChargingReadingAt(r.RecordedAt, r.LastChargeStateAt)); + + // A charge too short for a poll to catch still leaves the end time the car reports. + var reportedEnd = await db.TelemetrySnapshots + .AsNoTracking() + .Where(s => s.VehicleId == vehicleId && s.RecordedAt >= since && s.ChargingLastEndAt != null) + .OrderByDescending(s => s.RecordedAt) + .Select(s => s.ChargingLastEndAt) + .FirstOrDefaultAsync(ct); + + return DistanceSinceCharge.LastChargeAt(now, reportedEnd, lastSeenCharging) is { } endedAt + ? await GetOdometerAtAsync(vehicleId, endedAt, ct) + : null; + } + // A finished day's statistics cannot change: every row is stamped when it arrives, so no row // lands on a day that has ended. The margin covers the merge window, which folds messages // arriving just after midnight into a row stamped before it; compaction folds old rows but diff --git a/src/GarageStack.Tests/DistanceSinceChargeTests.cs b/src/GarageStack.Tests/DistanceSinceChargeTests.cs new file mode 100644 index 00000000..c8b03998 --- /dev/null +++ b/src/GarageStack.Tests/DistanceSinceChargeTests.cs @@ -0,0 +1,282 @@ +using GarageStack.Api.Services; +using GarageStack.Core.Helpers; +using GarageStack.Core.Models; +using GarageStack.Data; +using GarageStack.Data.Repositories; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Caching.Memory; + +namespace GarageStack.Tests; + +public class DistanceSinceChargeTests +{ + private static readonly DateTimeOffset Now = new(2026, 11, 8, 13, 0, 0, TimeSpan.Zero); + private static readonly DateTime T0 = Now.UtcDateTime; + + [Theory] + [InlineData(1042.0, 1000.0, 42.0)] + [InlineData(1000.0, 1000.0, 0.0)] // charging, or just done: nothing driven since + [InlineData(1000.34, 1000.0, 0.3)] // to a tenth + [InlineData(999.0, 1000.0, null)] // an odometer that went backwards is wrong somewhere + [InlineData(null, 1000.0, null)] + [InlineData(1000.0, null, null)] + [InlineData(double.NaN, 1000.0, null)] + public void Between_IsTheOdometerGainToATenth(double? now, double? atCharge, double? expected) => + Assert.Equal(expected, DistanceSinceCharge.Between(now, atCharge)); + + [Fact] + public void ChargingReadingAt_IsTheRowsTime_WhenThePollIsTheRowsOwn() => + Assert.Equal(T0, DistanceSinceCharge.ChargingReadingAt(T0, T0)); + + [Fact] + public void ChargingReadingAt_IsThePollsOwnStamp_ForAnOldStateInANewRow() => + Assert.Equal(T0.AddDays(-3), DistanceSinceCharge.ChargingReadingAt(T0, T0.AddDays(-3))); + + [Fact] + public void ChargingReadingAt_WithoutAStamp_IsTheRowsTime() => + Assert.Equal(T0, DistanceSinceCharge.ChargingReadingAt(T0, null)); + + [Fact] + public void ChargingReadingAt_IgnoresAStampLaterThanTheRow() => + Assert.Equal(T0, DistanceSinceCharge.ChargingReadingAt(T0, T0.AddHours(1))); + + [Fact] + public void LastChargeAt_IsTheLaterOfTheReportedEndAndTheLastSeenCharging() + { + Assert.Equal(T0.AddHours(-1), DistanceSinceCharge.LastChargeAt(T0, T0.AddHours(-1), T0.AddHours(-2))); + Assert.Equal(T0.AddHours(-1), DistanceSinceCharge.LastChargeAt(T0, T0.AddHours(-2), T0.AddHours(-1))); + } + + [Fact] + public void LastChargeAt_WithOnlyOneOfThem_IsThatOne() + { + Assert.Equal(T0.AddHours(-1), DistanceSinceCharge.LastChargeAt(T0, T0.AddHours(-1), null)); + Assert.Equal(T0.AddHours(-1), DistanceSinceCharge.LastChargeAt(T0, null, T0.AddHours(-1))); + Assert.Null(DistanceSinceCharge.LastChargeAt(T0, null, null)); + } + + [Fact] + public void LastChargeAt_DoesNotBelieveATimeFromTheFuture() + { + // A car's clock that runs ahead would put the end of the last charge past every reading. + Assert.Equal(T0.AddHours(-1), DistanceSinceCharge.LastChargeAt(T0, T0.AddDays(2), T0.AddHours(-1))); + Assert.Null(DistanceSinceCharge.LastChargeAt(T0, T0.AddDays(2), null)); + } + + [Fact] + public void LastChargeAt_AllowsAFewMinutesOfClockDifference() => + Assert.Equal(T0.AddMinutes(2), DistanceSinceCharge.LastChargeAt(T0, null, T0.AddMinutes(2))); + + [Fact] + public void TheCalculatedFlag_IsNotAReadingToStoreMergeOrExport() + { + const string flag = nameof(TelemetrySnapshot.MileageSinceLastChargeCalculated); + + Assert.DoesNotContain(TelemetryFields.Mergeable, p => p.Name == flag); + Assert.DoesNotContain(ZipExport.TelemetryColumns, p => p.Name == flag); + } + + // ── The repository ─────────────────────────────────────────────────────── + + private static async Task<(AppDbContext Db, TelemetryRepository Repo, int VehicleId)> SetupAsync( + IMemoryCache? cache = null, params TelemetrySnapshot[] rows) + { + var db = new AppDbContext(new DbContextOptionsBuilder() + .UseInMemoryDatabase(Guid.NewGuid().ToString()) + .Options); + var vehicle = new Vehicle { Vin = "FAKEVN00000000001" }; + db.Vehicles.Add(vehicle); + await db.SaveChangesAsync(); + foreach (var row in rows) row.VehicleId = vehicle.Id; + db.TelemetrySnapshots.AddRange(rows); + await db.SaveChangesAsync(); + return (db, new TelemetryRepository(db, cache: cache, time: new FixedTimeProvider(Now)), vehicle.Id); + } + + private static TelemetrySnapshot Odometer(DateTime at, double km) => new() { RecordedAt = at, OdometerKm = km }; + + private static TelemetrySnapshot Charging(DateTime at, bool charging, DateTime? stateAt = null) => + new() { RecordedAt = at, IsCharging = charging, LastChargeStateAt = stateAt }; + + [Fact] + public async Task GetMergedLatest_CarThatReportsTheCounter_KeepsItsOwnValue() + { + var ct = TestContext.Current.CancellationToken; + var (db, repo, vehicleId) = await SetupAsync(null, + Odometer(T0.AddDays(-2), 1000), + Charging(T0.AddDays(-2), true), + new TelemetrySnapshot { RecordedAt = T0.AddMinutes(-5), OdometerKm = 1080, MileageSinceLastCharge = 77 }); + await using var _ = db; + + var result = await repo.GetMergedLatestAsync(vehicleId, ct); + + Assert.Equal(77, result!.MileageSinceLastCharge); + Assert.False(result.MileageSinceLastChargeCalculated); + } + + [Fact] + public async Task GetMergedLatest_CarWithoutTheCounter_DrivenSinceItsLastSeenCharge_IsTheOdometerGain() + { + var ct = TestContext.Current.CancellationToken; + var (db, repo, vehicleId) = await SetupAsync(null, + Odometer(T0.AddDays(-3), 990), + Odometer(T0.AddDays(-2).AddHours(-1), 1000), + Charging(T0.AddDays(-2).AddHours(-1), true), + Charging(T0.AddDays(-2), true), + Charging(T0.AddDays(-2).AddMinutes(1), false), + Odometer(T0.AddHours(-5), 1030), + Odometer(T0.AddMinutes(-5), 1042)); + await using var _ = db; + + var result = await repo.GetMergedLatestAsync(vehicleId, ct); + + Assert.Equal(42, result!.MileageSinceLastCharge); + Assert.True(result.MileageSinceLastChargeCalculated); + } + + [Fact] + public async Task GetMergedLatest_WhileCharging_IsZero() + { + var ct = TestContext.Current.CancellationToken; + var (db, repo, vehicleId) = await SetupAsync(null, + Odometer(T0.AddDays(-2), 1000), + Charging(T0.AddDays(-2), true), + Charging(T0.AddDays(-2).AddHours(3), false), + Odometer(T0.AddHours(-3), 1042), + Charging(T0.AddMinutes(-20), true), + Charging(T0.AddMinutes(-5), true)); + await using var _ = db; + + var result = await repo.GetMergedLatestAsync(vehicleId, ct); + + Assert.Equal(0, result!.MileageSinceLastCharge); + } + + [Fact] + public async Task GetMergedLatest_ChargeTooShortToBeSeen_UsesTheEndTimeTheCarReported() + { + // No reading ever showed the car charging, but it says when its last charge ended. + var ct = TestContext.Current.CancellationToken; + var (db, repo, vehicleId) = await SetupAsync(null, + Odometer(T0.AddDays(-1), 2927), + new TelemetrySnapshot { RecordedAt = T0.AddDays(-1).AddMinutes(10), IsCharging = false, ChargingLastEndAt = T0.AddDays(-1).AddMinutes(3) }, + Odometer(T0.AddMinutes(-5), 2945)); + await using var _ = db; + + var result = await repo.GetMergedLatestAsync(vehicleId, ct); + + Assert.Equal(18, result!.MileageSinceLastCharge); + } + + [Fact] + public async Task GetMergedLatest_WithNoChargeInTheReadings_HasNoDistance() + { + // A car's first charge after GarageStack began recording has not happened: nothing to count from. + var ct = TestContext.Current.CancellationToken; + var (db, repo, vehicleId) = await SetupAsync(null, + Odometer(T0.AddDays(-1), 2834), + Charging(T0.AddDays(-1), false), + Odometer(T0.AddMinutes(-5), 2858)); + await using var _ = db; + + var result = await repo.GetMergedLatestAsync(vehicleId, ct); + + Assert.Null(result!.MileageSinceLastCharge); + Assert.False(result.MileageSinceLastChargeCalculated); + } + + [Fact] + public async Task GetMergedLatest_AnOldChargeStateInANewRow_DoesNotMoveTheEndOfTheLastCharge() + { + // The gateway sent its retained topics again when it started: a row from now that says + // "charging", with the stamp of a poll from days ago. The charge is the old one. + var ct = TestContext.Current.CancellationToken; + var (db, repo, vehicleId) = await SetupAsync(null, + Odometer(T0.AddDays(-4), 1000), + Charging(T0.AddDays(-4), true), + Odometer(T0.AddHours(-2), 1060), + Charging(T0.AddHours(-1), true, stateAt: T0.AddDays(-4)), + Odometer(T0.AddMinutes(-5), 1075)); + await using var _ = db; + + var result = await repo.GetMergedLatestAsync(vehicleId, ct); + + Assert.Equal(75, result!.MileageSinceLastCharge); + } + + [Fact] + public async Task GetMergedLatest_ChargeFurtherBackThanTheLookback_IsNotUsed() + { + var ct = TestContext.Current.CancellationToken; + var (db, repo, vehicleId) = await SetupAsync(null, + Odometer(T0 - DistanceSinceCharge.Lookback.Add(TimeSpan.FromDays(2)), 1000), + Charging(T0 - DistanceSinceCharge.Lookback.Add(TimeSpan.FromDays(2)), true), + Odometer(T0.AddMinutes(-5), 9000)); + await using var _ = db; + + var result = await repo.GetMergedLatestAsync(vehicleId, ct); + + Assert.Null(result!.MileageSinceLastCharge); + } + + [Fact] + public async Task GetMergedLatest_WithoutAnOdometer_HasNoDistance() + { + var ct = TestContext.Current.CancellationToken; + var (db, repo, vehicleId) = await SetupAsync(null, + Charging(T0.AddDays(-2), true), + new TelemetrySnapshot { RecordedAt = T0.AddMinutes(-5), EvSocPercent = 60 }); + await using var _ = db; + + var result = await repo.GetMergedLatestAsync(vehicleId, ct); + + Assert.Null(result!.MileageSinceLastCharge); + } + + [Fact] + public async Task GetMergedLatest_RemembersTheOdometerAtTheLastCharge_ForAMinute() + { + var ct = TestContext.Current.CancellationToken; + using var cache = new MemoryCache(new MemoryCacheOptions()); + var (db, repo, vehicleId) = await SetupAsync(cache, + Odometer(T0.AddDays(-2), 1000), + Charging(T0.AddDays(-2), true), + Odometer(T0.AddMinutes(-5), 1042)); + await using var _ = db; + + Assert.Equal(42, (await repo.GetMergedLatestAsync(vehicleId, ct))!.MileageSinceLastCharge); + + // A charge that is seen after the first read does not change the odometer remembered for the + // last one, however the merged snapshot is built again, until the minute is up. + db.TelemetrySnapshots.AddRange( + new TelemetrySnapshot { VehicleId = vehicleId, RecordedAt = T0.AddMinutes(-2), IsCharging = true, OdometerKm = 1042 }); + await db.SaveChangesAsync(ct); + cache.Remove($"telemetry-latest/{vehicleId}"); + + Assert.Equal(42, (await repo.GetMergedLatestAsync(vehicleId, ct))!.MileageSinceLastCharge); + } + + [Fact] + public async Task GetMergedLatest_RemembersThatThereWasNoCharge_TooSoThatItIsNotSearchedForOnEveryRead() + { + var ct = TestContext.Current.CancellationToken; + using var cache = new MemoryCache(new MemoryCacheOptions()); + var (db, repo, vehicleId) = await SetupAsync(cache, Odometer(T0.AddMinutes(-5), 2858)); + await using var _ = db; + + Assert.Null((await repo.GetMergedLatestAsync(vehicleId, ct))!.MileageSinceLastCharge); + + db.TelemetrySnapshots.Add(new TelemetrySnapshot + { + VehicleId = vehicleId, + RecordedAt = T0.AddMinutes(-1), + IsCharging = true, + OdometerKm = 2858, + }); + await db.SaveChangesAsync(ct); + cache.Remove($"telemetry-latest/{vehicleId}"); + + // Still the cached "no charge": the search is not run again within the minute. + Assert.Null((await repo.GetMergedLatestAsync(vehicleId, ct))!.MileageSinceLastCharge); + } +} diff --git a/src/GarageStack.Tests/Postgres/TelemetryRepositoryPostgresTests.cs b/src/GarageStack.Tests/Postgres/TelemetryRepositoryPostgresTests.cs index 3433f283..0a23900a 100644 --- a/src/GarageStack.Tests/Postgres/TelemetryRepositoryPostgresTests.cs +++ b/src/GarageStack.Tests/Postgres/TelemetryRepositoryPostgresTests.cs @@ -172,4 +172,25 @@ public async Task EveryWrite_TellsTheApi_OverNotify() var notification = await heard.Task.WaitAsync(TimeSpan.FromSeconds(5), ct); Assert.Equal((PgChannels.TelemetryUpdated, vehicleId.ToString()), (notification.Channel, notification.Payload)); } + + [Fact] + public async Task TheDistanceSinceTheLastCharge_ForACarThatDoesNotReportIt_TranslatesToSql() + { + var ct = TestContext.Current.CancellationToken; + await using var database = await PostgresDatabase.CreateAsync(ct); + await using var db = database.CreateContext(); + var vehicleId = await AddVehicleAsync(db, ct); + // The charge nine days ago is the one before the last, which the newest charging reading outranks. + db.TelemetrySnapshots.AddRange( + new TelemetrySnapshot { VehicleId = vehicleId, RecordedAt = Now.AddDays(-3), OdometerKm = 2900 }, + new TelemetrySnapshot { VehicleId = vehicleId, RecordedAt = Now.AddDays(-2), IsCharging = true }, + new TelemetrySnapshot { VehicleId = vehicleId, RecordedAt = Now.AddDays(-9), IsCharging = true }, + new TelemetrySnapshot { VehicleId = vehicleId, RecordedAt = Now.AddDays(-2).AddHours(4), IsCharging = false }, + new TelemetrySnapshot { VehicleId = vehicleId, RecordedAt = Now.AddHours(-1), OdometerKm = 2951 }); + await db.SaveChangesAsync(ct); + + var merged = await new TelemetryRepository(db).GetMergedLatestAsync(vehicleId, ct); + + Assert.Equal(51, merged!.MileageSinceLastCharge); + } } From 97ce08754c3ceefb14a1dee83a911f4878f2c114 Mon Sep 17 00:00:00 2001 From: arthur-lzrs <55158951+arthur-lzrs@users.noreply.github.com> Date: Fri, 27 Nov 2026 16:00:42 -0300 Subject: [PATCH 2/4] feat: count a charge from the battery level going up when no poll caught it The gateway reads a parked car rarely (every two minutes for a few minutes after it stops, then once a day), so a charge can start and end between two reads with no reading saying "charging", and the distance since the last charge then counted on from an older one. A stretch of readings at one odometer value is a car that did not move. When its state of charge climbs by two points or more above its lowest in that stretch, the car was charged, at that odometer. A new odometer value starts a new stretch, so driving, which regenerates and wobbles the figure, never counts. Two points is well clear of what a parked car does in the stored readings (tenths of a point at most, from both cars here) and still finds a top-up worth the name. The latest of this, a reading that showed the car charging and the end time the car reports is the last charge. The scan reads only the readings after the last charge otherwise known, or the last 60 days when none is. Limits: a charge with the car driven before the next read (the odometer changed in between) is not seen this way, and a battery that corrects itself upward at rest by two points would count as a charge, which shows as a shorter distance and is shown with the approximate sign anyway. Co-Authored-By: Claude Sonnet 5.5 --- README.md | 2 +- documentation/WIDGET.md | 2 +- frontend/src/locales/en.json | 2 +- frontend/src/locales/es.json | 2 +- frontend/src/locales/nl.json | 2 +- frontend/src/locales/pt-PT.json | 2 +- frontend/src/locales/pt.json | 2 +- .../Helpers/DistanceSinceCharge.cs | 60 +++++++ .../Repositories/TelemetryRepository.cs | 23 ++- .../DistanceSinceChargeTests.cs | 159 ++++++++++++++++++ .../TelemetryRepositoryPostgresTests.cs | 19 +++ 11 files changed, 265 insertions(+), 10 deletions(-) diff --git a/README.md b/README.md index e9e661b4..1b234de5 100644 --- a/README.md +++ b/README.md @@ -117,7 +117,7 @@ Cards are shown or hidden automatically based on vehicle type (HEV / PHEV / BEV) | Lights | Main beam, low beam, sidelights | All | | Daily Distance | Distance driven today | All | | Daily Energy | Energy used today (kWh), or fuel burned today (L) on an HEV. On a PHEV the kWh show once `HV_BATTERY_CAPACITY_KWH` is set | All | -| Since Charge | Distance since last charge session. A car that does not report this itself gets it worked out from the odometer at the end of the last recorded charge | PHEV, BEV | +| Since Charge | Distance since last charge session. A car that does not report this itself gets it worked out from the odometer at the end of its last charge: one a reading caught, one the car says when it ended, or a climb of 2 points or more in the battery level while it stood still. Shown with ≈ | PHEV, BEV | | Efficiency | Energy consumption in the chosen unit, or fuel consumption (L/100 km) on an HEV | All | | Speed | Current vehicle speed | All (off by default) | | Top Speed | Highest speed recorded in the most recent completed trip | All | diff --git a/documentation/WIDGET.md b/documentation/WIDGET.md index 02512a37..83a8e944 100644 --- a/documentation/WIDGET.md +++ b/documentation/WIDGET.md @@ -56,7 +56,7 @@ The endpoint returns a flat JSON object. Numeric fields are `null` when the vehi | `electricRangeKm` | number | Distance the car estimates it can drive on the battery alone (km), on a BEV or PHEV. Never reported as 0, so an empty battery keeps its last value | | `isCharging` | string | Charging state: `"Charging"` or `"Not charging"` | | `chargerConnected` | string | Charger connection state: `"Plugged in"` or `"Unplugged"` | -| `mileageSinceLastCharge` | number | Distance driven since the last charge (km). Where the car does not report it, worked out from the odometer at the end of the last recorded charge, and null until one has been recorded | +| `mileageSinceLastCharge` | number | Distance driven since the last charge (km). Where the car does not report it, worked out from the odometer at the end of the last charge GarageStack knows of (see the dashboard card), and null until there is one | | `hvSocKwh` | number | HV battery energy (kWh), as the gateway reports it | | `hvTotalCapacityKwh` | number | HV battery total capacity (kWh), as the gateway reports it | | `hvVoltage` | number | HV system voltage (V) | diff --git a/frontend/src/locales/en.json b/frontend/src/locales/en.json index 62a01302..c6b38b47 100644 --- a/frontend/src/locales/en.json +++ b/frontend/src/locales/en.json @@ -98,7 +98,7 @@ "lights": "On or off status of high beam, low beam and sidelights.", "efficiencyDistance": "Total distance driven so far today.", "efficiencyEnergy": "What the car has used since midnight. On a BEV or PHEV that is electrical energy through the high-voltage battery, in kilowatt-hours. On an HEV the same counter carries the trip computer's fuel total instead, so it is shown in litres.", - "efficiencyCharge": "Distance driven since the last charge ended. Where the car reports this itself, that figure is shown. Where it does not, GarageStack works it out: the odometer now, less the odometer where the last charge it recorded ended. It appears once a charge has been recorded for the car, and a charge so short that no reading caught it is missed unless the car says when it ended. A figure worked out this way is shown with ≈ in front of it. Only relevant for PHEV and BEV.", + "efficiencyCharge": "Distance driven since the last charge ended. Where the car reports this itself, that figure is shown. Where it does not, GarageStack works it out: the odometer now, less the odometer where the last charge ended. That charge is one a reading caught, one the car says when it ended, or, for a charge between two readings, a climb of 2 points or more in the battery level while the car stood still. It appears once such a charge is known, and a figure worked out this way is shown with ≈ in front of it. Only relevant for PHEV and BEV.", "efficiencySinceCharge": "Energy used per distance since the last charge, in {energyPerDistance}, where {energyBetter}. It comes from the battery's own since-last-charge counters, which start again at every charge. Only relevant for PHEV and BEV.", "efficiencyRatio": "How much the car used for the distance driven today. On a BEV or PHEV that is {energyPerDistance}, where {energyBetter}, and it translates directly to electricity cost per {distance}. On an HEV it is fuel consumption in {fuelConsumption}, where {fuelBetter}: motorway driving gives a better figure than short stop-start trips from cold. When no driving data is available yet, HEV and PHEV fall back to estimated fuel economy ({distancePerPercent}) derived from the car's own range computer, where higher is more efficient.", "speed": "Current vehicle speed as reported by the gateway.", diff --git a/frontend/src/locales/es.json b/frontend/src/locales/es.json index ef5805e1..46798463 100644 --- a/frontend/src/locales/es.json +++ b/frontend/src/locales/es.json @@ -98,7 +98,7 @@ "lights": "Estado de encendido o apagado de las luces altas, bajas y de posición.", "efficiencyDistance": "Distancia total recorrida hasta el momento hoy.", "efficiencyEnergy": "Lo que ha usado el coche desde medianoche. En un BEV o PHEV que es energía eléctrica a través de la batería de alto voltaje, en kilovatios-hora. En un HEV, el mismo contador lleva el total de combustible de la computadora de viaje, por lo que se muestra en litros.", - "efficiencyCharge": "Distancia recorrida desde que terminó la última carga. Si el coche la informa por sí mismo, se muestra esa cifra. Si no, GarageStack la calcula: el cuentakilómetros actual menos el cuentakilómetros en el que terminó la última carga registrada. Aparece cuando se ha registrado una carga del coche, y una carga tan corta que ninguna lectura la captó se pierde, salvo que el coche indique cuándo terminó. Una cifra calculada así se muestra con ≈ delante. Solo relevante para PHEV y BEV.", + "efficiencyCharge": "Distancia recorrida desde que terminó la última carga. Si el coche la informa por sí mismo, se muestra esa cifra. Si no, GarageStack la calcula: el cuentakilómetros actual menos el cuentakilómetros en el que terminó la última carga. Esa carga es una que una lectura captó, una de la que el coche indica cuándo terminó o, para una carga entre dos lecturas, una subida de 2 puntos o más del nivel de batería con el coche parado. Aparece cuando se conoce una carga así, y una cifra calculada de este modo se muestra con ≈ delante. Solo relevante para PHEV y BEV.", "efficiencySinceCharge": "Energía consumida por distancia desde la última carga, en {energyPerDistance}; un valor {energyBetter}. Procede de los contadores propios de la batería desde la última carga, que empiezan de nuevo en cada carga. Solo aplica a PHEV y BEV.", "efficiencyRatio": "Consumo de energía o combustible para la distancia recorrida hoy. En BEV y PHEV se muestra como {energyPerDistance}; un valor {energyBetter} y permite calcular el coste eléctrico por {distance}. En HEV se muestra el consumo de combustible como {fuelConsumption}; {fuelBetter}: conducir por autopista suele dar un consumo mejor que los trayectos cortos con paradas y arranques, especialmente con el motor frío. Si aún no hay datos de conducción, los HEV y PHEV muestran una estimación del consumo ({distancePerPercent}) calculada a partir de la autonomía que indica el coche.", "speed": "Velocidad actual del vehículo según lo informado por la puerta de enlace.", diff --git a/frontend/src/locales/nl.json b/frontend/src/locales/nl.json index c40beaff..f7d96930 100644 --- a/frontend/src/locales/nl.json +++ b/frontend/src/locales/nl.json @@ -98,7 +98,7 @@ "lights": "Aan/uit-status van groot licht, dimlicht en stadslichten.", "efficiencyDistance": "Totale afstand gereden vandaag.", "efficiencyEnergy": "Wat de auto sinds middernacht heeft verbruikt. Op een BEV of PHEV is dat elektrische energie door de hoogspanningsaccu, in kilowattuur. Op een HEV bevat diezelfde teller het brandstoftotaal van de boordcomputer en wordt die dus in liters getoond.", - "efficiencyCharge": "Afstand gereden sinds het einde van de laatste lading. Meldt de auto dit zelf, dan wordt die waarde getoond. Doet de auto dat niet, dan rekent GarageStack het uit: de kilometerstand nu, min de kilometerstand waar de laatste vastgelegde lading eindigde. Het verschijnt zodra een lading voor de auto is vastgelegd, en een lading die zo kort is dat geen enkele meting haar zag, wordt gemist, tenzij de auto meldt wanneer ze eindigde. Een zo uitgerekende waarde wordt getoond met ≈ ervoor. Alleen relevant voor PHEV en BEV.", + "efficiencyCharge": "Afstand gereden sinds het einde van de laatste lading. Meldt de auto dit zelf, dan wordt die waarde getoond. Doet de auto dat niet, dan rekent GarageStack het uit: de kilometerstand nu, min de kilometerstand waar de laatste lading eindigde. Die lading is er een die een meting zag, een waarvan de auto meldt wanneer ze eindigde, of, voor een lading tussen twee metingen, een stijging van het batterijniveau met 2 punten of meer terwijl de auto stilstond. Het verschijnt zodra zo’n lading bekend is, en een zo uitgerekende waarde wordt getoond met ≈ ervoor. Alleen relevant voor PHEV en BEV.", "efficiencySinceCharge": "Het verbruik per afstand sinds de laatste lading, in {energyPerDistance}, waarbij {energyBetter}. Het komt uit de eigen tellers van de accu sinds de laatste lading, die bij elke lading opnieuw beginnen. Alleen relevant voor PHEV en BEV.", "efficiencyRatio": "Hoeveel de auto verbruikte voor de afstand van vandaag. Op een BEV of PHEV is dat {energyPerDistance}, waarbij {energyBetter}, en dat vertaalt zich direct naar elektriciteitskosten per {distance}. Op een HEV is het brandstofverbruik in {fuelConsumption}, waarbij {fuelBetter}: snelwegrijden geeft een betere waarde dan korte ritjes vanuit koude start. Als er nog geen rijgegevens beschikbaar zijn, vallen HEV en PHEV terug op een geschat brandstofverbruik ({distancePerPercent}) afgeleid van de rangecalculator van de auto, waarbij hoger zuiniger is.", "speed": "Actuele rijsnelheid zoals gerapporteerd door de gateway.", diff --git a/frontend/src/locales/pt-PT.json b/frontend/src/locales/pt-PT.json index b5eab6e9..c44f94c5 100644 --- a/frontend/src/locales/pt-PT.json +++ b/frontend/src/locales/pt-PT.json @@ -98,7 +98,7 @@ "lights": "Estado ligado ou desligado dos máximos, dos médios e dos mínimos.", "efficiencyDistance": "Distância total percorrida até agora hoje.", "efficiencyEnergy": "O que o carro consumiu desde a meia-noite. Num BEV ou PHEV, é energia elétrica da bateria de alta tensão, em quilowatts-hora. Num HEV, o mesmo contador traz o total de combustível do computador de bordo, por isso aparece em litros.", - "efficiencyCharge": "Distância percorrida desde o fim do último carregamento. Se o carro comunica este valor, é esse que se mostra. Se não, o GarageStack calcula-o: o conta-quilómetros atual menos o conta-quilómetros em que terminou o último carregamento registado. Aparece quando um carregamento do carro foi registado, e um carregamento tão curto que nenhuma leitura o apanhou não é contado, a menos que o carro indique quando terminou. Um valor calculado assim aparece com ≈ à frente. Só relevante para PHEV e BEV.", + "efficiencyCharge": "Distância percorrida desde o fim do último carregamento. Se o carro comunica este valor, é esse que se mostra. Se não, o GarageStack calcula-o: o conta-quilómetros atual menos o conta-quilómetros em que terminou o último carregamento. Esse carregamento é um que uma leitura apanhou, um de que o carro indica quando terminou ou, para um carregamento entre duas leituras, uma subida de 2 pontos ou mais no nível da bateria com o carro parado. Aparece quando um carregamento assim é conhecido, e um valor calculado desta forma aparece com ≈ à frente. Só relevante para PHEV e BEV.", "efficiencySinceCharge": "Energia consumida por distância desde o último carregamento, em {energyPerDistance}, onde {energyBetter}. Vem dos próprios contadores da bateria desde o último carregamento, que recomeçam a cada carga. Relevante apenas para PHEV e BEV.", "efficiencyRatio": "Quanto o carro consumiu na distância percorrida hoje. Num BEV ou PHEV, é {energyPerDistance}, onde {energyBetter}, e isso traduz-se diretamente no custo de eletricidade por {distance}. Num HEV, é o consumo de combustível em {fuelConsumption}, onde {fuelBetter}: conduzir em autoestrada dá um resultado melhor do que trajetos curtos em pára-arranca com o motor frio. Quando ainda não há dados de condução, HEV e PHEV usam a economia de combustível estimada ({distancePerPercent}), calculada pelo computador de autonomia do próprio carro, onde quanto maior, mais eficiente.", "speed": "Velocidade atual do veículo, conforme comunicada pelo gateway.", diff --git a/frontend/src/locales/pt.json b/frontend/src/locales/pt.json index 33e8318b..a04abeb1 100644 --- a/frontend/src/locales/pt.json +++ b/frontend/src/locales/pt.json @@ -98,7 +98,7 @@ "lights": "Estado ligado ou desligado do farol alto, do farol baixo e das lanternas.", "efficiencyDistance": "Distância total percorrida até agora hoje.", "efficiencyEnergy": "O que o carro consumiu desde a meia-noite. Em um BEV ou PHEV, é energia elétrica da bateria de alta tensão, em quilowatts-hora. Em um HEV, o mesmo contador traz o total de combustível do computador de bordo, por isso aparece em litros.", - "efficiencyCharge": "Distância percorrida desde o fim do último carregamento. Se o carro informa esse valor por conta própria, ele é mostrado. Se não, o GarageStack calcula: o hodômetro de agora menos o hodômetro em que terminou o último carregamento registrado. Aparece quando um carregamento do carro foi registrado, e um carregamento tão curto que nenhuma leitura o captou não é contado, a menos que o carro informe quando ele terminou. Um valor calculado assim aparece com ≈ na frente. Só relevante para PHEV e BEV.", + "efficiencyCharge": "Distância percorrida desde o fim do último carregamento. Se o carro informa esse valor por conta própria, ele é mostrado. Se não, o GarageStack calcula: o hodômetro de agora menos o hodômetro em que terminou o último carregamento. Esse carregamento é um que uma leitura captou, um que o carro informa quando terminou ou, para um carregamento entre duas leituras, uma subida de 2 pontos ou mais no nível da bateria com o carro parado. Aparece quando um carregamento assim é conhecido, e um valor calculado desse jeito aparece com ≈ na frente. Só relevante para PHEV e BEV.", "efficiencySinceCharge": "Energia consumida por distância desde o último carregamento, em {energyPerDistance}, onde {energyBetter}. Vem dos próprios contadores da bateria desde o último carregamento, que recomeçam a cada carga. Relevante apenas para PHEV e BEV.", "efficiencyRatio": "Quanto o carro consumiu na distância percorrida hoje. Em um BEV ou PHEV, é {energyPerDistance}, onde {energyBetter}, e isso se traduz diretamente no custo de eletricidade por {distance}. Em um HEV, é o consumo de combustível em {fuelConsumption}, onde {fuelBetter}: rodar na rodovia dá um resultado melhor do que trajetos curtos de anda e para com o motor frio. Quando ainda não há dados de condução, HEV e PHEV usam a economia de combustível estimada ({distancePerPercent}), calculada pelo computador de autonomia do próprio carro, onde quanto maior, mais eficiente.", "speed": "Velocidade atual do veículo, conforme informada pelo gateway.", diff --git a/src/GarageStack.Core/Helpers/DistanceSinceCharge.cs b/src/GarageStack.Core/Helpers/DistanceSinceCharge.cs index ffeef834..5f90a22e 100644 --- a/src/GarageStack.Core/Helpers/DistanceSinceCharge.cs +++ b/src/GarageStack.Core/Helpers/DistanceSinceCharge.cs @@ -48,6 +48,66 @@ public static DateTime ChargingReadingAt(DateTime recordedAt, DateTime? chargeSt return reported is { } r && seen is { } s ? (r > s ? r : s) : reported ?? seen; } + /// + /// How many points the state of charge must climb, with the car standing still, to be taken for + /// a charge no reading caught. A parked car's figure does not climb on its own: in the stored + /// readings it moves by tenths of a point at most, but a charge adds far more, so two points + /// tells one from the other with room to spare and still finds a top-up worth the name. + /// + public const double MinimumSocRisePercent = 2; + + /// How far back a rise in the state of charge is looked for when no charge is known to start from. + public static readonly TimeSpan SocRiseLookback = TimeSpan.FromDays(60); + + /// A reading's state of charge and odometer, either of which a row may leave out. + public sealed record SocReading(DateTime RecordedAt, double? OdometerKm, double? EvSocPercent); + + /// A charge found from the state of charge alone: when it was seen to have happened, and the odometer it happened at. + public sealed record SocRiseCharge(DateTime At, double OdometerKm); + + /// + /// The latest charge that shows only as the state of charge going up. The gateway reads a parked + /// car rarely, so a charge can start and end between two reads, with nothing in them saying + /// "charging". The car cannot have been driven while its odometer stood still, so a stretch of + /// readings at one odometer value whose state of charge climbs by + /// or more above its lowest in that stretch is a charge, and it happened at that odometer. A new + /// odometer value starts a new stretch, so a drive (which regenerates and wobbles the figure) never counts. + /// Null when there is none. + /// + public static SocRiseCharge? LastSocRiseCharge( + IEnumerable readings, double minimumRise = MinimumSocRisePercent) + { + SocRiseCharge? found = null; + double? odometer = null; + double? stretchOdometer = null; + double? lowest = null; + + foreach (var reading in readings.OrderBy(r => r.RecordedAt)) + { + if (reading.OdometerKm is { } km && double.IsFinite(km)) + odometer = km; + if (odometer != stretchOdometer) + { + stretchOdometer = odometer; + lowest = null; + } + + if (reading.EvSocPercent is not { } soc || !double.IsFinite(soc) || stretchOdometer is not { } at) + continue; + + lowest = lowest is { } low && low < soc ? low : soc; + if (soc - lowest.Value >= minimumRise) + { + found = new SocRiseCharge(reading.RecordedAt, at); + // A charge goes on rising: the next two points count as the next sign of it, so the + // time found follows the charge to its end. + lowest = soc; + } + } + + return found; + } + /// /// The kilometres between the odometer at the end of the last charge and the odometer now, to a /// tenth. Null when either is unknown, or when the odometer went backwards: a reading that says diff --git a/src/GarageStack.Data/Repositories/TelemetryRepository.cs b/src/GarageStack.Data/Repositories/TelemetryRepository.cs index 9376f522..c595ffaf 100644 --- a/src/GarageStack.Data/Repositories/TelemetryRepository.cs +++ b/src/GarageStack.Data/Repositories/TelemetryRepository.cs @@ -294,9 +294,26 @@ private sealed record OdometerAtCharge(double? Km); .Select(s => s.ChargingLastEndAt) .FirstOrDefaultAsync(ct); - return DistanceSinceCharge.LastChargeAt(now, reportedEnd, lastSeenCharging) is { } endedAt - ? await GetOdometerAtAsync(vehicleId, endedAt, ct) - : null; + var endedAt = DistanceSinceCharge.LastChargeAt(now, reportedEnd, lastSeenCharging); + var odometerAtEnd = endedAt is { } end ? await GetOdometerAtAsync(vehicleId, end, ct) : null; + + // A charge the polls missed entirely: the gateway reads a parked car rarely, so a charge can + // start and end between two reads. After the last charge there is evidence of (or, with none + // known, within the lookback), a state of charge that climbed with the car standing still is + // one, and it is the later charge if it came after. + var riseFrom = endedAt ?? now - DistanceSinceCharge.SocRiseLookback; + var rise = DistanceSinceCharge.LastSocRiseCharge(await db.TelemetrySnapshots + .AsNoTracking() + .Where(s => s.VehicleId == vehicleId + && s.RecordedAt >= riseFrom + && (s.EvSocPercent != null || s.OdometerKm != null)) + .OrderBy(s => s.RecordedAt) + .Select(s => new DistanceSinceCharge.SocReading(s.RecordedAt, s.OdometerKm, s.EvSocPercent)) + .ToListAsync(ct)); + + return rise is { } missed && (endedAt is not { } known || missed.At > known) + ? missed.OdometerKm + : odometerAtEnd; } // A finished day's statistics cannot change: every row is stamped when it arrives, so no row diff --git a/src/GarageStack.Tests/DistanceSinceChargeTests.cs b/src/GarageStack.Tests/DistanceSinceChargeTests.cs index c8b03998..31f42bd0 100644 --- a/src/GarageStack.Tests/DistanceSinceChargeTests.cs +++ b/src/GarageStack.Tests/DistanceSinceChargeTests.cs @@ -76,6 +76,95 @@ public void TheCalculatedFlag_IsNotAReadingToStoreMergeOrExport() Assert.DoesNotContain(ZipExport.TelemetryColumns, p => p.Name == flag); } + // ── A charge the polls missed ───────────────────────────────────────────── + + private static DistanceSinceCharge.SocReading Reading(double hours, double? odometer, double? soc) => + new(T0.AddHours(hours), odometer, soc); + + [Fact] + public void LastSocRiseCharge_AParkedCarWhoseChargeRoseByTwoPoints_IsACharge() + { + var found = DistanceSinceCharge.LastSocRiseCharge( + [Reading(-5, 2858, 83.3), Reading(-4, 2858, 83.3), Reading(-1, 2858, 90)]); + + Assert.Equal(new DistanceSinceCharge.SocRiseCharge(T0.AddHours(-1), 2858), found); + } + + [Fact] + public void LastSocRiseCharge_LessThanTwoPoints_IsNotACharge() => + Assert.Null(DistanceSinceCharge.LastSocRiseCharge( + [Reading(-5, 2858, 83.3), Reading(-1, 2858, 85.2)])); + + [Fact] + public void LastSocRiseCharge_TheSmallWobbleOfAParkedCar_IsNotACharge() => + Assert.Null(DistanceSinceCharge.LastSocRiseCharge( + [Reading(-5, 2858, 83.3), Reading(-4, 2858, 83.6), Reading(-3, 2858, 83.3), Reading(-2, 2858, 83.5)])); + + [Fact] + public void LastSocRiseCharge_APointOrSoGainedWhileDriving_IsNotACharge() => + // Every reading is at a new odometer value, so none is a stretch of a parked car. + Assert.Null(DistanceSinceCharge.LastSocRiseCharge( + [Reading(-4, 2840, 83.0), Reading(-3, 2841, 83.9), Reading(-2, 2842, 84.4), Reading(-1, 2843, 86.0)])); + + [Fact] + public void LastSocRiseCharge_ClimbsCountedFromTheLowestOfTheStretch_NotFromTheLastReading() + { + // A slow charge adds a few tenths between reads, which only the whole rise shows. + var found = DistanceSinceCharge.LastSocRiseCharge( + [Reading(-5, 2858, 80), Reading(-4, 2858, 80.6), Reading(-3, 2858, 81.2), Reading(-2, 2858, 81.8), Reading(-1, 2858, 82.3)]); + + Assert.Equal(new DistanceSinceCharge.SocRiseCharge(T0.AddHours(-1), 2858), found); + } + + [Fact] + public void LastSocRiseCharge_ADropThenARise_CountsTheRiseFromTheDrop() + { + var found = DistanceSinceCharge.LastSocRiseCharge( + [Reading(-5, 2858, 80), Reading(-4, 2858, 78), Reading(-1, 2858, 80.1)]); + + Assert.Equal(T0.AddHours(-1), found!.At); + } + + [Fact] + public void LastSocRiseCharge_ACarThatChargedThenWasDriven_IsStillTheCharge() + { + var found = DistanceSinceCharge.LastSocRiseCharge( + [Reading(-9, 2858, 83.3), Reading(-8, 2858, 91), Reading(-6, 2860, 90), Reading(-5, 2870, 85)]); + + Assert.Equal(new DistanceSinceCharge.SocRiseCharge(T0.AddHours(-8), 2858), found); + } + + [Fact] + public void LastSocRiseCharge_WithTwoCharges_IsTheLaterOne() + { + var found = DistanceSinceCharge.LastSocRiseCharge( + [Reading(-20, 2800, 50), Reading(-19, 2800, 80), Reading(-10, 2840, 60), Reading(-9, 2840, 62.5)]); + + Assert.Equal(new DistanceSinceCharge.SocRiseCharge(T0.AddHours(-9), 2840), found); + } + + [Fact] + public void LastSocRiseCharge_RowsThatCarryOnlyOneOfTheTwo_AreCarriedForward() + { + var found = DistanceSinceCharge.LastSocRiseCharge( + [Reading(-5, 2858, null), Reading(-4, null, 83.3), Reading(-3, null, 84), Reading(-1, null, 90)]); + + Assert.Equal(new DistanceSinceCharge.SocRiseCharge(T0.AddHours(-1), 2858), found); + } + + [Fact] + public void LastSocRiseCharge_WithoutAnOdometer_IsNotACharge() => + Assert.Null(DistanceSinceCharge.LastSocRiseCharge([Reading(-5, null, 60), Reading(-1, null, 90)])); + + [Fact] + public void LastSocRiseCharge_InAnyOrder_IsReadInTimeOrder() + { + var found = DistanceSinceCharge.LastSocRiseCharge( + [Reading(-1, 2858, 90), Reading(-5, 2858, 83.3)]); + + Assert.Equal(T0.AddHours(-1), found!.At); + } + // ── The repository ─────────────────────────────────────────────────────── private static async Task<(AppDbContext Db, TelemetryRepository Repo, int VehicleId)> SetupAsync( @@ -279,4 +368,74 @@ public async Task GetMergedLatest_RemembersThatThereWasNoCharge_TooSoThatItIsNot // Still the cached "no charge": the search is not run again within the minute. Assert.Null((await repo.GetMergedLatestAsync(vehicleId, ct))!.MileageSinceLastCharge); } + + private static TelemetrySnapshot Soc(DateTime at, double soc, double? odometer = null) => + new() { RecordedAt = at, EvSocPercent = soc, OdometerKm = odometer }; + + [Fact] + public async Task GetMergedLatest_ChargeNoReadingCaught_StillCountsFromTheStateOfChargeGoingUp() + { + // The Urban was read at 83 %, unplugged, and next read at 90 % at the same odometer: a charge + // happened between the two reads, and the distance counts from it. + var ct = TestContext.Current.CancellationToken; + var (db, repo, vehicleId) = await SetupAsync(null, + Soc(T0.AddDays(-2), 83.3, 2858), + Soc(T0.AddDays(-1), 90), + Odometer(T0.AddMinutes(-5), 2900)); + await using var _ = db; + + var result = await repo.GetMergedLatestAsync(vehicleId, ct); + + Assert.Equal(42, result!.MileageSinceLastCharge); + Assert.True(result.MileageSinceLastChargeCalculated); + } + + [Fact] + public async Task GetMergedLatest_AMissedChargeAfterASeenOne_IsTheLastCharge() + { + var ct = TestContext.Current.CancellationToken; + var (db, repo, vehicleId) = await SetupAsync(null, + Odometer(T0.AddDays(-5), 2800), + Charging(T0.AddDays(-5), true), + Soc(T0.AddDays(-4), 60, 2850), + Soc(T0.AddDays(-3), 85), + Odometer(T0.AddMinutes(-5), 2900)); + await using var _ = db; + + var result = await repo.GetMergedLatestAsync(vehicleId, ct); + + Assert.Equal(50, result!.MileageSinceLastCharge); + } + + [Fact] + public async Task GetMergedLatest_ASeenChargeAfterAClimbOfTheStateOfCharge_IsTheLastCharge() + { + var ct = TestContext.Current.CancellationToken; + var (db, repo, vehicleId) = await SetupAsync(null, + Soc(T0.AddDays(-5), 60, 2800), + Soc(T0.AddDays(-4), 85), + Odometer(T0.AddDays(-2), 2850), + Charging(T0.AddDays(-2), true), + Odometer(T0.AddMinutes(-5), 2900)); + await using var _ = db; + + var result = await repo.GetMergedLatestAsync(vehicleId, ct); + + Assert.Equal(50, result!.MileageSinceLastCharge); + } + + [Fact] + public async Task GetMergedLatest_AClimbOfLessThanTwoPoints_IsNoChargeToCountFrom() + { + var ct = TestContext.Current.CancellationToken; + var (db, repo, vehicleId) = await SetupAsync(null, + Soc(T0.AddDays(-2), 83.3, 2858), + Soc(T0.AddDays(-1), 84.5), + Odometer(T0.AddMinutes(-5), 2900)); + await using var _ = db; + + var result = await repo.GetMergedLatestAsync(vehicleId, ct); + + Assert.Null(result!.MileageSinceLastCharge); + } } diff --git a/src/GarageStack.Tests/Postgres/TelemetryRepositoryPostgresTests.cs b/src/GarageStack.Tests/Postgres/TelemetryRepositoryPostgresTests.cs index 0a23900a..77e936e2 100644 --- a/src/GarageStack.Tests/Postgres/TelemetryRepositoryPostgresTests.cs +++ b/src/GarageStack.Tests/Postgres/TelemetryRepositoryPostgresTests.cs @@ -193,4 +193,23 @@ public async Task TheDistanceSinceTheLastCharge_ForACarThatDoesNotReportIt_Trans Assert.Equal(51, merged!.MileageSinceLastCharge); } + + [Fact] + public async Task TheDistanceSinceAChargeNoReadingCaught_ReadsTheStateOfChargeAsPostgresRunsIt() + { + var ct = TestContext.Current.CancellationToken; + await using var database = await PostgresDatabase.CreateAsync(ct); + await using var db = database.CreateContext(); + var vehicleId = await AddVehicleAsync(db, ct); + db.TelemetrySnapshots.AddRange( + new TelemetrySnapshot { VehicleId = vehicleId, RecordedAt = Now.AddDays(-2), EvSocPercent = 83.3, OdometerKm = 2858 }, + new TelemetrySnapshot { VehicleId = vehicleId, RecordedAt = Now.AddDays(-1), EvSocPercent = 90 }, + new TelemetrySnapshot { VehicleId = vehicleId, RecordedAt = Now.AddHours(-1), OdometerKm = 2900 }); + await db.SaveChangesAsync(ct); + + var merged = await new TelemetryRepository(db).GetMergedLatestAsync(vehicleId, ct); + + Assert.Equal(42, merged!.MileageSinceLastCharge); + Assert.True(merged.MileageSinceLastChargeCalculated); + } } From 05dd4336381b1f2705a13ab9e5c78e9a34e51d0c Mon Sep 17 00:00:00 2001 From: arthur-lzrs <55158951+arthur-lzrs@users.noreply.github.com> Date: Fri, 27 Nov 2026 16:22:30 -0300 Subject: [PATCH 3/4] feat: count a climb of a point to a full battery as a charge, and document the rules A parked car read at 98.3 % and then at 100 % was charged, but that is 1.7 points, under the two the climb must make to be taken for a charge no poll caught. When the climb ends at a full battery (99.5 % or more) a point is enough, so a top-up to full is not missed by a few tenths. A car already full that stays full still counts as nothing. ARCHITECTURE.md now says how the distance since the last charge is worked out for a car that does not report it: the signs the end of the last charge is taken from, the two points and the one point to full, why the figure is not stored, and what it cannot see. Co-Authored-By: Claude Sonnet 5.5 --- documentation/ARCHITECTURE.md | 9 +++++++++ .../Helpers/DistanceSinceCharge.cs | 17 +++++++++++++++-- .../DistanceSinceChargeTests.cs | 19 +++++++++++++++++++ 3 files changed, 43 insertions(+), 2 deletions(-) diff --git a/documentation/ARCHITECTURE.md b/documentation/ARCHITECTURE.md index f43899a6..f196d954 100644 --- a/documentation/ARCHITECTURE.md +++ b/documentation/ARCHITECTURE.md @@ -108,6 +108,15 @@ The `AddTripLog` migration clears the trips saved before it and resets the recor The charge history page (`/charge-history`, `VehicleEndpoints`) rebuilds sessions from telemetry rather than storing a second history table. `GET .../charge-sessions` takes a period (`from`/`to`, the last 90 days by default, at most 366) and `TelemetryRepository` reads that period's charging-state, state-of-charge, odometer, battery-energy, power and GPS readings, plus two days either side so a session crossing an edge is seen whole. `ChargeSessionHistory` opens a session where `drivetrain/charging` turns true and closes it where it turns false, and takes the gateway's `charging/lastStart` and `charging/lastEnd` times when they fit between those readings. A row whose `refresh/lastChargeState` stamp is older than one already seen is a retained message the gateway or the broker published again, and is skipped, so it cannot reopen a charge that ended. The list carries the peak power but not the curve: `GET .../charge-sessions/power?from=&to=` gives one session's readings when it is picked (`useChargePower`, which keeps a finished session's curve). The page is laid out as the trip log: two-line rows (`ChargeSessionItem`) with when, the duration, the charge levels, the peak power and the energy, and the picked session's `ChargeSessionDetail` beside them from 1024 px, or in a dialog below that, with where it charged, the odometer, the driving since the charge before and the power curve. Power is in kW. The gateway sends the onboard charger figures in watts and the Worker stores kW since #574, so `ChargerPower` reads a figure above 50 as watts from an older row. `ChargerPower` picks the single- or three-phase onboard charger figure, whichever is closer to the battery's own power (`drivetrain/power`), since the gateway works out both from one voltage and current and only one is right; on DC the onboard charger reads zero and the battery's power is the charge. A plain hybrid gets no sessions (`ChargeSessionHistory.Applies`) and no menu entry. Battery kWh is the gateway's `drivetrain/soc_kwh`, which is MG's nominal 72.5 kWh pack scaled by the state of charge on anything but a BEV series the gateway knows. The browser (`utils/chargeSessions.ts`, `trustedBatteryKwh` in `utils/energy.ts`) shows kWh from a configured capacity (`HV_BATTERY_CAPACITY_KWH`) when there is one, else only on a BEV, and the consumption since the last charge only on a BEV, whose distance is all electric. Once telemetry is compacted (`TELEMETRY_FULL_DETAIL_DAYS`), older sessions come from 15-minute readings, so a short one can disappear and curves are coarser. +### Distance since the last charge + +Some cars send a distance-since-last-charge counter (`mileageSinceLastCharge`, which starts again from zero when a charge ends) and some never do. For a car whose merged snapshot has none, `TelemetryRepository.GetMergedLatestAsync` fills it in from the odometer, and sets `MileageSinceLastChargeCalculated` so the dashboard shows the figure with an approximate sign. The flag is `[NotMapped]`: it is not stored, and `TelemetryFields` and the data export leave it out. A car that reports the counter is never touched. The rules live in `DistanceSinceCharge` (Core): + +- The figure is the odometer now less the odometer where the car's last charge ended, to a tenth of a kilometre. An odometer that went backwards, or a car with no charge to count from, gives no figure and the card stays hidden. +- The end of the last charge is the latest of three signs. The end time the car reports (`charging/lastEnd`). The last reading that showed the car charging, dated by its poll's own stamp (`refresh/lastChargeState`) when that is older than its row, as for charge sessions, so a gateway that starts again does not move it. And a charge no poll caught, found from the state of charge alone. A charge still going counts as ending now, so it reads zero. A time more than five minutes ahead of now is not believed. +- A charge that shows only as the state of charge going up: the gateway reads a parked car rarely (after a short spell it polls once a day), so a charge can start and end between two reads. Readings at one odometer value are a car that stood still, and a climb of 2 points or more above the lowest of that stretch (`MinimumSocRisePercent`) is a charge, at that odometer. One point is enough when the climb ends at a full battery (99.5 % or more). The 2 points are well clear of what a parked car does in the stored readings, which is tenths of a point at most. A new odometer value starts a new stretch, so driving, which regenerates and wobbles the figure, never counts, and neither does a charge with the car driven before the next read. +- The lookup reads back at most 400 days for the first two signs, and the readings after the last known charge (60 days when none) for the third. Its result is cached for a minute, a missing charge included, apart from the merged snapshot's own five-second cache. + ### Phone GPS (the app and Dawarich) A car that reports a position every few minutes leaves gaps a phone can fill. The Worker's `PhoneFusionService` adds phone positions to saved trips from two sources: those the installed app sends while it is on screen, which need nothing configured, and, when `DAWARICH_URL` and `DAWARICH_API_KEY` are set, those of the driver's own [Dawarich](https://dawarich.app) instance. [`PHONE_GPS.md`](PHONE_GPS.md) covers the setup; this is how it works. diff --git a/src/GarageStack.Core/Helpers/DistanceSinceCharge.cs b/src/GarageStack.Core/Helpers/DistanceSinceCharge.cs index 5f90a22e..d3e497d1 100644 --- a/src/GarageStack.Core/Helpers/DistanceSinceCharge.cs +++ b/src/GarageStack.Core/Helpers/DistanceSinceCharge.cs @@ -56,6 +56,17 @@ public static DateTime ChargingReadingAt(DateTime recordedAt, DateTime? chargeSt /// public const double MinimumSocRisePercent = 2; + /// + /// The state of charge at which a battery counts as full, and how many points a climb that ends + /// there must have made: a parked car that reaches full has been charged, even when the last + /// read before it was only a point or so below (98.3 to 100 is 1.7 points, short of + /// , and is the end of a charge all the same). + /// + public const double FullChargePercent = 99.5; + + /// The smallest climb to a full battery that is taken for a charge. + public const double MinimumRiseToFullPercent = 1; + /// How far back a rise in the state of charge is looked for when no charge is known to start from. public static readonly TimeSpan SocRiseLookback = TimeSpan.FromDays(60); @@ -70,7 +81,8 @@ public sealed record SocRiseCharge(DateTime At, double OdometerKm); /// car rarely, so a charge can start and end between two reads, with nothing in them saying /// "charging". The car cannot have been driven while its odometer stood still, so a stretch of /// readings at one odometer value whose state of charge climbs by - /// or more above its lowest in that stretch is a charge, and it happened at that odometer. A new + /// or more above its lowest in that stretch (a point is enough when it ends at a full battery) is a + /// charge, and it happened at that odometer. A new /// odometer value starts a new stretch, so a drive (which regenerates and wobbles the figure) never counts. /// Null when there is none. /// @@ -96,7 +108,8 @@ public sealed record SocRiseCharge(DateTime At, double OdometerKm); continue; lowest = lowest is { } low && low < soc ? low : soc; - if (soc - lowest.Value >= minimumRise) + var rise = soc - lowest.Value; + if (rise >= minimumRise || (soc >= FullChargePercent && rise >= MinimumRiseToFullPercent)) { found = new SocRiseCharge(reading.RecordedAt, at); // A charge goes on rising: the next two points count as the next sign of it, so the diff --git a/src/GarageStack.Tests/DistanceSinceChargeTests.cs b/src/GarageStack.Tests/DistanceSinceChargeTests.cs index 31f42bd0..ba931d89 100644 --- a/src/GarageStack.Tests/DistanceSinceChargeTests.cs +++ b/src/GarageStack.Tests/DistanceSinceChargeTests.cs @@ -95,6 +95,25 @@ public void LastSocRiseCharge_LessThanTwoPoints_IsNotACharge() => Assert.Null(DistanceSinceCharge.LastSocRiseCharge( [Reading(-5, 2858, 83.3), Reading(-1, 2858, 85.2)])); + [Theory] + [InlineData(98.3, 100)] // 1.7 points: short of two, but the car is full + [InlineData(98.9, 100)] + [InlineData(99.0, 100)] + public void LastSocRiseCharge_AParkedCarThatReachesFull_IsACharge_EvenOnALessThanTwoPointClimb(double before, double full) + { + var found = DistanceSinceCharge.LastSocRiseCharge([Reading(-5, 2858, before), Reading(-1, 2858, full)]); + + Assert.Equal(new DistanceSinceCharge.SocRiseCharge(T0.AddHours(-1), 2858), found); + } + + [Fact] + public void LastSocRiseCharge_ACarAlreadyFullThatStaysFull_IsNotACharge() => + Assert.Null(DistanceSinceCharge.LastSocRiseCharge([Reading(-5, 2858, 99.6), Reading(-1, 2858, 100)])); + + [Fact] + public void LastSocRiseCharge_AClimbOfAPointThatDoesNotReachFull_IsNotACharge() => + Assert.Null(DistanceSinceCharge.LastSocRiseCharge([Reading(-5, 2858, 80), Reading(-1, 2858, 81.5)])); + [Fact] public void LastSocRiseCharge_TheSmallWobbleOfAParkedCar_IsNotACharge() => Assert.Null(DistanceSinceCharge.LastSocRiseCharge( From 23d105e970bb3fed3d0245e1e4bd2d07f9f4363d Mon Sep 17 00:00:00 2001 From: arthur-lzrs <55158951+arthur-lzrs@users.noreply.github.com> Date: Fri, 27 Nov 2026 17:01:34 -0300 Subject: [PATCH 4/4] fix: keep the calculated distance off plain hybrids and rates, and bound its lookups A review of the calculated distance since the last charge found what it should not touch and what it costs to find. A plain hybrid never charges from a plug, and an engine topping its battery up at a standstill would have read as one: the repository now gives it nothing (ChargeSessionHistory.Applies, with the car's own type setting first, as the charge history does). Where the distance was worked out, nothing that divides by it or sets it against the car's own counters uses it: the dashboard's efficiency since the last charge (the car's energy counter over a distance that starts elsewhere), the widget's electricSharePercent and the Statistics page's electric share are left to a car that reported the distance itself. The widget carries mileageSinceLastChargeCalculated, as the snapshot does. The lookups are bounded. The last charge is searched for in windows of 7, 30, 120 and 400 days and the search stops at the first that holds one, so a car that charges often reads a week; a reported end time only counts when the time itself is inside the window, so a zero or an epoch says nothing (it used to be able to send the state-of-charge scan back to 1970); that scan never reads further back than 90 days; and "no charge found", the answer that costs most to find, is remembered for two minutes instead of one. The demo's plug-in hybrid no longer sends the distance, so its dashboard shows the figure worked out, with the approximate sign. Co-Authored-By: Claude Sonnet 5.5 --- documentation/ARCHITECTURE.md | 5 +- documentation/WIDGET.md | 3 +- documentation/openapi.json | 4 + frontend/src/cards/__tests__/registry.spec.ts | 12 ++ frontend/src/cards/registry.ts | 11 +- .../src/components/DashboardCardContent.vue | 5 +- .../__tests__/DashboardCardContent.spec.ts | 6 +- frontend/src/views/StatisticsView.vue | 2 + .../views/__tests__/StatisticsView.spec.ts | 14 +++ .../Endpoints/WidgetEndpoints.cs | 6 +- .../Helpers/DistanceSinceCharge.cs | 22 +++- src/GarageStack.Data/Demo/DemoCar.cs | 6 + src/GarageStack.Data/Demo/DemoCars.HsPhev.cs | 2 + .../Demo/DemoTelemetryRepository.cs | 1 + .../Repositories/TelemetryRepository.cs | 65 ++++++---- .../DistanceSinceChargeTests.cs | 117 +++++++++++++++++- src/GarageStack.Tests/WidgetStatusDtoTests.cs | 28 +++++ 17 files changed, 269 insertions(+), 40 deletions(-) diff --git a/documentation/ARCHITECTURE.md b/documentation/ARCHITECTURE.md index f196d954..3182f877 100644 --- a/documentation/ARCHITECTURE.md +++ b/documentation/ARCHITECTURE.md @@ -115,7 +115,10 @@ Some cars send a distance-since-last-charge counter (`mileageSinceLastCharge`, w - The figure is the odometer now less the odometer where the car's last charge ended, to a tenth of a kilometre. An odometer that went backwards, or a car with no charge to count from, gives no figure and the card stays hidden. - The end of the last charge is the latest of three signs. The end time the car reports (`charging/lastEnd`). The last reading that showed the car charging, dated by its poll's own stamp (`refresh/lastChargeState`) when that is older than its row, as for charge sessions, so a gateway that starts again does not move it. And a charge no poll caught, found from the state of charge alone. A charge still going counts as ending now, so it reads zero. A time more than five minutes ahead of now is not believed. - A charge that shows only as the state of charge going up: the gateway reads a parked car rarely (after a short spell it polls once a day), so a charge can start and end between two reads. Readings at one odometer value are a car that stood still, and a climb of 2 points or more above the lowest of that stretch (`MinimumSocRisePercent`) is a charge, at that odometer. One point is enough when the climb ends at a full battery (99.5 % or more). The 2 points are well clear of what a parked car does in the stored readings, which is tenths of a point at most. A new odometer value starts a new stretch, so driving, which regenerates and wobbles the figure, never counts, and neither does a charge with the car driven before the next read. -- The lookup reads back at most 400 days for the first two signs, and the readings after the last known charge (60 days when none) for the third. Its result is cached for a minute, a missing charge included, apart from the merged snapshot's own five-second cache. +- A plain hybrid (`ChargeSessionHistory.Applies`) gets nothing: an engine topping its battery up at a standstill would look like a charge, and it never charges from a plug. +- The lookup reads outward through `DistanceSinceCharge.SearchWindows` (7, 30, 120 and then 400 days) and stops at the first window that holds a sign of a charge, so a car that charges often reads a week of readings and only one that rarely or never does reads the whole lookback. An end time the car reports only counts when the time itself is inside the window, so a zero or an epoch there says nothing. The state-of-charge scan reads the readings after the last known charge (60 days when none), and never further back than 90 days. +- The odometer found is cached for a minute, and a missing charge for two, because the lookup that finds nothing is the one that costs most. The merged snapshot has its own five-second cache on top. +- The figure is a distance, not a rate. Where it was worked out, what divides by it or sets it against the car's own energy counter (the dashboard's efficiency since the last charge, the widget's `electricSharePercent`, the Statistics page's electric share) uses it only when the car reported it itself. ### Phone GPS (the app and Dawarich) diff --git a/documentation/WIDGET.md b/documentation/WIDGET.md index 83a8e944..d0e7c79f 100644 --- a/documentation/WIDGET.md +++ b/documentation/WIDGET.md @@ -57,6 +57,7 @@ The endpoint returns a flat JSON object. Numeric fields are `null` when the vehi | `isCharging` | string | Charging state: `"Charging"` or `"Not charging"` | | `chargerConnected` | string | Charger connection state: `"Plugged in"` or `"Unplugged"` | | `mileageSinceLastCharge` | number | Distance driven since the last charge (km). Where the car does not report it, worked out from the odometer at the end of the last charge GarageStack knows of (see the dashboard card), and null until there is one | +| `mileageSinceLastChargeCalculated` | boolean | True when `mileageSinceLastCharge` was worked out from the odometer rather than reported by the car | | `hvSocKwh` | number | HV battery energy (kWh), as the gateway reports it | | `hvTotalCapacityKwh` | number | HV battery total capacity (kWh), as the gateway reports it | | `hvVoltage` | number | HV system voltage (V) | @@ -65,7 +66,7 @@ The endpoint returns a flat JSON object. Numeric fields are `null` when the vehi | `odometerKm` | number | Total odometer reading (km) | | `mileageOfTheDayKm` | number | Distance driven today (km) | | `powerUsageOfDayKwh` | number | Energy used today (kWh). On a plain hybrid this counter holds the trip computer's fuel total in hundredths of a litre instead, so divide by 100 for litres. It is the gateway's figure as it comes: on a plug-in hybrid that is on MG's nominal 72.5 kWh pack, so multiply by your real capacity divided by 72.5 | -| `electricSharePercent` | number | % of today's distance driven on electric power (PHEV) | +| `electricSharePercent` | number | % of today's distance driven on electric power (PHEV). Null when `mileageSinceLastCharge` was worked out rather than reported by the car | | `isLocked` | string | Lock state: `"Locked"` or `"Unlocked"` | | `engineRunning` | string | Engine state: `"Engine on"` or `"Engine off"` | | `climateOn` | string | Remote climate state: `"On"` or `"Off"` | diff --git a/documentation/openapi.json b/documentation/openapi.json index 6eb2b855..00930970 100644 --- a/documentation/openapi.json +++ b/documentation/openapi.json @@ -11001,6 +11001,7 @@ "isCharging", "chargerConnected", "mileageSinceLastCharge", + "mileageSinceLastChargeCalculated", "hvSocKwh", "hvTotalCapacityKwh", "hvVoltage", @@ -11124,6 +11125,9 @@ ], "format": "double" }, + "mileageSinceLastChargeCalculated": { + "type": "boolean" + }, "hvSocKwh": { "type": [ "null", diff --git a/frontend/src/cards/__tests__/registry.spec.ts b/frontend/src/cards/__tests__/registry.spec.ts index e33be442..c063cb2e 100644 --- a/frontend/src/cards/__tests__/registry.spec.ts +++ b/frontend/src/cards/__tests__/registry.spec.ts @@ -77,6 +77,18 @@ describe('card registry', () => { expect(cardHasData('efficiencyCharge', context(status, 'bev'))).toBe(true) }) + // The car's own energy counter over a distance GarageStack worked out would mix two windows. + it('has no efficiency since the last charge where the distance was worked out, but still the distance', () => { + const status = { + powerUsageSinceLastCharge: 8.2, + mileageSinceLastCharge: 46, + mileageSinceLastChargeCalculated: true, + } + + expect(cardHasData('efficiencySinceCharge', context(status, 'bev'))).toBe(false) + expect(cardHasData('efficiencyCharge', context(status, 'bev'))).toBe(true) + }) + it('shows efficiency since the last charge for a car that plugs in and has driven', () => { const status = { powerUsageSinceLastCharge: 11.12, mileageSinceLastCharge: 46 } expect(cardHasData('efficiencySinceCharge', context(status, 'bev'))).toBe(true) diff --git a/frontend/src/cards/registry.ts b/frontend/src/cards/registry.ts index 872b0c13..90e03085 100644 --- a/frontend/src/cards/registry.ts +++ b/frontend/src/cards/registry.ts @@ -202,14 +202,19 @@ export function defaultCards(type: VehicleType = 'unknown'): CardConfig[] { /** * Wh/km since the last charge, off the battery's since-last-charge counters, for a car that - * plugs in: the pair that held up on the ZS EV whose day counter did not (issue #551). + * plugs in: the pair that held up on the ZS EV whose day counter did not (issue #551). Both + * counters are the car's own: where the API worked the distance out from the odometer, the energy + * counter and the distance start from different moments, and the two do not describe the same driving. */ export function sinceChargeWhPerKm( - status: Pick, + status: Pick< + TelemetrySnapshot, + 'powerUsageSinceLastCharge' | 'mileageSinceLastCharge' | 'mileageSinceLastChargeCalculated' + >, vehicleType: VehicleType, scale: CounterScale, ): number | null { - return plugsIn(vehicleType) + return plugsIn(vehicleType) && status.mileageSinceLastChargeCalculated !== true ? whPerKm(scaledCounter(status.powerUsageSinceLastCharge, scale), status.mileageSinceLastCharge) : null } diff --git a/frontend/src/components/DashboardCardContent.vue b/frontend/src/components/DashboardCardContent.vue index 6dadb7bc..7f3f4f71 100644 --- a/frontend/src/components/DashboardCardContent.vue +++ b/frontend/src/components/DashboardCardContent.vue @@ -208,10 +208,7 @@ const simpleCards = computed((): SimpleCardConfig[] => { { id: 'efficiencySinceCharge', label: t('vehicle.efficiency.efficiencySinceCharge'), - ...approximate( - measured('energyPerDistance', sinceChargeWhPerKm(s, ctx.vehicleType, ctx.counterScale)), - s.mileageSinceLastChargeCalculated === true, - ), + ...measured('energyPerDistance', sinceChargeWhPerKm(s, ctx.vehicleType, ctx.counterScale)), }, // efficiencyRatio - measured fuel consumption on a hybrid, which beats the estimate below { diff --git a/frontend/src/components/__tests__/DashboardCardContent.spec.ts b/frontend/src/components/__tests__/DashboardCardContent.spec.ts index 891409dc..7fc896c9 100644 --- a/frontend/src/components/__tests__/DashboardCardContent.spec.ts +++ b/frontend/src/components/__tests__/DashboardCardContent.spec.ts @@ -150,7 +150,9 @@ describe('DashboardCardContent', () => { expect(card.text).toBeNull() }) - it('shows the efficiency since the last charge as approximate when its distance was worked out', () => { + // The energy counter is the car's own and starts where the car says; the distance GarageStack + // worked out starts where GarageStack found a charge. The two are not the same driving. + it("does not divide the car's energy counter by a distance that was worked out", () => { const card = render( 'efficiencySinceCharge', status({ @@ -161,7 +163,7 @@ describe('DashboardCardContent', () => { 'bev', ) - expect(card.text).toBe(`${en.vehicle.efficiency.efficiencySinceCharge}|≈ 24.2|kWh/100 km`) + expect(card.text).toBeNull() }) it('is also shown since the last charge, off the since-last-charge counters', () => { diff --git a/frontend/src/views/StatisticsView.vue b/frontend/src/views/StatisticsView.vue index 8a91d211..2f5e3100 100644 --- a/frontend/src/views/StatisticsView.vue +++ b/frontend/src/views/StatisticsView.vue @@ -206,6 +206,8 @@ const avgSpeedKmh = computed(() => averageMovingSpeedKmh(store.tripSummaries)) const electricShareToday = computed(() => { const s = status.value if (!s?.mileageSinceLastCharge || !s?.mileageOfTheDay || s.mileageOfTheDay === 0) return null + // Only off the car's own counter: a distance the API worked out is itself an estimate. + if (s.mileageSinceLastChargeCalculated === true) return null return Math.min(100, Math.round((s.mileageSinceLastCharge / s.mileageOfTheDay) * 100)) }) diff --git a/frontend/src/views/__tests__/StatisticsView.spec.ts b/frontend/src/views/__tests__/StatisticsView.spec.ts index 5c659083..d406110f 100644 --- a/frontend/src/views/__tests__/StatisticsView.spec.ts +++ b/frontend/src/views/__tests__/StatisticsView.spec.ts @@ -212,6 +212,20 @@ describe('StatisticsView', () => { expect(shownInsights(wrapper)[insights.electricShare]).toBe('75%') }) + it('leaves out the electric share when the distance since the last charge was worked out', async () => { + vi.mocked(vehicleApi.list).mockResolvedValue([car('phev')]) + vi.mocked(vehicleApi.status).mockResolvedValue({ + ...parked, + mileageOfTheDay: 40, + mileageSinceLastCharge: 30, + mileageSinceLastChargeCalculated: true, + } as TelemetrySnapshot) + + const wrapper = await mountView() + + expect(shownInsights(wrapper)[insights.electricShare]).not.toBe('75%') + }) + it('shows where the car parked once the insight is opened', async () => { const wrapper = await mountView() diff --git a/src/GarageStack.Api/Endpoints/WidgetEndpoints.cs b/src/GarageStack.Api/Endpoints/WidgetEndpoints.cs index 36d47a6e..9afc1a71 100644 --- a/src/GarageStack.Api/Endpoints/WidgetEndpoints.cs +++ b/src/GarageStack.Api/Endpoints/WidgetEndpoints.cs @@ -83,6 +83,7 @@ public record WidgetStatusDto( string? IsCharging, string? ChargerConnected, double? MileageSinceLastCharge, + bool MileageSinceLastChargeCalculated, double? HvSocKwh, double? HvTotalCapacityKwh, double? HvVoltage, @@ -191,7 +192,9 @@ public static WidgetStatusDto FromSnapshot(TelemetrySnapshot s, VehicleFacts f, // charge can be several days ago while MileageOfTheDay only covers today, the ratio can // exceed 100% (e.g. charged 3 days ago, driven a little each day since) - capped rather // than treated as exact. - double? electricShare = s.MileageSinceLastCharge.HasValue && s.MileageOfTheDay is > 0 + // Only off the car's own counter: a distance GarageStack worked out is itself an estimate, + // and a share built on it would be an estimate of an estimate. + double? electricShare = s.MileageSinceLastCharge.HasValue && !s.MileageSinceLastChargeCalculated && s.MileageOfTheDay is > 0 ? Math.Min(100, Math.Round(s.MileageSinceLastCharge.Value / s.MileageOfTheDay!.Value * 100)) : null; @@ -210,6 +213,7 @@ public static WidgetStatusDto FromSnapshot(TelemetrySnapshot s, VehicleFacts f, IsCharging: Loc(s.IsCharging, "ChargingYes", "ChargingNo", l), ChargerConnected: Loc(s.ChargerConnected, "PluggedIn", "Unplugged", l), MileageSinceLastCharge: s.MileageSinceLastCharge, + MileageSinceLastChargeCalculated: s.MileageSinceLastChargeCalculated, HvSocKwh: s.HvSocKwh, HvTotalCapacityKwh: s.HvTotalCapacityKwh, HvVoltage: s.HvVoltage, diff --git a/src/GarageStack.Core/Helpers/DistanceSinceCharge.cs b/src/GarageStack.Core/Helpers/DistanceSinceCharge.cs index d3e497d1..3fe88238 100644 --- a/src/GarageStack.Core/Helpers/DistanceSinceCharge.cs +++ b/src/GarageStack.Core/Helpers/DistanceSinceCharge.cs @@ -11,12 +11,32 @@ public static class DistanceSinceCharge /// How far back the last charge is looked for: more than a year, so a car that is rarely plugged in still has one. public static readonly TimeSpan Lookback = TimeSpan.FromDays(400); + /// + /// The spans the last charge is looked for in, nearest first. The search stops at the first that + /// holds a sign of one, so a car that charges often is found in a week of readings, and only a + /// car that rarely or never does reads back as far as . + /// + public static readonly IReadOnlyList SearchWindows = + [TimeSpan.FromDays(7), TimeSpan.FromDays(30), TimeSpan.FromDays(120), Lookback]; + /// /// How long the odometer at the last charge is reused before it is looked up again. A charge - /// ends rarely and the lookup reads far back, so a minute's delay in noticing one costs nothing. + /// ends rarely, so a minute's delay in noticing one costs nothing. /// public static readonly TimeSpan CacheFor = TimeSpan.FromMinutes(1); + /// + /// How long "no charge found" is reused. It is the answer that costs the most to find (the whole + /// lookback is read for it), and a car's first charge appears within a couple of minutes anyway. + /// + public static readonly TimeSpan CacheNoChargeFor = TimeSpan.FromMinutes(2); + + /// + /// The furthest back readings are read for a charge that shows only as the state of charge + /// going up, however long ago the last known charge was. + /// + public static readonly TimeSpan SocRiseMaxLookback = TimeSpan.FromDays(90); + /// How many of the newest readings that show the car charging are compared, to find the latest charge. public const int ChargingReadingsCompared = 20; diff --git a/src/GarageStack.Data/Demo/DemoCar.cs b/src/GarageStack.Data/Demo/DemoCar.cs index 09f56990..3468773a 100644 --- a/src/GarageStack.Data/Demo/DemoCar.cs +++ b/src/GarageStack.Data/Demo/DemoCar.cs @@ -20,6 +20,12 @@ public DemoCar() public required Vehicle Vehicle { get; init; } + /// + /// Whether the car sends its own distance since the last charge. One that does not has it worked + /// out from the odometer, as for a real car like that, which the dashboard shows as approximate. + /// + public bool ReportsDistanceSinceCharge { get; init; } = true; + /// Seeds the history's randomness: each car's readings differ, and stay the same on every start. public required int Seed { get; init; } diff --git a/src/GarageStack.Data/Demo/DemoCars.HsPhev.cs b/src/GarageStack.Data/Demo/DemoCars.HsPhev.cs index b5760a8f..3cccef7e 100644 --- a/src/GarageStack.Data/Demo/DemoCars.HsPhev.cs +++ b/src/GarageStack.Data/Demo/DemoCars.HsPhev.cs @@ -16,6 +16,8 @@ internal static partial class DemoCars { Vehicle = DemoVehicleRepository.SecondDemoVehicle, Seed = 7, + // The plug-in hybrid sends no distance since the last charge, so the dashboard shows it worked out. + ReportsDistanceSinceCharge = false, Home = HsHome, CurrentOdometerKm = 18243, CapacityKwh = 24.7, diff --git a/src/GarageStack.Data/Demo/DemoTelemetryRepository.cs b/src/GarageStack.Data/Demo/DemoTelemetryRepository.cs index 42f919c6..61f7c75c 100644 --- a/src/GarageStack.Data/Demo/DemoTelemetryRepository.cs +++ b/src/GarageStack.Data/Demo/DemoTelemetryRepository.cs @@ -455,6 +455,7 @@ private static TelemetrySnapshot BuildDefaultSnapshot(DemoCar car) LastVehicleStateAt = DateTime.UtcNow, LastChargeStateAt = DateTime.UtcNow.AddHours(-8), MileageSinceLastCharge = Math.Round(history.SinceChargeKm + drivingKm, 1), + MileageSinceLastChargeCalculated = !car.ReportsDistanceSinceCharge, MileageOfTheDay = Math.Round(history.DayKm + drivingKm, 1), PowerUsageOfDay = Math.Round(history.DayKwh + drivingKwh, 2), PowerUsageSinceLastCharge = Math.Round(history.SinceChargeKwh + drivingKwh, 2), diff --git a/src/GarageStack.Data/Repositories/TelemetryRepository.cs b/src/GarageStack.Data/Repositories/TelemetryRepository.cs index c595ffaf..e2cdd02f 100644 --- a/src/GarageStack.Data/Repositories/TelemetryRepository.cs +++ b/src/GarageStack.Data/Repositories/TelemetryRepository.cs @@ -263,45 +263,62 @@ private sealed record OdometerAtCharge(double? Km); return known.Km; var km = await ReadOdometerAtLastChargeAsync(vehicleId, ct); - cache?.Set(key, new OdometerAtCharge(km), DistanceSinceCharge.CacheFor); + cache?.Set(key, new OdometerAtCharge(km), km is null ? DistanceSinceCharge.CacheNoChargeFor : DistanceSinceCharge.CacheFor); return km; } private async Task ReadOdometerAtLastChargeAsync(int vehicleId, CancellationToken ct) { + // A plain hybrid never charges from a plug: what its battery does at a standstill (an engine + // topping it up at a red light) is not a charge, and there is none to count from. + var vehicle = await db.Vehicles.AsNoTracking().FirstOrDefaultAsync(v => v.Id == vehicleId, ct); + if (vehicle is not null + && !ChargeSessionHistory.Applies(vehicle.Settings?.VehicleType ?? VehicleTypeHelper.GetVehicleType(vehicle))) + return null; + var now = UtcNow; - var since = now - DistanceSinceCharge.Lookback; - // The newest readings that show the car charging. Compared by when each was true of the car - // rather than by when its row landed, as a gateway that starts again sends an old charge - // state in a new row. - var charging = await db.TelemetrySnapshots - .AsNoTracking() - .Where(s => s.VehicleId == vehicleId && s.RecordedAt >= since && s.IsCharging == true) - .OrderByDescending(s => s.RecordedAt) - .Take(DistanceSinceCharge.ChargingReadingsCompared) - .Select(s => new { s.RecordedAt, s.LastChargeStateAt }) - .ToListAsync(ct); - DateTime? lastSeenCharging = charging.Count == 0 - ? null - : charging.Max(r => DistanceSinceCharge.ChargingReadingAt(r.RecordedAt, r.LastChargeStateAt)); + // The nearest span that holds a sign of a charge. The signs are the newest readings that show + // the car charging, compared by when each was true of the car rather than by when its row + // landed (a gateway that starts again sends an old charge state in a new row), and the end + // time the car reports, which only counts when the time itself is inside the span: a car + // that reports a zero or an old epoch there has told us nothing about a charge. + DateTime? endedAt = null; + foreach (var window in DistanceSinceCharge.SearchWindows) + { + var since = now - window; + var charging = await db.TelemetrySnapshots + .AsNoTracking() + .Where(s => s.VehicleId == vehicleId && s.RecordedAt >= since && s.IsCharging == true) + .OrderByDescending(s => s.RecordedAt) + .Take(DistanceSinceCharge.ChargingReadingsCompared) + .Select(s => new { s.RecordedAt, s.LastChargeStateAt }) + .ToListAsync(ct); + DateTime? lastSeenCharging = charging.Count == 0 + ? null + : charging.Max(r => DistanceSinceCharge.ChargingReadingAt(r.RecordedAt, r.LastChargeStateAt)); + + // A charge too short for a poll to catch still leaves the end time the car reports. + var reportedEnd = await db.TelemetrySnapshots + .AsNoTracking() + .Where(s => s.VehicleId == vehicleId && s.RecordedAt >= since && s.ChargingLastEndAt >= since) + .OrderByDescending(s => s.RecordedAt) + .Select(s => s.ChargingLastEndAt) + .FirstOrDefaultAsync(ct); - // A charge too short for a poll to catch still leaves the end time the car reports. - var reportedEnd = await db.TelemetrySnapshots - .AsNoTracking() - .Where(s => s.VehicleId == vehicleId && s.RecordedAt >= since && s.ChargingLastEndAt != null) - .OrderByDescending(s => s.RecordedAt) - .Select(s => s.ChargingLastEndAt) - .FirstOrDefaultAsync(ct); + endedAt = DistanceSinceCharge.LastChargeAt(now, reportedEnd, lastSeenCharging); + if (endedAt is not null) break; + } - var endedAt = DistanceSinceCharge.LastChargeAt(now, reportedEnd, lastSeenCharging); var odometerAtEnd = endedAt is { } end ? await GetOdometerAtAsync(vehicleId, end, ct) : null; // A charge the polls missed entirely: the gateway reads a parked car rarely, so a charge can // start and end between two reads. After the last charge there is evidence of (or, with none // known, within the lookback), a state of charge that climbed with the car standing still is - // one, and it is the later charge if it came after. + // one, and it is the later charge if it came after. Never read further back than the cap. var riseFrom = endedAt ?? now - DistanceSinceCharge.SocRiseLookback; + var cap = now - DistanceSinceCharge.SocRiseMaxLookback; + if (riseFrom < cap) riseFrom = cap; var rise = DistanceSinceCharge.LastSocRiseCharge(await db.TelemetrySnapshots .AsNoTracking() .Where(s => s.VehicleId == vehicleId diff --git a/src/GarageStack.Tests/DistanceSinceChargeTests.cs b/src/GarageStack.Tests/DistanceSinceChargeTests.cs index ba931d89..467eaaa6 100644 --- a/src/GarageStack.Tests/DistanceSinceChargeTests.cs +++ b/src/GarageStack.Tests/DistanceSinceChargeTests.cs @@ -186,13 +186,21 @@ public void LastSocRiseCharge_InAnyOrder_IsReadInTimeOrder() // ── The repository ─────────────────────────────────────────────────────── - private static async Task<(AppDbContext Db, TelemetryRepository Repo, int VehicleId)> SetupAsync( - IMemoryCache? cache = null, params TelemetrySnapshot[] rows) + private static Task<(AppDbContext Db, TelemetryRepository Repo, int VehicleId)> SetupAsync( + IMemoryCache? cache = null, params TelemetrySnapshot[] rows) => + SetupCarAsync(null, cache, rows); + + private static async Task<(AppDbContext Db, TelemetryRepository Repo, int VehicleId)> SetupCarAsync( + string? vehicleType, IMemoryCache? cache, params TelemetrySnapshot[] rows) { var db = new AppDbContext(new DbContextOptionsBuilder() .UseInMemoryDatabase(Guid.NewGuid().ToString()) .Options); - var vehicle = new Vehicle { Vin = "FAKEVN00000000001" }; + var vehicle = new Vehicle + { + Vin = "FAKEVN00000000001", + Settings = vehicleType is null ? null : new VehicleSettings { VehicleType = vehicleType }, + }; db.Vehicles.Add(vehicle); await db.SaveChangesAsync(); foreach (var row in rows) row.VehicleId = vehicle.Id; @@ -457,4 +465,107 @@ public async Task GetMergedLatest_AClimbOfLessThanTwoPoints_IsNoChargeToCountFro Assert.Null(result!.MileageSinceLastCharge); } + + // ── Which cars, how far back, and how much is read ────────────────────────── + + [Fact] + public async Task GetMergedLatest_APlainHybrid_HasNoDistanceFromACharge() + { + // Its battery climbs at a standstill when the engine tops it up, and it never charges from a plug. + var ct = TestContext.Current.CancellationToken; + var (db, repo, vehicleId) = await SetupCarAsync("hev", null, + Soc(T0.AddDays(-2), 60, 1000), + Soc(T0.AddDays(-2).AddMinutes(5), 64), + Charging(T0.AddDays(-1), true), + Odometer(T0.AddMinutes(-5), 1042)); + await using var _ = db; + + var result = await repo.GetMergedLatestAsync(vehicleId, ct); + + Assert.Null(result!.MileageSinceLastCharge); + Assert.False(result.MileageSinceLastChargeCalculated); + } + + [Theory] + [InlineData("bev")] + [InlineData("phev")] + public async Task GetMergedLatest_APlugInCar_HasItsDistanceFromACharge(string type) + { + var ct = TestContext.Current.CancellationToken; + var (db, repo, vehicleId) = await SetupCarAsync(type, null, + Odometer(T0.AddDays(-2), 1000), + Charging(T0.AddDays(-2), true), + Odometer(T0.AddMinutes(-5), 1042)); + await using var _ = db; + + var result = await repo.GetMergedLatestAsync(vehicleId, ct); + + Assert.Equal(42, result!.MileageSinceLastCharge); + } + + [Theory] + [InlineData(40)] // in the first span + [InlineData(100)] // in the third + [InlineData(300)] // in the last + public async Task GetMergedLatest_ALastChargeAtAnyDistanceInTheLookback_IsFound(int daysAgo) + { + var ct = TestContext.Current.CancellationToken; + var (db, repo, vehicleId) = await SetupAsync(null, + Odometer(T0.AddDays(-daysAgo), 1000), + Charging(T0.AddDays(-daysAgo), true), + Odometer(T0.AddMinutes(-5), 1042)); + await using var _ = db; + + var result = await repo.GetMergedLatestAsync(vehicleId, ct); + + Assert.Equal(42, result!.MileageSinceLastCharge); + } + + [Theory] + [InlineData(0)] + [InlineData(-62135596800)] // the year 1 + public async Task GetMergedLatest_AnEndTimeThatIsAnEpoch_SaysNothingAboutACharge(long epochSeconds) + { + // A car that reports charging/lastEnd as zero has not said when a charge ended. + var ct = TestContext.Current.CancellationToken; + var (db, repo, vehicleId) = await SetupAsync(null, + Odometer(T0.AddDays(-2), 1000), + new TelemetrySnapshot + { + RecordedAt = T0.AddDays(-1), + ChargingLastEndAt = DateTimeOffset.FromUnixTimeSeconds(epochSeconds).UtcDateTime, + }, + Odometer(T0.AddMinutes(-5), 1042)); + await using var _ = db; + + var result = await repo.GetMergedLatestAsync(vehicleId, ct); + + Assert.Null(result!.MileageSinceLastCharge); + } + + [Fact] + public async Task GetMergedLatest_AClimbOfTheStateOfChargeOlderThanTheCap_IsNotLookedFor() + { + // The last charge a reading saw is 200 days ago; a climb 100 days ago is further back than + // readings are read for one, so the distance counts from the charge that was seen. + var ct = TestContext.Current.CancellationToken; + var (db, repo, vehicleId) = await SetupAsync(null, + Odometer(T0.AddDays(-200), 1000), + Charging(T0.AddDays(-200), true), + Soc(T0.AddDays(-101), 60, 1500), + Soc(T0.AddDays(-100), 85), + Odometer(T0.AddMinutes(-5), 1600)); + await using var _ = db; + + var result = await repo.GetMergedLatestAsync(vehicleId, ct); + + Assert.Equal(600, result!.MileageSinceLastCharge); + } + + [Fact] + public void TheSearchWindows_GetWiderAndEndAtTheLookback() + { + Assert.Equal(DistanceSinceCharge.SearchWindows.Order(), DistanceSinceCharge.SearchWindows); + Assert.Equal(DistanceSinceCharge.Lookback, DistanceSinceCharge.SearchWindows[^1]); + } } diff --git a/src/GarageStack.Tests/WidgetStatusDtoTests.cs b/src/GarageStack.Tests/WidgetStatusDtoTests.cs index 13f16832..e37e7c5e 100644 --- a/src/GarageStack.Tests/WidgetStatusDtoTests.cs +++ b/src/GarageStack.Tests/WidgetStatusDtoTests.cs @@ -22,6 +22,34 @@ public void FromSnapshot_PowerUsageOfDay_PassesKwhThrough() Assert.Equal(16.34, dto.PowerUsageOfDayKwh); } + [Fact] + public void FromSnapshot_CarriesWhetherTheDistanceSinceTheLastChargeWasWorkedOut() + { + var reported = WidgetStatusDto.FromSnapshot( + new TelemetrySnapshot { MileageSinceLastCharge = 30 }, NoFacts, new KeyEchoLocalizer()); + var calculated = WidgetStatusDto.FromSnapshot( + new TelemetrySnapshot { MileageSinceLastCharge = 30, MileageSinceLastChargeCalculated = true }, + NoFacts, new KeyEchoLocalizer()); + + Assert.False(reported.MileageSinceLastChargeCalculated); + Assert.True(calculated.MileageSinceLastChargeCalculated); + } + + [Fact] + public void FromSnapshot_ElectricShare_IsOffTheCarsOwnCounterOnly() + { + // 30 of today's 40 km since the last charge. Worked out from the odometer, the distance is an + // estimate, and a share built on it would be an estimate of an estimate. + var reported = WidgetStatusDto.FromSnapshot( + new TelemetrySnapshot { MileageSinceLastCharge = 30, MileageOfTheDay = 40 }, NoFacts, new KeyEchoLocalizer()); + var calculated = WidgetStatusDto.FromSnapshot( + new TelemetrySnapshot { MileageSinceLastCharge = 30, MileageOfTheDay = 40, MileageSinceLastChargeCalculated = true }, + NoFacts, new KeyEchoLocalizer()); + + Assert.Equal(75, reported.ElectricSharePercent); + Assert.Null(calculated.ElectricSharePercent); + } + [Fact] public void FromSnapshot_NoPowerUsageOfDay_ReturnsNull() {