GNSS simulation on its own diagnostics page (/sim.html: drive the trip's route or randomly, stop, simulated time, the position and the trip); along the route with a detour now and then (300–800 m off every 3–8 km, routed by Valhalla); simulated time 1–20× with the fixes carrying the simulation's clock, so a recorded trip keeps real speeds (PUT /api/sim/gnss); /api/can says simulated
This commit is contained in:
1 parent
7d72e9eb63
commit
0c809b3e2b
9 files changed
+265
-46
No files matched your search
@@ -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
|
||||
|
||||
@@ -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).
|
||||
|
||||
+88
-4
@@ -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
|
||||
|
||||
+3
-34
@@ -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 {
|
||||
<label class="live-tracker__row"><input type="checkbox" data-widget="navigation"> Speed limit & ahead (route)</label>
|
||||
<label class="live-tracker__row"><input type="checkbox" data-widget="banner"> Navigation banner (next turn)</label>
|
||||
<label class="live-tracker__row">Background <input type="range" class="dash-opacity" min="0" max="1" step="0.05"></label>
|
||||
<button type="button" class="dash-sim">Simulate driving from a random place</button>
|
||||
<p class="live-panel__status dash-sim-status" hidden></p>
|
||||
<a class="dash-sim" href="/sim.html" target="_blank">GNSS simulation ↗</a>
|
||||
</div>`;
|
||||
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";
|
||||
|
||||
+1
-1
@@ -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.
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -108,6 +108,7 @@
|
||||
<div class="basemap-panel__list">
|
||||
<a class="basemap-panel__link" href="/status.html" target="_blank">Server status (all endpoints) ↗</a>
|
||||
<a class="basemap-panel__link" href="/can.html" target="_blank">CANopen diagnostics ↗</a>
|
||||
<a class="basemap-panel__link" href="/sim.html" target="_blank">GNSS simulation ↗</a>
|
||||
<button type="button" class="basemap-panel__link debug-panel__update-check" hidden>Check for an update now</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
+101
@@ -0,0 +1,101 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<meta name="color-scheme" content="light dark">
|
||||
<title>GNSS simulation</title>
|
||||
<link rel="icon" href="/icons/icon.svg" type="image/svg+xml">
|
||||
<style>
|
||||
:root { color-scheme: light dark; --muted: GrayText; --line: color-mix(in srgb, CanvasText 15%, transparent); --ok: #2e7d32; --bad: #c62828; }
|
||||
body { margin: 0; padding: 16px; background: Canvas; color: CanvasText; font: 15px/1.4 -apple-system, "Segoe UI", Roboto, Helvetica, Arial, sans-serif; }
|
||||
header { display: flex; flex-wrap: wrap; gap: 8px 16px; align-items: baseline; margin-bottom: 16px; }
|
||||
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: 0 0 8px; }
|
||||
#cards { display: grid; gap: 16px; grid-template-columns: repeat(auto-fill, minmax(min(360px, 100%), 1fr)); align-items: start; }
|
||||
section { border: 1px solid var(--line); border-radius: 8px; padding: 12px 16px; }
|
||||
button, select { font-size: 1rem; padding: 10px 14px; border-radius: 8px; }
|
||||
.actions { display: flex; flex-wrap: wrap; gap: 8px; }
|
||||
dl { display: grid; grid-template-columns: max-content 1fr; gap: 4px 16px; margin: 0; }
|
||||
dt { color: var(--muted); } dd { margin: 0; font-variant-numeric: tabular-nums; }
|
||||
.on { color: var(--ok); font-weight: 600; } .bad { color: var(--bad); }
|
||||
a { color: inherit; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<header>
|
||||
<h1>GNSS simulation</h1>
|
||||
<span id="state">loading…</span>
|
||||
<a href="/status.html">Server status</a> <a href="/can.html">CANopen diagnostics</a> <a href="/" target="maptool">The map</a>
|
||||
</header>
|
||||
<div id="cards">
|
||||
<section>
|
||||
<h2>Drive</h2>
|
||||
<div class="actions">
|
||||
<button type="button" id="route">Drive the trip's route</button>
|
||||
<button type="button" id="random">From a random place</button>
|
||||
<button type="button" id="stop">Stop</button>
|
||||
</div>
|
||||
<p id="hint" style="color: GrayText; font-size: 0.85rem"></p>
|
||||
<label>Simulated time
|
||||
<select id="speedup"></select>
|
||||
</label>
|
||||
<p style="color: GrayText; font-size: 0.85rem">Faster time: the car moves on sooner; a recorded trip keeps the real speeds (each fix carries the simulation's clock).</p>
|
||||
</section>
|
||||
<section>
|
||||
<h2>Position</h2>
|
||||
<dl id="position"></dl>
|
||||
</section>
|
||||
<section>
|
||||
<h2>Trip</h2>
|
||||
<dl id="trip"></dl>
|
||||
</section>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
// The simulation's controls (lib/maptool/gnss_sim.rb, /api/sim/gnss):
|
||||
// the trip's route with detours, or random trips; its time sped up.
|
||||
// The map (another tab) follows it with GNSS on. Polled every second.
|
||||
const $ = (id) => document.getElementById(id);
|
||||
const json = async (url, options) => {
|
||||
const response = await fetch(url, { cache: "no-store", ...options });
|
||||
const body = await response.json().catch(() => ({}));
|
||||
if (!response.ok) throw new Error(body.error || `HTTP ${response.status}`);
|
||||
return body;
|
||||
};
|
||||
const rows = (el, pairs) => (el.innerHTML = pairs.map(([k, v]) => `<dt>${k}</dt><dd>${v ?? "—"}</dd>`).join(""));
|
||||
const send = (method, body) => json("/api/sim/gnss", { method, headers: { "Content-Type": "application/json" }, body: body && JSON.stringify(body) }).catch((e) => alert(e.message)).then(refresh);
|
||||
|
||||
$("route").addEventListener("click", () => send("POST", { trip: true }));
|
||||
$("random").addEventListener("click", () => send("POST", {}));
|
||||
$("stop").addEventListener("click", () => send("DELETE"));
|
||||
$("speedup").addEventListener("change", () => send("PUT", { speedup: Number($("speedup").value) }));
|
||||
|
||||
async function refresh() {
|
||||
try {
|
||||
const [sim, gnss, trip, log] = await Promise.all([
|
||||
json("/api/sim/gnss"), json("/api/gnss/position"), json("/api/trip"), json("/api/trip/log"),
|
||||
]);
|
||||
$("state").innerHTML = sim.running ? `<span class="on">● running</span>${sim.speedup > 1 ? ` · ${sim.speedup}× time` : ""}` : sim.error ? `<span class="bad">stopped: ${sim.error}</span>` : "stopped";
|
||||
if (!$("speedup").options.length) $("speedup").innerHTML = sim.speedups.map((n) => `<option value="${n}">${n}×${n === 1 ? " (real)" : ""}</option>`).join("");
|
||||
$("speedup").value = String(sim.speedup);
|
||||
$("route").disabled = !trip.route;
|
||||
$("hint").textContent = trip.route ? `The trip's route: ${trip.route.properties.distance_km.toFixed(1)} km, with a detour now and then.` : "No trip route — plan one on the map to drive it.";
|
||||
rows($("position"), gnss.available ? [
|
||||
["Lat, lon", `${gnss.lat.toFixed(5)}, ${gnss.lon.toFixed(5)}`], ["Speed", gnss.speed != null ? `${Math.round(gnss.speed * 3.6)} km/h` : null],
|
||||
["Course", gnss.track != null ? `${Math.round(gnss.track)}°` : null], ["Fix", gnss.mode === 3 ? "3D" : gnss.mode === 2 ? "2D" : gnss.available ? "yes" : null],
|
||||
] : [["Fix", "none"]]);
|
||||
rows($("trip"), [
|
||||
["Stops", trip.points.length ? `${trip.points.length} (${trip.points.filter((p) => p.passed).length} passed)` : "none"],
|
||||
["Recording", log.active ? `<span class="on">● ${log.folder}</span>` : "no — Start the trip in the map's Trip menu"],
|
||||
["Driven", log.active ? `${(log.distance_m / 1000).toFixed(1)} km, ${log.points} points` : null],
|
||||
]);
|
||||
} catch (e) {
|
||||
$("state").innerHTML = `<span class="bad">${e.message}</span>${/401/.test(e.message) ? ' — <a href="/login">log in</a>' : ""}`;
|
||||
}
|
||||
}
|
||||
refresh();
|
||||
setInterval(refresh, 1000);
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
+1
-1
@@ -32,7 +32,7 @@
|
||||
<span id="status">loading…</span>
|
||||
<input id="filter" type="search" placeholder="Filter endpoints or content…">
|
||||
<button id="pause" type="button">Pause</button>
|
||||
<a href="/can.html">CANopen diagnostics</a>
|
||||
<a href="/can.html">CANopen diagnostics</a> <a href="/sim.html">GNSS simulation</a>
|
||||
</header>
|
||||
<div id="cards"></div>
|
||||
|
||||
|
||||
Reference in new issue
Block a user