diff --git a/TODO.adoc b/TODO.adoc
index 7654e80..0bf9407 100644
--- a/TODO.adoc
+++ b/TODO.adoc
@@ -133,6 +133,12 @@ already reaches the home MQTT broker (`mqtt_ext`) from ESPHome nodes in `~/espho
(`public/js/live.js`) polls it
* [x] Car position from the LTE GNSS tracker (`mcu-tracker/location`) — a badge with its age
and details; the last position stays (a parked tracker reports rarely)
+** [x] Own "Tracker" overlay (ITS-G5 separate, Overlays grouped by category); name, icon and color
+ set in the overlay (server-side, `data/live/settings.json`); USB power / charging from
+ `mcu-tracker/binary_sensor/usb_power/state`; a floating info card (per-device on/off + opacity);
+ the trail of the last 1/2/4/8/24 h; optional logging to `data/live/tracker.jsonl`, which also
+ restores the trail after a restart (`lib/maptool/live_store.rb`)
+** [ ] Export the logged trail (GPX / into the library)
* [ ] … also as a source for the GNSS control ("where is the car" / follow it)
* [x] ITS-G5: `mcu-its-g5.yaml` publishes the decoded header as JSON on `mcu-its-g5/decoded`
(1 Hz per station); stations on the map colored by type, DENM bigger and red, gone after 60 s
diff --git a/app.rb b/app.rb
index 29c21c5..c3ddc02 100644
--- a/app.rb
+++ b/app.rb
@@ -11,6 +11,7 @@ require_relative "lib/maptool/library"
require_relative "lib/maptool/routing"
require_relative "lib/maptool/gpsd_client"
require_relative "lib/maptool/mqtt_client"
+require_relative "lib/maptool/live_store"
require_relative "lib/maptool/livetrack_store"
require_relative "lib/maptool/livetrack_client"
require_relative "lib/maptool/kiwix"
@@ -305,31 +306,20 @@ module Maptool
end
end
- # Live vehicle data off the home MQTT broker (MQTT_URL), polled by the
- # frontend from /api/live like GNSS above: the car's position from its LTE
- # GNSS tracker, and ITS-G5 stations heard by its receiver (one decoded
- # header per station and second). A station drops out once it hasn't been
- # heard for ITS_STALE_AFTER; the car's last position stays, with its age
- # (a parked tracker reports rarely).
+ # Live data off the home MQTT broker (MQTT_URL), polled by the frontend
+ # from /api/live like GNSS above — the "Tracker" and "ITS-G5" overlays:
+ # the LTE GNSS tracker's position and USB power (+ its trail, optionally
+ # logged), and ITS-G5 stations heard by its receiver. See LiveStore.
TRACKER_TOPIC = "mcu-tracker/location"
+ TRACKER_POWER_TOPIC = "mcu-tracker/binary_sensor/usb_power/state"
ITS_TOPIC = "mcu-its-g5/decoded"
- ITS_STALE_AFTER = 60 # seconds
-
- LIVE = { vehicle: nil, its: {} }
- LIVE_MUTEX = Mutex.new
+ LIVE_STORE = LiveStore.new(File.join(DATA_DIR, "live"))
def self.record_live(topic, payload, at: Time.now.to_f)
- data = JSON.parse(payload)
- return unless data.is_a?(Hash)
-
- LIVE_MUTEX.synchronize do
- case topic
- when TRACKER_TOPIC
- LIVE[:vehicle] = data.merge("received_at" => at) if data["latitude"] && data["longitude"]
- when ITS_TOPIC
- LIVE[:its][data["id"]] = data.merge("received_at" => at) if data["id"] && data["lat"] && data["lon"]
- LIVE[:its].delete_if { |_, station| at - station["received_at"] > ITS_STALE_AFTER }
- end
+ case topic
+ when TRACKER_TOPIC then LIVE_STORE.record_tracker(JSON.parse(payload), at: at)
+ when TRACKER_POWER_TOPIC then LIVE_STORE.record_usb_power(payload)
+ when ITS_TOPIC then LIVE_STORE.record_its(JSON.parse(payload), at: at)
end
rescue JSON::ParserError
nil
@@ -338,7 +328,7 @@ module Maptool
unless MQTT_URL.empty?
Thread.new do
MqttClient.new(url: MQTT_URL, username: ENV.fetch("MQTT_USERNAME", ""), password: ENV.fetch("MQTT_PASSWORD", ""),
- topics: [TRACKER_TOPIC, ITS_TOPIC]).each_message { |topic, payload| record_live(topic, payload) }
+ topics: [TRACKER_TOPIC, TRACKER_POWER_TOPIC, ITS_TOPIC]).each_message { |topic, payload| record_live(topic, payload) }
end
end
@@ -1037,12 +1027,13 @@ module Maptool
get "/api/live" do
require_login!
- now = Time.now.to_f
- age = ->(item) { item.except("received_at").merge("age" => (now - item["received_at"]).round) }
- LIVE_MUTEX.synchronize do
- stations = LIVE[:its].values.select { |station| now - station["received_at"] <= ITS_STALE_AFTER }
- json(available: !MQTT_URL.empty?, vehicle: LIVE[:vehicle] && age.(LIVE[:vehicle]), its: stations.map(&age))
- end
+ json LIVE_STORE.snapshot.merge(available: !MQTT_URL.empty?)
+ end
+
+ # The tracker's name, icon, color, trail logging and trail length.
+ put "/api/live/settings" do
+ require_login!
+ json LIVE_STORE.update_settings(params.slice("name", "icon", "color", "logging", "trail_hours"))
end
get "/api/gnss/position" do
diff --git a/lib/maptool/live_store.rb b/lib/maptool/live_store.rb
new file mode 100644
index 0000000..08452c0
--- /dev/null
+++ b/lib/maptool/live_store.rb
@@ -0,0 +1,144 @@
+require "json"
+require "fileutils"
+
+module Maptool
+ # Live data off the home MQTT broker (app.rb wires the topics in): the GNSS
+ # tracker's position, its USB power state and the trail behind it, and the
+ # ITS-G5 stations its receiver hears. Thread-safe — the MQTT thread writes,
+ # requests read.
+ #
+ # The trail is kept in memory for TRAIL_KEEP; with logging on (a setting)
+ # every trail point is also appended to tracker.jsonl, which is read back
+ # on start, so the trail survives a restart/redeploy. The tracker's
+ # settings (name, icon, color, logging, trail_hours) live in settings.json
+ # next to it — the same for every device viewing the map.
+ class LiveStore
+ ITS_STALE_AFTER = 60 # seconds
+ TRAIL_KEEP = 24 * 3600 # seconds
+ # A trail point is only added once the tracker has moved this far, or
+ # this long has passed — a parked tracker repeating its position doesn't
+ # grow it.
+ TRAIL_MIN_METERS = 10
+ TRAIL_MIN_SECONDS = 300
+ DEFAULT_SETTINGS = {
+ "name" => "Tracker", "icon" => "automobiles", "color" => "#1a1a1a", "logging" => false, "trail_hours" => 1,
+ }.freeze
+ TRAIL_HOURS = [0, 1, 2, 4, 8, 24].freeze
+
+ def initialize(dir)
+ @dir = dir
+ @mutex = Mutex.new
+ @tracker = nil
+ @usb_power = nil
+ @its = {}
+ @settings = DEFAULT_SETTINGS.merge(read_json(settings_path) || {})
+ @trail = load_trail
+ end
+
+ def record_tracker(data, at: Time.now.to_f)
+ return unless data.is_a?(Hash) && data["latitude"] && data["longitude"]
+
+ @mutex.synchronize do
+ @tracker = data.merge("received_at" => at)
+ add_trail_point([at.round, data["longitude"].to_f.round(6), data["latitude"].to_f.round(6)])
+ end
+ end
+
+ # ESPHome's binary sensor state: "ON" / "OFF".
+ def record_usb_power(payload)
+ @mutex.synchronize { @usb_power = payload.to_s.strip.upcase == "ON" }
+ end
+
+ def record_its(data, at: Time.now.to_f)
+ return unless data.is_a?(Hash) && data["id"] && data["lat"] && data["lon"]
+
+ @mutex.synchronize do
+ @its[data["id"]] = data.merge("received_at" => at)
+ @its.delete_if { |_, station| at - station["received_at"] > ITS_STALE_AFTER }
+ end
+ end
+
+ # What /api/live returns: the tracker (with its age, settings, USB power
+ # and the trail of the last trail_hours) and the fresh ITS-G5 stations.
+ def snapshot(now: Time.now.to_f)
+ @mutex.synchronize do
+ tracker = @tracker && @tracker.except("received_at").merge(
+ "age" => (now - @tracker["received_at"]).round,
+ "usb_power" => @usb_power,
+ "trail" => @trail.select { |t, _, _| now - t <= @settings["trail_hours"] * 3600 }.map { |_, lon, lat| [lon, lat] },
+ )
+ stations = @its.values.select { |s| now - s["received_at"] <= ITS_STALE_AFTER }
+ .map { |s| s.except("received_at").merge("age" => (now - s["received_at"]).round) }
+ { tracker: tracker, settings: @settings.dup, its: stations }
+ end
+ end
+
+ def settings
+ @mutex.synchronize { @settings.dup }
+ end
+
+ # Only known keys, sanitized; returns the new settings.
+ def update_settings(changes)
+ @mutex.synchronize do
+ changes = changes.to_h.transform_keys(&:to_s)
+ @settings["name"] = changes["name"].to_s.strip[0, 40] if changes.key?("name") && !changes["name"].to_s.strip.empty?
+ @settings["icon"] = changes["icon"].to_s[0, 60] if changes.key?("icon")
+ @settings["color"] = changes["color"] if changes["color"].to_s.match?(/\A#\h{6}\z/)
+ @settings["logging"] = [true, "true", "1", "on"].include?(changes["logging"]) if changes.key?("logging")
+ hours = changes["trail_hours"].to_s
+ @settings["trail_hours"] = hours.to_i if TRAIL_HOURS.include?(hours.to_i) && hours.match?(/\A\d+\z/)
+ FileUtils.mkdir_p(@dir)
+ File.write(settings_path, JSON.generate(@settings))
+ @settings.dup
+ end
+ end
+
+ private
+
+ def add_trail_point(point)
+ last = @trail.last
+ return if last && point[0] - last[0] < TRAIL_MIN_SECONDS && meters(last, point) < TRAIL_MIN_METERS
+
+ @trail << point
+ @trail.shift while @trail.first && point[0] - @trail.first[0] > TRAIL_KEEP
+ append_log(point) if @settings["logging"]
+ end
+
+ def append_log(point)
+ FileUtils.mkdir_p(@dir)
+ File.open(log_path, "a") { |f| f.puts(JSON.generate(point)) }
+ rescue SystemCallError => e
+ warn "[live] could not log the trail: #{e.message}"
+ end
+
+ # The last TRAIL_KEEP of the log, if there is one.
+ def load_trail
+ return [] unless File.exist?(log_path)
+
+ cutoff = Time.now.to_f - TRAIL_KEEP
+ File.foreach(log_path).filter_map do |line|
+ point = JSON.parse(line)
+ point if point.is_a?(Array) && point.size == 3 && point[0] >= cutoff
+ rescue JSON::ParserError
+ nil
+ end
+ end
+
+ # Equirectangular approximation; plenty for "has it moved 10 m".
+ def meters(a, b)
+ _, lon1, lat1 = a
+ _, lon2, lat2 = b
+ x = (lon2 - lon1) * Math.cos((lat1 + lat2) * Math::PI / 360)
+ Math.sqrt((x**2) + ((lat2 - lat1)**2)) * 111_320
+ end
+
+ def read_json(path)
+ JSON.parse(File.read(path)) if File.exist?(path)
+ rescue JSON::ParserError
+ nil
+ end
+
+ def settings_path = File.join(@dir, "settings.json")
+ def log_path = File.join(@dir, "tracker.jsonl")
+ end
+end
diff --git a/public/css/style.css b/public/css/style.css
index ecdedb6..782babc 100644
--- a/public/css/style.css
+++ b/public/css/style.css
@@ -2119,6 +2119,20 @@ body.side-pinned:has(.basemap-panel:not([hidden]), .gpx-panel:not([hidden])) .pr
height: 100%;
}
+/* Category headings between the Overlays items (overlays.js). */
+.overlays-panel__group {
+ margin: 10px 4px 2px;
+ font-size: 11px;
+ font-weight: 600;
+ color: #888;
+ text-transform: uppercase;
+ letter-spacing: 0.05em;
+}
+
+.overlays-panel__group:first-child {
+ margin-top: 0;
+}
+
.overlays-panel__row {
display: flex;
align-items: center;
@@ -2993,3 +3007,88 @@ body.side-pinned:has(.basemap-panel:not([hidden]), .gpx-panel:not([hidden])) .pr
background: var(--accent);
color: #fff;
}
+
+/* Tracker overlay settings (live.js). */
+.live-tracker__settings {
+ display: flex;
+ flex-direction: column;
+ gap: 6px;
+}
+
+/* Same "author display wins over the UA [hidden] rule" gotcha as
+ .gpx-panel__action[hidden]. */
+.live-tracker__settings[hidden] {
+ display: none;
+}
+
+.live-tracker__row {
+ display: flex;
+ align-items: center;
+ gap: 6px;
+}
+
+.live-tracker__row input[type="range"] {
+ flex: 1;
+}
+
+.live-tracker__name-input {
+ padding: 4px 6px;
+ font: inherit;
+}
+
+.live-tracker__save {
+ align-self: flex-start;
+ padding: 4px 14px;
+ border: none;
+ border-radius: 4px;
+ background: var(--accent);
+ color: #fff;
+ font: inherit;
+ cursor: pointer;
+}
+
+/* The tracker's floating info card over the map (per-device opacity). */
+.live-tracker-card {
+ position: absolute;
+ left: 12px;
+ bottom: 36px;
+ z-index: 3;
+ min-width: 170px;
+ padding: 8px 10px;
+ border-radius: 8px;
+ background: #fff;
+ box-shadow: 0 1px 6px rgba(0, 0, 0, 0.25);
+ font-size: 12px;
+ cursor: pointer;
+}
+
+.live-tracker-card__title {
+ display: flex;
+ align-items: center;
+ gap: 6px;
+ margin-bottom: 4px;
+ font-weight: 600;
+ font-size: 13px;
+}
+
+.live-tracker-card__icon {
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ width: 20px;
+ height: 20px;
+ border-radius: 5px;
+ color: #fff;
+}
+
+.live-tracker-card__icon svg {
+ width: 14px;
+ height: 14px;
+}
+
+.live-tracker-card th {
+ padding-right: 10px;
+ color: #666;
+ font-weight: normal;
+ text-align: left;
+}
diff --git a/public/js/hiking_trails.js b/public/js/hiking_trails.js
index db62949..cf63eb5 100644
--- a/public/js/hiking_trails.js
+++ b/public/js/hiking_trails.js
@@ -202,7 +202,10 @@ export class HikingTrailsControl {
this._details = li.querySelector(".overlays-panel__details");
this._countryList = li.querySelector(".hiking-trail-countries");
- this._checkbox.addEventListener("change", (event) => this._toggleOnline(event.target.checked));
+ this._checkbox.addEventListener("change", (event) => {
+ if (this._offlineCountries.length) this._toggleAllCountries(event.target.checked);
+ else this._toggleOnline(event.target.checked);
+ });
this._nameButton.addEventListener("click", () => {
if (this._offlineCountries.length === 0) return; // nothing to expand into yet
const expanding = this._details.hidden;
@@ -222,7 +225,10 @@ export class HikingTrailsControl {
if (countries.length === 0) return;
if (this._active) this._toggleOnline(false);
- this._checkbox.hidden = true;
+ // The main checkbox stays: offline it switches every country at once
+ // (indeterminate while only some are on); the name opens the list.
+ this._checkbox.checked = false;
+ this._checkbox.title = "All countries — click the name to pick some";
this._countryList.innerHTML = countries
.map(
@@ -237,7 +243,10 @@ export class HikingTrailsControl {
)
.join("");
this._countryList.querySelectorAll(".hiking-trail-countries__toggle").forEach((input) => {
- input.addEventListener("change", (event) => this._toggleCountry(event.target.value, event.target.checked));
+ input.addEventListener("change", (event) => {
+ this._toggleCountry(event.target.value, event.target.checked);
+ this._syncMainCheckbox();
+ });
});
}
@@ -247,6 +256,23 @@ export class HikingTrailsControl {
if (!input || input.checked) return;
input.checked = true;
this._toggleCountry(code, true);
+ this._syncMainCheckbox();
+ }
+
+ _toggleAllCountries(active) {
+ this._countryList.querySelectorAll(".hiking-trail-countries__toggle").forEach((input) => {
+ if (input.checked === active) return;
+ input.checked = active;
+ this._toggleCountry(input.value, active);
+ });
+ this._syncMainCheckbox();
+ }
+
+ _syncMainCheckbox() {
+ const inputs = [...this._countryList.querySelectorAll(".hiking-trail-countries__toggle")];
+ const on = inputs.filter((input) => input.checked).length;
+ this._checkbox.checked = on > 0 && on === inputs.length;
+ this._checkbox.indeterminate = on > 0 && on < inputs.length;
}
_toggleOnline(active) {
diff --git a/public/js/live.js b/public/js/live.js
index 078f932..685c448 100644
--- a/public/js/live.js
+++ b/public/js/live.js
@@ -1,18 +1,17 @@
import { Popup } from "/vendor/maplibre-gl/maplibre-gl.mjs";
-import { NPS_SYMBOLS, MAP_MARKER_ICON } from "/js/icons.js";
+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";
-// 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.
+// 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 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 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 = {
@@ -29,7 +28,6 @@ const STATION_COLORS = {
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`;
@@ -37,44 +35,161 @@ function ago(seconds) {
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 {
+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._timer = null;
this._centered = false;
- // setStyle() (base map switch) drops custom sources/layers.
+ this._onData = (data) => this._render(data);
map.on("style.load", () => {
- if (this._enabled) this._addLayers().then(() => this._render());
+ if (this._enabled) this._addLayers().then(() => this._render(this._data));
});
}
mount(li) {
li.innerHTML = `
-