Tracker and ITS-G5 as separate overlays, Overlays grouped by category: the tracker gets a name/icon/color, charging from its USB power topic, a floating info card (per-device opacity), a trail of the last 1–24 h and optional position logging that survives restarts (LiveStore); hiking trails keep their main checkbox as an all-countries toggle
This commit is contained in:
1 parent
3fc8c75c60
commit
0e5f79f8e4
9 files changed
+794
-198
No files matched your search
@@ -133,6 +133,12 @@ already reaches the home MQTT broker (`mqtt_ext`) from ESPHome nodes in `~/espho
|
|||||||
(`public/js/live.js`) polls it
|
(`public/js/live.js`) polls it
|
||||||
* [x] Car position from the LTE GNSS tracker (`mcu-tracker/location`) — a badge with its age
|
* [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)
|
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)
|
* [ ] … 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`
|
* [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
|
(1 Hz per station); stations on the map colored by type, DENM bigger and red, gone after 60 s
|
||||||
|
|||||||
@@ -11,6 +11,7 @@ require_relative "lib/maptool/library"
|
|||||||
require_relative "lib/maptool/routing"
|
require_relative "lib/maptool/routing"
|
||||||
require_relative "lib/maptool/gpsd_client"
|
require_relative "lib/maptool/gpsd_client"
|
||||||
require_relative "lib/maptool/mqtt_client"
|
require_relative "lib/maptool/mqtt_client"
|
||||||
|
require_relative "lib/maptool/live_store"
|
||||||
require_relative "lib/maptool/livetrack_store"
|
require_relative "lib/maptool/livetrack_store"
|
||||||
require_relative "lib/maptool/livetrack_client"
|
require_relative "lib/maptool/livetrack_client"
|
||||||
require_relative "lib/maptool/kiwix"
|
require_relative "lib/maptool/kiwix"
|
||||||
@@ -305,31 +306,20 @@ module Maptool
|
|||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
# Live vehicle data off the home MQTT broker (MQTT_URL), polled by the
|
# Live data off the home MQTT broker (MQTT_URL), polled by the frontend
|
||||||
# frontend from /api/live like GNSS above: the car's position from its LTE
|
# from /api/live like GNSS above — the "Tracker" and "ITS-G5" overlays:
|
||||||
# GNSS tracker, and ITS-G5 stations heard by its receiver (one decoded
|
# the LTE GNSS tracker's position and USB power (+ its trail, optionally
|
||||||
# header per station and second). A station drops out once it hasn't been
|
# logged), and ITS-G5 stations heard by its receiver. See LiveStore.
|
||||||
# heard for ITS_STALE_AFTER; the car's last position stays, with its age
|
|
||||||
# (a parked tracker reports rarely).
|
|
||||||
TRACKER_TOPIC = "mcu-tracker/location"
|
TRACKER_TOPIC = "mcu-tracker/location"
|
||||||
|
TRACKER_POWER_TOPIC = "mcu-tracker/binary_sensor/usb_power/state"
|
||||||
ITS_TOPIC = "mcu-its-g5/decoded"
|
ITS_TOPIC = "mcu-its-g5/decoded"
|
||||||
ITS_STALE_AFTER = 60 # seconds
|
LIVE_STORE = LiveStore.new(File.join(DATA_DIR, "live"))
|
||||||
|
|
||||||
LIVE = { vehicle: nil, its: {} }
|
|
||||||
LIVE_MUTEX = Mutex.new
|
|
||||||
|
|
||||||
def self.record_live(topic, payload, at: Time.now.to_f)
|
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
|
case topic
|
||||||
when TRACKER_TOPIC
|
when TRACKER_TOPIC then LIVE_STORE.record_tracker(JSON.parse(payload), at: at)
|
||||||
LIVE[:vehicle] = data.merge("received_at" => at) if data["latitude"] && data["longitude"]
|
when TRACKER_POWER_TOPIC then LIVE_STORE.record_usb_power(payload)
|
||||||
when ITS_TOPIC
|
when ITS_TOPIC then LIVE_STORE.record_its(JSON.parse(payload), at: at)
|
||||||
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
|
|
||||||
end
|
end
|
||||||
rescue JSON::ParserError
|
rescue JSON::ParserError
|
||||||
nil
|
nil
|
||||||
@@ -338,7 +328,7 @@ module Maptool
|
|||||||
unless MQTT_URL.empty?
|
unless MQTT_URL.empty?
|
||||||
Thread.new do
|
Thread.new do
|
||||||
MqttClient.new(url: MQTT_URL, username: ENV.fetch("MQTT_USERNAME", ""), password: ENV.fetch("MQTT_PASSWORD", ""),
|
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
|
||||||
end
|
end
|
||||||
|
|
||||||
@@ -1037,12 +1027,13 @@ module Maptool
|
|||||||
|
|
||||||
get "/api/live" do
|
get "/api/live" do
|
||||||
require_login!
|
require_login!
|
||||||
now = Time.now.to_f
|
json LIVE_STORE.snapshot.merge(available: !MQTT_URL.empty?)
|
||||||
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
|
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
|
end
|
||||||
|
|
||||||
get "/api/gnss/position" do
|
get "/api/gnss/position" do
|
||||||
|
|||||||
@@ -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
|
||||||
@@ -2119,6 +2119,20 @@ body.side-pinned:has(.basemap-panel:not([hidden]), .gpx-panel:not([hidden])) .pr
|
|||||||
height: 100%;
|
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 {
|
.overlays-panel__row {
|
||||||
display: flex;
|
display: flex;
|
||||||
align-items: center;
|
align-items: center;
|
||||||
@@ -2993,3 +3007,88 @@ body.side-pinned:has(.basemap-panel:not([hidden]), .gpx-panel:not([hidden])) .pr
|
|||||||
background: var(--accent);
|
background: var(--accent);
|
||||||
color: #fff;
|
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;
|
||||||
|
}
|
||||||
@@ -202,7 +202,10 @@ export class HikingTrailsControl {
|
|||||||
this._details = li.querySelector(".overlays-panel__details");
|
this._details = li.querySelector(".overlays-panel__details");
|
||||||
this._countryList = li.querySelector(".hiking-trail-countries");
|
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", () => {
|
this._nameButton.addEventListener("click", () => {
|
||||||
if (this._offlineCountries.length === 0) return; // nothing to expand into yet
|
if (this._offlineCountries.length === 0) return; // nothing to expand into yet
|
||||||
const expanding = this._details.hidden;
|
const expanding = this._details.hidden;
|
||||||
@@ -222,7 +225,10 @@ export class HikingTrailsControl {
|
|||||||
if (countries.length === 0) return;
|
if (countries.length === 0) return;
|
||||||
|
|
||||||
if (this._active) this._toggleOnline(false);
|
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
|
this._countryList.innerHTML = countries
|
||||||
.map(
|
.map(
|
||||||
@@ -237,7 +243,10 @@ export class HikingTrailsControl {
|
|||||||
)
|
)
|
||||||
.join("");
|
.join("");
|
||||||
this._countryList.querySelectorAll(".hiking-trail-countries__toggle").forEach((input) => {
|
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;
|
if (!input || input.checked) return;
|
||||||
input.checked = true;
|
input.checked = true;
|
||||||
this._toggleCountry(code, 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) {
|
_toggleOnline(active) {
|
||||||
|
|||||||
+382
-141
@@ -1,18 +1,17 @@
|
|||||||
import { Popup } from "/vendor/maplibre-gl/maplibre-gl.mjs";
|
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 { svgToImageData, badgeImageId, escapeHtml } from "/js/gpx.js";
|
||||||
import { isLoggedIn } from "/js/auth.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
|
// Live data off the home MQTT broker (app.rb's /api/live, LiveStore): two
|
||||||
// position from the LTE GNSS tracker, and the ITS-G5 stations its receiver
|
// Overlays items, "Tracker" (the GNSS tracker: position, trail, an optional
|
||||||
// hears. An Overlays item; polled like the GNSS control, since the server
|
// floating info card) and "ITS-G5" (stations its receiver hears). One
|
||||||
// side only holds the latest state anyway.
|
// shared poller feeds both, running only while either is on.
|
||||||
|
|
||||||
const SOURCE_ID = "live-points";
|
|
||||||
const POLL_INTERVAL_MS = 2000;
|
const POLL_INTERVAL_MS = 2000;
|
||||||
const VEHICLE_COLOR = "#1a1a1a";
|
|
||||||
const VEHICLE_ICON_ID = "live-vehicle-icon";
|
|
||||||
const ICON_IMAGE_SIZE = 48;
|
const ICON_IMAGE_SIZE = 48;
|
||||||
|
const TRAIL_CHOICES = [0, 1, 2, 4, 8, 24];
|
||||||
const DENM_COLOR = "#e63946";
|
const DENM_COLOR = "#e63946";
|
||||||
// ITS stations by ETSI station type (mcu-its-g5's decode.h names).
|
// ITS stations by ETSI station type (mcu-its-g5's decode.h names).
|
||||||
const STATION_COLORS = {
|
const STATION_COLORS = {
|
||||||
@@ -29,7 +28,6 @@ const STATION_COLORS = {
|
|||||||
pedestrian: "#7cc957",
|
pedestrian: "#7cc957",
|
||||||
roadSideUnit: "#546619",
|
roadSideUnit: "#546619",
|
||||||
};
|
};
|
||||||
const LAYERS = ["live-its", "live-its-label", "live-vehicle-badge", "live-vehicle-icon", "live-vehicle-label"];
|
|
||||||
|
|
||||||
function ago(seconds) {
|
function ago(seconds) {
|
||||||
if (seconds < 60) return `${seconds} s ago`;
|
if (seconds < 60) return `${seconds} s ago`;
|
||||||
@@ -37,44 +35,161 @@ function ago(seconds) {
|
|||||||
return `${Math.round(seconds / 3600)} h ago`;
|
return `${Math.round(seconds / 3600)} h ago`;
|
||||||
}
|
}
|
||||||
|
|
||||||
// "passengerCar" → "passenger car"
|
|
||||||
function stationLabel(station) {
|
function stationLabel(station) {
|
||||||
return String(station || "unknown").replace(/([a-z])([A-Z])/g, "$1 $2").toLowerCase();
|
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 `<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>`;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 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) {
|
constructor(map) {
|
||||||
this._map = map;
|
this._map = map;
|
||||||
this._enabled = false;
|
this._enabled = false;
|
||||||
this._data = null;
|
this._data = null;
|
||||||
this._timer = null;
|
|
||||||
this._centered = false;
|
this._centered = false;
|
||||||
// setStyle() (base map switch) drops custom sources/layers.
|
this._onData = (data) => this._render(data);
|
||||||
map.on("style.load", () => {
|
map.on("style.load", () => {
|
||||||
if (this._enabled) this._addLayers().then(() => this._render());
|
if (this._enabled) this._addLayers().then(() => this._render(this._data));
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
mount(li) {
|
mount(li) {
|
||||||
li.innerHTML = `
|
li.innerHTML = `
|
||||||
<label>
|
<div class="overlays-panel__row">
|
||||||
<input type="checkbox" class="overlays-panel__toggle">
|
<input type="checkbox" class="overlays-panel__toggle">
|
||||||
<span class="overlays-panel__icon">${NPS_SYMBOLS.automobiles}</span>
|
<span class="overlays-panel__icon live-tracker__icon">${NPS_SYMBOLS.automobiles}</span>
|
||||||
<span>Vehicle & ITS-G5</span>
|
<button type="button" class="overlays-panel__name live-tracker__name" aria-expanded="false">Tracker</button>
|
||||||
</label>
|
</div>
|
||||||
<p class="live-panel__status" hidden></p>
|
<p class="live-panel__status" hidden></p>
|
||||||
|
<div class="overlays-panel__details live-tracker__settings" hidden>
|
||||||
|
<label class="live-tracker__row"><input type="checkbox" class="live-tracker__card-toggle"> Info card on the map</label>
|
||||||
|
<label class="live-tracker__row">Card opacity <input type="range" class="live-tracker__card-opacity" min="0.2" max="1" step="0.05"></label>
|
||||||
|
<label class="live-tracker__row">Trail <select class="live-tracker__trail">${TRAIL_CHOICES.map((h) => `<option value="${h}">${h ? `last ${h} h` : "off"}</option>`).join("")}</select></label>
|
||||||
|
<label class="live-tracker__row"><input type="checkbox" class="live-tracker__logging"> Log positions (keeps the trail across restarts)</label>
|
||||||
|
<input type="text" class="live-tracker__name-input" maxlength="40" placeholder="Name">
|
||||||
|
<div class="live-tracker__style"></div>
|
||||||
|
<button type="button" class="live-tracker__save">Save</button>
|
||||||
|
</div>
|
||||||
`;
|
`;
|
||||||
this._toggle = li.querySelector(".overlays-panel__toggle");
|
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._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) => {
|
this._status.addEventListener("click", (event) => {
|
||||||
if (event.target.closest(".live-panel__show")) this._showVehicle();
|
if (event.target.closest(".live-panel__show")) this._showTracker();
|
||||||
});
|
});
|
||||||
if (!isLoggedIn()) {
|
if (!isLoggedIn()) {
|
||||||
this._toggle.disabled = true;
|
this._toggle.disabled = true;
|
||||||
li.title = "Log in to see the car's live data";
|
li.title = "Log in to see the tracker";
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
this._toggle.addEventListener("change", () => (this._toggle.checked ? this._enable() : this._disable()));
|
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() {
|
async _enable() {
|
||||||
@@ -83,50 +198,239 @@ export class LiveControl {
|
|||||||
this._status.hidden = false;
|
this._status.hidden = false;
|
||||||
this._status.textContent = "Connecting…";
|
this._status.textContent = "Connecting…";
|
||||||
await this._addLayers();
|
await this._addLayers();
|
||||||
this._poll();
|
poller.subscribe(this._onData);
|
||||||
}
|
}
|
||||||
|
|
||||||
_disable() {
|
_disable() {
|
||||||
this._enabled = false;
|
this._enabled = false;
|
||||||
clearTimeout(this._timer);
|
poller.unsubscribe(this._onData);
|
||||||
this._status.hidden = true;
|
this._status.hidden = true;
|
||||||
for (const id of LAYERS) if (this._map.getLayer(id)) this._map.removeLayer(id);
|
this._card?.remove();
|
||||||
if (this._map.getSource(SOURCE_ID)) this._map.removeSource(SOURCE_ID);
|
this._card = null;
|
||||||
|
removeLayers(this._map, TRACKER_LAYERS, [TRACKER_SOURCE, TRAIL_SOURCE]);
|
||||||
}
|
}
|
||||||
|
|
||||||
async _poll() {
|
_showTracker() {
|
||||||
clearTimeout(this._timer);
|
const t = this._data?.tracker;
|
||||||
try {
|
if (t) this._map.flyTo({ center: [t.longitude, t.latitude], zoom: Math.max(this._map.getZoom(), 14) });
|
||||||
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() {
|
async _addLayers() {
|
||||||
if (this._map.getSource(SOURCE_ID)) return;
|
if (this._map.getSource(TRACKER_SOURCE)) return;
|
||||||
await this._registerImages();
|
const empty = { type: "FeatureCollection", features: [] };
|
||||||
if (this._map.getSource(SOURCE_ID)) return; // a style.load raced this
|
this._map.addSource(TRAIL_SOURCE, { type: "geojson", data: empty });
|
||||||
this._map.addSource(SOURCE_ID, { type: "geojson", data: { type: "FeatureCollection", features: [] } });
|
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)} · <button type="button" class="live-panel__show">show</button>`
|
||||||
|
: `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 = `<div class="live-tracker-card__title"><span class="live-tracker-card__icon" style="background:${escapeHtml(s.color)}">${POI_ICONS[s.icon] || NPS_SYMBOLS.automobiles}</span>${escapeHtml(s.name)}</div>
|
||||||
|
<table>${rows.map(([k, v]) => `<tr><th>${k}</th><td>${escapeHtml(v)}</td></tr>`).join("")}</table>`;
|
||||||
|
}
|
||||||
|
|
||||||
|
_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 = `
|
||||||
|
<label>
|
||||||
|
<input type="checkbox" class="overlays-panel__toggle">
|
||||||
|
<span class="overlays-panel__icon">${NPS_SYMBOLS.radios}</span>
|
||||||
|
<span>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");
|
||||||
|
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({
|
this._map.addLayer({
|
||||||
id: "live-its",
|
id: "live-its",
|
||||||
type: "circle",
|
type: "circle",
|
||||||
source: SOURCE_ID,
|
source: ITS_SOURCE,
|
||||||
filter: ["==", ["get", "kind"], "its"],
|
|
||||||
paint: {
|
paint: {
|
||||||
"circle-radius": ["case", ["==", ["get", "msg"], "DENM"], 8, 6],
|
"circle-radius": ["case", ["==", ["get", "msg"], "DENM"], 8, 6],
|
||||||
"circle-color": ["get", "color"],
|
"circle-color": ["get", "color"],
|
||||||
@@ -137,117 +441,54 @@ export class LiveControl {
|
|||||||
this._map.addLayer({
|
this._map.addLayer({
|
||||||
id: "live-its-label",
|
id: "live-its-label",
|
||||||
type: "symbol",
|
type: "symbol",
|
||||||
source: SOURCE_ID,
|
source: ITS_SOURCE,
|
||||||
filter: ["==", ["get", "kind"], "its"],
|
|
||||||
minzoom: 12,
|
minzoom: 12,
|
||||||
layout: { "text-field": ["get", "label"], "text-font": ["Noto Sans Regular"], "text-size": 11, "text-offset": [0, 1.2], "text-anchor": "top" },
|
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 },
|
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) {
|
if (!this._interactive) {
|
||||||
this._interactive = true;
|
this._interactive = true;
|
||||||
for (const id of ["live-its", "live-vehicle-badge"]) {
|
this._map.on("click", "live-its", (event) => this._popup(event.features[0].properties, event.lngLat));
|
||||||
this._map.on("click", id, (event) => this._popup(event.features[0], event.lngLat));
|
this._map.on("mouseenter", "live-its", () => (this._map.getCanvas().style.cursor = "pointer"));
|
||||||
this._map.on("mouseenter", id, () => (this._map.getCanvas().style.cursor = "pointer"));
|
this._map.on("mouseleave", "live-its", () => (this._map.getCanvas().style.cursor = ""));
|
||||||
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() {
|
_render(data) {
|
||||||
const data = this._data;
|
if (!this._enabled) return;
|
||||||
if (!data) return;
|
this._data = data;
|
||||||
const features = [];
|
if (!data) {
|
||||||
const vehicle = data.vehicle;
|
this._status.textContent = "Live data unavailable";
|
||||||
if (vehicle) {
|
return;
|
||||||
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) {
|
if (!data.available) {
|
||||||
this._status.textContent = "No MQTT broker configured on the server";
|
this._status.textContent = "No MQTT broker configured on the server";
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
const car = vehicle ? `Car ${ago(vehicle.age)} · <button type="button" class="live-panel__show">show</button>` : "No car position yet";
|
const stations = data.its || [];
|
||||||
const its = data.its?.length ? `${data.its.length} ITS-G5 station${data.its.length === 1 ? "" : "s"}` : "no ITS-G5 stations heard";
|
this._status.textContent = stations.length ? `${stations.length} station${stations.length === 1 ? "" : "s"} heard` : "No stations heard";
|
||||||
this._status.innerHTML = `${car} · ${its}`;
|
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(feature, lngLat) {
|
_popup(p, lngLat) {
|
||||||
const p = feature.properties;
|
const html = popupTable(`ITS-G5 ${escapeHtml(p.msg)}`, [
|
||||||
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)],
|
["Station", stationLabel(p.station)],
|
||||||
["Speed", `${Math.round(p.speed)} km/h`],
|
["Speed", `${Math.round(p.speed)} km/h`],
|
||||||
["Heading", `${Math.round(p.heading)}°`],
|
["Heading", `${Math.round(p.heading)}°`],
|
||||||
["Signal", `${p.rssi} dBm${p.secured === true || p.secured === "true" ? " · signed" : ""}`],
|
["Signal", `${p.rssi} dBm${p.secured === true || p.secured === "true" ? " · signed" : ""}`],
|
||||||
["Heard", ago(p.age)],
|
["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);
|
new Popup({ maxWidth: "260px" }).setLngLat(lngLat).setHTML(html).addTo(this._map);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
+23
-21
@@ -6,7 +6,7 @@ import { RadarControl } from "/js/radar.js";
|
|||||||
import { ShadowControl } from "/js/shadow.js";
|
import { ShadowControl } from "/js/shadow.js";
|
||||||
import { ContourControl } from "/js/contour.js";
|
import { ContourControl } from "/js/contour.js";
|
||||||
import { HikingTrailsControl } from "/js/hiking_trails.js";
|
import { HikingTrailsControl } from "/js/hiking_trails.js";
|
||||||
import { LiveControl } from "/js/live.js";
|
import { TrackerControl, ItsControl } from "/js/live.js";
|
||||||
import { NpsControl } from "/js/nps.js";
|
import { NpsControl } from "/js/nps.js";
|
||||||
|
|
||||||
const ICON_IMAGE_SIZE = 48; // rasterized once at this size, rendered much smaller by icon-size below
|
const ICON_IMAGE_SIZE = 48; // rasterized once at this size, rendered much smaller by icon-size below
|
||||||
@@ -188,7 +188,8 @@ export class OverlaysControl {
|
|||||||
this._shadow = new ShadowControl(map);
|
this._shadow = new ShadowControl(map);
|
||||||
this._contour = new ContourControl(map);
|
this._contour = new ContourControl(map);
|
||||||
this._hikingTrails = new HikingTrailsControl(map);
|
this._hikingTrails = new HikingTrailsControl(map);
|
||||||
this._live = new LiveControl(map);
|
this._tracker = new TrackerControl(map);
|
||||||
|
this._its = new ItsControl(map);
|
||||||
this._nps = new NpsControl(map);
|
this._nps = new NpsControl(map);
|
||||||
this._wikiEnabled = false; // the checkbox's own state
|
this._wikiEnabled = false; // the checkbox's own state
|
||||||
this._wikiMoveHandler = null; // the moveend listener driving its live refetch, while enabled
|
this._wikiMoveHandler = null; // the moveend listener driving its live refetch, while enabled
|
||||||
@@ -216,26 +217,27 @@ export class OverlaysControl {
|
|||||||
.querySelector(".basemap-panel__close")
|
.querySelector(".basemap-panel__close")
|
||||||
.addEventListener("click", () => this._togglePanel(false));
|
.addEventListener("click", () => this._togglePanel(false));
|
||||||
|
|
||||||
|
// Items grouped under a heading each; [heading, [[mount, expandable]]].
|
||||||
|
const groups = [
|
||||||
|
["Terrain", [[(li) => this._hillshade.mount(li)], [(li) => this._shadow.mount(li), true], [(li) => this._contour.mount(li)]]],
|
||||||
|
["Weather", [[(li) => this._radar.mount(li), true]]],
|
||||||
|
["Places & trails", [[(li) => this._hikingTrails.mount(li), true], [(li) => this._mountWiki(li)], [(li) => this._nps.mount(li)]]],
|
||||||
|
["Live", [[(li) => this._tracker.mount(li)], [(li) => this._its.mount(li)]]],
|
||||||
|
];
|
||||||
const list = this._panel.querySelector(".overlays-panel__list");
|
const list = this._panel.querySelector(".overlays-panel__list");
|
||||||
list.innerHTML = `
|
list.innerHTML = "";
|
||||||
<li class="overlays-panel__item"></li>
|
for (const [heading, items] of groups) {
|
||||||
<li class="overlays-panel__item"></li>
|
const head = document.createElement("li");
|
||||||
<li class="overlays-panel__item overlays-panel__item--expandable"></li>
|
head.className = "overlays-panel__group";
|
||||||
<li class="overlays-panel__item overlays-panel__item--expandable"></li>
|
head.textContent = heading;
|
||||||
<li class="overlays-panel__item"></li>
|
list.appendChild(head);
|
||||||
<li class="overlays-panel__item overlays-panel__item--expandable"></li>
|
for (const [mount, expandable] of items) {
|
||||||
<li class="overlays-panel__item"></li>
|
const li = document.createElement("li");
|
||||||
<li class="overlays-panel__item"></li>
|
li.className = `overlays-panel__item${expandable ? " overlays-panel__item--expandable" : ""}`;
|
||||||
`;
|
list.appendChild(li);
|
||||||
const [hillshadeItem, wikiItem, radarItem, shadowItem, contourItem, hikingTrailsItem, liveItem, npsItem] = list.children;
|
mount(li);
|
||||||
this._hillshade.mount(hillshadeItem);
|
}
|
||||||
this._mountWiki(wikiItem);
|
}
|
||||||
this._radar.mount(radarItem);
|
|
||||||
this._shadow.mount(shadowItem);
|
|
||||||
this._contour.mount(contourItem);
|
|
||||||
this._hikingTrails.mount(hikingTrailsItem);
|
|
||||||
this._live.mount(liveItem);
|
|
||||||
this._nps.mount(npsItem);
|
|
||||||
|
|
||||||
onlyOneSidePanelOpen(this._panel, () => this._icon.classList.remove("active"));
|
onlyOneSidePanelOpen(this._panel, () => this._icon.classList.remove("active"));
|
||||||
|
|
||||||
|
|||||||
+15
-7
@@ -137,22 +137,30 @@ class AppTest < Minitest::Test
|
|||||||
assert_equal 401, request.get("/api/live").status
|
assert_equal 401, request.get("/api/live").status
|
||||||
end
|
end
|
||||||
|
|
||||||
# The car's last position stays (with its age); ITS stations expire.
|
# MQTT messages land in the tracker / ITS-G5 parts of /api/live.
|
||||||
def test_live_keeps_the_vehicle_and_drops_stale_its_stations
|
def test_live_routes_topics_into_the_snapshot
|
||||||
app = Maptool::App
|
app = Maptool::App
|
||||||
now = Time.now.to_f
|
now = Time.now.to_f
|
||||||
app.record_live(app::TRACKER_TOPIC, '{"latitude":48.1,"longitude":17.1,"speed":3}', at: now - 600)
|
app.record_live(app::TRACKER_TOPIC, '{"latitude":48.1,"longitude":17.1,"speed":3}', at: now - 600)
|
||||||
app.record_live(app::ITS_TOPIC, '{"id":"old","msg":"CAM","lat":48,"lon":17}', at: now - app::ITS_STALE_AFTER - 5)
|
app.record_live(app::TRACKER_POWER_TOPIC, "ON")
|
||||||
app.record_live(app::ITS_TOPIC, '{"id":"new","msg":"DENM","lat":48.2,"lon":17.2}', at: now)
|
app.record_live(app::ITS_TOPIC, '{"id":"new","msg":"DENM","lat":48.2,"lon":17.2}', at: now)
|
||||||
app.record_live(app::ITS_TOPIC, "not json")
|
app.record_live(app::ITS_TOPIC, "not json")
|
||||||
body = json_body(request.get("/api/live", **logged_in_env))
|
body = json_body(request.get("/api/live", **logged_in_env))
|
||||||
assert_equal 48.1, body["vehicle"]["latitude"]
|
assert_equal 48.1, body["tracker"]["latitude"]
|
||||||
assert_in_delta 600, body["vehicle"]["age"], 2
|
assert_in_delta 600, body["tracker"]["age"], 2
|
||||||
refute body["vehicle"].key?("received_at")
|
assert_equal true, body["tracker"]["usb_power"]
|
||||||
assert_equal ["new"], body["its"].map { |s| s["id"] }
|
assert_equal ["new"], body["its"].map { |s| s["id"] }
|
||||||
|
assert_equal "Tracker", body["settings"]["name"]
|
||||||
assert_equal false, body["available"] # no MQTT_URL in tests
|
assert_equal false, body["available"] # no MQTT_URL in tests
|
||||||
|
end
|
||||||
|
|
||||||
|
def test_live_settings_require_login_and_save
|
||||||
|
assert_equal 401, request.put("/api/live/settings", params: { name: "x" }).status
|
||||||
|
body = json_body(request.put("/api/live/settings", params: { name: "Car", trail_hours: "2" }, **logged_in_env))
|
||||||
|
assert_equal "Car", body["name"]
|
||||||
|
assert_equal 2, body["trail_hours"]
|
||||||
ensure
|
ensure
|
||||||
app::LIVE_MUTEX.synchronize { app::LIVE.replace(vehicle: nil, its: {}) }
|
Maptool::App::LIVE_STORE.update_settings("name" => "Tracker", "trail_hours" => "1")
|
||||||
end
|
end
|
||||||
|
|
||||||
# --- auth guard ---
|
# --- auth guard ---
|
||||||
|
|||||||
@@ -0,0 +1,79 @@
|
|||||||
|
require_relative "test_helper"
|
||||||
|
require "tmpdir"
|
||||||
|
require_relative "../lib/maptool/live_store"
|
||||||
|
|
||||||
|
class LiveStoreTest < Minitest::Test
|
||||||
|
def setup
|
||||||
|
@dir = Dir.mktmpdir("maptool-live-test")
|
||||||
|
end
|
||||||
|
|
||||||
|
def teardown
|
||||||
|
FileUtils.remove_entry(@dir)
|
||||||
|
end
|
||||||
|
|
||||||
|
def position(lat, lon, extra = {})
|
||||||
|
{ "latitude" => lat, "longitude" => lon }.merge(extra)
|
||||||
|
end
|
||||||
|
|
||||||
|
def test_tracker_snapshot_with_age_power_and_settings
|
||||||
|
store = Maptool::LiveStore.new(@dir)
|
||||||
|
now = Time.now.to_f
|
||||||
|
store.record_tracker(position(48.1, 17.1, "battery_level" => 80), at: now - 30)
|
||||||
|
store.record_usb_power("ON")
|
||||||
|
tracker = store.snapshot(now: now)[:tracker]
|
||||||
|
assert_equal 48.1, tracker["latitude"]
|
||||||
|
assert_equal 30, tracker["age"]
|
||||||
|
assert_equal true, tracker["usb_power"]
|
||||||
|
refute tracker.key?("received_at")
|
||||||
|
assert_equal "Tracker", store.snapshot[:settings]["name"]
|
||||||
|
store.record_usb_power("OFF")
|
||||||
|
assert_equal false, store.snapshot(now: now)[:tracker]["usb_power"]
|
||||||
|
end
|
||||||
|
|
||||||
|
# A parked tracker repeating itself doesn't grow the trail; moving does,
|
||||||
|
# and the trail shown is only the last trail_hours.
|
||||||
|
def test_trail_grows_on_movement_and_is_cut_to_trail_hours
|
||||||
|
store = Maptool::LiveStore.new(@dir)
|
||||||
|
now = Time.now.to_f
|
||||||
|
store.record_tracker(position(48.0, 17.0), at: now - 7200)
|
||||||
|
store.record_tracker(position(48.0, 17.0), at: now - 7100) # same spot, 100 s later: skipped
|
||||||
|
store.record_tracker(position(48.01, 17.0), at: now - 600) # ~1.1 km on
|
||||||
|
store.record_tracker(position(48.02, 17.0), at: now - 60)
|
||||||
|
assert_equal [[17.0, 48.01], [17.0, 48.02]], store.snapshot(now: now)[:tracker]["trail"] # trail_hours 1
|
||||||
|
store.update_settings("trail_hours" => "4")
|
||||||
|
assert_equal 3, store.snapshot(now: now)[:tracker]["trail"].size
|
||||||
|
store.update_settings("trail_hours" => "0")
|
||||||
|
assert_empty store.snapshot(now: now)[:tracker]["trail"]
|
||||||
|
end
|
||||||
|
|
||||||
|
def test_logged_trail_survives_a_restart_and_unlogged_does_not
|
||||||
|
store = Maptool::LiveStore.new(@dir)
|
||||||
|
now = Time.now.to_f
|
||||||
|
store.record_tracker(position(48.0, 17.0), at: now - 120)
|
||||||
|
store.update_settings("logging" => "true")
|
||||||
|
store.record_tracker(position(48.01, 17.0), at: now - 60)
|
||||||
|
store.record_tracker(position(48.02, 17.0), at: now)
|
||||||
|
|
||||||
|
reloaded = Maptool::LiveStore.new(@dir)
|
||||||
|
reloaded.record_tracker(position(48.02, 17.0), at: now) # same spot: no new point
|
||||||
|
assert_equal [[17.0, 48.01], [17.0, 48.02]], reloaded.snapshot(now: now)[:tracker]["trail"]
|
||||||
|
assert_equal true, reloaded.settings["logging"]
|
||||||
|
end
|
||||||
|
|
||||||
|
def test_settings_are_sanitized_and_persisted
|
||||||
|
store = Maptool::LiveStore.new(@dir)
|
||||||
|
store.update_settings("name" => " Run ", "icon" => "walking", "color" => "#7cc957", "trail_hours" => "2", "evil" => "x")
|
||||||
|
store.update_settings("color" => "red", "trail_hours" => "3", "name" => "")
|
||||||
|
settings = Maptool::LiveStore.new(@dir).settings
|
||||||
|
assert_equal({ "name" => "Run", "icon" => "walking", "color" => "#7cc957", "logging" => false, "trail_hours" => 2 }, settings)
|
||||||
|
end
|
||||||
|
|
||||||
|
def test_its_stations_expire
|
||||||
|
store = Maptool::LiveStore.new(@dir)
|
||||||
|
now = Time.now.to_f
|
||||||
|
store.record_its({ "id" => "old", "lat" => 48, "lon" => 17 }, at: now - Maptool::LiveStore::ITS_STALE_AFTER - 5)
|
||||||
|
store.record_its({ "id" => "new", "lat" => 48, "lon" => 17 }, at: now)
|
||||||
|
store.record_its({ "lat" => 48 }, at: now) # no id: ignored
|
||||||
|
assert_equal ["new"], store.snapshot(now: now)[:its].map { |s| s["id"] }
|
||||||
|
end
|
||||||
|
end
|
||||||
Reference in new issue
Block a user