import { isLoggedIn } from "/js/auth.js";
import { onRouteChanged, requestReroute, notifyRouteProgress } from "/js/panels.js";
import { elevationAt } from "/js/dem.js";
// The car's dashboard over the map, off the CAN signals (GET /api/can,
// names from data/can.json): one inclinometer — compass ring around a rear
// view (roll) and a side view (pitch) — and the speed. Which widgets show
// is per device (localStorage); levelling is the node's own (its offsets,
// set from /can.html). Turn signals / brake: when they're on the bus.
// Heading: driving, the GNSS course (from consecutive fixes); standing
// still, the compass (imu.heading, once the node sends it) — else the
// last course stays, dimmed.
const SIGNALS = { pitch: "imu.pitch", roll: "imu.roll", heading: "imu.heading", speed: "gnss.speed", alt: "gnss.alt", lat: "gnss.lat", lon: "gnss.lon", hdop: "gnss.hdop" };
const MOVING_MS = 1.5; // m/s: above this the GNSS course counts
const COURSE_MIN_M = 5; // fixes closer than this: too noisy for a course
const POLL_MS = 500;
// Simulated tilt: the terrain's slope along the course (pitch) and across
// it (roll), from the DEM 2·TILT_HALF_M apart — the terrain, not the road:
// a road cut into a hillside is flatter across than this reads.
const TILT_ZOOM = 12; // ~20–40 m pixels (offline terrain goes to 13)
const TILT_HALF_M = 15;
const STALE_S = 5; // older signal: shown as missing
const WARN = { roll: 20, pitch: 25 }; // ° — amber past these, red past 1.5×
const STORE_KEY = "maptool.dashboard";
// Navigation (the speed limit, what's ahead): along the route panel's route
// while on it (its speed_limits / signals / maneuvers from /api/route),
// else the limit of the road being driven (POST /api/road, map-matched).
const OVER_KMH = 3; // over the limit by more than this: warning
// Off the route → rerouting, after Ferrostar's split: deviation detected
// (farther than ON_ROUTE_M for OFF_ROUTE_FIXES fixes in a row, fixes with an
// HDOP over MAX_HDOP don't count), then a new route from the position to
// the points not reached yet — at most every REROUTE_EVERY_MS, only moving.
const ON_ROUTE_M = 30; // farther from the route line: off it
const OFF_ROUTE_FIXES = 3;
const MAX_HDOP = 5; // ~ over 10 m off at the NEO-6M's few m UERE
const REROUTE_EVERY_MS = 15000;
const ROAD_EVERY_MS = 4000; // /api/road at most this often, only while moving
const TRACE_STEP_M = 10; // fixes kept for /api/road at least this far apart
const LANES_AHEAD_M = 1000; // the next maneuver's lanes from this close
const DEFAULT_WIDGETS = { inclinometer: true, speed: true, altitude: true, navigation: true, banner: true };
const THEN_M = 300; // the maneuver after the next one shown with it when it follows this closely
const DEFAULT_OPACITY = 0.45; // the card's background, the map shows through
const load = () => {
try { const saved = JSON.parse(localStorage.getItem(STORE_KEY)) || {}; return { ...saved, widgets: { ...DEFAULT_WIDGETS, ...saved.widgets } }; }
catch { return { widgets: { ...DEFAULT_WIDGETS } }; }
};
const RAD = Math.PI / 180;
// meters between two [lon, lat] (equirectangular: fine at these distances)
const meters = ([lon1, lat1], [lon2, lat2]) => Math.hypot((lon2 - lon1) * Math.cos(((lat1 + lat2) / 2) * RAD), lat2 - lat1) * 111320;
const distance = (m) => (m >= 1000 ? `${(m / 1000).toFixed(1)} km` : `${Math.round(m / 10) * 10} m`);
const esc = (text) => String(text ?? "").replace(/[&<>"]/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """ })[c]);
// An arrow from the bottom center turning by `angle` (° from straight on),
// in a 24 × 32 box: a lane's, and the banner's maneuver.
function arrowPath(angle, cls) {
const a = (angle * Math.PI) / 180;
const [x, y] = [12 + 9 * Math.sin(a), 15 - 9 * Math.cos(a)];
const back = (side) => `${(x - 5 * Math.sin(a + side)).toFixed(1)} ${(y + 5 * Math.cos(a + side)).toFixed(1)}`;
return ` `;
}
const uturnPath = (cls) => ` `;
// Valhalla's maneuver types (its API docs) → the banner's arrow angle;
// "uturn", "arrive", "roundabout" drawn their own way.
const MANEUVER_ANGLES = { 1: 0, 2: 45, 3: -45, 7: 0, 8: 0, 9: 45, 10: 90, 11: 135, 14: -135, 15: -90, 16: -45, 17: 0, 18: 45, 19: -45,
20: 45, 21: -45, 22: 0, 23: 30, 24: -30, 25: 0, 37: 30, 38: -30 };
function maneuverSvg(type) {
let body;
if (type === 12 || type === 13) body = uturnPath("dash-banner__arrow");
else if (type >= 4 && type <= 6) body = ` `; // a flag: arriving
else if (type === 26 || type === 27) body = ` `;
else body = arrowPath(MANEUVER_ANGLES[type] ?? 0, "dash-banner__arrow");
return `${body} `;
}
// Valhalla's lane direction bits → the arrow's angle (° from straight on)
const LANE_ANGLES = { 2: 0, 16: -45, 8: -90, 4: -135, 32: 45, 64: 90, 128: 135, 512: -25, 1024: 25 };
const LANE_REVERSE = 256;
// One lane as an SVG: an arrow per direction it allows; `active` (the
// directions to take, a bitmask too) drawn bold.
function laneSvg({ directions, active = 0 }) {
const arrow = (bit) => {
const cls = `dash-lane__arrow${active & bit ? " dash-lane__take" : ""}`;
return bit === LANE_REVERSE ? uturnPath(cls) : arrowPath(LANE_ANGLES[bit], cls);
};
const bits = [2, 16, 8, 4, 32, 64, 128, 512, 1024, LANE_REVERSE].filter((bit) => directions & bit);
return `${(bits.length ? bits : [2]).map(arrow).join("")} `;
}
// A route prepared for "where am I on it": km at every vertex, maneuvers' start km.
function prepareRoute(route) {
if (!route?.properties?.speed_limits) return null;
const coords = route.geometry.coordinates;
const km = [0];
for (let i = 1; i < coords.length; i++) km.push(km[i - 1] + meters(coords[i - 1], coords[i]) / 1000);
let start = 0;
const maneuvers = route.properties.maneuvers.map((m) => { const at = start; start += m.km; return { ...m, at }; });
let leg = 0;
const viaKm = (route.properties.legs_km || []).slice(0, -1).map((length) => (leg += length)); // km at each via point
return { coords, km, limits: route.properties.speed_limits, signals: route.properties.signals || [], maneuvers, viaKm };
}
// Nearest point on the route: [km along it, meters off it]. Near the last
// one first (fromKm: LOCATE_BACK_KM behind to LOCATE_AHEAD_KM ahead), so a
// route that comes back along the same road or crosses itself doesn't jump
// to the other pass — progress goes forward, as Ferrostar's does; the whole
// route only when that window has nothing close (a reroute, a restart).
const LOCATE_BACK_KM = 0.1;
const LOCATE_AHEAD_KM = 3;
function locate(route, position, fromKm = null) {
if (fromKm != null) {
const near = locateIn(route, position, fromKm - LOCATE_BACK_KM, fromKm + LOCATE_AHEAD_KM);
if (near[1] <= ON_ROUTE_M) return near;
}
return locateIn(route, position, -Infinity, Infinity);
}
function locateIn(route, position, fromKm, toKm) {
let best = [0, Infinity];
const { coords, km } = route;
const cos = Math.cos(position[1] * RAD);
for (let i = 1; i < coords.length; i++) {
if (km[i] < fromKm || km[i - 1] > toKm) continue;
const [ax, ay] = [coords[i - 1][0] * cos, coords[i - 1][1]];
const [bx, by] = [coords[i][0] * cos, coords[i][1]];
const [px, py] = [position[0] * cos, position[1]];
const len2 = (bx - ax) ** 2 + (by - ay) ** 2;
const t = len2 ? Math.max(0, Math.min(1, ((px - ax) * (bx - ax) + (py - ay) * (by - ay)) / len2)) : 0;
const off = Math.hypot(px - (ax + t * (bx - ax)), py - (ay + t * (by - ay))) * 111320;
if (off < best[1]) best = [km[i - 1] + t * (km[i] - km[i - 1]), off];
}
return best;
}
const ticks = Array.from({ length: 36 }, (_, i) => {
const a = i * 10;
const long = a % 30 === 0;
return ` `;
}).join("");
const labels = ["N", "E", "S", "W"].map((l, i) => `${l} `).join("");
const INCLINOMETER = `
${ticks}${labels}
roll
pitch
`;
export class DashboardControl {
constructor(map) {
this._map = map;
this._settings = load();
this._timer = null;
this._values = {};
this._fix = null; // last fix a course was measured from
this._course = null;
this._route = prepareRoute(onRouteChanged((route) => {
this._route = prepareRoute(route);
this._lastAt = 0;
this._offFixes = 0;
this._sentKm = undefined; // the new route drawn by the next fix
}));
this._trace = []; // [lon, lat] fixes TRACE_STEP_M apart, for /api/road
this._road = null; // its last answer
this._roadAt = 0;
this._lastAt = 0; // km along the route at the last fix on it
this._offFixes = 0;
this._rerouteAt = 0;
}
// What the simulation doesn't send, from the terrain at its position: the
// altitude, and pitch / roll in degrees (nose up and right side down
// positive, as the inclinometer draws them) — unless a node sends them.
async _simulateTerrain() {
const { lat, lon } = this._values;
if (lat == null) return;
this._offlineTerrain ??= fetch("/api/terrain-tiles").then((r) => r.json()).then((d) => d.available).catch(() => false);
const offline = await this._offlineTerrain;
const rad = Math.PI / 180;
const at = (bearing) => {
const dx = TILT_HALF_M * Math.sin(bearing * rad);
const dy = TILT_HALF_M * Math.cos(bearing * rad);
return elevationAt(lon + dx / (111320 * Math.cos(lat * rad)), lat + dy / 111320, offline, { zoom: TILT_ZOOM, smooth: true });
};
if (this._values.alt == null) {
this._values.alt = await elevationAt(lon, lat, offline, { zoom: TILT_ZOOM, smooth: true });
}
if (this._course == null || this._values.pitch != null || this._values.roll != null) return;
const [front, back, right, left] = await Promise.all([0, 180, 90, 270].map((b) => at(this._course + b)));
if ([front, back, right, left].includes(null)) return;
const deg = (rise) => Math.atan(rise / (2 * TILT_HALF_M)) / rad;
this._values.pitch = deg(front - back);
this._values.roll = deg(left - right);
}
// To the route panel (the driven part dimmed), when it moved ≥ 10 m.
_progress(km) {
if (km === this._sentKm || (km != null && this._sentKm != null && Math.abs(km - this._sentKm) < 0.01)) return;
this._sentKm = km;
notifyRouteProgress(km);
}
// The limit and what's ahead: from the route while on it, else the road.
_navigate() {
const { lat, lon, speed } = this._values;
if (lat == null || lon == null) return (this._nav = null);
const position = [lon, lat];
if (!this._trace.length || meters(this._trace.at(-1), position) >= TRACE_STEP_M) this._trace = [...this._trace.slice(-7), position];
const [at, off] = this._route ? locate(this._route, position, this._lastAt || null) : [0, Infinity];
const fresh = position.join() !== this._lastFix; // polled faster than the fixes come
this._lastFix = position.join();
if (fresh && this._route && off > ON_ROUTE_M && (this._values.hdop ?? 0) <= MAX_HDOP) this._offFixes++;
else if (off <= ON_ROUTE_M) this._offFixes = 0;
if (this._route && this._offFixes < OFF_ROUTE_FIXES) {
const { limits, signals, maneuvers } = this._route;
const current = limits.findLast(([km]) => km <= at);
const next = limits.find(([km, limit]) => km > at && limit !== current?.[1]);
const signal = signals.find(([, , km]) => km > at);
const index = maneuvers.findIndex((m) => m.at > at + 0.005);
const maneuver = maneuvers[index];
const then = maneuvers[index + 1];
const onStreet = maneuvers[index - 1]?.street; // the one being driven: the last maneuver's
if (off <= ON_ROUTE_M) {
this._lastAt = at;
this._progress(at);
}
this._nav = {
limit: current?.[1] ?? null,
next: next && { limit: next[1], m: (next[0] - at) * 1000 },
signal: signal && (signal[2] - at) * 1000,
maneuver: maneuver && { ...maneuver, m: (maneuver.at - at) * 1000 },
then: maneuver && then && then.at - maneuver.at <= THEN_M / 1000 ? then : null,
street: onStreet,
};
return;
}
this._progress(null);
this._nav = { limit: this._road?.speed_limit ?? null, offRoute: !!this._route, street: this._road?.name };
if (this._route && (speed ?? 0) >= MOVING_MS && Date.now() - this._rerouteAt >= REROUTE_EVERY_MS) {
this._rerouteAt = Date.now();
requestReroute(position, this._route.viaKm.filter((km) => km <= this._lastAt).length);
}
if ((speed ?? 0) < MOVING_MS || this._trace.length < 2 || Date.now() - this._roadAt < ROAD_EVERY_MS) return;
this._roadAt = Date.now();
fetch("/api/road", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ points: this._trace }) })
.then((response) => (response.ok ? response.json() : null))
.then((road) => { this._road = road; })
.catch(() => { this._road = null; });
}
// Course over ground from the fix COURSE_MIN_M back, while moving.
_updateCourse({ lat, lon, speed }) {
if (lat == null || lon == null) return;
if (!this._fix || speed == null || speed < MOVING_MS) {
this._fix = { lat, lon };
return;
}
const rad = Math.PI / 180;
const dLon = (lon - this._fix.lon) * rad;
const y = Math.sin(dLon) * Math.cos(lat * rad);
const x = Math.cos(this._fix.lat * rad) * Math.sin(lat * rad) - Math.sin(this._fix.lat * rad) * Math.cos(lat * rad) * Math.cos(dLon);
const north = (lat - this._fix.lat) * 111320;
const east = (lon - this._fix.lon) * 111320 * Math.cos(lat * rad);
if (Math.hypot(north, east) < COURSE_MIN_M) return;
this._course = (Math.atan2(y, x) / rad + 360) % 360;
this._fix = { lat, lon };
}
mount(li) {
li.innerHTML = `
Dashboard
`;
this._toggle = li.querySelector(".overlays-panel__toggle");
this._status = li.querySelector(".live-panel__status");
const name = li.querySelector(".overlays-panel__name");
const details = li.querySelector(".overlays-panel__details");
name.addEventListener("click", () => {
details.hidden = !details.hidden;
name.setAttribute("aria-expanded", String(!details.hidden));
});
if (!isLoggedIn()) {
this._toggle.disabled = true;
li.title = "Log in to see the car's dashboard";
return;
}
for (const box of li.querySelectorAll("[data-widget]")) {
box.checked = !!this._settings.widgets[box.dataset.widget];
box.addEventListener("change", () => {
this._settings.widgets[box.dataset.widget] = box.checked;
this._save();
this._render();
});
}
this._toggle.addEventListener("change", () => (this._toggle.checked ? this._enable() : this._disable()));
const opacity = li.querySelector(".dash-opacity");
opacity.value = this._settings.opacity ?? DEFAULT_OPACITY;
opacity.addEventListener("input", () => {
this._settings.opacity = +opacity.value;
this._save();
this._card?.style.setProperty("--dash-alpha", opacity.value);
});
}
_save() {
try { localStorage.setItem(STORE_KEY, JSON.stringify(this._settings)); } catch { /* private window: just not kept */ }
}
_enable() {
this._card = document.createElement("div");
this._card.className = "dash-card";
this._card.style.setProperty("--dash-alpha", this._settings.opacity ?? DEFAULT_OPACITY);
this._card.innerHTML = `${INCLINOMETER} km/h
m
`;
this._map.getContainer().appendChild(this._card);
// the next turn across the top, as in a car navigation
this._banner = document.createElement("div");
this._banner.className = "dash-banner";
this._banner.hidden = true;
this._map.getContainer().appendChild(this._banner);
this._status.hidden = false;
this._status.textContent = "Connecting…";
this._poll();
}
_disable() {
this._progress(null);
clearTimeout(this._timer);
this._timer = null;
this._card?.remove();
this._card = null;
this._banner?.remove();
this._banner = null;
this._status.hidden = true;
}
async _poll() {
try {
const response = await fetch("/api/can", { cache: "no-store" });
if (!response.ok) throw new Error(`HTTP ${response.status}`);
const data = await response.json();
const now = Date.parse(response.headers.get("Date")) / 1000 || Date.now() / 1000;
this._values = Object.fromEntries(Object.entries(SIGNALS).map(([key, name]) => {
const s = data.signals[name];
// Date has 1 s resolution: +1 so a fresh value isn't "stale"
return [key, s && now - s.at < STALE_S + 1 ? s.value : null];
}));
this._updateCourse(this._values);
this._simRunning = !!data.simulated; // /sim.html runs it
if (this._simRunning) await this._simulateTerrain();
this._navigate();
this._status.textContent = this._simRunning ? "Simulated GNSS" : data.available ? "" : "CAN is off on this server";
this._status.hidden = !this._status.textContent;
} catch (e) {
this._values = {};
this._status.hidden = false;
this._status.textContent = `Can't reach the server: ${e.message}`;
}
this._render();
if (this._card) this._timer = setTimeout(() => this._poll(), POLL_MS);
}
_render() {
if (!this._card) return;
const { widgets } = this._settings;
const v = this._values;
const svg = this._card.querySelector(".dash-incl");
svg.style.display = widgets.inclinometer ? "" : "none";
const speed = this._card.querySelector(".dash-speed");
speed.style.display = widgets.speed ? "" : "none";
const nav = this._card.querySelector(".dash-nav");
nav.style.display = widgets.navigation ? "" : "none";
const alt = this._card.querySelector(".dash-alt");
alt.style.display = widgets.altitude ? "" : "none";
alt.querySelector("span").textContent = v.alt == null ? "—" : Math.round(v.alt);
this._card.hidden = !widgets.inclinometer && !widgets.speed && !widgets.altitude && !widgets.navigation;
this._renderNav(nav);
this._renderBanner();
const severity = (key, value) => (value == null ? "" : Math.abs(value) >= WARN[key] * 1.5 ? "dash-bad" : Math.abs(value) >= WARN[key] ? "dash-warn" : "");
for (const key of ["roll", "pitch"]) {
const value = v[key];
// the pitch car faces right: nose up = counter-clockwise
svg.querySelector(`.dash-${key}`).setAttribute("transform", `rotate(${value == null ? 0 : key === "pitch" ? -value : value})`);
const text = svg.querySelector(`.dash-${key}-value`);
text.textContent = value == null ? "—" : `${value > 0 ? "+" : ""}${Math.round(value)}°`;
text.setAttribute("class", `dash-value dash-${key}-value ${severity(key, value)}`);
}
const moving = v.speed != null && v.speed >= MOVING_MS;
const heading = moving ? this._course ?? v.heading : v.heading ?? this._course;
const live = heading != null && (moving ? this._course != null : v.heading != null);
svg.querySelector(".dash-ring").setAttribute("transform", `rotate(${heading == null ? 0 : -heading})`);
svg.querySelector(".dash-ring").style.opacity = heading == null ? 0.3 : live ? 1 : 0.55;
svg.querySelector(".dash-heading").textContent = heading == null ? "" : `${Math.round((heading + 360) % 360)}°`;
speed.querySelector("span").textContent = v.speed == null ? "—" : Math.round(v.speed * 3.6);
}
_renderNav(nav) {
const n = this._nav;
const limit = n?.limit;
const kmh = this._values.speed == null ? null : this._values.speed * 3.6;
const over = typeof limit === "number" && kmh != null && kmh > limit + OVER_KMH;
this._card.classList.toggle("dash-card--over", over);
const sign = nav.querySelector(".dash-limit");
sign.hidden = limit == null;
sign.className = `dash-limit${limit === "unlimited" ? " dash-limit--none" : ""}`;
sign.textContent = typeof limit === "number" ? limit : "";
const rows = [];
if (n?.offRoute) rows.push(`Off the route — rerouting
`);
if (n?.next) rows.push(`${typeof n.next.limit === "number" ? n.next.limit : n.next.limit ? "" : "?"} in ${distance(n.next.m)}
`);
if (n?.signal != null) rows.push(` ${distance(n.signal)}
`);
if (n?.maneuver && !this._settings.widgets.banner) {
const { text, m, lanes } = n.maneuver;
rows.push(`${distance(m)} · ${esc(text)}
`);
if (lanes && m <= LANES_AHEAD_M) {
rows.push(`${lanes.map(laneSvg).join("")}
`);
}
}
nav.querySelector(".dash-ahead").innerHTML = rows.join("");
}
// Across the top: the next maneuver's arrow, distance and street (its
// instruction when it has no street), "then …" when the one after follows
// closely, its lanes from LANES_AHEAD_M, and the street being driven.
_renderBanner() {
const n = this._nav;
const show = this._settings.widgets.banner && !!n?.maneuver;
this._banner.hidden = !show;
if (!show) return;
this._banner.style.setProperty("--dash-alpha", Math.max(0.8, this._settings.opacity ?? DEFAULT_OPACITY));
const { m, type, street, text, exit, lanes } = n.maneuver;
const what = street ? `${exit ? `${exit}. exit · ` : ""}${esc(street)}` : esc(text);
const then = n.then ? `then ${maneuverSvg(n.then.type)} ${esc(n.then.street || n.then.text)}
` : "";
const lanesRow = lanes && m <= LANES_AHEAD_M ? `${lanes.map(laneSvg).join("")}
` : "";
const onStreet = n.street ? `on ${esc(n.street)}
` : "";
this._banner.innerHTML = `${maneuverSvg(type)}
${distance(m)}
` +
`
${what}
${lanesRow}${then}${onStreet}`;
}
}