Dashboard overlay (Overlays → Live → Dashboard): one inclinometer (compass ring, roll and pitch), speed, the speed limit with an over-limit warning and, on the route, the next limit change, traffic signal, maneuver and its lanes; /api/route gains speed_limits, signals and lanes, POST /api/road gives the driven road's limit; GNSS simulation (random trips over Valhalla) for trying it without the car; the HMC5883L heading in can.json
CI / check (push) Successful in 24s
CI / deploy (push) Successful in 17s

This commit is contained in:
randy committed 2026-11-30 18:30:21 +01:00
1 parent 5958ffd153
commit 190a8ad334
13 files changed
+713 -27

No files matched your search

+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)
data = valhalla(valhalla_url, "/route",
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"]
along = (along_route(valhalla_url, legs, costing, options) if %w[auto truck].include?(costing)) || {}
{ type: "Feature",
geometry: { type: "LineString", coordinates: legs.flat_map { |leg| decode_polyline(leg["shape"]) } },
properties: { kind: "route", costing: costing, distance_km: data["trip"]["summary"]["length"],
time_s: data["trip"]["summary"]["time"],
countries: (countries(valhalla_url, legs, costing, options) if %w[auto truck].include?(costing)),
maneuvers: legs.flat_map { |leg| leg["maneuvers"].map { |m| { text: m["instruction"], km: m["length"] } } } } }
time_s: data["trip"]["summary"]["time"], countries: along[:countries],
speed_limits: along[:speed_limits], signals: along[:signals],
# 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
raise RouteError, "invalid coordinates"
end
# [{ code: "AT", km:, motorway_km:, toll_km: }, ...] in route order, from
# Valhalla's per-edge attributes. nil if that lookup fails: it's extra.
def self.countries(valhalla_url, legs, costing, options)
# From Valhalla's per-edge attributes along the route:
# countries: [{ code: "AT", km:, motorway_km:, toll_km: }, ...] in route
# 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 = {}
limits = []
signals = []
km = 0.0
legs.each do |leg|
shape = decode_polyline(leg["shape"])
data = valhalla(valhalla_url, "/trace_attributes",
encoded_polyline: leg["shape"], shape_match: "edge_walk", costing: costing,
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"] }
data["edges"].each do |edge|
code = codes[edge.dig("end_node", "admin_index").to_i] || "?"
@@ -274,13 +286,41 @@ module Maptool
row[:km] += edge["length"]
row[:motorway_km] += edge["length"] if edge["road_class"] == "motorway"
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
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
nil
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