254 lines
9.6 KiB
JavaScript
254 lines
9.6 KiB
JavaScript
import { Popup } from "/vendor/maplibre-gl/maplibre-gl.mjs";
|
|
import { NPS_SYMBOLS, MAP_MARKER_ICON } from "/js/icons.js";
|
|
import { svgToImageData, badgeImageId, escapeHtml } from "/js/gpx.js";
|
|
import { isLoggedIn } from "/js/auth.js";
|
|
|
|
// The car's live data off the home MQTT broker (app.rb's /api/live): its
|
|
// position from the LTE GNSS tracker, and the ITS-G5 stations its receiver
|
|
// hears. An Overlays item; polled like the GNSS control, since the server
|
|
// side only holds the latest state anyway.
|
|
|
|
const SOURCE_ID = "live-points";
|
|
const POLL_INTERVAL_MS = 2000;
|
|
const VEHICLE_COLOR = "#1a1a1a";
|
|
const VEHICLE_ICON_ID = "live-vehicle-icon";
|
|
const ICON_IMAGE_SIZE = 48;
|
|
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",
|
|
};
|
|
const LAYERS = ["live-its", "live-its-label", "live-vehicle-badge", "live-vehicle-icon", "live-vehicle-label"];
|
|
|
|
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`;
|
|
}
|
|
|
|
// "passengerCar" → "passenger car"
|
|
function stationLabel(station) {
|
|
return String(station || "unknown").replace(/([a-z])([A-Z])/g, "$1 $2").toLowerCase();
|
|
}
|
|
|
|
export class LiveControl {
|
|
constructor(map) {
|
|
this._map = map;
|
|
this._enabled = false;
|
|
this._data = null;
|
|
this._timer = null;
|
|
this._centered = false;
|
|
// setStyle() (base map switch) drops custom sources/layers.
|
|
map.on("style.load", () => {
|
|
if (this._enabled) this._addLayers().then(() => this._render());
|
|
});
|
|
}
|
|
|
|
mount(li) {
|
|
li.innerHTML = `
|
|
<label>
|
|
<input type="checkbox" class="overlays-panel__toggle">
|
|
<span class="overlays-panel__icon">${NPS_SYMBOLS.automobiles}</span>
|
|
<span>Vehicle & ITS-G5</span>
|
|
</label>
|
|
<p class="live-panel__status" hidden></p>
|
|
`;
|
|
this._toggle = li.querySelector(".overlays-panel__toggle");
|
|
this._status = li.querySelector(".live-panel__status");
|
|
this._status.addEventListener("click", (event) => {
|
|
if (event.target.closest(".live-panel__show")) this._showVehicle();
|
|
});
|
|
if (!isLoggedIn()) {
|
|
this._toggle.disabled = true;
|
|
li.title = "Log in to see the car's live data";
|
|
return;
|
|
}
|
|
this._toggle.addEventListener("change", () => (this._toggle.checked ? this._enable() : this._disable()));
|
|
}
|
|
|
|
async _enable() {
|
|
this._enabled = true;
|
|
this._centered = false;
|
|
this._status.hidden = false;
|
|
this._status.textContent = "Connecting…";
|
|
await this._addLayers();
|
|
this._poll();
|
|
}
|
|
|
|
_disable() {
|
|
this._enabled = false;
|
|
clearTimeout(this._timer);
|
|
this._status.hidden = true;
|
|
for (const id of LAYERS) if (this._map.getLayer(id)) this._map.removeLayer(id);
|
|
if (this._map.getSource(SOURCE_ID)) this._map.removeSource(SOURCE_ID);
|
|
}
|
|
|
|
async _poll() {
|
|
clearTimeout(this._timer);
|
|
try {
|
|
const response = await fetch("/api/live");
|
|
if (!response.ok) throw new Error(response.status);
|
|
this._data = await response.json();
|
|
this._render();
|
|
// The first time the car shows up, go to it.
|
|
if (!this._centered && this._data.vehicle) {
|
|
this._centered = true;
|
|
this._showVehicle();
|
|
}
|
|
} catch (err) {
|
|
this._status.textContent = "Live data unavailable";
|
|
}
|
|
if (this._enabled) this._timer = setTimeout(() => this._poll(), POLL_INTERVAL_MS);
|
|
}
|
|
|
|
_showVehicle() {
|
|
const vehicle = this._data?.vehicle;
|
|
if (vehicle) this._map.flyTo({ center: [vehicle.longitude, vehicle.latitude], zoom: Math.max(this._map.getZoom(), 14) });
|
|
}
|
|
|
|
async _addLayers() {
|
|
if (this._map.getSource(SOURCE_ID)) return;
|
|
await this._registerImages();
|
|
if (this._map.getSource(SOURCE_ID)) return; // a style.load raced this
|
|
this._map.addSource(SOURCE_ID, { type: "geojson", data: { type: "FeatureCollection", features: [] } });
|
|
this._map.addLayer({
|
|
id: "live-its",
|
|
type: "circle",
|
|
source: SOURCE_ID,
|
|
filter: ["==", ["get", "kind"], "its"],
|
|
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: SOURCE_ID,
|
|
filter: ["==", ["get", "kind"], "its"],
|
|
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 },
|
|
});
|
|
this._map.addLayer({
|
|
id: "live-vehicle-badge",
|
|
type: "symbol",
|
|
source: SOURCE_ID,
|
|
filter: ["==", ["get", "kind"], "vehicle"],
|
|
layout: { "icon-image": badgeImageId(VEHICLE_COLOR), "icon-size": 0.7, "icon-allow-overlap": true },
|
|
});
|
|
this._map.addLayer({
|
|
id: "live-vehicle-icon",
|
|
type: "symbol",
|
|
source: SOURCE_ID,
|
|
filter: ["==", ["get", "kind"], "vehicle"],
|
|
layout: { "icon-image": VEHICLE_ICON_ID, "icon-size": 0.4, "icon-allow-overlap": true },
|
|
});
|
|
this._map.addLayer({
|
|
id: "live-vehicle-label",
|
|
type: "symbol",
|
|
source: SOURCE_ID,
|
|
filter: ["==", ["get", "kind"], "vehicle"],
|
|
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 id of ["live-its", "live-vehicle-badge"]) {
|
|
this._map.on("click", id, (event) => this._popup(event.features[0], event.lngLat));
|
|
this._map.on("mouseenter", id, () => (this._map.getCanvas().style.cursor = "pointer"));
|
|
this._map.on("mouseleave", id, () => (this._map.getCanvas().style.cursor = ""));
|
|
}
|
|
}
|
|
}
|
|
|
|
async _registerImages() {
|
|
const badge = badgeImageId(VEHICLE_COLOR);
|
|
if (!this._map.hasImage(badge)) {
|
|
const image = await svgToImageData(MAP_MARKER_ICON.replace(/currentColor/g, VEHICLE_COLOR), ICON_IMAGE_SIZE);
|
|
if (!this._map.hasImage(badge)) this._map.addImage(badge, image);
|
|
}
|
|
if (!this._map.hasImage(VEHICLE_ICON_ID)) {
|
|
const image = await svgToImageData(NPS_SYMBOLS.automobiles.replace(/currentColor/g, "#fff"), ICON_IMAGE_SIZE);
|
|
if (!this._map.hasImage(VEHICLE_ICON_ID)) this._map.addImage(VEHICLE_ICON_ID, image);
|
|
}
|
|
}
|
|
|
|
_render() {
|
|
const data = this._data;
|
|
if (!data) return;
|
|
const features = [];
|
|
const vehicle = data.vehicle;
|
|
if (vehicle) {
|
|
features.push({
|
|
type: "Feature",
|
|
geometry: { type: "Point", coordinates: [vehicle.longitude, vehicle.latitude] },
|
|
properties: { ...vehicle, kind: "vehicle", label: `Car · ${ago(vehicle.age)}` },
|
|
});
|
|
}
|
|
for (const station of data.its || []) {
|
|
features.push({
|
|
type: "Feature",
|
|
geometry: { type: "Point", coordinates: [station.lon, station.lat] },
|
|
properties: {
|
|
...station,
|
|
kind: "its",
|
|
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` : ""}`,
|
|
},
|
|
});
|
|
}
|
|
this._map.getSource(SOURCE_ID)?.setData({ type: "FeatureCollection", features });
|
|
|
|
if (!data.available) {
|
|
this._status.textContent = "No MQTT broker configured on the server";
|
|
return;
|
|
}
|
|
const car = vehicle ? `Car ${ago(vehicle.age)} · <button type="button" class="live-panel__show">show</button>` : "No car position yet";
|
|
const its = data.its?.length ? `${data.its.length} ITS-G5 station${data.its.length === 1 ? "" : "s"}` : "no ITS-G5 stations heard";
|
|
this._status.innerHTML = `${car} · ${its}`;
|
|
}
|
|
|
|
_popup(feature, lngLat) {
|
|
const p = feature.properties;
|
|
const rows =
|
|
p.kind === "vehicle"
|
|
? [
|
|
["Position", `${(+p.latitude).toFixed(5)}, ${(+p.longitude).toFixed(5)}`],
|
|
p.speed != null && ["Speed", `${Math.round(p.speed)} km/h`],
|
|
p.course != null && ["Course", `${Math.round(p.course)}°`],
|
|
p.altitude != null && ["Altitude", `${Math.round(p.altitude)} m`],
|
|
p.gps_accuracy != null && ["Accuracy", `±${p.gps_accuracy} m`],
|
|
p.battery_level != null && ["Battery", `${Math.round(p.battery_level)} %`],
|
|
["Updated", ago(p.age)],
|
|
]
|
|
: [
|
|
["Message", 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)],
|
|
];
|
|
const title = p.kind === "vehicle" ? "Car" : `ITS-G5 ${escapeHtml(p.msg)}`;
|
|
const html = `<strong>${title}</strong><table class="live-popup">${rows
|
|
.filter(Boolean)
|
|
.map(([k, v]) => `<tr><th>${k}</th><td>${escapeHtml(String(v))}</td></tr>`)
|
|
.join("")}</table>`;
|
|
new Popup({ maxWidth: "260px" }).setLngLat(lngLat).setHTML(html).addTo(this._map);
|
|
}
|
|
}
|