diff --git a/TODO.adoc b/TODO.adoc index fc770c7..32538ab 100644 --- a/TODO.adoc +++ b/TODO.adoc @@ -249,6 +249,14 @@ already reaches the home MQTT broker (`mqtt_ext`) from ESPHome nodes in `~/espho *** [ ] 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") +* [x] Dead reckoning in a tunnel (`App.gnss_position`): no fix for 3 s (or `mode` < 2) on the + trip's route — the position carried along it, `estimated: true`, a grey arrow; by the CAN + signal `vehicle.speed` (m/s) when there is one, the average speed of the last ~20 s before + otherwise; up to 10 min (2026-12-01). The SIM7600E's GNSS has no DR of its own +** [ ] `vehicle.speed` off the car (OBD/CAN) into `can.json`; its scale calibrated against GNSS +** [ ] Off the route: the gyro's yaw rate (the IMU node) or the compass, with map matching +** [ ] Back out of the tunnel: the first fixes taken only once consistent (HDOP, the jump from + the estimate); the trip log keeps a straight line through the tunnel for now === 3D navigation mode diff --git a/app.rb b/app.rb index 91ef4f3..ec22935 100644 --- a/app.rb +++ b/app.rb @@ -390,6 +390,21 @@ module Maptool GNSS_LATEST_MUTEX = Mutex.new COURSE_MIN_M = 5 # fixes closer than this: too noisy for a course COURSE_MIN_SPEED = 1.5 # m/s: slower, the last course stays + SPEED_AVG_S = 20.0 + VEHICLE_SPEED_FRESH_S = 2 # older: no CAN speed, the average held + + # The car's speed off CANopen (signal vehicle.speed, m/s): the meters + # driven since the last fix (dr_m), for dead reckoning in a tunnel. + def self.vehicle_speed_update(speed, at: Time.now.to_f) + GNSS_LATEST_MUTEX.synchronize do + last, last_at = GNSS_LATEST.values_at(:vehicle_speed, :vehicle_speed_at) + if last && GNSS_LATEST[:dr_m] && at - last_at < VEHICLE_SPEED_FRESH_S + GNSS_LATEST[:dr_m] += last * (at - last_at) + end + GNSS_LATEST[:vehicle_speed] = speed.to_f + GNSS_LATEST[:vehicle_speed_at] = at + end + end # Where every GNSS fix lands (the node over CAN, the simulation): into # GNSS_LATEST, with the course over ground (track, °) worked out from @@ -399,7 +414,17 @@ module Maptool fix = GNSS_LATEST_MUTEX.synchronize do GNSS_LATEST.merge!(gnss) next unless gnss.key?(:lat) || gnss.key?(:lon) + # a receiver that lost its fix (a tunnel) and repeats the last one + next if GNSS_LATEST[:mode] && GNSS_LATEST[:mode].to_i < 2 + # the average speed of the last ~SPEED_AVG_S (the speed a tunnel was + # entered at), and the car's own odometer since this fix reset + last_at = GNSS_LATEST[:received_at] + if gnss[:speed] && last_at && at > last_at + k = 1 - Math.exp(-(at - last_at) / SPEED_AVG_S) + GNSS_LATEST[:speed_avg] = (GNSS_LATEST[:speed_avg] || gnss[:speed]) * (1 - k) + gnss[:speed] * k + end + GNSS_LATEST[:dr_m] = 0.0 GNSS_LATEST[:received_at] = at unless gnss.key?(:track) position = GNSS_LATEST.values_at(:lon, :lat) @@ -452,6 +477,7 @@ module Maptool CAN_CONFIG.fetch("interfaces", []).each do |interface| Thread.new do Can.listen(interface, decoder: decoder, store: CAN_STORE, start_nodes: CAN_CONFIG["nmt_start"]) do |values| + App.vehicle_speed_update(values["vehicle.speed"]) if values["vehicle.speed"] gnss = values.filter_map { |name, value| [name.delete_prefix("gnss.").to_sym, value] if name.start_with?("gnss.") }.to_h next if gnss.empty? || GNSS_SIM.running? @@ -1432,13 +1458,35 @@ module Maptool json LIVE_STORE.update_settings(params.slice("name", "icon", "color", "logging", "trail_hours")) end + # No fix for DR_AFTER_S while driving the trip's route (a tunnel): the + # position carried along the route, `estimated: true`, for up to + # DR_MAX_S — by the car's speed off CAN when there is one (dr_m), the + # average speed the tunnel was entered at otherwise. ponytail: along + # the route only; off it the gyro's yaw rate would be needed (TODO). + DR_AFTER_S = 3 + DR_MAX_S = 600 + + def self.gnss_position(now: Time.now.to_f) + latest = GNSS_LATEST_MUTEX.synchronize { GNSS_LATEST.dup } + dr_m, vehicle_at = latest.values_at(:dr_m, :vehicle_speed_at) + fix = latest.except(:course_from, :dr_m, :vehicle_speed_at) + age = fix[:received_at] && now - fix[:received_at] + return { available: false } unless age + + speed = fix[:speed_avg] || fix[:speed] + if age >= DR_AFTER_S && age < DR_MAX_S && speed.to_f >= TripStore::MIN_SPEED && + (coords = TRIP_STORE.get.dig(:route, :geometry, :coordinates)) + can = vehicle_at && now - vehicle_at < VEHICLE_SPEED_FRESH_S + meters = can ? dr_m + fix[:vehicle_speed] * (now - vehicle_at) : speed * age + lngLat, track = TripStore.ahead(coords, [fix[:lon], fix[:lat]], meters) + return fix.merge(lon: lngLat[0], lat: lngLat[1], track: track, speed: can ? fix[:vehicle_speed] : speed, available: true, estimated: true) if lngLat + end + age < GNSS_STALE_AFTER ? fix.merge(available: true) : { available: false } + end + get "/api/gnss/position" do require_login! - GNSS_LATEST_MUTEX.synchronize do - received_at = GNSS_LATEST[:received_at] - fresh = received_at && (Time.now.to_f - received_at) < GNSS_STALE_AFTER - json(fresh ? GNSS_LATEST.except(:course_from).merge(available: true) : { available: false }) - end + json App.gnss_position end end end diff --git a/lib/maptool/gnss_sim.rb b/lib/maptool/gnss_sim.rb index 10f8103..ffab080 100644 --- a/lib/maptool/gnss_sim.rb +++ b/lib/maptool/gnss_sim.rb @@ -53,7 +53,7 @@ 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:, time: the simulation's epoch s }. + # { lat:, lon:, speed: m/s, satellites:, hdop:, mode: 3, time: the simulation's epoch s }. def start(lon = nil, lat = nil, bboxes: nil, route: nil, &on_fix) stop @error = nil @@ -112,7 +112,7 @@ module Maptool 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, time: @clock.round(1)) + on_fix&.call(lat: lat, lon: lon, speed: kmh / 3.6, satellites: 12, hdop: 0.8, mode: 3, time: @clock.round(1)) break if i == coords.size - 1 && t >= 1 @sleep.call(TICK_S) diff --git a/lib/maptool/trip.rb b/lib/maptool/trip.rb index 4c227f8..f883310 100644 --- a/lib/maptool/trip.rb +++ b/lib/maptool/trip.rb @@ -97,6 +97,20 @@ module Maptool best end + # Dead reckoning along the line: from the point nearest `position`, + # `meters` further on — [[lon, lat], bearing °], or nil if `position` + # is more than ON_ROUTE_M off it (no telling where the car went then). + # Stops at the line's end. + def self.ahead(coords, position, meters) + at, off = locate(coords, position) + return nil if off > ON_ROUTE_M + + km = coords.each_cons(2).reduce([0.0]) { |acc, (a, b)| acc << acc.last + GnssSim.meters(a, b) / 1000 } + to = [at + meters / 1000.0, km.last].min + here = GnssSim.point_at(coords, km, to) + [here, GnssSim.bearing(GnssSim.point_at(coords, km, [to - 0.02, 0].max), GnssSim.point_at(coords, km, [to + 0.02, km.last].min)).round(1)] + end + # points: [{ lngLat: [lon, lat], name:, nav:, passed: }]. Routes through # the ones not passed with the block (locations, vehicle id, avoid → the # /api/route Feature, may raise Routing errors) unless only names/nav diff --git a/public/css/style.css b/public/css/style.css index d1cbe1b..dc4a47e 100644 --- a/public/css/style.css +++ b/public/css/style.css @@ -3468,6 +3468,8 @@ button.basemap-panel__link[hidden] { display: none; } /* The GNSS position once it has a course: an arrow, not the dot. */ .gnss-marker--arrow { width: 26px; height: 26px; border: none; border-radius: 0; background: none; box-shadow: none; filter: drop-shadow(0 1px 2px rgb(0 0 0 / 0.5)); } .gnss-marker--arrow svg { display: block; } +/* no fix, the position estimated along the route (a tunnel): greyed */ +.gnss-marker--estimated { filter: grayscale(1) opacity(0.7) drop-shadow(0 1px 2px rgb(0 0 0 / 0.5)); } /* The navigation banner across the top (dashboard.js): the next turn. */ .dash-banner { diff --git a/public/js/gnss.js b/public/js/gnss.js index a6e8f7a..dd46d6b 100644 --- a/public/js/gnss.js +++ b/public/js/gnss.js @@ -71,6 +71,14 @@ export function resumeFollow(map) { clearTimeout(state.timer); } +// The first step of a follow (or a jump after a gap): zoom in to see the +// road ahead. easeTo, not flyTo — flyTo's swoop zooms out over the distance +// first, the wrong way when starting to drive. +export const FOLLOW_ZOOM = 16; +export function startFollow(map, lngLat) { + map.easeTo({ center: lngLat, zoom: Math.max(map.getZoom(), FOLLOW_ZOOM), duration: 1000 }); +} + export function followPosition(map, lngLat, heading, speed, duration) { const free = freeLookState(map); free.followedAt = Date.now(); @@ -83,14 +91,27 @@ export function followPosition(map, lngLat, heading, speed, duration) { free.button.hidden = true; const pitched = map.getPitch() > 0; const moving = Number.isFinite(heading) && (speed ?? 0) >= 1; + const zoom = moving && autoZoom(map.getZoom(), speed); map.easeTo({ center: lngLat, padding: { top: pitched ? map.getContainer().clientHeight * 0.4 : 0 }, ...(pitched && moving && { bearing: heading }), + ...(zoom && { zoom }), ...(duration != null && { duration, easing: (t) => t }), }); } +// Auto-zoom like a car navigation: close in town, farther out the faster +// (0 km/h z17, 50 z16.2, 90 z15.6, 130+ z15). Eased toward that by at most +// 0.15 a fix and ignored within 0.25, so speed jitter doesn't pump the map. +// A hand zoom pauses the follow; on resuming it eases back. +export function autoZoom(current, speed) { + const target = Math.min(17, Math.max(15, 17 - speed * 3.6 * 0.0154)); + const diff = target - current; + if (Math.abs(diff) < 0.25) return null; + return current + Math.sign(diff) * Math.min(Math.abs(diff), 0.15); +} + // Meters between a MapLibre LngLat and [lon, lat] (equirectangular). function distanceM({ lng, lat }, [lon2, lat2]) { return Math.hypot((lon2 - lng) * Math.cos((lat * Math.PI) / 180), lat2 - lat) * 111320; @@ -189,15 +210,16 @@ export class GnssControl { return; } - this._status.textContent = fixLabel(data); + // no fix, carried along the route (a tunnel: App.gnss_position) + this._status.textContent = data.estimated ? "estimated (no fix)" : fixLabel(data); const lngLat = [data.lon, data.lat]; // Recenters on every fix while enabled — this is the app's own // receiver, so "GNSS on" means "follow it", the same way LocateControl // (public/js/locate.js) follows it when GNSS is what it's using too. - // flyTo (with its zoom swoop) only for the first fix, since that's the - // one jumping from wherever the map already was; easeTo for later - // updates, a plain follow rather than repeating that swoop every poll. + // startFollow (zooming in) only for the first fix, since that's the + // one jumping from wherever the map already was; a plain follow for + // later updates, zooming by the speed (autoZoom). const far = this._marker && distanceM(this._marker.getLngLat(), lngLat) > JUMP_M; if (far) this._removeMarker(); if (!this._marker) { @@ -208,7 +230,7 @@ export class GnssControl { // survives map.setStyle() (switching Online/Offline) with no extra // re-add handling needed. this._marker = new Marker({ element: el, rotationAlignment: "map", pitchAlignment: "map" }).setLngLat(lngLat).addTo(this._map); - this._map.flyTo({ center: lngLat, zoom: Math.max(this._map.getZoom(), 15) }); + startFollow(this._map, lngLat); } else { glideMarker(this._marker, lngLat, POLL_INTERVAL_MS); followPosition(this._map, lngLat, data.track, data.speed, POLL_INTERVAL_MS); @@ -222,6 +244,7 @@ export class GnssControl { } this._marker.setRotation(data.track); } + this._marker.getElement().classList.toggle("gnss-marker--estimated", !!data.estimated); } _removeMarker() { diff --git a/public/js/locate.js b/public/js/locate.js index e4920d4..bd8f7a5 100644 --- a/public/js/locate.js +++ b/public/js/locate.js @@ -1,5 +1,5 @@ import { Marker } from "/vendor/maplibre-gl/maplibre-gl.mjs"; -import { followPosition } from "/js/gnss.js"; +import { followPosition, startFollow } from "/js/gnss.js"; // Replaces MapLibre's own GeolocateControl (browser Geolocation API only) // with one that prefers this app's own GNSS receiver when it's turned on @@ -96,7 +96,7 @@ export class LocateControl { _jumpToGnss({ alertIfNoFix = false } = {}) { const position = this._gnssControl.getPosition(); if (position) { - this._map.flyTo({ center: position, zoom: Math.max(this._map.getZoom(), 15) }); + startFollow(this._map, position); } else if (alertIfNoFix) { window.alert("Waiting for a GNSS fix…"); } @@ -118,10 +118,9 @@ export class LocateControl { } // Recenters on every fix, following the position the way GeolocateControl - // itself does while tracking — flyTo (with its zoom swoop) only for the + // itself does while tracking — startFollow (zooming in) only for the // first fix, since that's the one jumping from wherever the map already - // was; easeTo for later updates, a plain pan/zoom-preserving follow - // rather than repeating that same swoop on every update. + // was; a plain follow zooming by the speed (autoZoom) for later updates. // // MapLibre's own blue pulsing "user location" dot styling // (.maplibregl-user-location-dot, maplibre-gl.css — the exact look @@ -138,7 +137,7 @@ export class LocateControl { const circleEl = document.createElement("div"); circleEl.className = "maplibregl-user-location-accuracy-circle"; this._circleMarker = new Marker({ element: circleEl, pitchAlignment: "map" }).setLngLat([lon, lat]).addTo(this._map); - this._map.flyTo({ center: [lon, lat], zoom: Math.max(this._map.getZoom(), 15) }); + startFollow(this._map, [lon, lat]); } else { this._marker.setLngLat([lon, lat]); this._circleMarker.setLngLat([lon, lat]); diff --git a/test/test_app.rb b/test/test_app.rb index 0002762..f71f9e6 100644 --- a/test/test_app.rb +++ b/test/test_app.rb @@ -679,6 +679,37 @@ class AppTest < Minitest::Test latest.clear end + # A tunnel: no fix for a while, the position carried along the trip's + # route — at the average speed it was entered at, by the CAN speed when there is one. + def test_no_fix_on_the_route_is_dead_reckoned_along_it + latest = Maptool::App::GNSS_LATEST + latest.clear + store = Maptool::App::TRIP_STORE + saved = store.instance_variable_get(:@trip) + north = 1000.0 / 111_320 # 1 km north + store.instance_variable_set(:@trip, saved.merge(points: [], route: { geometry: { coordinates: [[17.0, 48.0], [17.0, 48.0 + 5 * north]] } })) + Maptool::App.gnss_update({ lat: 48.0, lon: 17.0, speed: 20.0, mode: 3 }, at: 100.0) + Maptool::App.gnss_update({ lat: 48.0, lon: 17.0, speed: 20.0 }, at: 101.0) + + assert_nil Maptool::App.gnss_position(now: 102.0)[:estimated] # not yet: a fix may just be late + position = Maptool::App.gnss_position(now: 111.0) # 10 s × 20 m/s + assert position[:estimated] + assert_in_delta 48.0 + 0.2 * north, position[:lat], 1e-6 + assert_in_delta 0.0, position[:track], 0.5 + + Maptool::App.gnss_update({ lat: 48.0, lon: 17.0, mode: 1 }, at: 105.0) # the receiver repeating its last fix + assert Maptool::App.gnss_position(now: 111.0)[:estimated] + + Maptool::App.vehicle_speed_update(10.0, at: 102.0) # the car's own speed: 10 m/s + Maptool::App.vehicle_speed_update(10.0, at: 103.0) + position = Maptool::App.gnss_position(now: 104.0) + assert_in_delta 48.0 + 0.02 * north, position[:lat], 1e-6 + assert_equal 10.0, position[:speed] + ensure + latest.clear + store.instance_variable_set(:@trip, saved) + end + private def upload(filename, content, folder: "", content_type: "application/octet-stream")