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}${rows .filter(Boolean) .map(([k, v]) => ``) .join("")}
${k}${escapeHtml(String(v))}
`; } // 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-vehicle", "live-tracker-label"]; // Below this speed the GNSS course is noise: the vehicle keeps its last one. const MOVING_KMH = 3; const NAV_PITCH = 60; const NAV_ZOOM = 16; // Top-down shapes pointing north, rotated on the map by the course (like // OpenTrafficMap's vehicles): picked from the tracker's icon. const VEHICLE_SHAPES = { car: ``, moto: ``, bike: ``, }; function vehicleShape(icon) { if (/moto/.test(icon)) return "moto"; if (/bicycle|cycl|vtt|bike/.test(icon)) return "bike"; return "car"; } 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 (event.target.closest(".live-panel__follow")) this._setFollow(true); }); 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._setFollow(false); 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]); } // Navigation mode: the map follows the tracker heading-up, tilted, with // the vehicle in the lower third so more road ahead shows. _setFollow(on) { if (!this._follow === !on) return; this._follow = on; this._renderCard(); const t = this._data?.tracker; if (on && t) this._navigate(t); if (!on) this._map.easeTo({ padding: { top: 0, bottom: 0, left: 0, right: 0 }, duration: 300 }); } _navigate(t) { this._map.easeTo({ center: [t.longitude, t.latitude], bearing: this._course ?? this._map.getBearing(), pitch: NAV_PITCH, zoom: Math.max(this._map.getZoom(), NAV_ZOOM), padding: { top: this._map.getContainer().clientHeight * 0.4, bottom: 0, left: 0, right: 0 }, duration: Math.min(POLL_INTERVAL_MS, 1000), }); } _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 }, }); // Badge + glyph until a course is known, then the rotated vehicle. const still = ["!", ["has", "course"]]; this._map.addLayer({ id: "live-tracker-badge", type: "symbol", source: TRACKER_SOURCE, filter: still, 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, filter: still, layout: { "icon-image": ["get", "glyph"], "icon-size": 0.4, "icon-allow-overlap": true }, }); this._map.addLayer({ id: "live-tracker-vehicle", type: "symbol", source: TRACKER_SOURCE, filter: ["has", "course"], layout: { "icon-image": ["get", "vehicle"], "icon-size": 0.9, "icon-rotate": ["get", "course"], "icon-rotation-alignment": "map", "icon-pitch-alignment": "map", "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; for (const layer of ["live-tracker-badge", "live-tracker-vehicle"]) { this._map.on("click", layer, (event) => this._popup(event.lngLat)); this._map.on("mouseenter", layer, () => (this._map.getCanvas().style.cursor = "pointer")); this._map.on("mouseleave", layer, () => (this._map.getCanvas().style.cursor = "")); } // Panning by hand ends navigation mode (zoom/pinch keeps it). this._map.on("dragstart", () => this._setFollow(false)); } } // 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); } const shape = vehicleShape(icon); const vehicle = `live-vehicle-${shape}-${color}`; if (!this._map.hasImage(vehicle)) { const image = await svgToImageData(VEHICLE_SHAPES[shape].replace(/currentColor/g, color), ICON_IMAGE_SIZE); if (!this._map.hasImage(vehicle)) this._map.addImage(vehicle, image); } return { badge, glyph, vehicle }; } 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`; if (t?.course != null && (t.speed ?? MOVING_KMH) >= MOVING_KMH) this._course = t.course; this._renderCard(); if (!t) return; const { badge, glyph, vehicle } = await this._ensureImages(settings.color, settings.icon); const properties = { badge, glyph, vehicle, label: `${settings.name} · ${ago(t.age)}` }; if (this._course != null) properties.course = this._course; this._map.getSource(TRACKER_SOURCE)?.setData({ type: "FeatureCollection", features: [{ type: "Feature", geometry: { type: "Point", coordinates: [t.longitude, t.latitude] }, properties }], }); if (this._follow) this._navigate(t); 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", (event) => { if (event.target.closest(".live-tracker-card__nav")) this._setFollow(!this._follow); else 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]) => ``).join("")}
${k}${escapeHtml(v)}
`; } _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); } }