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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 |
Expand Down
12 changes: 12 additions & 0 deletions documentation/ARCHITECTURE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
5 changes: 3 additions & 2 deletions documentation/WIDGET.md
Original file line number Diff line number Diff line change
Expand Up @@ -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) |
Expand All @@ -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"` |
Expand Down
10 changes: 9 additions & 1 deletion documentation/openapi.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down Expand Up @@ -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",
Expand Down Expand Up @@ -10997,6 +11001,7 @@
"isCharging",
"chargerConnected",
"mileageSinceLastCharge",
"mileageSinceLastChargeCalculated",
"hvSocKwh",
"hvTotalCapacityKwh",
"hvVoltage",
Expand Down Expand Up @@ -11120,6 +11125,9 @@
],
"format": "double"
},
"mileageSinceLastChargeCalculated": {
"type": "boolean"
},
"hvSocKwh": {
"type": [
"null",
Expand Down
12 changes: 12 additions & 0 deletions frontend/src/cards/__tests__/registry.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
11 changes: 8 additions & 3 deletions frontend/src/cards/registry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<TelemetrySnapshot, 'powerUsageSinceLastCharge' | 'mileageSinceLastCharge'>,
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
}
Expand Down
14 changes: 13 additions & 1 deletion frontend/src/components/DashboardCardContent.vue
Original file line number Diff line number Diff line change
Expand Up @@ -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<SimpleCardConfig, 'value' | 'unit'>,
calculated: boolean,
): Pick<SimpleCardConfig, 'value' | 'unit'> {
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
Expand Down Expand Up @@ -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',
Expand Down
44 changes: 44 additions & 0 deletions frontend/src/components/__tests__/DashboardCardContent.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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',
Expand Down
2 changes: 1 addition & 1 deletion frontend/src/locales/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -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.",
Expand Down
Loading
Loading