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>
238 lines
7.6 KiB
Go
238 lines
7.6 KiB
Go
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
|
|
}
|