Vehicle & ITS-G5 overlay: a stdlib MQTT subscriber (MQTT_URL/USERNAME/PASSWORD) keeps the car's LTE tracker position and the ITS-G5 stations heard by mcu-its-g5 (decoded header, stations expire after 60 s), served by /api/live and drawn as a car badge plus stations colored by type with DENM in red; Meshtastic noted in TODO
This commit is contained in:
1 parent
b381ca289f
commit
02c2ef05f8
12 files changed
+608
-12
No files matched your search
@@ -112,6 +112,9 @@ jobs:
|
||||
P4N_USER=${{ secrets.P4N_USER }}
|
||||
P4N_PASSWORD=${{ secrets.P4N_PASSWORD }}
|
||||
P4N_SESSION_COOKIE=${{ secrets.P4N_SESSION_COOKIE }}
|
||||
MQTT_URL=${{ secrets.MQTT_URL }}
|
||||
MQTT_USERNAME=${{ secrets.MQTT_USERNAME }}
|
||||
MQTT_PASSWORD=${{ secrets.MQTT_PASSWORD }}
|
||||
EOF
|
||||
chmod 600 /srv/podman/maptool/.env
|
||||
|
||||
|
||||
@@ -126,17 +126,22 @@ Deprioritized for now — revisit after the sections above land.
|
||||
maptool as the dashboard for the car/van too, not only the map. Idea stage. Most of the data
|
||||
already reaches the home MQTT broker (`mqtt_ext`) from ESPHome nodes in `~/esphome`:
|
||||
|
||||
* [ ] One MQTT subscriber in the maptool server — its own read-only broker user (ACL on just
|
||||
the topics below), a thread like the gpsd client, latest state per key with an expiry, pushed
|
||||
to the browser; one generic "MQTT live" layer/panel rather than one integration per source
|
||||
* [ ] Car position from the LTE GNSS tracker (`mcu-tracker.yaml`, JSON on
|
||||
`mcu-tracker/location`) as another source for the GNSS control — "where is the car" even when
|
||||
away from it
|
||||
* [ ] ITS-G5 (`mcu-its-g5.yaml`, already receiving): publish the decoded header per packet as
|
||||
JSON next to the raw `its/<node>/packet` (type, station type, lat/lon, speed, heading —
|
||||
`its_g5_decode::stats.last` already has them; throttle CAMs to ~1 Hz per station), so maptool
|
||||
needs no ASN.1 decoding; on the map: stations by type (car, truck, roadside unit), DENM events
|
||||
as warning icons that expire
|
||||
* [x] One MQTT subscriber in the maptool server — `lib/maptool/mqtt_client.rb` (stdlib MQTT
|
||||
3.1.1, QoS 0, reconnects), `MQTT_URL`/`MQTT_USERNAME`/`MQTT_PASSWORD` (read-only broker
|
||||
user), latest state in app.rb's `LIVE`, `GET /api/live`; the "Vehicle & ITS-G5" overlay
|
||||
(`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)
|
||||
* [ ] … 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
|
||||
* [ ] Meshtastic nodes (each has GNSS) — incl. a running tracker to follow on the map. Not in
|
||||
the broker today: the HA Meshtastic integration only makes `device_tracker` entities and
|
||||
doesn't republish them. Options: read HA's REST API (`/api/states`, `device_tracker` with
|
||||
coordinates; needs `HA_URL` + a read-only long-lived `HA_TOKEN`, and covers any other HA
|
||||
tracker too), HA's `mqtt_statestream` (one topic per attribute — awkward), or MQTT with JSON
|
||||
output on `rpi-meshtastic` itself (fights the HA integration over the single TCP API while
|
||||
configuring, see home-gitops docs/embedded-services.adoc)
|
||||
* [ ] Car CAN data (`mcu-car-can.yaml`, today over the native API to HA): add `mqtt:` like the
|
||||
tracker; RPM, doors, parking brake, … in a dashboard panel
|
||||
* [ ] IMU shocks along a drive as a map layer — road roughness / potholes colored by intensity
|
||||
|
||||
@@ -10,6 +10,7 @@ require_relative "lib/maptool/gpx_store"
|
||||
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/livetrack_store"
|
||||
require_relative "lib/maptool/livetrack_client"
|
||||
require_relative "lib/maptool/kiwix"
|
||||
@@ -158,6 +159,9 @@ module Maptool
|
||||
KIWIX_URL = ENV.fetch("KIWIX_URL", "")
|
||||
# The valhalla container (docker-compose.yaml), reached server side only.
|
||||
VALHALLA_URL = ENV.fetch("VALHALLA_URL", "")
|
||||
# The home MQTT broker the car's ESPHome nodes publish to (empty = off):
|
||||
# mqtt:// or mqtts://, with a read-only user. See LIVE below.
|
||||
MQTT_URL = ENV.fetch("MQTT_URL", "")
|
||||
Routing.install_service_script(DATA_DIR)
|
||||
|
||||
# Login delegates to the Gitea instance the user already has an account
|
||||
@@ -301,6 +305,43 @@ 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).
|
||||
TRACKER_TOPIC = "mcu-tracker/location"
|
||||
ITS_TOPIC = "mcu-its-g5/decoded"
|
||||
ITS_STALE_AFTER = 60 # seconds
|
||||
|
||||
LIVE = { vehicle: nil, its: {} }
|
||||
LIVE_MUTEX = Mutex.new
|
||||
|
||||
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
|
||||
end
|
||||
rescue JSON::ParserError
|
||||
nil
|
||||
end
|
||||
|
||||
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) }
|
||||
end
|
||||
end
|
||||
|
||||
get "/" do
|
||||
erb :index, locals: { logged_in: logged_in?, user: session[:user], revision: REVISION }
|
||||
end
|
||||
@@ -970,6 +1011,16 @@ module Maptool
|
||||
json(type: "FeatureCollection", features: features)
|
||||
end
|
||||
|
||||
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
|
||||
end
|
||||
|
||||
get "/api/gnss/position" do
|
||||
require_login!
|
||||
GNSS_LATEST_MUTEX.synchronize do
|
||||
|
||||
@@ -31,6 +31,11 @@ services:
|
||||
# Optional: blank disables the LiveTrack webhook endpoint rather than
|
||||
# failing to start, since it's not needed for the app's core function.
|
||||
LIVETRACK_WEBHOOK_SECRET: ${LIVETRACK_WEBHOOK_SECRET:-}
|
||||
# Optional: the home MQTT broker with the car's live data (GNSS
|
||||
# tracker, ITS-G5) — a read-only user; blank turns /api/live off.
|
||||
MQTT_URL: ${MQTT_URL:-}
|
||||
MQTT_USERNAME: ${MQTT_USERNAME:-}
|
||||
MQTT_PASSWORD: ${MQTT_PASSWORD:-}
|
||||
# Optional, only read by data/plugins/p4n2gpx/'s own p4n2gpx.rb (not
|
||||
# part of this repo — see docs/deployment.adoc) if that private
|
||||
# plugin is present; blank just means it fails with its own "could
|
||||
|
||||
@@ -162,6 +162,15 @@ id/secret to store as the two `OAUTH_CLIENT_*` secrets above.
|
||||
usernames, e.g. `randy,friend1,friend2` — not their emails, the
|
||||
`login` field from Gitea's `/api/v1/user`.
|
||||
|
||||
Optional: `MQTT_URL`, `MQTT_USERNAME`, `MQTT_PASSWORD` (same names as
|
||||
secrets and in `.env`) — the home MQTT broker the car's ESPHome nodes
|
||||
publish to, read by `/api/live` (the "Vehicle & ITS-G5" overlay): the
|
||||
GNSS tracker's `mcu-tracker/location` and the ITS-G5 receiver's
|
||||
`mcu-its-g5/decoded`. Use a read-only broker user limited to those
|
||||
topics. Blank `MQTT_URL` turns it off. The URL needs a name the
|
||||
container can resolve — `ha.local` (mDNS) doesn't resolve inside it,
|
||||
`mqtt://ha.priesol.net:1883` does.
|
||||
|
||||
== GNSS simulator
|
||||
|
||||
`docker-compose.yaml`'s `gnss-simulator` service (`bin/gnss_simulator.rb`,
|
||||
|
||||
@@ -0,0 +1,153 @@
|
||||
require "socket"
|
||||
require "openssl"
|
||||
require "securerandom"
|
||||
require "uri"
|
||||
|
||||
module Maptool
|
||||
# A minimal MQTT 3.1.1 subscriber (stdlib only, like GpsdClient): connects,
|
||||
# subscribes to a few topics at QoS 0 and yields every message, for as long
|
||||
# as the block keeps running. Enough for reading sensor topics off the home
|
||||
# broker; no publishing, no QoS 1/2 delivery guarantees, no persistent
|
||||
# session. mqtt:// is plain TCP, mqtts:// is TLS.
|
||||
class MqttClient
|
||||
class ProtocolError < StandardError; end
|
||||
|
||||
RECONNECT_DELAY = 5 # seconds
|
||||
KEEPALIVE = 30 # seconds, sent in CONNECT; a PINGREQ goes out at half of it
|
||||
|
||||
def initialize(url:, topics:, username: nil, password: nil, client_id: "maptool-#{SecureRandom.hex(4)}")
|
||||
@uri = URI(url)
|
||||
raise ArgumentError, "unsupported MQTT URL #{url}" unless %w[mqtt mqtts].include?(@uri.scheme)
|
||||
|
||||
@topics = topics
|
||||
@username = username.to_s.empty? ? nil : username
|
||||
@password = password.to_s.empty? ? nil : password
|
||||
@client_id = client_id
|
||||
end
|
||||
|
||||
# Never returns under normal operation: reconnects after any I/O or
|
||||
# protocol error, so a broker that's down or restarting isn't fatal.
|
||||
def each_message(&block)
|
||||
loop do
|
||||
session(&block)
|
||||
rescue SystemCallError, IOError, SocketError, OpenSSL::SSL::SSLError, ProtocolError => e
|
||||
warn "[mqtt] #{e.class}: #{e.message} — retrying in #{RECONNECT_DELAY}s"
|
||||
sleep RECONNECT_DELAY
|
||||
end
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def session
|
||||
socket = open_socket
|
||||
write_packet(socket, 0x10, connect_payload)
|
||||
type, _flags, body = read_packet(socket)
|
||||
raise ProtocolError, "no CONNACK" unless type == 2
|
||||
raise ProtocolError, "connection refused (code #{body.getbyte(1)})" unless body.getbyte(1).zero?
|
||||
|
||||
write_packet(socket, 0x82, [1].pack("n") + @topics.map { |t| utf8(t) + "\x00".b }.join)
|
||||
last_sent = last_received = now
|
||||
loop do
|
||||
if readable?(socket, 1)
|
||||
type, flags, body = read_packet(socket)
|
||||
last_received = now
|
||||
yield(*parse_publish(socket, flags, body)) if type == 3
|
||||
end
|
||||
if now - last_sent >= KEEPALIVE / 2
|
||||
write_packet(socket, 0xC0, "".b)
|
||||
last_sent = now
|
||||
end
|
||||
raise ProtocolError, "broker silent for #{KEEPALIVE * 2}s" if now - last_received > KEEPALIVE * 2
|
||||
end
|
||||
ensure
|
||||
socket&.close
|
||||
end
|
||||
|
||||
def open_socket
|
||||
tls = @uri.scheme == "mqtts"
|
||||
tcp = Socket.tcp(@uri.host, @uri.port || (tls ? 8883 : 1883), connect_timeout: 10)
|
||||
return tcp unless tls
|
||||
|
||||
context = OpenSSL::SSL::SSLContext.new
|
||||
context.set_params(verify_mode: OpenSSL::SSL::VERIFY_PEER)
|
||||
ssl = OpenSSL::SSL::SSLSocket.new(tcp, context)
|
||||
ssl.hostname = @uri.host
|
||||
ssl.sync_close = true
|
||||
ssl.connect
|
||||
ssl
|
||||
end
|
||||
|
||||
def connect_payload
|
||||
flags = 0x02 # clean session
|
||||
flags |= 0x80 if @username
|
||||
flags |= 0x40 if @password
|
||||
utf8("MQTT") + [4, flags, KEEPALIVE].pack("CCn") + utf8(@client_id) +
|
||||
(@username ? utf8(@username) : "".b) + (@password ? utf8(@password) : "".b)
|
||||
end
|
||||
|
||||
# [topic, payload]; a QoS 1 message (the broker may downgrade to our 0,
|
||||
# but don't count on it) is acknowledged so it isn't redelivered.
|
||||
def parse_publish(socket, flags, body)
|
||||
qos = (flags >> 1) & 0x03
|
||||
length = body.unpack1("n")
|
||||
topic = body.byteslice(2, length).force_encoding("UTF-8")
|
||||
offset = 2 + length
|
||||
if qos.positive?
|
||||
packet_id = body.byteslice(offset, 2)
|
||||
write_packet(socket, 0x40, packet_id) if qos == 1
|
||||
offset += 2
|
||||
end
|
||||
[topic, body.byteslice(offset..).force_encoding("UTF-8")]
|
||||
end
|
||||
|
||||
def write_packet(socket, header, body)
|
||||
socket.write([header].pack("C") + encode_length(body.bytesize) + body)
|
||||
end
|
||||
|
||||
def read_packet(socket)
|
||||
header = read_exactly(socket, 1).ord
|
||||
length = 0
|
||||
multiplier = 1
|
||||
loop do
|
||||
byte = read_exactly(socket, 1).ord
|
||||
length += (byte & 0x7F) * multiplier
|
||||
break if byte < 0x80
|
||||
|
||||
multiplier *= 128
|
||||
raise ProtocolError, "bad remaining length" if multiplier > 128**3
|
||||
end
|
||||
[header >> 4, header & 0x0F, length.zero? ? "".b : read_exactly(socket, length)]
|
||||
end
|
||||
|
||||
def read_exactly(socket, count)
|
||||
data = socket.read(count)
|
||||
raise EOFError, "connection closed" if data.nil? || data.bytesize < count
|
||||
|
||||
data
|
||||
end
|
||||
|
||||
def encode_length(length)
|
||||
bytes = []
|
||||
loop do
|
||||
byte = length % 128
|
||||
length /= 128
|
||||
bytes << (length.positive? ? byte | 0x80 : byte)
|
||||
break unless length.positive?
|
||||
end
|
||||
bytes.pack("C*")
|
||||
end
|
||||
|
||||
def utf8(string)
|
||||
[string.bytesize].pack("n") + string.b
|
||||
end
|
||||
|
||||
# An SSLSocket may hold already-decrypted bytes IO.select can't see.
|
||||
def readable?(socket, timeout)
|
||||
(socket.respond_to?(:pending) && socket.pending.positive?) || IO.select([socket], nil, nil, timeout)
|
||||
end
|
||||
|
||||
def now
|
||||
Process.clock_gettime(Process::CLOCK_MONOTONIC)
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -2822,3 +2822,27 @@ body.side-pinned:has(.basemap-panel:not([hidden]), .gpx-panel:not([hidden])) .pr
|
||||
margin: 0 0 8px;
|
||||
color: #666;
|
||||
}
|
||||
|
||||
/* Vehicle & ITS-G5 overlay (live.js): its status line and popup table. */
|
||||
.live-panel__status {
|
||||
margin: 4px 0 0 26px;
|
||||
font-size: 12px;
|
||||
color: #666;
|
||||
}
|
||||
|
||||
.live-panel__show {
|
||||
padding: 0;
|
||||
border: none;
|
||||
background: none;
|
||||
color: var(--accent);
|
||||
font: inherit;
|
||||
text-decoration: underline;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.live-popup th {
|
||||
padding-right: 8px;
|
||||
color: #666;
|
||||
font-weight: normal;
|
||||
text-align: left;
|
||||
}
|
||||
@@ -0,0 +1,253 @@
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -6,6 +6,7 @@ import { RadarControl } from "/js/radar.js";
|
||||
import { ShadowControl } from "/js/shadow.js";
|
||||
import { ContourControl } from "/js/contour.js";
|
||||
import { HikingTrailsControl } from "/js/hiking_trails.js";
|
||||
import { LiveControl } from "/js/live.js";
|
||||
|
||||
const ICON_IMAGE_SIZE = 48; // rasterized once at this size, rendered much smaller by icon-size below
|
||||
const ICON_SIZE = 0.3; // 48 * 0.3 = ~14px, sized to sit inside the marker badge below
|
||||
@@ -186,6 +187,7 @@ export class OverlaysControl {
|
||||
this._shadow = new ShadowControl(map);
|
||||
this._contour = new ContourControl(map);
|
||||
this._hikingTrails = new HikingTrailsControl(map);
|
||||
this._live = new LiveControl(map);
|
||||
this._wikiEnabled = false; // the checkbox's own state
|
||||
this._wikiMoveHandler = null; // the moveend listener driving its live refetch, while enabled
|
||||
this._wikiRequestSeq = 0; // ignores an in-flight refetch a newer one has already superseded
|
||||
@@ -220,14 +222,16 @@ export class OverlaysControl {
|
||||
<li class="overlays-panel__item overlays-panel__item--expandable"></li>
|
||||
<li class="overlays-panel__item"></li>
|
||||
<li class="overlays-panel__item overlays-panel__item--expandable"></li>
|
||||
<li class="overlays-panel__item"></li>
|
||||
`;
|
||||
const [hillshadeItem, wikiItem, radarItem, shadowItem, contourItem, hikingTrailsItem] = list.children;
|
||||
const [hillshadeItem, wikiItem, radarItem, shadowItem, contourItem, hikingTrailsItem, liveItem] = list.children;
|
||||
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);
|
||||
|
||||
onlyOneSidePanelOpen(this._panel, () => this._icon.classList.remove("active"));
|
||||
|
||||
|
||||
@@ -108,6 +108,28 @@ class AppTest < Minitest::Test
|
||||
assert_equal 401, request.get("/api/gnss/position").status
|
||||
end
|
||||
|
||||
def test_live_requires_login
|
||||
assert_equal 401, request.get("/api/live").status
|
||||
end
|
||||
|
||||
# The car's last position stays (with its age); ITS stations expire.
|
||||
def test_live_keeps_the_vehicle_and_drops_stale_its_stations
|
||||
app = Maptool::App
|
||||
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::ITS_TOPIC, '{"id":"old","msg":"CAM","lat":48,"lon":17}', at: now - app::ITS_STALE_AFTER - 5)
|
||||
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")
|
||||
body = json_body(request.get("/api/live", **logged_in_env))
|
||||
assert_equal 48.1, body["vehicle"]["latitude"]
|
||||
assert_in_delta 600, body["vehicle"]["age"], 2
|
||||
refute body["vehicle"].key?("received_at")
|
||||
assert_equal ["new"], body["its"].map { |s| s["id"] }
|
||||
assert_equal false, body["available"] # no MQTT_URL in tests
|
||||
ensure
|
||||
app::LIVE_MUTEX.synchronize { app::LIVE.replace(vehicle: nil, its: {}) }
|
||||
end
|
||||
|
||||
# --- auth guard ---
|
||||
|
||||
def test_write_routes_require_login
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
require_relative "test_helper"
|
||||
require "socket"
|
||||
require_relative "../lib/maptool/mqtt_client"
|
||||
|
||||
class MqttClientTest < Minitest::Test
|
||||
# A one-connection fake broker: checks CONNECT/SUBSCRIBE, then sends a QoS 0
|
||||
# and a QoS 1 PUBLISH and records what the client sends back.
|
||||
def test_connects_subscribes_and_yields_messages
|
||||
server = TCPServer.new("127.0.0.1", 0)
|
||||
port = server.addr[1]
|
||||
seen = {}
|
||||
broker = Thread.new do
|
||||
conn = server.accept
|
||||
type, body = read_packet(conn)
|
||||
seen[:connect] = [type, body]
|
||||
conn.write("\x20\x02\x00\x00".b) # CONNACK, accepted
|
||||
type, body = read_packet(conn)
|
||||
seen[:subscribe] = [type, body]
|
||||
conn.write("\x90\x04\x00\x01\x00\x00".b) # SUBACK
|
||||
conn.write(publish("mcu-tracker/location", '{"latitude":48.1}', qos: 0))
|
||||
conn.write(publish("mcu-its-g5/decoded", '{"id":"a"}', qos: 1, packet_id: 7))
|
||||
seen[:puback] = read_packet(conn)
|
||||
sleep 0.2
|
||||
conn.close
|
||||
end
|
||||
|
||||
client = Maptool::MqttClient.new(url: "mqtt://127.0.0.1:#{port}", username: "maptool", password: "secret",
|
||||
topics: ["mcu-tracker/location", "mcu-its-g5/decoded"], client_id: "test")
|
||||
messages = []
|
||||
worker = Thread.new { client.each_message { |topic, payload| messages << [topic, payload] } }
|
||||
broker.join(5)
|
||||
sleep 0.1
|
||||
worker.kill
|
||||
|
||||
assert_equal [["mcu-tracker/location", '{"latitude":48.1}'], ["mcu-its-g5/decoded", '{"id":"a"}']], messages
|
||||
type, body = seen[:connect]
|
||||
assert_equal 1, type
|
||||
assert_includes body, "MQTT".b
|
||||
assert_equal 0xC2, body.getbyte(7) # clean session + username + password
|
||||
assert_includes body, "maptool".b
|
||||
assert_includes body, "secret".b
|
||||
type, body = seen[:subscribe]
|
||||
assert_equal 8, type
|
||||
assert_includes body, "mcu-its-g5/decoded".b
|
||||
assert_equal [4, "\x00\x07".b], seen[:puback] # PUBACK for packet 7
|
||||
ensure
|
||||
server&.close
|
||||
end
|
||||
|
||||
def test_rejects_other_url_schemes
|
||||
assert_raises(ArgumentError) { Maptool::MqttClient.new(url: "http://broker:1883", topics: []) }
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def read_packet(conn)
|
||||
header = conn.read(1).ord
|
||||
length = conn.read(1).ord # tests stay under 128 bytes
|
||||
[header >> 4, conn.read(length)]
|
||||
end
|
||||
|
||||
def publish(topic, payload, qos:, packet_id: nil)
|
||||
body = [topic.bytesize].pack("n") + topic.b + (qos.positive? ? [packet_id].pack("n") : "".b) + payload.b
|
||||
[0x30 | (qos << 1), body.bytesize].pack("CC") + body
|
||||
end
|
||||
end
|
||||
@@ -17,6 +17,7 @@
|
||||
"/js/gnss.js": "/js/gnss.js?v=<%= ASSET_VERSION %>",
|
||||
"/js/gpx.js": "/js/gpx.js?v=<%= ASSET_VERSION %>",
|
||||
"/js/hiking_trails.js": "/js/hiking_trails.js?v=<%= ASSET_VERSION %>",
|
||||
"/js/live.js": "/js/live.js?v=<%= ASSET_VERSION %>",
|
||||
"/js/icons.js": "/js/icons.js?v=<%= ASSET_VERSION %>",
|
||||
"/js/livetrack.js": "/js/livetrack.js?v=<%= ASSET_VERSION %>",
|
||||
"/js/locate.js": "/js/locate.js?v=<%= ASSET_VERSION %>",
|
||||
|
||||
Reference in new issue
Block a user