Skip to content

Commit 96efa6c

Browse files
atulmguptaCopilot
andauthored
Muse spark (#108)
* feat(charging): overlay Tesla bills, fix energy baseline Two related charging-accuracy fixes: 1. Charge energy delta baselines now use State() strictly before StartedAt instead of at StartedAt, since Fleet Telemetry can emit the session-start batch after energy has already begun accumulating, causing undercounted energy in both the live handler and the completed-session tracker. 2. New Tesla Supercharger invoice overlay: ChargingHandler.Get resolves the vehicle's VIN and matches it against tesla_charging_history via a new FindBestMatch repo method (closest charge_start_datetime within a 2h window). When a match is found, billed energy/cost/currency/rate are added to the response and preferred for display on the frontend KPI tiles, with vehicle-measured energy shown as a secondary subtitle. * Fix FSD trip meter glitch attribution Treat spurious trip-meter resets and implausible counter jumps as discontinuities instead of driven distance. Adds reset/restore cursor logic and tests so include_fields zero snap-backs do not inflate FSD or driving aggregates. * Add Grok dynamics briefing Adds a live Grok powertrain read to Driving Dynamics using motor and chassis signals, with interpretation logic and tests. Also adds shared client-side pagination for FSD insight lists and DataTable-backed FSD tables. * Add telemetry honesty insights Adds honesty-focused UI across the fleet dashboard, status bar, charging, battery, driving, and FSD views. Surfaces Supercharger bill site/fee metadata, preserves signal ingest timestamps for Tesla physics clocks, paginates physics evidence instead of truncating it, and fixes nav highlighting to prefer the most specific active route. * feat(driving): scope dynamics history by trip Add trip selection and date-scoped motor history, preserve active drives, and evenly sample backend history responses across the selected window. * fix(charging): correct history attribution Preserve and backfill charge coordinates without creating geofences from stale GPS, use Tesla billed energy for tariff pricing, and resolve date windows in the vehicle timezone. * Fix sparse FSD drive detail attribution Expand the drive detail FSD insights range to look around 24 hours so sparse counter bookends are included, preventing unknown/blank attribution for valid deltas. Adds backend and frontend regression coverage for the wider range behavior. * Scope FSD insights to drive detail Adds drive_id support for FSD insights with a 7-day bookend lookup and focused attribution, while filtering negligible fidget drives so they do not steal sparse counter deltas. Updates drive detail and list UI to use the drive-scoped hook and omit unknown FSD badges. * feat: add charging autopilot, OCPP, TCO ledger, and session insights Wire always-on charge autopilot, shared-charger queue planning, OCPP charge points, Tesla bill variance, session share reports, TCO fixed ledger, and related warranty, silence, and trip copilot surfaces. Register new i18n namespaces (autopilot, chargeQueue, ocpp) so the strict namespace audit and Docker web build pass. Fix TypeScript i18n count types, geofence hook typing, and AutomationFull.conflicts. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> * feat(charging): add charge autopilot Add per-vehicle autopilot profiles, TOU-based charge previews, health guardrails, and savings tracking. Integrate the configuration and preview panel into Smart Charge with API and UI tests. * feat: expand charging and automation insights Add next-charge recommendations comparing home TOU costs with Supercharger quotes, surfaced on dashboards and vehicle details. Expand automation, routine, and alert template catalogs with category filtering, localization, and tests. * Expand automation and alert templates Adds ecosystem automation presets and routine templates covering more Tesla commands, locations, charging, climate, media, and security scenarios. Updates catalogue tests and alert rule template coverage thresholds for the expanded preset set. * feat: storm guardian severe-weather auto-prep Watches Open-Meteo forecasts at each armed vehicle's home coords and pre-charges before storms: hourly evaluator raises the charge limit on fresh warnings when SOC is below target. Includes status/config/events API, StormGuardPanel on Emergency Resilience, and backend+UI tests. * feat: cabin comfort autopilot with calendar-aware preconditioning Polls a per-vehicle ICS subscription, finds the next offsite event in the lead window, and preconditions once per event (5-minute evaluator). Includes next/config/now/runs API, ComfortPanel on Automations, offline refusal for the actuation endpoint, and backend+UI tests. * feat: warranty claim autopilot drafts service tickets BuildClaimDraft assembles a ready-to-paste ticket from the owner issue, live warranty countdown, matched TSBs, ranked symptoms, and evidence. New claim-draft endpoint, ClaimDraftPanel on Service Intelligence, and backend+UI tests. * feat: ghost-driver alerting for unknown-driver drives Flags recent drives that fit no named profile and sit far from their cluster centroid (median-adaptive score, deterministic pure function). New GET /driver-attribution/ghost-drives endpoint plus a GhostDrivesPanel on the Driver Attribution page with alert banner, score table, and one-click labelling that re-anchors the cluster. * feat: supercharger wait-time oracle from fleet history Predicts queue waits per site and arrival time: hour-of-week demand from tesla_charging_sessions feeds Little's-law load plus an Erlang-C queue model (stalls estimated from peak overlap, documented lower bound). Read-only GET /waitoracle/sites + /forecast; WaitOraclePanel on the fleet sessions page with site/arrival pickers, verdict hero, best-hour suggestion, and the full-day wait curve. * fix(fsd): accept quantized FSD mileage ticks Allow one Tesla 1-mile wire quantum above the physical travel threshold so valid 10-second counter samples are retained, while still rejecting implausible jumps. Add unit and drive analytics regression coverage. * fix: align wait-oracle, ghost, claim, comfort, storm with conventions Route new panels through Icons, SI seconds for wait forecasts, queryPolicy/scopedPath on hooks, ICS host allowlist, catalog i18n keys, and useDataState fatalError surfaces. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> * feat(journey): trip sessions with status machine and versioned plans Slice 1 of Journey Autopilot: persistent journey_sessions (planned/active/paused/completed/aborted, one active per vehicle, race-safe conditional transitions) plus append-only versioned plans for future replan diffs. New /journeys page with session manager: plan form, status filter, lifecycle actions driven by server next_statuses, plan history. Also regenerates routetemplates_gen.go, absorbing 19 previously unregenerated routes so the freshness gate passes. * docs: redesign site and add feature catalogue Refresh the VitePress theme, navigation, landing pages, and onboarding. Add generated screen catalogues, Markdown page tools, and new homepage visuals. * fix(journey): clamp limits and localize status Cap journey list limits at 100 with safe defaults and tests. Localize status labels and inherit theme-aware icon colors. * feat(i18n): add journey status labels Add English translations for planned, active, paused, completed, and aborted journey statuses. * test(trips): align journey panel i18n Update localized JourneyPanel assertions and align journey namespace ordering in English manifests. * refactor: tighten package boundaries Extract weekly FSD digest logic from the API package, remove unused helpers, document migrations 235–242, clean up translations and lint findings, and refresh gRPC and telemetry dependencies. * chore: document packages and update grpc Adds package documentation and layer annotations, upgrades gRPC to v1.83.2, and removes an unused React test import. * fix(ci): empty-state audit exemptions and Gitleaks policy fixture mount EmptyState CTA audit now passes with documented no-action comments. Gitleaks policy self-test writes fixtures under the workspace and scans directories so Docker bind-mounts work on self-hosted runners. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> * fix(ci): arch ratchet, chart-legend, CodeQL node, visual snapshots Move fleet state handler into handler/v1/fleetstate so internal/handler/v1 stays under the max_files ratchet. Waive SharedSessionReport legend toggle. Install Node before CodeQL JS extraction. Refresh Windows visual baselines from the failing Playwright actuals. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> * fix(ci): restore CodeQL SHA pin and run SI gate on ubuntu-latest Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> * fix(ci): run SI canonical gate on push so the required workflow has jobs Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> * fix(web): classify new mutation hooks for live-mode audit Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> * fix(web): waive FSD observatory pagination in virtualization audit Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> * fix(web): unblock frontend vitest QueryClient, breadcrumbs, and panel tests Stub chart annotation hooks globally, parent Tesla Physics nested routes, and keep ChartContainer/page tests from requiring a QueryClient. Align Power Flow / Temperature Impact / Ghost Drives tests with current UI and surface ghost-scan errors instead of an empty table. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> * fix(web): show warranty claim draft when query data is present Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> * fix(web): restore i18n provider and annotation hook tests under global stubs Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> * fix(web): unblock remaining frontend vitest failures Clamp Intl fraction digits to 0-20, add a no-op toast fallback when ToastProvider is missing, unique Smart Charge field ids, catalog /journeys, and test matchers for Beta/required labels/driver payload. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> * fix(ci): stop si-canonical-gate 0s push failures Drop the push trigger (matches main) and only read runner input on workflow_dispatch so GitHub does not reject the workflow file. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> * fix(ci): run si-canonical-gate on push with a valid runner Keep the push trigger so required checks fire, but never read inputs.runner except on workflow_dispatch. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> * fix(ci): always run si-canonical-gate on push and PR Required checks plus path filters produced 0-job workflow-file failures. Run on every push/PR with ubuntu-latest so the job starts. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> * fix(ci): move SI canonical gate Python out of invalid YAML Unindented heredocs made GitHub treat the workflow as a file issue (0 jobs). Run the checks from .github/scripts/si_canonical_gate.py. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> * fix(ci): repair span-budget, proto-gen, and load-test gates Enable CGO for -race on ubuntu-latest, drop make from proto-gen-check, and capture teslasync-api logs in the nightly k6 job. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> * fix(ci): run k6 on host network so load-test reaches the API grafana/k6-action isolated localhost from compose-published :8080. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> * fix(ci): treat 4xx as smoke-ok and write k6 summary in script cwd Unauthenticated CI hits ForwardAuth 401/403; only 5xx should fail api_errors. Write summary.json next to the script so the k6 container can persist it. * fix(ci): persist k6 summary.json with host uid on bind mount The grafana/k6 image is non-root, so handleSummary could not write tests/k6/summary.json and the artifact upload warned with no files. * feat(journey): stop scoring on wait, price, health, corridor Slice 2 of Journey Autopilot: POST /journey/sessions/{id}/score-stops ranks caller-nominated candidates using wait-oracle waits, realized per-site invoice pricing, peak-kW stall consistency, and straight-line corridor deviation, with per-signal renormalization when feeds are thin. Rankings persist as plan versions. StopScorePanel in the journey detail drives it from the fleet site directory. Resolves the stash-pop conflict in handler.go keeping both sides (upstream clampListLimit + NewSession conversion, slice-2 scorer). * feat(journey): departure advisor and ready-to-roll checklist Slice 3 of Journey Autopilot: GET .../departure ranks hourly slots on storm severity at the origin (new stormguard.HourLevel so both surfaces agree) with live charge context; POST .../checklist/runs evaluates charge level/limit, tire pressures, recent storm events, and software-update state from live telemetry, persisting append-only runs for the debrief. DeparturePanel + ChecklistPanel join the journey detail; 404-never-ran renders an empty state, not an error. * feat(journey): live trip session with trail checkpoints and glanceable view Slice 4: POST checkpoints (live-telemetry backfill, idempotent retry) and GET live snapshot (straight-line progress, energy-vs-distance range verdict, head of scored plan, 20-point trail) plus LiveTripPanel with check-in. * feat(journey): replan engine with deviation verdict and one-click rescore Slice 5: GET replan assesses cross-track deviation (on_track/drifted/off_route at 2/10 km) and POST replan re-ranks the saved candidates from the latest fix with waits as of now, persisting a replan version. ScoreStops now echoes rescorable candidates; live next-stop reads replan plans and picks by max version. UI gains ReplanPanel plus a shared StopScoreTable extracted verbatim from StopScorePanel. * feat(journey): arrival prep with pace ETA and destination charge advice Slice 6: GET arrival derives pace from the two newest fixes (odometer preferred, GPS-jump guarded), projects ETA only while moving, and grades destination energy with a top-up shortfall that restores the buffer. UI gains ArrivalPanel on live sessions; check-ins invalidate arrival. * feat(journey): trip report card debrief Slice 7: GET report computes the debrief card from the trail (odometer-span distance, started/ended duration, detour ratio vs the straight line, replan counts, checklist recap). UI gains ReportPanel on finished sessions; check-ins and replans invalidate the card. * feat(journey): leave-now nudge from calm slots and blockers Slice 8: GET nudge folds the calm-hour ranking and action-level checklist blockers into one verdict (leave_now/wait/delay/unknown) for planned sessions. UI gains NudgePanel; checklist refreshes invalidate the nudge. * feat(journey): route learning adjusts ETA and debrief Slice 9: RouteLegs reads odometer-backed detour legs from completed trips on a route (both directions); RouteFactor averages 2+ trips into a 1.0-2.0 multiplier that scales arrival ETA and charge advice and shows on the report card. No migration: derived from sessions plus checkpoints. * feat(journey): offline check-in outbox with reconnect replay Slice 10: taps while offline (or sends failing without a status) queue in localStorage and replay in order with original instants on reconnect; the server dedupes idempotently. useCheckIn takes an optional recorded_at and stays silent on network failures by contract; LiveTripPanel shows the queued count. * refactor(trips): remove obsolete journey strings Prune unused live-trip, replanning, arrival, report, and toast translations. Standardize stop-score cells on shared typography and pass route-trip counts directly to interpolation. * fix(journey): SI identifiers and ops migration manifest Rename scored-stop unit_price JSON and chargeNeed UI state so the SI-canonical gate stops treating new kWh suffixes as legacy units. Register 000243/000244 in the ops migration manifest. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> * fix(web): exempt journey EmptyStates from CTA audit Check-in, checklist run, and site-sync are already on the panels; the empty copy is informational. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> * fix(web): give journey empty states real CTAs Wire EmptyState actions for checklist run, live check-in, charging history, and plan-journey instead of audit exemption comments. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> * fix(web): narrow checklist run before rendering items Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> * fix(web): classify journey mutations for live-mode audit Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> * fix(web): align DeparturePanel tests with render and hook args Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --------- Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
1 parent 1dcf3de commit 96efa6c

60 files changed

Lines changed: 8602 additions & 49 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

internal/api/journey/arrival.go

Lines changed: 263 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,263 @@
1+
package journey
2+
3+
import (
4+
"context"
5+
"net/http"
6+
"strconv"
7+
"time"
8+
9+
"github.com/rs/zerolog/log"
10+
11+
"github.com/ev-dev-labs/teslasync/internal/api/httpx"
12+
)
13+
14+
// Pace bounds in SI m/s. Below stopMS the car reads as parked (no
15+
// ETA — a stopped car has none); above implausibleMS the fix pair is
16+
// a GPS jump, not motion (~360 km/h).
17+
const (
18+
stopMS = 2.0
19+
implausibleMS = 100.0
20+
)
21+
22+
// Arrival is the GET response: ETA from recent pace plus the charge
23+
// advice for making the destination with buffer. LeftM stays the
24+
// straight-line remainder; ETA and advice apply the learned route
25+
// factor when history exists.
26+
type Arrival struct {
27+
SessionID int64 `json:"session_id"`
28+
DestName string `json:"dest_name"`
29+
LeftM *float64 `json:"left_m"`
30+
PaceMS *float64 `json:"pace_ms"`
31+
EtaAt *time.Time `json:"eta_at"`
32+
Moving bool `json:"moving"`
33+
Verdict string `json:"verdict"` // ok, attention, action, unknown
34+
ShortfallWh *float64 `json:"shortfall_wh"`
35+
RouteFactor *float64 `json:"route_factor"`
36+
RouteTrips int `json:"route_trips"`
37+
Evidence []string `json:"evidence"`
38+
}
39+
40+
// PaceMS derives speed from two fixes. Odometer delta wins when both
41+
// fixes carry one (road truth beats coordinates); otherwise the
42+
// haversine gap over elapsed time. Zero/negative time, odometer
43+
// rollback, and implausible speeds all read as no pace. Pure.
44+
func PaceMS(older, newer *Checkpoint) (float64, bool) {
45+
if older == nil || newer == nil {
46+
return 0, false
47+
}
48+
dt := newer.RecordedAt.Sub(older.RecordedAt).Seconds()
49+
if dt <= 0 {
50+
return 0, false
51+
}
52+
dist := haversineM(older.Lat, older.Lng, newer.Lat, newer.Lng)
53+
if older.OdometerM != nil && newer.OdometerM != nil {
54+
if *newer.OdometerM < *older.OdometerM {
55+
return 0, false
56+
}
57+
dist = *newer.OdometerM - *older.OdometerM
58+
}
59+
pace := dist / dt
60+
if pace < 0 || pace > implausibleMS {
61+
return 0, false
62+
}
63+
return pace, true
64+
}
65+
66+
// ArrivalETA projects arrival from distance left and pace. A stopped
67+
// car (below stopMS) has no ETA — moving=false, eta nil. Pure.
68+
func ArrivalETA(leftM, paceMS float64, now time.Time) (eta *time.Time, moving bool) {
69+
if paceMS < stopMS || leftM <= 0 {
70+
return nil, paceMS >= stopMS
71+
}
72+
t := now.Add(time.Duration(leftM / paceMS * float64(time.Second)))
73+
return &t, true
74+
}
75+
76+
// ChargeAdvice grades destination energy (via ComputeRange, the single
77+
// verdict source) and sizes the top-up that restores the buffer when
78+
// short. Shortfall is nil when energy already covers need×buffer or
79+
// when inputs are missing. Pure.
80+
func ChargeAdvice(haveWh *float64, leftM float64, effWhKm *float64) (verdict string, shortfallWh *float64) {
81+
r := ComputeRange(haveWh, leftM, effWhKm)
82+
if r.Verdict == ItemOK || r.NeedWh == nil || haveWh == nil {
83+
return r.Verdict, nil
84+
}
85+
short := *r.NeedWh*rangeBuffer - *haveWh
86+
if short <= 0 {
87+
return r.Verdict, nil
88+
}
89+
return r.Verdict, &short
90+
}
91+
92+
// ArrivalHandler serves arrival prep. Stateless beyond constructor
93+
// inputs; safe for concurrent use.
94+
type ArrivalHandler struct {
95+
store SessionStore
96+
trail TrailStore
97+
live LiveSignals
98+
now func() time.Time
99+
}
100+
101+
// NewArrivalHandler wires the handler. Panics on nil inputs (fail-fast
102+
// wiring contract, matching sibling handlers).
103+
func NewArrivalHandler(store SessionStore, trail TrailStore, live LiveSignals) *ArrivalHandler {
104+
if store == nil || trail == nil || live == nil {
105+
panic("journey: nil dependency")
106+
}
107+
return &ArrivalHandler{store: store, trail: trail, live: live, now: time.Now}
108+
}
109+
110+
// Prep serves GET /journey/sessions/{id}/arrival: ETA from recent pace
111+
// plus the charge advice for the destination. Degrades honestly — no
112+
// fixes, no pace, or no energy each narrow the answer instead of
113+
// failing it.
114+
func (h *ArrivalHandler) Prep(w http.ResponseWriter, r *http.Request) {
115+
id, err := sessionIDParam(r)
116+
if err != nil {
117+
httpx.WriteError(w, http.StatusBadRequest, err.Error())
118+
return
119+
}
120+
ctx := r.Context()
121+
session, err := h.store.Get(ctx, id)
122+
if err != nil {
123+
log.Error().Err(err).Int64("id", id).Msg("journey: get failed")
124+
httpx.WriteError(w, http.StatusInternalServerError, "failed to read journey")
125+
return
126+
}
127+
if session == nil {
128+
httpx.WriteError(w, http.StatusNotFound, "journey not found")
129+
return
130+
}
131+
now := h.now().UTC()
132+
latest, err := h.trail.LatestCheckpoint(ctx, id)
133+
if err != nil {
134+
log.Error().Err(err).Int64("id", id).Msg("journey: latest checkpoint failed")
135+
httpx.WriteError(w, http.StatusInternalServerError, "failed to read trail")
136+
return
137+
}
138+
progress := ComputeProgress(session.OriginLat, session.OriginLng, session.DestLat, session.DestLng, latest)
139+
pace, paceOK, err := h.pace(ctx, id)
140+
if err != nil {
141+
log.Error().Err(err).Int64("id", id).Msg("journey: trail failed")
142+
httpx.WriteError(w, http.StatusInternalServerError, "failed to read trail")
143+
return
144+
}
145+
var left *float64
146+
if progress != nil {
147+
left = &progress.LeftM
148+
}
149+
factor, trips, err := routeFactorFor(ctx, h.trail, session)
150+
if err != nil {
151+
log.Error().Err(err).Int64("id", id).Msg("journey: route history failed")
152+
httpx.WriteError(w, http.StatusInternalServerError, "failed to read route history")
153+
return
154+
}
155+
effLeft := left
156+
if left != nil && factor != nil {
157+
adjusted := *left * *factor
158+
effLeft = &adjusted
159+
}
160+
var eta *time.Time
161+
moving := false
162+
if effLeft != nil && paceOK {
163+
eta, moving = ArrivalETA(*effLeft, pace, now)
164+
} else if paceOK {
165+
_, moving = ArrivalETA(1, pace, now)
166+
}
167+
verdict, shortfall, err := h.advice(ctx, session, effLeft)
168+
if err != nil {
169+
log.Error().Err(err).Int64("id", id).Msg("journey: arrival advice failed")
170+
httpx.WriteError(w, http.StatusInternalServerError, "failed to read vehicle state")
171+
return
172+
}
173+
out := Arrival{
174+
SessionID: id, DestName: session.DestName, LeftM: left,
175+
EtaAt: eta, Moving: moving, Verdict: verdict, ShortfallWh: shortfall,
176+
RouteFactor: factor, RouteTrips: trips,
177+
}
178+
if paceOK {
179+
out.PaceMS = &pace
180+
}
181+
out.Evidence = arrivalEvidence(session, left, out.PaceMS, eta, moving, verdict, shortfall, factor, trips)
182+
httpx.WriteJSON(w, http.StatusOK, out)
183+
}
184+
185+
// pace orders the two newest fixes by time (stores order either way)
186+
// and derives speed. False when fewer than two fixes exist.
187+
func (h *ArrivalHandler) pace(ctx context.Context, sessionID int64) (float64, bool, error) {
188+
pair, err := h.trail.Trail(ctx, sessionID, 2)
189+
if err != nil {
190+
return 0, false, err
191+
}
192+
if len(pair) < 2 {
193+
return 0, false, nil
194+
}
195+
older, newer := pair[0], pair[1]
196+
if newer.RecordedAt.Before(older.RecordedAt) {
197+
older, newer = newer, older
198+
}
199+
pace, ok := PaceMS(older, newer)
200+
return pace, ok, nil
201+
}
202+
203+
func (h *ArrivalHandler) advice(ctx context.Context, session *Session, left *float64) (string, *float64, error) {
204+
if left == nil {
205+
return ItemUnknown, nil, nil
206+
}
207+
energyKWh, err := signalFloat(h.live, ctx, session.VehicleID, "EnergyRemaining")
208+
if err != nil {
209+
return "", nil, err
210+
}
211+
var haveWh *float64
212+
if energyKWh != nil {
213+
have := *energyKWh * 1000
214+
haveWh = &have
215+
}
216+
eff, ok, err := h.trail.VehicleEfficiency(ctx, session.VehicleID)
217+
if err != nil {
218+
return "", nil, err
219+
}
220+
var effPtr *float64
221+
if ok {
222+
effPtr = &eff
223+
}
224+
verdict, shortfall := ChargeAdvice(haveWh, *left, effPtr)
225+
return verdict, shortfall, nil
226+
}
227+
228+
func arrivalEvidence(session *Session, left, pace *float64, eta *time.Time, moving bool, verdict string, shortfall *float64, factor *float64, trips int) []string {
229+
out := []string{}
230+
dest := session.DestName
231+
if dest == "" {
232+
dest = "the destination"
233+
}
234+
if left == nil {
235+
out = append(out, "route coordinates missing — distance to "+dest+" unavailable")
236+
} else {
237+
out = append(out, formatKm("", *left/1000)+" to "+dest)
238+
}
239+
if factor != nil {
240+
out = append(out, "adjusted by your "+strconv.FormatFloat(*factor, 'f', 2, 64)+"× history on this route ("+strconv.Itoa(trips)+" trips)")
241+
}
242+
switch {
243+
case pace == nil:
244+
out = append(out, "need two fixes to read pace")
245+
case !moving:
246+
out = append(out, "parked — ETA once moving")
247+
case eta != nil:
248+
out = append(out, "ETA "+eta.Format("15:04"))
249+
}
250+
switch verdict {
251+
case ItemOK:
252+
out = append(out, "arrive with buffer")
253+
case ItemAttention, ItemAction:
254+
if shortfall != nil {
255+
out = append(out, "top up ≈ "+strconv.FormatFloat(*shortfall/1000, 'f', 1, 64)+" kWh en route to hold the buffer")
256+
} else {
257+
out = append(out, "arrival energy tight — charge soon")
258+
}
259+
default:
260+
out = append(out, "arrival energy unknown: needs live energy + drive history")
261+
}
262+
return out
263+
}

0 commit comments

Comments
 (0)