Compare commits

..
3 Commits
17 changed files with 779 additions and 35 deletions

No files matched your search

+45 -5
View File
@@ -174,11 +174,22 @@ already reaches the home MQTT broker (`mqtt_ext`) from ESPHome nodes in `~/espho
** [ ] Discover our esphome-canopen nodes over SDO (0x1008 name, 0x2001 entity types, ** [ ] Discover our esphome-canopen nodes over SDO (0x1008 name, 0x2001 entity types,
0x2000+0x10·N names/units/min/max, 0x1A00+n TPDO mapping): their entities decoded with no 0x2000+0x10·N names/units/min/max, 0x1A00+n TPDO mapping): their entities decoded with no
`can.json`; 0x1008/0x1018 identity for any CANopen device `can.json`; 0x1008/0x1018 identity for any CANopen device
** [ ] A configurable dashboard overlay over the map (like dashcams burn it in): widgets picked ** [x] A node that stops its heartbeat (3 missed) is flagged: one journal line when it goes
and placed per screen, each bound to a signal — speed, turn signals, brake, … — and one silent and when it's back (`can: node 2 silent, last heartbeat …`), red in `/can.html`
combined inclinometer (Pajero style, but one instrument, not three): compass heading, pitch ** [x] Dashboard overlay (Overlays → Live → Dashboard, `public/js/dashboard.js`): one combined
and roll, all from the GNSS node (pitch/roll already in its TPDO1; the HMC5883L compass inclinometer (Pajero style, but one instrument, not three) — compass ring around a rear view
still to add to its firmware); GNSS course as the heading until then (roll) and a side view (pitch), amber past 20° roll / 25° pitch, red past 1.5× — and the
speed; widgets on/off per device. Heading: driving (≥ 1.5 m/s) the GNSS course from fixes
≥ 5 m apart, standing still the compass (`imu.heading`), else the last course, dimmed
*** [ ] Widgets placed per screen and bound to any signal — turn signals, brake, … once the
car's bridge puts them on the bus
*** [x] The compass (HMC5883L on node 0x21, TPDO 0x221) as `imu.heading` + `mag.x/y/z` in
`can.json` — for orienting while standing; driving uses the GNSS course
*** [ ] Tilt compensation (pitch/roll from the IMU) and hard-/soft-iron calibration of the
heading — ESPHome's is a plain `atan2(y, x)`; in the node, like the levelling
*** [ ] IMU every 100–200 ms (the node reads it every 5 s today) and levelling done by the
node itself, set by an SDO write from a button in `/can.html` — design in home-gitops
`docs/canopen-nodes.adoc` ("Nulovanie náklonu a rýchlosť IMU")
=== 3D navigation mode === 3D navigation mode
@@ -186,6 +197,35 @@ already reaches the home MQTT broker (`mqtt_ext`) from ESPHome nodes in `~/espho
heading, pitched ~60°, smooth easing — the tracker's "Navigate" (see the Tablet-friendly heading, pitched ~60°, smooth easing — the tracker's "Navigate" (see the Tablet-friendly
section); follows the MQTT tracker, not the browser's own GNSS control yet section); follows the MQTT tracker, not the browser's own GNSS control yet
** [ ] Real 3D relief from the raster-dem terrain and Liberty's `building-3d` extrusions while navigating ** [ ] Real 3D relief from the raster-dem terrain and Liberty's `building-3d` extrusions while navigating
* [ ] Full navigation (the car's main screen while driving; everything from our own Valhalla
tiles, no online service — Valhalla has OSM `maxspeed`, `traffic_signals` and turn lanes)
** [x] Basics on the dashboard (`public/js/dashboard.js`): the speed limit as a sign and a red
warning over it (+3 km/h); on the route panel's route (≤ 50 m off it): the next limit
change and its distance, the distance to the next traffic signal, the next maneuver and
its lanes (from 1 km, the lanes to take highlighted). `/api/route` gains `speed_limits`
(km → limit, per change), `signals` ([lon, lat, km]) and `maneuvers[].lanes`
(`turn_lanes`), from the same `trace_attributes` pass as the countries; the route's
signals drawn on the map from z14. Off the route / with none: `POST /api/road`
(map-matched last fixes → the road's name and limit), every 4 s while moving
** [ ] Speed limits that aren't on the edge: `maxspeed:conditional` (time, wet), variable
signs, `zone:maxspeed` defaults per country (Valhalla leaves untagged roads empty — show
the country's default by road class?), the vehicle's own limits (a camper > 3.5 t: 80/100)
** [ ] Rerouting when off the route (> 50 m for a while): a new route from the position to the
remaining points
** [ ] Turn-by-turn: the next maneuver big (arrow, distance, street), voice
(`speechSynthesis`), the route ahead highlighted / the driven part greyed
** [ ] Lanes as proper arrows (SVG per direction bit, not Unicode) and only the lanes Valhalla
marks for the maneuver; through-lanes guidance before motorway exits
** [ ] Traffic signals with no route: around the position (Valhalla `locate` or the offline
PBF), and only for the direction driven (`traffic_signals:direction`)
** [ ] The "Navigate" follow mode for the CAN GNSS position (today the MQTT tracker and the
browser's GNSS control), the dashboard as part of the driving-mode UI
** [ ] `locate()` scans the whole route each fix — a window around the last hit on long routes
** [x] GNSS simulation for trying it without the car (`lib/maptool/gnss_sim.rb`, Dashboard
settings → "Simulate driving from the map center", `POST/DELETE /api/sim/gnss`): random
trips over our Valhalla (2–8 km each, one after another) at 90 % of the road's limit, a fix
a second into the same `gnss.*` signals / GNSS_LATEST as the node's (ignored meanwhile)
*** [ ] Replay a library track (GPX/FIT with times) instead, at its own speed
* [ ] While following a planned route: the route ahead highlighted, distance to the next * [ ] While following a planned route: the route ahead highlighted, distance to the next
maneuver from Valhalla's directions maneuver from Valhalla's directions
+49 -1
View File
@@ -12,6 +12,7 @@ require_relative "lib/maptool/google_saved"
require_relative "lib/maptool/routing" require_relative "lib/maptool/routing"
require_relative "lib/maptool/mqtt_client" require_relative "lib/maptool/mqtt_client"
require_relative "lib/maptool/can" require_relative "lib/maptool/can"
require_relative "lib/maptool/gnss_sim"
require_relative "lib/maptool/sync" require_relative "lib/maptool/sync"
require "ipaddr" require "ipaddr"
require_relative "lib/maptool/live_store" require_relative "lib/maptool/live_store"
@@ -398,13 +399,16 @@ module Maptool
warn "can: #{CAN_CONFIG_PATH}: #{e.message} — CAN off" warn "can: #{CAN_CONFIG_PATH}: #{e.message} — CAN off"
[nil, nil] [nil, nil]
end end
# Simulated driving (lib/maptool/gnss_sim.rb) in place of the GNSS node.
GNSS_SIM = GnssSim.new(VALHALLA_URL)
if CAN_CONFIG && !test? if CAN_CONFIG && !test?
decoder = CAN_DECODER decoder = CAN_DECODER
CAN_CONFIG.fetch("interfaces", []).each do |interface| CAN_CONFIG.fetch("interfaces", []).each do |interface|
Thread.new do Thread.new do
Can.listen(interface, decoder: decoder, store: CAN_STORE, start_nodes: CAN_CONFIG["nmt_start"]) do |values| Can.listen(interface, decoder: decoder, store: CAN_STORE, start_nodes: CAN_CONFIG["nmt_start"]) do |values|
gnss = values.filter_map { |name, value| [name.delete_prefix("gnss.").to_sym, value] if name.start_with?("gnss.") }.to_h gnss = values.filter_map { |name, value| [name.delete_prefix("gnss.").to_sym, value] if name.start_with?("gnss.") }.to_h
next if gnss.empty? next if gnss.empty? || GNSS_SIM.running?
GNSS_LATEST_MUTEX.synchronize do GNSS_LATEST_MUTEX.synchronize do
GNSS_LATEST.merge!(gnss) GNSS_LATEST.merge!(gnss)
@@ -654,6 +658,21 @@ module Maptool
halt 503, json(error: e.message) halt 503, json(error: e.message)
end end
# The road being driven ({"points": [[lon, lat], ...]}, the last few
# fixes): name and speed limit, for the dashboard. Open like /api/route.
post "/api/road" do
points = JSON.parse(request.body.read)["points"]
halt 400, json(error: "points must be a list of [lon, lat]") unless points.is_a?(Array) && points.all?(Array)
json Routing.road(VALHALLA_URL, points.last(10))
rescue JSON::ParserError
halt 400, json(error: "invalid JSON")
rescue Routing::RouteError => e
halt 422, json(error: e.message)
rescue Routing::Unavailable => e
halt 503, json(error: e.message)
end
# Where the vehicle profile gets in each of `minutes` from `center` # Where the vehicle profile gets in each of `minutes` from `center`
# ({"center": [lon, lat], "minutes": [30, 60]}). Open like /api/route. # ({"center": [lon, lat], "minutes": [30, 60]}). Open like /api/route.
post "/api/isochrone" do post "/api/isochrone" do
@@ -1217,6 +1236,35 @@ module Maptool
json snapshot.merge(available: !CAN_CONFIG.nil?) json snapshot.merge(available: !CAN_CONFIG.nil?)
end end
# The GNSS simulation: POST {"start": [lon, lat]} drives randomly from
# there, DELETE stops it, GET says whether it's on (and why it stopped).
get "/api/sim/gnss" do
require_login!
json running: GNSS_SIM.running?, error: GNSS_SIM.error
end
post "/api/sim/gnss" do
require_login!
lon, lat = JSON.parse(request.body.read)["start"]
halt 400, json(error: "start must be [lon, lat]") unless lon.is_a?(Numeric) && lat.is_a?(Numeric)
CAN_STORE.override_prefix = "gnss."
GNSS_SIM.start(lon, lat) do |fix|
CAN_STORE.put(fix.transform_keys { |key| "gnss.#{key}" })
GNSS_LATEST_MUTEX.synchronize { GNSS_LATEST.merge!(fix, received_at: Time.now.to_f) }
end
json running: true
rescue JSON::ParserError
halt 400, json(error: "invalid JSON")
end
delete "/api/sim/gnss" do
require_login!
GNSS_SIM.stop
CAN_STORE.override_prefix = nil
json running: false
end
get "/api/live" do get "/api/live" do
require_login! require_login!
json LIVE_STORE.snapshot.merge(available: !MQTT_URL.empty?) json LIVE_STORE.snapshot.merge(available: !MQTT_URL.empty?)
+9 -2
View File
@@ -244,10 +244,17 @@ same node) isn't in the firmware yet:
{ "name": "gnss.satellites", "id": "0x4A1", "byte": 6, "type": "u8", "scale": 1.0039370078740157, "invalid": 255 }, { "name": "gnss.satellites", "id": "0x4A1", "byte": 6, "type": "u8", "scale": 1.0039370078740157, "invalid": 255 },
{ "name": "imu.pitch", "id": "0x2A1", "byte": 0, "type": "u16", "scale": 0.005493331705679495, "offset": -180, "invalid": 65535, "unit": "°" }, { "name": "imu.pitch", "id": "0x2A1", "byte": 0, "type": "u16", "scale": 0.005493331705679495, "offset": -180, "invalid": 65535, "unit": "°" },
{ "name": "imu.roll", "id": "0x2A1", "byte": 2, "type": "u16", "scale": 0.005493331705679495, "offset": -180, "invalid": 65535, "unit": "°" }, { "name": "imu.roll", "id": "0x2A1", "byte": 2, "type": "u16", "scale": 0.005493331705679495, "offset": -180, "invalid": 65535, "unit": "°" },
{ "name": "imu.temperature", "id": "0x2A1", "byte": 4, "type": "u16", "scale": 0.0025177770317697684, "offset": -40, "invalid": 65535, "unit": "°C" } ] } { "name": "imu.temperature", "id": "0x2A1", "byte": 4, "type": "u16", "scale": 0.0025177770317697684, "offset": -40, "invalid": 65535, "unit": "°C" },
{ "name": "mag.x", "id": "0x221", "byte": 0, "type": "u16", "scale": 0.006103701895199438, "offset": -200, "invalid": 65535, "unit": "µT" },
{ "name": "mag.y", "id": "0x221", "byte": 2, "type": "u16", "scale": 0.006103701895199438, "offset": -200, "invalid": 65535, "unit": "µT" },
{ "name": "mag.z", "id": "0x221", "byte": 4, "type": "u16", "scale": 0.006103701895199438, "offset": -200, "invalid": 65535, "unit": "µT" },
{ "name": "imu.heading", "id": "0x221", "byte": 6, "type": "u16", "scale": 0.005493331705679495, "invalid": 65535, "unit": "°" } ] }
---- ----
Speed's scale also converts km/h to m/s (`300 / 65534 / 3.6`). The node Speed's scale also converts km/h to m/s (`300 / 65534 / 3.6`). 0x221 is
the HMC5883L (TPDO 4 → `0x200 + node`): the field ±200 µT and ESPHome's
heading 0..360°, plain `atan2(y, x)` — no tilt compensation or hard-iron
calibration yet, so only roughly right standing level. The node
goes operational by itself, so no `nmt_start`. goes operational by itself, so no `nmt_start`.
=== Map data (one way) === Map data (one way)
+30 -1
View File
@@ -117,6 +117,10 @@ module Maptool
class Store class Store
MAX_FRAME_IDS = 2048 # ponytail: stops counting new ids past this, enough for a bus MAX_FRAME_IDS = 2048 # ponytail: stops counting new ids past this, enough for a bus
# Signals starting with this aren't taken from the bus (the GNSS
# simulation's, put by #put, stand in for the node's meanwhile).
attr_accessor :override_prefix
def initialize def initialize
@mutex = Mutex.new @mutex = Mutex.new
@signals = {} @signals = {}
@@ -137,6 +141,13 @@ module Maptool
role, node = Can.canopen_role(frame.id, extended: frame.extended) role, node = Can.canopen_role(frame.id, extended: frame.extended)
if node if node
n = (@nodes[node] ||= {}) n = (@nodes[node] ||= {})
if n.delete(:silent)
warn "can: node #{node} back after #{(at - n[:seen_at]).round}s"
end
if role == :heartbeat
n[:heartbeat_interval] = at - n[:heartbeat_at] if n[:heartbeat_at]
n[:heartbeat_at] = at
end
n[:seen_at] = at n[:seen_at] = at
n[:state] = HEARTBEAT_STATES.fetch(frame.data.getbyte(0) & 0x7F, "unknown") if role == :heartbeat && frame.data.bytesize >= 1 n[:state] = HEARTBEAT_STATES.fetch(frame.data.getbyte(0) & 0x7F, "unknown") if role == :heartbeat && frame.data.bytesize >= 1
# EMCY: error code (0 = errors reset), error register, 5 bytes vendor-specific # EMCY: error code (0 = errors reset), error register, 5 bytes vendor-specific
@@ -154,7 +165,25 @@ module Maptool
end end
f.merge!(count: f[:count] + 1, data: frame.data.unpack1("H*"), at: at) f.merge!(count: f[:count] + 1, data: frame.data.unpack1("H*"), at: at)
end end
values.each { |name, value| @signals[name] = { value: value, at: at } } values.each { |name, value| @signals[name] = { value: value, at: at } unless @override_prefix && name.start_with?(@override_prefix) }
mark_silent(at)
end
end
def put(values, at: Time.now.to_f)
@mutex.synchronize { values.each { |name, value| @signals[name] = { value: value, at: at } } }
end
# A node with a heartbeat that missed 3 of them: silent, warned once
# (in the journal, so the time it stopped is kept). Checked as other
# frames come in — with the whole bus quiet the interface says so.
def mark_silent(at)
return if @checked_at && at - @checked_at < 1
@checked_at = at
@nodes.each do |node, n|
next if n[:silent] || !n[:heartbeat_interval] || at - n[:heartbeat_at] < 3 * n[:heartbeat_interval]
n[:silent] = true
warn "can: node #{node} silent, last heartbeat #{Time.at(n[:heartbeat_at]).strftime('%F %T')}"
end end
end end
+100
View File
@@ -0,0 +1,100 @@
require_relative "routing"
module Maptool
# Simulated driving, to try the dashboard and navigation without the car:
# from a start point it routes (our Valhalla) to a random point 2–8 km
# away and drives there at the road's speed limit, a fix a second, then
# on to the next random point. Its fixes go where the GNSS node's do
# (app.rb: the CAN store's gnss.* signals and GNSS_LATEST), the node's own
# are ignored meanwhile.
class GnssSim
TICK_S = 1.0
DEST_KM = (2.0..8.0)
NO_LIMIT_KMH = 50 # an untagged road
UNLIMITED_KMH = 130
LIMIT_SHARE = 0.9 # drives a bit under the limit
attr_reader :error
def initialize(valhalla_url, vehicle: { id: "car" }, random: Random.new, sleep: ->(s) { Kernel.sleep(s) })
@valhalla_url = valhalla_url
@vehicle = vehicle
@random = random
@sleep = sleep
@thread = nil
@mutex = Mutex.new
end
def running?
@mutex.synchronize { @thread&.alive? || false }
end
# Drives from [lon, lat] until stopped; each fix to the block:
# { lat:, lon:, speed: m/s, satellites:, hdop: }.
def start(lon, lat, &on_fix)
stop
@error = nil
@mutex.synchronize do
@thread = Thread.new do
position = [Float(lon), Float(lat)]
loop { position = drive(position, &on_fix) }
rescue StandardError => e
@error = e.message
warn "gnss sim: #{e.message}"
end
end
end
def stop
thread = @mutex.synchronize { @thread.tap { @thread = nil } }
thread&.kill&.join
end
# One random trip from position; returns where it ended.
def drive(position, &on_fix)
route = random_route(position)
coords = route[:geometry][:coordinates]
km = [0.0]
coords.each_cons(2) { |a, b| km << km.last + self.class.meters(a, b) / 1000 }
limits = route[:properties][:speed_limits] || [[0.0, nil]]
at = 0.0
i = 1
while i < coords.size
kmh = speed_kmh(limits.reverse.find { |start, _| start <= at }&.last)
at += kmh / 3600 * TICK_S
i += 1 while i < coords.size - 1 && km[i] < at
t = km[i] > km[i - 1] ? ((at - km[i - 1]) / (km[i] - km[i - 1])).clamp(0.0, 1.0) : 1.0
lon, lat = coords[i - 1].zip(coords[i]).map { |a, b| a + (b - a) * t }
on_fix&.call(lat: lat, lon: lon, speed: kmh / 3.6, satellites: 12, hdop: 0.8)
break if i == coords.size - 1 && t >= 1
@sleep.call(TICK_S)
end
coords.last
end
def speed_kmh(limit)
(limit == "unlimited" ? UNLIMITED_KMH : limit || NO_LIMIT_KMH) * LIMIT_SHARE
end
# A route to a random point DEST_KM away; a few tries (a lake, no road there).
def random_route(position)
last = nil
5.times do
bearing = @random.rand * 2 * Math::PI
distance = @random.rand(DEST_KM) * 1000
lon, lat = position
dest = [lon + distance * Math.sin(bearing) / (111_320 * Math.cos(lat * Math::PI / 180)), lat + distance * Math.cos(bearing) / 111_320]
route = Routing.route(@valhalla_url, [position, dest], @vehicle)
return route if route[:geometry][:coordinates].size >= 2
rescue Routing::RouteError => e
last = e
end
raise Routing::RouteError, "no route from #{position.map { |v| v.round(5) }.join(', ')}: #{last&.message}"
end
def self.meters((lon1, lat1), (lon2, lat2))
Math.hypot((lon2 - lon1) * Math.cos((lat1 + lat2) / 2 * Math::PI / 180), lat2 - lat1) * 111_320
end
end
end
+50 -10
View File
@@ -246,27 +246,39 @@ module Maptool
costing, options = costing(vehicle, avoid) costing, options = costing(vehicle, avoid)
data = valhalla(valhalla_url, "/route", data = valhalla(valhalla_url, "/route",
locations: locations.map { |lon, lat| { lon: Float(lon), lat: Float(lat) } }, locations: locations.map { |lon, lat| { lon: Float(lon), lat: Float(lat) } },
costing: costing, costing_options: { costing => options }, units: "kilometers") costing: costing, costing_options: { costing => options }, units: "kilometers", turn_lanes: true)
legs = data["trip"]["legs"] legs = data["trip"]["legs"]
along = (along_route(valhalla_url, legs, costing, options) if %w[auto truck].include?(costing)) || {}
{ type: "Feature", { type: "Feature",
geometry: { type: "LineString", coordinates: legs.flat_map { |leg| decode_polyline(leg["shape"]) } }, geometry: { type: "LineString", coordinates: legs.flat_map { |leg| decode_polyline(leg["shape"]) } },
properties: { kind: "route", costing: costing, distance_km: data["trip"]["summary"]["length"], properties: { kind: "route", costing: costing, distance_km: data["trip"]["summary"]["length"],
time_s: data["trip"]["summary"]["time"], time_s: data["trip"]["summary"]["time"], countries: along[:countries],
countries: (countries(valhalla_url, legs, costing, options) if %w[auto truck].include?(costing)), speed_limits: along[:speed_limits], signals: along[:signals],
maneuvers: legs.flat_map { |leg| leg["maneuvers"].map { |m| { text: m["instruction"], km: m["length"] } } } } } # lanes: Valhalla's [{directions:, valid:, active:}] bitmasks, at junctions that have them
maneuvers: legs.flat_map { |leg| leg["maneuvers"].map { |m| { text: m["instruction"], km: m["length"], lanes: m["lanes"] }.compact } } } }
rescue ArgumentError, TypeError rescue ArgumentError, TypeError
raise RouteError, "invalid coordinates" raise RouteError, "invalid coordinates"
end end
# [{ code: "AT", km:, motorway_km:, toll_km: }, ...] in route order, from # From Valhalla's per-edge attributes along the route:
# Valhalla's per-edge attributes. nil if that lookup fails: it's extra. # countries: [{ code: "AT", km:, motorway_km:, toll_km: }, ...] in route
def self.countries(valhalla_url, legs, costing, options) # order (vignettes, tolls);
# speed_limits: [[km from the start, km/h | "unlimited" | nil], ...], an
# entry where the limit changes (nil: not tagged);
# signals: [[lon, lat, km from the start], ...], the traffic signals.
# nil if that lookup fails: it's extra.
def self.along_route(valhalla_url, legs, costing, options)
totals = {} totals = {}
limits = []
signals = []
km = 0.0
legs.each do |leg| legs.each do |leg|
shape = decode_polyline(leg["shape"])
data = valhalla(valhalla_url, "/trace_attributes", data = valhalla(valhalla_url, "/trace_attributes",
encoded_polyline: leg["shape"], shape_match: "edge_walk", costing: costing, encoded_polyline: leg["shape"], shape_match: "edge_walk", costing: costing,
costing_options: { costing => options }, costing_options: { costing => options },
filters: { attributes: %w[edge.length edge.road_class edge.toll node.admin_index admin.country_code], action: "include" }) filters: { attributes: %w[edge.length edge.road_class edge.toll edge.speed_limit edge.end_shape_index
node.admin_index node.traffic_signal admin.country_code], action: "include" })
codes = data["admins"].map { |admin| admin["country_code"] } codes = data["admins"].map { |admin| admin["country_code"] }
data["edges"].each do |edge| data["edges"].each do |edge|
code = codes[edge.dig("end_node", "admin_index").to_i] || "?" code = codes[edge.dig("end_node", "admin_index").to_i] || "?"
@@ -274,13 +286,41 @@ module Maptool
row[:km] += edge["length"] row[:km] += edge["length"]
row[:motorway_km] += edge["length"] if edge["road_class"] == "motorway" row[:motorway_km] += edge["length"] if edge["road_class"] == "motorway"
row[:toll_km] += edge["length"] if edge["toll"] row[:toll_km] += edge["length"] if edge["toll"]
limit = speed_limit(edge["speed_limit"])
limits << [km.round(3), limit] if limits.empty? || limits.last[1] != limit
km += edge["length"]
point = shape[edge["end_shape_index"].to_i] if edge.dig("end_node", "traffic_signal")
signals << [*point, km.round(3)] if point
end end
end end
totals.values.each { |row| row.transform_values! { |v| v.is_a?(Float) ? v.round(1) : v } } { countries: totals.values.each { |row| row.transform_values! { |v| v.is_a?(Float) ? v.round(1) : v } },
speed_limits: limits, signals: signals }
rescue RouteError, Unavailable, Net::ReadTimeout, NoMethodError, TypeError rescue RouteError, Unavailable, Net::ReadTimeout, NoMethodError, TypeError
nil nil
end end
private_class_method :countries private_class_method :along_route
# Valhalla's speed_limit: km/h, "unlimited" (a German Autobahn), else nil
# (0 or missing = not tagged).
def self.speed_limit(value)
value == "unlimited" || (value.is_a?(Integer) && value.positive?) ? value : nil
end
# The road at the end of a short trace ([[lon, lat], ...] oldest first,
# the last few fixes) for driving without a route: its name, class and
# speed limit. Map-matched, so the road actually driven, not just the
# nearest one (a bridge over the motorway).
def self.road(valhalla_url, points)
raise RouteError, "at least two points are needed" if points.size < 2
data = valhalla(valhalla_url, "/trace_attributes",
shape: points.map { |lon, lat| { lon: Float(lon), lat: Float(lat) } }, costing: "auto", shape_match: "map_snap",
filters: { attributes: %w[edge.names edge.road_class edge.speed_limit], action: "include" })
edge = data["edges"]&.last or raise RouteError, "no road here"
{ name: edge["names"]&.first, road_class: edge["road_class"], speed_limit: speed_limit(edge["speed_limit"]) }
rescue ArgumentError, TypeError
raise RouteError, "invalid coordinates"
end
ISOCHRONE_MAX_MINUTES = 240 # Valhalla's own default limit ISOCHRONE_MAX_MINUTES = 240 # Valhalla's own default limit
+63
View File
@@ -3284,3 +3284,66 @@ html.night .maplibregl-marker {
.gpx-panel__action[hidden] { .gpx-panel__action[hidden] {
display: none; display: none;
} }
/* The car's dashboard over the map (public/js/dashboard.js). */
.dash-card {
position: absolute;
right: 12px;
bottom: 36px;
z-index: 3;
padding: 8px;
border-radius: 12px;
background: #fff;
box-shadow: 0 1px 6px rgba(0, 0, 0, 0.25);
text-align: center;
pointer-events: none;
}
.dash-incl {
display: block;
width: 190px;
height: 190px;
font-family: system-ui, sans-serif;
}
.dash-incl text { text-anchor: middle; dominant-baseline: middle; fill: #222; }
.dash-face { fill: #f6f6f4; stroke: #bbb; stroke-width: 2; }
.dash-ring line { stroke: #555; stroke-width: 2; }
.dash-ring text { font-size: 14px; font-weight: 600; }
.dash-ring .dash-n { fill: #c62828; }
.dash-lubber { fill: #c62828; }
.dash-heading { font-size: 15px; font-weight: 600; font-variant-numeric: tabular-nums; }
.dash-ground { stroke: #999; stroke-width: 1.5; stroke-dasharray: 3 3; }
.dash-car { fill: #37474f; }
.dash-wheel { fill: #111; }
.dash-value { font-size: 18px; font-weight: 700; font-variant-numeric: tabular-nums; }
.dash-caption { font-size: 10px; fill: #777 !important; text-transform: uppercase; letter-spacing: 0.05em; }
.dash-incl .dash-warn { fill: #ef6c00; }
.dash-incl .dash-bad { fill: #c62828; }
.dash-speed { font-size: 14px; color: #555; }
.dash-speed span { font-size: 34px; font-weight: 700; color: #222; font-variant-numeric: tabular-nums; }
/* Navigation on the dashboard: the speed limit sign and what's ahead. */
.dash-nav { display: flex; align-items: center; gap: 10px; margin-bottom: 6px; text-align: left; font-size: 13px; color: #333; }
.dash-limit {
display: inline-flex; align-items: center; justify-content: center; flex: none;
width: 56px; height: 56px; box-sizing: border-box; border: 7px solid #d32f2f; border-radius: 50%;
background: #fff; color: #111; font-size: 22px; font-weight: 700; font-variant-numeric: tabular-nums;
}
.dash-limit[hidden] { display: none; }
.dash-limit--small { width: 26px; height: 26px; border-width: 3px; font-size: 11px; vertical-align: middle; }
/* no limit (Autobahn): the white sign with the black slash */
.dash-limit--none { border: 2px solid #111; background: linear-gradient(135deg, transparent 45%, #111 45% 55%, transparent 55%), #fff; }
.dash-ahead > div { margin: 2px 0; white-space: nowrap; }
.dash-maneuver { max-width: 220px; overflow: hidden; text-overflow: ellipsis; font-weight: 600; }
.dash-signal {
display: inline-block; width: 8px; height: 20px; vertical-align: middle; border-radius: 3px; background:
radial-gradient(circle at 50% 17%, #e53935 2.5px, transparent 3px), radial-gradient(circle at 50% 50%, #fbc02d 2.5px, transparent 3px),
radial-gradient(circle at 50% 83%, #43a047 2.5px, transparent 3px), #222;
}
.dash-lanes { display: flex; gap: 3px; }
.dash-lanes span { min-width: 22px; padding: 1px 3px; border-radius: 4px; background: #eee; color: #999; text-align: center; font-size: 16px; }
.dash-lanes .dash-lane--go { background: #1d6fdc; color: #fff; }
.dash-card--over { box-shadow: 0 0 0 4px #d32f2f, 0 1px 6px rgba(0, 0, 0, 0.25); }
.dash-card--over .dash-speed span { color: #d32f2f; }
+324
View File
@@ -0,0 +1,324 @@
import { isLoggedIn } from "/js/auth.js";
import { onRouteChanged } from "/js/panels.js";
// The car's dashboard over the map, off the CAN signals (GET /api/can,
// names from data/can.json): one inclinometer — compass ring around a rear
// view (roll) and a side view (pitch) — and the speed. Which widgets show
// is per device (localStorage); levelling is the node's own (its offsets,
// set from /can.html). Turn signals / brake: when they're on the bus.
// Heading: driving, the GNSS course (from consecutive fixes); standing
// still, the compass (imu.heading, once the node sends it) — else the
// last course stays, dimmed.
const SIGNALS = { pitch: "imu.pitch", roll: "imu.roll", heading: "imu.heading", speed: "gnss.speed", lat: "gnss.lat", lon: "gnss.lon" };
const MOVING_MS = 1.5; // m/s: above this the GNSS course counts
const COURSE_MIN_M = 5; // fixes closer than this: too noisy for a course
const POLL_MS = 500;
const STALE_S = 5; // older signal: shown as missing
const WARN = { roll: 20, pitch: 25 }; // ° — amber past these, red past 1.5×
const STORE_KEY = "maptool.dashboard";
// Navigation (the speed limit, what's ahead): along the route panel's route
// while on it (its speed_limits / signals / maneuvers from /api/route),
// else the limit of the road being driven (POST /api/road, map-matched).
const OVER_KMH = 3; // over the limit by more than this: warning
const ON_ROUTE_M = 50; // farther from the route line: off it
const ROAD_EVERY_MS = 4000; // /api/road at most this often, only while moving
const TRACE_STEP_M = 10; // fixes kept for /api/road at least this far apart
const LANES_AHEAD_M = 1000; // the next maneuver's lanes from this close
const DEFAULT_WIDGETS = { inclinometer: true, speed: true, navigation: true };
const load = () => {
try { const saved = JSON.parse(localStorage.getItem(STORE_KEY)) || {}; return { ...saved, widgets: { ...DEFAULT_WIDGETS, ...saved.widgets } }; }
catch { return { widgets: { ...DEFAULT_WIDGETS } }; }
};
const RAD = Math.PI / 180;
// meters between two [lon, lat] (equirectangular: fine at these distances)
const meters = ([lon1, lat1], [lon2, lat2]) => Math.hypot((lon2 - lon1) * Math.cos(((lat1 + lat2) / 2) * RAD), lat2 - lat1) * 111320;
const distance = (m) => (m >= 1000 ? `${(m / 1000).toFixed(1)} km` : `${Math.round(m / 10) * 10} m`);
// Valhalla's lane direction bits → arrows
const LANE_ARROWS = [[2, "↑"], [16, "↖"], [8, "←"], [4, "↙"], [32, "↗"], [64, "→"], [128, "↘"], [256, "↶"], [512, "⇤"], [1024, "⇥"]];
const laneArrows = (bits) => LANE_ARROWS.filter(([bit]) => bits & bit).map(([, arrow]) => arrow).join("") || "↑";
// A route prepared for "where am I on it": km at every vertex, maneuvers' start km.
function prepareRoute(route) {
if (!route?.properties?.speed_limits) return null;
const coords = route.geometry.coordinates;
const km = [0];
for (let i = 1; i < coords.length; i++) km.push(km[i - 1] + meters(coords[i - 1], coords[i]) / 1000);
let start = 0;
const maneuvers = route.properties.maneuvers.map((m) => { const at = start; start += m.km; return { ...m, at }; });
return { coords, km, limits: route.properties.speed_limits, signals: route.properties.signals || [], maneuvers };
}
// Nearest point on the route: [km along it, meters off it].
// ponytail: scans every segment each fix — a window around the last hit if long routes get slow.
function locate(route, position) {
let best = [0, Infinity];
const { coords, km } = route;
const cos = Math.cos(position[1] * RAD);
for (let i = 1; i < coords.length; i++) {
const [ax, ay] = [coords[i - 1][0] * cos, coords[i - 1][1]];
const [bx, by] = [coords[i][0] * cos, coords[i][1]];
const [px, py] = [position[0] * cos, position[1]];
const len2 = (bx - ax) ** 2 + (by - ay) ** 2;
const t = len2 ? Math.max(0, Math.min(1, ((px - ax) * (bx - ax) + (py - ay) * (by - ay)) / len2)) : 0;
const off = Math.hypot(px - (ax + t * (bx - ax)), py - (ay + t * (by - ay))) * 111320;
if (off < best[1]) best = [km[i - 1] + t * (km[i] - km[i - 1]), off];
}
return best;
}
const ticks = Array.from({ length: 36 }, (_, i) => {
const a = i * 10;
const long = a % 30 === 0;
return `<line x1="0" y1="-95" x2="0" y2="${long ? -86 : -90}" transform="rotate(${a})"/>`;
}).join("");
const labels = ["N", "E", "S", "W"].map((l, i) => `<text y="-74" transform="rotate(${i * 90})" class="${l === "N" ? "dash-n" : ""}">${l}</text>`).join("");
const INCLINOMETER = `
<svg viewBox="-100 -100 200 200" class="dash-incl">
<circle r="97" class="dash-face"/>
<g class="dash-ring">${ticks}${labels}</g>
<path d="M0,-99 l-6,-0 l6,12 l6,-12 z" class="dash-lubber"/>
<text y="-46" class="dash-heading"></text>
<line x1="-62" y1="16" x2="-8" y2="16" class="dash-ground"/>
<line x1="8" y1="16" x2="62" y2="16" class="dash-ground"/>
<g transform="translate(-35,14)"><g class="dash-roll">
<path d="M-20,0 h40 v-9 l-5,-14 h-30 l-5,14 z" class="dash-car"/>
<rect x="-20" y="-1" width="9" height="5" rx="1" class="dash-wheel"/><rect x="11" y="-1" width="9" height="5" rx="1" class="dash-wheel"/>
</g></g>
<g transform="translate(35,14)"><g class="dash-pitch">
<path d="M-26,-4 h52 v-9 l-9,-2 l-7,-10 h-21 l-5,10 l-10,2 z" class="dash-car"/>
<circle cx="-15" cy="-2" r="5" class="dash-wheel"/><circle cx="15" cy="-2" r="5" class="dash-wheel"/>
</g></g>
<text x="-35" y="44" class="dash-value dash-roll-value"></text>
<text x="35" y="44" class="dash-value dash-pitch-value"></text>
<text x="-35" y="60" class="dash-caption">roll</text>
<text x="35" y="60" class="dash-caption">pitch</text>
</svg>`;
export class DashboardControl {
constructor(map) {
this._map = map;
this._settings = load();
this._timer = null;
this._values = {};
this._fix = null; // last fix a course was measured from
this._course = null;
this._route = prepareRoute(onRouteChanged((route) => (this._route = prepareRoute(route))));
this._trace = []; // [lon, lat] fixes TRACE_STEP_M apart, for /api/road
this._road = null; // its last answer
this._roadAt = 0;
}
// The limit and what's ahead: from the route while on it, else the road.
_navigate() {
const { lat, lon, speed } = this._values;
if (lat == null || lon == null) return (this._nav = null);
const position = [lon, lat];
if (!this._trace.length || meters(this._trace.at(-1), position) >= TRACE_STEP_M) this._trace = [...this._trace.slice(-7), position];
const [at, off] = this._route ? locate(this._route, position) : [0, Infinity];
if (off <= ON_ROUTE_M) {
const { limits, signals, maneuvers } = this._route;
const current = limits.findLast(([km]) => km <= at);
const next = limits.find(([km, limit]) => km > at && limit !== current?.[1]);
const signal = signals.find(([, , km]) => km > at);
const maneuver = maneuvers.find((m) => m.at > at + 0.005);
this._nav = {
limit: current?.[1] ?? null,
next: next && { limit: next[1], m: (next[0] - at) * 1000 },
signal: signal && (signal[2] - at) * 1000,
maneuver: maneuver && { text: maneuver.text, m: (maneuver.at - at) * 1000, lanes: maneuver.lanes },
};
return;
}
this._nav = { limit: this._road?.speed_limit ?? null };
if ((speed ?? 0) < MOVING_MS || this._trace.length < 2 || Date.now() - this._roadAt < ROAD_EVERY_MS) return;
this._roadAt = Date.now();
fetch("/api/road", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ points: this._trace }) })
.then((response) => (response.ok ? response.json() : null))
.then((road) => { this._road = road; })
.catch(() => { this._road = null; });
}
// Course over ground from the fix COURSE_MIN_M back, while moving.
_updateCourse({ lat, lon, speed }) {
if (lat == null || lon == null) return;
if (!this._fix || speed == null || speed < MOVING_MS) {
this._fix = { lat, lon };
return;
}
const rad = Math.PI / 180;
const dLon = (lon - this._fix.lon) * rad;
const y = Math.sin(dLon) * Math.cos(lat * rad);
const x = Math.cos(this._fix.lat * rad) * Math.sin(lat * rad) - Math.sin(this._fix.lat * rad) * Math.cos(lat * rad) * Math.cos(dLon);
const north = (lat - this._fix.lat) * 111320;
const east = (lon - this._fix.lon) * 111320 * Math.cos(lat * rad);
if (Math.hypot(north, east) < COURSE_MIN_M) return;
this._course = (Math.atan2(y, x) / rad + 360) % 360;
this._fix = { lat, lon };
}
mount(li) {
li.innerHTML = `
<div class="overlays-panel__row">
<input type="checkbox" class="overlays-panel__toggle">
<button type="button" class="overlays-panel__name" aria-expanded="false">Dashboard</button>
</div>
<p class="live-panel__status" hidden></p>
<div class="overlays-panel__details" hidden>
<label class="live-tracker__row"><input type="checkbox" data-widget="inclinometer"> Inclinometer &amp; compass</label>
<label class="live-tracker__row"><input type="checkbox" data-widget="speed"> Speed</label>
<label class="live-tracker__row"><input type="checkbox" data-widget="navigation"> Speed limit &amp; ahead (route)</label>
<button type="button" class="dash-sim">Simulate driving from the map center</button>
<p class="live-panel__status dash-sim-status" hidden></p>
</div>`;
this._toggle = li.querySelector(".overlays-panel__toggle");
this._status = li.querySelector(".live-panel__status");
const name = li.querySelector(".overlays-panel__name");
const details = li.querySelector(".overlays-panel__details");
name.addEventListener("click", () => {
details.hidden = !details.hidden;
name.setAttribute("aria-expanded", String(!details.hidden));
});
if (!isLoggedIn()) {
this._toggle.disabled = true;
li.title = "Log in to see the car's dashboard";
return;
}
for (const box of li.querySelectorAll("[data-widget]")) {
box.checked = !!this._settings.widgets[box.dataset.widget];
box.addEventListener("change", () => {
this._settings.widgets[box.dataset.widget] = box.checked;
this._save();
this._render();
});
}
this._toggle.addEventListener("change", () => (this._toggle.checked ? this._enable() : this._disable()));
this._simButton = li.querySelector(".dash-sim");
this._simStatus = li.querySelector(".dash-sim-status");
this._simButton.addEventListener("click", () => this._simulate(!this._simRunning));
this._simulate(null);
}
// GNSS simulation on the server (POST/DELETE /api/sim/gnss): random
// driving from the map center; on = true / false, null = just read the state.
async _simulate(on) {
const { lng, lat } = this._map.getCenter();
const options = on === true ? { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ start: [lng, lat] }) }
: on === false ? { method: "DELETE" } : {};
try {
const response = await fetch("/api/sim/gnss", options);
const state = await response.json();
if (!response.ok) throw new Error(state.error || `HTTP ${response.status}`);
this._simRunning = state.running;
this._simStatus.hidden = !state.error;
this._simStatus.textContent = state.error ? `Simulation stopped: ${state.error}` : "";
} catch (e) {
this._simStatus.hidden = false;
this._simStatus.textContent = `Simulation: ${e.message}`;
}
this._simButton.textContent = this._simRunning ? "Stop the simulation" : "Simulate driving from the map center";
}
_save() {
try { localStorage.setItem(STORE_KEY, JSON.stringify(this._settings)); } catch { /* private window: just not kept */ }
}
_enable() {
this._card = document.createElement("div");
this._card.className = "dash-card";
this._card.innerHTML = `<div class="dash-nav"><div class="dash-limit"></div><div class="dash-ahead"></div></div>${INCLINOMETER}<div class="dash-speed"><span></span> km/h</div>`;
this._map.getContainer().appendChild(this._card);
this._status.hidden = false;
this._status.textContent = "Connecting…";
this._poll();
}
_disable() {
clearTimeout(this._timer);
this._timer = null;
this._card?.remove();
this._card = null;
this._status.hidden = true;
}
async _poll() {
try {
const response = await fetch("/api/can", { cache: "no-store" });
if (!response.ok) throw new Error(`HTTP ${response.status}`);
const data = await response.json();
const now = Date.parse(response.headers.get("Date")) / 1000 || Date.now() / 1000;
this._values = Object.fromEntries(Object.entries(SIGNALS).map(([key, name]) => {
const s = data.signals[name];
// Date has 1 s resolution: +1 so a fresh value isn't "stale"
return [key, s && now - s.at < STALE_S + 1 ? s.value : null];
}));
this._updateCourse(this._values);
this._navigate();
this._status.textContent = this._simRunning ? "Simulated GNSS" : data.available ? "" : "CAN is off on this server";
this._status.hidden = !this._status.textContent;
} catch (e) {
this._values = {};
this._status.hidden = false;
this._status.textContent = `Can't reach the server: ${e.message}`;
}
this._render();
if (this._card) this._timer = setTimeout(() => this._poll(), POLL_MS);
}
_render() {
if (!this._card) return;
const { widgets } = this._settings;
const v = this._values;
const svg = this._card.querySelector(".dash-incl");
svg.style.display = widgets.inclinometer ? "" : "none";
const speed = this._card.querySelector(".dash-speed");
speed.style.display = widgets.speed ? "" : "none";
const nav = this._card.querySelector(".dash-nav");
nav.style.display = widgets.navigation ? "" : "none";
this._card.hidden = !widgets.inclinometer && !widgets.speed && !widgets.navigation;
this._renderNav(nav);
const severity = (key, value) => (value == null ? "" : Math.abs(value) >= WARN[key] * 1.5 ? "dash-bad" : Math.abs(value) >= WARN[key] ? "dash-warn" : "");
for (const key of ["roll", "pitch"]) {
const value = v[key];
// the pitch car faces right: nose up = counter-clockwise
svg.querySelector(`.dash-${key}`).setAttribute("transform", `rotate(${value == null ? 0 : key === "pitch" ? -value : value})`);
const text = svg.querySelector(`.dash-${key}-value`);
text.textContent = value == null ? "—" : `${value > 0 ? "+" : ""}${Math.round(value)}°`;
text.setAttribute("class", `dash-value dash-${key}-value ${severity(key, value)}`);
}
const moving = v.speed != null && v.speed >= MOVING_MS;
const heading = moving ? this._course ?? v.heading : v.heading ?? this._course;
const live = heading != null && (moving ? this._course != null : v.heading != null);
svg.querySelector(".dash-ring").setAttribute("transform", `rotate(${heading == null ? 0 : -heading})`);
svg.querySelector(".dash-ring").style.opacity = heading == null ? 0.3 : live ? 1 : 0.55;
svg.querySelector(".dash-heading").textContent = heading == null ? "" : `${Math.round((heading + 360) % 360)}°`;
speed.querySelector("span").textContent = v.speed == null ? "—" : Math.round(v.speed * 3.6);
}
_renderNav(nav) {
const n = this._nav;
const limit = n?.limit;
const kmh = this._values.speed == null ? null : this._values.speed * 3.6;
const over = typeof limit === "number" && kmh != null && kmh > limit + OVER_KMH;
this._card.classList.toggle("dash-card--over", over);
const sign = nav.querySelector(".dash-limit");
sign.hidden = limit == null;
sign.className = `dash-limit${limit === "unlimited" ? " dash-limit--none" : ""}`;
sign.textContent = typeof limit === "number" ? limit : "";
const rows = [];
if (n?.next) rows.push(`<div><span class="dash-limit dash-limit--small${n.next.limit === "unlimited" ? " dash-limit--none" : ""}">${typeof n.next.limit === "number" ? n.next.limit : n.next.limit ? "" : "?"}</span> in ${distance(n.next.m)}</div>`);
if (n?.signal != null) rows.push(`<div><span class="dash-signal"></span> ${distance(n.signal)}</div>`);
if (n?.maneuver) {
const { text, m, lanes } = n.maneuver;
rows.push(`<div class="dash-maneuver">${distance(m)} · ${text.replace(/[&<>]/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;" })[c])}</div>`);
if (lanes && m <= LANES_AHEAD_M) {
rows.push(`<div class="dash-lanes">${lanes.map((lane) => `<span class="${lane.active || lane.valid ? "dash-lane--go" : ""}">${laneArrows(lane.directions)}</span>`).join("")}</div>`);
}
}
nav.querySelector(".dash-ahead").innerHTML = rows.join("");
}
}
+15 -1
View File
@@ -9,7 +9,21 @@
// same patched style, so the two can't drift apart. // same patched style, so the two can't drift apart.
export function patchOnlineStyle(style) { export function patchOnlineStyle(style) {
return insertTrackOnlyLayer(protectedAreasAndTextures(parkTilesStyle(style))); return insertTrackOnlyLayer(protectedAreasAndTextures(roadLabelSpacing(parkTilesStyle(style))));
}
// Road names and route numbers repeat every symbol-spacing *pixels*, so
// zoomed in close (z22) a street got its name every few meters. Past
// z16 the spacing grows with the zoom: the same distance on the ground
// (~400 m here) at every zoom.
const ROAD_LABEL_FIXED_ZOOM = 16;
function roadLabelSpacing(style) {
for (const layer of style.layers) {
if (layer.type !== "symbol" || layer["source-layer"] !== "transportation_name") continue;
const spacing = layer.layout?.["symbol-spacing"] ?? 250; // the style spec's default
layer.layout = { ...layer.layout, "symbol-spacing": ["interpolate", ["exponential", 2], ["zoom"], ROAD_LABEL_FIXED_ZOOM, spacing, 22, spacing * 64] };
}
return style;
} }
const PARK_TILES_PATCH = { const PARK_TILES_PATCH = {
+3 -1
View File
@@ -8,6 +8,7 @@ import { ContourControl } from "/js/contour.js";
import { HikingTrailsControl } from "/js/hiking_trails.js"; import { HikingTrailsControl } from "/js/hiking_trails.js";
import { TrackerControl, ItsControl } from "/js/live.js"; import { TrackerControl, ItsControl } from "/js/live.js";
import { NpsControl } from "/js/nps.js"; import { NpsControl } from "/js/nps.js";
import { DashboardControl } from "/js/dashboard.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
const ICON_SIZE = 0.3; // 48 * 0.3 = ~14px, sized to sit inside the marker badge below const ICON_SIZE = 0.3; // 48 * 0.3 = ~14px, sized to sit inside the marker badge below
@@ -199,6 +200,7 @@ export class OverlaysControl {
this._tracker = new TrackerControl(map); this._tracker = new TrackerControl(map);
this._its = new ItsControl(map); this._its = new ItsControl(map);
this._nps = new NpsControl(map); this._nps = new NpsControl(map);
this._dashboard = new DashboardControl(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
this._wikiRequestSeq = 0; // ignores an in-flight refetch a newer one has already superseded this._wikiRequestSeq = 0; // ignores an in-flight refetch a newer one has already superseded
@@ -230,7 +232,7 @@ export class OverlaysControl {
["Terrain", [[(li) => this._hillshade.mount(li)], [(li) => this._shadow.mount(li), true], [(li) => this._contour.mount(li)]]], ["Terrain", [[(li) => this._hillshade.mount(li)], [(li) => this._shadow.mount(li), true], [(li) => this._contour.mount(li)]]],
["Weather", [[(li) => this._radar.mount(li), true]]], ["Weather", [[(li) => this._radar.mount(li), true]]],
["Places & trails", [[(li) => this._hikingTrails.mount(li), true], [(li) => this._mountWiki(li)], [(li) => this._nps.mount(li)]]], ["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)]]], ["Live", [[(li) => this._tracker.mount(li)], [(li) => this._its.mount(li)], [(li) => this._dashboard.mount(li), true]]],
]; ];
const list = this._panel.querySelector(".overlays-panel__list"); const list = this._panel.querySelector(".overlays-panel__list");
list.innerHTML = ""; list.innerHTML = "";
+15
View File
@@ -112,3 +112,18 @@ export function editRoute(key, feature) {
export function onRouteEdit(callback) { export function onRouteEdit(callback) {
document.addEventListener(ROUTE_EDIT_EVENT, (event) => callback(event.detail)); document.addEventListener(ROUTE_EDIT_EVENT, (event) => callback(event.detail));
} }
// The route the route panel shows (its /api/route Feature, or null when
// cleared), for the dashboard's speed limits, signals and lanes ahead.
const ROUTE_CHANGED_EVENT = "route-changed";
let currentRoute = null;
export function notifyRouteChanged(route) {
currentRoute = route;
document.dispatchEvent(new CustomEvent(ROUTE_CHANGED_EVENT, { detail: route }));
}
export function onRouteChanged(callback) {
document.addEventListener(ROUTE_CHANGED_EVENT, (event) => callback(event.detail));
return currentRoute;
}
+14 -3
View File
@@ -1,6 +1,6 @@
import { Marker } from "/vendor/maplibre-gl/maplibre-gl.mjs"; import { Marker } from "/vendor/maplibre-gl/maplibre-gl.mjs";
import { ROUTE_ICON, POSITION_ICON, SAVED_POINT_ICON, REVERSE_ICON, CLEAR_ICON, SAVE_ICON } from "/js/icons.js"; import { ROUTE_ICON, POSITION_ICON, SAVED_POINT_ICON, REVERSE_ICON, CLEAR_ICON, SAVE_ICON } from "/js/icons.js";
import { notifySidePanelOpen, onlyOneSidePanelOpen, notifyGpxStoreChanged, onRoutePoint, onRouteEdit } from "/js/panels.js"; import { notifySidePanelOpen, onlyOneSidePanelOpen, notifyGpxStoreChanged, onRoutePoint, onRouteEdit, notifyRouteChanged } from "/js/panels.js";
import { isLoggedIn } from "/js/auth.js"; import { isLoggedIn } from "/js/auth.js";
import { wirePreview } from "/js/preview.js"; import { wirePreview } from "/js/preview.js";
import { elevationAt } from "/js/dem.js"; import { elevationAt } from "/js/dem.js";
@@ -268,6 +268,7 @@ export class RoutePanelControl {
_showResult(route, message) { _showResult(route, message) {
this._draw(); this._draw();
notifyRouteChanged(route);
this._saveButton.hidden = !route || !isLoggedIn(); this._saveButton.hidden = !route || !isLoggedIn();
this._directions.hidden = !route; this._directions.hidden = !route;
this._profileButton.hidden = true; this._profileButton.hidden = true;
@@ -359,7 +360,9 @@ export class RoutePanelControl {
}); });
} }
const data = { type: "FeatureCollection", features: this._route ? [this._route] : [] }; // the traffic signals on it as points next to the line
const signals = (this._route?.properties.signals || []).map(([lon, lat]) => ({ type: "Feature", geometry: { type: "Point", coordinates: [lon, lat] }, properties: {} }));
const data = { type: "FeatureCollection", features: this._route ? [this._route, ...signals] : [] };
const source = this._map.getSource(SOURCE); const source = this._map.getSource(SOURCE);
if (source) { if (source) {
source.setData(data); source.setData(data);
@@ -380,6 +383,14 @@ export class RoutePanelControl {
layout: { "line-cap": "round", "line-join": "round" }, layout: { "line-cap": "round", "line-join": "round" },
paint: { "line-color": COLOR, "line-width": 5 }, paint: { "line-color": COLOR, "line-width": 5 },
}); });
this._map.addLayer({
id: `${SOURCE}-signals`,
type: "circle",
source: SOURCE,
minzoom: 14,
filter: ["==", ["geometry-type"], "Point"],
paint: { "circle-radius": 5, "circle-color": "#222", "circle-stroke-color": "#f9a825", "circle-stroke-width": 2.5 },
});
} }
// A route item in the library ("Routes" folder), keeping its points and // A route item in the library ("Routes" folder), keeping its points and
@@ -389,7 +400,7 @@ export class RoutePanelControl {
const name = window.prompt("Route name:", this._editing?.name || `Route ${new Date().toLocaleDateString()}`); const name = window.prompt("Route name:", this._editing?.name || `Route ${new Date().toLocaleDateString()}`);
if (!name || !name.trim()) return; if (!name || !name.trim()) return;
const { maneuvers, ...properties } = this._route.properties; const { maneuvers, speed_limits: _limits, signals: _signals, ...properties } = this._route.properties;
const feature = { const feature = {
type: "Feature", type: "Feature",
geometry: this._route.geometry, geometry: this._route.geometry,
+14 -1
View File
@@ -57,7 +57,7 @@ class CanTest < Minitest::Test
store.record("vcan0", Frame.new(0x181, "".b, false), { "gnss.lat" => 49.1 }, at: 2.0) store.record("vcan0", Frame.new(0x181, "".b, false), { "gnss.lat" => 49.1 }, at: 2.0)
snapshot = store.snapshot snapshot = store.snapshot
assert_equal({ frames: 2, last_frame_at: 2.0 }, snapshot[:interfaces]["vcan0"]) assert_equal({ frames: 2, last_frame_at: 2.0 }, snapshot[:interfaces]["vcan0"])
assert_equal({ seen_at: 1.0, state: "operational" }, snapshot[:nodes][5]) assert_equal [1.0, "operational"], snapshot[:nodes][5].values_at(:seen_at, :state)
assert_equal({ value: 49.1, at: 2.0 }, snapshot[:signals]["gnss.lat"]) assert_equal({ value: 49.1, at: 2.0 }, snapshot[:signals]["gnss.lat"])
store.record("vcan0", Frame.new(0x181, "".b, false), {}, at: 2.5) store.record("vcan0", Frame.new(0x181, "".b, false), {}, at: 2.5)
@@ -68,6 +68,19 @@ class CanTest < Minitest::Test
assert_equal({ code: 0x8130, register: 0x11, at: 3.0 }, snapshot[:nodes][5][:emcy]) assert_equal({ code: 0x8130, register: 0x11, at: 3.0 }, snapshot[:nodes][5][:emcy])
end end
def test_a_node_missing_3_heartbeats_is_silent_until_heard_again
store = Maptool::Can::Store.new
[0, 5, 10].each { |t| store.record("vcan0", Frame.new(0x702, "\x05".b, false), {}, at: t.to_f) }
_, err = capture_io { store.record("vcan0", Frame.new(0x701, "\x05".b, false), {}, at: 24.0) }
refute store.snapshot[:nodes][2][:silent]
_, err = capture_io { store.record("vcan0", Frame.new(0x701, "\x05".b, false), {}, at: 26.0) }
assert store.snapshot[:nodes][2][:silent]
assert_match(/node 2 silent/, err)
_, err = capture_io { store.record("vcan0", Frame.new(0x702, "\x05".b, false), {}, at: 30.0) }
refute store.snapshot[:nodes][2][:silent]
assert_match(/node 2 back after 20s/, err)
end
# Over a real SocketCAN interface when there is one: # Over a real SocketCAN interface when there is one:
# sudo ip link add dev vcan0 type vcan && sudo ip link set up vcan0 # sudo ip link add dev vcan0 type vcan && sudo ip link set up vcan0
def test_frames_go_over_vcan0 def test_frames_go_over_vcan0
+24
View File
@@ -0,0 +1,24 @@
require_relative "test_helper"
require_relative "../lib/maptool/gnss_sim"
class GnssSimTest < Minitest::Test
# A 1 km route north, 36 km/h limit for the first half, untagged after.
class FixedRoute < Maptool::GnssSim
def random_route(_position)
{ geometry: { coordinates: [[17.0, 48.0], [17.0, 48.0 + 1000.0 / 111_320]] },
properties: { speed_limits: [[0.0, 40], [0.5, nil]] } }
end
end
def test_drives_the_route_at_its_limits_and_ends_at_its_end
fixes = []
sim = FixedRoute.new("http://valhalla", sleep: ->(_s) {})
last = sim.drive([17.0, 48.0]) { |fix| fixes << fix }
assert_in_delta 36 / 3.6, fixes.first[:speed], 0.01 # 90 % of 40
assert_in_delta 45 / 3.6, fixes.last[:speed], 0.01 # 90 % of an untagged road's 50
assert_in_delta 48.0 + 1000.0 / 111_320, fixes.last[:lat], 1e-9
assert_equal [17.0, 48.0 + 1000.0 / 111_320], last
assert fixes.each_cons(2).all? { |a, b| b[:lat] >= a[:lat] } # never backwards
assert_in_delta 1000 / (36 / 3.6) / 2 + 500 / (45 / 3.6), fixes.size, 3 # ~1 fix a second
end
end
+16 -5
View File
@@ -145,18 +145,29 @@ class RoutingTest < Minitest::Test
def test_a_route_sums_motorway_and_toll_km_per_country_and_can_avoid_tolls def test_a_route_sums_motorway_and_toll_km_per_country_and_can_avoid_tolls
route = JSON.generate(trip: { summary: { length: 3, time: 90 }, legs: [{ shape: "wdg|xA{ubdQc@w@", maneuvers: [] }] }) route = JSON.generate(trip: { summary: { length: 3, time: 90 }, legs: [{ shape: "wdg|xA{ubdQc@w@", maneuvers: [] }] })
attributes = JSON.generate(admins: [{ country_code: "AT" }, { country_code: "SK" }], attributes = JSON.generate(admins: [{ country_code: "AT" }, { country_code: "SK" }],
edges: [{ length: 1.0, road_class: "motorway", toll: false, end_node: { admin_index: 0 } }, edges: [{ length: 1.0, road_class: "motorway", toll: false, speed_limit: 130, end_shape_index: 0, end_node: { admin_index: 0 } },
{ length: 0.5, road_class: "primary", toll: false, end_node: { admin_index: 0 } }, { length: 0.5, road_class: "primary", toll: false, speed_limit: 0, end_shape_index: 1, end_node: { admin_index: 0, traffic_signal: true } },
{ length: 1.5, road_class: "motorway", toll: true, end_node: { admin_index: 1 } }]) { length: 1.5, road_class: "motorway", toll: true, speed_limit: 130, end_shape_index: 1, end_node: { admin_index: 1 } }])
ok = ->(body) { "HTTP/1.1 200 OK\r\nContent-Length: #{body.bytesize}\r\n\r\n#{body}" } ok = ->(body) { "HTTP/1.1 200 OK\r\nContent-Length: #{body.bytesize}\r\n\r\n#{body}" }
request = serve_once(ok.(route), ok.(attributes)) do |url| request = serve_once(ok.(route), ok.(attributes)) do |url|
countries = Maptool::Routing.route(url, [[1, 2], [3, 4]], { id: "car" }, { "tolls" => true })[:properties][:countries] properties = Maptool::Routing.route(url, [[1, 2], [3, 4]], { id: "car" }, { "tolls" => true })[:properties]
assert_equal [{ code: "AT", km: 1.5, motorway_km: 1.0, toll_km: 0.0 }, { code: "SK", km: 1.5, motorway_km: 1.5, toll_km: 1.5 }], countries assert_equal [{ code: "AT", km: 1.5, motorway_km: 1.0, toll_km: 0.0 }, { code: "SK", km: 1.5, motorway_km: 1.5, toll_km: 1.5 }], properties[:countries]
assert_equal [[0.0, 130], [1.0, nil], [1.5, 130]], properties[:speed_limits]
assert_equal [[9.521034, 47.140974, 1.5]], properties[:signals]
end end
assert_includes request, %("costing_options":{"auto":{"use_tolls":0.0}}) assert_includes request, %("costing_options":{"auto":{"use_tolls":0.0}})
assert_includes request, "/trace_attributes" assert_includes request, "/trace_attributes"
end end
def test_the_road_driven_is_the_last_matched_edge
reply = JSON.generate(edges: [{ names: ["A"], road_class: "primary", speed_limit: 90 }, { names: ["B"], road_class: "motorway", speed_limit: "unlimited" }])
request = serve_once("HTTP/1.1 200 OK\r\nContent-Length: #{reply.bytesize}\r\n\r\n#{reply}") do |url|
assert_equal({ name: "B", road_class: "motorway", speed_limit: "unlimited" }, Maptool::Routing.road(url, [[17.1, 48.1], [17.2, 48.2]]))
end
assert_includes request, %("shape_match":"map_snap")
assert_raises(Maptool::Routing::RouteError) { Maptool::Routing.road("http://x", [[17.1, 48.1]]) }
end
def test_bicycle_and_foot_use_their_own_costing_without_the_country_lookup def test_bicycle_and_foot_use_their_own_costing_without_the_country_lookup
reply = JSON.generate(trip: { summary: { length: 1.5, time: 90 }, legs: [{ shape: "wdg|xA{ubdQc@w@", maneuvers: [] }] }) reply = JSON.generate(trip: { summary: { length: 1.5, time: 90 }, legs: [{ shape: "wdg|xA{ubdQc@w@", maneuvers: [] }] })
request = serve_once("HTTP/1.1 200 OK\r\nContent-Length: #{reply.bytesize}\r\n\r\n#{reply}") do |url| request = serve_once("HTTP/1.1 200 OK\r\nContent-Length: #{reply.bytesize}\r\n\r\n#{reply}") do |url|
+7 -5
View File
@@ -12,12 +12,12 @@
header { display: flex; flex-wrap: wrap; gap: 8px 16px; align-items: baseline; margin-bottom: 12px; } header { display: flex; flex-wrap: wrap; gap: 8px 16px; align-items: baseline; margin-bottom: 12px; }
h1 { font-size: 1.2rem; margin: 0; } h1 { font-size: 1.2rem; margin: 0; }
h2 { font-size: 0.8rem; font-weight: 600; color: var(--muted); text-transform: uppercase; letter-spacing: 0.05em; margin: 20px 0 6px; } h2 { font-size: 0.8rem; font-weight: 600; color: var(--muted); text-transform: uppercase; letter-spacing: 0.05em; margin: 20px 0 6px; }
#status { color: var(--muted); font-size: 0.85rem; } #status { color: var(--muted); font-size: 0.85rem; } #status.bad { color: var(--bad); }
.scroll { overflow-x: auto; } .scroll { overflow-x: auto; }
table { border-collapse: collapse; font-size: 0.85rem; min-width: 100%; } table { border-collapse: collapse; font-size: 0.85rem; }
th, td { padding: 6px 12px 6px 0; text-align: left; border-bottom: 1px solid var(--line); white-space: nowrap; } th, td { padding: 6px 12px 6px 0; text-align: left; border-bottom: 1px solid var(--line); white-space: nowrap; }
th { color: var(--muted); font-weight: 500; } th { color: var(--muted); font-weight: 500; }
td.num { font-variant-numeric: tabular-nums; text-align: right; } .num { font-variant-numeric: tabular-nums; text-align: right; }
code { font: 0.85rem ui-monospace, SFMono-Regular, Menlo, monospace; } code { font: 0.85rem ui-monospace, SFMono-Regular, Menlo, monospace; }
.ok { color: var(--ok); } .warn { color: var(--warn); } .bad { color: var(--bad); } .ok { color: var(--ok); } .warn { color: var(--warn); } .bad { color: var(--bad); }
.stale td { opacity: 0.5; } .stale td { opacity: 0.5; }
@@ -74,7 +74,7 @@
for (const f of data.frames) if (f.node != null) (roles[f.node] ||= new Set()).add(f.role); for (const f of data.frames) if (f.node != null) (roles[f.node] ||= new Set()).add(f.role);
fill("nodes", Object.entries(data.nodes).sort((a, b) => a[0] - b[0]).map(([id, n]) => { fill("nodes", Object.entries(data.nodes).sort((a, b) => a[0] - b[0]).map(([id, n]) => {
const emcy = n.emcy ? `<code>${hex(n.emcy.code, 4)}</code> reg <code>${hex(n.emcy.register, 2)}</code> ${n.emcy.code === 0 ? "(reset)" : ""} · ${age(n.emcy.at)}` : "—"; const emcy = n.emcy ? `<code>${hex(n.emcy.code, 4)}</code> reg <code>${hex(n.emcy.register, 2)}</code> ${n.emcy.code === 0 ? "(reset)" : ""} · ${age(n.emcy.at)}` : "—";
return `<tr class="${stale(n.seen_at) ? "stale" : ""}"><td>${nodeName(id)}</td><td class="${STATE_CLASS[n.state] || ""}">${esc(n.state || "no heartbeat")}</td><td>${age(n.seen_at)}</td><td class="${n.emcy?.code ? "bad" : ""}">${emcy}</td><td>${[...(roles[id] || [])].sort().map(esc).join(", ")}</td></tr>`; return `<tr class="${stale(n.seen_at) && !n.silent ? "stale" : ""}"><td>${nodeName(id)}</td><td class="${n.silent ? "bad" : STATE_CLASS[n.state] || ""}">${n.silent ? "silent (heartbeat stopped)" : esc(n.state || "no heartbeat")}</td><td>${age(n.seen_at)}</td><td class="${n.emcy?.code ? "bad" : ""}">${emcy}</td><td>${[...(roles[id] || [])].sort().map(esc).join(", ")}</td></tr>`;
}), "No CANopen node heard yet.", 5); }), "No CANopen node heard yet.", 5);
fill("signals", Object.entries(data.signals).sort().map(([name, s]) => fill("signals", Object.entries(data.signals).sort().map(([name, s]) =>
@@ -100,7 +100,9 @@
const date = Date.parse(response.headers.get("Date")); const date = Date.parse(response.headers.get("Date"));
if (date) clockOffset = Math.abs(date / 1000 - Date.now() / 1000) > 2 ? date / 1000 - Date.now() / 1000 : 0; if (date) clockOffset = Math.abs(date / 1000 - Date.now() / 1000) > 2 ? date / 1000 - Date.now() / 1000 : 0;
render(last = await response.json()); render(last = await response.json());
status.textContent = `updated ${new Date().toLocaleTimeString()}`; const silent = Object.keys(last.nodes).filter((id) => last.nodes[id].silent);
status.className = silent.length ? "bad" : "";
status.textContent = (silent.length ? `⚠ node ${silent.join(", ")} silent · ` : "") + `updated ${new Date().toLocaleTimeString()}`;
} catch (e) { } catch (e) {
status.textContent = `can't reach the server: ${e.message}`; status.textContent = `can't reach the server: ${e.message}`;
} finally { } finally {
+1
View File
@@ -18,6 +18,7 @@
"/js/gpx.js": "/js/gpx.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/hiking_trails.js": "/js/hiking_trails.js?v=<%= ASSET_VERSION %>",
"/js/live.js": "/js/live.js?v=<%= ASSET_VERSION %>", "/js/live.js": "/js/live.js?v=<%= ASSET_VERSION %>",
"/js/dashboard.js": "/js/dashboard.js?v=<%= ASSET_VERSION %>",
"/js/icons.js": "/js/icons.js?v=<%= ASSET_VERSION %>", "/js/icons.js": "/js/icons.js?v=<%= ASSET_VERSION %>",
"/js/livetrack.js": "/js/livetrack.js?v=<%= ASSET_VERSION %>", "/js/livetrack.js": "/js/livetrack.js?v=<%= ASSET_VERSION %>",
"/js/locate.js": "/js/locate.js?v=<%= ASSET_VERSION %>", "/js/locate.js": "/js/locate.js?v=<%= ASSET_VERSION %>",