Connected cars: update the odometer automatically

The provider tab gets an "Update odometer automatically" switch and an
interval (30 minutes to a week, daily by default). The API Server does
the updating on the scheduler's ticker, so it carries on with no page
open: every five minutes it takes the provider's odometer for each due
car and stores it when it is ahead, never backwards, the same as the
Update odometer button.

The setting belongs to the car. Readings are fetched under the account
of whoever switched it on, and stop if that user can no longer edit the
car. Each attempt and its error, if any, are stored on the car and shown
under the switch. The switch also shows when the provider can't be
reached, so updates that are failing can still be switched off.

New car fields odometer_auto_sync, odometer_sync_minutes,
odometer_sync_by, odometer_synced_at and odometer_sync_error; new route
PUT /api/cars/{id}/provider/auto-sync. Unlinking leaves the setting as
it is; the sweep only looks at linked cars.

launch.json gains api-server-8081 / web-app-8081 for when 8080 is taken.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
tajniak81andClaude Opus 5.5 committed 2026-11-18 12:07:02 +01:00
1 parent 914aeeee23
commit 3db12dba63
14 files changed
+512 -11

No files matched your search

@@ -62,6 +62,8 @@ type taskRunResult struct {
func (s *Server) StartScheduler() {
ctx, cancel := context.WithCancel(context.Background())
s.schedulerStop = cancel
// Automatic odometer updates ride on the same lifetime (odometersync.go).
s.startOdometerSync(ctx)
go func() {
t := time.NewTicker(taskTick)
defer t.Stop()
+237
View File
@@ -0,0 +1,237 @@
package api
// Automatic odometer updates from a car's connected service.
//
// The MyToyota tab already offers the provider's odometer when it is ahead of
// the stored one; this is that same write done on a timer, so a car that is
// driven every day does not need somebody to open its page and press the
// button. It runs on the server's own ticker rather than in the browser for the
// same reason the charging scheduler does: an update that needs the page open
// is a reminder, not an update.
//
// Provider calls always run under a person's account, so the car remembers who
// switched updates on and reads under theirs. That person must still have write
// access when a sweep comes round — a share that was revoked stops the updates
// rather than letting them write on a car the user no longer may edit.
import (
"context"
"encoding/json"
"errors"
"log"
"net/http"
"net/url"
"time"
)
// The intervals offered, in minutes. A fixed set rather than any number: the
// provider's servers are somebody else's, and every update is a login plus a
// batch of calls, so nothing more often than every half hour.
var odometerSyncIntervals = map[int]bool{
30: true, 60: true, 180: true, 360: true, 720: true, 1440: true, 10080: true,
}
// defaultOdometerSyncMinutes is what a car gets when updates are switched on
// without an interval: once a day, enough for service reminders.
const defaultOdometerSyncMinutes = 1440
// How often the sweep looks for cars that are due. The shortest interval is 30
// minutes, so a five-minute look lands every update within five of its time.
const odometerSyncTick = 5 * time.Minute
// How long one sweep may take, across every due car.
const odometerSyncSweepTimeout = 4 * time.Minute
// PUT /api/cars/{id}/provider/auto-sync — switch automatic odometer updates on
// or off, and choose how often. Body: {enabled: bool, intervalMinutes?: int}.
// Needs write access, since the updates write to the car, and a linked car.
// Switching on records the caller as the account the readings come from, and
// runs one update straight away so the choice shows its effect.
func (s *Server) handleCarOdometerAutoSync(w http.ResponseWriter, r *http.Request) {
who := caller(r)
if who == nil {
writeError(w, http.StatusUnauthorized, "not authenticated")
return
}
var body struct {
Enabled bool `json:"enabled"`
IntervalMinutes int `json:"intervalMinutes"`
}
if err := decodeJSON(r, &body); err != nil {
writeError(w, http.StatusBadRequest, err.Error())
return
}
carID := r.PathValue("id")
level, rec, err := s.carAccessLevel(r.Context(), who.ID, carID)
if err != nil {
writePBError(w, err)
return
}
if !canWrite(level) {
writeError(w, http.StatusForbidden, "you cannot edit this car")
return
}
if rec.Provider == "" {
writeError(w, http.StatusBadRequest, "this car is not linked to a connected service")
return
}
minutes := body.IntervalMinutes
if minutes == 0 {
minutes = rec.OdometerSyncMinutes
}
if minutes == 0 {
minutes = defaultOdometerSyncMinutes
}
if !odometerSyncIntervals[minutes] {
writeError(w, http.StatusBadRequest, "unsupported interval")
return
}
payload := map[string]any{
"odometer_auto_sync": body.Enabled,
"odometer_sync_minutes": minutes,
}
if body.Enabled {
payload["odometer_sync_by"] = who.ID
} else {
payload["odometer_sync_error"] = ""
}
var updated carRecord
if err := s.pb.Update(r.Context(), colCars, carID, payload, &updated); err != nil {
writePBError(w, err)
return
}
// Switching on (or changing the interval while on) updates once now, so the
// panel can show "last checked" and the odometer moves without waiting a day.
if body.Enabled {
s.syncCarOdometer(r.Context(), updated)
_ = s.pb.GetOne(r.Context(), colCars, carID, &updated)
}
m := updated.toModel()
m.Access = level
writeJSON(w, http.StatusOK, m)
}
// startOdometerSync starts the ticker that updates due cars. Called from
// StartScheduler and stopped by the same cancel.
func (s *Server) startOdometerSync(ctx context.Context) {
go func() {
t := time.NewTicker(odometerSyncTick)
defer t.Stop()
for {
select {
case <-ctx.Done():
return
case <-t.C:
s.sweepOdometerSync(ctx)
}
}
}()
}
// sweepOdometerSync updates every car whose interval has run out.
func (s *Server) sweepOdometerSync(ctx context.Context) {
if !s.pb.Configured() {
return
}
ctx, cancel := context.WithTimeout(ctx, odometerSyncSweepTimeout)
defer cancel()
res, err := s.pb.List(ctx, colCars, url.Values{
"filter": {`odometer_auto_sync=true && provider!=""`},
"perPage": {"500"},
})
if err != nil {
return // the database not answering is retried next tick, silently
}
var recs []carRecord
if err := json.Unmarshal(res.Items, &recs); err != nil {
return
}
now := time.Now()
for _, rec := range recs {
if !odometerSyncDue(rec, now) {
continue
}
s.syncCarOdometer(ctx, rec)
}
}
// odometerSyncDue says whether a car's interval has run out. A car never
// attempted, or whose timestamp is unreadable, is due.
func odometerSyncDue(rec carRecord, now time.Time) bool {
minutes := rec.OdometerSyncMinutes
if minutes <= 0 {
minutes = defaultOdometerSyncMinutes
}
last, err := time.Parse(time.RFC3339, rec.OdometerSyncedAt)
if err != nil {
return true
}
return !now.Before(last.Add(time.Duration(minutes) * time.Minute))
}
// syncCarOdometer fetches the provider's odometer for one car and stores it
// when it is ahead of the car's, then records the attempt. Failures are stored
// on the car (and so shown on its page) rather than returned: there is nobody
// waiting on a background update to tell.
func (s *Server) syncCarOdometer(ctx context.Context, rec carRecord) {
km, err := s.fetchCarOdometer(ctx, rec)
payload := map[string]any{
"odometer_synced_at": time.Now().UTC().Format(time.RFC3339),
"odometer_sync_error": "",
}
if err != nil {
payload["odometer_sync_error"] = err.Error()
log.Printf("odometer sync: car %s (%s): %v", rec.ID, rec.Name, err)
} else if km > rec.CurrentKm {
// Only ever forward, as with the button: a reading behind the stored one
// is the provider being stale, not the car running backwards.
payload["current_km"] = km
}
if err := s.pb.Update(ctx, colCars, rec.ID, payload, nil); err != nil {
log.Printf("odometer sync: car %s: saving: %v", rec.ID, err)
}
}
// fetchCarOdometer reads the provider's odometer for a car under the account of
// the user who switched updates on, checking they may still write to it.
func (s *Server) fetchCarOdometer(ctx context.Context, rec carRecord) (int, error) {
if rec.OdometerSyncBy == "" {
return 0, errors.New("nobody is set to read this car's odometer; switch automatic updates off and on again")
}
level, _, err := s.carAccessLevel(ctx, rec.OdometerSyncBy, rec.ID)
if err != nil {
return 0, err
}
if !canWrite(level) {
return 0, errors.New("the user who switched automatic updates on can no longer edit this car")
}
who, userRaw, err := s.callerForUser(ctx, rec.OdometerSyncBy)
if err != nil {
return 0, err
}
src, found := carVehicleSource(rec.Provider, rec.Make)
if !found {
return 0, errors.New("unknown vehicle provider")
}
cfg, ok, detail := src.gate(ctx, s, who, userRaw)
if !ok {
return 0, errors.New(detail)
}
vehicles, err := s.fetchProviderVehicles(ctx, src, cfg)
if err != nil {
return 0, err
}
vehicle, found := findVehicle(vehicles, rec.ProviderVehicleID)
if !found {
return 0, errors.New("this vehicle is not on the " + src.label() + " account")
}
km, ok := s.providerOdometer(ctx, src, cfg, vehicle.ID)
if !ok {
return 0, errors.New(src.label() + " did not report an odometer")
}
return km, nil
}
@@ -0,0 +1,65 @@
package api
import (
"net/http"
"strings"
"testing"
"time"
)
func TestOdometerSyncDue(t *testing.T) {
now := time.Date(2026, 11, 18, 12, 0, 0, 0, time.UTC)
at := func(d time.Duration) string { return now.Add(-d).Format(time.RFC3339) }
cases := []struct {
name string
rec carRecord
want bool
}{
{"never attempted", carRecord{OdometerSyncMinutes: 60}, true},
{"unreadable timestamp", carRecord{OdometerSyncMinutes: 60, OdometerSyncedAt: "yesterday"}, true},
{"inside the interval", carRecord{OdometerSyncMinutes: 60, OdometerSyncedAt: at(59 * time.Minute)}, false},
{"exactly at the interval", carRecord{OdometerSyncMinutes: 60, OdometerSyncedAt: at(time.Hour)}, true},
{"no interval falls back to daily", carRecord{OdometerSyncedAt: at(23 * time.Hour)}, false},
{"daily default runs out", carRecord{OdometerSyncedAt: at(24 * time.Hour)}, true},
}
for _, c := range cases {
if got := odometerSyncDue(c.rec, now); got != c.want {
t.Errorf("%s: due = %v, want %v", c.name, got, c.want)
}
}
}
func TestOdometerAutoSyncNeedsLinkedCar(t *testing.T) {
srv := newProviderTestServer(t, &fakeProviderPB{})
status, body := call(t, srv, http.MethodPut, "/api/cars/"+provCarID+"/provider/auto-sync", `{"enabled":true}`)
if status != http.StatusBadRequest || !strings.Contains(toStr(body["error"]), "not linked") {
t.Errorf("status = %d (%v), want 400 not linked", status, body["error"])
}
}
func TestOdometerAutoSyncRejectsOddInterval(t *testing.T) {
srv := newProviderTestServer(t, &fakeProviderPB{carProvider: "toyota", carVehicleID: "VIN1"})
status, body := call(t, srv, http.MethodPut, "/api/cars/"+provCarID+"/provider/auto-sync",
`{"enabled":true,"intervalMinutes":7}`)
if status != http.StatusBadRequest || !strings.Contains(toStr(body["error"]), "interval") {
t.Errorf("status = %d (%v), want 400 unsupported interval", status, body["error"])
}
}
func TestOdometerAutoSyncSwitchOff(t *testing.T) {
fake := &fakeProviderPB{carProvider: "toyota", carVehicleID: "VIN1"}
srv := newProviderTestServer(t, fake)
status, body := call(t, srv, http.MethodPut, "/api/cars/"+provCarID+"/provider/auto-sync",
`{"enabled":false,"intervalMinutes":360}`)
if status != http.StatusOK {
t.Fatalf("status = %d (%v), want 200", status, body["error"])
}
patch := fake.patch()
if patch["odometer_auto_sync"] != false || patch["odometer_sync_minutes"] != float64(360) {
t.Errorf("patch = %+v, want updates off at 360 minutes", patch)
}
if _, set := patch["odometer_sync_by"]; set {
t.Error("switching off must not record whose account to read under")
}
}
+12 -1
View File
@@ -64,6 +64,11 @@ type carRecord struct {
FirstRegistrationDate string `json:"first_registration_date"`
Provider string `json:"provider"`
ProviderVehicleID string `json:"provider_vehicle_id"`
OdometerAutoSync bool `json:"odometer_auto_sync"`
OdometerSyncMinutes int `json:"odometer_sync_minutes"`
OdometerSyncBy string `json:"odometer_sync_by"`
OdometerSyncedAt string `json:"odometer_synced_at"`
OdometerSyncError string `json:"odometer_sync_error"`
Owner string `json:"owner"`
Created string `json:"created"`
Updated string `json:"updated"`
@@ -108,7 +113,11 @@ func (rec carRecord) toModel() models.Car {
FirstRegistrationDate: rec.FirstRegistrationDate,
Provider: rec.Provider,
ProviderVehicleID: rec.ProviderVehicleID,
HiddenTabs: decodeStringList(rec.HiddenTabs),
OdometerAutoSync: rec.OdometerAutoSync,
OdometerSyncMinutes: rec.OdometerSyncMinutes,
OdometerSyncedAt: rec.OdometerSyncedAt,
OdometerSyncError: rec.OdometerSyncError,
HiddenTabs: decodeStringList(rec.HiddenTabs),
HiddenFields: decodeStringList(rec.HiddenFields),
HiddenServiceColumns: decodeStringList(rec.HiddenServiceColumns),
HiddenServiceParts: decodeStringList(rec.HiddenServiceParts),
@@ -155,6 +164,8 @@ func carPayload(c models.Car) map[string]any {
// provider clears both fields (unlink).
func carProviderPayload(provider, vehicleID string) map[string]any {
if provider == "" {
// Automatic odometer updates are left as they are: the sweep only looks
// at linked cars, so an unlinked one is simply never updated.
return map[string]any{"provider": "", "provider_vehicle_id": ""}
}
return map[string]any{"provider": provider, "provider_vehicle_id": vehicleID}
+2
View File
@@ -72,6 +72,7 @@
// PUT /api/cars/{id}/view
// GET /api/cars/{id}/provider POST /api/cars/{id}/provider
// POST /api/cars/{id}/provider/sync
// PUT /api/cars/{id}/provider/auto-sync
// GET /api/cars/{id}/service-records
// GET /api/cars/{id}/parts
// GET /api/cars/{id}/shares POST /api/cars/{id}/shares
@@ -530,6 +531,7 @@ func (s *Server) Handler() http.Handler {
mux.HandleFunc("GET /api/cars/{id}/provider", s.handleCarProvider)
mux.HandleFunc("POST /api/cars/{id}/provider", s.handleLinkCarProvider)
mux.HandleFunc("POST /api/cars/{id}/provider/sync", s.handleSyncCarProvider)
mux.HandleFunc("PUT /api/cars/{id}/provider/auto-sync", s.handleCarOdometerAutoSync)
mux.HandleFunc("GET /api/cars/{id}/shares", s.handleListShares)
mux.HandleFunc("POST /api/cars/{id}/shares", s.handleUpsertShare)
mux.HandleFunc("DELETE /api/cars/{id}/shares/{userId}", s.handleDeleteShare)
+9
View File
@@ -41,6 +41,15 @@ var collectionsSchema = map[string][]fieldDef{
// internal/api/vehicleproviders.go. Blank for a hand-entered car.
fText("provider", false),
fText("provider_vehicle_id", false),
// Automatic odometer updates from that service: on/off, how often (in
// minutes), whose account the reading is fetched under (the user who
// switched it on — provider calls always run as a person), and the last
// attempt with its error, if any. See internal/api/odometersync.go.
fBool("odometer_auto_sync"),
fNumber("odometer_sync_minutes"),
fText("odometer_sync_by", false),
fText("odometer_synced_at", false),
fText("odometer_sync_error", false),
// What this car's page shows: the tabs switched off (["fuel"] on an EV)
// and the Information fields switched off (["differentialOil"] on a car
// without one). Properties of the car, so everyone it is shared with sees
+9
View File
@@ -66,6 +66,15 @@ type Car struct {
Provider string `json:"provider,omitempty"`
ProviderVehicleID string `json:"providerVehicleId,omitempty"`
// OdometerAutoSync keeps CurrentKm in step with the provider's odometer in
// the background, every OdometerSyncMinutes. OdometerSyncedAt is the last
// attempt (RFC 3339) and OdometerSyncError what went wrong with it, if
// anything. Set through PUT /api/cars/{id}/provider/auto-sync only.
OdometerAutoSync bool `json:"odometerAutoSync"`
OdometerSyncMinutes int `json:"odometerSyncMinutes,omitempty"`
OdometerSyncedAt string `json:"odometerSyncedAt,omitempty"`
OdometerSyncError string `json:"odometerSyncError,omitempty"`
// HiddenTabs and HiddenFields are what this car's page does not show: tabs
// (["fuel"] on an EV) and Information fields (["differentialOil"] on a car
// without one). Properties of the car, so everyone it is shared with sees the