require "sinatra/base" require "sinatra/json" require "oauth2" require "securerandom" require "zip" require "stringio" require "tempfile" require_relative "lib/maptool/gpx" require_relative "lib/maptool/fit" require_relative "lib/maptool/gpx_store" require_relative "lib/maptool/library" require_relative "lib/maptool/google_saved" require_relative "lib/maptool/routing" require_relative "lib/maptool/mqtt_client" require_relative "lib/maptool/can" require_relative "lib/maptool/can_discovery" require_relative "lib/maptool/can_recorder" require_relative "lib/maptool/keypad" require_relative "lib/maptool/outputs" require_relative "lib/maptool/can_time" require_relative "lib/maptool/gnss_sim" require_relative "lib/maptool/trip" require_relative "lib/maptool/trip_log" require_relative "lib/maptool/trip_days" require_relative "lib/maptool/link_place" require_relative "lib/maptool/updater" require_relative "lib/maptool/sync" require "ipaddr" require_relative "lib/maptool/live_store" require_relative "lib/maptool/livetrack_store" require_relative "lib/maptool/livetrack_client" require_relative "lib/maptool/kiwix" require_relative "lib/maptool/plugins" require_relative "lib/maptool/corridor" require_relative "lib/maptool/pmtiles_builder" require_relative "lib/maptool/search" module Maptool # Only /login, /auth/callback and /logout ever write to session # (oauth_state, user, session.clear) — everything else only ever reads # it, if it touches session at all. That still matters: # Rack::Session::Cookie re-serializes and re-sets the cookie on *every* # response that so much as read session (Rack::Protection's own CSRF # check does, on nearly every request) — reflecting whatever cookie # that particular request happened to arrive with, whether or not # anything changed. A HAR capture caught the actual failure mode this # caused: seconds after a successful login, a background poll fired the # instant the page loads was still carrying the browser's pre-login # cookie (a client-side timing race across the OAuth redirect chain, # not something this server controls), and its own re-issued Set-Cookie # landed *after* the login's, silently overwriting session[:user] with # nothing logged anywhere to explain it. # # A plain Rack middleware, not a Sinatra `before` filter: static assets # (public_folder — every JS/CSS/font/vendor file) are served by # Sinatra's own built-in static-file shortcut, which bypasses route and # filter dispatch entirely but is still wrapped by this, same as every # other response — each one was independently capable of winning the # clobbering race a `before` filter alone left uncovered. class SkipSessionWrite WRITE_PATHS = %w[/login /auth/callback /logout].freeze def initialize(app) @app = app end def call(env) env["rack.session.options"][:skip] = true unless WRITE_PATHS.include?(env["PATH_INFO"]) @app.call(env) end end class App < Sinatra::Base set :public_folder, File.join(__dir__, "public") # Revalidate every static file (a cheap 304 when unchanged): /js and # /css are cache-busted by ASSET_VERSION below, but the /vendor modules # they import (mdi.mjs, nps-symbols.mjs, ...) aren't versioned — with no # Cache-Control a browser caches them heuristically for hours, and a # deploy that adds an export there (mdi.mjs gaining a new icon) left a # tablet with new icons.js + stale mdi.mjs: a failed import, a blank map. set :static_cache_control, [:no_cache] # The PWA manifest (public/manifest.webmanifest) — Rack doesn't know # this extension and would serve it as application/octet-stream. mime_type :webmanifest, "application/manifest+json" set :views, File.join(__dir__, "views") # sinatra/json defaults to MultiJson, whose `encode` (what # sinatra-contrib 4.2.1 actually calls) is deprecated in newer # multi_json versions in favor of a constant this app has no other use # for — stdlib JSON already does the same job and every use of the # `json` helper below is a plain hash/array, nothing MultiJson-specific. set :json_encoder, JSON # A persistent secret across restarts/redeploys — otherwise every deploy # would invalidate every logged-in session's cookie (see # docs/deployment.adoc). Falls back to a random one so the app still # loads locally/in CI without it set; that fallback just means sessions # don't survive a restart there, which is fine outside production. # expire_after: without it the cookie is a browser-session one, which # Android drops whenever it kills the browser/PWA — a fresh Gitea # login + MFA every time on the tablet. Counted from login (only the # login paths write the cookie, see SkipSessionWrite). set :sessions, httponly: true, secure: production?, same_site: :lax, expire_after: 90 * 24 * 3600, secret: ENV.fetch("SESSION_SECRET") { SecureRandom.hex(32) } use SkipSessionWrite # Cache-busts /js and /css requests: browsers (and a caching proxy in # front of production, see docs/deployment.adoc) hang onto static # assets for hours, so without this a deploy that changes app.js/css # can go unnoticed by an already-open tab until that cache expires. # A fresh value every process start (i.e. every deploy, which restarts # the container) is enough — it doesn't need to survive restarts. ASSET_VERSION = Time.now.to_i # Written by the CI deploy job (.gitea/workflows/ci.yml) right before it # drops .git from the deployed copy, so this is the only way to tell # which commit is actually live short of asking the deploy job itself — # handy for exactly the kind of "did my push actually deploy, or am I # looking at a stale browser cache" confusion ASSET_VERSION above can't # answer by itself (that only proves *a* deploy happened recently, not # *which* one). Absent outside a real deploy (local dev, CI's own # `check` job), hence the fallback. REVISION = begin File.read(File.join(__dir__, "REVISION")).strip rescue Errno::ENOENT "dev" end # Overridable so the test suite can point this at a throwaway directory # instead of the real data/ — nothing else needs to set this. DATA_DIR = ENV.fetch("MAPTOOL_DATA_DIR") { File.join(__dir__, "data") } OFFLINE_PMTILES_PATH = File.join(DATA_DIR, "offline.pmtiles") TERRAIN_PMTILES_PATH = File.join(DATA_DIR, "terrain.pmtiles") # Pre-library uploads (data/gpx/), still read for migrated layers. GPX_STORE = GpxStore.new(File.join(DATA_DIR, "gpx")) LIBRARY = Library.new(File.join(DATA_DIR, "library.sqlite"), gpx_store: GPX_STORE, sources_dir: File.join(DATA_DIR, "library", "sources")) # Once per parser upgrade, in the background so boot isn't held up. Thread.new do warn "library: re-read #{LIBRARY.reparse} track profiles" rescue StandardError => e warn "library reparse failed: #{e.message}" end # Google Maps saved lists from a scheduled Google Takeout (product # "Saved"), synced into TAKEOUT_DIR (mounted read-only, see # docker-compose.yaml): checked hourly, a new export is imported into # Tracks & Points under "Google Maps/" (GoogleSaved). Unset = off. TAKEOUT_DIR = ENV.fetch("TAKEOUT_DIR", "") unless TAKEOUT_DIR.empty? || test? Thread.new do loop do count = GoogleSaved.import_takeout(TAKEOUT_DIR, library: LIBRARY, state_path: File.join(DATA_DIR, "takeout_imported")) warn "takeout: imported #{count} saved places" if count rescue StandardError => e warn "takeout import failed: #{e.class}: #{e.message}" ensure sleep 3600 end end end LIVETRACK_STORE = LiveTrackStore.new(File.join(DATA_DIR, "livetrack.json")) # Not under DATA_DIR: unlike everything else there (uploads, PMTiles, # the kiwix ZIM), a plugin is code, not local data — plugins/overpass-pois # ships checked into this repo as the reference example of the # contract. Overridable so tests can point it at a throwaway fixture # directory. In production this whole directory is baked into the # image (see Dockerfile's `COPY . .`) and wiped/replaced on every # deploy along with the rest of the checkout (docs/deployment.adoc) — # fine for a plugin checked into this repo, not for a private one. PLUGINS_DIR = ENV.fetch("MAPTOOL_PLUGINS_DIR") { File.join(__dir__, "plugins") } # A second, optional plugin directory under DATA_DIR — the same # persistent bind mount as gpx/kiwix (docs/deployment.adoc), so a # private/scraper plugin (one whose ToS forbids living in this public # repo) dropped in data/plugins/ survives a redeploy the way PLUGINS_DIR # above can't. Checked after PLUGINS_DIR (see Plugins.list/run), so a # same-named private plugin never shadows the built-in one. PLUGINS_DIRS = [PLUGINS_DIR, File.join(DATA_DIR, "plugins")].freeze PLUGIN_SETTINGS = File.join(DATA_DIR, "plugin_settings.json") # Shared secret for the Garmin LiveTrack webhook (a Google Apps Script # watching Gmail for LiveTrack emails, see docs/deployment.adoc) — not a # Gitea-authenticated user, so it can't use the OAuth2 login flow above. # Blank means the endpoint is disabled, same fallback story as the # OAuth2 secrets: fine outside production, nothing works without it set. LIVETRACK_WEBHOOK_SECRET = ENV.fetch("LIVETRACK_WEBHOOK_SECRET", "") # An external kiwix-serve instance (see docs/development.adoc), not # something this app runs itself — blank disables the "Nearby on # Wikipedia" popup link the same way the other optional-integration # blanks above do. Only ever reached server-side (the Docker-network # service name in production, e.g. "http://kiwix:8080") — production # sits behind a reverse proxy (map.priesol.net) that only forwards to # this app, so a browser can't reach kiwix-serve directly by any # hostname/port of its own. GET /kiwix/* below proxies to it instead. KIWIX_URL = ENV.fetch("KIWIX_URL", "") # The valhalla container (docker-compose.yaml), reached server side only. VALHALLA_URL = ENV.fetch("VALHALLA_URL", "") # The home MQTT broker the car's ESPHome nodes publish to (empty = off): # mqtt:// or mqtts://, with a read-only user. See LIVE below. MQTT_URL = ENV.fetch("MQTT_URL", "") Routing.install_service_script(DATA_DIR) # Login delegates to the Gitea instance the user already has an account # on, rather than maintaining a local username/password — see # docs/architecture.adoc. Only users listed in ALLOWED_GITEA_USERS may # write; anyone else can authenticate against Gitea but is still # refused. No defaults for the OAuth2 client id/secret/user list: blank # values just mean login (and thus writing) doesn't work, which is fine # outside production — nothing here is eagerly validated at load time. GITEA_URL = ENV.fetch("GITEA_URL", "https://git.priesol.net") ALLOWED_GITEA_USERS = ENV.fetch("MAPTOOL_ALLOWED_GITEA_USER", "").split(",").map(&:strip) OAUTH_CLIENT = OAuth2::Client.new( ENV.fetch("GITEA_OAUTH_CLIENT_ID", ""), ENV.fetch("GITEA_OAUTH_CLIENT_SECRET", ""), site: GITEA_URL, authorize_url: "/login/oauth/authorize", token_url: "/login/oauth/access_token" ) # The car's server (no internet, so no Gitea login): requests from # these networks (comma-separated CIDRs) count as logged in. By the # socket's own peer address, never X-Forwarded-For — and only for a # server no reverse proxy sits in front of (behind one every request # comes from the proxy's address). "connected" stands for the subnets # the server's own interfaces are on right now (host networking: the # Pi's LAN, whichever Wi-Fi it's on), looked up on each request. TRUSTED_NETWORKS = ENV.fetch("TRUSTED_NETWORKS", "").split(",").map(&:strip).reject(&:empty?) .map { |cidr| cidr == "connected" ? :connected : IPAddr.new(cidr) } # The directly connected subnets: each interface address under its netmask. def self.connected_networks Socket.getifaddrs.filter_map do |i| next unless i.addr&.ip? && i.netmask&.ip? IPAddr.new("#{i.addr.ip_address.split('%').first}/#{i.netmask.ip_address}") rescue IPAddr::Error nil end end # Library sync (Sync), OsmAnd-style: brick is the server, a client # (the car's) has SYNC_SERVER_URL and syncs on its Sync button. The same # SYNC_TOKEN on both: the server's /api/sync/* answer only to it. SYNC_TOKEN = ENV.fetch("SYNC_TOKEN", "") SYNC_SERVER_URL = ENV.fetch("SYNC_SERVER_URL", "") SYNC_CLIENT = SYNC_TOKEN.empty? || SYNC_SERVER_URL.empty? ? nil : Sync.new(server: SYNC_SERVER_URL, token: SYNC_TOKEN, library: LIBRARY, state_path: File.join(DATA_DIR, "sync_state.json")) SYNC_MUTEX = Mutex.new # Map data the server hands its clients (GET /api/sync/maps, pulled by # bin/pull-maps.sh — one way, the server builds it): these files and # everything under these directories of DATA_DIR. # Of kiwix/ only the ZIM kiwix-serve is given (other ZIMs lying there are GBs). MAP_SYNC_FILES = %w[offline.pmtiles offline.pmtiles.meta.json terrain.pmtiles terrain.pmtiles.meta.json offline_regions.json kiwix/wikipedia.zim].freeze MAP_SYNC_DIRS = %w[routing places hiking_trails nps].freeze # { "relative/path" => absolute path } of the map data there is now; # hidden and temporary files (.rsync-partial, *.part, *.tmp) left out, # and routing/service.sh (each server copies its own in at boot). def self.map_sync_files paths = MAP_SYNC_FILES.map { |f| File.join(DATA_DIR, f) } + MAP_SYNC_DIRS.flat_map { |d| Dir.glob(File.join(DATA_DIR, d, "**", "*")) } paths.select { |p| File.file?(p) } .to_h { |p| [p.delete_prefix("#{DATA_DIR}/"), p] } .reject { |rel, _| rel.split("/").any? { |part| part.start_with?(".") } || rel.match?(/\.(part|tmp)\z|[\t\n]/) || rel == "routing/service.sh" } end helpers do def logged_in? !!session[:user] || trusted_network? end def trusted_network? return false if TRUSTED_NETWORKS.empty? address = IPAddr.new(request.env["REMOTE_ADDR"].to_s.delete_prefix("::ffff:")) TRUSTED_NETWORKS.flat_map { |n| n == :connected ? App.connected_networks : [n] }.any? { |network| network.include?(address) } rescue IPAddr::Error false end def require_sync_token! given = request.env["HTTP_AUTHORIZATION"].to_s.delete_prefix("Bearer ") halt 401, json(error: "sync token required") if SYNC_TOKEN.empty? || !Rack::Utils.secure_compare(given, SYNC_TOKEN) end def require_login! halt 401, json(error: "login required", login_url: "/login") unless logged_in? end def pmtiles_file_status(path, meta) return { available: false } unless File.exist?(path) status = { available: true, size: File.size(path), mtime: File.mtime(path).utc.iso8601 } meta ? status.merge(meta: meta) : status end def callback_url "#{request.base_url}/auth/callback" end # Zip-bomb guard: the entries' *declared* uncompressed sizes are summed # before anything is extracted, and rubyzip itself (validate_entry_sizes, # on by default) raises Zip::EntrySizeError if an entry inflates past # what it declared — so a lying header can't sneak past this either. MAX_ZIP_UNCOMPRESSED = 500 * 1024 * 1024 def parse_feature feature = JSON.parse(params[:feature].to_s) halt 400, json(error: "invalid feature") unless feature.is_a?(Hash) && feature["geometry"] feature rescue JSON::ParserError halt 400, json(error: "invalid feature") end # The node's first line as a FIT course (FitCourse), or nil. A route # planned for a bicycle/foot profile keeps that sport. def fit_course(geojson, name) feature = JSON.parse(geojson)["features"].find { |f| f.dig("geometry", "type").to_s.end_with?("LineString") } return unless feature props = feature["properties"] || {} coordinates = feature["geometry"]["type"] == "LineString" ? feature["geometry"]["coordinates"] : feature["geometry"]["coordinates"].flatten(1) vehicle = props["vehicle"].is_a?(Hash) ? props["vehicle"] : {} sport = case vehicle["type"] when "bicycle" then "cycling" when "foot" then vehicle["speed"].to_f >= 7 ? "running" : "hiking" else props["activity_type"] end points = JSON.parse(geojson)["features"].select { |f| f.dig("geometry", "type") == "Point" }.map do |f| p = f["properties"] || {} { coordinate: f["geometry"]["coordinates"], name: p["name"], hint: [p["name"], p["category"], p["icon"]].compact.join(" ") } end FitCourse.encode(coordinates, name: props["name"] || name, sport: sport, duration: props["duration_secs"], points: points) rescue ArgumentError nil end def save_zip_entries(folder:, io:) paths = [] Zip::File.open_buffer(io) do |zip| entries = zip.select { |entry| entry.file? && Library::EXTENSIONS.any? { |ext| entry.name.downcase.end_with?(ext) } } halt 413, json(error: "zip contents too large") if entries.sum(&:size) > MAX_ZIP_UNCOMPRESSED entries.each do |entry| paths.concat(LIBRARY.import(folder: folder, filename: File.basename(entry.name), io: StringIO.new(entry.get_input_stream.read))) end end paths end end get "/login" do session[:oauth_state] = SecureRandom.hex(16) redirect OAUTH_CLIENT.auth_code.authorize_url( redirect_uri: callback_url, state: session[:oauth_state], scope: "read:user" ) end get "/auth/callback" do halt 400, "invalid state" unless params[:state] && params[:state] == session.delete(:oauth_state) token = OAUTH_CLIENT.auth_code.get_token(params[:code], redirect_uri: callback_url) user = token.get("/api/v1/user").parsed halt 403, "not authorized" unless ALLOWED_GITEA_USERS.include?(user["login"]) session[:user] = user["login"] redirect "/" end get "/logout" do session.clear redirect "/" end # Live GNSS position, polled by the frontend from /api/gnss/position. # No receiver feeds it for now: gpsd support was dropped, the car's # GNSS is to come over CAN (TODO.adoc) and will fill GNSS_LATEST the # same way. Polling instead of push (SSE/WebSocket) is deliberate — a # receiver reports at ~1Hz, so there is nothing to gain from a push # channel, and it avoids # Sinatra's `stream(:keep_open)` helper, which — absent an EventMachine # reactor (i.e. under plain threaded Puma, as here) — busy-loops calling # its block repeatedly instead of waiting for external writes; fine for # a single blocking per-message write, not for "register once, get # pushed to later" like this. # A fix is only reported back as "available" for this long after it # last arrived — otherwise a receiver that's lost its fix, or been # unplugged, would keep showing its last position forever as if it # were still live. GNSS_STALE_AFTER = 10 # seconds GNSS_LATEST = {} 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 # the fix COURSE_MIN_M back when the receiver sends none — following # heading-up from behind (followPosition, gnss.js) turns by it. def self.gnss_update(gnss, at: Time.now.to_f) 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) from = GNSS_LATEST[:course_from] if from.nil? || (GNSS_LATEST[:speed] || 0) < COURSE_MIN_SPEED GNSS_LATEST[:course_from] = position elsif GnssSim.meters(from, position) >= COURSE_MIN_M GNSS_LATEST[:track] = GnssSim.bearing(from, position).round(1) GNSS_LATEST[:course_from] = position end end GNSS_LATEST.dup end return unless fix && fix[:lat] && fix[:lon] # 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| Routing.route(VALHALLA_URL, locations, Routing.vehicle(DATA_DIR, vehicle), avoid.transform_keys(&:to_s)) end end # Native CAN (lib/maptool/can.rb), on when data/can.json exists: one # reader thread per interface. Signals named gnss. (lat, lon, # alt, speed in m/s, track in degrees, mode) feed GNSS_LATEST; a fix # counts from the frame that brings lat or lon. CAN_CONFIG_PATH = File.join(DATA_DIR, "can.json") CAN_STORE = Can::Store.new # A broken can.json turns CAN off (logged) instead of the whole server. CAN_CONFIG, CAN_DECODER = begin config = JSON.parse(File.read(CAN_CONFIG_PATH)) if File.exist?(CAN_CONFIG_PATH) [config, config && Can::Decoder.new(config.fetch("signals", []))] rescue StandardError => e warn "can: #{CAN_CONFIG_PATH}: #{e.message} — CAN off" [nil, nil] end # can.json's "actions": SDO writes /can.html offers beside their node (Can::Sdo::Action). CAN_ACTIONS = (CAN_CONFIG ? CAN_CONFIG.fetch("actions", []) : []).filter_map do |action| Can::Sdo::Action.parse(action) rescue StandardError => e warn "can: #{CAN_CONFIG_PATH}: action #{action.inspect}: #{e.message} — skipped" nil end # can.json's "keypads": keys and knobs as channels for the screen # profile's bindings (Keypad). KEYPAD = begin k = CAN_CONFIG&.dig("keypads") k && !k.empty? ? Keypad.new(k) : nil rescue StandardError => e warn "can: #{CAN_CONFIG_PATH}: keypads: #{e.message} — no keypads" nil end CAN_DECODER.set_node(:keypad, KEYPAD.signals) if KEYPAD # Frames maptool puts on the bus (LEDs, outputs, TIME): one socket on # the first interface, opened when first needed, again after an error. CAN_TX_MUTEX = Mutex.new def self.can_send(frame) CAN_TX_MUTEX.synchronize do @can_tx ||= Can.open(CAN_CONFIG.fetch("interfaces").first) @can_tx.write(frame.pack) rescue SocketError, SystemCallError @can_tx&.close @can_tx = nil raise end end # can.json's "outputs": relay modules driven by the profile's bindings (Outputs). OUTPUTS = begin o = CAN_CONFIG&.dig("outputs") o && !o.empty? ? Outputs.new(o) { |frame| App.can_send(frame) } : nil rescue StandardError => e warn "can: #{CAN_CONFIG_PATH}: outputs: #{e.message} — no outputs" nil end # CANopen TIME while nobody else sends it (can.json's "time": false: never). CAN_TIME = CAN_CONFIG && CAN_CONFIG.fetch("time", true) && !test? ? Can::TimeProducer.new { |f| App.can_send(f) } : nil # The keypads' bindings: the ones saved in /keypad.html (data/drive/ # bindings.json, this car's), else the screen profile's defaults; read # again when the file changes. The browser takes them from GET /api/keypad/bindings. DRIVE_PROFILE_PATH = File.join(__dir__, "public", "drive", "road.json") BINDINGS_PATH = File.join(DATA_DIR, "drive", "bindings.json") def self.bindings path = File.exist?(BINDINGS_PATH) ? BINDINGS_PATH : DRIVE_PROFILE_PATH key = [path, File.mtime(path)] @bindings = [key, JSON.parse(File.read(path)).fetch("bindings", [])] unless @bindings&.first == key @bindings.last rescue StandardError => e warn "drive bindings: #{e.message}" [] end BINDING_KEYS = %w[input action menu output mode pulse_s led led_on].freeze # A saved list's check: each an input, an action / menu or an output, known modes and colours. def self.check_bindings(list) raise ArgumentError, "bindings: a list" unless list.is_a?(Array) list.map do |b| raise ArgumentError, "a binding: an object" unless b.is_a?(Hash) b = b.slice(*BINDING_KEYS).reject { |_, v| v.nil? || v == "" } raise ArgumentError, "a binding without an input" unless b["input"].is_a?(String) && b["input"].include?(".") raise ArgumentError, "#{b['input']}: unknown mode #{b['mode']}" if b["mode"] && !Outputs::MODES.include?(b["mode"]) %w[led led_on].each { |k| raise ArgumentError, "#{b['input']}: unknown colour #{b[k]}" if b[k] && !Keypad::COLORS.key?(b[k]) } b["pulse_s"] = Float(b["pulse_s"]) if b["pulse_s"] b end end def self.keypads_present nodes = CAN_STORE.snapshot[:nodes] KEYPAD ? KEYPAD.devices.select { |d| (seen = nodes.dig(d.heartbeat_node, :heartbeat_at)) && Time.now.to_f - seen < Keypad::PRESENT_S } : [] end # A keypad's key LEDs: the screen's colours (PUT /api/keypad/leds) with # the keys bound to outputs on top (their "led" while on, dark off), # sent when they change. KEYPAD_SCREEN_LEDS = {} def self.keypad_leds_frames(device) on = (KEYPAD_SCREEN_LEDS.dig(device.name, "on") || {}).dup if OUTPUTS bindings.each do |b| next unless b["output"] && b["input"].to_s.start_with?("#{device.name}.") on[b["input"].delete_prefix("#{device.name}.")] = OUTPUTS.on?(b["output"]) ? b.fetch("led", "red") : nil end end KEYPAD.led_frames(device.name, on, KEYPAD_SCREEN_LEDS.dig(device.name, "blink")) end # The bus recorded on the server into MF4 files (/trace.html, can-recorder/). CAN_RECORDER = Can::Recorder.new(File.join(DATA_DIR, "can_rec"), CAN_CONFIG ? CAN_CONFIG.fetch("interfaces", []) : []) at_exit { CAN_RECORDER.stop } # Simulated driving (lib/maptool/gnss_sim.rb) in place of the GNSS node. GNSS_SIM = GnssSim.new(VALHALLA_URL) if CAN_CONFIG && !test? decoder = CAN_DECODER # Our esphome-canopen nodes describe themselves over SDO (can_discovery.rb); # can.json's "aliases" name their signals ({"XIAO STM32C5 2.Latitude": "gnss.lat"}). if CAN_CONFIG.fetch("discover", true) && (interface = CAN_CONFIG.fetch("interfaces", []).first) Can::Discoverer.new(store: CAN_STORE, decoder: decoder, cache_dir: File.join(DATA_DIR, "can_nodes"), aliases: CAN_CONFIG.fetch("aliases", {}), interface: interface).start end CAN_CONFIG.fetch("interfaces", []).each do |interface| Thread.new do Can.listen(interface, decoder: decoder, store: CAN_STORE, start_nodes: CAN_CONFIG["nmt_start"], on_frame: ->(f) { CAN_TIME&.heard(f) }) do |values| App.vehicle_speed_update(values["vehicle.speed"]) if values["vehicle.speed"] events = KEYPAD&.update(values) || [] events.each { |e| OUTPUTS.input(e, App.bindings) } if OUTPUTS 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? App.gnss_update(gnss) end end end end # Every 100 ms: the outputs (pulses ending, their state again for the # modules' watchdog), a keypad gone silent letting go of what it held, # the keypads' LEDs when they changed; every second the TIME. if CAN_CONFIG && !test? && (OUTPUTS || KEYPAD || CAN_TIME) Thread.new do was_present = [] leds_sent = {} time_at = 0 loop do begin OUTPUTS&.tick present = App.keypads_present (was_present.map(&:name) - present.map(&:name)).each { |name| OUTPUTS&.keypad_lost(name) } leds_sent = {} if present != was_present was_present = present present.select { |d| d.protocol == "pkp" }.each do |d| frames = App.keypad_leds_frames(d) next if leds_sent[d.name] == frames.map(&:data) frames.each { |f| App.can_send(f) } leds_sent[d.name] = frames.map(&:data) end if CAN_TIME && Time.now.to_f - time_at >= Can::TimeProducer::INTERVAL_S time_at = Time.now.to_f CAN_TIME.tick end rescue StandardError => e warn "can tick: #{e.message}" unless e.message == @last_tick_error @last_tick_error = e.message end sleep Outputs::REPEAT_S end end end # Live data off the home MQTT broker (MQTT_URL), polled by the frontend # from /api/live like GNSS above — the "Tracker" and "ITS-G5" overlays: # the LTE GNSS tracker's position and USB power (+ its trail, optionally # logged), and ITS-G5 stations heard by its receiver. See LiveStore. TRACKER_TOPIC = "mcu-tracker/location" TRACKER_POWER_TOPIC = "mcu-tracker/binary_sensor/usb_power/state" ITS_TOPIC = "mcu-its-g5/decoded" LIVE_STORE = LiveStore.new(File.join(DATA_DIR, "live")) def self.record_live(topic, payload, at: Time.now.to_f) case topic when TRACKER_TOPIC then LIVE_STORE.record_tracker(JSON.parse(payload), at: at) when TRACKER_POWER_TOPIC then LIVE_STORE.record_usb_power(payload) when ITS_TOPIC then LIVE_STORE.record_its(JSON.parse(payload), at: at) end rescue JSON::ParserError nil end unless MQTT_URL.empty? Thread.new do MqttClient.new(url: MQTT_URL, username: ENV.fetch("MQTT_USERNAME", ""), password: ENV.fetch("MQTT_PASSWORD", ""), topics: [TRACKER_TOPIC, TRACKER_POWER_TOPIC, ITS_TOPIC]).each_message { |topic, payload| record_live(topic, payload) } end end get "/" do erb :index, locals: { logged_in: logged_in?, user: session[:user] || "local network", revision: REVISION, sync_client: !SYNC_CLIENT.nil? } end # Map legend + symbol browser. A view, not a static public/ page, so it # gets the same versioned importmap as the map: as a static page it # imported /js/icons.js and /vendor/mdi/mdi.mjs unversioned, and a # browser still holding an older copy of either rendered no symbols. get "/symbols.html" do 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 end # CANopen diagnostics (polls GET /api/can, which needs the login). get "/can.html" do erb :can, layout: false end # The keypads' bindings, edited (after the Design canvas' GridBinding). get "/keypad.html" do erb :keypad, layout: false end # Every CAN frame as it came, decoded (polls GET /api/can?since=). get "/trace.html" do erb :trace, layout: false end # A share to the installed app normally never reaches the server: the # service worker (public/sw.js) takes the POST, parks the files and # opens the app. Only lands here if no worker is running yet — back to # the map rather than a 404, the share just has to be repeated. post "/share-target" do redirect "/", 303 end # Self-update (lib/maptool/updater.rb), on the car's server only # (SELF_UPDATE=1): GET says whether main has a newer commit that passed # CI, POST asks the host to install it (bin/update-maptool.sh). SELF_UPDATE = ENV["SELF_UPDATE"] == "1" UPDATE_REPO = ENV.fetch("UPDATE_REPO", "randy/maptool") get "/api/update" do require_login! halt json(enabled: false) unless SELF_UPDATE Updater.reset! if params[:fresh] # "Check now": past the 10 min cache latest = Updater.latest(GITEA_URL, UPDATE_REPO) available = !!latest && latest[:ci] == "success" && latest[:sha] && !latest[:sha].start_with?(REVISION) json enabled: true, current: REVISION, latest: latest&.dig(:sha)&.slice(0, 7), ci: latest&.dig(:ci), available: available, status: Updater.status(DATA_DIR) end post "/api/update" do require_login! halt 404, json(error: "self-update is off on this server") unless SELF_UPDATE latest = Updater.latest(GITEA_URL, UPDATE_REPO) halt 409, json(error: "no newer version that passed CI") unless latest && latest[:ci] == "success" && !latest[:sha].start_with?(REVISION) Updater.request(DATA_DIR, latest[:sha]) json requested: latest[:sha][0, 7] end get "/api/health" do json status: "ok", revision: REVISION end get "/api/offline-tiles" do json pmtiles_file_status(OFFLINE_PMTILES_PATH, PmtilesBuilder.offline_meta(DATA_DIR)) end # Served as a plain range-request-capable file, not decoded server-side: # pmtiles.js reads the archive's directory and fetches only the byte # ranges it needs for the tiles currently on screen. get "/tiles/offline.pmtiles" do halt 404 unless File.exist?(OFFLINE_PMTILES_PATH) send_file OFFLINE_PMTILES_PATH, type: "application/octet-stream" end # Compares the recorded build (offline.pmtiles.meta.json) against the # current latest Protomaps build without rebuilding anything — # update_available is null (not true/false) if there's no local build # yet, or the live index couldn't be reached, so the frontend can tell # "don't know" apart from "no, up to date". Not folded into GET # /api/offline-tiles above: that route is on the hot path (map.js's own # topbar-dot check on every page load), this one only gets called when # the Offline data panel is actually opened. get "/api/offline-tiles/check-update" do json update_available: PmtilesBuilder.offline_update_available?(DATA_DIR) end # Lists the selectable countries and which of them are currently # selected (data/offline_regions.json) — read-only, no login needed, # same tier as the plain availability checks above. get "/api/offline-regions" do json continents: PmtilesBuilder.continents, available: PmtilesBuilder.available_regions, selected: PmtilesBuilder.selected_regions(DATA_DIR) end # Just updates the selection — does not itself start a build, so # ticking several countries doesn't fire off several rebuilds. The # frontend follows this with the two build routes below once the user # is done choosing. post "/api/offline-regions" do require_login! codes = Array(params[:codes]) begin PmtilesBuilder.set_selected_regions(DATA_DIR, codes) rescue PmtilesBuilder::BuildError => e halt 400, json(error: e.message) end json ok: true end # Regenerates offline.pmtiles for the currently selected regions (see # POST /api/offline-regions above) by downloading each from Geofabrik # and tiling them with Planetiler — see lib/maptool/pmtiles_builder.rb. # Runs in the background; poll build-status below for progress. post "/api/offline-tiles/build" do require_login! begin PmtilesBuilder.build_offline(data_dir: DATA_DIR) rescue PmtilesBuilder::BuildError => e halt 409, json(error: e.message) end json status: "started" end get "/api/offline-tiles/build-status" do json PmtilesBuilder.offline_status end # Per-step timings of past offline/terrain builds, newest first — the # "benchmark" to compare a later build against (debug panel). get "/api/build-history" do json PmtilesBuilder.build_history(DATA_DIR) end # Deletes offline.pmtiles plus its whole per-country download cache — # a manual "reclaim the space"/"start over" action, distinct from # unticking countries in the region picker (which only changes what a # future build covers, doesn't free anything already on disk). delete "/api/offline-tiles" do require_login! begin PmtilesBuilder.delete_offline_data(DATA_DIR) rescue PmtilesBuilder::BuildError => e halt 409, json(error: e.message) end json ok: true end # What's actually in the per-country download cache right now (not the # same as offline.pmtiles' own meta.sources — see cached_extracts) — # read-only, same tier as GET /api/offline-regions above, so the region # picker can show a size + delete affordance next to each cached # country regardless of whether it's still selected or already built. get "/api/offline-tiles/cache" do json extracts: PmtilesBuilder.cached_extracts(DATA_DIR) end # Deletes one country's cached Geofabrik extract only — e.g. to force a # clean re-download of just that one, or reclaim space for a country # that's no longer selected (the cache otherwise keeps it indefinitely). delete "/api/offline-tiles/cache/:code" do require_login! begin PmtilesBuilder.delete_cached_extract(DATA_DIR, params[:code]) rescue PmtilesBuilder::BuildError => e halt 409, json(error: e.message) end json ok: true end # Same optional-local-file story as offline.pmtiles above — see # docs/development.adoc for how to generate one, until then hillshade # just stays unavailable while the offline basemap is active. get "/api/terrain-tiles" do json pmtiles_file_status(TERRAIN_PMTILES_PATH, PmtilesBuilder.terrain_meta(DATA_DIR)) end get "/tiles/terrain.pmtiles" do halt 404 unless File.exist?(TERRAIN_PMTILES_PATH) send_file TERRAIN_PMTILES_PATH, type: "application/octet-stream" end # Same reasoning as GET /api/offline-tiles/check-update above. get "/api/terrain-tiles/check-update" do json update_available: PmtilesBuilder.terrain_update_available?(DATA_DIR) end post "/api/terrain-tiles/build" do require_login! begin PmtilesBuilder.build_terrain(data_dir: DATA_DIR) rescue PmtilesBuilder::BuildError => e halt 409, json(error: e.message) end json status: "started" end get "/api/terrain-tiles/build-status" do json PmtilesBuilder.terrain_status end # Offline routing (lib/maptool/routing.rb): the same status/build/ # build-status/check-update shape as the two rows above, so the Offline # data panel shows it the same way. Valhalla builds in its own # container; these only hand it requests and read its status files. get "/api/routing-tiles" do json Routing.tiles_status(DATA_DIR, VALHALLA_URL) end get "/api/routing-tiles/check-update" do json update_available: Routing.update_available?(DATA_DIR) end post "/api/routing-tiles/build" do require_login! begin Routing.request_build(DATA_DIR) rescue PmtilesBuilder::BuildError => e halt 409, json(error: e.message) end json status: "started" end get "/api/routing-tiles/build-status" do json Routing.build_status(DATA_DIR) end # A route through the posted points ({"locations": [[lon, lat], ...]}) # for the vehicle profile "vehicle" (an id, default the first). Open to anyone, like viewing the map; only # saving it to the library needs a login. post "/api/route" do body = JSON.parse(request.body.read) locations = body["locations"] halt 400, json(error: "locations must be a list of [lon, lat]") unless locations.is_a?(Array) && locations.all?(Array) json Routing.route(VALHALLA_URL, locations, Routing.vehicle(DATA_DIR, body["vehicle"]), body["avoid"]) 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 # The shared trip (lib/maptool/trip.rb): every screen polls it # (?version=N: 204 while it's still N) and edits it with PUT # {points: [{lngLat, name, nav}], vehicle, avoid, editing}, routed here. # Logged in only — it's this server's own itinerary. TRIP_STORE = TripStore.new(File.join(DATA_DIR, "trip.json")) # The trip recorded (lib/maptool/trip_log.rb): GET its state (?since=N: # the line's coordinates from N on), POST {"name"} starts it — a # Trips/ folder with the planned route and its stops — # DELETE ends it. Every fix goes in meanwhile (App.gnss_update). TRIP_LOG = TripLog.new(File.join(DATA_DIR, "trip_log"), library: LIBRARY) get "/api/trip/log" do require_login! json TRIP_LOG.status(since: params[:since]) end post "/api/trip/log" do require_login! name = JSON.parse(request.body.read)["name"].to_s trip = TRIP_STORE.get json folder: TRIP_LOG.start(name, plan: trip[:route], stops: trip[:points]) rescue JSON::ParserError halt 400, json(error: "invalid JSON") rescue ArgumentError => e halt 409, json(error: e.message) end delete "/api/trip/log" do require_login! json folder: TRIP_LOG.stop end # The recording's days (lib/maptool/trip_days.rb) — the running trip's, or # the last one's: totals, the days with what cut them, and (?track=1) the # line as [lon, lat, t] for picking a piece on the map. get "/api/trip/log/days" do require_login! rec = TRIP_LOG.recording halt 404, json(error: "no trip recorded") unless rec && rec[:points].size >= 2 points = rec[:points] days = TripDays.days(points, TripDays.cuts(points, hand: rec[:hand], joined: rec[:joined])) body = { folder: rec[:folder], active: rec[:active], started_at: rec[:started_at], totals: TripDays.stats(points).merge(days: days.size, started_at: points.first[3], ended_at: points.last[3]), days: days.map { |d| d.merge(bbox: TripDays.bbox(points[d[:from]...d[:to]])) } } body[:track] = points.map { |lon, lat, _, t| [lon.round(6), lat.round(6), t] } if params[:track] json body end # {"cut": t} or {"join": t} (epoch s; a cut with none: now). post "/api/trip/log/days" do require_login! body = JSON.parse(request.body.read) kind = body.key?("join") ? :join : :cut TRIP_LOG.mark(kind, Float(body[kind.to_s] || Time.now.to_f)) json ok: true rescue JSON::ParserError, TypeError halt 400, json(error: "invalid JSON") rescue ArgumentError => e halt 422, json(error: e.message) end # The recording as GPX: ?days=1,2 (those days), ?from=t&to=t (a piece), # neither: the whole trip — a track per day (?per_day=1: a .gpx per day in # a .zip), with ?stops=1 the trip's stops near the line, ?plan=1 the # planned route, ?pauses=1 the stands as waypoints. get "/api/trip/log/export" do require_login! rec = TRIP_LOG.recording halt 404, json(error: "no trip recorded") unless rec && rec[:points].size >= 2 points = rec[:points] days = TripDays.days(points, TripDays.cuts(points, hand: rec[:hand], joined: rec[:joined])) name = rec[:folder].to_s.delete_prefix("Trips/") label = ->(d) { "#{name} · Day #{d[:index]} · #{Time.at(d[:started_at]).strftime('%Y-%m-%d')}" } pieces = if params[:from] && params[:to] from, to = [params[:from], params[:to]].map(&:to_f).sort piece = points.select { |p| p[3].between?(from, to) } [["#{name} · #{Time.at(from).strftime('%d. %m. %H:%M')} – #{Time.at(to).strftime('%H:%M')}", piece]] else picked = params[:days].to_s.split(",").map(&:to_i) days.select { |d| picked.empty? || picked.include?(d[:index]) }.map { |d| [label.(d), points[d[:from]...d[:to]]] } end pieces = pieces.reject { |_, piece| piece.size < 2 } halt 422, json(error: "nothing to export") if pieces.empty? folder = rec[:folder] ? (LIBRARY.folder_features(rec[:folder]) rescue []) : [] extras = lambda do |piece| line = piece.map { |p| p.first(2) } out = [] out += folder.select { |f| f.dig("properties", "kind") == "route" } if params[:plan] if params[:stops] out += folder.select { |f| f.dig("geometry", "type") == "Point" && Corridor.distance_km(f["geometry"]["coordinates"], line) <= 0.3 } end out += TripDays.pauses(piece) if params[:pauses] out end if params[:per_day] && pieces.size > 1 content_type "application/zip" attachment "#{name}.zip" Zip::OutputStream.write_buffer do |zip| pieces.each do |title, piece| zip.put_next_entry("#{title.tr('/', '-')}.gpx") zip.write(TripDays.gpx([[title, piece]], extras.(piece))) end end.string else content_type "application/gpx+xml" attachment "#{pieces.size == 1 ? pieces.first.first.tr('/', '-') : name}.gpx" TripDays.gpx(pieces, extras.(pieces.flat_map(&:last))) end end get "/api/trip" do require_login! trip = TRIP_STORE.get halt 204 if params[:version] && params[:version].to_i == trip[:version] json trip end put "/api/trip" do require_login! body = JSON.parse(request.body.read, symbolize_names: true) halt 400, json(error: "points must be a list of {lngLat: [lon, lat]}") unless body[:points].is_a?(Array) && body[:points].all? { |p| p.is_a?(Hash) && p[:lngLat].is_a?(Array) } json(TRIP_STORE.update(points: body[:points], vehicle: body[:vehicle], avoid: body[:avoid], editing: body[:editing], name: body[:name], start: body[:start], day_start: body[:day_start], note: body[:note], budget: body[:budget], fuel_price: body[:fuel_price]) do |locations, vehicle, avoid| Routing.route(VALHALLA_URL, locations, Routing.vehicle(DATA_DIR, vehicle), avoid.transform_keys(&:to_s)) end) rescue JSON::ParserError halt 400, json(error: "invalid JSON") rescue ArgumentError, TypeError, KeyError halt 400, json(error: "invalid points") 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` # ({"center": [lon, lat], "minutes": [30, 60]}). Open like /api/route. post "/api/isochrone" do body = JSON.parse(request.body.read) json Routing.isochrone(VALHALLA_URL, body["center"], body["minutes"], Routing.vehicle(DATA_DIR, body["vehicle"]), body["avoid"]) 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 get "/api/vehicles" do json Routing.vehicles(DATA_DIR) end put "/api/vehicles" do require_login! json Routing.save_vehicles(DATA_DIR, JSON.parse(request.body.read)) rescue JSON::ParserError halt 400, json(error: "invalid JSON") rescue ArgumentError => e halt 400, json(error: e.message) end # Same reasoning as DELETE /api/offline-tiles above. delete "/api/terrain-tiles" do require_login! begin PmtilesBuilder.delete_terrain_data(DATA_DIR) rescue PmtilesBuilder::BuildError => e halt 409, json(error: e.message) end json ok: true end # Generated as a step inside POST /api/offline-tiles/build (see # PmtilesBuilder.extract_hiking_trails) rather than its own separate # build — it's derived from the exact same per-country .osm.pbf cache # offline.pmtiles itself already downloads, so there's nothing of its # own to trigger; DELETE /api/offline-tiles removes it too. One file # per country (not one combined file) so a viewer only ever fetches # the country they actually pick in the Hiking trails overlay's own # checklist (public/js/hiking_trails.js), not every selected country's # trails at once — `countries` lists which ones exist to build that # checklist from, `bboxes` ([w, s, e, n] each) which are in view. get "/api/hiking-trails" do countries = PmtilesBuilder.hiking_trails_countries(DATA_DIR) json countries: countries, bboxes: countries.to_h { |code| [code, PmtilesBuilder.country_bbox(code)] }.compact end # Fetched client-side only for a country the viewer actually ticks in # the Hiking trails checklist, not on page load. :code must be one # hiking_trails_countries actually lists — otherwise this would accept # an arbitrary ".."-laden path segment. get "/tiles/hiking_trails/:code.geojson" do halt 404 unless PmtilesBuilder.hiking_trails_countries(DATA_DIR).include?(params[:code]) path = PmtilesBuilder.hiking_trails_country_path(DATA_DIR, params[:code]) halt 404 unless File.exist?(path) send_file path, type: "application/geo+json" end # The search box's local half (public/js/search.js) — saved layers # (shown or not), offline hiking trails, the offline place index and # Kiwix; lat/lng (the map center) puts nearer places first. Read-only # and login-free like the tree listing: viewing needs no account. get "/api/search" do sources = params[:sources].to_s.split(",") sources = Search::SOURCES.keys if sources.empty? center = params[:lat] && params[:lng] ? [params[:lat].to_f, params[:lng].to_f] : nil json results: Search.query(params[:q], library: LIBRARY, data_dir: DATA_DIR, sources: sources, center: center, kiwix_url: KIWIX_URL) end # A link pasted into the search → a place (lib/maptool/link_place.rb). # The server fetches the page, so only for a logged-in user. get "/api/link" do require_login! place = LinkPlace.resolve(params[:url].to_s) halt 404, json(error: "no coordinates in that link or its page") unless place json place rescue LinkPlace::Error => e halt 422, json(error: e.message) end # Pinged once per page load (public/js/map.js) — url is a same-origin # path (not kiwix-serve's own address, which the browser can't reach # directly behind the reverse proxy in front of this app), proxied by # GET /kiwix/* below. get "/api/kiwix" do reachable = Kiwix.reachable?(KIWIX_URL) json available: reachable, url: (reachable ? "/kiwix" : "") end # Backs the "Wikipedia" map layer (public/js/gpx.js) — replaces the old # per-popup "Nearby on Wikipedia" link, which only ever pointed at one # POI at a time. Read-only and login-free, same as the tree/plugin # listing routes below: viewing the map needs no account, only writing # to it does. get "/api/kiwix/nearby" do halt 404 if KIWIX_URL.empty? bbox = %w[south west north east].map { |key| params[key].to_s } halt 400, json(error: "south, west, north, east are required") if bbox.any?(&:empty?) json Kiwix.nearby(KIWIX_URL, bbox.map(&:to_f)) end # Proxies kiwix-serve's own search UI and content pages through this # app instead of linking the browser to it directly (see KIWIX_URL) — # kiwix-serve is started with --urlRootLocation=/kiwix # (docker-compose.yaml), so every link/asset it emits already carries # this same /kiwix prefix and Just Works through this passthrough. GET # only: browsing a read-only ZIM archive never needs to write anything. get "/kiwix/*" do halt 404 if KIWIX_URL.empty? response = Kiwix.proxy(KIWIX_URL, "/kiwix/#{params[:splat].first}", request.query_string) halt 502 unless response content_type response["content-type"] || "application/octet-stream" status response.code.to_i body response.body end # Tracks & Points (lib/maptool/library.rb). Reading is login-free like # the rest of the map; every write needs a login. A node `key` is # "item:" or "points:" (see Library). get "/api/library/tree" do json LIBRARY.tree end # A .zip (Garmin's bulk/FIT export format) is expanded into its # .gpx/.fit/.geojson entries, each imported like its own upload. post "/api/library/import" do require_login! file = params[:file] halt 400, json(error: "file is required") unless file && file[:tempfile] begin keys = if file[:filename].to_s.downcase.end_with?(".zip") save_zip_entries(folder: params[:folder].to_s, io: file[:tempfile]) else LIBRARY.import(folder: params[:folder].to_s, filename: file[:filename], io: file[:tempfile]) end rescue Library::InvalidPath halt 400, json(error: "invalid folder") rescue Library::ParseError halt 422, json(error: "could not parse file") rescue Zip::Error halt 400, json(error: "invalid zip file") end json paths: keys, tree: LIBRARY.tree end # ?download=original sends the file the node came from, ?download=geojson # the node's GeoJSON as an attachment — both login-only, like the other # export/manage actions; plain viewing on the map isn't. get "/api/library/node/:key" do require_login! if params[:download] key = params[:key] if params[:download] == "original" path = LIBRARY.original(key) halt 404 unless path && File.file?(path) return send_file(path, filename: File.basename(path), disposition: "attachment") end begin body = LIBRARY.geojson(key) rescue Library::NotFound, Errno::ENOENT halt 404 rescue Gpx::ParseError, Fit::ParseError halt 422, json(error: "could not parse file") end name = params[:name].to_s.empty? ? "export" : File.basename(params[:name].to_s) if params[:download] == "fit" fit = fit_course(body, name) halt 422, json(error: "not a track or route") unless fit content_type "application/vnd.ant.fit" attachment "#{name}.fit" return fit end content_type :json attachment "#{name}.geojson" if params[:download] body end delete "/api/library/node/:key" do require_login! LIBRARY.delete_node(params[:key]) json tree: LIBRARY.tree rescue Library::NotFound halt 404 end # Rename/recolor a track, route or layer. patch "/api/library/node/:key" do require_login! LIBRARY.update_node(params[:key], name: params[:name], color: params[:color]) json tree: LIBRARY.tree rescue Library::InvalidValue halt 400, json(error: "invalid name or color") rescue Library::NotFound halt 404 end # A point into a track/route (body: a GeoJSON Point Feature, as for notes). post "/api/library/node/:key/points" do require_login! id = LIBRARY.add_point(params[:key], parse_feature) json id: id, tree: LIBRARY.tree rescue Library::InvalidValue halt 400, json(error: "a Point feature is required") rescue Library::NotFound halt 404 end # A migrated layer → ordinary items (Library#split_layer). post "/api/library/node/:key/split" do require_login! json paths: LIBRARY.split_layer(params[:key]), tree: LIBRARY.tree rescue Library::ParseError halt 422, json(error: "could not parse file") rescue Library::NotFound halt 404 end # The client's side of a sync (Sync): its pull (whole rows after # ?since=, an item's source file) and its push (rows, then the # source files we said we lack). get "/api/sync/changes" do require_sync_token! json LIBRARY.sync_changes(params[:since] || 0) rescue ArgumentError, TypeError halt 400, json(error: "since must be a number") end get "/api/sync/source/:id" do require_sync_token! path = LIBRARY.item_source(params[:id]) halt 404 unless path && File.file?(path) send_file path end post "/api/sync/apply" do require_sync_token! missing = LIBRARY.apply_sync(JSON.parse(request.body.read)) json missing: missing.map { |item| item["id"] } rescue JSON::ParserError, Library::InvalidValue halt 400, json(error: "bad changes") end put "/api/sync/source/:id" do require_sync_token! row = LIBRARY.source_row(params[:id]) or halt 404 # Source files never change: one already here stays. LIBRARY.store_source(row, request.body.read) unless File.exist?(LIBRARY.source_file(row["type"], row["source_path"])) json ok: true rescue Library::InvalidValue halt 400, json(error: "bad source path") end # Map data for bin/pull-maps.sh: one "sizemtimepath" line per # file, then each file by its path (Range requests resume a cut-off one). get "/api/sync/maps" do require_sync_token! content_type :text App.map_sync_files.sort.map { |rel, path| [File.size(path), File.mtime(path).to_i, rel].join("\t") }.join("\n") + "\n" end get "/api/sync/maps/file" do require_sync_token! path = App.map_sync_files[params[:path].to_s] or halt 404 # Straight through brick's nginx: buffered, it spools the response to # a temp file capped at 1 GB (proxy_max_temp_file_size) and a bigger # file's download ended there. headers "X-Accel-Buffering" => "no" send_file path end # The Sync button (a client only): pull, then push, now. post "/api/sync/run" do require_login! halt 404, json(error: "not a sync client") unless SYNC_CLIENT halt 409, json(error: "a sync is already running") unless SYNC_MUTEX.try_lock begin json SYNC_CLIENT.run rescue *Sync::NETWORK_ERRORS => e halt 502, json(error: "sync with #{SYNC_SERVER_URL} failed: #{e.message}") ensure SYNC_MUTEX.unlock end end # The sync feed (Library#changes): everything after ?since=. # Login-only, like the other exports. get "/api/library/changes" do require_login! json LIBRARY.changes(params[:since]) rescue Library::InvalidValue halt 400, json(error: "since must be a number") end # A folder (?folder=a/b, "" = top level) for an app: ?flavor=locus is # one GPX, ?flavor=osmand a zip of favourites.gpx + tracks/. get "/api/library/export" do require_login! folder = params[:folder].to_s name = folder.split("/").last || "MapTool" case params[:flavor] when "locus" content_type "application/gpx+xml" # before attachment, which doesn't know .gpx attachment "#{name}.gpx" LIBRARY.export_gpx(folder) when "osmand" files = LIBRARY.export_osmand(folder) halt 404, json(error: "nothing to export") if files.empty? content_type "application/zip" attachment "#{name}-osmand.zip" Zip::OutputStream.write_buffer do |zip| files.each do |path, gpx| zip.put_next_entry(path) zip.write(gpx) end end.string else halt 400, json(error: "flavor must be locus or osmand") end rescue Library::InvalidPath halt 400, json(error: "invalid folder") rescue Library::NotFound halt 404 end post "/api/library/move" do require_login! key = LIBRARY.move_node(params[:key].to_s, params[:to_folder].to_s) json path: key, tree: LIBRARY.tree rescue Library::InvalidPath halt 400, json(error: "invalid folder") rescue Library::NotFound halt 404 end post "/api/library/folder" do require_login! LIBRARY.create_folder(params[:path].to_s) json tree: LIBRARY.tree rescue Library::InvalidPath halt 400, json(error: "invalid path") end # Rename (`name`) and/or move (`to_folder`, "" = top level) a folder. patch "/api/library/folder/*" do require_login! path = params[:splat].first path = LIBRARY.rename_folder(path, params[:name]) if params[:name] path = LIBRARY.move_folder(path, params[:to_folder].to_s) if params.key?("to_folder") json path: path, tree: LIBRARY.tree rescue Library::InvalidPath halt 400, json(error: "invalid folder") rescue Library::InvalidValue halt 409, json(error: "a folder with that name already exists there") rescue Library::NotFound halt 404 end delete "/api/library/folder/*" do require_login! LIBRARY.delete_folder(params[:splat].first) json tree: LIBRARY.tree rescue Library::InvalidPath halt 400 rescue Library::NotFound halt 404 end # A hand-drawn point/shape (notes.js, measure.js) into a folder. post "/api/library/notes" do require_login! feature = parse_feature key = LIBRARY.add_note(feature, params[:folder].to_s) json path: key, tree: LIBRARY.tree rescue Library::InvalidPath halt 400, json(error: "invalid folder") end # Edit/delete one note from its popup: `path` is the node it's drawn # in, `id` its properties.id. put "/api/library/notes" do require_login! feature = parse_feature halt 400, json(error: "path and id are required") if params[:path].to_s.empty? || params[:id].to_s.empty? LIBRARY.update_feature(params[:path], params[:id], feature) json ok: true rescue Library::NotFound, Errno::ENOENT halt 404, json(error: "note not found") rescue GpxStore::InvalidPath halt 400, json(error: "invalid path") end delete "/api/library/notes" do require_login! halt 400, json(error: "path and id are required") if params[:path].to_s.empty? || params[:id].to_s.empty? LIBRARY.delete_feature(params[:path], params[:id]) json ok: true rescue Library::NotFound, Errno::ENOENT halt 404, json(error: "note not found") rescue GpxStore::InvalidPath halt 400, json(error: "invalid path") end # Lists whatever import plugins are on disk (see lib/maptool/plugins.rb # for the contract) — read-only, doesn't need require_login! the way # actually running one does below. get "/api/plugins" do saved = Plugins.saved_settings(PLUGIN_SETTINGS) json(Plugins.list(PLUGINS_DIRS).map { |p| p.merge("set" => (saved[p["name"]] || {}).keys) }) end # A plugin's settings (its plugin.json "settings": a login cookie, a key): # {KEY: value}, an empty value clears it. Kept in data/, never sent back. put "/api/plugins/:name/settings" do require_login! json set: Plugins.save_settings(PLUGIN_SETTINGS, PLUGINS_DIRS, params[:name], JSON.parse(request.body.read)) rescue Plugins::RunError => e halt 404, json(error: e.message) rescue JSON::ParserError halt 400, json(error: "invalid JSON") end # Runs one plugin for the given bbox (the current map viewport, from # the frontend's "Run for this area" button) and imports its GeoJSON # output into a folder of its own, named after the area's center and # the run's time — so one run's POIs stay apart from another's. # # route=1&corridor_km=N instead: along the shared trip's route, N km # either side (a plugin with "route": true covers just that; the points # further off are dropped either way), into the recorded trip's folder # when one is running. post "/api/plugins/:name/run" do require_login! timestamp = Time.now.strftime("%y%m%d_%H%M") env = Plugins.saved_settings(PLUGIN_SETTINGS)[params[:name]] || {} if params[:route] coords = TRIP_STORE.get[:route]&.dig(:geometry, :coordinates) halt 422, json(error: "the trip has no route") unless coords && coords.size >= 2 corridor = params[:corridor_km].to_f halt 400, json(error: "corridor_km must be 0.5 to 50") unless (0.5..50).cover?(corridor) geojson = Tempfile.create(["route", ".geojson"]) do |file| file.write(JSON.generate(type: "LineString", coordinates: coords)) file.flush Plugins.run(PLUGINS_DIRS, params[:name], Corridor.bbox(coords, corridor), route: file.path, corridor_km: corridor, env: env) end geojson["features"] = geojson["features"].select do |f| f.dig("geometry", "type") != "Point" || Corridor.distance_km(f["geometry"]["coordinates"], coords) <= corridor end name = "#{params[:name]} along the route #{format('%g', corridor)} km #{timestamp}" folder = TRIP_LOG.status[:folder] || name else bbox = %w[south west north east].map { |key| params[key].to_s } halt 400, json(error: "south, west, north, east are required") if bbox.any?(&:empty?) south, west, north, east = bbox.map(&:to_f) geojson = Plugins.run(PLUGINS_DIRS, params[:name], [south, west, north, east], env: env) center_lat = format("%.2f", (south + north) / 2) center_lon = format("%.2f", (west + east) / 2) folder = name = "#{params[:name]}_#{center_lat}_#{center_lon}_#{timestamp}" end keys = LIBRARY.import(folder: folder, filename: "#{name}.geojson", io: StringIO.new(JSON.generate(geojson))) json path: keys.first, tree: LIBRARY.tree, count: geojson["features"].size rescue Plugins::RunError => e halt 502, json(error: e.message) end # Called by the Apps Script watching Gmail for Garmin LiveTrack emails — # it only extracts and forwards the session id/token, nothing else. post "/api/livetrack/session" do halt 403 if LIVETRACK_WEBHOOK_SECRET.empty? || params[:secret] != LIVETRACK_WEBHOOK_SECRET session_id = params[:session_id].to_s.strip session_token = params[:session_token].to_s.strip halt 400, json(error: "session_id is required") if session_id.empty? LIVETRACK_STORE.add(session_id, session_token) json ok: true end get "/api/livetrack/sessions" do json sessions: LIVETRACK_STORE.list end # Garmin stops serving a session's live-track page some while after the # activity ends (its own session/token URL, not the API — see # LiveTrackClient) — the exact cutoff isn't documented, ~24h is what's # been observed. Ended sessions old enough to likely be past that are # verified once at startup (LiveTrackStore#stale_ended already skips # ones already flagged, so this doesn't re-hit Garmin for the same # dead session on every restart), so the panel can grey them out up # front instead of only failing after a user clicks one and waits on # a fetch. LIVETRACK_MAP_STALE_AFTER = 24 * 60 * 60 # seconds Thread.new do LIVETRACK_STORE.stale_ended(LIVETRACK_MAP_STALE_AFTER).each do |session| LiveTrackClient.fetch(session["id"], session["token"]) rescue LiveTrackClient::FetchError LIVETRACK_STORE.mark_unavailable(session["id"]) end end # Garmin's own API (livetrack.garmin.com/api/v2/...) 403s a plain server # request no matter what headers it gets — see LiveTrackClient — so this # fetches the session page itself and pulls the track out of that. get "/api/livetrack/sessions/:id/track" do session = LIVETRACK_STORE.find(params[:id]) halt 404, json(error: "unknown session") unless session halt 404, json(error: "session has no token") if session["token"].to_s.empty? begin result = LiveTrackClient.fetch(session["id"], session["token"]) rescue LiveTrackClient::FetchError => e halt 502, json(error: "could not fetch track: #{e.message}") end summary = LiveTrackClient.summarize(result) LIVETRACK_STORE.set_summary(session["id"], summary) points = result.points coordinates = points.filter_map { |p| p.dig("position", "lon") && p.dig("position", "lat") && [p["position"]["lon"], p["position"]["lat"]] } halt 502, json(error: "track has no positions") if coordinates.empty? last = points.last features = [ { type: "Feature", geometry: { type: "LineString", coordinates: coordinates }, properties: { "kind" => "actual" } }, { type: "Feature", geometry: { type: "Point", coordinates: coordinates.last }, # Merges the session summary in too — the point layer's hover # popup (public/js/livetrack.js) reads it straight off here # rather than needing a second fetch against /sessions. properties: summary.merge( "time" => last["dateTime"], "speed_meters_per_sec" => last["speedMetersPerSec"], "heart_rate_beats_per_min" => last["heartRateBeatsPerMin"] ), }, ] # Only present when the activity was started from a saved Garmin # course (see LiveTrackClient#fetch) — plotted separately from the # actual track ("kind" distinguishes the two LineStrings) since it's # the planned route, not where the person has actually been. course_coordinates = result.course&.[]("geoPoints")&.filter_map { |p| p.dig("position", "lon") && p.dig("position", "lat") && [p["position"]["lon"], p["position"]["lat"]] } if course_coordinates&.any? features << { type: "Feature", geometry: { type: "LineString", coordinates: course_coordinates }, properties: { "kind" => "planned", "name" => result.course["name"] }, } end json(type: "FeatureCollection", features: features) end # NPS park maps (the "NPS park maps" overlay, public/js/nps.js): Harpers # Ferry Center brochure maps, public domain. data/nps/ holds nps.json (the # index: parks with bboxes, maps with download links and, for the 289 # georeferenced ones, overlay corners) plus overlay/ (JPEGs), geotiff/ and # pdf/ — built outside this app by ~/Projects/NPS_Maps/nps-maps.py. Absent # = the overlay stays disabled. NPS_DIR = File.join(DATA_DIR, "nps") get "/api/nps" do path = File.join(NPS_DIR, "nps.json") halt 404, json(error: "no NPS data") unless File.exist?(path) cache_control :public, max_age: 3600 send_file path, type: "application/json" end get %r{/nps/(overlay|geotiff|pdf)/([\w.@-]+)} do |kind, name| path = File.join(NPS_DIR, kind, name) halt 404 unless File.file?(path) cache_control :public, max_age: 86_400 send_file path, disposition: kind == "geotiff" ? "attachment" : "inline" end # What the CAN bus last said: per interface (up, frames, error), per # CANopen node (heartbeat state, last seen) and each configured signal. get "/api/can" do require_login! snapshot = CAN_STORE.snapshot(since: params[:since]&.to_i) units = CAN_DECODER ? CAN_DECODER.units : {} snapshot[:signals] = snapshot[:signals].to_h { |name, signal| [name, units[name] ? signal.merge(unit: units[name]) : signal] } # simulated: the GNSS simulation (/sim.html) stands in for gnss.* actions = CAN_ACTIONS.map { |a| { name: a.name, node: a.node } } # time: whether maptool sends CANopen TIME (off while another node does) time = CAN_TIME && { sending: !CAN_TIME.others? } json snapshot.merge(available: !CAN_CONFIG.nil?, simulated: GNSS_SIM.running?, actions: actions, time: time) end # The keypads (can.json's "keypads") for drive mode: which are on the bus # (their heartbeat; with LEDs or not) and the events on their channels # after seq :since — a long poll, answered as soon as one comes (10 s at # most). ponytail: holds one of Puma's threads per drive-mode screen, # fine for the one or two in the car. get "/api/keypad" do require_login! halt 404, json(error: "no keypads in data/can.json") unless KEYPAD since = params[:since] && Integer(params[:since], exception: false) present = App.keypads_present answer = KEYPAD.events(present.empty? ? nil : since) json answer.merge(present: present.map { |d| { name: d.name, leds: d.protocol == "pkp" } }) end # The screen's colours for a keypad's key LEDs: { "keypad": "pad", "on": # { "K1": "cyan", … }, "blink": { … } } (Keypad::COLORS); the keys bound # to outputs come on top, the 100 ms tick sends them (App.keypad_leds_frames). put "/api/keypad/leds" do require_login! halt 404, json(error: "no keypads in data/can.json") unless KEYPAD body = JSON.parse(request.body.read) begin KEYPAD.led_frames(body["keypad"].to_s, body["on"], body["blink"]) # checks the names and colours rescue ArgumentError => e halt 400, json(error: e.message) end KEYPAD_SCREEN_LEDS[body["keypad"].to_s] = { "on" => body["on"] || {}, "blink" => body["blink"] || {} } json ok: true end # The bindings and what they can bind (/keypad.html, drive mode): the # keypads' channels, the outputs, the colours; saved: this car's own # (PUT {bindings}), else the profile's (DELETE goes back to them). get "/api/keypad/bindings" do require_login! keypads = (KEYPAD&.devices || []).map do |d| keys = d.protocol == "pkp" ? (1..d.keys).map { |k| "K#{k}" } : [] { name: d.name, protocol: d.protocol, node: d.node, channels: (keys + d.inputs.keys).uniq } end outputs = (OUTPUTS&.snapshot || []).flat_map { |m| m[:channels].map { |c| { output: "#{m[:name]}.#{c[:n]}", label: c[:label] } } } json bindings: App.bindings, saved: File.exist?(BINDINGS_PATH), keypads: keypads, outputs: outputs, modes: Outputs::MODES, colors: Keypad::COLORS.keys - ["off"] end put "/api/keypad/bindings" do require_login! begin list = App.check_bindings(JSON.parse(request.body.read)["bindings"]) rescue ArgumentError, JSON::ParserError => e halt 400, json(error: e.message) end FileUtils.mkdir_p(File.dirname(BINDINGS_PATH)) File.write("#{BINDINGS_PATH}.tmp", JSON.pretty_generate(bindings: list)) File.rename("#{BINDINGS_PATH}.tmp", BINDINGS_PATH) json bindings: App.bindings, saved: true end delete "/api/keypad/bindings" do require_login! FileUtils.rm_f(BINDINGS_PATH) json bindings: App.bindings, saved: false end # The outputs (can.json's "outputs"): each module's channels, their # labels and state, which bindings drive them. get "/api/outputs" do require_login! halt 404, json(error: "no outputs in data/can.json") unless OUTPUTS bound = App.bindings.select { |b| b["output"] } json modules: OUTPUTS.snapshot, bindings: bound end # Switches an output by hand (a tile on the screen, /sim.html): # { "on": true | false }, or {} to toggle. post "/api/outputs/:module/:n" do require_login! halt 404, json(error: "no outputs in data/can.json") unless OUTPUTS output = "#{params[:module]}.#{params[:n]}" halt 404, json(error: "no output #{output}") unless OUTPUTS.find(output) body = request.body.read on = body.empty? ? nil : JSON.parse(body)["on"] OUTPUTS.set(output, on.nil? ? !OUTPUTS.on?(output) : !!on) json on: OUTPUTS.on?(output) end # Runs can.json's action number :n (its place in GET /api/can's actions). post "/api/can/actions/:n" do require_login! halt 409, json(error: "CAN is off: no data/can.json on this server") unless CAN_CONFIG action = CAN_ACTIONS[Integer(params[:n], exception: false) || -1] or halt 404 transport = Can::Sdo::SocketTransport.new(CAN_CONFIG.fetch("interfaces").first) begin action.run(Can::Sdo.new(transport)) rescue Can::Sdo::Error => e halt 502, json(error: e.message) ensure transport.close end json ok: true end # Recording the bus into MF4 files on the server: GET whether it runs and # the files (newest first), POST starts it, DELETE stops it (the segment # being recorded is written); a file by GET /api/can/recordings/. get "/api/can/recording" do require_login! json available: !CAN_CONFIG.nil?, running: CAN_RECORDER.running?, started_at: CAN_RECORDER.started_at, error: CAN_RECORDER.error, files: CAN_RECORDER.files end post "/api/can/recording" do require_login! halt 409, json(error: "CAN is off: no data/can.json on this server") unless CAN_CONFIG begin CAN_RECORDER.start rescue SystemCallError => e halt 500, json(error: CAN_RECORDER.error || e.message) end json running: CAN_RECORDER.running? end delete "/api/can/recording" do require_login! CAN_RECORDER.stop json running: CAN_RECORDER.running?, error: CAN_RECORDER.error end get "/api/can/recordings/:name" do require_login! path = CAN_RECORDER.path(params[:name]) or halt 404 send_file path, disposition: "attachment", type: "application/octet-stream" end # The GNSS simulation: POST {"start": [lon, lat]} drives randomly from # there, POST {} from a random place in the offline countries, 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, 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 require_login! body = JSON.parse(request.body.read) lon, lat = body["start"] # {"trip": true}: along the shared trip's route (to try the navigation) route = TRIP_STORE.get[:route] if body["trip"] halt 422, json(error: "the trip has no route") if body["trip"] && !route # {"track": "item:"}: a library track replayed at its own speed if body["track"] begin line = JSON.parse(LIBRARY.geojson(body["track"].to_s))["features"].find { |f| f.dig("geometry", "type") == "LineString" } rescue Library::NotFound halt 404, json(error: "no such track") end track = line&.dig("properties", "profile")&.filter_map { |p| [p["lon"], p["lat"], p["elapsed_secs"]] if p["elapsed_secs"] } halt 422, json(error: "the track has no times") if track.nil? || track.size < 2 end if route || track then nil elsif lon.nil? codes = (PmtilesBuilder.offline_meta(DATA_DIR) || {}).fetch("sources", []).map { |source| source["code"] } bboxes = codes.filter_map { |code| PmtilesBuilder.country_bbox(code) } halt 422, json(error: "no offline countries to start in") if bboxes.empty? elsif !lon.is_a?(Numeric) || !lat.is_a?(Numeric) halt 400, json(error: "start must be [lon, lat]") end CAN_STORE.override_prefix = "gnss." GNSS_SIM.start(lon, lat, bboxes: bboxes, route: route, track: track) do |fix| CAN_STORE.put(fix.except(:time).transform_keys { |key| "gnss.#{key}" }) App.gnss_update(fix) 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 require_login! json LIVE_STORE.snapshot.merge(available: !MQTT_URL.empty?) end # The tracker's name, icon, color, trail logging and trail length. put "/api/live/settings" do require_login! 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! json App.gnss_position end end end