import { Popup } from "/vendor/maplibre-gl/maplibre-gl.mjs";
import { NPS_SYMBOLS, POI_ICONS, MAP_MARKER_ICON } from "/js/icons.js";
import { svgToImageData, badgeImageId, escapeHtml } from "/js/gpx.js";
import { isLoggedIn } from "/js/auth.js";
import { PointStyleFields } from "/js/notes.js";
// Live data off the home MQTT broker (app.rb's /api/live, LiveStore): two
// Overlays items, "Tracker" (the GNSS tracker: position, trail, an optional
// floating info card) and "ITS-G5" (stations its receiver hears). One
// shared poller feeds both, running only while either is on.
const POLL_INTERVAL_MS = 2000;
const ICON_IMAGE_SIZE = 48;
const TRAIL_CHOICES = [0, 1, 2, 4, 8, 24];
const DENM_COLOR = "#e63946";
// ITS stations by ETSI station type (mcu-its-g5's decode.h names).
const STATION_COLORS = {
passengerCar: "#5a55e0",
bus: "#e0a32e",
lightTruck: "#9058d6",
heavyTruck: "#9058d6",
trailer: "#9058d6",
specialVehicle: "#e0a32e",
tram: "#e0a32e",
motorcycle: "#2aa7a0",
moped: "#2aa7a0",
cyclist: "#7cc957",
pedestrian: "#7cc957",
roadSideUnit: "#546619",
};
function ago(seconds) {
if (seconds < 60) return `${seconds} s ago`;
if (seconds < 3600) return `${Math.round(seconds / 60)} min ago`;
return `${Math.round(seconds / 3600)} h ago`;
}
function stationLabel(station) {
return String(station || "unknown").replace(/([a-z])([A-Z])/g, "$1 $2").toLowerCase();
}
function stored(key, fallback) {
try {
const value = localStorage.getItem(key);
return value === null ? fallback : JSON.parse(value);
} catch {
return fallback;
}
}
function store(key, value) {
try {
localStorage.setItem(key, JSON.stringify(value));
} catch {
// private window / blocked storage: not remembered
}
}
function removeLayers(map, layers, sources) {
for (const id of layers) if (map.getLayer(id)) map.removeLayer(id);
for (const id of sources) if (map.getSource(id)) map.removeSource(id);
}
function popupTable(title, rows) {
return `${title}
`;
}
// One /api/live poll for every subscriber.
const poller = {
listeners: new Set(),
timer: null,
last: null,
subscribe(fn) {
this.listeners.add(fn);
if (this.last) fn(this.last);
if (this.listeners.size === 1) this.poll();
},
unsubscribe(fn) {
this.listeners.delete(fn);
if (!this.listeners.size) clearTimeout(this.timer);
},
async poll() {
clearTimeout(this.timer);
let data = null;
try {
const response = await fetch("/api/live");
if (response.ok) data = await response.json();
} catch {
// network hiccup: listeners get null and say so
}
this.last = data;
this.listeners.forEach((fn) => fn(data));
if (this.listeners.size) this.timer = setTimeout(() => this.poll(), POLL_INTERVAL_MS);
},
refresh() {
if (this.listeners.size) this.poll();
},
};
// --- Tracker -------------------------------------------------------------
const TRACKER_SOURCE = "live-tracker";
const TRAIL_SOURCE = "live-tracker-trail";
const TRACKER_LAYERS = ["live-tracker-trail", "live-tracker-badge", "live-tracker-icon", "live-tracker-label"];
export class TrackerControl {
constructor(map) {
this._map = map;
this._enabled = false;
this._data = null;
this._centered = false;
this._onData = (data) => this._render(data);
map.on("style.load", () => {
if (this._enabled) this._addLayers().then(() => this._render(this._data));
});
}
mount(li) {
li.innerHTML = `
${NPS_SYMBOLS.automobiles}
`;
this._toggle = li.querySelector(".overlays-panel__toggle");
this._iconEl = li.querySelector(".live-tracker__icon");
this._nameButton = li.querySelector(".live-tracker__name");
this._status = li.querySelector(".live-panel__status");
this._settingsEl = li.querySelector(".live-tracker__settings");
this._cardToggle = li.querySelector(".live-tracker__card-toggle");
this._cardOpacity = li.querySelector(".live-tracker__card-opacity");
this._trailSelect = li.querySelector(".live-tracker__trail");
this._logging = li.querySelector(".live-tracker__logging");
this._nameInput = li.querySelector(".live-tracker__name-input");
this._style = new PointStyleFields(li.querySelector(".live-tracker__style"));
this._status.addEventListener("click", (event) => {
if (event.target.closest(".live-panel__show")) this._showTracker();
});
if (!isLoggedIn()) {
this._toggle.disabled = true;
li.title = "Log in to see the tracker";
return;
}
this._toggle.addEventListener("change", () => (this._toggle.checked ? this._enable() : this._disable()));
this._nameButton.addEventListener("click", () => {
const open = this._settingsEl.hidden;
this._settingsEl.hidden = !open;
this._nameButton.setAttribute("aria-expanded", String(open));
});
// The card is per device (localStorage); the rest is the server's.
this._cardToggle.checked = stored("trackerCard", true);
this._cardOpacity.value = stored("trackerCardOpacity", 0.85);
this._cardToggle.addEventListener("change", () => {
store("trackerCard", this._cardToggle.checked);
this._renderCard();
});
this._cardOpacity.addEventListener("input", () => {
store("trackerCardOpacity", +this._cardOpacity.value);
if (this._card) this._card.style.opacity = this._cardOpacity.value;
});
this._trailSelect.addEventListener("change", () => this._saveSettings({ trail_hours: this._trailSelect.value }));
this._logging.addEventListener("change", () => this._saveSettings({ logging: this._logging.checked }));
li.querySelector(".live-tracker__save").addEventListener("click", () =>
this._saveSettings({ name: this._nameInput.value, icon: this._style.icon, color: this._style.color || "#1a1a1a" }),
);
}
async _saveSettings(changes) {
const body = new URLSearchParams(Object.entries(changes).map(([k, v]) => [k, String(v)]));
try {
const response = await fetch("/api/live/settings", { method: "PUT", body });
if (!response.ok) throw new Error(response.status);
poller.refresh();
} catch {
window.alert("Could not save the tracker settings.");
}
}
async _enable() {
this._enabled = true;
this._centered = false;
this._status.hidden = false;
this._status.textContent = "Connecting…";
await this._addLayers();
poller.subscribe(this._onData);
}
_disable() {
this._enabled = false;
poller.unsubscribe(this._onData);
this._status.hidden = true;
this._card?.remove();
this._card = null;
removeLayers(this._map, TRACKER_LAYERS, [TRACKER_SOURCE, TRAIL_SOURCE]);
}
_showTracker() {
const t = this._data?.tracker;
if (t) this._map.flyTo({ center: [t.longitude, t.latitude], zoom: Math.max(this._map.getZoom(), 14) });
}
async _addLayers() {
if (this._map.getSource(TRACKER_SOURCE)) return;
const empty = { type: "FeatureCollection", features: [] };
this._map.addSource(TRAIL_SOURCE, { type: "geojson", data: empty });
this._map.addSource(TRACKER_SOURCE, { type: "geojson", data: empty });
this._map.addLayer({
id: "live-tracker-trail",
type: "line",
source: TRAIL_SOURCE,
layout: { "line-cap": "round", "line-join": "round" },
paint: { "line-color": ["get", "color"], "line-width": 3, "line-opacity": 0.75 },
});
this._map.addLayer({
id: "live-tracker-badge",
type: "symbol",
source: TRACKER_SOURCE,
layout: { "icon-image": ["get", "badge"], "icon-size": 0.7, "icon-allow-overlap": true },
});
this._map.addLayer({
id: "live-tracker-icon",
type: "symbol",
source: TRACKER_SOURCE,
layout: { "icon-image": ["get", "glyph"], "icon-size": 0.4, "icon-allow-overlap": true },
});
this._map.addLayer({
id: "live-tracker-label",
type: "symbol",
source: TRACKER_SOURCE,
layout: { "text-field": ["get", "label"], "text-font": ["Noto Sans Regular"], "text-size": 12, "text-offset": [0, 1.6], "text-anchor": "top", "text-allow-overlap": true },
paint: { "text-color": "#1a1a1a", "text-halo-color": "#fff", "text-halo-width": 1.5 },
});
if (!this._interactive) {
this._interactive = true;
this._map.on("click", "live-tracker-badge", (event) => this._popup(event.lngLat));
this._map.on("mouseenter", "live-tracker-badge", () => (this._map.getCanvas().style.cursor = "pointer"));
this._map.on("mouseleave", "live-tracker-badge", () => (this._map.getCanvas().style.cursor = ""));
}
}
// The badge in the tracker's color and its icon in white, each image
// registered once per color/icon.
async _ensureImages(color, icon) {
const badge = badgeImageId(color);
if (!this._map.hasImage(badge)) {
const image = await svgToImageData(MAP_MARKER_ICON.replace(/currentColor/g, color), ICON_IMAGE_SIZE);
if (!this._map.hasImage(badge)) this._map.addImage(badge, image);
}
const glyph = `live-glyph-${icon}`;
if (!this._map.hasImage(glyph)) {
const svg = POI_ICONS[icon] || NPS_SYMBOLS.automobiles;
const image = await svgToImageData(svg.replace(/currentColor/g, "#fff"), ICON_IMAGE_SIZE);
if (!this._map.hasImage(glyph)) this._map.addImage(glyph, image);
}
return { badge, glyph };
}
async _render(data) {
if (!this._enabled) return;
this._data = data;
if (!data) {
this._status.textContent = "Live data unavailable";
return;
}
const settings = data.settings;
this._applySettings(settings);
if (!data.available) {
this._status.textContent = "No MQTT broker configured on the server";
return;
}
const t = data.tracker;
this._status.innerHTML = t
? `${escapeHtml(settings.name)} ${ago(t.age)} · `
: `No ${escapeHtml(settings.name)} position yet`;
this._renderCard();
if (!t) return;
const { badge, glyph } = await this._ensureImages(settings.color, settings.icon);
this._map.getSource(TRACKER_SOURCE)?.setData({
type: "FeatureCollection",
features: [
{
type: "Feature",
geometry: { type: "Point", coordinates: [t.longitude, t.latitude] },
properties: { badge, glyph, label: `${settings.name} · ${ago(t.age)}` },
},
],
});
const trail = [...(t.trail || []), [t.longitude, t.latitude]];
this._map.getSource(TRAIL_SOURCE)?.setData({
type: "FeatureCollection",
features: trail.length > 1 ? [{ type: "Feature", geometry: { type: "LineString", coordinates: trail }, properties: { color: settings.color } }] : [],
});
if (!this._centered) {
this._centered = true;
this._showTracker();
}
}
// Server settings into the controls, unless the user is mid-edit there.
_applySettings(settings) {
const key = JSON.stringify(settings);
if (key === this._settingsKey) return;
this._settingsKey = key;
this._nameButton.textContent = settings.name;
this._iconEl.innerHTML = POI_ICONS[settings.icon] || NPS_SYMBOLS.automobiles;
this._trailSelect.value = String(settings.trail_hours);
this._logging.checked = settings.logging;
if (document.activeElement !== this._nameInput) this._nameInput.value = settings.name;
this._style.set(settings.icon, settings.color);
}
// The floating info card (per-device on/off and opacity).
_renderCard() {
const t = this._data?.tracker;
if (!this._enabled || !this._cardToggle.checked || !t) {
this._card?.remove();
this._card = null;
return;
}
if (!this._card) {
this._card = document.createElement("div");
this._card.className = "live-tracker-card";
this._card.addEventListener("click", () => this._showTracker());
this._map.getContainer().appendChild(this._card);
}
this._card.style.opacity = this._cardOpacity.value;
const s = this._data.settings;
const battery = t.battery_level != null ? `${Math.round(t.battery_level)} %` : null;
const rows = [
t.speed != null && ["Speed", `${Math.round(t.speed)} km/h`],
battery && ["Battery", `${battery}${t.usb_power ? " ⚡ charging" : ""}`],
!battery && t.usb_power && ["Power", "⚡ USB"],
t.altitude != null && ["Altitude", `${Math.round(t.altitude)} m`],
t.gps_accuracy != null && ["Accuracy", `±${t.gps_accuracy} m`],
["Updated", ago(t.age)],
].filter(Boolean);
this._card.innerHTML = `${POI_ICONS[s.icon] || NPS_SYMBOLS.automobiles}${escapeHtml(s.name)}
${rows.map(([k, v]) => `| ${k} | ${escapeHtml(v)} |
`).join("")}
`;
}
_popup(lngLat) {
const t = this._data?.tracker;
if (!t) return;
const html = popupTable(escapeHtml(this._data.settings.name), [
["Position", `${(+t.latitude).toFixed(5)}, ${(+t.longitude).toFixed(5)}`],
t.speed != null && ["Speed", `${Math.round(t.speed)} km/h`],
t.course != null && ["Course", `${Math.round(t.course)}°`],
t.altitude != null && ["Altitude", `${Math.round(t.altitude)} m`],
t.gps_accuracy != null && ["Accuracy", `±${t.gps_accuracy} m`],
t.battery_level != null && ["Battery", `${Math.round(t.battery_level)} %${t.usb_power ? " ⚡" : ""}`],
["Updated", ago(t.age)],
]);
new Popup({ maxWidth: "260px" }).setLngLat(lngLat).setHTML(html).addTo(this._map);
}
}
// --- ITS-G5 --------------------------------------------------------------
const ITS_SOURCE = "live-its";
const ITS_LAYERS = ["live-its", "live-its-label"];
export class ItsControl {
constructor(map) {
this._map = map;
this._enabled = false;
this._data = null;
this._onData = (data) => this._render(data);
map.on("style.load", () => {
if (this._enabled) {
this._addLayers();
this._render(this._data);
}
});
}
mount(li) {
li.innerHTML = `
`;
this._toggle = li.querySelector(".overlays-panel__toggle");
this._status = li.querySelector(".live-panel__status");
if (!isLoggedIn()) {
this._toggle.disabled = true;
li.title = "Log in to see ITS-G5 stations";
return;
}
this._toggle.addEventListener("change", () => (this._toggle.checked ? this._enable() : this._disable()));
}
_enable() {
this._enabled = true;
this._status.hidden = false;
this._status.textContent = "Connecting…";
this._addLayers();
poller.subscribe(this._onData);
}
_disable() {
this._enabled = false;
poller.unsubscribe(this._onData);
this._status.hidden = true;
removeLayers(this._map, ITS_LAYERS, [ITS_SOURCE]);
}
_addLayers() {
if (this._map.getSource(ITS_SOURCE)) return;
this._map.addSource(ITS_SOURCE, { type: "geojson", data: { type: "FeatureCollection", features: [] } });
this._map.addLayer({
id: "live-its",
type: "circle",
source: ITS_SOURCE,
paint: {
"circle-radius": ["case", ["==", ["get", "msg"], "DENM"], 8, 6],
"circle-color": ["get", "color"],
"circle-stroke-color": "#fff",
"circle-stroke-width": 1.5,
},
});
this._map.addLayer({
id: "live-its-label",
type: "symbol",
source: ITS_SOURCE,
minzoom: 12,
layout: { "text-field": ["get", "label"], "text-font": ["Noto Sans Regular"], "text-size": 11, "text-offset": [0, 1.2], "text-anchor": "top" },
paint: { "text-color": "#333", "text-halo-color": "#fff", "text-halo-width": 1.5 },
});
if (!this._interactive) {
this._interactive = true;
this._map.on("click", "live-its", (event) => this._popup(event.features[0].properties, event.lngLat));
this._map.on("mouseenter", "live-its", () => (this._map.getCanvas().style.cursor = "pointer"));
this._map.on("mouseleave", "live-its", () => (this._map.getCanvas().style.cursor = ""));
}
}
_render(data) {
if (!this._enabled) return;
this._data = data;
if (!data) {
this._status.textContent = "Live data unavailable";
return;
}
if (!data.available) {
this._status.textContent = "No MQTT broker configured on the server";
return;
}
const stations = data.its || [];
this._status.textContent = stations.length ? `${stations.length} station${stations.length === 1 ? "" : "s"} heard` : "No stations heard";
this._map.getSource(ITS_SOURCE)?.setData({
type: "FeatureCollection",
features: stations.map((station) => ({
type: "Feature",
geometry: { type: "Point", coordinates: [station.lon, station.lat] },
properties: {
...station,
color: station.msg === "DENM" ? DENM_COLOR : STATION_COLORS[station.station] || "#888",
label: `${station.msg} · ${stationLabel(station.station)}${station.speed > 1 ? ` · ${Math.round(station.speed)} km/h` : ""}`,
},
})),
});
}
_popup(p, lngLat) {
const html = popupTable(`ITS-G5 ${escapeHtml(p.msg)}`, [
["Station", stationLabel(p.station)],
["Speed", `${Math.round(p.speed)} km/h`],
["Heading", `${Math.round(p.heading)}°`],
["Signal", `${p.rssi} dBm${p.secured === true || p.secured === "true" ? " · signed" : ""}`],
["Heard", ago(p.age)],
]);
new Popup({ maxWidth: "260px" }).setLngLat(lngLat).setHTML(html).addTo(this._map);
}
}