diff --git a/app.rb b/app.rb index b4009d4..1c24346 100644 --- a/app.rb +++ b/app.rb @@ -415,7 +415,8 @@ module Maptool end return unless fix && fix[:lat] && fix[:lon] - TRIP_LOG.record(fix[:lon], fix[:lat], fix[:alt], at) if TRIP_LOG.active? + # a fix's own time when it has one (the simulation's clock, sped up) + TRIP_LOG.record(fix[:lon], fix[:lat], fix[:alt], gnss[:time].is_a?(Numeric) ? gnss[:time] : at) if TRIP_LOG.active? # off the shared trip's route: routed again from here (TripStore#follow) TRIP_STORE.follow([fix[:lon], fix[:lat]], speed: fix[:speed], hdop: fix[:hdop]) do |locations, vehicle, avoid| @@ -498,6 +499,11 @@ module Maptool erb :symbols, layout: false end + # The GNSS simulation's controls (its API below, login). + get "/sim.html" do + erb :sim, layout: false + end + # Every status endpoint on one full-screen page (they need the login). get "/status.html" do erb :status, layout: false @@ -1361,7 +1367,8 @@ module Maptool snapshot = CAN_STORE.snapshot units = CAN_DECODER ? CAN_DECODER.units : {} snapshot[:signals] = snapshot[:signals].to_h { |name, signal| [name, units[name] ? signal.merge(unit: units[name]) : signal] } - json snapshot.merge(available: !CAN_CONFIG.nil?) + # simulated: the GNSS simulation (/sim.html) stands in for gnss.* + json snapshot.merge(available: !CAN_CONFIG.nil?, simulated: GNSS_SIM.running?) end # The GNSS simulation: POST {"start": [lon, lat]} drives randomly from @@ -1369,7 +1376,16 @@ module Maptool # 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 + json running: GNSS_SIM.running?, error: GNSS_SIM.error, speedup: GNSS_SIM.speedup, speedups: GnssSim::SPEEDUPS + end + + # {"speedup": 1|2|5|10|20}: the simulation's time, faster (also while it runs). + put "/api/sim/gnss" do + require_login! + GNSS_SIM.speedup = JSON.parse(request.body.read)["speedup"] + json running: GNSS_SIM.running?, error: GNSS_SIM.error, speedup: GNSS_SIM.speedup, speedups: GnssSim::SPEEDUPS + rescue JSON::ParserError + halt 400, json(error: "invalid JSON") end post "/api/sim/gnss" do @@ -1390,7 +1406,7 @@ module Maptool CAN_STORE.override_prefix = "gnss." GNSS_SIM.start(lon, lat, bboxes: bboxes, route: route) do |fix| - CAN_STORE.put(fix.transform_keys { |key| "gnss.#{key}" }) + CAN_STORE.put(fix.except(:time).transform_keys { |key| "gnss.#{key}" }) App.gnss_update(fix) end json running: true diff --git a/docs/deployment.adoc b/docs/deployment.adoc index 8ad4677..5ce4a72 100644 --- a/docs/deployment.adoc +++ b/docs/deployment.adoc @@ -326,9 +326,12 @@ The node sends no course: `App.gnss_update` (where every fix lands, the node's and the GNSS simulation's) works it out from the fix ≥ 5 m back while moving ≥ 1.5 m/s and keeps the last one standing still, so `/api/gnss/position` has `track` and following in 3D turns heading-up. -The simulation (Dashboard settings, `POST`/`DELETE /api/sim/gnss`; `{"trip": true}` drives the shared trip's route first, the dashboard's button does when there is one) drives +The simulation (its own diagnostics page, `/sim.html` — linked from Status / debug and the dashboard settings; `POST`/`DELETE /api/sim/gnss`; `{"trip": true}` drives the shared trip's route first — with a detour now and then, 300–800 m off to one side every 3–8 km, to try off-route and the rerouting — the page's "Drive the trip's route") drives random trips over the local Valhalla and stands in for the node's `gnss.*` -meanwhile — on the car's server only for trying things out. While it +meanwhile — on the car's server only for trying things out. Its time can run faster +("Simulated time" 1–20×, `PUT /api/sim/gnss {"speedup"}`): the car moves +on that much sooner, while each fix carries the simulation's own clock, so +a recorded trip (it's recorded like the car's) shows the real speeds. While it runs, the dashboard takes the altitude from the terrain (no `gnss.alt` then) and, when no IMU sends pitch/roll, tilts the car by it: the DEM's slope 15 m ahead/behind and left/right of the course (`dem.js`, zoom 12, the terrain's slope rather than the road's). diff --git a/lib/maptool/gnss_sim.rb b/lib/maptool/gnss_sim.rb index a309668..10f8103 100644 --- a/lib/maptool/gnss_sim.rb +++ b/lib/maptool/gnss_sim.rb @@ -15,6 +15,16 @@ module Maptool LIMIT_SHARE = 0.9 # drives a bit under the limit attr_reader :error + # Time runs this many times faster (1, 2, 5, 10…): the car covers that + # much more ground per real tick, while each fix's `time` is the + # simulation's own clock — a recorded trip shows the real speeds, not + # 250 km/h. Changeable while it runs. + SPEEDUPS = [1, 2, 5, 10, 20].freeze + attr_reader :speedup + + def speedup=(value) + @speedup = SPEEDUPS.include?(value.to_i) ? value.to_i : 1 + end def initialize(valhalla_url, vehicle: { id: "car" }, random: Random.new, sleep: ->(s) { Kernel.sleep(s) }, router: Routing.method(:route)) @@ -25,6 +35,8 @@ module Maptool @sleep = sleep @thread = nil @mutex = Mutex.new + @speedup = 1 + @clock = Time.now.to_f end def running? @@ -41,13 +53,14 @@ module Maptool # from a random place in one of them; with a route (the trip's /api/route # Feature), that route from its start first, random trips after it; # each fix to the block: - # { lat:, lon:, speed: m/s, satellites:, hdop: }. + # { lat:, lon:, speed: m/s, satellites:, hdop:, time: the simulation's epoch s }. def start(lon = nil, lat = nil, bboxes: nil, route: nil, &on_fix) stop @error = nil + @clock = Time.now.to_f @mutex.synchronize do @thread = Thread.new do - position, route = if route then [route[:geometry][:coordinates].first, route] + position, route = if route then [route[:geometry][:coordinates].first, with_detours(route)] elsif bboxes then random_start(bboxes) else [[Float(lon), Float(lat)], nil] end @@ -94,11 +107,12 @@ module Maptool i = 1 while i < coords.size kmh = speed_kmh(limits.reverse.find { |start, _| start <= at }&.last) - at += kmh / 3600 * TICK_S + at += kmh / 3600 * TICK_S * @speedup + @clock += TICK_S * @speedup 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) + on_fix&.call(lat: lat, lon: lon, speed: kmh / 3.6, satellites: 12, hdop: 0.8, time: @clock.round(1)) break if i == coords.size - 1 && t >= 1 @sleep.call(TICK_S) @@ -110,6 +124,76 @@ module Maptool (limit == "unlimited" ? UNLIMITED_KMH : limit || NO_LIMIT_KMH) * LIMIT_SHARE end + DETOUR_EVERY_KM = (3.0..8.0) # along the route between two detours + DETOUR_ALONG_KM = (0.6..1.5) # the stretch of route a detour replaces + DETOUR_OFF_M = (300.0..800.0) # how far off it goes, either side + + # The route with a detour now and then (to try off-route and the + # rerouting): a stretch of it replaced by a way (our Valhalla) through a + # point DETOUR_OFF_M to one side; where there's no way, the route as it + # is. Speed limits carried along, the detours' own. + def with_detours(route) + 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]] + out = [] + out_limits = [] + add = lambda do |line, line_limits, from_km| + offset = out.empty? ? 0.0 : self.class.length_km(out) + line_limits.each { |start, limit| out_limits << [offset + start - from_km, limit] } + out.concat(out.empty? ? line : line.drop(1)) + end + original = ->(from, to) { add.(self.class.slice(coords, km, from, to), limits_in(limits, from, to), from) } + at = 0.0 + loop do + start = at + @random.rand(DETOUR_EVERY_KM) + finish = start + @random.rand(DETOUR_ALONG_KM) + break original.(at, km.last) if finish >= km.last + + original.(at, start) + a, b = self.class.point_at(coords, km, start), self.class.point_at(coords, km, finish) + side = @random.rand < 0.5 ? -1 : 1 + bearing = (self.class.bearing(a, b) + 90 * side) * Math::PI / 180 + mid = self.class.point_at(coords, km, (start + finish) / 2) + off = @random.rand(DETOUR_OFF_M) + via = [mid[0] + off * Math.sin(bearing) / (111_320 * Math.cos(mid[1] * Math::PI / 180)), mid[1] + off * Math.cos(bearing) / 111_320] + begin + detour = @router.call(@valhalla_url, [a, via, b], @vehicle) + add.(detour[:geometry][:coordinates], detour[:properties][:speed_limits] || [[0.0, nil]], 0.0) + rescue Routing::RouteError + original.(start, finish) + end + at = finish + end + { geometry: { type: "LineString", coordinates: out }, properties: { speed_limits: out_limits.uniq } } + end + + # The limits that apply from `from` to `to` km, from `from` on. + def limits_in(limits, from, to) + first = limits.reverse.find { |start, _| start <= from } || [from, nil] + [[from, first[1]]] + limits.select { |start, _| start > from && start < to } + end + + # [lon, lat] at km along the line (km: the cumulative km at each vertex). + def self.point_at(coords, km, at) + i = km.index { |k| k >= at } || (km.size - 1) + return coords[i] if i.zero? || km[i] == km[i - 1] + + t = (at - km[i - 1]) / (km[i] - km[i - 1]) + coords[i - 1].zip(coords[i]).map { |p, q| p + (q - p) * t } + end + + # The line from `from` to `to` km, its ends cut at those points. + def self.slice(coords, km, from, to) + inner = coords.each_index.select { |i| km[i] > from && km[i] < to }.map { |i| coords[i] } + [point_at(coords, km, from), *inner, point_at(coords, km, to)] + end + + def self.length_km(line) + line.each_cons(2).sum { |a, b| meters(a, b) } / 1000 + end + # A route to a random point DEST_KM away; a few tries (a lake, no road there). def random_route(position) last = nil diff --git a/public/js/dashboard.js b/public/js/dashboard.js index f9a5376..1c13e47 100644 --- a/public/js/dashboard.js +++ b/public/js/dashboard.js @@ -1,5 +1,5 @@ import { isLoggedIn } from "/js/auth.js"; -import { onRouteChanged, requestReroute, requestGnssFollow, notifyRouteProgress } from "/js/panels.js"; +import { onRouteChanged, requestReroute, notifyRouteProgress } from "/js/panels.js"; import { elevationAt } from "/js/dem.js"; // The car's dashboard over the map, off the CAN signals (GET /api/can, @@ -176,7 +176,6 @@ export class DashboardControl { this._lastAt = 0; this._offFixes = 0; this._sentKm = undefined; // the new route drawn by the next fix - this._simLabel(); })); this._trace = []; // [lon, lat] fixes TRACE_STEP_M apart, for /api/road this._road = null; // its last answer @@ -299,8 +298,7 @@ export class DashboardControl { - -
+ GNSS simulation ↗ `; this._toggle = li.querySelector(".overlays-panel__toggle"); this._status = li.querySelector(".live-panel__status"); @@ -331,36 +329,6 @@ export class DashboardControl { this._save(); this._card?.style.setProperty("--dash-alpha", opacity.value); }); - 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 a random place in the offline countries, the GNSS control - // turned on to follow it; on = true / false, null = just read the state. - async _simulate(on) { - // along the route when there is one (the shared trip's), else from a random place - const options = on === true ? { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(this._route ? { trip: true } : {}) } - : 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; - if (on === true && state.running) requestGnssFollow(); // the map follows the simulated position - 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._simLabel(); - } - - _simLabel() { - if (this._simButton) this._simButton.textContent = this._simRunning ? "Stop the simulation" : this._route ? "Simulate driving the route" : "Simulate driving from a random place"; } _save() { @@ -406,6 +374,7 @@ export class DashboardControl { return [key, s && now - s.at < STALE_S + 1 ? s.value : null]; })); this._updateCourse(this._values); + this._simRunning = !!data.simulated; // /sim.html runs it if (this._simRunning) await this._simulateTerrain(); this._navigate(); this._status.textContent = this._simRunning ? "Simulated GNSS" : data.available ? "" : "CAN is off on this server"; diff --git a/test/test_app.rb b/test/test_app.rb index f929ed2..0002762 100644 --- a/test/test_app.rb +++ b/test/test_app.rb @@ -174,7 +174,7 @@ class AppTest < Minitest::Test def test_can_requires_login_and_is_off_without_a_config assert_equal 401, request.get("/api/can").status - assert_equal({ "interfaces" => {}, "nodes" => {}, "signals" => {}, "frames" => [], "available" => false }, json_body(request.get("/api/can", **logged_in_env))) + assert_equal({ "interfaces" => {}, "nodes" => {}, "signals" => {}, "frames" => [], "available" => false, "simulated" => false }, json_body(request.get("/api/can", **logged_in_env))) end # MQTT messages land in the tracker / ITS-G5 parts of /api/live. diff --git a/test/test_gnss_sim.rb b/test/test_gnss_sim.rb index 57f1ab9..f189fd9 100644 --- a/test/test_gnss_sim.rb +++ b/test/test_gnss_sim.rb @@ -35,6 +35,51 @@ class GnssSimTest < Minitest::Test sim&.stop end + # Sped up: five times the ground per tick, the fixes' clock five times + # faster — the speed they report (and a recorded track's) stays real. + def test_speedup_covers_more_ground_on_a_faster_clock + times = ->(speedup) do + sim = FixedRoute.new("http://valhalla", sleep: ->(_s) {}) + sim.speedup = speedup + fixes = [] + sim.drive([17.0, 48.0]) { |fix| fixes << fix } + fixes + end + real, fast = times.(1), times.(5) + assert_in_delta real.size / 5.0, fast.size, 2 + assert_in_delta real.last[:time] - real.first[:time], fast.last[:time] - fast.first[:time], 5 # the same simulated time + assert_equal real.first[:speed], fast.first[:speed] + sim = Maptool::GnssSim.new("http://valhalla") + sim.speedup = 7 + assert_equal 1, sim.speedup # not one of SPEEDUPS + end + + # A long route gets detours: a stretch replaced by the router's way through + # a point off to one side (here: straight there and back), the start and the + # end kept, the limits in order; a detour with no way keeps the route. + def test_a_route_gets_detours_off_to_the_side + asked = [] + router = lambda do |_url, (a, via, b), _vehicle| + asked << via + raise Maptool::Routing::RouteError, "no way" if asked.size == 2 + + { geometry: { coordinates: [a, via, b] }, properties: { speed_limits: [[0.0, 30]] } } + end + sim = Maptool::GnssSim.new("http://valhalla", random: Random.new(1), router: router) + line = [[17.0, 48.0], [17.3, 48.0]] # ~22 km east + route = sim.with_detours({ geometry: { coordinates: line }, properties: { speed_limits: [[0.0, 90]] } }) + coords = route[:geometry][:coordinates] + assert_equal [line.first, line.last], [coords.first, coords.last] + assert_operator asked.size, :>=, 2 + off = asked.map { |_lon, lat| (lat - 48.0).abs * 111_320 } + assert(off.all? { |m| m.between?(250, 850) }, "#{off} m off the route") + assert_includes coords, asked.first # the first detour driven through its point + refute_includes coords, asked[1] # the second had no way: the route as it was + starts = route[:properties][:speed_limits].map(&:first) + assert_equal starts.sort, starts + assert_includes route[:properties][:speed_limits].map(&:last), 30 + end + # No road at the first random place: another one, inside the bbox. class FirstPlaceAtSea < Maptool::GnssSim attr_reader :tried diff --git a/views/index.erb b/views/index.erb index be1064c..d29f95e 100644 --- a/views/index.erb +++ b/views/index.erb @@ -108,6 +108,7 @@ diff --git a/views/sim.erb b/views/sim.erb new file mode 100644 index 0000000..6f0a771 --- /dev/null +++ b/views/sim.erb @@ -0,0 +1,101 @@ + + + + + + +Faster time: the car moves on sooner; a recorded trip keeps the real speeds (each fix carries the simulation's clock).
+