diff --git a/README.md b/README.md index e57d5279..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 | 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/ARCHITECTURE.md b/documentation/ARCHITECTURE.md index f43899a6..3182f877 100644 --- a/documentation/ARCHITECTURE.md +++ b/documentation/ARCHITECTURE.md @@ -108,6 +108,18 @@ 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. +- 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) 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/documentation/WIDGET.md b/documentation/WIDGET.md index 47145fe2..d0e7c79f 100644 --- a/documentation/WIDGET.md +++ b/documentation/WIDGET.md @@ -56,7 +56,8 @@ 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 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 a33483e2..00930970 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", @@ -10997,6 +11001,7 @@ "isCharging", "chargerConnected", "mileageSinceLastCharge", + "mileageSinceLastChargeCalculated", "hvSocKwh", "hvTotalCapacityKwh", "hvVoltage", @@ -11120,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 686a9d9f..7f3f4f71 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,7 +200,10 @@ 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', diff --git a/frontend/src/components/__tests__/DashboardCardContent.spec.ts b/frontend/src/components/__tests__/DashboardCardContent.spec.ts index c8238eec..7fc896c9 100644 --- a/frontend/src/components/__tests__/DashboardCardContent.spec.ts +++ b/frontend/src/components/__tests__/DashboardCardContent.spec.ts @@ -122,6 +122,50 @@ 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() + }) + + // 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({ + powerUsageSinceLastCharge: 11.12, + mileageSinceLastCharge: 46, + mileageSinceLastChargeCalculated: true, + }), + 'bev', + ) + + expect(card.text).toBeNull() + }) + 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..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 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 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 a14e8a3f..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 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. 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 bb54f4d7..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 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 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 6c373372..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 ú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. 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 531e82dd..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 ú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. 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/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/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/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/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.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..3fe88238 --- /dev/null +++ b/src/GarageStack.Core/Helpers/DistanceSinceCharge.cs @@ -0,0 +1,155 @@ +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); + + /// + /// 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, 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; + + /// + /// 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; + } + + /// + /// 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; + + /// + /// 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); + + /// 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 (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. + /// + 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; + 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 + // 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 + /// 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/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 f90a7dcf..e2cdd02f 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,94 @@ 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), 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; + + // 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); + + endedAt = DistanceSinceCharge.LastChargeAt(now, reportedEnd, lastSeenCharging); + if (endedAt is not null) break; + } + + 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. 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 + && 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 // 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..467eaaa6 --- /dev/null +++ b/src/GarageStack.Tests/DistanceSinceChargeTests.cs @@ -0,0 +1,571 @@ +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); + } + + // ── 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)])); + + [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( + [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 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", + 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; + 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); + } + + 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); + } + + // ── 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/Postgres/TelemetryRepositoryPostgresTests.cs b/src/GarageStack.Tests/Postgres/TelemetryRepositoryPostgresTests.cs index 3433f283..77e936e2 100644 --- a/src/GarageStack.Tests/Postgres/TelemetryRepositoryPostgresTests.cs +++ b/src/GarageStack.Tests/Postgres/TelemetryRepositoryPostgresTests.cs @@ -172,4 +172,44 @@ 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); + } + + [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); + } } 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() {