Compare commits

...
191 Commits
Author SHA1 Message Date
randy 5998fdfe88 park4night's login: Firefox's session store (there's no remember me), kept alive every 15 min; the plugin and its timer now in home-gitops
CI / deploy (push) Successful in 18s
CI / check (push) Successful in 23s
2026-12-05 17:14:51 +01:00
randy 462303eed6 Docs and TODO after the MilCAN / NGVA notes (docs/design.adoc "What the military vehicles do"): Silent Watch, Blackout of our own devices, a hardware interlock; the Pi on 12 V only behind a HAT with an STM32C5 (power supervisor, watchdog, the Pi's CAN, 5.1 V / 5 A); the outputs' controller moves to that STM32C5 ("The controller on the Pi's HAT": requests from keypads, mcu-lvgl and maptool, Zephyr, 16 MB flash for MCUboot and a black box; native_sim on SocketCAN first). TODO: can.json curves, multiplexing and warning limits after candinista; the mcu-lvgl panel in the Garmin style; TPMS off the car's CAN; Android Auto with the Pi as the phone (AOA over USB-OTG); a universal STM32C5 board v1 with TCAN1043 2026-12-05 16:03:02 +01:00
randy cba14300b5 Driving declutter by a ["pitch"] in the layers' filters (MapLibre 6.21): route numbers and minor roads' / paths' names go already while tilting past 30°, no pitchend listener, no re-apply on style.load
CI / deploy (push) Successful in 17s
CI / check (push) Successful in 25s
2026-12-05 14:36:11 +01:00
randy f85785c61d Update dependency maplibre-gl to v6.21.0
CI / deploy (push) Successful in 17s
CI / check (push) Successful in 23s
2026-12-05 14:14:40 +01:00
randy 59f64f2f97 Update dependency rexml to v3.4.5
CI / check (pull_request) Successful in 27s
CI / deploy (pull_request) Skipped
CI / deploy (push) Successful in 38s
CI / check (push) Successful in 27s
2026-12-05 13:12:33 +00:00
randy 88fa2d27a3 Switches in drive mode, after the Design canvas' GridSwitches: Menu → Switches (only when /api/outputs answers), 3×3 tiles per page with the output's name, On / Off / Flashing / level, the key and mode driving it and its LED colour line, a group per module, All off, More ▸, a tap toggles. The status pill above the car (pypilot's note in SidePanel): ● REC while the trip is recorded, estimated / no fix, hidden when all is well
CI / deploy (push) Successful in 18s
CI / check (push) Successful in 23s
2026-12-04 21:45:04 +01:00
randy 82a728e024 Outputs: positions (a key steps off → a → b → off, a knob up and down, the last off before the next on), strobe (a period) and dimmer (a knob's level by a step; a dimmable module gets a byte per channel, a relay just switches); in /keypad.html and /sim.html, a key's LED on while a position is chosen or a strobe runs
CI / deploy (push) Successful in 17s
CI / check (push) Successful in 23s
2026-12-04 18:50:37 +01:00
randy e82b2236b5 Keypad bindings in the UI (/keypad.html, after the Design canvas' GridBinding): the keypads drawn as can.json has them, a key or knob picked by a tap or by pressing it, what it drives (a screen action or an output), the output's mode, what it does in an open menu, its LEDs; saved per car in data/drive/bindings.json over the profile's (GET/PUT/DELETE /api/keypad/bindings, checked on the way in), drive mode takes them when it loads
CI / deploy (push) Successful in 18s
CI / check (push) Successful in 23s
2026-12-04 17:25:03 +01:00
randy d6af65f4ef Keypads: the XIAO's knobs by their discovered names (mcu-stm32-xiao-c5.encoder_1, encoder_button_1), the action that sets them turning freely (entity 7, REAL32 at 0x2072)
CI / deploy (push) Successful in 18s
CI / check (push) Successful in 22s
2026-12-04 16:16:15 +01:00
randy 38fb06853e Keypads as channels and bindings, the PDMs' way (lib/maptool/keypad.rb): can.json's keypads (a Blink Marine PKP by its protocol, or any signals as inputs) give channels pad.K1, pad.E3, pad.E3 press; the drive profile's bindings give each a screen action, a knob action (zoom, pan, rows), another in an open menu and its LED colour, sent back to the PKP. Outputs (lib/maptool/outputs.rb): relay modules (simulated, no current measured), a binding's output with toggle/on/off/hold/pulse, hold off when the keypad goes silent, the state re-sent every 100 ms; /sim.html switches them by hand. CANopen TIME from maptool while no other node sends it (lib/maptool/can_time.rb), shown in /can.html
CI / deploy (push) Successful in 17s
CI / check (push) Successful in 23s
2026-12-04 16:14:39 +01:00
randy bf90f4cf23 Rounded, after the Design canvas' GridRounded: drive mode's cells and keys with 12 px corners on a black ground, the gaps (3 px a side) out of them, the map keeping its area with corners of its own; the map's points one frame, the NPS rounded square — the trip's stops, the search pins, the clusters and the points with no pictogram (badges like the p4n/OsmAnd ones) instead of circles
CI / deploy (push) Successful in 17s
CI / check (push) Successful in 23s
2026-12-04 14:28:32 +01:00
randy 87d7bd2463 Planning (the Design canvas' Plan and GridToday, ideas from azedler/roadplanner): a stop's type as its NPS pictogram (marker and list), notes on the trip, its days and stops, + on a leg inserts the next point there; a parking spot per stop (P marker, the route goes there, the walk shown); a link pasted into the search becomes a place (/api/link: the URL's coordinates, else the page's geo meta / JSON-LD / a map link; public addresses only, logged in), added on the leg it lengthens least; avoids for the trip (+ ferries, unpaved) or a day (routed in pieces, joined); Check and Costs folds in the Route panel (no leave time, long days, arriving after sunset, long walks, missing vignettes; fuel from km × consumption × price, stop costs / paid, the budget); Today in drive mode's Menu (stops left, tonight, sunset, Open-Meteo weather, the day's notes, Skip next, Tomorrow). Plugins along the trip's route (Maptool::Corridor, a corridor width; Overpass around:) and plugin settings saved server-side; p4n via a host Firefox's cookies (docs/deployment.adoc). The recording's days (cut where the car stood ≥ 4 h, or by hand) and their export (days, a piece A–B, the whole trip; GPX with times). Track replay in the GNSS simulator. Step advance 5 m past a maneuver. The level gauge (drive mode, from Terrain): lift per wheel to the ramps' steps from roll, pitch, wheelbase and track
CI / deploy (push) Successful in 18s
CI / check (push) Successful in 23s
2026-12-03 23:34:25 +01:00
randy 5e31dfaba9 Profiles in a dialog, the chip in the map's bottom-left corner picks one (the Design canvas' Vehicle): a car gains fuel, Euro class, stickers and vignettes / toll units with dates; drive mode's Menu steps through them. Speed limits by country for cars and over 3.5 t (public/js/speed_limits.js, sources in it): the route's roads (km, road class, country), the limit shown the lower of the sign and the profile's; the Route panel's countries with their limits and how the motorways are paid; past a border a card in drive mode (GridBorder). The itinerary in the Route panel (Itinerary): the trip's name, leave time, days start; per stop a night, stay and note, planned times, day headers; another screen's change shown where it happened with Undo
CI / deploy (push) Successful in 17s
CI / check (push) Successful in 24s
2026-12-03 19:00:09 +01:00
randy a6158f4083 Navigation: arrived 30 m from the end (banner, drive mode), navigating on past it (the reroute turns back); the next maneuver's lanes from 1 km or 45 s at the speed driven, in drive mode a cell under the maneuver over the map ("ahead" in the profile, shown only with something in it) with the next traffic signal; signals with no route: /api/road also routes 1.5 km straight on from the last fix and gives that way's signals, the nearest one in front shown. TODO: the CAN GNSS follow done (the LTE tracker a layer to switch on), any tracker point followable later
CI / deploy (push) Successful in 17s
CI / check (push) Successful in 1m22s
2026-12-03 17:57:27 +01:00
randy ad975bcf62 What's here on a right click / long press / Alt+click (the Design canvas' Desktop): the position on top (a click copies it, with the DMS and the ground's height), Route here / Add to the trip / Save a point, the features' raw properties folded under it; C copies the position under the mouse. Voice prompts while navigating (speechSynthesis, Valhalla's verbal alert and pre-transition instructions, ~25 s and ~7 s ahead), on/off in drive mode's Menu, off by default. TODO: the touch items closed (the Pad7 is fine as it is)
CI / deploy (push) Successful in 17s
CI / check (push) Successful in 25s
2026-12-03 17:44:27 +01:00
randy f15fbef746 Drive: the limit as a round sign at the speed field's end (the next one under it), the speed red past it; the Limit cell gone, Speed over 4 cells, and no surface in its place (the terrain panel's head has it). Terrain view in the Menu: opens and closes by itself / opens and stays / by hand; simulated, the tilt doesn't open it (the DEM's slope on a hillside road is the hill's). Desktop: the sun times in the status bar (the chart opens over it), the night button out of the top bar — On the map's Theme row and drive mode still cycle it
CI / deploy (push) Successful in 17s
CI / check (push) Successful in 25s
2026-12-03 14:21:07 +01:00
randy f981b80599 Terrain closes by itself again: the road's surface only off the route (back on it the last road's stayed, so the view never closed); while it's open the top row's Limit shows the surface. Navigated, the planned route behind the car thin and dashed under the trip log's track (the line and its casing clear there). The scale back over the map, bottom left. CAN recordings older than CAN_REC_KEEP_HOURS (24 by default, 0 keeps all) deleted when listed and every segment while recording. TODO tidied
CI / deploy (push) Successful in 2m41s
CI / check (push) Successful in 23s
2026-12-03 13:52:13 +01:00
randy 21ad6c0c21 Terrain: the cars redrawn (a rear view on its tyres with the back window, a side view on two round wheels with two windows, the wheels apart from the body); every row of the panel a cell as on the artboard, what a bigger screen adds goes to a blank row above the buttons instead of stretching the fields and the elevation; the dials' data-key renamed data-dial (the keys took it for a binding and drew an empty label)
CI / deploy (push) Successful in 18s
CI / check (push) Successful in 22s
2026-12-03 12:40:11 +01:00
randy 1ee79fff66 Drive keys (canvas GridKeys): a screen key's "key" in the profile clicks it (F1 F2 F3 / F5 − + 3 F T N; "keypad" K1–K8 / E3 kept for the keypad), the menus' own buttons too (1 2 3 the scopes / presets, H hide all / all off); in an open menu ↑ ↓ move the row (the keypad's encoder will send the same arrows), Enter its first button, Space its eye, + adds it, ⌫ up a folder, Esc closes. The key in each button's corner and the row in purple with ⏎ ␣ +, from the first key pressed on (a touch-only screen stays clean)
CI / deploy (push) Successful in 18s
CI / check (push) Successful in 23s
2026-12-03 12:27:45 +01:00
randy d39e3b5edd Drive on other screens (field test on a 26″): the cells at most the profile's 80 px, on a bigger screen only the map's columns and rows stretch (the right column, the menus and the map keys stay cell-sized, a list shows more rows), on a smaller one everything — cells, type, icons — scaled by one factor so a 7″ keeps the same elements; a menu now lies over the cells of the area it opens in (Next stop and the rest covered Terrain), the dials sized by the cell; the simulation's roll and pitch always from the terrain under it, not the IMU of the car standing at home; the dashboard's card over the map hidden while driving (Terrain instead)
CI / deploy (push) Successful in 17s
CI / check (push) Successful in 27s
2026-12-03 11:04:45 +01:00
randy f73badd107 Drive as the Design canvas' Grid: the page as 16 × 10 cells from a screen profile (public/drive/road.json, {area, widget, …} per cell, to be edited in the app later), the map 13 × 8 with nothing over it; the manoeuvre, speed, limit, altitude, time, sun, status (online, rec), next stop with km / ETA to it and to the end, the route's elevation of the next 10 km, a compass; keys Trip, Points, Layers, Search, Menu, − + 3D Follow, Terrain, day/dusk/night. A menu opens in the right 7 × 8 as cells of its own and the map narrows to 9 × 8 (drive_menus.js): Trip and Search as GridTrip / GridSearch (a stop a row, ✓ ↑ ↓ ✕ a cell each; results with their pins on the map); Points as GridPoints (the library nearest the car — /api/search with no words and a center lists every saved feature nearest first — along the route ahead, shown, or one folder at a time; an eye per row, + a point as a stop); Layers as GridLayers (the On the map panel's own switches and Online | Offline, presets Road / Off-road / Overnight, + Keep); Terrain as GridTerrain (roll / pitch dials with the max held, climb and side slope ahead from the DEM, the next 2 km, Level here = can.json's levelling action in two taps), on by itself on an unpaved surface (/api/road now gives Valhalla's surface) or past 10° for 10 s, back after 2 km of paved road, automatic / by hand in the Menu. The dashboard polls for the grid without its overlay; the old drive bar and floating buttons gone
CI / deploy (push) Successful in 17s
CI / check (push) Successful in 23s
2026-12-03 10:47:40 +01:00
randy 285af64a65 On the map: the toggles plain checkboxes again (16 px, at the row's end), not circles that read as radio buttons; rows, names and section gaps smaller
CI / deploy (push) Successful in 18s
CI / check (push) Successful in 28s
2026-12-03 10:02:35 +01:00
randy 91fa9cec41 Library as on the artboard (after Locus Map), renamed from Tracks & Points: find on top (text, kind chips with counts, shown on the map only, Folders | List), one folder level at a time with ← up and the path (the up button takes a dragged item a level up), folders first, an eye per row (● shown, ◐ some of a folder, ○ none; a folder's eye shows or hides everything in it), a track's points open from its ›; while searching or in List every match flat with its folder; totals and Hide all at the foot; uploads, new folders and drops on blank space go to the folder open. The elevation profile docked under the map: the map gives up its height; a route shows its own profile once the terrain is sampled (not while driving) and hides it when cleared
CI / deploy (push) Successful in 18s
CI / check (push) Successful in 22s
2026-12-03 09:39:19 +01:00
randy fc8564fe3b On the map as on the artboard: section titles as small caps on white (no gray bands), compact rows with a bold name, the on/off as the eye at the row's end (● on, ○ off) instead of a checkbox at its start; the map as one row with an Online | Offline switch, a Theme row (the topbar's night cycle), the legend as a row. The map's buttons in the artboard's three cards (zoom; compass, north lock, 3D, my position; measure, note, home). Topbar: the offline state as a pill (Offline ready / Online only), Drive filled. Status bar: the ground's height under the cursor once the mouse rests
CI / deploy (push) Successful in 17s
CI / check (push) Successful in 22s
2026-12-03 09:34:16 +01:00
randy d559f76b4a Desktop after the artboard, the panels too: the rail dark like the topbar (the open panel's item on a lighter band with an accent edge), side panels 400 px, the map's buttons as white cards of 40 px; Route laid out as drawn — Reverse/Clear in the head, each point with a grip to drag it elsewhere, its letter (the same on the marker), name and role, the leg to it as a dashed line between, + Search / Saved point / My position chips, the totals as a card (distance, time, climb, arrival; descent and steepest grade under it), vehicle and avoid as chips, Directions and Reach folded with their counts, Save to library and Elevation profile at the bottom; On the map: the Online/Offline choice and the legend are the first group of the Overlays panel, renamed On the map — no Base map item or panel of its own. TODO: copy the cursor's position, the scale back over the map
CI / deploy (push) Successful in 17s
CI / check (push) Successful in 24s
2026-12-03 09:20:27 +01:00
randy 258d35a7a1 Follow zoom closer in town (z18 up to 20 km/h, 15.5 at 120+, the first step z17); TODO: driver's and co-driver's views by whether Android Auto is connected
CI / deploy (push) Successful in 18s
CI / check (push) Successful in 22s
2026-12-03 01:29:12 +01:00
randy f161243c61 design.adoc: screen profiles (road / terrain / planning, every grid field configurable, the terrain view switching itself on off-road or past 10° and back, menu: automatic / by hand) and switches and the keypad — how Garmin PowerSwitch, OnDeck, MaxxECU, ECUMaster PMU do it, maptool as the controller (bindings per profile, modes, the LED colour line under a key, fail-safe), the interim keypad's 8 keys and 8 encoders 2026-12-03 01:29:12 +01:00
randy 97d1bda09c CAN actions: can.json's "actions" ({name, node, index, subindex, data: 1–4 bytes hex}) are SDO expedited downloads, a button beside their node on /can.html (confirm first, the result in the status line) — POST /api/can/actions/:n (login, 409 with no config, 404 unknown, 502 on an SDO error), GET /api/can lists them; first one: Level IMU on node 0x21 (0x2022:1 ← 01) 2026-12-03 01:29:12 +01:00
randy 0a5548cd8f Desktop redesign after the Design canvas' Desktop artboard: search is one field in the topbar (places, the library, coordinates; / focuses it, sources and results drop down under it), the side rail is labelled (Map, Overlays, Library, Import | Route, Offline | GNSS, Live, Status at the bottom), the map's buttons in one column on the right (zoom and compass, north lock, 3D, my position, measure, note, home; measure/note panels open to the left), a status bar under the map (center coordinates to copy, the point under the mouse, zoom, scale, revision) instead of the zoom-level control, the scale on the map and the coordinates in the topbar; the base map button on the map dropped (the rail has it). Route panel reordered: points with their legs, adding one, the totals as a card, vehicle and avoid, directions and reach folded, reverse/clear/save last. Drive unchanged: the search, the status bar and the right column hide there
CI / check (push) Successful in 23s
CI / deploy (push) Successful in 17s
2026-12-03 01:28:49 +01:00
randy 60d7c825fc CAN bus recorded on the server into ASAM MDF4: can-recorder (Rust, can-recorder/) reads every interface's SocketCAN frames with the kernel's timestamp and writes a finished .mf4 every 5 min (data/can_rec/<UTC start>.mf4, .part then renamed: a power cut loses at most the last segment), its own minimal MDF 4.10 writer in the CANedge CAN_DataFrame layout (mdf4-rs's lacks the bus-event flags and components: asammdf couldn't DBC-decode it) — checked in asammdf 8.8.35 against candump, every frame, < 0.002 ms, DBC decoding works; lib/maptool/can_recorder.rb starts and stops it, GET/POST/DELETE /api/can/recording, the files by GET /api/can/recordings/<name>; /trace.html's 'Recording on the server (MF4)'; built in its own Dockerfile stage (rust:1.100-slim-trixie)
CI / deploy (push) Successful in 1m37s
CI / check (push) Successful in 23s
2026-12-02 19:35:54 +01:00
randy 712c6bf7ad CAN trace on its own debug tab (/trace.html), off the CAN analyzer: records between Start and Stop only (polled every 0.5 s, the server keeps the last 5000 frames, lost ones counted, stops at 20000), the newest on top; sorted by any column, filtered by text (a, b = either), frame type, interface, node and only changes; Δ per ID; 1000 rows drawn, the filter and sort over all; export as candump .log (can-utils, SavvyCAN, python-can) or the shown rows decoded as CSV; SDO objects named by esphome-canopen's EDS (public/can/esphome.eds, from can2mqtt) and its entity objects 2026-12-02 19:05:07 +01:00
randy b1a5d47859 design.adoc: layout as a grid, not floating panels — ECDIS, marine plotter, Garmin data fields, OpenCPN Dashboard; 16×10 cells of 80 px on the navigator's 1280×800 (mockups: the Design canvas, Grid/GridTrip/GridSearch)
CI / deploy (push) Successful in 18s
CI / check (push) Successful in 23s
2026-12-02 18:24:47 +01:00
randy 7204355510 Dead reckoning in a tunnel: 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 car's CAN speed (vehicle.speed) when there is one, the average speed of the last ~20 s otherwise, up to 10 min (App.gnss_position, TripStore.ahead) 2026-12-02 18:24:47 +01:00
randy 7fdc0114e6 Debug pages switch between each other: one tab bar on top of /status.html, /can.html and /sim.html (views/_debug_nav.erb). CAN analyzer: a trace of every frame as it came (the server keeps the last 1000, GET /api/can?since=<seq> gives the new ones), each byte colored by what it is and decoded by its CANopen role — SDO command, index:subindex, expedited payload, segments, abort codes, byte 0 in bits; NMT, heartbeat, EMCY, SYNC, PDOs; who sent it, Δ ms, pause, clear, the frame filter
CI / deploy (push) Successful in 17s
CI / check (push) Successful in 22s
2026-12-02 18:22:16 +01:00
randy 7901d75ff1 Drive mode: the Trip menu beside the map instead of over it (like Android Auto's side panel): the map narrower and keeping its buttons, its center (follow, the crosshair, the overview) in what's seen — the car was hidden under the panel before
CI / deploy (push) Successful in 17s
CI / check (push) Successful in 23s
2026-12-02 18:21:14 +01:00
randy 3325ff5d17 Update dependency onthegomap/planetiler to v0.11.1
CI / check (pull_request) Successful in 23s
CI / deploy (pull_request) Skipped
CI / deploy (push) Successful in 47s
CI / check (push) Successful in 23s
2026-12-02 15:16:17 +00:00
randy c101c7441f Update dependency onthegomap/planetiler to v0.11.0
CI / deploy (push) Successful in 3m0s
CI / check (push) Successful in 25s
2026-12-01 19:42:10 +01:00
randy 27b77790c4 Update dependency puma to v8.1.4
CI / check (pull_request) Successful in 32s
CI / deploy (pull_request) Skipped
CI / deploy (push) Successful in 38s
CI / check (push) Successful in 31s
2026-12-01 18:38:13 +00:00
randy bd689faa93 Trip log crash-safe like a FIT: an append-only journal per trip (data/trip_log/<started>.ndjson, fsynced every 5 s, a torn last line skipped and the next one on a line of its own), a restart picks the running trip up from it into the same track, no state file to corrupt; the library's track built from it every 5 min and at the end. Drive mode: a pinned side panel's room goes back to the map
CI / deploy (push) Successful in 17s
CI / check (push) Successful in 43s
2026-12-01 10:14:57 +01:00
randy 0c809b3e2b 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
CI / check (push) Successful in 21s
CI / deploy (push) Successful in 17s
2026-12-01 02:31:31 +01:00
randy 7d72e9eb63 Trip log: a trip is a library folder (Trips/<date> <name>) with the planned route and its stops; the car's GNSS recorded into its track there (10 m steps, written every minute and at the end), GET/POST/DELETE /api/trip/log; the Trip menu's Start / End and the line really driven (--route-driven); along-route POI mode for the plugins in TODO
CI / deploy (push) Successful in 17s
CI / check (push) Successful in 21s
2026-12-01 02:25:20 +01:00
randy 809e88ab1a Driving menu Trip: the stops as big rows (look, ✓ passed, ↑ ↓, ✕), a stop at the crosshair, the start at the car, search of saved points and offline places; each leg's km and time (legs_s) and the total, in the route panel too; passed stops kept (not routed, dimmed, editable) — a reroute marks them instead of dropping them; /status.html: every status endpoint full width (the debug panel links it); the trip-as-plan-and-log model and planned-vs-driven colors in docs/TODO
CI / deploy (push) Successful in 17s
CI / check (push) Successful in 22s
2026-12-01 02:21:14 +01:00
randy 0eb9d05cdc Driving bar after the research: four 76 px buttons (zoom ±, 2D/3D, route overview), one Follow button bottom left shown only while the map isn't following, night and exit off the bar; research on day/night and on driving buttons (Garmin aviation/marine/zūmo, ships' ECDIS/S-Mode, Android Auto) in docs/design.adoc, its follow-ups in TODO
CI / deploy (push) Successful in 17s
CI / check (push) Successful in 21s
2026-12-01 02:02:55 +01:00
randy 9b797fd48c Night palette fixed (the section bands, the remaining light fills and row lines onto --ui-*, color-scheme: dark for checkboxes, the map controls lifted off the dark map, the home icon); side panels below the topbar (the title in view); offline login ticked in TODO (session cookie + TRUSTED_NETWORKS)
CI / deploy (push) Successful in 17s
CI / check (push) Successful in 21s
2026-12-01 01:56:51 +01:00
randy 7fcac61c99 Simulation along the trip's route ("Simulate driving the route" when there is one, POST /api/sim/gnss {"trip": true}), random trips after it
CI / deploy (push) Successful in 17s
CI / check (push) Successful in 21s
2026-12-01 01:45:38 +01:00
randy 07a4d363ec Driving mode ("Drive": big buttons — follow, zoom, 2D/3D, night, route overview — the sidebar hidden); palettes instead of the inversion (the UI's greys onto --ui-*, MapLibre's controls too, night → Night, new ◑ Dusk); the navigated route magenta, the driven part dimmed; route progress only forward (locate near the last position first); rerouting on the server off its own GNSS (TripStore#follow), the browser's only without the shared trip; the overview map hidden while following in 3D; the topbar's items apart
CI / check (push) Successful in 21s
CI / deploy (push) Successful in 17s
2026-12-01 01:44:54 +01:00
randy 12b4ac6725 Dashboard: altitude (gnss.alt, the terrain's while simulating), the car tilted by the terrain's slope while simulating; free look while following (the map moved by hand pauses the follow, "Back to the position" or 15 s resumes it); overlays and shown library files remembered per device (localStorage), back after a reload once the offline checks are in
CI / deploy (push) Successful in 17s
CI / check (push) Successful in 24s
2026-12-01 00:15:08 +01:00
randy 8c999919b8 Night mode: only the instruments and signs take the night palette (the UI's own colors stay Day's for the page inversion to darken — an active menu item had gone almost white)
CI / deploy (push) Successful in 17s
CI / check (push) Successful in 23s
2026-11-30 21:01:20 +01:00
randy bfa70c1d17 /can.html: two columns from 900px, the frames at least 560px wide (their data in view), the left column the rest
CI / deploy (push) Successful in 18s
CI / check (push) Successful in 21s
2026-11-30 20:42:04 +01:00
randy a11a71dc89 Status / debug: "Check for an update now" — past the update check's 10 min cache
CI / deploy (push) Successful in 18s
CI / check (push) Successful in 22s
2026-11-30 20:27:58 +01:00
randy d58f7efc41 Safer self-update: staged next to build/ (two renames, not a copy from RAM), waits for the new revision on /api/health and rolls back to build.old if it doesn't come up, a repeated request is a no-op, maptool-recover puts build/ back after a power cut mid-swap; the dashboard dark under the page's night mode; /can.html: frames in a second column on wide screens, changed bytes highlighted (fading, bits in the tooltip), the node state column a fixed width
CI / deploy (push) Successful in 17s
CI / check (push) Successful in 21s
2026-11-30 20:21:29 +01:00
randy 27313b3101 Navigation banner across the top (the next maneuver's arrow by Valhalla's type, distance, street, then…, lanes, the street being driven; maneuvers gain type/street/exit); the driving view (tilted to 3D) hides route numbers and minor roads' names, road labels further apart
CI / deploy (push) Successful in 17s
CI / check (push) Successful in 22s
2026-11-30 20:06:44 +01:00
randy e62eb90dc7 Palettes after IHO S-52 (Day / Dusk / Night, the same tokens, data-palette on <html>): night dim with low blue and no white areas, the speed limit sign dimmed too; the dashboard light with dark values by day again (the slider fades it instead of whitening it), the dark bezel for dusk and night
CI / deploy (push) Successful in 18s
CI / check (push) Successful in 22s
2026-11-30 20:00:39 +01:00
randy 4c58c9351f Update dependency rubyzip to v3.7.1
CI / deploy (push) Successful in 37s
CI / check (push) Successful in 27s
2026-11-30 19:52:36 +01:00
randy e92f01db12 Nodes describe themselves: an SDO client (Can::Sdo) reads each esphome-canopen node's TPDOs and entities (type, name, unit, range) on its first heartbeat, cached by the TPDO layout hash, decoded with no hand-written signals — can.json keeps aliases (with unit conversion) and foreign devices; design doc (NPS planning, cockpit instruments, Unigrid band) with color tokens, the dashboard in cockpit colors; starting the simulation turns the GNSS follow on, the GNSS position an arrow by its course
CI / deploy (push) Successful in 17s
CI / check (push) Successful in 23s
2026-11-30 19:51:03 +01:00
randy ce290f2162 TODO: hardware buttons, a virtual switch panel for the PDM, the group over LoRa and audio (inspired by Garmin Tread, details in home-gitops) 2026-11-30 19:29:56 +01:00
randy e7f3b91337 Update check: a failed one or CI still running is asked again after a minute, not cached for 10
CI / deploy (push) Successful in 18s
CI / check (push) Successful in 22s
2026-11-30 19:26:32 +01:00
randy e03e426eb6 SELF_UPDATE passed into the container
CI / deploy (push) Successful in 18s
CI / check (push) Successful in 21s
2026-11-30 19:20:21 +01:00
randy 17891c53b5 Shared trip: one itinerary per server (data/trip.json, GET/PUT /api/trip, routed server-side), the route panel edits it when logged in and polls other screens' changes in without moving the camera; the GNSS simulation skips trips under 1 km and starts elsewhere when it can't get on from a road island; the car's server updates itself from a topbar button (SELF_UPDATE=1: newer main with CI passed → bin/update-maptool.sh via maptool-update.path); Android Auto and the trip's next steps in TODO
CI / deploy (push) Successful in 17s
CI / check (push) Successful in 22s
2026-11-30 19:19:37 +01:00
randy 5f4c7c6ee8 Navigation: rerouting off the route (30 m for 3 fixes, HDOP ≤ 5, every 15 s at most) from the position to the points not reached yet; lanes as SVG arrows, the ones to take bold; dashboard background see-through with a slider; the GNSS simulation starts at a random place in the offline countries, the map jumping there
CI / deploy (push) Successful in 18s
CI / check (push) Successful in 22s
2026-11-30 19:11:07 +01:00
randy fbccb2acc9 GNSS follow glides the marker and the camera linearly to each fix over the poll interval instead of jumping; the simulation sends a fix every 0.5 s
CI / deploy (push) Successful in 17s
CI / check (push) Successful in 22s
2026-11-30 18:48:20 +01:00
randy 8680cdbee7 GNSS course worked out server-side (App.gnss_update, for the CAN node and the simulation, which send none): following in 3D turns heading-up behind the position again
CI / deploy (push) Successful in 17s
CI / check (push) Successful in 23s
2026-11-30 18:45:32 +01:00
randy f65eb98d18 Docs: the HMC5883L heading — ESPHome's atan2(-x, y) is −180..180, the node now adds 360 to the negatives (they arrived as 0 in its 0..360 encoding) 2026-11-30 18:42:50 +01:00
randy 190a8ad334 Dashboard overlay (Overlays → Live → Dashboard): one inclinometer (compass ring, roll and pitch), speed, the speed limit with an over-limit warning and, on the route, the next limit change, traffic signal, maneuver and its lanes; /api/route gains speed_limits, signals and lanes, POST /api/road gives the driven road's limit; GNSS simulation (random trips over Valhalla) for trying it without the car; the HMC5883L heading in can.json
CI / deploy (push) Successful in 17s
CI / check (push) Successful in 24s
2026-11-30 18:30:21 +01:00
randy 5958ffd153 Road names and route numbers past z16 keep the same spacing on the ground (symbol-spacing grows with the zoom), not one every few meters at z22 2026-11-30 18:30:21 +01:00
randy 500acf9fd5 CAN: a node that misses 3 heartbeats is flagged silent (one journal line when it stops and when it's back, red in /can.html); /can.html tables as wide as their content, numeric headers aligned with their values 2026-11-30 18:30:21 +01:00
randy 5c023619ec Map data pull over brick's nginx: X-Accel-Buffering: no on map files (buffered, nginx's 1 GB temp file cap ended every bigger download there); each attempt resumes from the part on disk (curl's --retry kept its first offset); a file that can't be written is skipped, not the whole run
CI / deploy (push) Successful in 17s
CI / check (push) Successful in 21s
2026-11-29 17:52:02 +01:00
randy 62045be0f7 TRUSTED_NETWORKS=connected: requests from the subnets the server's interfaces are on right now count as logged in (the car's server, whichever Wi-Fi it's on); CIDRs still work alongside
CI / deploy (push) Successful in 23s
CI / check (push) Successful in 21s
2026-11-29 17:19:13 +01:00
randy ea14b110e6 kiwix waits for a non-empty ZIM instead of a restart loop (on the car's server each restart's veth set off avahi's mDNS announcements and filled the Pi's Wi-Fi); pull-maps drops a connection a minute without data so the retry resumes (Wi-Fi switched under it)
CI / deploy (push) Successful in 17s
CI / check (push) Successful in 22s
2026-11-29 17:03:53 +01:00
randy f9fbcdbbc5 Map data pull: of kiwix/ only the served wikipedia.zim, not the other ZIMs lying there (65 GB)
CI / deploy (push) Successful in 17s
CI / check (push) Successful in 21s
2026-11-29 13:13:02 +01:00
randy 5eea31c741 Update dependency maplibre-gl to v6.20.0
CI / check (pull_request) Successful in 21s
CI / deploy (pull_request) Skipped
CI / deploy (push) Successful in 17s
CI / check (push) Successful in 20s
2026-11-29 11:49:22 +00:00
randy 6a0d6194fe CANopen diagnostics and map data over HTTPS: /can.html (interfaces, nodes with heartbeat state and last EMCY, decoded signals, every COB-ID with role, count, rate and last data); signals can mark an invalid raw value (esphome-canopen's unknown) and NaN gives no value; the CAN reader never dies and a broken can.json only turns CAN off; the GNSS node mcu-stm32-xiao-c5-2 (0x21) and host networking for the car's server in docs; bin/pull-maps.sh pulls map data from GET /api/sync/maps(/file) with SYNC_TOKEN instead of rsync over SSH, resuming cut-off downloads
CI / deploy (push) Successful in 18s
CI / check (push) Successful in 42s
2026-11-29 12:47:23 +01:00
randy a3e5fefaf1 3D relief like OsmAnd: the 3D button raises the terrain on its own DEM source (exaggeration 1.5), no longer needing Terrain shading or waiting for isStyleLoaded (false while tiles load, so it never came on); color-relief uses ["elevation"] (MapLibre 6), which had broken the whole Terrain shading overlay
CI / deploy (push) Successful in 18s
CI / check (push) Successful in 22s
2026-11-28 19:37:40 +01:00
randy dbe742321a Library sync OsmAnd-style: brick is the server, a client (the car's maptool, SYNC_SERVER_URL) syncs on its Sync button — pulls the server's rows, pushes its own with the source files the server lacks, newer updated_at wins; /api/sync/* guarded by SYNC_TOKEN (written into brick's .env by CI). TRUSTED_NETWORKS logs in the car's LAN (no Gitea offline); TAKEOUT_HOST_DIR for a server without the Takeout; bin/pull-maps.sh pulls map data one way while at home
CI / deploy (push) Successful in 18s
CI / check (push) Successful in 22s
2026-11-27 23:22:32 +01:00
randy 850a5946ad Native CAN (the van's final setup, MQTT the stopgap): SocketCAN on any number of interfaces, CANopen frame roles, heartbeat states and NMT start, signals decoded by data/can.json (id/mask, byte/bit, type, scale/offset, unit); gnss.* signals feed the GNSS control, GET /api/can; tested over vcan0
CI / deploy (push) Successful in 17s
CI / check (push) Successful in 20s
2026-11-27 22:48:46 +01:00
randy 78bdc7f6f0 Symbols page: point symbols grouped into categories (safety, accessibility, water, camping, food, winter, trails, transport, sights, programs, services) by name, empty ones hidden while filtering
CI / deploy (push) Successful in 18s
CI / check (push) Successful in 21s
2026-11-27 17:26:34 +01:00
randy 9015a4936d Side panels: header icon buttons one size and color (pin and export menu no longer off), title cut short instead of wrapping; tree dividers between siblings so a folder's line comes after its contents; Offline data group rows centered, subregion row smaller; plugin rows wrap with the whole Run button 2026-11-27 17:26:34 +01:00
randy b32f7d3bd3 Trails by kind: the extract keeps hiking, foot, bicycle, mtb and ski routes, each with a kind (educational told apart by educational=yes, the green diagonal marking or the name); versioned so the next offline build redoes old files; the overlay picks kinds (hiking and educational by default), the elevation profile shows the ones for the activity
CI / deploy (push) Successful in 18s
CI / check (push) Successful in 21s
2026-11-27 14:40:46 +01:00
randy 4bcd85f269 Hiking trails: lanes built only from the route pieces around the view (half a view each side), rebuilt when the view leaves it, drawn from zoom 11 — a whole country's graph took seconds per rebuild on the main thread and froze the browser
CI / deploy (push) Successful in 17s
CI / check (push) Successful in 21s
2026-11-27 14:34:24 +01:00
randy cf43c3e926 Update ghcr.io/renovatebot/renovate Docker tag to v45
CI / deploy (push) Successful in 17s
CI / check (push) Successful in 20s
2026-11-27 14:30:12 +01:00
randy cd8444ce2a Runtime map images (texture patterns, peak triangle) added with every style before tiles ask for them; styleimagemissing kept as the fallback (MapLibre 6 skips an image added from it for the requesting tile)
CI / deploy (push) Successful in 17s
CI / check (push) Successful in 23s
2026-11-27 14:29:29 +01:00
randy f0ff5f390f Hiking trails: the main checkbox loads the countries in view from zoom 10 (and those panned into), not all at once — together ~1 GB of GeoJSON the browser never finished; /api/hiking-trails also sends each country's bbox 2026-11-27 14:29:29 +01:00
randy 477f68f5b3 Map: ski lifts and cable cars (OpenMapTiles aerialway, which Liberty doesn't draw) as a line with topo cross ticks from z12, named from z13; night colors
CI / deploy (push) Successful in 18s
CI / check (push) Successful in 20s
2026-11-27 14:15:21 +01:00
randy 3561cb2f45 Side panels: OsmAnd-style list dividers between rows, section headings on a gray band, full-width group separators in the sidebar rail 2026-11-27 14:15:21 +01:00
randy 49900c1703 Drop gpsd support and the GNSS simulator service: the car's GNSS comes over CAN later; /api/gnss/position and the GNSS control stay, fed through GNSS_LATEST
CI / deploy (push) Successful in 17s
CI / check (push) Successful in 20s
2026-11-27 13:59:53 +01:00
randy 09a9d8baba Test: the cut-off download case runs as the last attempt, so the new retry doesn't hang CI for minutes reconnecting to a one-shot server 2026-11-27 13:59:46 +01:00
randy 064871b687 Google saved places: a name or description changed here survives a new export (the last imported text is kept per point, a field differing from it counts as a hand edit); the popup marks such a point as edited
CI / check (push) Successful in 8m50s
CI / deploy (push) Successful in 17s
2026-11-27 12:47:58 +01:00
randy 3f4b30d737 Side panels: finger-sized rows and controls on desktop too (one layout, as OsmAnd); track and folder actions (edit, download, delete) behind one ⋯ menu
CI / deploy (push) Successful in 17s
CI / check (push) Successful in 8m50s
2026-11-27 12:30:30 +01:00
randy cc833d5793 Map: protected area names while zoomed out (z6–10, local name, green italic) and mountain peaks from z7 (triangle drawn at runtime as SDF, name and elevation, highest win a collision); both recolored in night mode 2026-11-27 12:30:30 +01:00
randy 6182a2856d Points: bare waypoints (Google saved places) as small NPS-style dots instead of an empty badge, names as dark labels with a white halo from zoom 10; every library point editable (Edit/Move/Delete) when logged in, not only notes
CI / deploy (push) Successful in 17s
CI / check (push) Successful in 8m51s
2026-11-27 00:06:20 +01:00
randy 9a3c2fc1d2 Update dependency puma to v8.1.3
CI / check (pull_request) Successful in 9m0s
CI / deploy (pull_request) Skipped
CI / deploy (push) Successful in 38s
CI / check (push) Successful in 9m0s
2026-11-25 20:11:31 +00:00
randy 0aee739ac3 Google Maps saved lists from a scheduled Google Takeout: hourly check of TAKEOUT_DIR (brick's Drive backup, mounted read-only), the zip with Takeout/Saved/*.csv picked by its central directory (photo parts skipped), each list into Google Maps/<list>; positions decoded offline from the place's S2 feature id and refined by Nominatim, unresolved ones flagged approximate in the popup (cleared when moved by hand); points matched by Google id per folder, so a new export updates them (own color/icon/position kept, deleted stay deleted)
CI / check (push) Successful in 8m56s
CI / deploy (push) Successful in 38s
2026-11-25 15:10:30 +01:00
randy 261b4c053e Touch screens: finger-sized (44 px) rows, buttons and checkboxes in every side panel and sidebar menu; desktop keeps the compact lists
CI / deploy (push) Successful in 24s
CI / check (push) Successful in 8m59s
2026-11-24 21:59:13 +01:00
randy f1c2b22821 Feature inspector also on right click and long press (touch browsers fire contextmenu), not only Alt+click
CI / deploy (push) Successful in 17s
CI / check (push) Successful in 8m50s
2026-11-24 21:21:15 +01:00
randy b98a3ebcf1 Offline build: retry a stalled Geofabrik download (3 attempts, 120 s read timeout) and report network errors as a BuildError; a timed-out Last-Modified HEAD no longer fails the build
CI / deploy (push) Successful in 18s
CI / check (push) Successful in 8m50s
2026-11-24 14:27:29 +01:00
randy 637f739e18 Auto night mode: below zoom 5 keep the last real place for the sun check (zoomed out to the world the map center can sit in another time zone's night)
CI / deploy (push) Successful in 17s
CI / check (push) Successful in 1m12s
2026-11-24 13:32:09 +01:00
randy 2c27bcd6bf Update dependency maplibre-contour to v0.2.0
CI / deploy (push) Successful in 18s
CI / check (push) Successful in 20s
2026-11-24 13:03:20 +01:00
randy 357d28bf72 Map textures after field test: forest texture dropped (too busy), scrub / dwarf pine gets its own tint + bushes from zoom 11 instead of the grass texture; strict reserves and natural monuments a step darker than landscape protected areas; fix military outline losing its source
CI / deploy (push) Successful in 18s
CI / check (push) Successful in 19s
2026-11-24 13:00:52 +01:00
randy 25f5c42a1b NPS-style protected areas and textures: national parks keep the full sage fill, other protected areas a translucent gray-green with a dashed outline, military areas red hatch + outline; forest (z12+) and grass (z13+) textures drawn on canvas and registered on styleimagemissing, with night variants; legend rows
CI / deploy (push) Successful in 18s
CI / check (push) Successful in 20s
2026-11-23 19:19:11 +01:00
randy 31b27a0852 Night map palette instead of inverting it: dark blue-gray ground, roads a step lighter, muted ochre motorways, light-gray labels on dark halos, switched live with setPaintProperty (NightMap); raster overlays dimmed, own track/point colors kept; the UI panels keep the invert filter for now
CI / deploy (push) Successful in 17s
CI / check (push) Successful in 18s
2026-11-23 16:23:35 +01:00
randy 80d0039148 GNSS simulator: report the real direction of travel (it drives the loop counterclockwise, so the bearing is -angle, not angle+90°)
CI / deploy (push) Successful in 17s
CI / check (push) Successful in 18s
2026-11-23 16:15:15 +01:00
randy 06ae14bc02 Bigger night mode button (40 px tap target, 26 px glyph)
CI / check (push) Successful in 19s
CI / deploy (push) Successful in 17s
2026-11-23 16:12:48 +01:00
randy e9c9e96b92 Following the GNSS receiver or the browser's own position turns the map heading-up in the 3D view, position in the lower part of the screen, like a car navigation
CI / deploy (push) Successful in 17s
CI / check (push) Successful in 19s
2026-11-23 16:11:48 +01:00
randy fdd77986c1 Offline hiking trails drawn only from zoom 10 (a whole country's lanes rebuilt per zoom froze the zoomed-out map); TODO: server in the car (RPi CM5) — builds on brick, offline login, HTTPS, Pi kiosk display, home ⇄ car sync with conflict handling, hardware buttons over CAN
CI / deploy (push) Successful in 17s
CI / check (push) Successful in 19s
2026-11-23 15:56:20 +01:00
randy 2470099877 Login lasts 90 days instead of the browser session — Android dropped the session cookie whenever it killed the browser/PWA, forcing a fresh Gitea login + MFA
CI / deploy (push) Successful in 17s
CI / check (push) Successful in 19s
2026-11-23 15:04:17 +01:00
randy 9148c9a411 Night mode (auto after sunset / on / off, one invert+dim filter for now), tracker drawn as a top-down vehicle rotated by its GNSS course with a heading-up tilted Navigate mode, side panels float over the map on phone width instead of squeezing it
CI / deploy (push) Successful in 18s
CI / check (push) Successful in 36s
2026-11-23 15:03:58 +01:00
randy 0e5f79f8e4 Tracker and ITS-G5 as separate overlays, Overlays grouped by category: the tracker gets a name/icon/color, charging from its USB power topic, a floating info card (per-device opacity), a trail of the last 1–24 h and optional position logging that survives restarts (LiveStore); hiking trails keep their main checkbox as an all-countries toggle
CI / deploy (push) Successful in 18s
CI / check (push) Successful in 20s
2026-11-19 11:57:36 +01:00
randy 3fc8c75c60 NPS park maps overlay: park points and map footprints, a park search, a park popup listing its Harpers Ferry Center maps with local PDF/GeoTIFF links, and the 289 georeferenced ones laid over the base map with an opacity slider; data from data/nps served by /api/nps and /nps/{overlay,geotiff,pdf}
CI / deploy (push) Successful in 17s
CI / check (push) Successful in 19s
2026-11-19 10:52:17 +01:00
randy ff5924faf1 Offline regions for the whole world: the region list comes from Geofabrik's index (bin/geofabrik-regions-sync.mjs → geofabrik_regions.geojson, 193 countries plus subregions like the US states), keeping the European ISO codes; the picker folds it by continent with a search box and subregions under their country, flags for all of them
CI / deploy (push) Successful in 17s
CI / check (push) Successful in 19s
2026-11-19 10:03:47 +01:00
randy df69886220 Update dependency ruby to v4.0.10
CI / check (pull_request) Successful in 37s
CI / deploy (pull_request) Skipped
CI / deploy (push) Successful in 1m7s
CI / check (push) Successful in 36s
2026-11-19 08:06:54 +00:00
randy 878ba206a1 CI: non-secret values (OAuth client id, allowed users, P4N user) may be Actions variables too, falling back to secrets
CI / deploy (push) Successful in 17s
CI / check (push) Successful in 19s
2026-11-19 00:50:46 +01:00
randy 6b6a7f0027 CI: MQTT_URL and MQTT_USERNAME may be Actions variables (not secret), falling back to secrets
CI / deploy (push) Successful in 18s
CI / check (push) Successful in 18s
2026-11-19 00:48:44 +01:00
randy 02c2ef05f8 Vehicle & ITS-G5 overlay: a stdlib MQTT subscriber (MQTT_URL/USERNAME/PASSWORD) keeps the car's LTE tracker position and the ITS-G5 stations heard by mcu-its-g5 (decoded header, stations expire after 60 s), served by /api/live and drawn as a car badge plus stations colored by type with DENM in red; Meshtastic noted in TODO
CI / check (push) Successful in 21s
CI / deploy (push) Successful in 18s
2026-11-19 00:46:26 +01:00
randy b381ca289f TODO: vehicle dashboard over MQTT (LTE tracker position, decoded ITS-G5, car CAN, IMU road roughness, later a CAN bridge in the van), a 3D follow/navigation mode, and the touch fixes done so far
CI / deploy (push) Successful in 17s
CI / check (push) Successful in 19s
2026-11-19 00:18:56 +01:00
randy 07f3711760 Tablet-friendlier points: route markers get a 48px grab area, notes can be moved (Move in the popup: drag or tap the new spot), new and edited points pick an icon and a color with B/I buttons for their text, and the Tracks & Points open/close arrows get a real hit area
CI / check (push) Successful in 18s
CI / deploy (push) Successful in 17s
2026-11-19 00:03:39 +01:00
randy 3e5fada66a Legend page served as a view with the map's versioned importmap (shared partial): as a static page it imported icons.js and mdi.mjs unversioned and a browser with an older copy showed no symbols; it also stays light (color-scheme) since auto-darkening washed out its swatches, no autofocus, a clearer filter and a symbol count
CI / deploy (push) Successful in 18s
CI / check (push) Successful in 19s
2026-11-18 23:47:07 +01:00
randy 1bb0e1137a UI accent in the Park Tiles palette instead of light blue: active sidebar icons, selected panel options and primary buttons use NPS boundary olive on a light sage, defined once as --accent/--accent-bg
CI / deploy (push) Successful in 18s
CI / check (push) Successful in 18s
2026-11-18 23:40:04 +01:00
randy 59a29e86a5 Park Tiles look as the only base map theme: the old ONLINE_STYLE_PATCH palette and the theme switch are gone, the legend at /symbols.html shows the one look, and the docs carry the sampled Park Tiles colors
CI / deploy (push) Successful in 18s
CI / check (push) Successful in 19s
2026-11-18 23:36:30 +01:00
randy 07b623b7ca Vendored modules versioned like the app's own: the 7 /vendor modules our JS imports get importmap entries and maplibre-gl.css, pmtiles and maplibre-contour a ?v=, so a deploy busts them too; a test keeps every imported /vendor module in the importmap
CI / check (push) Successful in 19s
CI / deploy (push) Successful in 17s
2026-11-18 23:26:53 +01:00
randy a21e2b0bc6 Static files sent with Cache-Control: no-cache (revalidated, a 304 when unchanged): unversioned /vendor modules were cached heuristically, so a tablet kept the old mdi.mjs after the deploy that added the lock icons and the new icons.js failed to import from it, leaving a blank map
CI / deploy (push) Successful in 18s
CI / check (push) Successful in 18s
2026-11-18 23:24:15 +01:00
randy f09216b102 Base map theme switch: Maptool or NPS Park Tiles (colors sampled from the Park Tiles legend, park fill above landcover with a tint band), remembered; both themes in map_themes.js so /symbols.html draws a side-by-side map legend from the same patched style, linked from the Base map panel, which now stays even without offline tiles
CI / deploy (push) Successful in 17s
CI / check (push) Successful in 18s
2026-11-18 23:11:44 +01:00
randy cb6412f0ba NPS research notes: the NPS app's offline downloads (sources, georeferenced brochure maps, park boundaries), HFC starter maps and symbol sheet (linework, color families, swatches), and TODO entries for tablet-friendly UI, NPS parks & maps and a Park Tiles look 2026-11-18 23:01:13 +01:00
randy 085c14beca All 307 NPS symbols (symbol-library 2024 revision, CC0) vendored by bin/nps-symbols-sync.mjs and browsable at /symbols.html; POI_ICONS maps every symbol by name plus the OsmAnd names, the note icon picker gets a filter, and only the glyphs a shown file uses get rasterized 2026-11-18 23:01:13 +01:00
randy 6faabca93d Compass and a north-up rotation lock (on by default, remembered): a two-finger gesture on a tablet rotated the map far too easily 2026-11-18 22:59:12 +01:00
randy 4265421457 Tracks and routes as containers of points: listed (collapsed) under them in the tree, added via a point's popup, a new note or the route planner's navigation pins, and written as course points into the FIT course
CI / deploy (push) Successful in 18s
CI / check (push) Successful in 18s
2026-11-18 12:39:04 +01:00
randy 6aa7b34f92 Track lines: dark casing, direction arrows, end dots, and a per-file palette color when the track has none
CI / deploy (push) Successful in 17s
CI / check (push) Successful in 19s
2026-11-18 12:28:47 +01:00
randy d87b8b8f80 Unnamed imported tracks (FIT, ...) take the file's name, backfilled once for earlier imports; split and best-effort times with seconds
CI / deploy (push) Successful in 17s
CI / check (push) Successful in 18s
2026-11-17 23:37:41 +01:00
randy 21c5c2f21b Import plugins: a side panel like the others (pinned/overlay, swaps with them) instead of a flyout
CI / deploy (push) Successful in 17s
CI / check (push) Successful in 18s
2026-11-17 23:30:03 +01:00
randy 7ea5e72a2c Merge remote-tracking branch 'origin/renovate/maplibre-gl-6.x'
CI / deploy (push) Successful in 57s
CI / check (push) Successful in 28s
2026-11-17 23:25:27 +01:00
randy a8a30d99c3 Merge remote-tracking branch 'origin/renovate/ghcr.io-valhalla-valhalla-3.x' 2026-11-17 23:25:27 +01:00
randy 3ecdc8c4c1 Merge remote-tracking branch 'origin/renovate/sinatra-contrib-4.x-lockfile' 2026-11-17 23:25:27 +01:00
randy 2697acde86 Merge remote-tracking branch 'origin/renovate/puma-8.x-lockfile' 2026-11-17 23:25:27 +01:00
randy d1c96d3fcc CI: run on push only for main, PR branches are checked by pull_request
CI / deploy (push) Successful in 17s
CI / check (push) Successful in 18s
2026-11-17 23:24:53 +01:00
randy e255789b56 Update dependency maplibre-gl to v6.19.0
CI / deploy (push) Skipped
CI / check (pull_request) Successful in 18s
CI / deploy (pull_request) Skipped
CI / check (push) Successful in 18s
2026-11-17 22:19:55 +00:00
randy 273446a71c Update ghcr.io/valhalla/valhalla Docker tag to v3.9.3
CI / deploy (push) Skipped
CI / check (pull_request) Successful in 18s
CI / deploy (pull_request) Skipped
CI / check (push) Successful in 17s
2026-11-17 22:19:35 +00:00
randy f3f81d3189 Update dependency sinatra-contrib to v4.2.2
CI / deploy (push) Skipped
CI / check (pull_request) Successful in 24s
CI / deploy (pull_request) Skipped
CI / check (push) Successful in 22s
2026-11-17 22:19:33 +00:00
randy c3aec193a9 Update dependency puma to v8.1.2
CI / deploy (push) Skipped
CI / check (pull_request) Successful in 26s
CI / deploy (pull_request) Skipped
CI / check (push) Successful in 26s
2026-11-17 22:19:20 +00:00
randy c2df1f4d30 Side panels: pinned (the map moves over) or overlay (hides on mouse out), switched by a pin button in each panel header
CI / deploy (push) Successful in 17s
CI / check (push) Successful in 18s
2026-11-17 23:18:21 +01:00
randy 066e831219 Profile: the time axis is scaled by moving time (pauses take no width), splits and laps redrawn on it
CI / check (push) Successful in 18s
CI / deploy (push) Successful in 17s
2026-11-17 16:57:19 +01:00
randy 38368fc801 Profile: 1/5/10 km splits or laps (FIT/TCX) shaded in the charts, in the table and as numbered posts on the map; tooltip follows the pointer over the plots only
CI / deploy (push) Successful in 17s
CI / check (push) Successful in 19s
2026-11-17 16:47:22 +01:00
randy 3e487539bc Re-read already-uploaded tracks once so their profiles get power and temperature
CI / deploy (push) Successful in 22s
CI / check (push) Successful in 19s
2026-11-16 18:46:58 +01:00
randy ebd4852e98 Temperature from FIT/GPX in the profile chart, splits and summary
CI / deploy (push) Successful in 17s
CI / check (push) Successful in 24s
2026-11-16 14:59:55 +01:00
randy e3f08f2267 Splits: descent column and a header row; Tracks & Points: clicking a name shows the item and zooms to it
CI / deploy (push) Successful in 17s
CI / check (push) Successful in 20s
2026-11-16 13:26:59 +01:00
randy 07e22a87af Track lines: pure-expression layer filter (MapLibre rejects the mixed legacy "!has" form, so no line layer was added)
CI / check (push) Successful in 19s
CI / deploy (push) Successful in 17s
2026-11-16 13:20:58 +01:00
randy acda303470 Update dependency maplibre-gl-lanes to v1.7.0
CI / deploy (push) Successful in 18s
CI / check (push) Successful in 18s
2026-11-16 12:21:10 +01:00
randy f8755ea65a Bicycle and foot route profiles (Valhalla bicycle/pedestrian costing); hiking trail colours in the elevation profile; power, splits and best efforts in the profile; TCX import; FIT course export
CI / deploy (push) Successful in 18s
CI / check (push) Successful in 19s
2026-11-16 12:18:06 +01:00
randy 4c704045c5 Material Design Icons replace the hand-drawn UI icons (only the used ones vendored, Renovate-tracked); route panel: saved-point picker, buttons on two rows with icons
CI / deploy (push) Successful in 17s
CI / check (push) Successful in 19s
2026-11-15 11:17:40 +01:00
randy a6d63e242b Merge remote-tracking branch 'origin/renovate/ghcr.io-valhalla-valhalla-3.x'
CI / deploy (push) Successful in 17s
CI / check (push) Successful in 18s
2026-11-15 10:16:45 +01:00
randy e94bfd1740 Merge remote-tracking branch 'origin/renovate/puma-8.x-lockfile' 2026-11-15 10:16:45 +01:00
randy db586c0166 One-way hiking route members (forward/backward roles) kept in their direction by maplibre-gl-lanes; raise Valhalla trace limits for the per-country route summary 2026-11-15 10:16:45 +01:00
randy 43119cfdae Update ghcr.io/valhalla/valhalla Docker tag to v3.9.2
CI / deploy (push) Successful in 27s
CI / check (push) Successful in 18s
2026-11-15 10:12:47 +01:00
randy dca447a9e9 Update dependency puma to v8.1.1
CI / deploy (push) Successful in 37s
CI / check (push) Successful in 26s
2026-11-15 10:12:39 +01:00
randy d810765de5 Update dependency puma to v8.1.1
CI / deploy (push) Skipped
CI / check (pull_request) Successful in 26s
CI / deploy (pull_request) Skipped
CI / check (push) Successful in 29s
2026-11-15 09:08:33 +00:00
randy 0a1fc266b7 Update dependency maplibre-gl-lanes to v1.6.0
CI / check (pull_request) Successful in 18s
CI / deploy (pull_request) Skipped
CI / check (push) Successful in 21s
CI / deploy (push) Successful in 17s
2026-11-15 09:08:19 +00:00
randy 573e6b3455 Update ghcr.io/valhalla/valhalla Docker tag to v3.9.2
CI / deploy (push) Skipped
CI / check (pull_request) Successful in 20s
CI / deploy (pull_request) Skipped
CI / check (push) Successful in 18s
2026-11-15 09:08:00 +00:00
randy 916b016da1 Update dependency maplibre-gl-lanes to v1.5.0
CI / deploy (push) Successful in 17s
CI / check (push) Successful in 36s
2026-11-15 10:07:00 +01:00
randy 69aa284e36 Vehicle profiles (Car, Camper, ...), avoid tolls/motorways, per-country vignette and toll km for a route
CI / deploy (push) Successful in 17s
CI / check (push) Successful in 19s
2026-11-14 21:20:23 +01:00
randy 58ca871662 Routing: start once the offline build's extracts are in, not after Planetiler; merged file keeps the .osm.pbf extension osmium needs
CI / deploy (push) Successful in 12s
CI / check (push) Successful in 19s
2026-11-14 14:50:39 +01:00
randy ac7c7f3ba9 Valhalla container waits for maptool to install the freshly deployed service script
CI / deploy (push) Successful in 22s
CI / check (push) Successful in 19s
2026-11-14 12:16:22 +01:00
randy dbe1804ebf Routing: reject a pre-merge multi-country request, don't resume a failed build, Apply queues when the running build lacks the merge
CI / deploy (push) Successful in 27s
CI / check (push) Successful in 17s
2026-11-14 12:13:25 +01:00
randy acf5256c74 Routing: merge the countries' extracts with osmium before Valhalla, which fails on overlapping extracts
CI / deploy (push) Successful in 12s
CI / check (push) Successful in 23s
2026-11-14 12:11:17 +01:00
randy 92efe118b0 Routing build status: show the container's step while a request is queued; Apply during a build of the same regions queues nothing
CI / deploy (push) Successful in 22s
CI / check (push) Successful in 20s
2026-11-14 00:20:02 +01:00
randy 59447c56f2 Library phase 3: change feed and folder export for Locus (GPX) and OsmAnd (favourites + tracks zip)
CI / deploy (push) Successful in 13s
CI / check (push) Successful in 20s
2026-11-13 23:00:07 +01:00
randy cca985d2b9 Route elevation profile (climb, descent, max grade) from the terrain tiles, and reach (isochrones) in the route panel 2026-11-13 22:55:55 +01:00
randy b80575828a Preview a search result or route point on hover / press-and-hold, back on leave, committed on click 2026-11-13 22:45:42 +01:00
randy abde7fe5f9 Route panel: points from search, GPS and library points, reordering, editing a saved route 2026-11-13 22:37:49 +01:00
randy 3146478c23 Offline routing phase 2: route panel, /api/route via Valhalla, vehicle profile, save a route to the library 2026-11-13 22:34:47 +01:00
randy d93c77727f Atomic, EOF-checked extract downloads; Apply starts builds one after another so routing waits for the offline map's downloads 2026-11-13 22:28:37 +01:00
randy bf912b96e5 Offline routing phase 1: valhalla container building from the offline map's extracts, status in the Offline data panel
CI / deploy (push) Successful in 2m48s
CI / check (push) Successful in 55s
2026-11-13 21:24:19 +01:00
randy 6f5f11cb4d Library phase 2: rename/recolor nodes, rename and move folders, split a layer into items; offline routing design 2026-11-13 21:16:35 +01:00
randy 4d838395b8 Merge pull request 'Update https://github.com/hyperknot/openfreemap-styles digest to 006ea57' (#23) from renovate/https-github.com-hyperknot-openfreemap-styles-digest into main
CI / deploy (push) Successful in 12s
CI / check (push) Successful in 18s
Reviewed-on: #23
2026-11-13 09:44:51 +01:00
randy 8a2734d59e Update https://github.com/hyperknot/openfreemap-styles digest to 006ea57
CI / deploy (push) Skipped
CI / check (pull_request) Successful in 17s
CI / deploy (pull_request) Skipped
CI / check (push) Successful in 20s
2026-11-13 08:42:01 +00:00
randy 3834f4fe1e Renovate: allow bin/assets-sync.mjs as a postUpgradeTask, re-pin Liberty one commit back to retest
CI / deploy (push) Successful in 13s
CI / check (push) Successful in 18s
2026-11-13 09:40:23 +01:00
randy f0f463d9b2 Update https://github.com/hyperknot/openfreemap-styles digest to 006ea57
CI / deploy (push) Successful in 22s
CI / check (push) Successful in 18s
2026-11-13 09:36:50 +01:00
randy 7cef82116f Update dependency puma to v8.0.3
CI / check (pull_request) Successful in 26s
CI / deploy (pull_request) Skipped
CI / deploy (push) Successful in 53s
CI / check (push) Successful in 27s
2026-11-13 08:33:58 +00:00
randy 5e1d1988ab Renovate: track Noto Sans glyphs and the Liberty style/sprite via git commit pins
CI / deploy (push) Successful in 12s
CI / check (push) Successful in 19s
2026-11-13 09:32:33 +01:00
randy ad8b72c3d3 Library phase 1: SQLite item library with folders, migration of old files as layers, import split into items 2026-11-13 09:03:22 +01:00
randy 4216211a20 Topbar: fit phone width by hiding wordmark, username and sunset countdown
CI / deploy (push) Successful in 13s
CI / check (push) Successful in 18s
2026-11-12 16:14:32 +01:00
randy 25b87b94fe Installable PWA with a share target; design for an item-based library
CI / deploy (push) Successful in 13s
CI / check (push) Successful in 18s
Android's share sheet (OsmAnd, Locus, mapy.com, ...) can now send
GPX/FIT/GeoJSON/ZIP files to the installed app: the service worker parks
them and the page offers to import them into a Tracks & Points folder,
waiting through a login if needed. Manifest, app icon, a server-side
fallback for /share-target.

docs/library-design.adoc proposes replacing the file-based GpxStore with
folders and items (stable ids, timestamps, tombstones, a change feed) as
the base for syncing with OsmAnd and Locus.
2026-11-12 13:42:04 +01:00
randy e2461f794c Places index: also drop localities, isolated dwellings and kindless objects
Measured on France (5.3M rows): place=locality ~10% (mostly cadastral
names of fields and woods), isolated_dwelling ~5%, objects with a name
but none of the recognized kind keys ~4% (bus route relations etc.).
Schema version 3, so rake places:index rebuilds existing indexes.
2026-11-12 13:42:04 +01:00
randy f3dd37dd4e Places index: drop buildings and land use, search without apostrophes and by brand
CI / deploy (push) Successful in 12s
CI / check (push) Successful in 18s
Named buildings and land-use areas are skipped unless they're also a
shop/amenity/etc. A second, unshown FTS column holds the name without
apostrophes and the brand tag, so "mcdonalds" finds McDonald's and
"lidl" finds "Lidl Petržalka". The index records a schema version;
rake places:index rebuilds older ones by itself.
2026-11-12 12:58:31 +01:00
randy 8e4c466829 chore(deps): update dependency maplibre-gl to v6.18.0
CI / deploy (push) Successful in 12s
CI / check (push) Successful in 17s
2026-11-12 12:54:49 +01:00
randy 54e811ef95 chore(deps): update dependency suncalc to v2.1.4
CI / check (pull_request) Successful in 17s
CI / deploy (pull_request) Skipped
CI / deploy (push) Successful in 13s
CI / check (push) Successful in 17s
2026-11-12 11:52:17 +00:00
randy e63f6f7ce7 Enable YJIT in the container
CI / deploy (push) Successful in 1m2s
CI / check (push) Successful in 19s
The official Ruby image ships YJIT but leaves it off. Set via ENV so the
puma server and rake jobs run through podman compose exec both get it.
2026-11-12 12:27:42 +01:00
randy 3f973a26d7 Search the offline map and Wikipedia, nearest results first
CI / deploy (push) Successful in 33s
CI / check (push) Successful in 26s
Every named OSM object in each country's Geofabrik extract goes into a
SQLite FTS5 index (data/places/<CODE>.sqlite, lib/maptool/places.rb),
built as the last offline-build step or on its own with
rake places:index. Kiwix full-text search is another source; clicking a
hit opens the article. Results from every source are sorted by distance
from the map center (settlements weighted closer) and show it; each
source is queried separately so a slow one doesn't hold up the list.
2026-11-12 12:13:13 +01:00
randy ba9c40ac3d Search: highlight the found spot, open a waypoint's popup, full-height list
A point result (typed coordinates, a geocoded place, a waypoint) leaves
a pulsing marker on the map until the next jump or a click on it. A
result from a layer opens that point's popup as if clicked on the map.
The panel grows to the window height so long result lists fit.
2026-11-12 12:13:13 +01:00
randy 81e688be9b Record per-step timings of offline/terrain builds
CI / deploy (push) Successful in 12s
CI / check (push) Successful in 38s
Live in build-status while running; every finished build (done or
error) is appended to data/build_history.jsonl with its step timings,
regions, thread count and, for offline builds, the tail of Planetiler's
output (its own per-phase summary). GET /api/build-history, shown in the
debug panel, gives a baseline to compare later builds against.
2026-11-12 11:54:49 +01:00
randy 7429e4ae33 Zip upload: reject archives over 500 MB uncompressed
Sums the entries' declared sizes before extracting anything; rubyzip's
own validate_entry_sizes (on by default) catches an entry that inflates
past what it declared.
2026-11-12 11:54:49 +01:00
randy ca2e67599b Sun & moon chart: click the topbar's sun readout
A horizon-style chart drawn from the vendored suncalc, so fully offline:
real sun and moon altitude over the 24 h around solar noon, sunrise/
sunset lines, dawn/noon/dusk on the time axis, the moon in its current
phase, plus moonrise/set, phase and current sun/moon position below.
Polar day/night now shows as a label instead of hiding the readout.
2026-11-12 11:54:49 +01:00
randy cf483d183c Add a logged-in-only status/debug panel at the bottom of the sidebar
Dumps every read-only status endpoint (health, offline/terrain build
status, regions, caches, hiking trails, kiwix, plugins, GNSS, LiveTrack)
as JSON, refreshed every 5s while open so a running build's progress
shows live.
2026-11-12 11:37:42 +01:00
randy 0051a0337c Search: look through all saved layers and offline hiking trails
GET /api/search (lib/maptool/search.rb) matches feature name and
description, case- and diacritics-insensitive, across every file in
Tracks & Points (shown or not) and every offline hiking-trails country.
Parsed features are cached in memory per file by mtime.

The search box now queries local sources and Nominatim side by side,
labels each result with where it was found, lets you untick sources,
and switches a result's layer on if it was off before zooming to it.
2026-11-12 11:37:42 +01:00
296 changed files with 32581 additions and 2688 deletions

No files matched your search

+1
View File
@@ -5,3 +5,4 @@ data
.ruby-lsp .ruby-lsp
.env .env
node_modules node_modules
can-recorder/target
+13 -3
View File
@@ -1,7 +1,10 @@
name: CI name: CI
# push only for main: a PR branch is already checked by pull_request,
# so both would run the same check twice.
on: on:
push: push:
branches: [main]
pull_request: pull_request:
jobs: jobs:
@@ -98,17 +101,24 @@ jobs:
# — hence OAUTH_CLIENT_* rather than GITEA_OAUTH_CLIENT_*; the .env # — hence OAUTH_CLIENT_* rather than GITEA_OAUTH_CLIENT_*; the .env
# var names on the right of `=` are unaffected, still what app.rb # var names on the right of `=` are unaffected, still what app.rb
# actually reads. # actually reads.
# Non-secret values (ids, user names, URLs) may be Actions *Variables*
# instead of Secrets: `vars.X || secrets.X` reads either, so moving one
# over needs no change here. Real secrets stay secrets-only.
- name: Write .env - name: Write .env
run: | run: |
cat > /srv/podman/maptool/.env <<EOF cat > /srv/podman/maptool/.env <<EOF
SESSION_SECRET=${{ secrets.SESSION_SECRET }} SESSION_SECRET=${{ secrets.SESSION_SECRET }}
GITEA_OAUTH_CLIENT_ID=${{ secrets.OAUTH_CLIENT_ID }} GITEA_OAUTH_CLIENT_ID=${{ vars.OAUTH_CLIENT_ID || secrets.OAUTH_CLIENT_ID }}
GITEA_OAUTH_CLIENT_SECRET=${{ secrets.OAUTH_CLIENT_SECRET }} GITEA_OAUTH_CLIENT_SECRET=${{ secrets.OAUTH_CLIENT_SECRET }}
MAPTOOL_ALLOWED_GITEA_USER=${{ secrets.MAPTOOL_ALLOWED_GITEA_USER }} MAPTOOL_ALLOWED_GITEA_USER=${{ vars.MAPTOOL_ALLOWED_GITEA_USER || secrets.MAPTOOL_ALLOWED_GITEA_USER }}
LIVETRACK_WEBHOOK_SECRET=${{ secrets.LIVETRACK_WEBHOOK_SECRET }} LIVETRACK_WEBHOOK_SECRET=${{ secrets.LIVETRACK_WEBHOOK_SECRET }}
P4N_USER=${{ secrets.P4N_USER }} P4N_USER=${{ vars.P4N_USER || secrets.P4N_USER }}
P4N_PASSWORD=${{ secrets.P4N_PASSWORD }} P4N_PASSWORD=${{ secrets.P4N_PASSWORD }}
P4N_SESSION_COOKIE=${{ secrets.P4N_SESSION_COOKIE }} P4N_SESSION_COOKIE=${{ secrets.P4N_SESSION_COOKIE }}
MQTT_URL=${{ vars.MQTT_URL || secrets.MQTT_URL }}
MQTT_USERNAME=${{ vars.MQTT_USERNAME || secrets.MQTT_USERNAME }}
MQTT_PASSWORD=${{ secrets.MQTT_PASSWORD }}
SYNC_TOKEN=${{ secrets.SYNC_TOKEN }}
EOF EOF
chmod 600 /srv/podman/maptool/.env chmod 600 /srv/podman/maptool/.env
+3 -3
View File
@@ -17,7 +17,7 @@ jobs:
# (RENOVATE_BINARY_SOURCE=install below). Renovate bumps this # (RENOVATE_BINARY_SOURCE=install below). Renovate bumps this
# tag itself. # tag itself.
container: container:
image: ghcr.io/renovatebot/renovate:44 image: ghcr.io/renovatebot/renovate:45
steps: steps:
- name: Run Renovate - name: Run Renovate
run: renovate run: renovate
@@ -28,7 +28,7 @@ jobs:
RENOVATE_REPOSITORIES: "${{ gitea.repository }}" RENOVATE_REPOSITORIES: "${{ gitea.repository }}"
RENOVATE_ONBOARDING: "false" RENOVATE_ONBOARDING: "false"
RENOVATE_BINARY_SOURCE: install RENOVATE_BINARY_SOURCE: install
# postUpgradeTasks in renovate.json (vendor re-sync on npm bumps) # postUpgradeTasks in renovate.json (vendor re-sync on npm and asset pin bumps)
RENOVATE_ALLOWED_COMMANDS: '["^npm ci( \\S+)*$", "^node bin/vendor-sync\\.mjs$"]' RENOVATE_ALLOWED_COMMANDS: '["^npm ci( \\S+)*$", "^node bin/vendor-sync\\.mjs$", "^node bin/assets-sync\\.mjs$"]'
# Secret named GH_COM_TOKEN: Gitea reserves the GITHUB_ prefix. # Secret named GH_COM_TOKEN: Gitea reserves the GITHUB_ prefix.
GITHUB_COM_TOKEN: ${{ secrets.GH_COM_TOKEN }} GITHUB_COM_TOKEN: ${{ secrets.GH_COM_TOKEN }}
+14
View File
@@ -32,6 +32,17 @@
/data/gpx/* /data/gpx/*
!/data/gpx/.gitkeep !/data/gpx/.gitkeep
# Tracks & Points library (lib/maptool/library.rb) and its stored uploads
/data/library.sqlite*
/data/library/
# Offline routing: Valhalla tiles and its status files (lib/maptool/routing.rb)
/data/routing/
# NPS park maps (index, overlays, GeoTIFFs, PDFs) for the NPS overlay,
# built outside this repo (~/Projects/NPS_Maps)
/data/nps
# Garmin LiveTrack session IDs received via webhook # Garmin LiveTrack session IDs received via webhook
/data/livetrack.json /data/livetrack.json
@@ -57,3 +68,6 @@
/REVISION /REVISION
node_modules/ node_modules/
# can-recorder's cargo build
/can-recorder/target/
+1 -1
View File
@@ -1 +1 @@
4.0.9 4.0.10
+17 -2
View File
@@ -1,7 +1,20 @@
# can-recorder (can-recorder/, Rust): the CAN bus into MF4 files, started
# and stopped by lib/maptool/can_recorder.rb. Built in its own stage, only
# the binary goes into the image (trixie as well: the same glibc).
FROM rust:1.100-slim-trixie AS can-recorder
WORKDIR /src
COPY can-recorder/ ./
RUN cargo build --release --locked
# trixie, not bookworm: Planetiler needs Java 21+ (UnsupportedClassVersionError # trixie, not bookworm: Planetiler needs Java 21+ (UnsupportedClassVersionError
# otherwise) and bookworm's own default-jre-headless is only Java 17 — # otherwise) and bookworm's own default-jre-headless is only Java 17 —
# bookworm-backports doesn't carry a newer one either, only trixie's does. # bookworm-backports doesn't carry a newer one either, only trixie's does.
FROM ruby:4.0.9-slim-trixie FROM ruby:4.0.10-slim-trixie
# YJIT is compiled into the official image but off unless asked for. Set
# here rather than as a puma flag so `podman compose exec ... rake` jobs
# (places:index, gpx backfills) get it too.
ENV RUBY_YJIT_ENABLE=1
# build-essential: puma has a native (C) extension; harmless if the # build-essential: puma has a native (C) extension; harmless if the
# platform-specific gem in Gemfile.lock already has a precompiled binary # platform-specific gem in Gemfile.lock already has a precompiled binary
@@ -42,10 +55,12 @@ RUN set -eux; \
# unlike go-pmtiles above. Default PLANETILER_JAR path (pmtiles_builder.rb) # unlike go-pmtiles above. Default PLANETILER_JAR path (pmtiles_builder.rb)
# expects it here. # expects it here.
# renovate: datasource=github-releases depName=onthegomap/planetiler # renovate: datasource=github-releases depName=onthegomap/planetiler
ARG PLANETILER_VERSION=0.10.2 ARG PLANETILER_VERSION=0.11.1
RUN curl -fsSL "https://github.com/onthegomap/planetiler/releases/download/v${PLANETILER_VERSION}/planetiler.jar" \ RUN curl -fsSL "https://github.com/onthegomap/planetiler/releases/download/v${PLANETILER_VERSION}/planetiler.jar" \
-o /usr/local/lib/planetiler.jar -o /usr/local/lib/planetiler.jar
COPY --from=can-recorder /src/target/release/can-recorder /usr/local/bin/can-recorder
WORKDIR /app WORKDIR /app
COPY Gemfile Gemfile.lock ./ COPY Gemfile Gemfile.lock ./
+3
View File
@@ -6,6 +6,7 @@ gem "puma", "~> 8.0"
gem "rexml", "~> 3.4" gem "rexml", "~> 3.4"
gem "oauth2", "~> 2.0" gem "oauth2", "~> 2.0"
gem "rubyzip", "~> 3.0" gem "rubyzip", "~> 3.0"
gem "sqlite3", "~> 2.10"
group :development do group :development do
gem "rerun" gem "rerun"
@@ -17,3 +18,5 @@ group :test do
end end
gem "faraday-cookie_jar", "~> 0.0.8" gem "faraday-cookie_jar", "~> 0.0.8"
gem "csv", "~> 3.3"
+41 -17
View File
@@ -7,6 +7,7 @@ GEM
version_gem (~> 1.1, >= 1.1.16) version_gem (~> 1.1, >= 1.1.16)
base64 (0.3.0) base64 (0.3.0)
bigdecimal (4.1.3) bigdecimal (4.1.3)
csv (3.3.7)
domain_name (0.6.20260902) domain_name (0.6.20260902)
drb (2.2.3) drb (2.2.3)
faraday (2.15.1) faraday (2.15.1)
@@ -43,7 +44,7 @@ GEM
minitest (6.1.0) minitest (6.1.0)
drb (~> 2.0) drb (~> 2.0)
prism (>= 1.5, < 3) prism (>= 1.5, < 3)
multi_json (1.21.1) multi_json (1.21.2)
multi_xml (0.9.1) multi_xml (0.9.1)
bigdecimal (>= 3.1, < 5) bigdecimal (>= 3.1, < 5)
mustermann (3.1.1) mustermann (3.1.1)
@@ -64,10 +65,10 @@ GEM
snaky_hash (~> 2.0, >= 2.0.9) snaky_hash (~> 2.0, >= 2.0.9)
version_gem (~> 1.1, >= 1.1.17) version_gem (~> 1.1, >= 1.1.17)
prism (1.9.0) prism (1.9.0)
puma (8.0.2) puma (8.1.4)
nio4r (~> 2.0) nio4r (~> 2.0)
rack (3.2.8) rack (3.2.8)
rack-protection (4.2.1) rack-protection (4.2.2)
base64 (>= 0.1.0) base64 (>= 0.1.0)
logger (>= 1.6.0) logger (>= 1.6.0)
rack (>= 3.0.0, < 4) rack (>= 3.0.0, < 4)
@@ -80,24 +81,34 @@ GEM
ffi (~> 1.0) ffi (~> 1.0)
rerun (0.14.0) rerun (0.14.0)
listen (~> 3.0) listen (~> 3.0)
rexml (3.4.4) rexml (3.4.5)
rubyzip (3.7.0) rubyzip (3.7.1)
sinatra (4.2.1) sinatra (4.2.2)
logger (>= 1.6.0) logger (>= 1.6.0)
mustermann (~> 3.0) mustermann (~> 3.0)
rack (>= 3.0.0, < 4) rack (>= 3.0.0, < 4)
rack-protection (= 4.2.1) rack-protection (= 4.2.2)
rack-session (>= 2.0.0, < 3) rack-session (>= 2.0.0, < 3)
tilt (~> 2.0) tilt (~> 2.0)
sinatra-contrib (4.2.1) sinatra-contrib (4.2.2)
multi_json (>= 0.0.2) multi_json (>= 0.0.2)
mustermann (~> 3.0) mustermann (~> 3.0)
rack-protection (= 4.2.1) rack-protection (= 4.2.2)
sinatra (= 4.2.1) sinatra (= 4.2.2)
tilt (~> 2.0) tilt (~> 2.0)
snaky_hash (2.0.9) snaky_hash (2.0.9)
hashie (>= 0.1.0, < 6) hashie (>= 0.1.0, < 6)
version_gem (~> 1.1, >= 1.1.16) version_gem (~> 1.1, >= 1.1.16)
sqlite3 (2.10.2-aarch64-linux-gnu)
sqlite3 (2.10.2-aarch64-linux-musl)
sqlite3 (2.10.2-arm-linux-gnu)
sqlite3 (2.10.2-arm-linux-musl)
sqlite3 (2.10.2-arm64-darwin)
sqlite3 (2.10.2-x86-linux-gnu)
sqlite3 (2.10.2-x86-linux-musl)
sqlite3 (2.10.2-x86_64-darwin)
sqlite3 (2.10.2-x86_64-linux-gnu)
sqlite3 (2.10.2-x86_64-linux-musl)
tilt (2.9.0) tilt (2.9.0)
timeout (0.6.1) timeout (0.6.1)
uri (1.1.2) uri (1.1.2)
@@ -116,6 +127,7 @@ PLATFORMS
x86_64-linux-musl x86_64-linux-musl
DEPENDENCIES DEPENDENCIES
csv (~> 3.3)
faraday-cookie_jar (~> 0.0.8) faraday-cookie_jar (~> 0.0.8)
minitest (~> 6.0) minitest (~> 6.0)
oauth2 (~> 2.0) oauth2 (~> 2.0)
@@ -126,6 +138,7 @@ DEPENDENCIES
rubyzip (~> 3.0) rubyzip (~> 3.0)
sinatra (~> 4.2) sinatra (~> 4.2)
sinatra-contrib (~> 4.2) sinatra-contrib (~> 4.2)
sqlite3 (~> 2.10)
CHECKSUMS CHECKSUMS
anonymous_loader (0.1.5) sha256=c96a4a1b5f49f320037fae63e931ac15b3823686e4f0ee6f24f75a0ade4227cb anonymous_loader (0.1.5) sha256=c96a4a1b5f49f320037fae63e931ac15b3823686e4f0ee6f24f75a0ade4227cb
@@ -133,6 +146,7 @@ CHECKSUMS
base64 (0.3.0) sha256=27337aeabad6ffae05c265c450490628ef3ebd4b67be58257393227588f5a97b base64 (0.3.0) sha256=27337aeabad6ffae05c265c450490628ef3ebd4b67be58257393227588f5a97b
bigdecimal (4.1.3) sha256=61ebe1e5e559bdc3cc6f2c0ee7f427321fc838f59611c294356eb04d6e21cf66 bigdecimal (4.1.3) sha256=61ebe1e5e559bdc3cc6f2c0ee7f427321fc838f59611c294356eb04d6e21cf66
bundler (4.0.20) sha256=7978a8ac648767f5e635bc522445b79e80a52b907a39a36c2d8085ed6bc762ae bundler (4.0.20) sha256=7978a8ac648767f5e635bc522445b79e80a52b907a39a36c2d8085ed6bc762ae
csv (3.3.7) sha256=15a3f16f6628da8664d455eb634e7f22031bcf53044923caf56975109e71b9f8
domain_name (0.6.20260902) sha256=4fac7f8e0a77dc85ec02f6534fdeff38e143d434ab8a86528fe68ca5bc45a042 domain_name (0.6.20260902) sha256=4fac7f8e0a77dc85ec02f6534fdeff38e143d434ab8a86528fe68ca5bc45a042
drb (2.2.3) sha256=0b00d6fdb50995fe4a45dea13663493c841112e4068656854646f418fda13373 drb (2.2.3) sha256=0b00d6fdb50995fe4a45dea13663493c841112e4068656854646f418fda13373
faraday (2.15.1) sha256=8708154deda739c5e86cc42b74960e23e8491fce0eba9e11639a6a34b1ac288f faraday (2.15.1) sha256=8708154deda739c5e86cc42b74960e23e8491fce0eba9e11639a6a34b1ac288f
@@ -155,7 +169,7 @@ CHECKSUMS
listen (3.10.0) sha256=c6e182db62143aeccc2e1960033bebe7445309c7272061979bb098d03760c9d2 listen (3.10.0) sha256=c6e182db62143aeccc2e1960033bebe7445309c7272061979bb098d03760c9d2
logger (1.7.0) sha256=196edec7cc44b66cfb40f9755ce11b392f21f7967696af15d274dde7edff0203 logger (1.7.0) sha256=196edec7cc44b66cfb40f9755ce11b392f21f7967696af15d274dde7edff0203
minitest (6.1.0) sha256=ff373595aa8888631e8a5463986a76b3845346ae6d7fa46e139c1633d418076e minitest (6.1.0) sha256=ff373595aa8888631e8a5463986a76b3845346ae6d7fa46e139c1633d418076e
multi_json (1.21.1) sha256=e6126a31808e3b4d19f483c775ceac34df190dffa62adfb63a165ee14ba68080 multi_json (1.21.2) sha256=245531eaf54bdba57aba515ff08b4503505c5e09911daa89c5a561e2f85bea8e
multi_xml (0.9.1) sha256=7ce766b59c17241ed62976caeae1fae9b2431b263398c35396239a68c4a64e57 multi_xml (0.9.1) sha256=7ce766b59c17241ed62976caeae1fae9b2431b263398c35396239a68c4a64e57
mustermann (3.1.1) sha256=4c6170c7234d5499c345562ba7c7dfe73e1754286dcc1abb053064d66a127198 mustermann (3.1.1) sha256=4c6170c7234d5499c345562ba7c7dfe73e1754286dcc1abb053064d66a127198
net-http (0.10.0) sha256=1a2ff6e37a05724973c43f2bf7bf105f59c36a4cd0a7e9b1c021a0a566987c27 net-http (0.10.0) sha256=1a2ff6e37a05724973c43f2bf7bf105f59c36a4cd0a7e9b1c021a0a566987c27
@@ -163,19 +177,29 @@ CHECKSUMS
nio4r (2.7.5) sha256=6c90168e48fb5f8e768419c93abb94ba2b892a1d0602cb06eef16d8b7df1dca1 nio4r (2.7.5) sha256=6c90168e48fb5f8e768419c93abb94ba2b892a1d0602cb06eef16d8b7df1dca1
oauth2 (2.1.0) sha256=69925a45030c231cdca3ef4a54a8e848e5319f12c3fdbbfa5065dfbeb4efe835 oauth2 (2.1.0) sha256=69925a45030c231cdca3ef4a54a8e848e5319f12c3fdbbfa5065dfbeb4efe835
prism (1.9.0) sha256=7b530c6a9f92c24300014919c9dcbc055bf4cdf51ec30aed099b06cd6674ef85 prism (1.9.0) sha256=7b530c6a9f92c24300014919c9dcbc055bf4cdf51ec30aed099b06cd6674ef85
puma (8.0.2) sha256=c8ed871dfbbe66448ea9ffd46692342d9804d4071522b52b5331b7b6e7b686fb puma (8.1.4) sha256=71859def3f0e055cd10307b608eb629b58d318b38af2e6fbb3aa6f8846c4b912
rack (3.2.8) sha256=1fecc85e463ebc7a2a945fff829ffcd549babeb1556384796fad946c28dc4ec7 rack (3.2.8) sha256=1fecc85e463ebc7a2a945fff829ffcd549babeb1556384796fad946c28dc4ec7
rack-protection (4.2.1) sha256=cf6e2842df8c55f5e4d1a4be015e603e19e9bc3a7178bae58949ccbb58558bac rack-protection (4.2.2) sha256=0e75764dae462c4041544452ce568bb1f1ced556b791cd32ac479d0781065a99
rack-session (2.1.2) sha256=595434f8c0c3473ae7d7ac56ecda6cc6dfd9d37c0b2b5255330aa1576967ffe8 rack-session (2.1.2) sha256=595434f8c0c3473ae7d7ac56ecda6cc6dfd9d37c0b2b5255330aa1576967ffe8
rake (13.4.2) sha256=cb825b2bd5f1f8e91ca37bddb4b9aaf345551b4731da62949be002fa89283701 rake (13.4.2) sha256=cb825b2bd5f1f8e91ca37bddb4b9aaf345551b4731da62949be002fa89283701
rb-fsevent (0.11.2) sha256=43900b972e7301d6570f64b850a5aa67833ee7d87b458ee92805d56b7318aefe rb-fsevent (0.11.2) sha256=43900b972e7301d6570f64b850a5aa67833ee7d87b458ee92805d56b7318aefe
rb-inotify (0.11.1) sha256=a0a700441239b0ff18eb65e3866236cd78613d6b9f78fea1f9ac47a85e47be6e rb-inotify (0.11.1) sha256=a0a700441239b0ff18eb65e3866236cd78613d6b9f78fea1f9ac47a85e47be6e
rerun (0.14.0) sha256=996a5af2b2b34dcb30146c6c728addab9113e07c119003370daa9bf27feb88fd rerun (0.14.0) sha256=996a5af2b2b34dcb30146c6c728addab9113e07c119003370daa9bf27feb88fd
rexml (3.4.4) sha256=19e0a2c3425dfbf2d4fc1189747bdb2f849b6c5e74180401b15734bc97b5d142 rexml (3.4.5) sha256=65533089925a7cdfd416ba865d44f5bb1d13e106a3d7f2551de678e7bcd3be24
rubyzip (3.7.0) sha256=65c19294da75297a939006f3516deacc33185fbd721ff1954f7a231db6d3e121 rubyzip (3.7.1) sha256=483aa0f698822a290c0edf2aee6f41bc80870878cb5cd74af03b48d006c85e9e
sinatra (4.2.1) sha256=b7aeb9b11d046b552972ade834f1f9be98b185fa8444480688e3627625377080 sinatra (4.2.2) sha256=3a0e63c600eb65d7ad6fa0d597a9533f2870d1862cc63ab7b0f7f0ad449ad42f
sinatra-contrib (4.2.1) sha256=10d091c944d268aa910c618ea40a3c3ebe0533e6e32990d84af92235a3d26b4a sinatra-contrib (4.2.2) sha256=3d629cfb3647e363cfca6609d0dcde63aa45db664645fe947f0eeddb9cca1620
snaky_hash (2.0.9) sha256=e93e6ec80632f8c8c4a3fe6e25d51eaef253e0e58dc7100f0f8370320feb3128 snaky_hash (2.0.9) sha256=e93e6ec80632f8c8c4a3fe6e25d51eaef253e0e58dc7100f0f8370320feb3128
sqlite3 (2.10.2-aarch64-linux-gnu) sha256=e9aea2c2b3476fc875dd8a89313a9a2862818519c0186bfb5b56d6f57bb08d98
sqlite3 (2.10.2-aarch64-linux-musl) sha256=4986fc40cdf21342362b72a941df28e95cfe0e644f3ad2532d948b157c39dbee
sqlite3 (2.10.2-arm-linux-gnu) sha256=762f609ef891463226b472d3df66aea84d5466ff4376d3ccf4a059718c4ce9c9
sqlite3 (2.10.2-arm-linux-musl) sha256=833623eaf1157b1b85d1c0830e3e8f9beb3bb95a9bec3d252f20557a50e9803a
sqlite3 (2.10.2-arm64-darwin) sha256=5b0d235ea037e6dcd1b8387a19d73be571917db9f93044d35741cf933a21a37d
sqlite3 (2.10.2-x86-linux-gnu) sha256=46a02a29e9ae452824082388be5c24fd26f133b14bdd268610c6aa9a8d924c44
sqlite3 (2.10.2-x86-linux-musl) sha256=38980cf01eb2e4ac1c0755964d60b3d743ccf00686798a626bab852ff4cd3d1e
sqlite3 (2.10.2-x86_64-darwin) sha256=fd2c67b49d313031af112e172c83ab321681a2b4996bf882eefac50be7bea08f
sqlite3 (2.10.2-x86_64-linux-gnu) sha256=ca92731ab464df9cae503fa1a439a549e2724f6953c8c05a7769b59366e38f15
sqlite3 (2.10.2-x86_64-linux-musl) sha256=b9f8fc62f3e0eb8966b41de251b492b4c8e9d1b23559beb6e150ad7f8d590941
tilt (2.9.0) sha256=da5735d0280bba96e9a91041bb14aee435ccad5c17b0fa519249ae543d9aa3a5 tilt (2.9.0) sha256=da5735d0280bba96e9a91041bb14aee435ccad5c17b0fa519249ae543d9aa3a5
timeout (0.6.1) sha256=78f57368a7e7bbadec56971f78a3f5ecbcfb59b7fcbb0a3ed6ddc08a5094accb timeout (0.6.1) sha256=78f57368a7e7bbadec56971f78a3f5ecbcfb59b7fcbb0a3ed6ddc08a5094accb
uri (1.1.2) sha256=89292e98eabbef6248b0a0ed5e7e398e152f83f17560023a6d94a7f492b169fb uri (1.1.2) sha256=89292e98eabbef6248b0a0ed5e7e398e152f83f17560023a6d94a7f492b169fb
+1 -1
View File
@@ -13,7 +13,7 @@ Early scaffold. The web application serves a vector map (MapLibre GL
JS), with an online style and an optional offline style backed by a local JS), with an online style and an optional offline style backed by a local
PMTiles file, an animated RainViewer radar overlay, GPX PMTiles file, an animated RainViewer radar overlay, GPX
upload/display (points and tracks, organized in folders), and a live upload/display (points and tracks, organized in folders), and a live
position marker from a local GNSS receiver via gpsd. position marker from the car's GNSS receiver (over CAN, to come).
== Requirements == Requirements
+28
View File
@@ -40,6 +40,34 @@ namespace :hiking do
end end
end end
namespace :places do
desc "Build the offline place-search index (data/places/<CODE>.sqlite) from every already-downloaded " \
"Geofabrik extract in data/geofabrik_cache, without a full offline build. Countries whose index is " \
"already newer than their extract are skipped. Usage: rake places:index [MAPTOOL_DATA_DIR=data]"
task :index do
require_relative "lib/maptool/pmtiles_builder"
data_dir = ENV.fetch("MAPTOOL_DATA_DIR", File.join(__dir__, "data"))
puts "Indexing places from #{data_dir}/geofabrik_cache..."
countries = Maptool::PmtilesBuilder.index_cached_places(data_dir)
puts "Place index available for: #{countries.empty? ? "(none)" : countries.join(", ")}"
end
end
namespace :library do
desc "Migrate data/gpx/ files into the library (runs on first start anyway; idempotent)"
task :migrate do
require_relative "lib/maptool/library"
data_dir = ENV.fetch("MAPTOOL_DATA_DIR") { File.join(__dir__, "data") }
library = Maptool::Library.new(File.join(data_dir, "library.sqlite"),
gpx_store: Maptool::GpxStore.new(File.join(data_dir, "gpx")),
sources_dir: File.join(data_dir, "library", "sources"))
library.migrate
puts "Library at rev #{library.rev}"
end
end
namespace :gpx do namespace :gpx do
desc "Backfill properties.id on Note-category features saved before edit/delete (and its id targeting) existed" desc "Backfill properties.id on Note-category features saved before edit/delete (and its id targeting) existed"
task :backfill_note_ids do task :backfill_note_ids do
+555 -5
View File
@@ -10,13 +10,19 @@ independence from connectivity.
* [x] Offline vector tiles (PMTiles/MBTiles) for Europe/world via Planetiler or MapTiler — Geofabrik per-country extracts, `osmium merge`, Planetiler's default OpenMapTiles profile straight to PMTiles (`lib/maptool/pmtiles_builder.rb`); offline now shares the exact same style/palette as online (`ONLINE_STYLE_PATCH`) instead of a separate protomaps-schema theme * [x] Offline vector tiles (PMTiles/MBTiles) for Europe/world via Planetiler or MapTiler — Geofabrik per-country extracts, `osmium merge`, Planetiler's default OpenMapTiles profile straight to PMTiles (`lib/maptool/pmtiles_builder.rb`); offline now shares the exact same style/palette as online (`ONLINE_STYLE_PATCH`) instead of a separate protomaps-schema theme
* [x] Shaded relief / DEM layer — hillshade toggle in the sidebar, sourced from public Terrarium tiles online; reads `data/terrain.pmtiles` for offline if one's been generated (see docs/development.adoc), otherwise the toggle is online-only for now * [x] Shaded relief / DEM layer — hillshade toggle in the sidebar, sourced from public Terrarium tiles online; reads `data/terrain.pmtiles` for offline if one's been generated (see docs/development.adoc), otherwise the toggle is online-only for now
** [ ] Terrain slope readout for parking (numeric, not just visual shading)
* [ ] Contour lines from OSM for hikes and mountain passes * [ ] Contour lines from OSM for hikes and mountain passes
* [x] Hiking trail overlay — Waymarked Trails raster tiles online (`public/js/hiking_trails.js`), colored per-route by the OSM `colour` tag they already render (the KST/KČT paint-blaze colors in Slovakia/Czechia, plain red elsewhere). Click queries a one-off Overpass `around` search (racing 3 public mirrors) for the route's name/colour/network/operator/distance * [x] Hiking trail overlay — Waymarked Trails raster tiles online (`public/js/hiking_trails.js`), colored per-route by the OSM `colour` tag they already render (the KST/KČT paint-blaze colors in Slovakia/Czechia, plain red elsewhere). Click queries a one-off Overpass `around` search (racing 3 public mirrors) for the route's name/colour/network/operator/distance
** [x] Offline copy wired in for real, no custom Planetiler profile needed — `Maptool::HikingTrails` (`lib/maptool/hiking_trails.rb`) runs `osmium tags-filter r/route=hiking` + `add-locations-to-ways` + `cat -f opl` against the *same* per-country Geofabrik `.osm.pbf` already downloaded for `offline.pmtiles`, no new download. One `data/hiking_trails/<CODE>.geojson` per country (not one combined file), generated as the last step of every offline build and cached like `geofabrik_cache` (skipped once already newer than its source PBF) — a many-country selection no longer means one giant file, since `GET /api/hiking-trails` lists available countries and the Overlays panel's own checklist only fetches `GET /tiles/hiking_trails/<CODE>.geojson` for whichever ones get ticked. Offline click uses a local `queryRenderedFeatures` hit-test instead of Overpass — instant, no network. See docs/development.adoc ** [x] Offline copy wired in for real, no custom Planetiler profile needed — `Maptool::HikingTrails` (`lib/maptool/hiking_trails.rb`) runs `osmium tags-filter r/route=hiking` + `add-locations-to-ways` + `cat -f opl` against the *same* per-country Geofabrik `.osm.pbf` already downloaded for `offline.pmtiles`, no new download. One `data/hiking_trails/<CODE>.geojson` per country (not one combined file), generated as the last step of every offline build and cached like `geofabrik_cache` (skipped once already newer than its source PBF) — a many-country selection no longer means one giant file, since `GET /api/hiking-trails` lists available countries and the Overlays panel's own checklist only fetches `GET /tiles/hiking_trails/<CODE>.geojson` for whichever ones get ticked. Offline click uses a local `queryRenderedFeatures` hit-test instead of Overpass — instant, no network. See docs/development.adoc
* [x] Overpass/OSM scripts to extract POIs (drinking water, dump stations, LPG, public toilets, laundromats, shops, springs) — `rake overpass:pois`, see docs/development.adoc; writes a `.geojson` to drop in `data/gpx/` or upload. Also runnable from inside the app itself now, see the import plugins entry below (`plugins/overpass-pois` wraps this same query). Each category now carries a real `POI_ICONS` glyph and color (not p4n2gpx's plain red marker) plus a popup description built from opening_hours/operator/website tags * [x] Overpass/OSM scripts to extract POIs (drinking water, dump stations, LPG, public toilets, laundromats, shops, springs) — `rake overpass:pois`, see docs/development.adoc; writes a `.geojson` to drop in `data/gpx/` or upload. Also runnable from inside the app itself now, see the import plugins entry below (`plugins/overpass-pois` wraps this same query). Each category now carries a real `POI_ICONS` glyph and color (not p4n2gpx's plain red marker) plus a popup description built from opening_hours/operator/website tags
* [x] Import plugins: a pluggable way to add more data sources (Park4Night, iOverlander, Freecampsites, ...) without their scrapers necessarily living in this (public) repo — sidebar icon (logged in only) lists whatever's under `plugins/`, "Run for this area" uses the current map viewport as the bbox, no separate area-picker needed. Contract: a `plugin.json` manifest + a script that reads `--south`/`--west`/`--north`/`--east` and prints a GeoJSON `FeatureCollection` to stdout (`lib/maptool/plugins.rb`, `GET /api/plugins`, `POST /api/plugins/:name/run`) — output saved the same way an upload would be. `plugins/overpass-pois` ships as the reference example; a private/ToS-sensitive scraper just drops its own directory in locally and is never `git add`ed * [x] Import plugins: a pluggable way to add more data sources (Park4Night, iOverlander, Freecampsites, ...) without their scrapers necessarily living in this (public) repo — sidebar icon (logged in only) lists whatever's under `plugins/`, "Run for this area" uses the current map viewport as the bbox, no separate area-picker needed. Contract: a `plugin.json` manifest + a script that reads `--south`/`--west`/`--north`/`--east` and prints a GeoJSON `FeatureCollection` to stdout (`lib/maptool/plugins.rb`, `GET /api/plugins`, `POST /api/plugins/:name/run`) — output saved the same way an upload would be. `plugins/overpass-pois` ships as the reference example; a private/ToS-sensitive scraper just drops its own directory in locally and is never `git add`ed
** [x] Park4Night — private plugin (`data/plugins/p4n2gpx/`, outside this repo per the "ToS-sensitive scraper" note above); iOverlander/Freecampsites still open, same story ** [x] Park4Night — private plugin (`data/plugins/p4n2gpx/`, outside this repo per the "ToS-sensitive scraper" note above); iOverlander/Freecampsites still open, same story
** [x] Along the planned route (2026-12-01): "Along the trip's route" ± 1/2/5/10/20 km in the
plugins panel; a plugin with `"route": true` gets `--route=<GeoJSON file> --corridor-km=N`
(overpass-pois: Overpass' `around:` over the thinned route; p4n2gpx: circles along it,
`lib/maptool/corridor.rb`), points further off dropped by maptool, into the recorded trip's
folder when one runs. Plugin settings (`"settings"` in plugin.json: a login cookie) set in the
panel, kept in `data/plugin_settings.json`, given to the command as env vars — p4n2gpx's
`P4N_SESSION_COOKIE` (park4night's login is behind reCAPTCHA: a browser's Cookie header)
** [x] A private plugin's own dependencies now have somewhere to live too: `data/plugins/` is under the persistent `data/` bind mount (survives a redeploy, unlike `build/`), and `docs/deployment.adoc` documents the convention ** [x] A private plugin's own dependencies now have somewhere to live too: `data/plugins/` is under the persistent `data/` bind mount (survives a redeploy, unlike `build/`), and `docs/deployment.adoc` documents the convention
* [x] Kiwix/ZIM offline Wikipedia linked to POI GPS coordinates — proxied through this app (`GET /kiwix/*` in app.rb) rather than a direct link to kiwix-serve — production sits behind a reverse proxy that only forwards to this app, so no address exists for a browser to reach kiwix-serve at directly; kiwix-serve runs with `--urlRootLocation=/kiwix` so its own emitted links already match. `KIWIX_URL` + `GET /api/kiwix` reachability check, same optional-integration pattern as offline.pmtiles/terrain.pmtiles; `docker-compose.yaml` now runs a `kiwix` service, ZIM not included (see docs/development.adoc for where to get one) * [x] Kiwix/ZIM offline Wikipedia linked to POI GPS coordinates — proxied through this app (`GET /kiwix/*` in app.rb) rather than a direct link to kiwix-serve — production sits behind a reverse proxy that only forwards to this app, so no address exists for a browser to reach kiwix-serve at directly; kiwix-serve runs with `--urlRootLocation=/kiwix` so its own emitted links already match. `KIWIX_URL` + `GET /api/kiwix` reachability check, same optional-integration pattern as offline.pmtiles/terrain.pmtiles; `docker-compose.yaml` now runs a `kiwix` service, ZIM not included (see docs/development.adoc for where to get one)
** [x] Replaced the old per-popup "Nearby on Wikipedia" link (one POI at a time, easy to miss) with a standalone "Wikipedia" layer under Tracks & Points — a live `GET /api/kiwix/nearby` refetch on every pan/zoom, not a saved file. kiwix-serve's own geo search never echoes back a result's coordinates, so `Maptool::Kiwix.nearby` fetches each matching article's own page too and reads its `<meta name="geo.position">` tag — verified against the real production ZIM (~1.6s for a 30-result page; tried parallelizing those fetches with threads, no measured gain, kept sequential) ** [x] Replaced the old per-popup "Nearby on Wikipedia" link (one POI at a time, easy to miss) with a standalone "Wikipedia" layer under Tracks & Points — a live `GET /api/kiwix/nearby` refetch on every pan/zoom, not a saved file. kiwix-serve's own geo search never echoes back a result's coordinates, so `Maptool::Kiwix.nearby` fetches each matching article's own page too and reads its `<meta name="geo.position">` tag — verified against the real production ZIM (~1.6s for a 30-result page; tried parallelizing those fetches with threads, no measured gain, kept sequential)
@@ -31,10 +37,12 @@ independence from connectivity.
** [ ] Point detail/sidepanel: black header banner with white location name and an NPS pictogram in the corner; amenities (water, waste, power, slope) shown as a pictogram grid, no extra text; action buttons for "route here" (Valhalla), "start leveling", "save offline" ** [ ] Point detail/sidepanel: black header banner with white location name and an NPS pictogram in the corner; amenities (water, waste, power, slope) shown as a pictogram grid, no extra text; action buttons for "route here" (Valhalla), "start leveling", "save offline"
** [x] Filter panel as a "Unigrid Matrix" — an icon grid to toggle categories on/off, styled like the legend on an official NPS paper map, instead of plain dropdowns ** [x] Filter panel as a "Unigrid Matrix" — an icon grid to toggle categories on/off, styled like the legend on an official NPS paper map, instead of plain dropdowns
* [ ] Custom vector style (MVT/MapLibre) using the NPS color palette — muted natural tones for forests, water, and contours — so POIs and routes stand out at high zoom * [ ] Custom vector style (MVT/MapLibre) using the NPS color palette — muted natural tones for forests, water, and contours — so POIs and routes stand out at high zoom
** [ ] Landuse & protections: distinct styling for national parks, nature reserves (translucent green/gray-green), military zones, and private land (important for wild camping) ** [x] Landuse & protections: national parks keep the flat Park Tiles sage, other protected areas (nature reserves, landscape areas, …) a translucent gray-green with a dashed edge, strict reserves / natural monuments a step darker than landscape areas (substring of the class again, `STRICT_RESERVE`), military areas red-hatched (`protectedAreasAndTextures` in `public/js/map_themes.js`). National parks are told apart by substring of OpenMapTiles' park `class` (the OSM protection_title when there is one, so it's per-language)
** [ ] OpenTopoMap-style `fill-pattern` texture for forest (tree icons) and meadow/pasture (grass texture) landcover, instead of flat fill colors — Liberty's own sprite (`public/vendor/liberty-sprite/`) only has a `wetland` dot pattern, no tree/grass, so this needs custom pattern images added to the sprite sheet; works offline and online alike since it's just a style/sprite change, unlike pulling in OpenTopoMap's own raster tiles (online-only, restrictive tile-usage policy, wouldn't match the NPS palette) *** [ ] Private land — not in the OpenMapTiles schema (no access tags on landuse); needs our own Planetiler layer or an Overpass overlay
** [x] OpenTopoMap-style `fill-pattern` texture for forest (tree icons) and meadow/pasture (grass texture) landcover, instead of flat fill colors — Liberty's own sprite (`public/vendor/liberty-sprite/`) only has a `wetland` dot pattern, no tree/grass, so this needs custom pattern images added to the sprite sheet; works offline and online alike since it's just a style/sprite change, unlike pulling in OpenTopoMap's own raster tiles (online-only, restrictive tile-usage policy, wouldn't match the NPS palette) — done without touching the sprite: the patterns are drawn on a canvas on MapLibre's `styleimagemissing` (`patternImage`), grass from 13, scrub / dwarf pine (kosodrevina, `subclass=scrub`) its own tint + bushes from 11, with night variants. Forest texture dropped after a field test: too busy, and OSM rarely says broadleaf/needleleaf anyway
** [x] Elevation-tinted terrain — a `color-relief` layer (hypsometric tint, this app's own green→brown→gray palette) under the hillshade layer, same "Terrain shading" toggle ** [x] Elevation-tinted terrain — a `color-relief` layer (hypsometric tint, this app's own green→brown→gray palette) under the hillshade layer, same "Terrain shading" toggle
** [x] Road hierarchy: clearly distinguish paved roads from unpaved/gravel/track — critical for knowing if the camper can get there ** [x] Road hierarchy: clearly distinguish paved roads from unpaved/gravel/track — critical for knowing if the camper can get there
** [x] Park Tiles "Standard" look as the base map — `PARK_TILES_PATCH` in `public/js/map_themes.js`, colors sampled from the Park Tiles legend swatches (values in `docs/nps-resources.adoc`): flat sage park areas above landcover with a tint band inside the boundary, cream land, Park Tiles road colors. Replaced the looser `ONLINE_STYLE_PATCH` palette (briefly both, switchable, to compare); map legend at `/symbols.html`
== Main menu reorganization (4 modules) == Main menu reorganization (4 modules)
@@ -59,21 +67,561 @@ independence from connectivity.
** [x] Fixed: the Unigrid Matrix category filter only re-sliced the *points* source (`_applyCategoryFilter`) — toggling the "Note" category off hid point notes but not polygon/line ones sharing that category. `_linesByPath` now tracks those alongside `_pointsByPath`, re-sliced/scanned the same way ** [x] Fixed: the Unigrid Matrix category filter only re-sliced the *points* source (`_applyCategoryFilter`) — toggling the "Note" category off hid point notes but not polygon/line ones sharing that category. `_linesByPath` now tracks those alongside `_pointsByPath`, re-sliced/scanned the same way
* [ ] Offline satellite tile caching (e.g. ESRI) for a selected route area — key for judging surface quality and obstacles when wild camping * [ ] Offline satellite tile caching (e.g. ESRI) for a selected route area — key for judging surface quality and obstacles when wild camping
== Search
* [x] Unified search box — one query across every data source, not just what's currently on the map. `GET /api/search` (`lib/maptool/search.rb`) for local sources, online ones queried from the browser (`public/js/search.js`)
** [x] Every layer under Tracks & Points (GPX, FIT, GeoJSON, notes, plugin output) and offline hiking trails — shown *and* hidden ones. Matches name + description, case/diacritics-insensitive ("kosice" finds "Košice"); parsed features cached in memory per file by mtime
** [x] Offline vector data — every named OSM object in each country's Geofabrik `.osm.pbf` (`osmium tags-filter nwr/name` + `osmium export -f geojsonseq`) into a SQLite FTS5 index, `data/places/<CODE>.sqlite` (`lib/maptool/places.rb`), built as the last offline-build step ("indexing places") and cached by mtime like hiking trails. Prefix + diacritics-insensitive matching, street segments merged per ~2 km cell; named buildings, land-use areas, `place=locality`/`isolated_dwelling` and objects with no recognized kind dropped (a shop in a building stays), names searchable without their apostrophes ("mcdonalds") and by `brand`. `Places::SCHEMA_VERSION` makes `rake places:index` rebuild older indexes by itself
** [x] Every result shows where it was found (layer file / "Hiking trails SK" / "Online · Nominatim"); clicking one zooms to it (fitBounds for a track) and switches its layer on if it was off
** [x] Source checklist in the search panel (all on by default), re-runs the search on change
** [x] Online sources pluggable — one more entry in search.js's `SOURCES`; Nominatim already in, its failure only adds a "no connection" line under the local results
** [x] Kiwix as a source — full-text search of the ZIM (`Kiwix.search`), each hit's coordinates read from its page like the Wikipedia layer does; clicking opens the article (and jumps to it when it has coordinates)
** [x] Nearest first — every result carries its distance from the map center and the list is sorted by it across all sources; settlements count as closer (city x0.01 … suburb x0.3, `Places::DISTANCE_WEIGHT`) so a town's name still finds the town. Nominatim gets the visible area as a (non-restricting) `viewbox`
== Sync with OsmAnd / Locus / mapy.com
* [x] Installable PWA with a share target — `public/manifest.webmanifest`, `public/sw.js` parks files shared from Android's share sheet (OsmAnd, Locus, mapy.com — the last has no API at all), `public/js/share_import.js` offers to import them into a Tracks & Points folder (login required, files wait until then)
* [x] Item-based library replacing the file-based `GpxStore`, phase 1 — `lib/maptool/library.rb`, design in `docs/library-design.adoc`; old files migrated as layers in subfolders
* [x] Library phase 2 — rename/recolor tracks, routes and layers, rename and move (drag) folders, split a migrated layer into items (its notes become items, keeping their ids)
* [x] Change feed + GPX export flavors for OsmAnd/Locus — `/api/library/changes`, folder menu → Export for Locus (GPX) / OsmAnd (zip)
* [ ] Android sync client (MapTool → apps first; apps → MapTool only if their APIs can list data)
== Tablet-friendly planning UI
The app is already reachable from the internet behind login, so a tablet is enough to
plan from — the server does the heavy lifting. The UI is built for a mouse today.
* [x] Touch targets ≥ 44 px (tree rows, panel buttons, icon grids) — on the Pad7 everything is big enough (2026-12-03), nothing more to do
** [x] Route markers: an invisible 48px grab area around the dot (a finger missed the 26px dot and panned the map)
** [x] Tracks & Points open/close arrows: a 24×28 px hit area, 36×40 on touch screens
** [x] Notes can be moved (Move in the popup: drag the marker or tap the new spot), and new/edited points get an icon, a color and B/I buttons
* [x] Nothing reachable only by hover — tooltips and flyouts must open on tap too
* [x] A touch substitute for the Alt+click debug inspector (e.g. long-press) — the long press is a contextmenu: what's here
* [x] Side panels as an overlay in portrait instead of a pinned column — under 640 px the pin is ignored and the panel floats over the map at full width (a pinned 300 px panel left the phone a sliver of map); a real bottom sheet still open
* [x] Driving mode (field test in the car, 2026-11): tiny icons and lists can't be hit while driving — a separate big-button UI for the few things needed on the road (navigate/follow, night mode, zoom, layer presets) rather than enlarging every planning panel. Done: "Drive" in the topbar (`driving.js`), per device — Follow, zoom, 2D/3D, night, route overview, exit down the left side; the sidebar and panels hidden
** [x] Layer presets on the driving bar (Layers: Road / Off-road / Overnight, + Keep)
** [x] The bar after the research (docs/design.adoc, "Buttons while driving"): four buttons
(zoom ±, view, overview), Follow and "Back to the position" one button shown only when not
following, 76×76 px; night and exit off the bar
** [~] The Grid of the Design canvas (docs/design.adoc, "Layout: a grid"), 2026-12-03: the page
as 16 × 10 cells, the map 13 × 8, nothing over it; which cell shows what is the screen
profile `public/drive/road.json` (`{area, widget, …}`, to be edited in the app later).
Done: manoeuvre, speed, limit, altitude, time, sun, status (online, rec); next stop, km/ETA
to it and to the end; elevation of the next 10 km; compass; keys Trip, Search, Menu (the
whole route, leave), − + 3D Follow, day/dusk/night; a menu in the right 7 × 8, the map
9 × 8; the dashboard polls for the grid without its overlay. Trip and Search as GridTrip /
GridSearch: the menu area as cells (a stop a row: name over 3, ✓ ↑ ↓ ✕ one each; recording
on top, + stop / start from the car at the foot), results a row each with their pins on the
map (saved cyan, places amber), "← Back to the stops". Points and Layers as GridPoints /
GridLayers (`drive_menus.js`): Points the library nearest the car (`/api/search` with no
words and a center lists every saved feature nearest first), Ahead (within 2 km of the
route still to drive, of those 50), Shown, or one folder at a time; an eye per row, + a
point as a stop. Layers the On the map panel's own checkboxes and Online | Offline, the ones
on first; presets Road / Off-road / Overnight, + Keep saves what's on into one (per
device). Terrain as GridTerrain (⛰): roll and pitch dials (amber / red, the max held until
Reset), heading, climb in 300 m and side slope 50 m ahead (DEM along the course), the
route's next 2 km, Level here (can.json's levelling action, two taps), Road view; on by
itself on an unpaved surface (`/api/road` now gives Valhalla's `surface`, off a route only)
or roll / pitch past 10° for 10 s (not while simulated: the DEM's slope on a hillside road
is the hill's), back after 2 km of paved road; Menu: opens and closes by itself / opens and
stays (the inclinometer all along) / by hand; the surface in its head. The limit as a sign
in the speed field (the next one under it), the speed red past it. Still to do: the surface while
on a route (along the route's edges), the lanes in the manoeuvre cell, the profile served from `data/` once the editor exists
** [x] The status pill above the car (2026-12-04, pypilot's note in the canvas' SidePanel): ● REC while the trip is recorded, estimated (a tunnel) / no fix; hidden when all is well (`gnss.js` `_showTag`)
** [ ] Softkeys: the CAN keypad's labels on the screen edge next to its keys (G1000 style)
** [x] The Trip menu beside the map, not over it (Android Auto's side panel, seen again in
signalk-pypilot-newui): the map narrower, its buttons kept, its center (follow, crosshair,
overview) in what's seen — the car was hidden under the panel before (2026-12-02)
** [x] Driving menu, Trip: the stops as 76 px rows (tap to look, ↑ ↓ ✕), a stop at the
crosshair, the start moved to the car (`driving.js`, `RoutePanelControl#stops` & co.)
Then: search (saved points + offline places, nearest the crosshair first, + adds), each
leg's km and time and the total; passed stops dimmed and still editable — a reroute marks
them `passed` (kept in the trip, not routed) instead of dropping them, ✓ marks one by
hand (a stop missed out: add it, move it up with ↑, ✓)
** [ ] The trip as plan + log (2026-12-01): start → the server records the trip log (GNSS,
no screen needed) → stops added on or off the route (on foot: not routed, still the
trip's) → end → one library item: the planned route, the driven track, the points with
their visit times. A point's two properties apart: routed or not, and planned / visited
(at) / skipped — `passed` splits into them; visited by the track passing near or by hand
The car's GNSS stays in the car: on foot the log is the car standing. The walk from
whatever else carried a position — a Garmin LiveTrack session (already in), the MQTT
tracker, a LoRa/Meshtastic node later — or the watch's FIT imported afterwards (the
library reads FIT); else just the point, visited by hand
** [x] A trip is a library folder (Trips/<date name>): routes per activity, points, tracks (the
car's log, a watch's FIT, LiveTrack) in it; "Start trip" makes it the active one and
records the car's GNSS into it (saved as it goes), "End trip" closes it. Its pictogram:
the folder's `icon` — by hand (the notes' icon picker, POI_ICONS / NPS) or, unset, from its
points (the destination's, else the most common)
Done: `lib/maptool/trip_log.rb`, `GET/POST/DELETE /api/trip/log`, the Trip menu's
Start / End, the line really driven (`--route-driven`). Stored crash-safe like a FIT: an
append-only journal per trip (`data/trip_log/<started>.ndjson`, fsynced every 5 s, a torn
last line skipped), a restart picks the running trip up from it; the library's track built
from it every 5 min and at the end. Still to do: the pictogram, a walk from another device shown with it, visited points
** [x] The recording's days and export (the canvas' GridRecording, 2026-12-03): the Trip menu's
"Recording ▸" opens it — the running trip, else the last one: totals, the days (one log, the
days only cuts: stood ≥ 4 h, else 03:00; ✂ Cut here and Join kept as journal lines), ⌕ a day
on the map; Export the days ticked, a piece between draggable A–B markers or the whole trip as
one GPX (a track per day, times per point) or a .zip of a file per day, with the stops near
the line, the planned route, the stands (`lib/maptool/trip_days.rb`,
`/api/trip/log/days`, `/api/trip/log/export`). Not yet: renaming the trip there, the days
named by place (no reverse geocoding offline), moving a cut by hand
** [x] Colors: planned vs really driven — the planned route (magenta ahead, the part behind
thin and dashed) and the recorded track solid on top (`--route-driven`), docs/design.adoc
** [x] The menu while driving: showing routes and points, editing the trip — all of it on the
road, so simple: a few big tiles (Trip, Points, Layers, Search), one level deep, rows
≥ 76 px, a handful per screen, the action a big button (add a stop here / at a point,
skip the next one, move one up/down, show / hide a layer) — no drag, no hover, no small
text fields. Who: the navigator (co-driver) runs the whole UI and the trip's points on the
16" display; the driver only looks at a finished map on Android Auto, touching the 16"
only now and then — so it's simple for a moving car, not driver-distraction rules
* [x] Desktop (the Design canvas' Desktop, 2026-12-03): copy the position under the cursor
to the clipboard (a key or the right-click menu) — today only the map's center copies,
from the status bar, so the way around it is to put the center on the point first. Done: right
click / long press / Alt+click = what's here (the position, a click copies it; Route here, Add to
the trip, Save a point; the features' raw properties folded), C copies the position under the mouse
* [x] Desktop: the scale back over the map, not in the status bar
* [x] Night mode — topbar button cycles auto (sun below the horizon at the map center) / on / off. The map has its own night palette (`NightMap` in `public/js/map_themes.js`, switched live with setPaintProperty): dark blue-gray ground, roads a step lighter, muted ochre motorways, light-gray labels on dark halos; raster overlays dimmed, our own track/point colors kept
** [x] The rest of the UI is still one invert+dim filter — CSS color tokens and a real dark set instead
* [x] Tracker as a top-down vehicle (car / motorbike / bicycle from its icon) rotated by the GNSS course, kept while standing still; "Navigate" (tracker card or Overlays status) follows it heading-up, tilted 60°, vehicle in the lower third — panning by hand ends it
== NPS parks & maps
Prototype outside this repo in `~/Projects/NPS_Maps/` (`nps-maps.py` + a standalone map
finder `index.html`); background in `docs/nps-resources.adoc` ("The NPS mobile app's offline
downloads"). Data and features move here once settled.
* [x] NPS brochure maps as an overlay layer — "NPS park maps" in Overlays (`public/js/nps.js`):
park points and map footprints, a park search, a park's popup lists its maps; a georeferenced
one (289 of them) goes over the base map as an `image` source with four corners, with an
opacity slider. Data in `data/nps/` (`nps.json` index from `nps-maps.py web`, `overlay/`
JPEGs, `geotiff/`, `pdf/` — all 947 PDFs), served by `/api/nps` and `/nps/…`
* [x] Park finder — the overlay's park search + the popup's links (local PDF/GeoTIFF, NPS JPG)
* [ ] NPS campgrounds (and alerts) as points with our NPS icons — via the home NPS MCP server,
no API key of our own (its API key only lives in home-gitops' Gitea secrets)
* [ ] Export brochure maps as MBTiles (`gdal_translate -of MBTILES` + `gdaladdo`) for Locus /
OsmAnd — the official park map offline on the phone, with GPS position, no NPS app needed
== Nice to have (later) == Nice to have (later)
Deprioritized for now — revisit after the sections above land. Deprioritized for now — revisit after the sections above land.
=== Vanlife features === Vanlife features
* [ ] Offline routing (Valhalla/OSRM) with vehicle parameters (height, weight, width) * [ ] Offline routing with vehicle parameters (height, weight, width) — Valhalla in its own container, design in `docs/routing-design.adoc`
** [x] Phase 1: `valhalla` compose service (`bin/routing-service.sh`), builds from the offline map's extracts, "Offline routing" row in the Offline data panel
** [x] Phase 2: `/api/route`, vehicle profile, route panel, save a route to the library
** [x] Route points from search / GPS / a library point, reordering, re-editing a saved route
** [x] Phase 3: elevation profile from terrain.pmtiles, isochrones
* [ ] Solar calculator — sun path for location/date, shadows from surroundings, camper orientation * [ ] Solar calculator — sun path for location/date, shadows from surroundings, camper orientation
=== Vehicle dashboard & live data
maptool as the dashboard for the car/van too, not only the map. Idea stage. Most of the data
already reaches the home MQTT broker (`mqtt_ext`) from ESPHome nodes in `~/esphome`:
* [x] One MQTT subscriber in the maptool server — `lib/maptool/mqtt_client.rb` (stdlib MQTT
3.1.1, QoS 0, reconnects), `MQTT_URL`/`MQTT_USERNAME`/`MQTT_PASSWORD` (read-only broker
user), latest state in app.rb's `LIVE`, `GET /api/live`; the "Vehicle & ITS-G5" overlay
(`public/js/live.js`) polls it
* [x] Car position from the LTE GNSS tracker (`mcu-tracker/location`) — a badge with its age
and details; the last position stays (a parked tracker reports rarely)
** [x] Own "Tracker" overlay (ITS-G5 separate, Overlays grouped by category); name, icon and color
set in the overlay (server-side, `data/live/settings.json`); USB power / charging from
`mcu-tracker/binary_sensor/usb_power/state`; a floating info card (per-device on/off + opacity);
the trail of the last 1/2/4/8/24 h; optional logging to `data/live/tracker.jsonl`, which also
restores the trail after a restart (`lib/maptool/live_store.rb`)
** [ ] Export the logged trail (GPX / into the library)
* [ ] … also as a source for the GNSS control ("where is the car" / follow it)
* [x] ITS-G5: `mcu-its-g5.yaml` publishes the decoded header as JSON on `mcu-its-g5/decoded`
(1 Hz per station); stations on the map colored by type, DENM bigger and red, gone after 60 s
* [ ] Meshtastic nodes (each has GNSS) — incl. a running tracker to follow on the map. Not in
the broker today: the HA Meshtastic integration only makes `device_tracker` entities and
doesn't republish them. Options: read HA's REST API (`/api/states`, `device_tracker` with
coordinates; needs `HA_URL` + a read-only long-lived `HA_TOKEN`, and covers any other HA
tracker too), HA's `mqtt_statestream` (one topic per attribute — awkward), or MQTT with JSON
output on `rpi-meshtastic` itself (fights the HA integration over the single TCP API while
configuring, see home-gitops docs/embedded-services.adoc)
* [ ] Car CAN data (`mcu-car-can.yaml`, today over the native API to HA): add `mqtt:` like the
tracker; RPM, doors, parking brake, … in a dashboard panel
* [ ] IMU shocks along a drive as a map layer — road roughness / potholes colored by intensity
* [x] Native CAN in maptool (the van's final setup, MQTT is the stopgap): SocketCAN on any
number of interfaces (USB adapter, the board's own controller, `vcan0` for tests),
CANopen frame roles + heartbeat states, NMT start, signals decoded by `data/can.json`
(COB-ID/mask, byte/bit, type, scale/offset — `lib/maptool/can.rb`), `gnss.*` signals feed
the GNSS control, `GET /api/can`
** [ ] The container on the CAN bus: `can0` lives in the host's network namespace — either
`network_mode: host` for maptool (then kiwix/valhalla by localhost ports, not service
names) or a vxcan pair moved into the container's namespace by a host script
** [ ] The car-CAN → CANopen bridge's mapping (not decided yet) as signals in `data/can.json`;
a dashboard panel for the `car.*` signals
** [ ] Signals in `data/can.json`, after candinista (github.com/mikeypi/candinista, its
`config.yaml`) — for third-party devices whose conversion we can't change:
*** [ ] A sensor curve: `x_values` → `y_values`, linear interpolation between points (NTC
temperature senders, pressure sensors), instead of `scale` / `offset`
*** [ ] Multiplexed signals: one byte of the frame says which channel it carries (`mux_byte`,
`mux_value`; e.g. Haltech TPMS, wheel 1–4 on one ID)
*** [ ] Warning limits per signal (`low_warn`, `high_warn`): the value coloured on its tile
** [ ] A display node on the CANopen bus (`mcu-lvgl`, ESP32-8048S043, 4.3" 800×480, LVGL) with
its own switch screens — it only sends requests to the controller and draws the state the
controller reports, so it works with the Pi off. The look: Garmin style, picked in the Design
canvas (PanelGarmin: Switches, Power, Tanks, Settings; the status bar is the navigation)
** [x] The GNSS node's PDO layout as `gnss.*` signals — `mcu-stm32-xiao-c5-2` (node 0x21,
esphome-canopen), `data/can.json` in docs/deployment.adoc
** [x] `/can.html` diagnostics: interfaces, nodes (heartbeat, last EMCY, what they send),
decoded signals, every COB-ID (role, count, rate, last data)
** [x] The bus recorded on the server into ASAM MDF4 (`/trace.html`, `can-recorder/` in Rust,
`lib/maptool/can_recorder.rb`): every interface, a finished `.mf4` every 5 min in
`data/can_rec/` (a power cut loses at most the last segment), the CANedge `CAN_DataFrame`
layout — asammdf decodes it with a DBC (checked against candump: every frame, < 0.002 ms)
*** [ ] Checked with CSS Electronics' converters (mdf2csv) too, and in CANalyzer if at hand
*** [x] Old recordings cleaned up (data/can_rec grows ~85 MB an hour at 1000 frames/s): segments
older than `CAN_REC_KEEP_HOURS` (24 by default, 0 keeps all) go — diagnostics only
** [ ] Nodes describing themselves — no hand-written signals for our own nodes:
*** [x] esphome-canopen nodes over SDO: on a node's first heartbeat read its TPDOs
(`0x1800+n`:1 COB-ID, `0x1A00+n` mapping), each mapped entity's type (`0x2001`:N) and
metadata (`0x2000+0x10·N`: name, unit, min/max → the scale), the decoder built from that,
cached by the TPDO layout hash (`0x3002`:1, read again when it changes — after an OTA);
`can.json` keeps only aliases (a node's "Latitude" → `gnss.lat`) and foreign devices
(`lib/maptool/can_discovery.rb`, `Can::Sdo`; aliases with a unit conversion; node 0x21
reads in 2 s, its 14 signals match the hand-written scales)
*** [ ] `/can.html`: each described node's entities (name, unit, range, TPDO), from the cache
*** [ ] EDS (CiA 306) read from a node (`0x1021`) or a file, the same decoder from it — once the
ESPHome side generates EDS (proposal for mrk in home-gitops `docs/canopen-nodes.adoc`); the
car bridge's frames described the same way
**** [x] Meanwhile one EDS for all of them: esphome-canopen's generic one (from can2mqtt) in
`public/can/esphome.eds`, names the SDO objects in `/trace.html` (plus the entity objects);
a node's own EDS (`0x1021`) to take its place per node
*** [ ] 0x1008/0x1018 identity for any CANopen device in `/can.html`
** [x] A node that stops its heartbeat (3 missed) is flagged: one journal line when it goes
silent and when it's back (`can: node 2 silent, last heartbeat …`), red in `/can.html`
** [x] Dashboard overlay (Overlays → Live → Dashboard, `public/js/dashboard.js`): one combined
inclinometer (Pajero style, but one instrument, not three) — compass ring around a rear view
(roll) and a side view (pitch), amber past 20° roll / 25° pitch, red past 1.5× — and the
speed; widgets on/off per device. Heading: driving (≥ 1.5 m/s) the GNSS course from fixes
≥ 5 m apart, standing still the compass (`imu.heading`), else the last course, dimmed
*** [ ] Widgets placed per screen and bound to any signal — turn signals, brake, … once the
car's bridge puts them on the bus
*** [x] The compass (HMC5883L on node 0x21, TPDO 0x221) as `imu.heading` + `mag.x/y/z` in
`can.json` — for orienting while standing; driving uses the GNSS course
*** [ ] Tilt compensation (pitch/roll from the IMU) and hard-/soft-iron calibration of the
heading — ESPHome's is a plain `atan2(-x, y)`; in the node, like the levelling
*** [x] The node sent the heading encoded 0..360 but ESPHome's is −180..180, negatives arrived
as 0 — fixed in the node (`x < 0 ? x + 360 : x` filter on `heading:`, 2026-11-30)
*** [ ] 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
* [ ] TPMS off the car's CAN (2026-12-05): the car's own TPMS read by the car gateway and passed on
as `car.tpms.*` signals in `data/can.json` (the 4 wheels, pressure, temperature where sent);
warnings: low pressure, a fast drop (a puncture). Find where the Yaris Cross has it — broadcast
on a CAN the gateway sees, or only on request (UDS from the TPMS ECU). No radio node of our own;
sniffing the 433 MHz sensors (`rtl_433` on the uConsole's SDR) only if the car's CAN doesn't
carry it
=== 3D navigation mode
* [x] A "follow" mode like a car navigation: camera locked to the GNSS position, rotated to the
heading, pitched ~60°, smooth easing — the tracker's "Navigate" (see the Tablet-friendly
section); follows the MQTT tracker, not the browser's own GNSS control yet
** [x] Real 3D relief from the raster-dem terrain and Liberty's `building-3d` extrusions while navigating (the 3D mode has both)
* [ ] Full navigation (the car's main screen while driving; everything from our own Valhalla
tiles, no online service — Valhalla has OSM `maxspeed`, `traffic_signals` and turn lanes)
** [x] Basics on the dashboard (`public/js/dashboard.js`): the speed limit as a sign and a red
warning over it (+3 km/h); on the route panel's route (≤ 50 m off it): the next limit
change and its distance, the distance to the next traffic signal, the next maneuver and
its lanes (from 1 km, the lanes to take highlighted). `/api/route` gains `speed_limits`
(km → limit, per change), `signals` ([lon, lat, km]) and `maneuvers[].lanes`
(`turn_lanes`), from the same `trace_attributes` pass as the countries; the route's
signals drawn on the map from z14. Off the route / with none: `POST /api/road`
(map-matched last fixes → the road's name and limit), every 4 s while moving
** [x] Speed limits that aren't on the edge: `maxspeed:conditional` (time, wet), variable
signs, `zone:maxspeed` defaults per country (Valhalla leaves untagged roads empty — show
the country's default by road class?), the vehicle's own limits (a camper > 3.5 t: 80/100). Done
for the vehicle: `public/js/speed_limits.js` (14 countries, cars and over 3.5 t, from two camping
guides — see its sources), the route's `roads` (km, road class, country), the limit shown = the
lower of the sign and the profile's; past a border a card in drive mode (the canvas' GridBorder).
Not yet: `maxspeed:conditional`, a car's country default where the edge has none, ES/SE/NO/BE/LU
** [x] Rerouting (after Ferrostar's split of deviation detection and recalculation): off the
route = over 30 m from its line for 3 fixes in a row (fixes with HDOP > 5 don't count), then
the route panel routes from the position to the points not reached yet (via points passed
by km along the route, `legs_km`), at most every 15 s and only moving
*** [x] Step advance like Ferrostar's DistanceEntryExit (30 m to the step's end, 5 m past it)
instead of "the first maneuver ahead by km"; arrival at 30 m. Done: progress only forward —
the position looked for near the last one first (`locate`, 0.1 km back to 3 km ahead), so a
route along the same road twice or crossing itself doesn't jump; the step still advances 5 m
past the maneuver. Arrival: 30 m from the end "Arrived" (banner, drive mode), the navigation
goes on — driven past it, the reroute turns back to it
** [x] The navigation banner across the top (Dashboard widget, on by default): the next
maneuver's arrow (Valhalla's maneuver type), distance and street, "then …" when the next one
follows within 300 m, its lanes from 1 km, the street being driven; `/api/route` maneuvers
gain `type`, `street`, `exit`
** [x] The driving view decluttered: tilted to 3D (≥ 30°), route numbers and minor roads' /
paths' names hidden; road labels 1.5× further apart, past z15 the same ground distance
** [x] Turn-by-turn voice (`speechSynthesis`), the route ahead highlighted / the driven part
greyed. Voice: Valhalla's `verbal_transition_alert_instruction` ("In 400 meters, …", 25 s / ≥ 400 m
ahead) and `verbal_pre_transition_instruction` (7 s / ≥ 60 m ahead), English; on/off in drive
mode's Menu, off by default
** [x] Lanes as SVG arrows, one per direction bit, the lanes to take (Valhalla's `active`) blue
with that direction bold
*** [x] Lane guidance before motorway exits (lanes several maneuvers ahead), bigger on the
driving screen. Done: the next maneuver's lanes from 1 km or 45 s at the speed driven, in drive
mode a cell under the maneuver (`ahead` in the profile), shown only when there's something
** [x] Traffic signals with no route: around the position (Valhalla `locate` or the offline
PBF), and only for the direction driven (`traffic_signals:direction`). Done: `/api/road` also routes
1.5 km straight on from the last fix (leaving in the direction driven) and gives that way's signals;
the nearest one in front shown (dashboard, drive mode's `ahead` cell up to 1 km). The
`:direction` tag not yet
** [x] The "Navigate" follow mode for the CAN GNSS position (today the MQTT tracker and the
browser's GNSS control), the dashboard as part of the driving-mode UI. Done: drive mode's Follow
follows the CAN GNSS; the LTE tracker (MQTT) is a tracker layer to switch on (a second car, the car
seen from home), Meshtastic the same with the nodes picked
*** [x] Any point of a tracker layer can be the one the map follows — one at a time (picking
another one, or the car's own GNSS, takes it over); today only the MQTT tracker's card has "Navigate"
** [x] `locate()` scans the whole route each fix — a window around the last hit on long routes
** [ ] Shared trip — one itinerary per server for every screen (the cab's display, the tablet
or display in the back, phones): the co-driver adds a stop, the driver's view reroutes on the
fly without losing the map (no stop / reload / start like Android Auto between two phones)
*** [x] `TripStore` (`lib/maptool/trip.rb`, `data/trip.json`): points, vehicle, avoids, the
library route being edited and the route, versioned; `GET /api/trip?version=N` (204 while
unchanged), `PUT /api/trip` routes it on the server (not again when only names/nav
changed). Logged in, the route panel edits it and polls it every 2 s — other screens'
changes swapped in, the camera untouched, the old route shown until the new one is in
*** [x] Rerouting on the server: it has the GNSS (CAN), so off-route detection and the new
route once for all screens, not per screen with a dashboard. Done: `TripStore#follow` on
every fix (3 fixes > 30 m off while moving, at most every 15 s), the browser's own reroute
only without the shared trip
*** [x] An itinerary view: stops by day/night, notes, planned arrival times (Valhalla's leg
times), "Add to the trip" from search, the library, park4night and other sources. Done in the
Route panel (the canvas' Itinerary): the trip's name, leave time, days start; per stop ☾ night
(the day ends), stay and note; day headers with km and time; another screen's change shown
where it happened with Undo. Not yet: the route coloured by day, each stop's source, the
drive mode's Trip menu by days
*** Planning (the canvas' Plan and GridToday, ideas from azedler/roadplanner), in this order:
**** [x] A stop's type (its NPS pictogram on the marker and in the list), notes on the trip,
the days (on a day's first point) and the stops; + on a leg inserts the next point there
**** [x] The place and where the car stays apart: Parking in a stop's ✎, a P marker (drag it), the route goes there, the walk ×1.25 straight
**** [x] A pasted link (Google Maps, park4night, a page with coordinates) becomes a place in the search (/api/link, logged in); + puts it on the leg it lengthens least
**** [x] Avoids for the trip (+ ferries, unpaved) or a day (the day's ✎; routed in pieces, joined). Soft preferences (camps ≤ 40 €, lakes) not yet: for the Check / search when wanted
**** [x] Check (a fold in the Route panel): no leave time, a day over 8 h driving, a night spot after sunset, a long walk from the parking, motorways without the vignette; each with ⌖. Not yet: a day's avoids vs its route, winter-closed roads, opening hours
**** [x] Costs (a fold): fuel = km × the profile's consumption × the trip's fuel price, each stop's costs / paid, the budget left. Not yet: documents / receipts per stop, prices per country
**** [x] Today in drive mode (Menu ▸ Today): the stops left with arrival, tonight, sunset, Open-Meteo weather, the day's notes and Check items, Skip next, Tomorrow ▸. Not yet: Late +30 min
**** [ ] MCP over maptool (later)
*** [ ] Brick ↔ the car: a trip planned at home on brick handed to the car's server (with
the library sync, or "send to the car")
*** [ ] Push instead of polling (SSE) if 2 s ever feels slow
** [ ] Android Auto with the Pi as the phone (2026-12-05): the Pi connects to the car's existing
Android Auto and shows maptool's navigation to the driver on the car's screen; the display on
the Pi / the tablet over Wi-Fi are the navigator's. No phone in the loop
*** [ ] Over USB first: the head unit is the host, switches the "phone" into Android Open
Accessory (AOA) mode, then the Android Auto protocol (AAP over TLS). The Pi must be a USB
gadget — USB-OTG: the Pi 5's USB-C port (`dwc2` peripheral), on a CM5 whether its carrier
brings out the USB 2.0 port; power from the HAT through the header, the USB-C data only
(car VBUS not connected). Wireless (Bluetooth, then Wi-Fi) later
*** [ ] First check the head unit accepts a foreign phone side: AARE
(github.com/prototux/AARE, an open phone-side reimplementation, an Android app) on a phone
in the Yaris Cross; from AARE, whether the head unit checks the phone's certificate (if it
wants a Google-signed one, this way is closed). No open phone side for Linux was found
*** [ ] Then a Linux phone side (the AAP messages are aasdk's protobufs, the same both ways),
tested at home against Google's Desktop Head Unit. Video is H.264: the Pi 5 / CM5 have no
hardware encoder, so software (x264 ultrafast) at the head unit's 800×480 or 1280×720,
30 fps, one or two cores. Back from the car: touch and the rotary into maptool; to the car:
navigation prompts on AA's own audio channel, the turn arrows in the cluster where supported
*** [ ] Fallback: a native app on the phone — the Car App Library's NavigationTemplate drawing
its own map surface (MapLibre Native) off the car server's trip and position (`/api/trip`,
`/api/gnss/position`); only the map and the next maneuver, planning stays on the web
*** [ ] Views by who's driving off which screen: no Android Auto connected → the 16" display
shows the 3D follow view (heading-up, pitched) for the driver; Android Auto connected → it
streams the 3D navigation to the driver, and the co-driver's display stays 2D (north-up
overview, planning). Needs the Android Auto link (the Pi's phone side, or the fallback app)
to report connected/disconnected (e.g. next to `/api/gnss/position`) and the driving view
to switch on it
** [ ] A native Android app on Ferrostar (rerouting, Valhalla speed limits, TTS built in) over
our Valhalla (`format: osrm`) — only if navigation is wanted on a phone outside the car; the
car's 16" display is the Pi's browser either way. Ferrostar's web components are beta: no
rerouting or annotations on the web, bundler + WASM, its own map element
** [x] GNSS simulation for trying it without the car (`lib/maptool/gnss_sim.rb`, Dashboard
settings → "Simulate driving from the map center", `POST/DELETE /api/sim/gnss`): random
trips over our Valhalla (2–8 km each, one after another) at 90 % of the road's limit, a fix
a second into the same `gnss.*` signals / GNSS_LATEST as the node's (ignored meanwhile)
*** [x] The dashboard's tilt from the terrain's slope while simulating
*** [x] Replay a library track (GPX/FIT with times) instead, at its own speed (`/sim.html`,
`GnssSim#replay`; stops longer than 30 s shortened to it)
** [x] Free look while following: moving the map by hand pauses the follow, "Back to the
position" or 15 s untouched resumes it
* [x] While following a planned route: the route ahead highlighted, distance to the next
maneuver from Valhalla's directions (the banner; the driven part dashed)
=== Design: the park brochure and the cockpit
Planning in the NPS look, driving in the cockpit look, joined by the Unigrid black band —
`docs/design.adoc`. Action plan:
. [x] Colors: tokens on `:root` (`--band`, `--inst-*`: ok / caution / warning, magenta = what
navigation follows, cyan = set by hand); the dashboard in them — a see-through black bezel,
light values, inverted back in night mode
. [x] The route line magenta while it's navigated (follow mode), blue while planning; the next
waypoint and maneuver magenta on the map too. Done for the line (the driven part dimmed,
while the dashboard is on the route); the waypoint / maneuver marks still to do
. [ ] The rest of the hard-coded colors → tokens (route, warnings, panel states), one place to tune
. [ ] Panel headers as the Unigrid band: black, white title in National Park (headings weight
to vendor), the same band as the topbar
. [ ] `/can.html` in the cockpit style: dark, the node / signal states in `--inst-*`
. [ ] The navigation strip: the next maneuver big at the top (arrow, distance, street, lanes) —
with the driving mode's big-button UI
. [ ] The PDM switch panel in the cockpit style (tiles: `--inst-ok` on, muted off,
`--inst-warning` fault)
. [x] Palettes after IHO S-52: the same tokens in Day / Dusk / Night (`data-palette` on
`<html>`), night dim with low blue and no white areas, the speed limit sign dimmed too
. [x] Switch them: by the sun (the night mode's auto) and by hand (the topbar button cycles
day / dusk / night / auto), replacing the inverting `html.night`; the planning UI's
hard-coded colors onto `--ui-*` first, or a dark palette leaves light panels. Done: the
greys on `--ui-*` (MapLibre's controls too), `color-scheme: dark`, the controls lifted off
the dark map; night mode sets Night, "◑" Dusk (the day map)
. [ ] A Dusk map (between Park Tiles and `NightMap`), the map's palette following the UI's
. [ ] Daylight: a full-opacity bezel preset for sun on the screen
. [ ] The display's backlight apart from the palette (as G1000/GPSMAP): the car's screen dimmed
for Night (DDC/CI or its own dimmer), the palette only picks the colors
. [ ] Auto night by the headlights (car CAN) or a light sensor on a node, with hysteresis
(not flipping in a tunnel) — the sun only as the fallback
. [ ] A red/black night palette (Garmin marine / Raymarine) for the darkest roads
. [ ] One night mode for every screen in the car (the server's, like Garmin over NMEA 2000)
. [ ] No flash back to Day at night: the palette switch eased in
=== HW integration === HW integration
* [ ] Level gauge from IMU (ESP32/RPi) — camper tilt, wheel-chock leveling calculation Inspired by Garmin Tread / zūmo, but open and over CANopen — the nodes' side and the options
are in home-gitops `docs/canopen-nodes.adoc` ("Inšpirácia: Garmin Tread / zūmo"):
* [ ] A universal STM32C5 board v1 (2026-12-05) instead of XIAOs (~9 € + VAT + 10 € postage
each; out of stock) and before role-specific boards — one design, one round of first-spin
fixes, 8–10 pieces for the IO nodes, the car gateway, the Meshtastic bridge, the
controller prototype. JLCPCB in batches, Basic parts assembled, the MCU by hand. The bare MCU
isn't reliably in stock either (TME showed 0, ~3.6 USD) — check before ordering the PCBs
** STM32C5A3CGT6 (LQFP48), 16 MB flash on QSPI (W25Q128, as on the XIAO, for Zephyr)
** 2× CAN transceiver, both TCAN1043 (CAN FD, VIO for 3.3 V, wake on bus traffic or the local
WAKE pin, INH switching the board's regulator → Silent Watch at µA); one part everywhere (one
JLCPCB extended-part fee), ~0.4–1 USD more than a TJA1051 at LCSC. Not selective wake
(TJA1145 / TCAN1145, SPI): any bus traffic wakes every node, fine while the bus is quiet
** Automotive 12 V in: reverse polarity, TVS, a buck to 3.3 V; SWD; the power + CAN connector
the same as the xt30_can_5v board (XT30 2+2)
** Headers with every free GPIO, SPI and UART: role add-ons on top — an output board, a
Meshtastic radio on UART (its firmware doesn't run on the C5)
* [ ] Hardware buttons (a CANopen keypad / a steering-wheel controller, read off `can0`):
actions in `data/can.json` — pan, zoom ±, add a point (the position into the library or the
trip), mark a place, switch views (navigation / overview / dashboard), mute / volume, the
trip's next stop, night mode; a long press for a second action, the keypad's LEDs showing state
** [x] Drive mode keys from the keyboard (profile `key`, labels in the corners, ↑ ↓ / Enter / Space / + / Esc in a menu)
** [x] Keypads as channels and bindings, the PDMs' way (2026-12-04, `lib/maptool/keypad.rb`): can.json's `"keypads"` (a PKP by its protocol, or any signals as `inputs`) give channels `pad.K1`, `pad.E3`, `pad.E3 press`; the screen profile's `"bindings"` give each an action (a screen key, zoom, pan, rows), another in an open menu, its LED colour and the colour while on. A keypad's heartbeat labels the screen keys with its channels (back after 5 s without it), a line under them in the LED colour. Not tried on the real node yet
*** [x] Outputs (2026-12-04, `lib/maptool/outputs.rb`): can.json's relay modules (simulated for now, no current measured), a binding's `output` with Toggle / On / Off / Hold / Pulse, Hold off when the keypad goes silent, the state re-sent every 100 ms (the module's 2 s watchdog), the key LED while on; `/sim.html` switches them by hand. Not tried on a real module
*** [x] Positions, strobe and dimmer (2026-12-04): a key steps through outputs (a knob up and down), blinking with a period, a knob's level by a step (a dimmable module: a byte per channel); in /keypad.html and /sim.html. Nothing real behind them yet
*** [x] Switch tiles on the screen (2026-12-04, the canvas' GridSwitches): Menu → Switches (only when `/api/outputs` answers), 3×3 tiles per page (name, On / Off / Flashing / level, the key and mode driving it, its LED colour line), a group per module, All off, More ▸; a tap toggles (`switchesMenu` in `drive_menus.js`)
*** [ ] Interlocks and conditions (speed, ignition), long press
*** [ ] The controller moves to the STM32C5 on the Pi's HAT (docs/design.adoc "The controller on
the Pi's HAT", 2026-12-05): first the CANopen objects for requests (toggle / on / off / level
from keypads, `mcu-lvgl`, maptool), the outputs' state (TPDO) and the configuration (bindings
over SDO), used by maptool's `outputs.rb` now; then the Zephyr firmware (MCUboot's second slot,
the black box and the bindings in the 16 MB external flash), checked against `outputs.rb`;
maptool fetches the black box when it comes up
**** [ ] Before more STM32C5 boards arrive (both XIAOs are in use): the controller in Zephyr as
`native_sim` on SocketCAN (`zephyr,native-linux-can`) — on a PC against `vcan0` with
`/sim.html` and the simulated outputs, on rpi-dev against `can0` and the real keypads; the
external flash emulated in a file; the same inputs give the same outputs as `outputs.rb`.
Only the chip's layer (CAN, flash, power) moves to the board later. Order more XIAO STM32C5
** [x] CANopen TIME from maptool while no node sends it (2026-12-04, `lib/maptool/can_time.rb`); the GNSS node takes over once esphome-canopen has TIME
*** [ ] A knob's hold (the eye), the focused row's badges in keypad mode, the knobs' LEDs (8Encoder colours over SDO)
** [x] The key mapping in our diagnostics (2026-12-04, `/keypad.html`, the canvas' GridBinding): pick a key or knob (or press it), what it drives, mode, menu, LEDs; saved per car in `data/drive/bindings.json`. Not yet: interlocks, conditions, long press; drive mode picks a change up only on reload
** [ ] The switch (auto / keyboard / keypad) in our diagnostics
* [ ] A virtual switch panel for the PDM node (like Garmin's PowerSwitch: tiles with icon,
label, state and current, groups) + rules: by speed, sun/time of day, geofence (the trip's
camp), ignition and battery voltage
** [ ] Blackout / camp mode: one key — keypad LEDs ~2 % dim red, screen Night at its lowest,
auxiliary outside lights off and inhibited (door → awning light) until left; road lights untouched
** [ ] Sleep (Silent Watch): outputs to their safe state, nodes NMT stopped / asleep, screen off;
what wakes them (a key, ignition / wake line, CAN wake-up) — node side in home-gitops
`docs/canopen-nodes.adoc` (TCAN1043 on every board: wake + INH, transparent until the firmware
uses its EN / nSTB pins; the "everyone to sleep" command from the controller)
** [ ] A node's hardware interlock (winch, inverter, heater off on a wire, MCU or bus dead or not)
shown on its tiles as "locked out"
* [ ] The group over LoRa (Meshtastic / MeshCore through a node on the Pi): the others' positions
as a live layer with trails, short messages, "come here" into the trip
* [ ] Audio: volume / mute from the keypad and the app, navigation prompts ducking the music
* [x] Level gauge from IMU (ESP32/RPi) — camper tilt, wheel-chock leveling calculation (the canvas'
GridLevel, 2026-12-03): Terrain → "Level ▸" (in place of Road view; ✕ closes it the same): the
car from above with the cm under each wheel (lifted to the highest, never dug in), rounded to
the profile's ramp steps or exact for jacks, the bubble, roll / pitch now and after; the
profile's new wheelbase, track and ramps fields (guessed from length / width when unset).
Not yet: a pitch target (the bed's head up), only the two low wheels on ramps
* [ ] Victron/Home Assistant via MQTT or WebSocket — battery SoC, tank levels, temperatures * [ ] Victron/Home Assistant via MQTT or WebSocket — battery SoC, tank levels, temperatures
* [ ] Plot GPS track with historical battery/speed data * [ ] Plot GPS track with historical battery/speed data
== Server in the car (RPi CM5, 8 GB)
The tablet talks to a server far away today, so without internet nothing loads. Moving the
server into the car (on the car's Wi-Fi, next to the MQTT broker) makes everything that's
already offline work on the road. The Pi only serves; heavy builds stay on brick.
* [ ] Run the existing docker-compose stack on the CM5 (arm64: our image handles it, check
that the Valhalla and kiwix-serve images have arm64 builds); data on NVMe, not the SD card.
maptool itself runs on rpi-dev (podman, data in /srv/podman/maptool/data on the NVMe);
Valhalla and kiwix-serve there not checked
* [ ] Build on brick, ship to the Pi: `offline.pmtiles`, `terrain.pmtiles`, Valhalla
`tiles.tar`, `places/*.sqlite`, `hiking_trails/*.geojson`, the ZIM — an rsync (only when
refreshed, which is rare) instead of the Pi's own build buttons; hide/disable those there
* [ ] Powering the Pi (docs/design.adoc "What the military vehicles do"): preferred, the Pi on
12 V only, anywhere in the car — the gateway node tells "car running" (car CAN data or its IGN
input); a HAT with an STM32C5 turns the Pi on (car running, or a wake from the network), asks
it to shut down cleanly and cuts power after, measures voltage / current; the HAT also has the
Pi's CAN (SPI controller + transceiver, `can0`), the STM32C5 a node on the same bus and the Pi's
watchdog (maptool's heartbeat — it sends none yet —, power-cycle when it hangs). The Pi 5 takes
5 V only and wants ≥ 5 A: the HAT's buck 5.1 V / 5 A+ into the header's 5 V pins, and
`PSU_MAX_CURRENT=5000` in the EEPROM (powered off the header it can't tell, and limits USB to
600 mA); the 12 V side survives a cold crank or shuts down cleanly. Fallback: the Pi on
the bus, 6-pin Deutsch DT (12 V, GND, CAN H, CAN L, IGN, spare), IGN read by the Pi
* [x] Login without internet: Gitea OAuth can't run offline — let the car's LAN through
without login (e.g. `TRUSTED_NETWORKS` CIDR list), or a local fallback account. Done: the
session cookie is checked locally (90 days, no Gitea after the login), and rpi-dev has
`TRUSTED_NETWORKS=connected` — whatever is on the Pi's own networks counts as logged in
* [ ] HTTPS on the LAN (the secure session cookie, the PWA and the service worker need it):
the same hostname resolved to the Pi by the car router's DNS, Let's Encrypt cert via DNS-01
* [ ] A touch display on the Pi itself (a portable ~16" USB touchscreen, the co-driver's —
the navigator plans on it while driving; Chromium in kiosk mode on
`http://localhost`) as the car display — solves a lot at once: localhost is a secure
context (no certificate needed for the PWA/service worker) and can skip login, it doesn't
depend on the car's Wi-Fi, buttons plug straight into the Pi (a USB/BLE keypad is just a
keyboard to Chromium, a CAN keypad via SocketCAN on the Pi). The tablet/phone stay optional
* [ ] Sync home ⇄ car — two servers, each fully usable on its own:
** Bulk data (pmtiles, Valhalla tiles, places, hiking trails, ZIM) only on the home network
(the car joining the home Wi-Fi as the trigger), never over LTE
** User data (library: folders/items/notes, tracker settings, logged trail) whenever both
ends are reachable, LTE included — small, incremental
** Builds on the library's existing pieces (docs/library-design.adoc): `rev` change counter,
`GET /api/library/changes?since=<rev>`, tombstones, `item_history` for the losing version.
Missing for two servers: per-peer high-water marks (my rev on your side and vice versa),
ids that never collide (UUIDs, already for items), and a base version per item so a real
conflict (both sides changed since the last sync) is told apart from a plain update
** Conflicts: per item, newer `updated_at` wins (clocks: the Pi needs NTP/GNSS time), the
other version into `item_history` and flagged in the UI so it can be restored; a delete vs.
an edit keeps the edit
** Logged tracker positions: append-only, merged by timestamp, no conflicts
* [x] Hardware buttons: keyboard shortcuts in the page (zoom, Navigate, night mode, …) — the
cheap way with any BLE/USB keypad that sends plain keys. Done in drive mode (the profile's
`key`s, see HW integration); the desktop has none yet
* [ ] … and the full way: a CANopen keypad (Blink Marine style) on the CAN bus wired straight
to the Pi, read by maptool's native CAN (see "Native CAN" above; NMT start, key bitmap
from `0x180+node` as `bit` signals, LEDs via `0x200+node` still to send) → the
browser over Server-Sent Events; the page's state (navigating, night) back the same way to
light the keypad's LEDs. Server needs to know which browser is "the car display" (a
per-device switch — or simply the Pi's own kiosk display)
== Admin / ops tooling == Admin / ops tooling
* [ ] Offline build log readability — a failed pmtiles/terrain build currently surfaces as one * [ ] Offline build log readability — a failed pmtiles/terrain build currently surfaces as one
@@ -82,3 +630,5 @@ Deprioritized for now — revisit after the sections above land.
* [ ] Expose the build log via an API endpoint, not just embedded in the admin page * [ ] Expose the build log via an API endpoint, not just embedded in the admin page
* [ ] Document all API endpoints somewhere and make them easy to browse (status of each) — * [ ] Document all API endpoints somewhere and make them easy to browse (status of each) —
maybe a status page, login-gated maybe a status page, login-gated
** [x] The status page: `/status.html`, every read-only status endpoint's JSON, full width,
refreshed every 5 s, filter and pause (the Status / debug panel links it)
+1349 -208
View File
File diff suppressed because it is too large. Load diff
+39
View File
@@ -0,0 +1,39 @@
#!/usr/bin/env node
// Re-downloads the vendored assets that aren't on npm, pinned to the git
// commits below. Renovate bumps each pin (git-refs digest, see renovate.json)
// and runs this as a postUpgradeTask, so its PR carries the new files.
// Manually: bump a sha, then `node bin/assets-sync.mjs`.
import { mkdirSync, writeFileSync } from "node:fs";
// renovate: datasource=git-refs depName=https://github.com/protomaps/basemaps-assets branch=main
const BASEMAPS_ASSETS = "028c18f713baecad011301ff7a69acc39bcc2ae7";
// renovate: datasource=git-refs depName=https://github.com/hyperknot/openfreemap-styles branch=main
const OPENFREEMAP_STYLES = "006ea5796803ba2df4330888836cb0a8f17473b4";
const vendor = new URL("../public/vendor/", import.meta.url).pathname;
async function get(url, to) {
const res = await fetch(url);
if (!res.ok) throw new Error(`${res.status} ${url}`);
const body = Buffer.from(await res.arrayBuffer());
if (to) {
mkdirSync(`${vendor}${to}`.replace(/\/[^/]+$/, ""), { recursive: true });
writeFileSync(`${vendor}${to}`, body);
}
return body;
}
const raw = `https://raw.githubusercontent.com/protomaps/basemaps-assets/${BASEMAPS_ASSETS}/fonts`;
await get(`${raw}/OFL.txt`, "fonts/OFL.txt");
for (const font of ["Noto Sans Regular", "Noto Sans Italic", "Noto Sans Medium"])
for (const range of ["0-255", "256-511"])
await get(`${raw}/${encodeURIComponent(font)}/${range}.pbf`, `fonts/${font}/${range}.pbf`);
// ponytail: OPENFREEMAP_STYLES only triggers the sync; what's fetched is the
// style tiles.openfreemap.org serves right now (built from that repo), and the
// sprite at whatever versioned path that style points to.
const style = await get("https://tiles.openfreemap.org/styles/liberty", "liberty-style/liberty.json");
const sprite = JSON.parse(style).sprite;
for (const suffix of [".json", ".png", "@2x.json", "@2x.png"])
await get(`${sprite}${suffix}`, `liberty-sprite/ofm${suffix}`);
console.log(`synced (openfreemap-styles ${OPENFREEMAP_STYLES.slice(0, 7)}, sprite ${sprite})`);
+105
View File
@@ -0,0 +1,105 @@
#!/usr/bin/env node
// Builds lib/maptool/data/geofabrik_regions.geojson — the offline map's
// region catalog (PmtilesBuilder) — from Geofabrik's own index
// (https://download.geofabrik.de/index-v1.json): every downloadable country
// grouped by continent, plus one level of subregions (US states, German
// Länder, ...), each with its Geofabrik path and boundary polygon (the
// polygon is what terrain extraction clips to). Rerun to pick up Geofabrik
// changes: `node bin/geofabrik-regions-sync.mjs`.
//
// Codes: a country's ISO 3166-1 alpha-2 code (the same codes the old
// Europe-only list used, so existing caches/selections stay valid); a
// subregion's ISO 3166-2 code, or <country>-<geofabrik id>; a region with no
// ISO code of its own (Canary Islands, Azores, ...) keeps its Geofabrik id.
import { writeFileSync } from "node:fs";
const OUT = new URL("../lib/maptool/data/geofabrik_regions.geojson", import.meta.url).pathname;
// Geofabrik's top-level index entries, as the picker's sections.
const CONTINENTS = {
europe: "Europe",
"north-america": "North America",
"central-america": "Central America",
"south-america": "South America",
asia: "Asia",
russia: "Russia",
africa: "Africa",
"australia-oceania": "Australia and Oceania",
antarctica: "Antarctica",
};
// Aggregates that only repeat countries listed on their own.
const SKIP = new Set([
"alps", "britain-and-ireland", "dach", "great-britain", "american-oceania", "sea",
"us-midwest", "us-northeast", "us-pacific", "us-south", "us-west",
]);
// Countries Geofabrik lists without an ISO code, or with a borrowed one
// (Clipperton is tagged PF, French Polynesia's).
const CODE_OVERRIDES = { kosovo: "XK", "ile-de-clipperton": "CP" };
const round = (geometry) => {
const r = (c) => (typeof c[0] === "number" ? [Math.round(c[0] * 1e4) / 1e4, Math.round(c[1] * 1e4) / 1e4] : c.map(r));
return { type: geometry.type, coordinates: r(geometry.coordinates) };
};
const index = await (await fetch("https://download.geofabrik.de/index-v1.json")).json();
const byId = new Map(index.features.map((f) => [f.properties.id, f]));
const slug = (f) => new URL(f.properties.urls.pbf).pathname.replace(/^\//, "").replace(/-latest\.osm\.pbf$/, "");
const regions = [];
const countryCode = new Map(); // geofabrik id -> country code
function country(f, continent) {
const p = f.properties;
const iso = p["iso3166-1:alpha2"];
const code = CODE_OVERRIDES[p.id] || (iso?.length === 1 ? iso[0] : p.id);
countryCode.set(p.id, code);
regions.push({ f, code, continent, parent: null });
}
for (const f of index.features) {
const p = f.properties;
if (SKIP.has(p.id)) continue;
if (p.id === "russia") country(f, "russia"); // a top-level entry that is itself a country
else if (CONTINENTS[p.parent] && p.parent !== "russia" && !p.id.startsWith("us/")) country(f, p.parent);
}
// One level of subregions: a country's direct children (Geofabrik lists the
// US states, and Russia's federal districts, under the continent instead).
for (const f of index.features) {
const p = f.properties;
if (SKIP.has(p.id) || countryCode.has(p.id)) continue;
const parentId = p.id.startsWith("us/") ? "us" : p.parent;
const parent = countryCode.get(parentId);
if (!parent) continue;
const code = p["iso3166-2"]?.[0] || `${parent}-${p.id.split("/").pop()}`;
regions.push({ f, code, continent: regions.find((r) => r.code === parent).continent, parent });
}
const codes = regions.map((r) => r.code);
const duplicates = codes.filter((c, i) => codes.indexOf(c) !== i);
if (duplicates.length) throw new Error(`duplicate codes: ${duplicates.join(", ")}`);
// Geofabrik's names: some carry HTML ("Nord-Norge<br />(Northern Norway)"),
// and the US states are named by their path ("us/new-york").
const displayName = ({ id, name }) =>
name === id
? id.split("/").pop().replace(/-/g, " ").replace(/\b\w/g, (c) => c.toUpperCase())
: name.replace(/<br\s*\/?>/gi, " ").replace(/<[^>]*>/g, "").replace(/\s+/g, " ").trim();
const features = regions.map(({ f, code, continent, parent }) => ({
type: "Feature",
properties: { code, name: displayName(f.properties), slug: slug(f), continent, ...(parent ? { parent } : {}) },
geometry: round(f.geometry),
}));
writeFileSync(
OUT,
JSON.stringify({
type: "FeatureCollection",
// The picker's section order and names.
continents: Object.entries(CONTINENTS).map(([id, name]) => ({ id, name })),
features,
}),
);
console.log(`${features.length} regions (${features.filter((f) => !f.properties.parent).length} countries) -> ${OUT}`);
-72
View File
@@ -1,72 +0,0 @@
#!/usr/bin/env ruby
# frozen_string_literal: true
# Speaks gpsd's own JSON wire protocol (https://gpsd.io/gpsd_json.html)
# directly on gpsd's default port — GpsdClient (lib/maptool/gpsd_client.rb)
# connects to it exactly as it would to real gpsd, so no app code or config
# changes are needed. Unlike docs/development.adoc's fake-NMEA-source
# example, this doesn't need gpsd itself installed/running at all, and
# actually moves (a fixed point isn't much of a "GNSS position" to look
# at) — drives a loop around a center point at a driving-ish pace, one TPV
# report per second like a real receiver.
#
# Usage: bin/gnss_simulator.rb [lat] [lon] [radius_m] [port]
require "socket"
require "json"
$stdout.sync = true
LAT = (ARGV[0] || 48.1486).to_f
LON = (ARGV[1] || 17.1077).to_f
RADIUS_M = (ARGV[2] || 300).to_f
PORT = (ARGV[3] || 2947).to_i
LOOP_SECONDS = 120 # time to complete one full loop
EARTH_RADIUS_M = 6_371_000
def point_on_loop(center_lat, center_lon, radius_m, angle_rad)
# Flat-plane offset, not geodesic — fine at this radius (metres, not km),
# same reasoning as measure.js's own approximations at this scale.
lat_offset = (radius_m * Math.sin(angle_rad)) / EARTH_RADIUS_M
lon_offset = (radius_m * Math.cos(angle_rad)) / (EARTH_RADIUS_M * Math.cos(center_lat * Math::PI / 180))
[center_lat + lat_offset * 180 / Math::PI, center_lon + lon_offset * 180 / Math::PI]
end
server = TCPServer.new("127.0.0.1", PORT)
puts "[gnss-simulator] driving a #{RADIUS_M.to_i}m loop around #{LAT},#{LON} — listening on 127.0.0.1:#{PORT}"
loop do
socket = server.accept
puts "[gnss-simulator] client connected"
start = Time.now
begin
loop do
elapsed = Time.now - start
angle = (elapsed / LOOP_SECONDS) * 2 * Math::PI
lat, lon = point_on_loop(LAT, LON, RADIUS_M, angle)
# Bearing of travel: tangent to the circle, 90 degrees ahead of the
# radius vector at this point.
track = (angle * 180 / Math::PI + 90) % 360
speed = (2 * Math::PI * RADIUS_M) / LOOP_SECONDS # m/s, constant pace
report = {
class: "TPV",
mode: 3,
lat: lat,
lon: lon,
altHAE: 150.0,
speed: speed,
track: track,
eph: 3.0,
time: Time.now.utc.strftime("%Y-%m-%dT%H:%M:%S.%3NZ"),
}
socket.puts(JSON.generate(report))
sleep 1
end
rescue Errno::EPIPE, IOError
puts "[gnss-simulator] client disconnected"
ensure
socket.close
end
end
+48
View File
@@ -0,0 +1,48 @@
#!/usr/bin/env node
// Vendors every NPS map symbol (22 px, black, standalone) from
// nationalparkservice/symbol-library's jakecoolidge-revision-2024 branch
// (PR #226, the newest artwork: a superset of npmap5-plugins' copy) into
// one ES module, { name: "<svg …>" }, cleaned to a bare viewBox and
// fill="currentColor". Public domain (CC0). Pinned to a commit; to update,
// change REF and run `node bin/nps-symbols-sync.mjs`.
import { mkdirSync, writeFileSync } from "node:fs";
const REPO = "nationalparkservice/symbol-library";
const REF = "94f772a21b593f2cdb6d2a2b8a5cc4d3dc5e3a61";
const out = new URL("../public/vendor/nps-symbols/", import.meta.url).pathname;
const tree = await (await fetch(`https://api.github.com/repos/${REPO}/git/trees/${REF}?recursive=1`)).json();
const files = tree.tree.map((t) => t.path).filter((p) => /^src\/standalone\/.+-black-22\.svg$/.test(p) && !p.includes("transparent"));
const clean = (svg) =>
svg
.replace(/<\?xml[^>]*>|<!--[\s\S]*?-->|<(style|title)[\s\S]*?<\/\1>/g, "")
.replace(/<\w+[^>]*fill="none"[^>]*\/>/g, "") // invisible leftovers
.replace(/\s(id|fill|class|style|enable-background|xml:space)="[^"]*"/g, "")
.replace(/<svg[^>]*>/, '<svg viewBox="0 0 22 22" fill="currentColor">')
.replace(/\s+/g, " ")
.replace(/> </g, "><")
.trim();
const symbols = {};
for (let i = 0; i < files.length; i += 6) {
await Promise.all(
files.slice(i, i + 6).map(async (path) => {
const res = await fetch(`https://raw.githubusercontent.com/${REPO}/${REF}/${path}`);
if (!res.ok) throw new Error(`${path}: ${res.status}`);
symbols[path.match(/([^/]+)-black-22\.svg$/)[1]] = clean(await res.text());
}),
);
}
mkdirSync(out, { recursive: true });
writeFileSync(
`${out}nps-symbols.mjs`,
`// Generated by bin/nps-symbols-sync.mjs from ${REPO}@${REF.slice(0, 7)} (CC0).\nexport const NPS_SYMBOLS = {\n` +
Object.keys(symbols)
.sort()
.map((name) => ` ${JSON.stringify(name)}: ${JSON.stringify(symbols[name])},\n`)
.join("") +
"};\n",
);
console.log(`${Object.keys(symbols).length} symbols`);
+98
View File
@@ -0,0 +1,98 @@
#!/bin/bash
# Map data, one way: the main server (brick) builds it, the car's server
# pulls it over HTTPS from the same public URL and SYNC_TOKEN as the
# library sync (no SSH/VPN): GET /api/sync/maps lists the files, each one
# comes from /api/sync/maps/file, a cut-off download resumes. The library
# goes both ways on its own (lib/maptool/sync.rb), not here.
#
# Run by maptool-pull-maps.timer on the car's server (docs/deployment.adoc).
# Big files (GBs), so by default only at home: when HOME_HOST answers.
# HOME_HOST= (empty) pulls anywhere, LTE included.
set -euo pipefail
ENV_FILE=${MAP_ENV:-/srv/podman/maptool/.env}
DATA=${MAP_DATA:-/srv/podman/maptool/data}
HOME_HOST=${HOME_HOST-10.17.240.2}
env_value() { grep -m1 "^$1=" "$ENV_FILE" | cut -d= -f2- | sed 's/^["'\'']//; s/["'\'']$//'; }
server=$(env_value SYNC_SERVER_URL)
token=$(env_value SYNC_TOKEN)
if [ -z "$server" ] || [ -z "$token" ]; then
echo "pull-maps: no SYNC_SERVER_URL/SYNC_TOKEN in $ENV_FILE" >&2
exit 1
fi
server=${server%/}
if [ -n "$HOME_HOST" ] && ! timeout 5 bash -c "</dev/tcp/$HOME_HOST/22" 2>/dev/null; then
echo "pull-maps: $HOME_HOST not reachable (not at home), skipping"
exit 0
fi
# The token in a header file, not on the command line (ps shows that).
auth=$(mktemp)
trap 'rm -f "$auth"' EXIT
printf 'Authorization: Bearer %s\n' "$token" > "$auth"
manifest=$(curl -fsS --retry 3 -H "@$auth" "$server/api/sync/maps")
updated=0
failed=0
declare -A wanted=()
while IFS=$'\t' read -r size mtime path; do
[ -n "$path" ] || continue
case "$path" in /* | *..*) echo "pull-maps: skipping odd path $path" >&2; continue ;; esac
wanted[$path]=1
local_file="$DATA/$path"
[ -f "$local_file" ] && [ "$(stat -c '%s %Y' "$local_file")" = "$size $mtime" ] && continue
part="$local_file.part"
# One file that can't be written (a directory the container owns) is
# that file's failure, not the whole run's.
if ! mkdir -p "$(dirname "$local_file")" || ! touch "$part.version" 2>/dev/null; then
echo "pull-maps: can't write $local_file, skipping" >&2
failed=$((failed + 1))
continue
fi
# A partial download of another version of the file starts over.
[ "$(cat "$part.version" 2>/dev/null)" = "$size $mtime" ] && [ "$(stat -c %s "$part" 2>/dev/null || echo 0)" -le "$size" ] || rm -f "$part"
echo "$size $mtime" > "$part.version"
echo "pull-maps: $path ($((size / 1048576)) MB)"
# Into a temp file, renamed when complete: the app and Valhalla keep
# reading the old copy until restarted. Each attempt resumes from what's
# there (curl's own --retry keeps its first offset); --speed-*: a
# connection that went dead (Wi-Fi switched) is dropped after a minute.
stalls=0
while have=$(stat -c %s "$part" 2>/dev/null || echo 0); [ "$have" -lt "$size" ] && [ "$stalls" -lt 5 ]; do
curl -fsS --retry 3 --retry-delay 5 --speed-limit 1024 --speed-time 60 -C - -o "$part" -H "@$auth" \
--get --data-urlencode "path=$path" "$server/api/sync/maps/file" || sleep 5
[ "$(stat -c %s "$part" 2>/dev/null || echo 0)" -gt "$have" ] && stalls=0 || stalls=$((stalls + 1))
done
if [ "$(stat -c %s "$part" 2>/dev/null || echo -1)" = "$size" ]; then
touch -d "@$mtime" "$part"
mv "$part" "$local_file"
rm -f "$part.version"
updated=$((updated + 1))
else
echo "pull-maps: $path incomplete, continuing next run" >&2
failed=$((failed + 1))
fi
done <<< "$manifest"
# What the server no longer has, in the directories it sends.
for dir in $(cut -f3 <<< "$manifest" | grep / | cut -d/ -f1 | sort -u); do
while IFS= read -r -d '' file; do
rel=${file#"$DATA/"}
case "$rel" in *.part | *.part.version | routing/service.sh) continue ;; esac
if [ -z "${wanted[$rel]:-}" ]; then
echo "pull-maps: removing $rel"
rm -f "$file"
updated=$((updated + 1))
fi
done < <(find "$DATA/$dir" -type f -not -path '*/.*' -print0)
done
if [ "$updated" -gt 0 ]; then
echo "pull-maps: $updated files changed, restarting maptool"
sudo systemctl restart podman-compose@maptool.service
fi
[ "$failed" -eq 0 ]
+119
View File
@@ -0,0 +1,119 @@
#!/bin/bash
# Runs inside the valhalla container (docker-compose.yaml), which mounts the
# whole data/ at /data. maptool copies this script to data/routing/ at boot
# (Maptool::Routing.install_service_script), so the container always runs
# the version that shipped with the app. See docs/routing-design.adoc.
#
# Serves data/routing/tiles.tar with valhalla_service, and polls for
# data/routing/build-request.json ({"regions": ["SK", ...]}, written by
# maptool). A build hard-links those countries' Geofabrik extracts, builds
# into staging/ while the old tiles keep serving, then swaps tiles.tar in
# and restarts the service. Progress goes to status.json, the build's
# output to build.log.
set -u
R=/data/routing
S=$R/staging
SERVICE_PID=
status() { # state step [message]
local now
now=$(date -u +%FT%TZ)
python3 - "$R/status.json" "$1" "$2" "${3:-}" "$now" "${STARTED:-$now}" <<'PY'
import json, os, sys
path, state, step, message, now, started = sys.argv[1:]
data = {"state": state, "started_at": started}
if step: data["step"] = step
if state != "running": data["finished_at"] = now
if message: data["message"] = message
with open(path + ".tmp", "w") as f: json.dump(data, f)
os.replace(path + ".tmp", path)
PY
}
# trace limits: maptool reads the per-country km of a whole route (up to
# 5000 km, like route's own auto limit) from /trace_attributes; the
# defaults (200 km, 16000 points) are meant for GPS traces.
config() { # dir
valhalla_build_config --mjolnir-tile-dir "$1/tiles" --mjolnir-tile-extract "$1/tiles.tar" \
--mjolnir-admin "$1/admins.sqlite" --mjolnir-concurrency "${BUILD_THREADS:-$(( $(nproc) / 2 ))}" \
--service-limits-trace-max-distance 5000000 --service-limits-trace-max-shape 500000 \
> "$1/valhalla.json"
}
stop_service() {
[ -n "$SERVICE_PID" ] || return 0
kill "$SERVICE_PID" 2>/dev/null
# It can take a long time to exit on SIGTERM; it holds nothing to flush.
for _ in 1 2 3 4 5 6 7 8 9 10; do kill -0 "$SERVICE_PID" 2>/dev/null || break; sleep 0.5; done
kill -9 "$SERVICE_PID" 2>/dev/null
wait "$SERVICE_PID" 2>/dev/null
SERVICE_PID=
}
serve() {
stop_service
[ -f "$R/tiles.tar" ] || return 0
valhalla_service "$R/valhalla.json" "${SERVICE_THREADS:-4}" &
SERVICE_PID=$!
}
build() {
STARTED=$(date -u +%FT%TZ)
local regions code
rm -rf "$S" "$R/pbf"
mkdir -p "$S" "$R/pbf"
mv "$R/build-request.json" "$S/request.json"
regions=$(python3 -c 'import json,sys; print(" ".join(json.load(open(sys.argv[1]))["regions"]))' "$S/request.json")
pbf=$(python3 -c 'import json,sys; print(json.load(open(sys.argv[1])).get("pbf", ""))' "$S/request.json")
if [ -z "$pbf" ] && [ "$(echo $regions | wc -w)" -gt 1 ]; then # a request from before the merge
status error "" "this request has several countries but no merged extract; click Apply again"
return 1
fi
if [ -n "$pbf" ]; then # several countries, merged by maptool (Valhalla breaks on overlapping extracts)
ln "/data/$pbf" "$R/pbf/" || { status error "" "missing $pbf"; return 1; }
else
for code in $regions; do
ln "/data/geofabrik_cache/$code.osm.pbf" "$R/pbf/" || { status error "" "no downloaded extract for $code"; return 1; }
done
fi
: > "$R/build.log"
run() { # step command...
status running "$1"
shift
nice -n 10 "$@" >> "$R/build.log" 2>&1 || { status error "" "$(tail -c 2000 "$R/build.log")"; return 1; }
}
config "$S" &&
run "admin areas" valhalla_build_admins -c "$S/valhalla.json" "$R"/pbf/*.osm.pbf &&
run "routing graph ($regions)" valhalla_build_tiles -c "$S/valhalla.json" "$R"/pbf/*.osm.pbf &&
run "packing tiles" valhalla_build_extract -c "$S/valhalla.json" -v || return 1
mv "$S/tiles.tar" "$R/tiles.tar"
mv "$S/admins.sqlite" "$R/admins.sqlite"
config "$R"
mv "$S/request.json" "$R/built.json"
rm -rf "$S" "$R/pbf"
# Not if a newer request (with a freshly merged file) is already waiting.
[ -n "$pbf" ] && [ ! -f "$R/build-request.json" ] && rm -f "/data/$pbf"
serve
status done ""
}
# bash as PID 1 ignores SIGTERM unless trapped: stop promptly on a redeploy.
trap 'stop_service; exit 0' TERM INT
mkdir -p "$R"
[ -f "$R/tiles.tar" ] && config "$R"
# A build interrupted by a restart (every redeploy restarts the whole
# compose project) starts over: its request is still in staging/.
if [ -f "$S/request.json" ] && [ ! -f "$R/build-request.json" ]; then
mv "$S/request.json" "$R/build-request.json"
fi
serve
while true; do
# A failed build isn't retried by the next restart.
[ -f "$R/build-request.json" ] && { build || rm -f "$S/request.json"; }
# valhalla_service died (or never started): start it again.
if [ -n "$SERVICE_PID" ] && ! kill -0 "$SERVICE_PID" 2>/dev/null; then serve; fi
sleep 10 & wait $! # interruptible, so the trap above runs right away
done
+73
View File
@@ -0,0 +1,73 @@
#!/bin/bash
# The car's server updating itself, when asked from the app: the update
# button (POST /api/update) writes data/update/request.json with the commit,
# maptool-update.path runs this as root (the container writes data/ as root).
# Downloads that commit's tree from Gitea (the repo is public: no token),
# swaps it into build/ (the old one kept as build.old), restarts maptool and
# waits for it to answer with the new revision — if it doesn't, puts the old
# one back. data/update/status.json tells the app how far it got.
# A power cut at any point leaves either the old or the new tree in build/
# (maptool-recover.service puts one back if a cut fell between the two
# renames). docs/deployment.adoc.
set -euo pipefail
ROOT=${MAPTOOL_ROOT:-/srv/podman/maptool}
REPO_URL=${REPO_URL:-https://git.priesol.net/randy/maptool}
HEALTH_URL=${HEALTH_URL:-http://127.0.0.1:4567/api/health}
START_TIMEOUT_S=${START_TIMEOUT_S:-900} # the image build on the Pi takes a while
DIR=$ROOT/data/update
req=$DIR/request.json
[ -f "$req" ] || exit 0
sha=$(sed -n 's/.*"sha" *: *"\([0-9a-f]\{40\}\)".*/\1/p' "$req")
rm -f "$req"
status() {
printf '{"state":"%s","sha":"%s","message":"%s","at":%s}\n' "$1" "$sha" "$2" "$(date +%s)" > "$DIR/status.json.tmp"
mv "$DIR/status.json.tmp" "$DIR/status.json"
}
fail() { status failed "$1"; echo "update-maptool: $1" >&2; exit 1; }
revision() { curl -fsS --max-time 5 "$HEALTH_URL" 2>/dev/null | sed -n 's/.*"revision" *: *"\([^"]*\)".*/\1/p'; }
[ -n "$sha" ] || fail "no commit in the request"
short=${sha:0:7}
# asked twice (two screens, a double click): nothing to do the second time
[ "$(cat "$ROOT/build/REVISION" 2>/dev/null)" = "$short" ] && { status done "already on $short"; exit 0; }
status running "downloading $short"
# staged next to build/, on the same filesystem: the swap below is two
# renames, not a copy (/tmp is RAM on the Pi)
new=$ROOT/build.new
rm -rf "$new"
mkdir "$new"
trap 'rm -rf "$new" "$new.tar.gz"' EXIT
curl -fsS --retry 3 --retry-delay 5 --speed-limit 1024 --speed-time 60 -o "$new.tar.gz" "$REPO_URL/archive/$sha.tar.gz" \
|| fail "download of $short failed"
tar -xzf "$new.tar.gz" -C "$new" --strip-components=1 || fail "the archive didn't unpack"
[ -f "$new/app.rb" ] && [ -f "$new/docker-compose.yaml" ] || fail "not a maptool tree"
echo "$short" > "$new/REVISION"
chown -R --reference="$ROOT" "$new"
sync
old=$(cat "$ROOT/build/REVISION" 2>/dev/null || echo "?")
rm -rf "$ROOT/build.old"
mv "$ROOT/build" "$ROOT/build.old"
mv "$new" "$ROOT/build"
sync
trap - EXIT
status restarting "restarting with $short"
systemctl restart podman-compose@maptool.service
# up with the new revision, or back to the old one
deadline=$(( $(date +%s) + START_TIMEOUT_S ))
while [ "$(date +%s)" -lt "$deadline" ]; do
[ "$(revision)" = "$short" ] && { status done "updated to $short"; exit 0; }
sleep 10
done
status rolling-back "$short didn't come up in $((START_TIMEOUT_S / 60)) min, back to $old"
rm -rf "$ROOT/build.bad"
mv "$ROOT/build" "$ROOT/build.bad"
mv "$ROOT/build.old" "$ROOT/build"
sync
systemctl restart podman-compose@maptool.service
fail "$short didn't come up, back on $old (the new tree is in build.bad)"
+26 -5
View File
@@ -3,9 +3,9 @@
// public/vendor/ (committed, served as-is, no bundler). package.json pins // public/vendor/ (committed, served as-is, no bundler). package.json pins
// the versions; Renovate bumps them and runs this as a postUpgradeTask so // the versions; Renovate bumps them and runs this as a postUpgradeTask so
// its PR carries the new files too. Manually: `npm ci && node bin/vendor-sync.mjs`. // its PR carries the new files too. Manually: `npm ci && node bin/vendor-sync.mjs`.
// Libraries not on npm (NPS plugins, Liberty style/sprite, fonts) stay // Assets not on npm: fonts and the Liberty style/sprite go through
// hand-updated, see docs/third-party-notices.adoc. // bin/assets-sync.mjs, the NPS plugins are updated by hand.
import { copyFileSync, readFileSync, readdirSync, writeFileSync } from "node:fs"; import { copyFileSync, mkdirSync, readFileSync, readdirSync, writeFileSync } from "node:fs";
const root = new URL("..", import.meta.url).pathname; const root = new URL("..", import.meta.url).pathname;
const nm = (p) => `${root}node_modules/${p}`; const nm = (p) => `${root}node_modules/${p}`;
@@ -28,5 +28,26 @@ copy("maplibre-gl-lanes/LICENSE", "maplibre-gl-lanes/LICENSE");
copy("suncalc/index.js", "suncalc/suncalc.js"); copy("suncalc/index.js", "suncalc/suncalc.js");
copy("suncalc/LICENSE", "suncalc/LICENSE"); copy("suncalc/LICENSE", "suncalc/LICENSE");
// Only the flags already vendored (the European subset), not all ~270. // Only the flags of the countries the offline region picker lists
for (const f of readdirSync(vendor("flag-icons/1x1"))) copy(`flag-icons/flags/1x1/${f}`, `flag-icons/1x1/${f}`); // (lib/maptool/data/geofabrik_regions.geojson, from bin/geofabrik-regions-sync.mjs).
const regionCatalog = JSON.parse(readFileSync(`${root}lib/maptool/data/geofabrik_regions.geojson`, "utf8"));
const flagCodes = new Set(regionCatalog.features.map((f) => f.properties.code.match(/^([A-Z]{2})(-|$)/)?.[1]).filter(Boolean));
for (const code of flagCodes) copy(`flag-icons/flags/1x1/${code.toLowerCase()}.svg`, `flag-icons/1x1/${code.toLowerCase()}.svg`);
// Material Design Icons: only the mdi* names public/js/ actually uses (the
// whole set is ~3 MB), as one small ES module. Using another icon is just
// naming it in the code and running this again.
const mdi = await import(nm("@mdi/js/mdi.js"));
const used = new Set();
for (const f of readdirSync(`${root}public/js`)) {
if (f.endsWith(".js")) for (const [name] of readFileSync(`${root}public/js/${f}`, "utf8").matchAll(/\bmdi[A-Z]\w*/g)) used.add(name);
}
const missing = [...used].filter((name) => !mdi[name]);
if (missing.length) throw new Error(`not in @mdi/js: ${missing.join(", ")}`);
mkdirSync(vendor("mdi"), { recursive: true });
writeFileSync(
vendor("mdi/mdi.mjs"),
`// Generated by bin/vendor-sync.mjs from @mdi/js ${JSON.parse(readFileSync(nm("@mdi/js/package.json"), "utf8")).version}, Apache-2.0 (LICENSE).\n` +
[...used].sort().map((name) => `export const ${name} = "${mdi[name]}";\n`).join(""),
);
copy("@mdi/js/LICENSE", "mdi/LICENSE");
+457
View File
@@ -0,0 +1,457 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 4
[[package]]
name = "autocfg"
version = "1.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53"
[[package]]
name = "bitflags"
version = "2.13.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06"
[[package]]
name = "byteorder"
version = "1.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "34fb07aac3b9f547c7af8dc897dfe73c10847b6c71130c364bdd7891d979c816"
[[package]]
name = "can-recorder"
version = "0.1.0"
dependencies = [
"embedded-can",
"signal-hook",
"socketcan",
]
[[package]]
name = "cfg-if"
version = "1.0.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600"
[[package]]
name = "cfg_aliases"
version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527"
[[package]]
name = "darling"
version = "0.20.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fc7f46116c46ff9ab3eb1597a45688b6715c6e628b5c133e288e709a29bcb4ee"
dependencies = [
"darling_core",
"darling_macro",
]
[[package]]
name = "darling_core"
version = "0.20.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0d00b9596d185e565c2207a0b01f8bd1a135483d02d9b7b0a54b11da8d53412e"
dependencies = [
"fnv",
"ident_case",
"proc-macro2",
"quote",
"strsim",
"syn 2.0.119",
]
[[package]]
name = "darling_macro"
version = "0.20.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fc34b93ccb385b40dc71c6fceac4b2ad23662c7eeb248cf10d529b7e055b6ead"
dependencies = [
"darling_core",
"quote",
"syn 2.0.119",
]
[[package]]
name = "derive_builder"
version = "0.20.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "507dfb09ea8b7fa618fcf76e953f4f5e192547945816d5358edffe39f6f94947"
dependencies = [
"derive_builder_macro",
]
[[package]]
name = "derive_builder_core"
version = "0.20.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2d5bcf7b024d6835cfb3d473887cd966994907effbe9227e8c8219824d06c4e8"
dependencies = [
"darling",
"proc-macro2",
"quote",
"syn 2.0.119",
]
[[package]]
name = "derive_builder_macro"
version = "0.20.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ab63b0e2bf4d5928aff72e83a7dace85d7bba5fe12dcc3c5a572d78caffd3f3c"
dependencies = [
"derive_builder_core",
"syn 2.0.119",
]
[[package]]
name = "either"
version = "1.19.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0e9c71c2167ca323c882b99918929403426e2373ea17242ff5653e0d5e1058be"
[[package]]
name = "embedded-can"
version = "0.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e9d2e857f87ac832df68fa498d18ddc679175cf3d2e4aa893988e5601baf9438"
dependencies = [
"nb",
]
[[package]]
name = "errno"
version = "0.3.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e35d6e78f4cebb90e51d543db8fe41528851d6deeef6ef21ebd4bfdc1e784776"
dependencies = [
"libc",
"windows-sys",
]
[[package]]
name = "fnv"
version = "1.0.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1"
[[package]]
name = "getset"
version = "0.1.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6cf442baaabe4213ce7d1239afc26c039180b6456da2cededa316ae2c8a77a77"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.119",
]
[[package]]
name = "hex"
version = "0.4.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70"
[[package]]
name = "ident_case"
version = "1.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b9e0384b61958566e926dc50660321d12159025e767c18e043daf26b70104c39"
[[package]]
name = "libc"
version = "0.2.191"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a"
[[package]]
name = "linux-raw-sys"
version = "0.12.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53"
[[package]]
name = "lock_api"
version = "0.4.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "224399e74b87b5f3557511d98dff8b14089b3dadafcab6bb93eab67d3aace965"
dependencies = [
"scopeguard",
]
[[package]]
name = "log"
version = "0.4.35"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c"
[[package]]
name = "memoffset"
version = "0.9.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "488016bfae457b036d996092f6cb448677611ce4449e970ceaf42695203f218a"
dependencies = [
"autocfg",
]
[[package]]
name = "nb"
version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8d5439c4ad607c3c23abf66de8c8bf57ba8adcd1f129e699851a6e43935d339d"
[[package]]
name = "neli"
version = "0.7.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6b152f4f18819e638ea350a740b16de75099302b5ec3a58f4f8766ef2fcf695d"
dependencies = [
"bitflags",
"byteorder",
"derive_builder",
"getset",
"libc",
"linux-raw-sys",
"log",
"neli-proc-macros",
"parking_lot",
]
[[package]]
name = "neli-proc-macros"
version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "05d8d08c6e98f20a62417478ebf7be8e1425ec9acecc6f63e22da633f6b71609"
dependencies = [
"either",
"proc-macro2",
"quote",
"serde",
"syn 2.0.119",
]
[[package]]
name = "nix"
version = "0.31.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2bc81ce8148d3b4f3274da811f11cdd824ae661ee4ef732cdb229825cf5be7f7"
dependencies = [
"bitflags",
"cfg-if",
"cfg_aliases",
"libc",
"memoffset",
]
[[package]]
name = "parking_lot"
version = "0.12.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "93857453250e3077bd71ff98b6a65ea6621a19bb0f559a85248955ac12c45a1a"
dependencies = [
"lock_api",
"parking_lot_core",
]
[[package]]
name = "parking_lot_core"
version = "0.9.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1"
dependencies = [
"cfg-if",
"libc",
"redox_syscall",
"smallvec",
"windows-link",
]
[[package]]
name = "proc-macro2"
version = "1.0.107"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9"
dependencies = [
"unicode-ident",
]
[[package]]
name = "quote"
version = "1.0.47"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001"
dependencies = [
"proc-macro2",
]
[[package]]
name = "redox_syscall"
version = "0.5.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d"
dependencies = [
"bitflags",
]
[[package]]
name = "scopeguard"
version = "1.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49"
[[package]]
name = "serde"
version = "1.0.229"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba"
dependencies = [
"serde_core",
"serde_derive",
]
[[package]]
name = "serde_core"
version = "1.0.229"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48"
dependencies = [
"serde_derive",
]
[[package]]
name = "serde_derive"
version = "1.0.229"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348"
dependencies = [
"proc-macro2",
"quote",
"syn 3.0.10",
]
[[package]]
name = "signal-hook"
version = "0.4.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "49f7447afd772ca79ad17ae0a3972a6b0df0cb4b80990fd82707593e9e012a74"
dependencies = [
"libc",
"signal-hook-registry",
]
[[package]]
name = "signal-hook-registry"
version = "1.4.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c4db69cba1110affc0e9f7bcd48bbf87b3f4fc7c61fc9155afd4c469eb3d6c1b"
dependencies = [
"errno",
"libc",
]
[[package]]
name = "smallvec"
version = "1.16.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3244542535d5de959d90ec55d1b5ff0fd2bb7b1310223907d5f11932847f7b59"
[[package]]
name = "socket2"
version = "0.6.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4"
dependencies = [
"libc",
"windows-sys",
]
[[package]]
name = "socketcan"
version = "4.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "472e000403167b1e2f65cfcf8ff235fe94b911f9bd9bdbc1f48047b8a1cf49aa"
dependencies = [
"bitflags",
"embedded-can",
"hex",
"libc",
"log",
"nb",
"neli",
"nix",
"smallvec",
"socket2",
"thiserror",
]
[[package]]
name = "strsim"
version = "0.11.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f"
[[package]]
name = "syn"
version = "2.0.119"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297"
dependencies = [
"proc-macro2",
"quote",
"unicode-ident",
]
[[package]]
name = "syn"
version = "3.0.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79"
dependencies = [
"proc-macro2",
"quote",
"unicode-ident",
]
[[package]]
name = "thiserror"
version = "2.0.21"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e"
dependencies = [
"thiserror-impl",
]
[[package]]
name = "thiserror-impl"
version = "2.0.21"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524"
dependencies = [
"proc-macro2",
"quote",
"syn 3.0.10",
]
[[package]]
name = "unicode-ident"
version = "1.0.27"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563"
[[package]]
name = "windows-link"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"
[[package]]
name = "windows-sys"
version = "0.61.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc"
dependencies = [
"windows-link",
]
+9
View File
@@ -0,0 +1,9 @@
[package]
name = "can-recorder"
version = "0.1.0"
edition = "2024"
[dependencies]
embedded-can = "0.4"
signal-hook = "0.4.6"
socketcan = "4.0.0"
+150
View File
@@ -0,0 +1,150 @@
//! can-recorder: SocketCAN frames into ASAM MDF4 files (CAN bus logging, the
//! CANedge layout: asammdf with a DBC, CSS Electronics' tools, CANalyzer).
//!
//! can-recorder [--segment SECONDS] OUT_DIR IFACE...
//!
//! One file per segment, `OUT_DIR/<UTC start>.mf4`, every interface in it
//! (CAN_DataFrame.BusChannel 1, 2… in the order given), written whole when
//! the segment ends (default 300 s) or on SIGTERM/SIGINT: a crash or a power
//! cut loses at most the segment being recorded, every file there is a
//! finished one (written as .part, then renamed). The frames' time: the
//! kernel's receive timestamp.
//!
//! ponytail: a segment is held in memory until written (24 B a frame: 300 s
//! of a full 500 kbit/s bus ≈ 30 MB); shorter segments if that's a lot.
mod mf4;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::mpsc;
use std::time::{Duration, SystemTime, UNIX_EPOCH};
use embedded_can::{Frame, Id};
use socketcan::{CanFrame, CanSocket, Socket, SocketOptions};
struct Segment {
records: mf4::Records,
start: SystemTime,
}
fn main() {
let mut args: Vec<String> = std::env::args().skip(1).collect();
let mut segment = Duration::from_secs(300);
if args.first().map(String::as_str) == Some("--segment") && args.len() > 1 {
segment = Duration::from_secs(args[1].parse().expect("--segment: seconds"));
args.drain(..2);
}
if args.len() < 2 || args.len() > 256 {
eprintln!("usage: can-recorder [--segment SECONDS] OUT_DIR IFACE...");
std::process::exit(2);
}
let out = PathBuf::from(&args[0]);
std::fs::create_dir_all(&out).expect("OUT_DIR");
let ifaces = args[1..].to_vec();
let stop = Arc::new(AtomicBool::new(false));
for signal in [signal_hook::consts::SIGTERM, signal_hook::consts::SIGINT] {
signal_hook::flag::register(signal, Arc::clone(&stop)).expect("signal handler");
}
let (tx, rx) = mpsc::sync_channel::<(u8, SystemTime, CanFrame)>(100_000);
for (i, iface) in ifaces.iter().cloned().enumerate() {
let tx = tx.clone();
std::thread::spawn(move || read(i as u8 + 1, &iface, tx));
}
drop(tx);
let mut current: Option<Segment> = None;
while !stop.load(Ordering::Relaxed) {
let next = rx.recv_timeout(Duration::from_millis(500));
// a quiet bus still gets its segment closed on time
let now = match &next {
Ok((_, at, _)) => *at,
Err(_) => SystemTime::now(),
};
if current.as_ref().is_some_and(|s| now.duration_since(s.start).unwrap_or_default() >= segment) {
write(&out, &ifaces, current.take().unwrap());
}
match next {
Ok((bus, at, CanFrame::Data(frame))) => {
let s = current.get_or_insert_with(|| Segment { records: mf4::Records::default(), start: at });
let t = at.duration_since(s.start).unwrap_or_default().as_secs_f64();
let (id, extended) = match frame.id() {
Id::Standard(id) => (u32::from(id.as_raw()), false),
Id::Extended(id) => (id.as_raw(), true),
};
s.records.push(t, bus, id, extended, frame.data());
}
Ok(_) | Err(mpsc::RecvTimeoutError::Timeout) => {} // remote and error frames: not logged
Err(mpsc::RecvTimeoutError::Disconnected) => break,
}
}
if let Some(s) = current {
write(&out, &ifaces, s);
}
}
/// An interface's frames into the channel; reopened every 5 s while it's
/// missing or down.
fn read(bus: u8, iface: &str, tx: mpsc::SyncSender<(u8, SystemTime, CanFrame)>) {
loop {
match CanSocket::open(iface).and_then(|socket| socket.set_recv_timestamp(true).map(|()| socket)) {
Ok(socket) => loop {
match socket.read_frame_with_timestamp() {
Ok((frame, at)) => {
if tx.send((bus, at, frame)).is_err() {
return;
}
}
Err(e) => {
eprintln!("can-recorder: {iface}: {e}");
break;
}
}
},
Err(e) => eprintln!("can-recorder: {iface}: {e}"),
}
std::thread::sleep(Duration::from_secs(5));
}
}
fn write(out: &Path, ifaces: &[String], s: Segment) {
if s.records.count == 0 {
return;
}
let since_epoch = s.start.duration_since(UNIX_EPOCH).unwrap_or_default();
let bytes = mf4::file(&s.records, since_epoch.as_nanos() as u64, ifaces);
let path = out.join(format!("{}.mf4", utc_stamp(since_epoch.as_secs())));
let part = path.with_extension("mf4.part");
match std::fs::write(&part, &bytes).and_then(|()| std::fs::rename(&part, &path)) {
Ok(()) => eprintln!("can-recorder: {} frames → {}", s.records.count, path.display()),
Err(e) => eprintln!("can-recorder: {}: {e}", path.display()),
}
}
/// YYYYMMDD-HHMMSS (UTC) of a unix time — Howard Hinnant's civil_from_days.
fn utc_stamp(secs: u64) -> String {
let (days, rem) = ((secs / 86_400) as i64, secs % 86_400);
let z = days + 719_468;
let era = z.div_euclid(146_097);
let doe = z - era * 146_097;
let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
let mp = (5 * doy + 2) / 153;
let d = doy - (153 * mp + 2) / 5 + 1;
let m = if mp < 10 { mp + 3 } else { mp - 9 };
let y = yoe + era * 400 + i64::from(m <= 2);
format!("{y:04}{m:02}{d:02}-{:02}{:02}{:02}", rem / 3600, rem / 60 % 60, rem % 60)
}
#[cfg(test)]
mod tests {
#[test]
fn utc_stamp() {
assert_eq!(super::utc_stamp(0), "19700101-000000");
assert_eq!(super::utc_stamp(1_709_164_800 + 3_723), "20240229-010203");
assert_eq!(super::utc_stamp(4_102_444_799), "20991231-235959");
}
}
+167
View File
@@ -0,0 +1,167 @@
//! A minimal ASAM MDF 4.10 writer for CAN bus logging: one data group, one
//! channel group of `CAN_DataFrame` records the way the ASAM bus logging
//! spec and CANedge lay them out (asammdf's extract_bus_logging and DBC
//! decoding, CSS Electronics' converters, CANalyzer read it).
//!
//! A record (24 bytes):
//! 0..8 Timestamp (f64, s since the header's start time)
//! 8 CAN_DataFrame.BusChannel (u8, 1 = the first interface)
//! 9..13 CAN_DataFrame.ID (29 bits)
//! 13 CAN_DataFrame.IDE (bit 0: an extended ID)
//! 14 CAN_DataFrame.DLC (4 bits)
//! 15 CAN_DataFrame.DataLength (u8)
//! 16..24 CAN_DataFrame.DataBytes (8 bytes)
pub const RECORD: usize = 24;
const UNSIGNED: u8 = 0;
const FLOAT: u8 = 4;
const BYTES: u8 = 10;
const BUS_EVENT: u32 = 1 << 10; // cn_flags
const CG_BUS_EVENT: u16 = 1 << 1;
const CG_PLAIN_BUS_EVENT: u16 = 1 << 2;
/// The frames of a segment, as records.
#[derive(Default)]
pub struct Records {
data: Vec<u8>,
pub count: u64,
}
impl Records {
pub fn push(&mut self, t: f64, bus: u8, id: u32, extended: bool, data: &[u8]) {
let len = data.len().min(8);
self.data.extend_from_slice(&t.to_le_bytes());
self.data.push(bus);
self.data.extend_from_slice(&(id & 0x1FFF_FFFF).to_le_bytes());
self.data.push(extended as u8);
self.data.push(len as u8); // classic CAN: DLC = length
self.data.push(len as u8);
let mut bytes = [0u8; 8];
bytes[..len].copy_from_slice(&data[..len]);
self.data.extend_from_slice(&bytes);
self.count += 1;
}
}
/// The blocks, each 8-byte aligned; links patched in once their target is written.
struct File(Vec<u8>);
impl File {
fn block(&mut self, id: &[u8; 4], links: usize, data: &[u8]) -> u64 {
let at = self.0.len() as u64;
let len = 24 + 8 * links + data.len();
self.0.extend_from_slice(b"##");
self.0.extend_from_slice(&id[2..]);
self.0.extend_from_slice(&[0; 4]);
self.0.extend_from_slice(&(len as u64).to_le_bytes());
self.0.extend_from_slice(&(links as u64).to_le_bytes());
self.0.resize(self.0.len() + 8 * links, 0);
self.0.extend_from_slice(data);
self.0.resize(self.0.len().next_multiple_of(8), 0);
at
}
fn link(&mut self, block: u64, n: usize, target: u64) {
let at = block as usize + 24 + 8 * n;
self.0[at..at + 8].copy_from_slice(&target.to_le_bytes());
}
fn text(&mut self, id: &[u8; 4], s: &str) -> u64 {
let mut data = s.as_bytes().to_vec();
data.push(0);
self.block(id, 0, &data)
}
/// A CN block: name, type, where in the record; its unit if any.
#[allow(clippy::too_many_arguments)]
fn channel(&mut self, name: &str, cn_type: u8, sync: u8, data_type: u8, byte: u32, bit: u8, bits: u32, flags: u32, unit: Option<&str>) -> u64 {
let mut d = vec![cn_type, sync, data_type, bit];
d.extend_from_slice(&byte.to_le_bytes());
d.extend_from_slice(&bits.to_le_bytes());
d.extend_from_slice(&flags.to_le_bytes());
d.extend_from_slice(&0u32.to_le_bytes()); // invalidation bit
d.extend_from_slice(&[0, 0, 0, 0]); // precision, reserved, attachment count
d.resize(d.len() + 6 * 8, 0); // value range and limits: none
let cn = self.block(b"##CN", 8, &d);
let tx = self.text(b"##TX", name);
self.link(cn, 2, tx);
if let Some(unit) = unit {
let tx = self.text(b"##TX", unit);
self.link(cn, 6, tx);
}
cn
}
}
/// The whole file: `start_ns` since 1970 (UTC), `buses` the interfaces in BusChannel order.
pub fn file(records: &Records, start_ns: u64, buses: &[String]) -> Vec<u8> {
let mut f = File(Vec::with_capacity(records.data.len() + 4096));
// ID block: no block header, 64 bytes
f.0.extend_from_slice(b"MDF 4.10 canrec ");
f.0.extend_from_slice(&[0; 4]);
f.0.extend_from_slice(&410u16.to_le_bytes());
f.0.resize(64, 0);
let mut time = start_ns.to_le_bytes().to_vec();
time.extend_from_slice(&[0, 0, 0, 0, 0, 0, 0, 0]); // tz, dst (UTC), time flags, class, flags, reserved
let mut hd_data = time.clone();
hd_data.resize(32, 0); // start angle, distance
let hd = f.block(b"##HD", 6, &hd_data);
let fh = f.block(b"##FH", 2, &time);
f.link(hd, 1, fh);
let comment = format!(
"<FHcomment><TX>recorded</TX><tool_id>can-recorder</tool_id><tool_vendor>maptool</tool_vendor><tool_version>{}</tool_version></FHcomment>",
env!("CARGO_PKG_VERSION")
);
let md = f.text(b"##MD", &comment);
f.link(fh, 1, md);
let dg = f.block(b"##DG", 4, &[0; 8]); // record id size 0: one channel group
f.link(hd, 0, dg);
let mut cg_data = Vec::new();
cg_data.extend_from_slice(&0u64.to_le_bytes()); // record id
cg_data.extend_from_slice(&records.count.to_le_bytes());
cg_data.extend_from_slice(&(CG_BUS_EVENT | CG_PLAIN_BUS_EVENT).to_le_bytes());
cg_data.extend_from_slice(&(b'.' as u16).to_le_bytes()); // path separator
cg_data.extend_from_slice(&[0; 4]);
cg_data.extend_from_slice(&(RECORD as u32).to_le_bytes());
cg_data.extend_from_slice(&0u32.to_le_bytes()); // invalidation bytes
let cg = f.block(b"##CG", 6, &cg_data);
f.link(dg, 1, cg);
let acq = f.text(b"##TX", "CAN");
f.link(cg, 2, acq);
let si = f.block(b"##SI", 3, &[2, 2, 0, 0, 0, 0, 0, 0]); // type bus, bus type CAN
let si_name = f.text(b"##TX", &buses.join(", "));
f.link(si, 0, si_name);
f.link(si, 1, si_name);
f.link(cg, 3, si);
let time = f.channel("Timestamp", 2, 1, FLOAT, 0, 0, 64, 0, Some("s"));
f.link(cg, 1, time);
let frame = f.channel("CAN_DataFrame", 0, 0, BYTES, 8, 0, 16 * 8, BUS_EVENT, None);
f.link(time, 0, frame);
let parts = [
("CAN_DataFrame.BusChannel", UNSIGNED, 8, 0, 8),
("CAN_DataFrame.ID", UNSIGNED, 9, 0, 29),
("CAN_DataFrame.IDE", UNSIGNED, 13, 0, 1),
("CAN_DataFrame.DLC", UNSIGNED, 14, 0, 4),
("CAN_DataFrame.DataLength", UNSIGNED, 15, 0, 8),
("CAN_DataFrame.DataBytes", BYTES, 16, 0, 64),
];
let mut prev: Option<u64> = None;
for (name, data_type, byte, bit, bits) in parts {
let cn = f.channel(name, 0, 0, data_type, byte, bit, bits, BUS_EVENT, None);
match prev {
Some(p) => f.link(p, 0, cn),
None => f.link(frame, 1, cn), // the frame's composition: its first part
}
prev = Some(cn);
}
let dt = f.block(b"##DT", 0, &records.data);
f.link(dg, 2, dt);
f.0
}
+59 -23
View File
@@ -31,6 +31,11 @@ services:
# Optional: blank disables the LiveTrack webhook endpoint rather than # Optional: blank disables the LiveTrack webhook endpoint rather than
# failing to start, since it's not needed for the app's core function. # failing to start, since it's not needed for the app's core function.
LIVETRACK_WEBHOOK_SECRET: ${LIVETRACK_WEBHOOK_SECRET:-} LIVETRACK_WEBHOOK_SECRET: ${LIVETRACK_WEBHOOK_SECRET:-}
# Optional: the home MQTT broker with the car's live data (GNSS
# tracker, ITS-G5) — a read-only user; blank turns /api/live off.
MQTT_URL: ${MQTT_URL:-}
MQTT_USERNAME: ${MQTT_USERNAME:-}
MQTT_PASSWORD: ${MQTT_PASSWORD:-}
# Optional, only read by data/plugins/p4n2gpx/'s own p4n2gpx.rb (not # Optional, only read by data/plugins/p4n2gpx/'s own p4n2gpx.rb (not
# part of this repo — see docs/deployment.adoc) if that private # part of this repo — see docs/deployment.adoc) if that private
# plugin is present; blank just means it fails with its own "could # plugin is present; blank just means it fails with its own "could
@@ -38,9 +43,9 @@ services:
# as the other optional secrets here. P4N_USER/P4N_PASSWORD alone # as the other optional secrets here. P4N_USER/P4N_PASSWORD alone
# don't actually work here — park4night's login form is behind # don't actually work here — park4night's login form is behind
# invisible reCAPTCHA, which no browserless login can satisfy — so # invisible reCAPTCHA, which no browserless login can satisfy — so
# P4N_SESSION_COOKIE (a real logged-in browser's session cookie, # the cookies of a Firefox logged in on the host (the plugin's own
# copied out by hand and refreshed whenever it expires) is what # firefox_cookie.py on a host timer, docs/deployment.adoc) or P4N_SESSION_COOKIE (a browser's Cookie header, by hand —
# p4n2gpx.rb's make_session actually ends up using. # also settable in the plugins panel) are what it ends up using.
P4N_USER: ${P4N_USER:-} P4N_USER: ${P4N_USER:-}
P4N_PASSWORD: ${P4N_PASSWORD:-} P4N_PASSWORD: ${P4N_PASSWORD:-}
P4N_SESSION_COOKIE: ${P4N_SESSION_COOKIE:-} P4N_SESSION_COOKIE: ${P4N_SESSION_COOKIE:-}
@@ -54,6 +59,20 @@ services:
# that only forwards to maptool itself, so app.rb's GET /kiwix/* # that only forwards to maptool itself, so app.rb's GET /kiwix/*
# proxies to this instead of handing the browser this address. # proxies to this instead of handing the browser this address.
KIWIX_URL: "http://kiwix:8080" KIWIX_URL: "http://kiwix:8080"
# The valhalla service below, same story as KIWIX_URL.
VALHALLA_URL: "http://valhalla:8002"
# Google Takeout exports (the "Saved" lists), mounted below; app.rb
# imports a new one hourly. Remove both lines to turn it off.
TAKEOUT_DIR: /app/takeout
# Library sync (lib/maptool/sync.rb): the shared token on the server
# and its clients; a client also has the server's URL (Sync button).
SYNC_SERVER_URL: ${SYNC_SERVER_URL:-}
SYNC_TOKEN: ${SYNC_TOKEN:-}
# Only on a server with no reverse proxy in front (the car's): these
# networks count as logged in. Never on one behind a proxy.
TRUSTED_NETWORKS: ${TRUSTED_NETWORKS:-}
# The car's server: the update button (lib/maptool/updater.rb).
SELF_UPDATE: ${SELF_UPDATE:-}
volumes: volumes:
# Uploaded GPX files and the offline PMTiles extract — kept outside # Uploaded GPX files and the offline PMTiles extract — kept outside
# the image so a rebuild/redeploy doesn't wipe them (see # the image so a rebuild/redeploy doesn't wipe them (see
@@ -73,32 +92,26 @@ services:
# recursively relabels that file to maptool's own private label, # recursively relabels that file to maptool's own private label,
# locking kiwix out of it (and kiwix's :Z would do the same back). # locking kiwix out of it (and kiwix's :Z would do the same back).
- ./data:/app/data:z - ./data:/app/data:z
# Where the Google Drive backup syncs the scheduled Takeout (a plain
# Fakes a GNSS fix (a loop around Bratislava, see # directory; changed files get moved to ../../old/, so the bind stays
# bin/gnss_simulator.rb/docs/development.adoc) since there's no real # valid). Read-only. Shared :z like data/ above: brick enforces
# receiver attached here — the "GNSS" control would otherwise just show # SELinux and the backup tree is unlabeled_t, unreadable for a
# "no fix" always. Remove this service (and nothing else) whenever a real # container; the root sync job is unaffected by the relabel and new
# receiver/gpsd setup replaces it. network_mode ties it to maptool's own # files inherit the directory's label.
# network namespace rather than a bridge network, since GpsdClient # TAKEOUT_HOST_DIR: another server (the car's) points it at an empty dir.
# connects to a hardcoded 127.0.0.1:2947 — same as gpsd itself normally - ${TAKEOUT_HOST_DIR:-/srv/backup/gdrive/my-drive/current/Takeout}:/app/takeout:ro,z
# being local to the machine it serves.
gnss-simulator:
image: maptool:latest
depends_on:
- maptool
restart: unless-stopped
network_mode: "service:maptool"
command: ["ruby", "bin/gnss_simulator.rb"]
# Serves an offline Wikipedia ZIM for the popup's "Nearby on Wikipedia" # Serves an offline Wikipedia ZIM for the popup's "Nearby on Wikipedia"
# link (see docs/development.adoc for where to get one and drop it in — # link (see docs/development.adoc for where to get one and drop it in —
# same "not part of the repo, place it under ./data locally" story as # same "not part of the repo, place it under ./data locally" story as
# offline.pmtiles/terrain.pmtiles). On the default compose network (not # offline.pmtiles/terrain.pmtiles). On the default compose network (not
# network_mode: "service:maptool" — unlike gnss-simulator this doesn't # network_mode: "service:maptool" — KIWIX_URL above reaches it by this
# need a hardcoded localhost port, KIWIX_URL above reaches it by this
# service's own name), so maptool and kiwix stay independent containers. # service's own name), so maptool and kiwix stay independent containers.
# Keeps restarting (harmlessly) if data/kiwix/wikipedia.zim isn't there # Waits (entrypoint below) while data/kiwix/wikipedia.zim is missing or
# yet — GET /api/kiwix just reports unavailable until it comes up. # empty — GET /api/kiwix just reports unavailable until it comes up. Not
# a restart loop: on the car's server (host network, placeholder ZIM
# until the map pull brings it) one restart a second meant a new veth
# each time, and avahi's mDNS announcements of them filled the Pi's Wi-Fi.
# #
# The volume binds the exact *file* path, not the data/kiwix/ directory — # The volume binds the exact *file* path, not the data/kiwix/ directory —
# deliberately, so data/kiwix/wikipedia.zim can be a symlink to wherever # deliberately, so data/kiwix/wikipedia.zim can be a symlink to wherever
@@ -123,11 +136,34 @@ services:
# this same prefix off incoming request paths, so both ends agree on # this same prefix off incoming request paths, so both ends agree on
# it) — no ports: mapping needed, nothing outside the compose network # it) — no ports: mapping needed, nothing outside the compose network
# ever talks to this container directly. # ever talks to this container directly.
# The image's own entrypoint (dumb-init, start.sh), after the wait.
entrypoint: ["/usr/bin/dumb-init", "--", "sh", "-c", "until [ -s /data/wikipedia.zim ]; do sleep 60; done; exec /usr/local/bin/start.sh \"$$@\"", "kiwix"]
command: ["--urlRootLocation=/kiwix", "/data/wikipedia.zim"] command: ["--urlRootLocation=/kiwix", "/data/wikipedia.zim"]
volumes: volumes:
# :z, shared for the same reason as maptool's own ./data mount above. # :z, shared for the same reason as maptool's own ./data mount above.
- ./data/kiwix/wikipedia.zim:/data/wikipedia.zim:z - ./data/kiwix/wikipedia.zim:/data/wikipedia.zim:z
# Offline routing (docs/routing-design.adoc). Valhalla's own image (it
# isn't packaged for Debian, so not in maptool's), running
# data/routing/service.sh — bin/routing-service.sh, copied there by
# maptool at boot so the two always match; the loop below waits for it
# on a first start. Mounts the whole data/ (not just data/routing/) so it
# can hard-link Geofabrik extracts from data/geofabrik_cache/ (a link
# can't cross two bind mounts). Serves port 8002 on the compose network
# only, maptool proxies to it.
valhalla:
image: ghcr.io/valhalla/valhalla:3.9.3
restart: unless-stopped
depends_on:
- maptool
# maptool copies the deployed script here at boot. On a redeploy the
# old copy is still there, so wait (up to a minute) for a fresh one;
# a restart of this container alone runs the one that's there.
command: ["bash", "-c", "s=/data/routing/service.sh; t=$$(date +%s); until [ -f $$s ] && { [ $$(stat -c %Y $$s) -ge $$t ] || [ $$(($$(date +%s) - t)) -gt 60 ]; }; do sleep 2; done; exec bash $$s"]
volumes:
# :z, shared for the same reason as maptool's own ./data mount above.
- ./data:/data:z
networks: networks:
default: default:
enable_ipv6: true enable_ipv6: true
+76 -91
View File
@@ -31,7 +31,7 @@ opened in a browser.
| `data/` | `data/`
| Local, gitignored data files, e.g. `offline.pmtiles` and uploaded | Local, gitignored data files, e.g. `offline.pmtiles` and uploaded
GPX/FIT files under `data/gpx/`. tracks and points (`library.sqlite`, `library/`, older `gpx/`).
| `lib/maptool/` | `lib/maptool/`
| Application code beyond routing: the GPX/FIT parsers and file store. | Application code beyond routing: the GPX/FIT parsers and file store.
@@ -66,9 +66,9 @@ approximate the online look — two independently-maintained palettes
that drifted out of sync (building opacity, road casings, park that drifted out of sync (building opacity, road casings, park
boundaries) every time one side changed. Planetiler's default profile boundaries) every time one side changed. Planetiler's default profile
*is* OpenMapTiles, so `offlineStyle()` now just clones the same parsed *is* OpenMapTiles, so `offlineStyle()` now just clones the same parsed
Liberty JSON `ONLINE_STYLE` already fetched, repoints its `sources`, Liberty JSON `ONLINE_STYLE_TEMPLATE` already fetched, repoints its `sources`,
`glyphs`, and `sprite` at local copies, and applies the exact same `glyphs`, and `sprite` at local copies, and applies the exact same
`ONLINE_STYLE_PATCH` recolor (below) — one palette, one place to tune `patchOnlineStyle` recolor (below) — one palette, one place to tune
it, correct on both sides by construction rather than by re-checking it, correct on both sides by construction rather than by re-checking
every time something changes. every time something changes.
@@ -111,22 +111,25 @@ snapshot under `public/vendor/liberty-sprite/` — both `offlineStyle()`
and the online style otherwise share identical `glyphs`/`sprite` and the online style otherwise share identical `glyphs`/`sprite`
roles, just resolved to local vs. `tiles.openfreemap.org` URLs. roles, just resolved to local vs. `tiles.openfreemap.org` URLs.
`public/js/map.js`'s `ONLINE_STYLE_PATCH` — applied to whichever `public/js/map_themes.js`'s `patchOnlineStyle` — applied to whichever
source is loaded, online or offline (see above) — nudges Liberty's source is loaded, online or offline (see above) — recolors Liberty's
OpenMapTiles layer ids towards a warm, National Park Service OpenMapTiles layer ids after the National Park Service's Park Tiles
"Park Tiles"-inspired look. A few of these values are the genuine "Standard" style (`PARK_TILES_PATCH`). Colors are sampled from the Park
paint colors pulled from a public Park Tiles style JSON Tiles legend swatches (`nps.gov/maps/web/img/legend/*-standard.png`)
(`nps.gov/lib/npmap.js/style/ck72fwp2642dv07o7tbqinvz4.json`, the plus the public "Imagery" style JSON
"Imagery" variant — the only one of NPS's four styles served from a (`nps.gov/lib/npmap.js/style/ck72fwp2642dv07o7tbqinvz4.json`, the only
plain, unauthenticated URL; "Standard"/"Slate"/"Light" resolve through one of NPS's four styles served from a plain, unauthenticated URL;
Mapbox Studio's private API with an access token, which isn't "Standard"/"Slate"/"Light" resolve through Mapbox Studio's private API
something to piggyback on even though it's technically visible in with an access token, which isn't something to piggyback on even though
their own JS bundle) — background, the park/protected-area green, the it's technically visible in their own JS bundle) — see
two road-importance tiers, and the park-boundary line color. The rest `docs/nps-resources.adoc` for the values. The park fill is moved above
are reasoned to match that same warm family (olive greens, muted blue, landcover, so a whole park reads as one flat sage like theirs, with a
brown road casings) rather than sourced. This is deliberately light-green tint band inside its boundary line; Natural Earth's
partial — labels, halos, rail, and minor overlays (cemetery/hospital/ low-zoom color relief is hidden. Line widths stay Liberty's own.
school/pitch/track shading) are left at Liberty's own defaults. `/symbols.html` draws its map legend from the same patched style.
(An earlier, looser "Park Tiles-inspired" palette, `ONLINE_STYLE_PATCH`,
was replaced by this one — it used Park Tiles' park *point* green
`#b3e378` as the area fill.)
+ +
Recreating the *color choices* is fine — that's not the kind of thing Recreating the *color choices* is fine — that's not the kind of thing
a data license restricts — but the actual Park Tiles *service* stays a data license restricts — but the actual Park Tiles *service* stays
@@ -138,10 +141,10 @@ irrelevant to this app either way now, since it never talks to NPS's
tile service, only ever OpenFreeMap/Geofabrik. tile service, only ever OpenFreeMap/Geofabrik.
`loadOnlineStyle` (`public/js/map.js`) fetches Liberty's live `loadOnlineStyle` (`public/js/map.js`) fetches Liberty's live
`style.json` once, patches it in place, and uses the resulting object `style.json` once and keeps it unpatched as `ONLINE_STYLE_TEMPLATE`;
everywhere `ONLINE_STYLE` used to be a plain URL string — MapLibre `onlineStyle()` patches a fresh copy for each `setStyle` — MapLibre
accepts a style object anywhere it accepts a style URL, so accepts a style object anywhere it accepts a style URL, so `applyStyle`'s
`applyStyle`'s `map.setStyle(... : ONLINE_STYLE)` needed no change. `map.setStyle` takes either.
That fetch runs before the map (and the rest of the page) is That fetch runs before the map (and the rest of the page) is
constructed — a top-level `await` — so there's no flash of Liberty's constructed — a top-level `await` — so there's no flash of Liberty's
own colors before the patch lands; a 3s timeout and a catch-all fall own colors before the patch lands; a 3s timeout and a catch-all fall
@@ -235,8 +238,7 @@ may not even read the same way there.
`GeolocateControl` — same button, reusing its exact CSS classes/icon `GeolocateControl` — same button, reusing its exact CSS classes/icon
(`.maplibregl-ctrl-geolocate`) rather than a new one, so it's a visual (`.maplibregl-ctrl-geolocate`) rather than a new one, so it's a visual
drop-in — but sourced differently. This app has its own GNSS receiver drop-in — but sourced differently. This app has its own GNSS receiver
(gpsd, possibly `bin/gnss_simulator.rb`'s simulated one — see (over CAN in the car, to come; see TODO.adoc), and "find my
`docs/development.adoc`/`docs/deployment.adoc`), and "find my
location" should mean that receiver, not a device's separate (and location" should mean that receiver, not a device's separate (and
often less accurate, e.g. wifi-based) location service — but only often less accurate, e.g. wifi-based) location service — but only
once it's actually turned on, via the sidebar's "GNSS" icon once it's actually turned on, via the sidebar's "GNSS" icon
@@ -341,35 +343,39 @@ upload GPX, FIT or GeoJSON files by dragging them in, organize them
into folders (also by dragging), and toggle each one on the map into folders (also by dragging), and toggle each one on the map
individually. individually.
Storage:: Files are stored as-is under `data/gpx/`, in a Storage:: An item-based library in `data/library.sqlite`
folder hierarchy the user manages directly — `Maptool::GpxStore` (`Maptool::Library`, `lib/maptool/library.rb`; full design and the
(`lib/maptool/gpx_store.rb`) provides `save`, `create_folder`, later phases in `docs/library-design.adoc`): folders, and in them
`delete_file`, `delete_folder` and `move`. Every path coming from the points, tracks, routes and shapes, each with a stable id, timestamps,
client (a folder to create/upload/move into, a file path in a URL) is a tombstone on delete and a global change counter (`rev`) for sync.
resolved with `File.expand_path` and checked against the store root An upload is kept as-is under `data/library/sources/<uuid>/` and split
before touching the filesystem, so `../..`-style path traversal can't into items; a feature already in the target folder (same fingerprint)
escape `data/gpx/`; `delete_folder` additionally refuses an empty path isn't added twice. Points from a GPX holding exactly one track carry
or one that resolves to the store root itself, so it can never `rm that track as `parent_id`. Files from before the library (`data/gpx/`,
-rf` the whole store. still `GpxStore`) were migrated on first start, each into a subfolder
`GET /api/gpx/tree` returns the resulting folder/file tree as JSON, named after it as one `layer` item still drawn from that file —
which the panel renders recursively (folders as `<details>`, files as `data/gpx/` itself is never written to any more except to edit notes
a checkbox, both with a delete button). inside such a layer. Folder paths from the client are split on `/`
and `.`/`..` rejected; nothing from the client is a filesystem path.
`GET /api/library/tree` returns folders and *nodes* — one checkbox
each: a track/route/layer (`item:<id>`, drawn with its child points)
or a folder's loose points and shapes (`points:<folder id>`).
Drag & drop:: The dropzone at the top of the panel accepts one or more Drag & drop:: The dropzone at the top of the panel accepts one or more
`.gpx`/`.fit`/`.geojson` files, or a `.zip` (`POST /api/gpx`, `.gpx`/`.fit`/`.geojson` files, or a `.zip` (`POST /api/library/import`,
multipart) into the top level, or click it to browse instead. A multipart) into the top level, or click it to browse instead. A
`.geojson` file needs no format conversion — it's already the shape `.geojson` file needs no format conversion — it's already the shape
`gpx.js` expects — so `GpxStore#geojson` just serves it straight from `gpx.js` expects — so `GpxStore#geojson` just serves it straight from
disk (see "Rendering" below); useful for a file already in this app's disk (see "Rendering" below); useful for a file already in this app's
own schema, e.g. one exported elsewhere in that shape, or a previous own schema, e.g. one exported elsewhere in that shape, or a previous
`GET /api/gpx/file` response saved and re-uploaded. A `.zip` — `GET /api/library/node` response saved and re-uploaded. A `.zip` —
Garmin's bulk/FIT export format — isn't stored itself: Garmin's bulk/FIT export format — isn't stored itself:
`save_zip_entries` (`app.rb`) expands it with `rubyzip` and saves each `save_zip_entries` (`app.rb`) expands it with `rubyzip` and saves each
`.gpx`/`.fit`/`.geojson` entry it contains individually (flattened — `.gpx`/`.fit`/`.geojson` entry it contains individually (flattened —
any folder structure inside the zip is discarded), skipping anything any folder structure inside the zip is discarded), skipping anything
else (readme files, etc.) it might hold. An already-uploaded file (a else (readme files, etc.) it might hold. An already-uploaded file (a
`.gpx-tree__file` row, `draggable`) can be dragged onto a folder to `.gpx-tree__file` row, `draggable`) can be dragged onto a folder to
move it there (`POST /api/gpx/move`), or dropped anywhere else in the move it there (`POST /api/library/move`), or dropped anywhere else in the
tree to move it back to the top level; an OS file can also be dropped tree to move it back to the top level; an OS file can also be dropped
directly onto a folder to upload straight into it. Both drag sources directly onto a folder to upload straight into it. Both drag sources
land on the same drop targets and are told apart by a custom land on the same drop targets and are told apart by a custom
@@ -379,29 +385,15 @@ map) gets moved, its map layers are re-added under the new path so it
stays visible; if it (or its containing folder) gets deleted, its stays visible; if it (or its containing folder) gets deleted, its
layers are removed instead. layers are removed instead.
Rendering:: Checking a file fetches `GET /api/gpx/file/<path>`, routed Rendering:: Checking a node fetches `GET /api/library/node/<key>`:
by extension to `Maptool::Gpx` or `Maptool::Fit` its items as one GeoJSON `FeatureCollection` (each feature's
(`lib/maptool/gpx.rb`/`fit.rb`) for parsing, and both convert to the `properties.id` is its item id), or for a migrated layer its old file
same GeoJSON `FeatureCollection` shape so the frontend doesn't need to converted by `Maptool::Gpx`/`Maptool::Fit` through `GpxStore#geojson`,
know which format it got. `GpxStore#geojson` caches that conversion which caches that conversion next to the file (`<path>.geojson`,
alongside the source file (`<path>.geojson`, invalidated by mtime) — invalidated by mtime) — REXML parsing a several-thousand-waypoint POI
REXML parsing a several-thousand-waypoint POI export (a park4night export can take tens of seconds. An import pays that parse once, at
area export, say) can take tens of seconds, and without a cache that upload time, under the frontend's "Uploading…" status. A file that
cost repeats on every single toggle. `GpxStore#save` also calls fails to parse is rejected at import (422).
`geojson` itself right after writing the file, so that cost is paid
once during the upload (covered by the frontend's own "Uploading…"
status) instead of on whichever toggle happens to be first — a silent
multi-second hang on a checkbox click reads as broken in a way the
same wait during an upload doesn't. A file that fails to parse still
saves fine either way; the error just surfaces on first view instead.
A `.geojson` upload skips this path entirely — `geojson` reads and
returns it directly, no cache file, no `Gpx`/`Fit` involved.
`GpxStore#save` converting eagerly means `cached` is `true` for
almost everything in the tree — the one exception is a `.gpx`/`.fit`
dropped straight into `data/gpx/` on the filesystem, bypassing the
app, and not yet opened. Badging the common case would just be noise,
so the file tree's icon (`PENDING_ICON`, `public/js/icons.js`) marks
that exception instead of the (near-universal) ready state.
+ +
The tree always shows a `.gpx`/`.fit` file under its real, as-uploaded The tree always shows a `.gpx`/`.fit` file under its real, as-uploaded
name, even once cached — it briefly grew a `.geojson` suffix there name, even once cached — it briefly grew a `.geojson` suffix there
@@ -421,11 +413,11 @@ document-level click listener the same way an outside click closes a
threaded through `onlyOneSidePanelOpen`. A directly-uploaded `.geojson` threaded through `onlyOneSidePanelOpen`. A directly-uploaded `.geojson`
keeps its own name and both menu items download the same (identical) keeps its own name and both menu items download the same (identical)
content — redundant there, not wrong. Both downloads (`GET content — redundant there, not wrong. Both downloads (`GET
/api/gpx/file/<path>?download=original`/`?download=geojson`) require /api/library/node/<key>?download=original`/`?download=geojson`) require
login, same as upload/move/delete/create-folder, so the whole button — login, same as upload/move/delete/create-folder, so the whole button —
not just its menu items — is left out of the DOM when logged out not just its menu items — is left out of the DOM when logged out
rather than shown and failing on click (see "Authentication" below); rather than shown and failing on click (see "Authentication" below);
`GET /api/gpx/file` itself stays open to anyone otherwise (viewing a `GET /api/library/node` itself stays open to anyone otherwise (viewing a
file on the map isn't a write action), just not `?download=...` on it. file on the map isn't a write action), just not `?download=...` on it.
Each menu item is a real `<a href>` (so right-click/middle-click still Each menu item is a real `<a href>` (so right-click/middle-click still
do something sensible), but a plain navigation would land a logged-out do something sensible), but a plain navigation would land a logged-out
@@ -487,20 +479,17 @@ reaches a layer, rather than a `coalesce` in a style expression — see
below for why. Unlike a pin, which has to anchor at its tip, the badge below for why. Unlike a pin, which has to anchor at its tip, the badge
is centered directly on the coordinate with plain default anchoring, is centered directly on the coordinate with plain default anchoring,
which also means the category-glyph layer on top needs no offset math: which also means the category-glyph layer on top needs no offset math:
both layers just share the same center anchor at `[0, 0]`. A small both layers just share the same center anchor at `[0, 0]`. The icon set
curated icon set (`public/js/icons.js`'s `POI_ICONS`, covering the (`public/js/icons.js`'s `POI_ICONS`: every NPS symbol by its own name,
categories p4n2gpx actually uses, not an exhaustive OsmAnd icon set) plus the OsmAnd names p4n2gpx/Overpass POIs use mapped onto them)
draws a white glyph on top of the badge for any waypoint whose `icon` draws a white glyph on top of the badge for any waypoint whose `icon`
matches a known key (filtered out entirely for anything else, so an matches a known key (filtered out entirely for anything else, so an
unrecognized icon key just falls back to a plain colored badge rather unrecognized icon key just falls back to a plain colored badge rather
than a broken/missing image warning). All seven glyphs are the National than a broken/missing image warning). The glyphs are the National
Park Service's own map symbols — pulled from Park Service's own map symbols, all of them, vendored by
`github.com/nationalparkservice/npmap5-plugins`'s bundled `bin/nps-symbols-sync.mjs` (CC0, see `docs/nps-resources.adoc`) and
`symbol-library` (CC0-licensed, an actively-maintained monorepo that's browsable at `/symbols.html`. Only the ones a shown file uses get
the designated replacement for the same org's older standalone rasterized.
`symbol-library` repo, per its maintainer) — a professional,
purpose-built icon set beats hand-drawing "fuel pump"/"picnic table"
glyphs from scratch.
+ +
Both the badge and the glyphs are rasterized from their source SVGs Both the badge and the glyphs are rasterized from their source SVGs
(an `<img>` → `<canvas>` → `ImageData` round trip, since `map.addImage` (an `<img>` → `<canvas>` → `ImageData` round trip, since `map.addImage`
@@ -705,23 +694,18 @@ toggling is a cheap re-render of just that strip.
== Live GNSS position == Live GNSS position
A "GNSS" map control (`public/js/gnss.js`) shows the fix from a local A "GNSS" map control (`public/js/gnss.js`) shows the fix from a local
GNSS receiver (a real one, plugged into the machine running the GNSS receiver (the car's, over CAN, to come — distinct from
server, or `bin/gnss_simulator.rb`'s simulated one — distinct from
`LocateControl`'s browser-geolocation fallback, `navigator.geolocation`, `LocateControl`'s browser-geolocation fallback, `navigator.geolocation`,
which the OS may or may not derive from such a receiver at all — which the OS may or may not derive from such a receiver at all —
see "Finding your location" above). see "Finding your location" above).
`lib/maptool/gpsd_client.rb` is a small client for Nothing feeds it for now: gpsd support was dropped in favor of the
https://gpsd.io[gpsd]'s JSON protocol over TCP (port 2947 by default): car's GNSS over CAN. Whatever reads the receiver keeps the latest fix
it watches for TPV — "time-position-velocity", gpsd's term for a fix — in `app.rb`'s `GNSS_LATEST`, guarded by a mutex since the HTTP threads
reports and yields each as a plain hash, reconnecting on any I/O error read it concurrently.
so a receiver that isn't plugged in yet (or gpsd not running) is not
fatal. `app.rb` runs one of these in a background thread for the
whole process and keeps the latest fix in `GNSS_LATEST`, guarded by a
mutex since the HTTP threads read it concurrently.
`GET /api/gnss/position`, polled by the frontend every 1.5s, is a `GET /api/gnss/position`, polled by the frontend every 1.5s, is a
deliberate choice over a push channel (SSE/WebSocket): gpsd itself deliberate choice over a push channel (SSE/WebSocket): a receiver
only reports at roughly 1Hz, so a push channel buys nothing here, and only reports at roughly 1Hz, so a push channel buys nothing here, and
it sidesteps a real problem — Sinatra's `stream(:keep_open)` helper, it sidesteps a real problem — Sinatra's `stream(:keep_open)` helper,
absent an EventMachine reactor (i.e. under plain threaded Puma, as absent an EventMachine reactor (i.e. under plain threaded Puma, as
@@ -754,10 +738,11 @@ exposed via Docker/nginx as `map.priesol.net`.
The GPX store's read endpoints (viewing the map, the folder tree, The GPX store's read endpoints (viewing the map, the folder tree,
individual files) are public — anyone with the URL can look. Its write individual files) are public — anyone with the URL can look. Its write
endpoints (`POST /api/gpx`, `POST /api/gpx/folder`, `DELETE endpoints (`POST /api/library/import`, `POST /api/library/folder`,
/api/gpx/file/*`, `DELETE /api/gpx/folder/*`, `POST /api/gpx/move`) `DELETE /api/library/node/:key`, `DELETE /api/library/folder/*`,
`POST /api/library/move`, `/api/library/notes`)
require login, guarded by `require_login!` in `app.rb` — and so does require login, guarded by `require_login!` in `app.rb` — and so does
exporting a file (`GET /api/gpx/file/*?download=...`), even though exporting a node (`GET /api/library/node/:key?download=...`), even though
plain viewing of that same URL (no `?download`) doesn't; not a write plain viewing of that same URL (no `?download`) doesn't; not a write
exactly, but treated the same as the others rather than left open. exactly, but treated the same as the others rather than left open.
The tree UI (`public/js/gpx.js`) mirrors this: every control for a The tree UI (`public/js/gpx.js`) mirrors this: every control for a
+301 -11
View File
@@ -58,7 +58,9 @@ expect this to flip the other way, `/srv/docker` symlinked to
references it, and the sync step doesn't need to special-case it references it, and the sync step doesn't need to special-case it
the way an earlier version of this layout did) — uploaded GPX the way an earlier version of this layout did) — uploaded GPX
files, `offline.pmtiles`, `terrain.pmtiles`, and files, `offline.pmtiles`, `terrain.pmtiles`, and
`kiwix/wikipedia.zim` (see `docs/development.adoc` for each). `kiwix/wikipedia.zim` (see `docs/development.adoc` for each), and
`routing/` (the offline routing graph, built and served by the
`valhalla` compose service, see `docs/routing-design.adoc`).
Persisted via that bind mount, so a redeploy never touches it. Persisted via that bind mount, so a redeploy never touches it.
Also where a private import plugin belongs (`data/plugins/<name>/`, Also where a private import plugin belongs (`data/plugins/<name>/`,
see `lib/maptool/plugins.rb`'s `PLUGINS_DIRS`) — `build/plugins/` see `lib/maptool/plugins.rb`'s `PLUGINS_DIRS`) — `build/plugins/`
@@ -135,6 +137,9 @@ It's not created by hand on the server — the deploy job's "Write
.env" step regenerates it on every deploy from repo-level Gitea .env" step regenerates it on every deploy from repo-level Gitea
Actions secrets (*Settings → Actions → Secrets*): `SESSION_SECRET`, Actions secrets (*Settings → Actions → Secrets*): `SESSION_SECRET`,
`OAUTH_CLIENT_ID`, `OAUTH_CLIENT_SECRET`, `MAPTOOL_ALLOWED_GITEA_USER`. `OAUTH_CLIENT_ID`, `OAUTH_CLIENT_SECRET`, `MAPTOOL_ALLOWED_GITEA_USER`.
The non-secret ones — `OAUTH_CLIENT_ID`, `MAPTOOL_ALLOWED_GITEA_USER`,
`P4N_USER`, `MQTT_URL`, `MQTT_USERNAME` — may be Actions *Variables*
instead (the step reads `vars.X || secrets.X`); the rest stay Secrets.
The OAuth2 ones aren't named `GITEA_OAUTH_CLIENT_*` to match the `.env` The OAuth2 ones aren't named `GITEA_OAUTH_CLIENT_*` to match the `.env`
var names 1:1 — Gitea rejects secret names starting with `GITEA_` or var names 1:1 — Gitea rejects secret names starting with `GITEA_` or
`GITHUB_` as reserved — but the workflow step maps them to the right `GITHUB_` as reserved — but the workflow step maps them to the right
@@ -160,17 +165,302 @@ id/secret to store as the two `OAUTH_CLIENT_*` secrets above.
usernames, e.g. `randy,friend1,friend2` — not their emails, the usernames, e.g. `randy,friend1,friend2` — not their emails, the
`login` field from Gitea's `/api/v1/user`. `login` field from Gitea's `/api/v1/user`.
== GNSS simulator Optional: `MQTT_URL`, `MQTT_USERNAME`, `MQTT_PASSWORD` (same names in
`.env`; the URL and username aren't secret and may be Actions
*Variables* instead of Secrets, the password a Secret) — the home MQTT broker the car's ESPHome nodes
publish to, read by `/api/live` (the "Vehicle & ITS-G5" overlay): the
GNSS tracker's `mcu-tracker/location` and the ITS-G5 receiver's
`mcu-its-g5/decoded`. Use a read-only broker user limited to those
topics. Blank `MQTT_URL` turns it off. The URL needs a name the
container can resolve — `ha.local` (mDNS) doesn't resolve inside it,
`mqtt://ha.priesol.net:1883` does.
`docker-compose.yaml`'s `gnss-simulator` service (`bin/gnss_simulator.rb`, == The car's server (rpi-dev, later the van's CM5)
also documented for local dev in `docs/development.adoc`) runs
alongside `maptool` in production too, sharing its network namespace A second maptool on a Raspberry Pi (Debian, arm64, rootful podman +
(`network_mode: "service:maptool"`) so it's reachable at the podman-compose), laid out like brick's: `/srv/podman/maptool/{build,data,.env}`,
hardcoded `127.0.0.1:2947` `Maptool::GpsdClient` expects — there's no the same `podman-compose@.service` unit. Deployed by hand for now (the
real GNSS receiver attached to the server, so without this the "GNSS" working tree rsynced into `build/`), not by CI.
control would just always show "no fix". It drives a loop around
Bratislava; remove the service block (nothing else needs to change) Its `.env` adds:
whenever a real receiver/gpsd setup replaces it.
* `TRUSTED_NETWORKS=connected` — requests from the subnets the Pi is
directly on (whichever Wi-Fi/LAN, looked up per request; loopback too)
count as logged in, since Gitea's OAuth needs internet and its redirect
URL is brick's. Comma-separated CIDRs work too, also next to `connected`. Only on a server no reverse proxy sits in front of —
never on brick, where every request comes from the proxy.
* `TAKEOUT_HOST_DIR` — an empty directory (the Takeout import is brick's).
* `SYNC_SERVER_URL` (`https://map.priesol.net`) and `SYNC_TOKEN`: it's a sync client.
* `SELF_UPDATE=1` — the update button (below).
=== park4night's login from the Pi's Firefox
The private p4n2gpx plugin (`data/plugins/p4n2gpx/`) borrows a logged-in
browser's cookies (park4night's login is behind reCAPTCHA). Log in once in
Firefox on the Pi as `randy` (on its screen or over remote desktop) and
leave it logged in: there's no "remember me", the login is only the
PHPSESSID session cookie, which Firefox keeps in its session store rather
than in `cookies.sqlite`. A timer on the host runs the plugin's
`firefox_cookie.py` as that user: it copies only park4night.com's cookies
(both stores; profiles in `~/.config/mozilla/firefox` or `~/.mozilla/firefox`) into
`data/plugins/p4n2gpx/firefox-cookie` (mode 600). The profile itself (every
synced password, every site's cookies) is never mounted into the container.
Every 15 min it also asks park4night with them, which keeps the session
alive; once park4night refuses it, it stops asking until the next login.
The plugin, `p4n-cookie.service` and `p4n-cookie.timer` live in the private
home-gitops repo (`ansible/files/p4n2gpx/`), not here: its
`deploy-p4n2gpx` workflow runs `ansible/playbooks/p4n2gpx.yaml` against
the Pi on every change.
=== Updates (a button, not CI)
CI deploys brick only: the car's server is often offline, and a deploy
mustn't restart it mid-drive. Instead it checks Gitea itself (every
10 min while online; the repo is public, no token): when `main` has a
newer commit whose CI passed, a ⟳ button shows in the topbar; a click
writes `data/update/request.json`, `maptool-update.path` starts
`bin/update-maptool.sh` (as root — the container writes `data/` as root),
which downloads that commit's archive from Gitea, stages it as
`build.new/` (next to `build/`, the same filesystem — `/tmp` is RAM on the
Pi, a move from there would be a copy), swaps it in with two renames (the
previous one stays as `build.old/`), restarts maptool and waits up to
15 min for `/api/health` to answer with the new revision — if it doesn't
(the image didn't build, the app crashes), it moves the new tree to
`build.bad/`, puts the old one back and restarts again. It reports in
`data/update/status.json`; the page reloads on the new revision. Asked
twice for the same commit, the second run does nothing.
What survives what: a reload or a closed page — the update runs on the
host; a power cut while downloading — `build/` untouched, the button shows
again; a cut between the two renames (milliseconds) — `maptool-recover`
puts `build.new/` (complete by then) or `build.old/` back at boot; a cut
after them — the new tree is in place, maptool builds and starts at boot.
----
# /etc/systemd/system/maptool-update.path
[Unit]
Description=Update maptool when the app asks
[Path]
PathExists=/srv/podman/maptool/data/update/request.json
[Install]
WantedBy=multi-user.target
# /etc/systemd/system/maptool-update.service
[Unit]
Description=Update maptool to the commit the app asked for
After=network-online.target
[Service]
Type=oneshot
TimeoutStartSec=30min
ExecStart=/srv/podman/maptool/build/bin/update-maptool.sh
# /etc/systemd/system/maptool-recover.service
[Unit]
Description=Put maptool's build/ back if a power cut fell into an update's swap
Before=podman-compose@maptool.service
[Service]
Type=oneshot
ExecStart=/bin/sh -c 'cd /srv/podman/maptool && [ -d build ] || { [ -f build.new/app.rb ] && mv build.new build || mv build.old build; }'
[Install]
WantedBy=multi-user.target
----
`systemctl enable --now maptool-update.path maptool-recover.service`. Back by hand:
`mv build build.bad && mv build.old build`, restart.
=== Library sync (both ways, OsmAnd-style)
brick is the server, the car's maptool a client: the client's Sync button
(Tracks & Points header, shown only where `SYNC_SERVER_URL` is set) pulls
the server's changes, then pushes its own (`lib/maptool/sync.rb`; the
server's `GET /api/sync/changes`, `GET`/`PUT /api/sync/source/:id`,
`POST /api/sync/apply`, all guarded by the shared `SYNC_TOKEN`). Newer
`updated_at` wins, source files come along, progress in the client's
`data/sync_state.json`. Over the public URL, so no VPN is needed for it.
On brick the CI deploy writes `SYNC_TOKEN` (a Gitea secret) into `.env`.
=== CAN (GNSS node)
SocketCAN interfaces live in the host's network namespace, so on the car's
server maptool runs with host networking: a `docker-compose.override.yaml`
next to the compose symlink (podman-compose picks it up), with kiwix and
Valhalla published on loopback since their service names no longer resolve
from maptool:
----
services:
maptool:
network_mode: host
environment:
KIWIX_URL: "http://127.0.0.1:8080"
VALHALLA_URL: "http://127.0.0.1:8002"
kiwix:
ports: ["127.0.0.1:8080:8080"]
valhalla:
ports: ["127.0.0.1:8002:8002"]
----
Our esphome-canopen nodes describe themselves: on a node's first heartbeat
maptool reads over SDO its TPDOs (`0x1800+n`, `0x1A00+n`) and, per mapped
entity, its type, name, unit and range (`canopen_entities`' OD, its
`OBJECT_DICTIONARY.md`) and decodes them with no hand-written signals
(`lib/maptool/can_discovery.rb`); cached in `data/can_nodes/<node>.json`
by the TPDO layout hash (`0x3002`:1, checked every 10 min — read again after
an OTA that changed the layout). Signals are named `<node name>.<entity
name>` (the ESPHome name, e.g. `mcu-stm32-xiao-c5-2.Latitude`, as
`/can.html` lists them); `data/can.json` only maps the ones the app uses to
its names, with a unit conversion where needed (the node's km/h → m/s).
`"signals"` stays for devices that don't describe themselves (the car
bridge), `"discover": false` turns it off:
----
{ "interfaces": ["can0"],
"aliases": {
"mcu-stm32-xiao-c5-2.Latitude": "gnss.lat",
"mcu-stm32-xiao-c5-2.Longitude": "gnss.lon",
"mcu-stm32-xiao-c5-2.Altitude": "gnss.alt",
"mcu-stm32-xiao-c5-2.Speed": { "name": "gnss.speed", "scale": 0.2777777777777778, "unit": "m/s" },
"mcu-stm32-xiao-c5-2.HDOP": "gnss.hdop",
"mcu-stm32-xiao-c5-2.Satellites": "gnss.satellites",
"mcu-stm32-xiao-c5-2.Pitch": "imu.pitch",
"mcu-stm32-xiao-c5-2.Roll": "imu.roll",
"mcu-stm32-xiao-c5-2.IMU Temperature": "imu.temperature",
"mcu-stm32-xiao-c5-2.Field Strength X": "mag.x",
"mcu-stm32-xiao-c5-2.Field Strength Y": "mag.y",
"mcu-stm32-xiao-c5-2.Field Strength Z": "mag.z",
"mcu-stm32-xiao-c5-2.Heading": "imu.heading" } }
----
What node 0x21 sends (read from it, 2026-11-30): TPDO1 0x2A1 pitch, roll
(-180..180°) and the IMU's temperature, Sensor16; TPDO2 0x3A1
latitude/longitude, REAL32; TPDO3 0x4A1 altitude, speed (km/h), HDOP
(Sensor16) and satellites (Sensor8); TPDO4 0x221 the HMC5883L, the field
±200 µT and the heading 0..360° (ESPHome's plain `atan2(-x, y)` is
−180..180, the node adds 360 to the negatives — a filter on `heading:`).
No tilt compensation or hard-iron calibration yet, so only roughly right
standing level. The node goes operational by itself, so no `nmt_start`.
Sensor16/8: `value = wire * (max - min) / (2^n - 2) + min`, all ones unknown.
Keypads for drive mode (`lib/maptool/keypad.rb`), the way PDMs do it: a
device's keys and knobs become named channels, and the screen profile's
`"bindings"` say what each one does (`public/drive/road.json`) — nothing
in the server knows what a key is for.
----
"keypads": [
{ "name": "pad", "protocol": "pkp", "node": 20, "keys": 8, "heartbeat_node": 32,
"inputs": { "E1": "mcu-stm32-xiao-c5.encoder_1", "E1 press": "mcu-stm32-xiao-c5.encoder_button_1",
"E2": "mcu-stm32-xiao-c5.encoder_2", "E3": "mcu-stm32-xiao-c5.encoder_3",
"E3 press": "mcu-stm32-xiao-c5.encoder_button_3" } } ]
----
The knobs turn freely once entity 7's bits are set — an action writes it
(a number is REAL32 at `0x2002 + 0x10 × entity`, sub 1; 7.0 = knobs 1–3):
`{ "name": "Encoders 1-3 free turning", "node": 32, "index": "0x2072",
"subindex": 1, "data": "0000e040" }`, once (the node keeps it).
`name` prefixes its channels (`pad.K1`, `pad.E3`, `pad.E3 press`).
`"protocol": "pkp"` — a Blink Marine PKP CANopen keypad, or ours speaking
its protocol (home-gitops `docs/canopen-nodes.adoc`): K1… come from its
TPDO1 (`0x180+node`, a bit each, `keys` of them) with no signals, and its
key LEDs take colours. Without it a keypad is just `inputs`: channel → any
signal, can.json's own or a discovered node's (as `/can.html` names them);
a channel starting with E is a knob (a free-turning counter mod 256 — set
its bit in the 8Encoder's "Encoder Relative Modes", entity 7, e.g. by an
`actions` SDO write), anything else a key. `heartbeat_node`: whose
heartbeat says it's there (a real PKP has it off; ours is the XIAO's own
node 0x20, the one with the knobs) — default `node`. The PKP waits for
NMT Start: `"nmt_start": true`.
A binding in the profile: `{ "input": "pad.K5", "action": "menu", "menu":
"close", "led": "cyan", "led_on": "green" }` — `action` a screen key's
(`trip`, `zoomIn`, `follow`, …) or a knob's (`zoom`, `panX`, `panY`,
`rows`), `menu` what it does while a menu is open (`rows`, `enter`,
`close`, or any action), `led` the key LED's colour (red green blue yellow
cyan magenta white), `led_on` while its screen key is on. `GET
/api/keypad?since=<seq>` is a long poll of the channels' events, `PUT
/api/keypad/leds` (`{"keypad": "pad", "on": {"K1": "cyan"}, "blink": {}}`)
sets a PKP's key LEDs.
The bindings are edited in `/keypad.html` (after the Design canvas'
GridBinding): the keypads drawn as can.json has them, a key or knob picked
by a tap or by pressing it on the keypad, then what it drives (a screen
key's action or an output), the output's mode, what it does in an open
menu, its LEDs. Saved, they're this car's own, `data/drive/bindings.json`
(`GET`/`PUT`/`DELETE /api/keypad/bindings`), and win over the profile's;
"Back to the profile's" deletes the file. Drive mode takes them when it
loads.
Outputs (`lib/maptool/outputs.rb`): relay modules on the bus, maptool the
controller, nothing measured (no current, no feedback). A binding with an
`output` in place of an `action` drives one channel:
----
"outputs": [ { "name": "relays", "node": 48, "channels": 8, "simulated": true,
"labels": { "1": "Lights", "2": "Winch in" } } ]
----
`{ "input": "pad.E2 press", "output": "relays.1", "mode": "hold", "led":
"red" }` — `mode`: `toggle` (default), `on`, `off`, `hold` (on while held;
off when let go or when the keypad's heartbeat is gone), `pulse` (on for
`pulse_s`, 1 s by default), `positions` (`"outputs": [a, b, …]`: a press
steps off → a → b → … → off, a knob turns up and down, one on at a time,
the last off before the next on), `strobe` (a press starts / stops it
blinking, `period_s` a whole on + off, 1 s), `dimmer` (a knob sets the
level by `step` %, 10; a press switches it on / off — only a module with
`"dimmable": true` dims, a relay just switches). A PKP key bound to an
output shows `led` (red by default) while it's on (a position chosen, a
strobe running), whatever the screen says. The module's
protocol is ours (after LD's native CAN control): RPDO1 `0x200+node`, a
bit per channel (byte 0 channels 1–8, byte 1 9–16) — a dimmable one a
byte per channel, 0–255, 8 channels at most — the whole state sent
on every change and every 100 ms; the module is to switch everything off
after 2 s without a frame. `"simulated": true` sends nothing, the state
only lives in the server — `/sim.html` shows the relays and switches
them by hand. `GET /api/outputs`, `POST /api/outputs/<module>/<n>` (`{"on":
true}`, empty toggles). An output in the profile that this car's can.json
hasn't is skipped.
CANopen TIME (`lib/maptool/can_time.rb`): maptool sends the TIME object
(`0x100`, CiA 301 TIME_OF_DAY, UTC: ms after midnight + days since
1984-01-01) once a second, but only while no other node does — once the
GNSS node sends it (esphome-canopen has no TIME yet), maptool stays quiet
until it's been silent 3 s. Nothing goes out while the Pi's clock is
unset (before 2025). `"time": false` in can.json turns it off; `/can.html`
shows who's sending it.
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 (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. 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).
Following the position (GNSS, Locate) pauses when the map is moved by
hand — to look around or change the route — while the marker keeps
moving; "Back to the position" or 15 s without touching the map resumes
it (`followPosition`, `gnss.js`).
=== Map data (one way)
`bin/pull-maps.sh`, run by `maptool-pull-maps.timer` (10 min after boot,
then every 6 h) as `randy`: pulls the pmtiles, routing, places, hiking
trails, the ZIM kiwix serves (`kiwix/wikipedia.zim`, not other ZIMs there) and the NPS maps from brick over HTTPS — the same public
URL and `SYNC_TOKEN` as the library sync (read from `.env`), so no SSH or
VPN. brick lists them (`GET /api/sync/maps`: size, mtime, path; the list
of files is app.rb's `MAP_SYNC_FILES`/`MAP_SYNC_DIRS`) and serves each
(`GET /api/sync/maps/file?path=`); a cut-off download resumes (Range) on
the next try or run, files gone on brick are removed, maptool restarts
when something changed. They're GBs, so only at home by default (brick's
LAN address `HOME_HOST` answers); `HOME_HOST=` pulls anywhere.
== Garmin LiveTrack session webhook == Garmin LiveTrack session webhook
+577
View File
@@ -0,0 +1,577 @@
= Design: the park brochure and the cockpit
MapTool has two jobs with two moods, and a style for each:
* *Planning, dreaming, remembering* — the map, the library, the trip, the
search: the *NPS* look. Warm Park Tiles cartography (`map_themes.js`),
the brochures and their symbols (`docs/nps-resources.adoc`), the olive
accent.
* *Driving* — whatever the driver glances at: the dashboard, the next
maneuver, the speed limit, the switch panel, warnings: the *cockpit*
look. Avionics (PFD/MFD) and chartplotters: displays over a bus, dark
bezel, big numbers, no decoration, colors that always mean the same.
They aren't two designs bolted together: the NPS brochures are Massimo
Vignelli's *Unigrid* (1977) — a strict grid, a black band with a white
sans-serif title, lots of white space, few colors. That's the same
modernist restraint as a glass cockpit. The black band is the shared
element: the topbar (`#1a1a1a`) is the brochure's band, the instruments'
bezel is the same black.
== Colors
Defined once as custom properties on `:root` (`public/css/style.css`);
nothing outside them for these meanings.
=== Planning (NPS)
[cols="1,1,3"]
|===
|Token |Value |Use
|`--accent` |`#546619` |active items, selected options, primary buttons (NPS boundary olive)
|`--accent-bg` |`#e1e5cf` |their light background (sage)
|`--band` |`#1a1a1a` |the Unigrid black band: the topbar, panel headers, and the instruments' bezel
|===
The map's own colors are Park Tiles' (`map_themes.js`), not tokens.
=== Instruments (cockpit)
Each color has one meaning, as in avionics — so a glance is enough and
a color never decorates.
[cols="1,1,3"]
|===
|Token |Value |Means
|`--inst-bezel` |`--band` at the card's opacity |the instrument's background
|`--inst-text` |`#f2f2f2` |values
|`--inst-muted` |`#9aa0a6` |labels, scales, what's inactive
|`--inst-ok` |`#3ccf4e` |normal, engaged (a switch on, a node alive)
|`--inst-caution` |`#ffb300` |attention: past a soft limit (roll > 20°), off the route, a stale signal
|`--inst-warning` |`#ff3b30` |act now: over the speed limit, past a hard limit, a fault
|`--inst-active` |`#e040fb` |*magenta*: the active route and the next waypoint / maneuver / lane to take — the avionics convention for what navigation is following
|`--inst-selected` |`#00d5ff` |*cyan*: a value you set yourself (a speed bug, the camper's own limit, a chosen target)
|===
Road signs stay road signs: the speed limit is the white disc with the
red ring — read as a sign, not as a color (`--sign-*`, only dimmed by
night).
=== Day, dusk, night (after IHO S-52)
Marine electronic charts (ECDIS) have the most worked-out rules for one
display across bright sun and a dark bridge — the IHO's S-52 (Edition
6.1.1, 2015): *three colour tables, Day, Dusk and Night*, every color a
named token with a value per table (the Presentation Library's Appendix
A). We do the same: the tokens above, three sets of values, `<html
data-palette="dusk|night">` (Day the default), meanings unchanged between
them. From S-52:
* *Day*: a light background with dark foreground details, strong contrast —
bright sun washes a display out. (Our instruments keep their dark bezel,
a full-opacity one for sun on the screen.)
* *Dusk*: a black-background table, "for optional use by day as well as at
twilight".
* *Night*: dark background, light foreground, dim enough not to impair night
vision; at low light colors are hard to tell apart, so important things
get a second cue (shape, line style), not color alone. Adjust by
contrast, not brightness (dark colors drop to black).
* Anything added on the chart's screen (panels, text) "should never generate
more light than the chart display itself" at night, and text panels
mustn't outshine the chart.
Our night values are roughly a third of Day's luminance, warm greys, blue
kept low; no white areas (the speed limit sign dims too). The map has its
own night palette (`NightMap`, `map_themes.js`); a Dusk map is still to do.
The night mode sets the palette (`map.js`): automatic by the sun or on →
Night (with the night map), "◑" → Dusk over the day map, off → Day. The
planning UI's greys are the `--ui-*` tokens (`--ui-bg`, `--ui-bg-2` for
hover, fills and the section bands, `--ui-line`, `--ui-fg`, `--ui-muted`);
MapLibre's controls and popups take them too, and a dark palette sets
`color-scheme: dark` (native checkboxes, scrollbars) and lifts the map
controls off the dark map (`--ui-bg-2` with a `--ui-line` ring). The first
try (2026-12-01) left the section bands light, checkboxes white and the
controls black on black — tokens missed by the first pass.
The driving mode (`driving.js`, "Drive" in the topbar) is the cockpit's
input side: big band-black buttons down the map's left — follow, zoom,
2D/3D, night, the route overview — and the planning sidebar hidden.
=== How others switch day and night (research, 2026-12-01)
[cols="1,3"]
|===
|Who |How
|Garmin G1000 / G3X (aviation)
|Color scheme *Day / Night / Auto* apart from the *backlight*, which a
photocell sets on its own (a curve between a minimum and maximum, and a
time constant so it doesn't jump), or the aircraft's dimmer bus, or by
hand (down to 0.22 % on the PFD).
|Garmin GPSMAP (boats)
|Color mode Day / Night / Auto (by the time of day or the light outside);
the night scheme itself selectable: *full color, red and black, or green
and black*; the backlight a setting of its own; display settings shared
with the other displays over NMEA 2000. Night charts "in muted tones
with enhanced contrast".
|Raymarine (boats)
|Night mode: red text and icons on dark backgrounds; warns that going
back to Day at night jumps to full brightness and spoils night vision.
|Garmin zūmo (motorbikes)
|Day / Night / Auto (by the time of day), brightness by hand — no
light sensor found in the manuals.
|Ships (IMO MSC.191(79), IEC 62288, S-52)
|Colors and brightness for daylight, dusk and night, readable everywhere
on the bridge "with due consideration to the night vision" of the watch;
color never alone (size, shape, orientation too), red for alarms.
Furuno: Day / Dusk / Night palettes, each in a gray or blue variant, at
about 110 / 50 / 5 cd/m²; JRC: Day Bright, Day Whiteback, Day Blackback,
Dusk, Night.
|Android Auto / CarPlay (cars)
|Automatic by the car's headlights or its light sensor, Day / Night by
hand; known to flip in tunnels and under bridges.
|===
What it means for us:
* *Colors and brightness are two controls.* Everyone keeps the palette
(which colors) apart from the backlight (how bright); Night at ~5 cd/m²
is a backlight thing — CSS can't get a lit display that dim. The car's
display's backlight (DDC/CI or the panel's own dimmer) wanted for that.
* *Auto by what the vehicle knows:* the sun today; the headlights from
the car's CAN once they're on the bus (as Android Auto), a light sensor
on a node later (as the photocell) — with hysteresis, not flipping in a
tunnel.
* *A red night* (red/black) as Garmin's and Raymarine's option, for the
darkest roads.
* *One setting for all the car's screens* (Garmin shares it over NMEA
2000): the night mode the server's, not each browser's, when they're in
the same car.
* *No flash on the way back to Day* at night: the switch eased in.
Sources: Garmin G1000 manual (Display backlighting); Garmin G3X install
manual (photocell parameters); Garmin GPSMAP display settings and
"Changing the color mode" help pages; Garmin's "Navigate confidently in
the dark" blog; Raymarine display mode docs; Garmin zūmo 395/396 display
settings; IMO MSC.191(79) §5.3, §5.5; Furuno FAR-2107 / FE-800 and JRC
JAN-701B manuals; Google Maps / Waze help and 9to5Google on Android Auto.
=== Buttons while driving: how others do it (research, 2026-12-01)
Our driving bar (`driving.js`) came from OsmAnd's map buttons: seven
76×64 px buttons down the left (follow, zoom ±, 2D/3D, night, route
overview, exit). What the others do:
[cols="1,3"]
|===
|Who |How
|Android Auto (Google's car design guidelines)
|Touch targets at least *76×76 dp* (the distance to the head unit, quick
taps); content readable in *2 s*, a response within 0.25 s; the map's
*action strip at most four buttons* (pan, recenter, zoom in/out). Google
Maps: *recenter only appears once the map was moved* and goes when
tapped; the compass toggles heading-up / north-up; route overview,
sound (mute / alerts only) and report on the edges.
|Garmin zūmo XT (motorbikes)
|The rider *picks which buttons the map shows* (a wrench, top left); the
rest in a side panel from the bottom right; reviewers still find the
buttons small with gloves.
|Garmin G1000 (aviation)
|*Softkeys*: a fixed row of physical keys along the display's bottom
bezel, their labels drawn on the screen right above them, changing with
the page; concentric knobs for values. Nothing to aim at — the hand finds
the key.
|Garmin G3000 (aviation)
|Most input moved off the displays onto separate *touch controllers*
(GTC) on the pedestal, each driving a pane of the big displays; some
knobs and keys kept.
|Ships (ECDIS, IMO S-Mode MSC.1/Circ.1609)
|Trackball and a key panel with *dedicated keys* (dimming up/down among
them); S-Mode standardizes the terms, icons and hot keys of the common
functions so every bridge works the same.
|===
What it means for us:
* *Fewer buttons on the map*: four, not seven — zoom +, zoom −, the
view (2D/3D, heading-up/north-up), the route overview. Night is
automatic (and a topbar thing), "exit" is the topbar's Drive button
already.
* *Recenter only when needed*: "Follow" and "Back to the position" are the
same thing — one button, shown only while the map isn't following, in
one place.
* *76 px square* targets at least (ours are 76×64).
* *Softkeys for the CAN keypad* (Blink Marine style): its keys' labels
on the screen's edge next to them, changing with the screen — the G1000
way, no aiming while driving.
* *A second screen as the controller* (G3000's GTC): the tablet or phone
drives the cab's display (the shared trip already works that way for
the route).
* *Pick your buttons* (zūmo) — later, if four fixed ones don't fit.
Sources: Google's car design guidelines (sizing; map action strip);
Google Maps help and the Navigation SDK docs (recenter, compass,
overview); zūmo XT owner's manual and reviews (Motorcycle.com, Bennetts);
Garmin G1000 pilot's guide (softkeys, knobs); AIN and Aviation Consumer on
the G3000's GTCs; JRC JAN-701B and Kongsberg ECDIS manuals; IMO
MSC.1/Circ.1609.
=== Layout: a grid, not floating panels (2026-12-01)
Floating cards and buttons over the map (OsmAnd's way, ours so far) cover
the map and move around. Chart displays on boats and ships dock
everything to the edges instead:
[cols="1,3"]
|===
|Who |How
|Ship's ECDIS (photo from a bridge)
|A *strip of values across the top* (HDG, STW, COG, SOG), a *column on the
right* with the route (active waypoint, ETA, TTG, distance), a *row of
tabs at the bottom* (Charts, Overlays, Route Planning, Targets, Tasks).
The chart in the frame between them.
|Marine plotter (16″, photo)
|Data boxes in a column on the left (COG, DTG, TTG, fuel, time), keys in a
column on the right, depth and SOG in a strip at the bottom.
|Garmin (plotters, cars, bikes)
|*Data fields*: the screen's cells are the user's — which value goes in
which cell is picked per field.
|OpenCPN
|The *Dashboard* plugin ships with OpenCPN: the instruments shown are
picked per pane; a pane can be docked to the left or right edge, and
docked it is dimmed at night. Colour schemes day, dusk, night (S-52; F5
cycles them in the inland ECDIS manual).
|===
What it means for us: *a grid* (Vignelli's Unigrid, which the NPS look
comes from, is one too) of *16 × 10 cells of 80 px* on the navigator's
1280×800:
* top row: the manoeuvre (4 cells), then fields (2 cells each);
* the map 13 × 8 cells, nothing over it;
* right column 3 cells wide: the next stop, km and ETA, the rest to the
end, the elevation ahead (3 cells; the inclinometer moved to the
Terrain profile, below), a small compass (1 cell);
* bottom row: the menu's tabs (Trip, Points, Layers, Search, Menu), the
map keys (−, +, 3D, Follow), day/dusk/night — all 80 px, the
Android Auto 76 px at least;
* a menu opens into 7 × 8 cells in place of the right column, a row per
item (a stop: name over 3 cells, ✓ ↑ ↓ ✕ a cell each), the map
narrows to 9 × 8.
* Every field is "which cell, which value" — the Garmin/OpenCPN way, the
user's to arrange later.
Mockups: the Design canvas (claude.ai, private), artboards Grid,
GridTrip, GridSearch, GridPoints, GridLayers, GridTerrain. To be tried
against: OpenCPN itself.
Built (2026-12-03): `driving.js` lays the page out as the profile's cells
(`public/drive/road.json`), the menus in `drive_menus.js` — Trip and
Search, Points (the library nearest the car, along the route ahead, shown,
or by folder), Layers (the On the map panel's own switches, presets Road /
Off-road / Overnight, + Keep saves what's on into one) and Terrain. A menu
is a grid of cells too: a row per item, a cell per action.
Sources: OpenCPN manuals — Dashboard
(opencpn-manuals.github.io/main/dashboard), inland ECDIS getting started;
the photos of the bridge and the plotter.
=== Screen profiles (2026-12-02)
The grid's cells belong to a *profile*: planning (standing, a big map and
the trip), road (the Grid above), terrain, later others. A profile is
its cells — `{area, widget, options}`, the widget a value field (any
signal from the bus or GNSS, label, unit, decimals, amber/red limits), a
dial (inclinometer, compass), a chart (elevation), a list (stops), the
map, a menu panel or a row of keys — plus the condition that switches it
on. Every cell is configurable; the grid differs per screen (16″
1280×800 is 16 × 10), so profiles are per screen type. Edited in the app,
standing only: tap a cell → widget and signal, drag a corner → its size.
Today one profile, `public/drive/road.json` (`columns`, `rows`, the map's
area, the menu's area and the map's beside it, `cells`: `{area, widget,
value | action | km}`; widgets `maneuver`, `field`, `status`,
`elevation`, `compass`, `key`); once the editor exists it saves to
`data/` and the file is the default.
*Keys* (artboard GridKeys): a `key` cell's `key` is the keyboard key
that clicks it (the uConsole has no touch), `keypad` the CAN keypad's;
the menus' own buttons carry theirs (1 2 3, H). In an open menu ↑ ↓
move the row (the keypad's encoder sends the same arrows), Enter its
first button, Space its eye, + adds it, ⌫ up a folder, Esc closes.
Every bound button shows its key in the corner, from the first key
pressed on. Keypads are channels (`pad.K1`, `pad.E3`) and the
profile's `"bindings"` say what each does (below, a binding), so any
keypad fits; a keypad's heartbeat switches the labels to its channels by
itself, a line under each screen key in its LED colour (menus cyan, the
map white, the view amber, green while on).
Still to do: the switch (auto / keyboard / keypad) and the mapping in our
diagnostics.
*Terrain* (artboard GridTerrain): the inclinometer only off-road — on
the road its cells show the elevation ahead. A 7 × 8 panel like a menu,
the map 9 × 8: roll (a rear view) and pitch (a side view), each with
amber past 20° / 25° and red past 1.5× (as `dashboard.js`), the maximum
held until reset; heading, the climb and the side slope ahead (DEM), the
elevation of the next 2 km; the surface in the top row in place of the
limit; "Level here" (the node levels itself, SDO, `/can.html`'s action
already), "Reset max", "Road view". It switches itself on when the car
leaves paved road (OSM `surface`, `tracktype` ≥ 2, or off any road) or
roll/pitch stay past 10° for 10 s, back after 2 km of paved road or by
hand; the menu has "Terrain view: automatic / by hand" (automatic by
default).
=== Switches and the keypad: how others do it (research, 2026-12-02)
Relay modules and lights on the CANopen bus, keys and rotary encoders on
a CANopen keypad (RGB LED per key), all driven by maptool.
[cols="1,3"]
|===
|Who |How
|Garmin PowerSwitch (app, custom layouts)
|A button: label, icon, colour. Actions per switch: *Toggle*, *Turn On*,
*Turn Off*. Button modes: *Normal* (one touch), *Momentary* (on only
while touched), *Strobe* (on and off at a chosen interval). A brightness
slider for lights.
|Garmin OnDeck (ActiveCaptain / chartplotter)
|*Latching* (on until turned off) or *Momentary* for a selected
*duration*; a name, an icon, a switch can be hidden.
|MaxxECU PDM, CAN keypads (Blink Marine, Grayhill/MoTeC)
|Button steps: *Momentary* or *2 to 6 positions* (each press moves to the
next state). *Keep state* at power loss: keep the last state or reset to
off. LED: a colour per state, a *fault indication* (blinks red on any or
a given fault), *user colours* on a condition; only green, orange and red
on the Grayhill/MoTeC keypads. Encoders: steps 0–255, LED pattern single
LED / bar graph / one + first/last. Backlight always on or with the
ignition (with an off delay), dimmed with the lights.
|ECUMaster PMU (5x3MT, RacePad)
|RGB, 7 colours. Encoder modes: *encoder* (a channel's value, first /
last / default state, autosaved), *changer* (pages, wrap from last to
first), *parameter controller* with buttons as *parameter selectors*
(radio buttons choosing what the knob changes; pressing the selected one
again releases the knob). 16 LEDs around each encoder show its value
(start offset, inverted, bi-directional from the centre).
|PDM and marine practice (not in the pages above)
|Timers (auto-off), exclusive *interlock* groups (winch in ⟂ out),
conditions (ignition, engine running, speed), a defined state when
communication is lost, a confirmation for dangerous circuits.
|===
What it means for us:
* *One controller*: keypads, relay modules and lights are I/O; the
modes, timers, strobe, interlocks, conditions and LED colours run in
one place — unless a device has its own firmware for that function,
which is outside our scope. Today that's maptool; it moves to the
STM32C5 on the Pi's HAT (below, "The controller on the Pi's HAT").
* *A binding* = an input (keypad node, key or encoder) + a mode + a
target: an output (a relay or light channel, SDO/RPDO) or a screen
function (zoom, the next profile, the next stop). Bindings live in the
screen profile, so a key can do something else off-road.
* *Modes*: Toggle, On, Off, Hold (momentary), Pulse (on for a duration),
Positions 1..N, Strobe (interval), Dimmer (a level, an encoder turns
it); per binding an interlock group, "only when", a long press, a
confirmation, the state at power-on and when maptool or the keypad is
lost.
* *The LED colour on the screen*: a thin line in the key's LED colour
under the tile or screen key it drives — dim off, full on, blinking red
on a fault — so it's clear which key controls what.
* *Fail-safe*: a Hold output goes off when the keypad or the controller
goes silent; a relay node consumes the controller's heartbeat and has
its own safe state.
* *Encoders*: a value (dimmer, volume), a changer (profiles, wrap) or a
parameter controller. The interim (Blink Marine style) keypad has 8
keys and 8 encoders: two move the map, one zooms, the rest are bound
per profile. *Moving with a knob* instead of dragging: press to grab
the selected row (a stop, a point, a layer), turn to move it up or
down the list or into a folder, press again to drop it — no dragging
on a bumpy road. Ours have one LED each, no ring: the value could
show for a moment on the keypad's other LEDs while the knob turns (a
bar across the keys, then back to their own colours) — to be worked
out.
Mockups: the Design canvas, artboards GridSwitches (tiles: icon, name,
state, mode, the key, the LED line) and GridBinding (the keypad, a key's
target, mode, options, LED colours).
Sources: Garmin PowerSwitch manual, "Adding a Button to a Custom Layout"
(www8.garmin.com/manuals/webhelp, Tread Overland Edition); Garmin OnDeck
manual, "Configuring the Switches with a Mobile Device" and "…with a
Chartplotter"; MaxxECU help, CAN keypad settings
(maxxecu.com/webhelp/settings-can_keypad-keypad_settings.html);
ECUMaster, "How-to Set Up Keyboards with Encoders in PMU" (v1.0,
2026-01-09); ECUMaster USA, CAN keypads with the PMU16; HP Academy, PDM
control pad setup.
=== What the military vehicles do (MilCAN, NGVA; notes, 2026-12-05)
From a chat with Gemini, checked only partly — treat the details as
leads, not facts.
* *MilCAN* (the MilCAN working group, UK): *MilCAN A* on 29-bit
identifiers, J1939-like; *MilCAN B* on CANopen (11-bit). Used for the
vehicle electronics (vetronics: power, lights, panels, keypads), the
engine stays on its own J1939. *NGVA* (NATO Generic Vehicle
Architecture, STANAG 4754) puts Ethernet on top for data and video,
CAN/J1939 stays for the automotive side — close to our maptool + CANopen
split.
* *Connectors*: MIL-DTL-38999, 150–400 € a pair — not for us. Gemini's
"7-pin vetronics pinout" (V+, GND, CAN_H, CAN_L, wake, interlock,
shield) is not a standard we could find; the two extra signals are
still worth having: *a wake line* and *a hardware interlock*.
Dual CAN (A/B on both sides of the hull) is beyond what a car needs.
What we can borrow:
* *Silent Watch* — parked for days on battery: every node asleep at
microamps, woken by a key, the ignition / wake line or a CAN wake-up.
Node side: a transceiver with a wake input and INH (TCAN1043 wakes on
any bus activity, WUP; TJA1145 / TCAN1145 also by a selected frame —
partial networking); STM32 in Stop. For later: whether ESPHome and
our CANopen can sleep and wake that way is unknown, and the node PCBs
have to be designed around the chosen transceiver (its wake pin, INH
switching the regulator). maptool's side: a *Sleep* action
(all outputs to their safe state, nodes to NMT stopped / sleep, the
screen off) and what wakes what.
* *Blackout / camp mode* — only our own devices, one key: keypad LEDs to ~2 % in a dim red,
the screen to Night at its lowest, the auxiliary outside lights
(awning, work lights) off and *inhibited* (the door no longer turns the
awning light on) until it's left. A screen profile + a condition on
the outputs, not a new mechanism. The road lights are the car's own
and stay untouched (the military's blackout keeps dim blackout stop
lights too; on a public road it's not ours to switch).
* *Smart fuses (SSPC)*: nothing new — that's the PDM node (dingoPDM and
the like: high-side switches with current sense, trip on a short, reset
over CAN); its current and faults on the switch tiles and load shedding
by battery voltage are already in the virtual switch panel's TODO.
* *Hardware interlock*: a wire that drops the power outputs (winch,
inverter, heater) even with a hung MCU or a dead bus — a node's own
safe state, maptool only shows it.
*Powering the Pi and the ignition* — two ways:
. *The Pi on the bus*: a 6-pin Deutsch DT — 12 V, GND, CAN H, CAN L, IGN
and one spare (seen like that on another project); the Pi watches IGN
and shuts itself down cleanly a while after the ignition goes off.
. *The Pi on 12 V only* (the usual way, preferred): the car's CAN is
read by *our gateway node*, which tells "the car is running" from the
car's CAN data or from its own IGN input. The Pi then needs only power
(12 V, GND, possibly IGN — a separate connector, like
https://www.reddit.com/r/raspberry_pi/comments/1codbfw/raspberry_pi_for_automotive_applications_update/[r/raspberry_pi,
"Raspberry Pi for automotive applications"]) and can sit anywhere in
the car. A *HAT with an STM32C5* is its power supervisor: it turns the
Pi on when the car runs or when something on the network needs it
(a node, the tablet), asks it to shut down and cuts its power after,
and measures the power (voltage, current, the battery) — later more.
The HAT also carries the Pi's own CAN (a controller on SPI such as the
MCP2518FD + a transceiver, so maptool keeps its `can0`); the STM32C5
sits on the same bus as a node of its own and is the Pi's *watchdog*:
it consumes maptool's heartbeat and power-cycles a Pi that hung.
IGN (or the gateway's "running") is also the simplest wake signal for
the nodes.
The nodes' side (transceiver, wake pin, PROFET board) belongs in
home-gitops `docs/canopen-nodes.adoc`.
=== The controller on the Pi's HAT (decided 2026-12-05)
The outputs' logic leaves maptool for the *STM32C5 on the Pi's HAT*, the
way PDMs (ECUMaster PMU, MaxxECU) keep the keypad and output logic in
themselves rather than on the display.
* *One owner of every output.* The keypads, the `mcu-lvgl` panel and
maptool only send *requests* (toggle, on, off, a level); the controller
decides, drives the output nodes and sends the outputs' state in a TPDO
that everyone draws from. No two devices write to the same relay.
* *It works with the Pi off.* The HAT's STM32C5 runs whenever there are
12 V (it's the Pi's power supervisor and watchdog anyway), so the lights
and the pump work while the Pi boots (20–30 s), hangs or is off at camp.
* *The chip*: the same STM32C5A3CGT6 as the nodes (Cortex-M33, 144 MHz,
1 MB internal flash, two FDCANs, LQFP48) plus the board's 16 MB
external flash. An STM32H was considered and dropped: the controller is
a state machine for a few dozen outputs, an H7 draws far more while the
car stands (the HAT never sleeps fully, Silent Watch), needs a bigger
package and power design, and would be a second MCU family to keep. An
H5 only if the controller ever needs Ethernet.
* *Firmware*: plain Zephyr, not ESPHome (which can't use the external
flash yet). The external flash holds MCUboot's second slot (OTA over CAN
without squeezing the 1 MB), a *black box* — who switched what, faults,
heartbeats lost, the battery voltage — that maptool fetches when it
comes up, so the night at camp can be seen afterwards, the bindings and
scenes with their earlier versions (back to the last good one), and
per-circuit current and on-time statistics.
* *Conditions* come off the bus: speed from the GNSS node, the ignition
from the gateway, the sun computed on the chip; a geofence (the trip's
camp) is a point and a radius sent by maptool.
* *maptool stays* the UI (the switch tiles, `/keypad.html`,
`/sim.html`), the bindings' editor — `bindings.json` written to the
controller (SDO) and kept in its flash — and the screen's own keypad
actions (zoom, pan, menus), which it keeps reading off the bus. Today's
`outputs.rb` stays as the simulator and the reference the firmware is
checked against.
* *A single point of failure*, softened: every relay node has its own safe
state when the controller's heartbeat is lost, and a few key outputs
(the interior light) can have an input of their own on their node.
Order: maptool stays the controller until the firmware is done. First
the messages are fixed — requests, state, configuration as CANopen
objects — so that maptool uses them now and the STM32 later, with no
change to the other nodes.
== Typography
* Planning UI: the system sans; *National Park* (the router-carved
signage face) only for the wordmark and, later, headings in the black
band — the brochure's title.
* Instruments: the system sans with tabular figures
(`font-variant-numeric: tabular-nums`), bold values, small uppercase
labels with letter-spacing — numbers that don't jitter as they change.
== Which surface is which
[cols="1,1"]
|===
|NPS (planning) |Cockpit (driving)
|the map and its layers, the library, the trip / itinerary, search, the
route panel, NPS maps, the offline data panel
|the dashboard (inclinometer, speed, limit, ahead), the navigation strip
(next maneuver, lanes), the switch panel (PDM), warnings, `/can.html`
|===
The route line is the bridge: blue (`--route-planned`) while planning,
magenta (`--route-active`) once it's being navigated.
On a trip with its log recording, two lines, never mixed up: *planned*
(the route — blue while planning, magenta ahead while navigated, the
planned part behind thin and dashed so a detour shows) and *really driven*
(the recorded track, `--route-driven`, solid, on top). Shape tells them
apart as well as color (S-52's second cue): dashed planned, solid driven.
Sources: IHO S-52 Edition 6.1.1 (2015), sections 2.2.6, 4.2; the avionics
color meanings are the common glass-cockpit convention (FAA AC 25-11B has
the color coding guidance, §5.3 — not checked here, its PDF refused the
fetch).
+14 -73
View File
@@ -160,12 +160,20 @@ build.
A logged-in user can also generate both files above from the app A logged-in user can also generate both files above from the app
itself, no local tooling needed — the sidebar's "Offline data" icon itself, no local tooling needed — the sidebar's "Offline data" icon
(Offline hub group) shows a checklist of European countries (Offline hub group) shows a checklist of the whole world's countries,
(`lib/maptool/data/europe_countries.geojson`, Natural Earth 110m folded by continent with a search box, a country's subregions (US
admin-0, public domain) plus each file's status (size, last updated). states, German Länder, ...) folded under it — selectable one by one, so
Ticking countries and clicking "Apply changes" saves the selection e.g. Utah alone doesn't mean downloading the 10+ GB United States
(`data/offline_regions.json`, an array of ISO A2 codes) and rebuilds extract — plus each file's status (size, last updated). The list is
both files to cover it. `lib/maptool/data/geofabrik_regions.geojson`, generated from Geofabrik's
own index (`download.geofabrik.de/index-v1.json`) by
`node bin/geofabrik-regions-sync.mjs` — rerun it to pick up Geofabrik
changes. Ticking regions and clicking "Apply changes" saves the selection
(`data/offline_regions.json`, an array of region codes: a country's ISO
3166-1 alpha-2, a subregion's ISO 3166-2 or `<country>-<geofabrik id>`)
and rebuilds both files to cover it. Picking a country *and* one of its
subregions just downloads the overlap twice; osmium's merge de-duplicates
it.
There's no standalone per-country *built* file — `offline.pmtiles`/ There's no standalone per-country *built* file — `offline.pmtiles`/
`terrain.pmtiles` are always one combined extract for the *whole `terrain.pmtiles` are always one combined extract for the *whole
@@ -317,73 +325,6 @@ through this app's own proxy rather than at kiwix-serve directly — it
already has a full search UI of its own, this just makes it reachable already has a full search UI of its own, this just makes it reachable
through the same origin/reverse proxy as the rest of the app. through the same origin/reverse proxy as the rest of the app.
== GNSS position (gpsd)
The "GNSS" control needs https://gpsd.io[gpsd] running and pointed at
a receiver (`gpsd /dev/ttyUSB0`, or whatever device the receiver shows
up as). On openSUSE, `gpsd` is a package with systemd units
(`gpsd.service` / `gpsd.socket`); on other distributions, check your
package manager. No app-side configuration is needed — it just
connects to `127.0.0.1:2947`, gpsd's default port.
To test without hardware or gpsd itself installed/running, run
`bin/gnss_simulator.rb` — it speaks gpsd's own JSON wire protocol
directly on gpsd's default port (`127.0.0.1:2947`), so
`Maptool::GpsdClient` connects to it exactly as it would to real
gpsd, no app-side changes needed. Drives a loop around a center point
(Bratislava by default) at a driving-ish pace instead of sitting at a
fixed position, since a stationary "GNSS position" isn't much to look
at on the map:
[source,shell]
----
bin/gnss_simulator.rb # loop around Bratislava, 300m radius
bin/gnss_simulator.rb 48.85 2.35 500 # custom center/radius (Paris, 500m)
----
`GET /api/gnss/position` should report a fix within a couple of
seconds, moving on every poll.
To test against gpsd itself instead (e.g. to exercise the actual
NMEA-parsing path, not just gpsd's JSON output), feed it a fake NMEA
stream over TCP instead of a real serial device — gpsd accepts a
`tcp://host:port` source:
[source,shell]
----
# terminal 1: a TCP server repeating one NMEA GGA/RMC sentence pair
python3 - <<'PY' 5001
import socket, sys, time
def checksum(s):
cs = 0
for ch in s:
cs ^= ord(ch)
return f"{cs:02X}"
def sentence(body):
return f"${body}*{checksum(body)}\r\n"
port = int(sys.argv[1])
srv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
srv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
srv.bind(("127.0.0.1", port))
srv.listen(1)
conn, _ = srv.accept()
gga = "GPGGA,123519,4808.916,N,01706.462,E,1,08,0.9,140.4,M,46.9,M,,"
rmc = "GPRMC,123519,A,4808.916,N,01706.462,E,000.5,084.4,230824,003.1,W"
while True:
conn.sendall((sentence(gga) + sentence(rmc)).encode())
time.sleep(1)
PY
# terminal 2: point gpsd at it instead of a real device
gpsd -N -n tcp://127.0.0.1:5001
----
`GET /api/gnss/position` should then report the fake fix (Bratislava
Castle, in the sentences above) within a couple of seconds.
== Tests == Tests
`bundle exec rake test` runs the whole suite (`test/test_*.rb`, `bundle exec rake test` runs the whole suite (`test/test_*.rb`,
+404
View File
@@ -0,0 +1,404 @@
= Library: data model for tracks, points and sync (design)
:toc:
:toclevels: 2
Status: *phases 1–3 implemented* (`lib/maptool/library.rb`, see Decisions); phase 4 (the Android client) proposed. Replaces the file-based store behind
Tracks & Points (`GpxStore`) with an item-based library that OsmAnd, Locus
Map and the MapTool web app can all be synced against.
== Why
The same tracks and points live in three places — MapTool, OsmAnd+ and
Locus Map on the phone/tablet — each edited independently. Today the unit
of storage in MapTool is a *file* (a `.gpx`/`.fit`/`.geojson` in a folder),
and nothing inside a file has a stable identity, a change time, or a
record of having been deleted. That's fine for "upload and look at it",
but any sync needs to answer _which point changed, where, and since
when_ — impossible when the smallest thing we know about is a whole file.
Goals:
* One folder tree with points and tracks mixed in it (Locus-style
"project" folders).
* Every point and track an item with a stable id, timestamps and a
tombstone on delete.
* A change feed that a sync client (Android app, the PWA) can poll.
* Import/export to GPX that round-trips what OsmAnd and Locus care about
(folders, names, descriptions, colors, icons).
Non-goals (for now): real-time collaboration, merging concurrent edits
field by field, syncing hiking trails / offline map data (those are
derived, not user data), LiveTrack sessions.
== How the apps model their data
=== Locus Map 4
* One *library*: a tree of folders and subfolders in which tracks,
planned routes and points can be mixed. The separate points/tracks tabs
of Locus 3 are gone.
* Nesting: 3 levels free, 6 with Premium.
* Items can be filtered by type (only tracks / only points) for display.
* Exporting a folder exports all of its content into one file.
* Syncs every change to Locus' own web library (no public API known).
* App data (`waypoints.db`, `tracks.db`) is SQLite, but not a supported
integration point; the Locus API is mainly for *sending* points/tracks
into Locus.
Sources: https://docs.locusmap.app/doku.php/manual:user_guide:my_library[My Library],
https://www.locusmap.app/the-new-library-brings-major-improvements-to-your-data-management/[blog],
https://github.com/asamm/locus-api[locus-api].
=== OsmAnd+
* *Favorites* (points) in folders/groups, nested ("Travel / Italy /
Rome"); a name must be unique within its folder. Each has address,
description, icon, color and background shape, defaulting to the
folder's. Stored as GPX `<wpt>` with `osmand:icon`, `osmand:color`,
`osmand:background`, `osmand:address` extensions.
* *Tracks* are separate GPX files in track folders (plus "smart folders",
virtual filters). A track file can carry its own waypoints.
* Points and tracks are *not* mixed: a "project" maps to a favorites
folder plus a track folder of the same name.
* AIDL API: add/update/remove favorites and favorite groups, import/show
GPX. Whether it can *list* existing favorites/tracks is unverified —
check `osmand-api-demo` before relying on reading from OsmAnd.
Sources: https://docs.osmand.net/docs/user/personal/favorites[Favorites],
https://docs.osmand.net/docs/user/personal/tracks/[Tracks],
https://docs.osmand.net/docs/technical/osmand-api-sdk[API/SDK].
=== mapy.com
No API. Data arrives by exporting/sharing a GPX from the app — the PWA
share target (`public/sw.js`, `public/js/share_import.js`) covers that.
=== What that means for us
Locus' model is the most general: a folder tree with mixed items. OsmAnd
fits into it by splitting each folder into "its points" (a favorites
folder) and "its tracks" (a track folder). So MapTool adopts Locus' shape
and maps to OsmAnd on export/sync.
== Current model (GpxStore) and its gaps
* `data/gpx/` folder tree; each file is a `.gpx`, `.fit` or `.geojson`,
converted to a GeoJSON FeatureCollection (cached as `*.gpx.geojson`).
* A file mixes tracks/routes (`LineString`/`MultiLineString`) and
waypoints (`Point`), each with `properties`: `kind`, `name`,
`description`, `time`, `category`, `color`, `icon` (OsmAnd icon keys,
e.g. `amenity_parking`), `photos`, `activity_type`.
* Notes (`notes.js`) are Features appended to a `.geojson` "layer" file,
the only ones with an `id`.
* Plugin output and Overpass POIs land as `.geojson` files the same way.
Gaps: no per-item id (except notes), no `updated_at`, no tombstones, the
file is the unit of move/delete/visibility, folder styling doesn't exist,
a file's name is doubling as a "collection" name.
== Proposed model
Stored in SQLite, `data/library.sqlite` (the `sqlite3` gem is already a
dependency for the place index).
=== Folders
[source,sql]
----
CREATE TABLE folders (
id TEXT PRIMARY KEY, -- uuid
parent_id TEXT REFERENCES folders(id),
name TEXT NOT NULL,
color TEXT, -- default for items inside
icon TEXT, -- OsmAnd icon key
visible INTEGER NOT NULL DEFAULT 1,
created_at TEXT NOT NULL,
updated_at TEXT NOT NULL,
deleted_at TEXT,
UNIQUE (parent_id, name)
);
----
Depth capped at 6 so a tree always fits Locus Premium (warn above 3).
=== Items
[source,sql]
----
CREATE TABLE items (
id TEXT PRIMARY KEY, -- uuid
folder_id TEXT NOT NULL REFERENCES folders(id),
type TEXT NOT NULL, -- 'point' | 'track' | 'route'
name TEXT,
description TEXT,
geometry TEXT NOT NULL, -- GeoJSON geometry (Point / LineString / MultiLineString)
properties TEXT NOT NULL DEFAULT '{}', -- JSON: color, icon, width, category, time,
-- activity_type, photos, address, ...
bbox TEXT NOT NULL, -- [w,s,e,n], for search and the map
fingerprint TEXT NOT NULL, -- hash of type + rounded geometry, for dedupe
source_id TEXT REFERENCES sources(id), -- the uploaded file it came from, if any
created_at TEXT NOT NULL,
updated_at TEXT NOT NULL,
deleted_at TEXT,
rev INTEGER NOT NULL -- global change counter at last write
);
CREATE INDEX items_rev ON items(rev);
----
* `type`: `track` = recorded (has timestamps/elevation), `route` =
planned. Both lines; the split matters to Locus and for stats.
* A recorded track keeps per-point time/elevation inside `geometry`'s
coordinates (`[lng, lat, ele]`) plus a parallel `properties.times`
array — what the elevation profile needs today.
* `properties` stays an open JSON bag so a GPX extension we don't model
(Locus/OsmAnd specific) survives a round trip unchanged.
=== Sources (original files)
[source,sql]
----
CREATE TABLE sources (
id TEXT PRIMARY KEY,
filename TEXT NOT NULL,
path TEXT NOT NULL, -- data/library/sources/<id>/<filename>
imported_at TEXT NOT NULL
);
----
An upload is still kept as-is (for "download original"), but what the
app works with is the items extracted from it. Deleting items never
deletes the source; deleting a source is a separate admin action.
=== Links to other apps
[source,sql]
----
CREATE TABLE item_links (
item_id TEXT NOT NULL REFERENCES items(id),
app TEXT NOT NULL, -- 'osmand' | 'locus' | ...
device TEXT NOT NULL, -- one phone/tablet
external_ref TEXT NOT NULL, -- the app's id / favorite name+group / GPX path
synced_rev INTEGER NOT NULL, -- our rev when last pushed/pulled
PRIMARY KEY (item_id, app, device)
);
----
Neither app gives us our id back, so this table — kept by the sync
client, reported to the server — is how "this OsmAnd favorite" and "this
MapTool point" stay the same thing.
=== Change counter
A single `rev` sequence (a one-row table, incremented in the same
transaction as every write) stamped on each folder/item write. `rev` —
not wall-clock time — is what clients sync against, so clock skew on a
phone can't skip a change.
== API
[cols="1,2"]
|===
| Route | Purpose
| `GET /api/library/tree`
| Folders with item counts (replaces `/api/gpx/tree`).
| `GET /api/library/folders/:id/items.geojson`
| A folder's items as a FeatureCollection, `id`/`folder_id`/`updated_at`
in `properties` — what the map draws.
| `POST /api/library/import`
| Multipart upload (GPX/FIT/TCX/GeoJSON/ZIP) into a folder: stores the
source, extracts items, skips items whose `fingerprint` already exists
in that folder (re-sharing the same track from OsmAnd doesn't
duplicate it).
| `PUT /api/library/items/:id`, `DELETE ...`
| Edit (name, description, style, move to folder) / tombstone. `PUT`
carries the `rev` the client last saw; an older one gets `409` with
the current item.
| `GET /api/library/changes?since=<rev>`
| Folders and items (including tombstones) with `rev > since`, plus the
new high-water `rev`. The sync feed.
| `GET /api/library/folders/:id/export.gpx?flavor=locus\|osmand`
| GPX of a folder for an app (see mapping below).
|===
== Mapping to the apps
=== GPX in (import, share target)
* `<wpt>` → point; `<trk>` → track; `<rte>` → route.
* `<type>` → `properties.category`; `osmand:color`/`locus:` color and
`osmand:icon` → `color`/`icon` (already parsed by `Gpx.waypoint_style`).
* Folder: the one picked in the import dialog; a GPX's own waypoint
groups (OsmAnd's per-folder favorites export) become subfolders.
* FIT → one track; TCX → one track per `<Activity>` (`Tcx`).
GeoJSON → items by geometry type.
* Heart rate, cadence, speed and power (FIT field 7, GPX `power` /
`PowerInWatts`, TCX `Watts`) go into the profile; the profile panel
computes splits and best efforts (fastest distances, best power over
5 s–60 min, biggest climb) from it in the browser.
* Laps: `laps` holds each lap's first profile index (FIT lap
`start_time`, TCX `<Lap>`), only with two or more. The panel switches
splits between 1/5/10 km (default by activity: run/hike 1, bike 5,
car 10) and laps; the segments are shaded in the charts, listed in the
table and marked as numbered posts on the map.
=== Points in a track or route
A track/route is a container for points (`parent_id`), like a GPX's own
waypoints: shown, moved, deleted and exported with it. `POST
/api/library/node/:key/points` adds one (the popup's "Add to …" copies a
point into any shown track/route); the tree lists them under the
track, collapsed. In a FIT course they become course points, placed at
the nearest point of the line, the type (water, food, summit, danger,
first aid, valley) guessed from the name/category/icon.
Points get in three ways: "Add to …" in a point's popup (a copy), a new
note saved "Into a track / route", and the route planner's 📍 points
(on by default for named places): saving the route syncs those as
points marked `from_route`, leaving hand-added ones alone.
=== FIT course out
`GET /api/library/node/:key?download=fit` writes the node's first line
as a FIT course (`FitCourse`) for Garmin/Wahoo devices: one record per
point with distance and a timestamp spread over the line's duration (a
4 m/s guess without one); the sport comes from the route's bicycle/foot
profile or the track's activity type.
=== Locus
Folder ⇄ folder, 1:1. Export a folder as one GPX with tracks and points
together (Locus imports it into a folder). Locus-specific extensions
(`locus:icon`, track style) are kept in `properties` and written back.
=== OsmAnd
* A folder's *points* → favorites group with the folder path as its
name ("Van / Croatia 2026"), written as GPX `<wpt>` with `osmand:`
extensions. OsmAnd requires unique names per group → duplicates get
" (2)" appended on export only.
* A folder's *tracks/routes* → one GPX per item in a track folder with
the same path (`tracks/Van/Croatia 2026/<name>.gpx`), track color/width
in the GPX `<extensions>` (exact `osmand:` tag names to verify against
a file exported from OsmAnd).
== Sync (later phase)
* Direction 1 — MapTool → apps: the Android sync client polls
`/changes`, pushes new/changed items into OsmAnd (AIDL: favorites,
GPX import) and Locus (locus-api: points/tracks into a folder), and
records `item_links`. Deletes: remove via the API where it allows it.
* Direction 2 — apps → MapTool: for now, *sharing* from the app (PWA
share target) — fingerprint dedupe makes re-sharing safe. Automatic
reading from the apps only if their APIs turn out to allow listing
data (open question above).
* Conflicts: last writer by `rev` wins per item; the losing version goes
to an `item_history` table so nothing is silently lost.
== Migration from GpxStore
One-off rake task, idempotent, `data/gpx/` left untouched until verified:
. Each directory under `data/gpx/` → a folder (same path).
. Each file → a subfolder named after the file (without extension), its
features → items in it; the file → a `sources` row. (Alternative: put
items straight into the directory's folder — see open questions.)
. Notes' existing `properties.id` reused as the item id, so links to
them survive.
. Category/icon/color carried over in `properties`.
Then the app switches to the library; `GpxStore` and `/api/gpx/*` are
removed once nothing uses them.
== What changes in the code
* `lib/maptool/library.rb` (new): schema, import (reusing `Gpx`, `Fit`,
`Geojson` parsing), queries, change feed, GPX export.
* `app.rb`: `/api/library/*` instead of `/api/gpx/*`.
* `public/js/gpx.js`: tree of folders → items (visibility per folder
and per item, item rename/move/delete), map sources per folder.
* `public/js/notes.js`: create/edit items instead of appending to a
layer file.
* `lib/maptool/search.rb`: the "layers" source queries `items` (an FTS
table over name/description) instead of scanning files in memory.
* Plugins: output imported via the same import path.
* `share_import.js`: posts to `/api/library/import`.
== Phases
. Library schema + import + read-only map view, migration task, behind
the same UI (tree shows folders/items). Old store still present.
. Editing (rename, move, delete, style) + notes on the library; remove
`GpxStore`.
. Change feed + GPX export flavors for OsmAnd/Locus.
. Android sync client (one direction), then the other direction if the
app APIs allow it.
== Decisions (phase 1)
* Migration: each old file → a subfolder named after it, holding the
file as one `layer` item still drawn from its GeoJSON — not split into
points. Splitting a layer into items can come later if needed; new
imports are split right away.
* Track waypoints: independent points with an optional `parent_id` (the
GPX's single track). The tree draws them with their track; Locus can
get them loose in the folder, OsmAnd inside the track's GPX. Both apps
import a GPX with tracks and points together; neither exports GeoJSON
(Locus imports it, OsmAnd doesn't), so exports are GPX.
* Simplified against the schema above: no `sources` table (an item's
`source_path` points at the stored upload), no `description`/`bbox`
columns (in `properties` / computed when needed), folder styling and
`item_links` not yet.
* Migration runs on first start (no `library.sqlite` yet); `rake
library:migrate` re-runs it (idempotent).
== Decisions (phase 2)
* Rename and color apply to tracks, routes and layers (the node in the
tree). Color is stored as `properties.color` and drawn as the line
color. A layer's color is laid over its legacy GeoJSON when it's served.
Single points keep their category color from the GPX.
* Folders: rename, and move by dragging one onto another folder (or onto
the tree's blank space for the top level). Moving into a folder's own
subfolder, or next to a sibling of the same name, is refused.
* "Split into items" turns a migrated layer into ordinary items in its
folder. Its notes keep their ids, the legacy file is copied to
`sources/` as their "original", and the layer is tombstoned.
`data/gpx/` isn't touched. A note edited in an unsplit layer still
goes to its legacy file.
* `GpxStore` stays, since unsplit layers are still drawn from it. It goes
away once nothing is a layer any more.
== Decisions (phase 3)
* `GET /api/library/changes?since=<rev>`: folders and items with
`rev > since`, tombstones as `"deleted": true`, plus the current `rev`,
read in one transaction. A layer comes without geometry; it's a legacy
file until split. Login-only for now. The Android client will need a
token instead of the browser session (phase 4).
* `GET /api/library/export?folder=<path>&flavor=locus|osmand`, from the
folder's own menu (and the panel header for the top level). It covers
the folder's own items, not its subfolders.
** Locus: one GPX with points, tracks and routes together.
** OsmAnd: a zip. `favourites.gpx` holds the loose points, with the
folder path as their `<type>` group ("Van / CZ") and duplicate names
made unique ("Gate (2)"). `tracks/<folder path>/<name>.gpx` holds
one file per track, route or layer, with that item's own points in
it.
* GPX writing (`Gpx.from_features`): colors as `<osmand:color>`, which is
what import reads back, and on lines also gpx_style `<line><color>`,
which Locus reads. Not verified yet against files the apps export
themselves; adjust the tags once a real OsmAnd/Locus export is at
hand.
== Open questions
* Folder depth over 3 — fine to require Locus Premium?
* Does OsmAnd's AIDL API list existing favorites/tracks? Does locus-api
read points/tracks by folder? Decides whether direction 2 can be
automatic.
+231 -25
View File
@@ -15,8 +15,10 @@ checking here before searching from zero next time.
|=== |===
| What | Where | License | What | Where | License
| `symbol-library` (map category icons, POI badge glyphs) | `symbol-library` (map category icons, POI badge glyphs): all 307
| `public/js/icons.js`'s `POI_ICONS`/`PARK4NIGHT_TAGS` symbols, browsable with search at `/symbols.html`
| `public/vendor/nps-symbols/` (from `bin/nps-symbols-sync.mjs`), used by
`public/js/icons.js`'s `POI_ICONS`/`PARK4NIGHT_TAGS`
| CC0 (public domain) | CC0 (public domain)
| `home-button` (the "Home" map control) | `home-button` (the "Home" map control)
@@ -25,7 +27,7 @@ checking here before searching from zero next time.
public domain as a US government work public domain as a US government work
| Park Tiles color palette (shared offline + online basemap theme) | Park Tiles color palette (shared offline + online basemap theme)
| `public/js/map.js`'s `ONLINE_STYLE_PATCH` | `public/js/map_themes.js`'s `PARK_TILES_PATCH`
| Colors only — see <<park-tiles>> for why the actual tile service isn't used | Colors only — see <<park-tiles>> for why the actual tile service isn't used
| `overview` (top-right minimap/inset control) | `overview` (top-right minimap/inset control)
@@ -126,23 +128,21 @@ NPS-flavored.
no current use case. no current use case.
|=== |===
=== Pending upstream: symbol artwork revisions === Symbol artwork: the 2024 revision branch
https://github.com/nationalparkservice/symbol-library/pull/226 ("npmap-hfc https://github.com/nationalparkservice/symbol-library/pull/226 ("npmap-hfc
standardization 2024") — a large (169-file), still-*open*/unmerged artwork standardization 2024", branch `jakecoolidge-revision-2024`) is the newest
revision pass on the *old* standalone repo, open since January 2024. Of the artwork (May 2024), newer than npmap5-plugins' copy (December 2023) and a
icons this app actually uses, three have revised artwork proposed there: superset of it: 307 standalone symbols vs. 305, adding `wifi`, `toilet`,
`e-bike`, `diesel`, `stargazing`, `snowshoeing`, `food-storage`, … and
renaming a few (`motor-bike-trail` → `motorbike-trail`). The PR is still
open, but it is where the artwork lives now, so `bin/nps-symbols-sync.mjs`
vendors every `src/standalone/*-black-22.svg` from a pinned commit of that
branch. To update: change `REF` there and run it.
* `bicycle-trail` (our `sport_cycling`/`vtt`) Locus Map's "NPS Map Symbols" packs (https://dfgtec.com/map-nps-symbols)
* `campground` (our `tourism_camp_site`) are ~250 of the same NPS symbols as PNGs under CC BY-NC-SA; the CC0 SVG
* `pets-on-leash` (our `animaux`) source above is both larger and freer.
Plus filename-only renames (e.g. `motor-bike-trail` → `motorbike-trail`,
`sea-plane` → `seaplane`) and a handful of new icons not relevant to our
current `PARK4NIGHT_TAGS` mapping (`e-bike`, `foraging-gathering`,
`seaplane`, `toilet`, `windmill`). Deliberately *not* pulled in — it's an
unmerged draft, could still change. Worth revisiting once it lands on
`main` in whichever repo ends up canonical.
[[park-tiles]] [[park-tiles]]
== Park Tiles (the NPS basemap theme) == Park Tiles (the NPS basemap theme)
@@ -187,8 +187,15 @@ why this app uses OpenFreeMap Liberty as its actual basemap, not Park
Tiles — see `docs/architecture.adoc`'s "Offline maps" section. Tiles — see `docs/architecture.adoc`'s "Offline maps" section.
Recreating the *color choices* is a different matter — not the kind of Recreating the *color choices* is a different matter — not the kind of
thing a data license restricts — and is what `ONLINE_STYLE_PATCH` in thing a data license restricts — and is what `PARK_TILES_PATCH` in
`public/js/map.js` actually does (see `docs/architecture.adoc`). `public/js/map_themes.js` actually does (see `docs/architecture.adoc`).
Its colors come from the Standard style's legend swatches
(`nps.gov/maps/web/img/legend/*-standard.png`, small rendered map
crops — sampled pixel by pixel): land `#F7EEE8`, NPS unit area a flat
sage `#CED2B7`, boundary `#779238`/`#8BA35A` with a `#B2C294` tint band,
water `#B5D0DE`, primary road `#F8ECBE` cased `#8F867A`, secondary
`#F9F9F6`, local `#F5F3E5`, trails dashed `#8E827B`, buildings
`#E7E4D5`/`#C1A88B`.
=== Public style JSON (source for the real colors we did pull) === Public style JSON (source for the real colors we did pull)
@@ -218,12 +225,11 @@ embedded credentials, even when technically reachable:
| `ck5cpia2u0auf01p9vbugvcpv` | `ck5cpia2u0auf01p9vbugvcpv`
|=== |===
Colors actually pulled from the Imagery style JSON and used in The Imagery style sits over satellite imagery, so it has no landcover
`ONLINE_STYLE_PATCH`: background (`hsl(40, 37%, 97%)`, a warm cream), the fills and white labels — useful for road/trail/boundary colors and label
park/protected-area green (`#b3e378`), the two road-importance tiers hierarchy, not for the land itself; those came from the legend swatches
(`#fdefbe`/`#fef7dd`), and the park-boundary line color (`#546619`, dark above. (Its `#b3e378` is the park *point* color, which an earlier palette
olive). The rest of `ONLINE_STYLE_PATCH` extends that same warm/olive mistakenly used as the park area fill.)
family by eye rather than from a sourced value.
=== Legend / cartographic hierarchy === Legend / cartographic hierarchy
@@ -401,3 +407,203 @@ turned up while looking at this:
called live. called live.
* https://github.com/seankelliher/us-national-parks-alerts — a * https://github.com/seankelliher/us-national-parks-alerts — a
Vue + Express directory of park alerts, pulled live through this API. Vue + Express directory of park alerts, pulled live through this API.
== The NPS mobile app's offline downloads
Investigated November 2026 from the Android app (`gov.nps.mobileapp`
2.16.0, native Kotlin + Mapbox Maps SDK): the APK pulled over `adb`,
strings read out of its `classes*.dex`, plus a Death Valley (`deva`)
offline download on a tablet. Nothing was decompiled or executed.
*There is no single offline bundle.* "Download Offline Content" queues
~20 separate per-park fetches and ticks each off in a Room table
(`ParkOfflineStorage`: `parkImagesStored`, `mapStored`, `placesStored`,
`campGroundsStored`, `autoToursAudioStored`, `roadClosuresStored`, …).
Photos and audio land in
`/sdcard/Android/data/gov.nps.mobileapp/files/.NPS/{images,audio}/<park>/`.
The map and API data go to app-private storage (not readable without
root). Where it comes from:
[cols="2,3,2"]
|===
| What | Source | Usable?
| Park content: places, campgrounds, visitor centers, things to do,
tours, amenities, road events, passport stamps, webcams
| `developer.nps.gov/api/v1/` — the public NPS Data API (see "NPS Data API" above)
| Yes. The app embeds its own key; use ours / the MCP instead
| App config, tours, timelines, transit, brochure-map index
| `www.nps.gov/external-resources/mobile/*.json` (e.g.
`tours/{parkCode}.json`, `transit.json`, `brochure-maps.json`),
`www.nps.gov/external-resources/timelines/{parkCode}.json`
| Yes, plain public JSON
| Audio-described tours
| `www.nps.gov/external-resources/audio-described-tours/{parkCode}_IEM.zip`
| Public
| Trails
| `www.nps.gov/external-resources/mobile/trails/{parkCode}/data.json`
| 404 for deva/yell/grca/yose/zion — only a few parks so far
| Basemap
| Mapbox offline region of the Park Tiles styles
(`mapbox://styles/atlas-user/ck58pyquo009v01p99xebegr9` Standard,
`…/ck5cpvc2e0avf01p9zaw4co8o` Slate) with the app's token
| No — same Mapbox Atlas licensing as <<park-tiles>>
| Yellowstone live roads
| `carto.nps.gov/user/nps-yell/api/v2/sql?format=geojson&q=…`
(`roads`, `road_construction`, `road_snowplows`, `road_incidents`,
`road_statuses`)
| Public GeoJSON, but Yellowstone only
| Site geometries
| `central.nps.gov/data/api/v1/sites/…`
| No — 401, internal
| `nps-one-mobile.s3.amazonaws.com`
| Only `safety-notifications.json` and `ar-wip.json`
| Nothing of interest
|===
=== Worth taking
* *Georeferenced brochure maps* (`brochure-maps.json`, also bundled in
the APK's `assets/`): 289 Harpers Ferry Center park maps for 219 parks,
each with pixel `size`, a GDAL-style `geoTransform` and `proj4` (Web
Mercator) — i.e. ready to drop onto the map as a raster `image`
source. Public domain as NPS works. `npgallery/GetAsset/{assetID}` is
the original print PDF (deva: 205 MB); the app downloads a smaller
raster (`fileSize`, deva: 20 MB) from somewhere under
`external-resources/mobile-brochure-maps/` whose exact filename
pattern isn't visible in the strings — needs a decompiler (jadx) to
pin down.
* *Park boundaries*: `assets/optimized-park-boundaries.sqlite` in the
APK, 3758 rows (`park_code`, bbox, center/radius, `polygon_data`
blob) with an R-tree index.
* *POIs from the Data API*: campgrounds come with coordinates, site
counts, water/toilets/dump station/RV flags, fee, reservation link and
current status text — maps straight onto our POI + park4night-style
tags. deva returns 12.
=== Getting the data without our own key
The home MCP server (`cyanheads/national-parks-mcp-server`, deployed
from `home-gitops`, key held there as a Gitea secret) is enough for
pulling data. It only wraps parks, campgrounds, alerts, events and
activities, though — not `places`, `visitorcenters` or `thingstodo`,
which the app also uses. Covering those would need a key of our own
(free, https://www.nps.gov/subjects/developer/get-started.htm) or
extending the MCP.
== HFC map standards: Unigrid starter maps and symbol sheet
Entry point: https://www.nps.gov/subjects/gisandmapping/starter-maps.htm
(HFC's "Starter Maps" page — the starter maps below and the symbol sheet are
linked from there; the wider map catalog is
https://www.nps.gov/subjects/gisandmapping/nps-maps.htm).
The full NPS map catalog (NPGallery collection "HFC Cartography", ~960 maps,
mirrored in `~/Projects/NPS_Maps/npgallery-maps.json`) also holds Harpers
Ferry Center's own production templates — public domain like the maps, each a
ZIP of Adobe Illustrator files (`.ai` is PDF-compatible: `pdftoppm` renders
it, `pdftotext` reads it, and the swatch palette sits as plain XMP
`<xmpG:swatchName>` entries inside). Downloaded and rendered to PNG under
`~/Projects/NPS_Maps/starter-maps/`:
[cols="2,3"]
|===
| Asset | What's in it
| Unigrid Waysides starter map
(`aeb8eaba-a260-4928-8b27-62ebe1ef1fee`)
| *"Standard Map Elements for Maps on Wayside Exhibits and Signs" (2006)* —
the spec sheet: linework (width, dash pattern, CMYK for every line type),
environment color families, NPS pictograms, scale bars, north arrows, road
shields, tour stops, "You Are Here" flags, locator symbols. Plus a starter
map with the named swatches
| Unigrid Area / A-width / B-width brochure starter maps
(`163a73b8-…`, `7eee590a-…`, `4bb3b9f0-…`)
| Brochure-format starter maps carrying the same 16 named swatches (the
Area one renders blank — content on hidden layers)
| Map Symbols — Harpers Ferry Center (`cd253093-6813-471e-9d16-042c2a373a97`)
| "NPS Map Symbols: Updated June 2026" — one sheet, ~270 symbols in 16
groups, positive and negative versions. By name it's the same set as the
307 we vendor (symbol-library 2024 revision) — only "Hiking" has no
same-named counterpart in ours. Side-by-side artwork comparison:
`~/Projects/NPS_Maps/symbols-compare.py` crops each symbol off the sheet
(located by its label's `pdftotext -bbox-layout` box) next to our
vendored SVG → `symbols-compare/index.html`
|===
=== Linework (from the 2006 spec)
Widths are print points on a 22×34 in sheet — relationships matter more than
absolute values. CMYK as `C/M/Y/K`; hex is a naive conversion (on screen the
printed colors read more muted).
[cols="2,3"]
|===
| Line | Spec
| Limited-access highway | 6 pt 60% black, 9 pt case 90% black
| Primary road | 7 pt 60% black
| Secondary road | 5 pt 60% black
| Unpaved road | 2.5 pt `0/0/20/60` (`#666652`)
| 4-wheel-drive road | 2.5 pt `0/0/20/60`, 20 pt dash / 2 pt gap
| Street grid | 2 pt white
| Parking area | 60% black
| Locked gate / overpass ticks | 2 pt 100% black
| Drainage | 3 pt `25/5/0/35` (`#7c9da6`)
| Intermittent drainage | 3 pt round caps `25/5/0/35`, 18 dash / 8 gap / 1 dash / 8 gap / 1 dash / 8 gap
| Waterfall | three parallel 3 pt ticks `25/5/0/35`
| Dam / ford / lock | 2 pt tick / two ticks / chevron pointing upstream, black
| Ferry route | 2 pt `33/15/0/50` (`#556c80`), 30 dash / 5 gap
| Trail | 3 pt in the trail color, 9 dash / 4 gap
| Tour route | colored line replacing the road, `80/0/80/40` (`#1f991f`), optional arrow
| Steep trail | 2 pt chevron pointing uphill, black
| National scenic trail | 3 pt `80/0/80/40`, 9 dash / 4 gap
| Railroad | 2 pt solid 60% black + 15 pt ticks (2 dash / 28 gap)
| Distance indicator | 12 pt Frutiger 55 Roman
|===
Trail colors: yellow 100%, black 100%, green `80/0/80/40`, red `0/100/100/50`,
white.
=== Color families (from the 2006 spec)
"Climatic or topographic swatch families" for subject-area fills or
background — pick one family per map, any shade; all linework is designed to
work with every family:
[cols="1,3"]
|===
| Family | Shades (light → dark)
| Green Forested | `30/15/30/00` `#b2d9b2`, `40/25/40/00` `#99bf99`, `50/35/50/00` `#80a680`
| Urban or Alpine | `00/02/04/19` `#cfcac6`, `00/03/06/25` `#bfbab4`, `00/04/09/38` `#9e9890`
| Desert or Beach | `00/02/12/15` `#d9d4bf`, `00/04/18/22` `#c7bfa3`, `00/06/28/34` `#a89e79`
| Glacial / Arctic | `03/02/00/02` `#f2f5fa`, `08/03/00/04` `#e1edf5`, `12/05/00/07` `#d1e1ed`
| Volcanic | `08/20/21/09` `#d5bab7`, `11/30/30/13` `#c59b9b`, `16/44/44/20` `#ab7272`
| Drainage & open water | `25/05/00/00`, `25/05/00/20`, `25/05/00/35`
| Other-subject area (outside the park) | `00/00/05/05`, `00/07/11/00`, `06/10/10/00`, `08/05/10/00`, `05/07/18/00`, `07/07/05/00`
|===
The starter maps' named swatches (newer than the 2006 sheet, same in all
four): Non-subject area `3/6/10/0` (`#f7f0e6`), NPS area `4/2/5/0`
(`#f5faf2`), Open water `40/16/0/15` (`#82b6d9`), Drainage & spring
`50/20/0.5/20`, Pk bdy `40/20/30/5` (`#91c2aa`), Pk bdy ribbon & name
`24/12/20/4` (`#bad7c4`), Park name `35/15/25/10`, Roads `0/50/40/30`
(`#b2596b`), Trail lines & distance labels `70/0/60/60` (`#1f6629`),
Unmaintained trail `20/50/100/15` (`#ad6c00`), Hydro type `70/30/0.5/30`,
Call-out box `60/0/50/50`, Red notes `0/70/56/50`, NPS Green `80/0/80/40`.
These are print (brochure/wayside) standards, a different system from the
web Park Tiles palette in <<park-tiles>> — but the same lineage, and a sourced
basis for things like the TODO's "custom vector style using the NPS color
palette" (environment families → landcover by region, linework → road/trail
hierarchy, Unmaintained trail → tracks).
+201
View File
@@ -0,0 +1,201 @@
= Offline routing — design
:toc:
:toclevels: 1
Status: *implemented* (the container and builds; the route panel, vehicle profile and saving a route; elevation profile and reach).
== Goal
Car/camper routing that works with no internet, from the same OSM
extracts the offline map is built from, with the vehicle's dimensions
(height, width, length, weight) respected, so the route doesn't go
under a 3 m bridge or over a 3.5 t bridge. Later on the same engine:
an elevation profile of the route and isochrones ("how far in 2 hours").
== How OsmAnd and Locus do it
Neither routes on raw OSM. Someone else builds a compact graph once and
the phone just downloads it:
* *OsmAnd*: every `.obf` map file has a routing section (roads with only
the tags routing needs) built on OsmAnd's servers. Since 4.6 it also
carries precomputed "HH" (highway hierarchy) shortcuts for long
routes. Vehicle height/weight/width are profile parameters checked
against `maxheight`/`maxweight` at query time.
* *Locus*: offline routing goes through BRouter: `.rd5` segment files
(5°×5° tiles, built weekly by brouter.de) and profiles scripted at
query time. Its lookup tables have no `maxheight`/`maxweight`, so it
can't respect vehicle dimensions. It's built for cycling first.
Valhalla is the same idea: the build (hours, once per map refresh)
produces compact tiles with only roads and their restrictions (a
fraction of the OSM extract), and queries are A* over those tiles in
milliseconds. The difference is only that we build the tiles ourselves
from the extracts we already have, instead of downloading someone
else's.
== Engine: Valhalla
[cols="1,3"]
|===
| Valhalla
| `truck` costing takes height/width/length/weight/axle load per
*request*, so one graph serves any vehicle. Has `/isochrone`,
`/height` and `/optimized_route` built in. Tiles are a memory-mapped
tar, so RAM stays modest even for many countries. Chosen.
| GraphHopper
| Java is already in the image (Planetiler), and custom models can do
dimensions too, but the import for ~16 GB of PBF wants a heap close
to the server's 30 GB RAM.
| OSRM
| Fastest queries, but restrictions are baked in at build time: one
graph per vehicle profile, no dimension parameters per request.
|===
== Data
The PBF files are already there: `data/geofabrik_cache/<CC>.osm.pbf`,
one per country selected for the offline map (`data/offline_regions.json`,
currently 14 countries, ~16 GB). Routing uses exactly that set, so
there's no second region picker. The files are hard-linked into
`data/routing/pbf/` (same file system, no copies, and Geofabrik refreshes
don't change a build that's in progress).
Measured on the server: 16 cores, 30 GB RAM, 780 GB free. Rough
expectation for this set: tiles 15–25 GB, a build of a few hours. The
build runs at a low priority and the old tiles keep serving while it
runs.
== Containers
Valhalla isn't packaged for Debian trixie, so it isn't in the maptool
image but in its own compose service, `valhalla`, from Valhalla's image
`ghcr.io/valhalla/valhalla` (Renovate bumps the tag). It runs
`bin/routing-service.sh`, which maptool copies to
`data/routing/service.sh` at boot, so the script always matches the
deployed app. It mounts the whole `data/`, since a hard link from
`data/geofabrik_cache/` can't cross two bind mounts.
The two sides talk through files in `data/routing/`:
[cols="1,1,2"]
|===
| File | Written by | Meaning
| `build-request.json`
| maptool
| `{"regions": [...], "pbf": "routing/merged.osm.pbf"}`: build these countries. `pbf` is set for more than one country.
| `merged.osm.pbf`
| maptool
| The countries' extracts merged by osmium. Valhalla fails on several overlapping extracts ("Failed tile ... _M_range_check", valhalla#3925), and its image has no osmium. Removed after a successful build.
| `status.json`
| container
| `state` (running/done/error), `step`, `started_at`, `message`.
| `tiles.tar`, `admins.sqlite`, `valhalla.json`
| container
| The served graph.
| `built.json`
| container
| The request the current tiles were built from.
| `build.log`
| container
| The last build's output.
|===
The script serves `tiles.tar` with `valhalla_service`, polls for a
request every 10 s, and builds into `staging/` while the old tiles keep
serving. It runs `valhalla_build_admins`, then `valhalla_build_tiles`,
then `valhalla_build_extract`, at `nice 10` with half the cores. When
the build succeeds, it swaps the tiles in and restarts the service. A
failure keeps the old tiles and puts the end of the log in
`status.json`. Every redeploy restarts the whole compose project; a
build cut off that way starts over on its own (its request is still in
`staging/`).
No timezone database (`valhalla_build_timezones` downloads one): only
time-dependent routing needs it.
Tested locally with Liechtenstein: the build takes 2 s, a rebuild while
serving swaps the tiles in, and a truck route with dimensions comes back.
== maptool side
* "Offline routing" row in the Offline data panel, next to the offline
map and terrain (`/api/routing-tiles`, same shape). Apply builds all
three. A routing request made while the offline map is still
downloading extracts waits for the downloads only, then runs alongside Planetiler (`Routing.extracts_ready`).
The row says whether the service answers.
* `POST /api/route` (`{"locations": [[lon, lat], ...]}`) proxies to
Valhalla `/route` and returns the route as a GeoJSON line with
distance, time and turn instructions. It's open to everyone, like the
map; only saving needs a login. The costing depends on the weight:
up to 3.5 t it's `auto` with the vehicle's height and width, because a
camper shouldn't be kept off roads closed to lorries (`hgv=no`). Above
3.5 t it's `truck` with every dimension.
* Vehicle profiles in `data/vehicles.json` (`GET`/`PUT /api/vehicles`,
saving needs a login): a name plus optional height, width, length,
weight (missing: no limit). Defaults: Car (no limits) and Camper
(3.0 m, 2.3 m, 7 m, 3.5 t; an older single `vehicle.json` becomes the
camper). The route panel picks one per browser (localStorage) and sends
its id with `/api/route` and `/api/isochrone`; Edit shows the fields.
* A profile's `type` is `car` (also when missing), `bicycle` or `foot`.
Bicycle uses Valhalla's `bicycle` costing (`bicycle_type`
Road/Hybrid/Cross/Mountain, `speed` as `cycling_speed`, `hills` as
`use_hills`); foot uses `pedestrian` (`speed` as `walking_speed`, `sac`
as `max_hiking_difficulty`, the hardest SAC grade, `hills`). The same
tiles serve both, no rebuild. Defaults: Bicycle, Mountain bike, Run
(10 km/h, T2), Hike (4.5 km/h, T3); a list saved before types existed
gets them once. Avoid and the per-country summary are car-only.
* Avoid tolls / motorways (`"avoid": {"tolls": true, "highways": true}`)
sets Valhalla's `use_tolls` / `use_highways` to 0 for the whole route.
Per country isn't possible in one Valhalla request.
* Vignettes and tolls: `/api/route` adds `countries`, the km, motorway km
and toll km per country, from `/trace_attributes` (edge_walk on each
leg's shape). The panel lists vignette countries (fixed list in
route.js) with motorway km, other countries with toll km. In vignette
countries every motorway km counts, since OSM doesn't tag those as toll
reliably.
* Route panel (`public/js/route.js`): while it's open, a map click adds a
point; markers drag; Reverse, Clear. The route is drawn with distance,
time and directions. "Save to library" stores it as a `route` item in
the "Routes" folder through the notes endpoint, with its points (`via`)
and vehicle in `properties`. That way it goes to OsmAnd/Locus through
the same export as everything else.
* Points also come from "+" on a search result, "Add to route" in a
library point's popup, or "+ My position" (the GNSS fix, else the
browser's position). These go through events in `panels.js`, the same
way the library refresh does. ↑/↓ reorder points.
* "Edit route" in a saved route's menu in the tree loads its points
back. Save then updates that item instead of adding a copy. A route
imported from GPX has no `via`, so it can't be edited this way.
== Phases
. Container + build script + "Build routing" + status. Done when
`curl valhalla:8002/route` answers on the server.
. `/api/route`, the vehicle profile, the route panel, save to library.
. Elevation profile of the route, then isochrones. Done:
* The browser samples the route every ≥50 m (at most 400 points) from
the same terrain tiles the hillshade uses (`dem.js`; from
`terrain.pmtiles` when it's there, else online), instead of
Valhalla's own SRTM download. The summary adds climb, descent and the
steepest grade sustained over 500 m. "Elevation profile" opens the
usual profile panel, and a saved route keeps the profile, so the
library shows it like a track's.
* `POST /api/isochrone` (`{"center": [lon, lat], "minutes": [...]}`,
1–4 times up to 240 min) returns Valhalla's polygons for the stored
vehicle. "Reach in" in the route panel draws them from the start
point, or from the map center when there are no points yet.
== Open questions
* Trailer / several vehicle profiles: one profile until it's needed.
* Build time and size for all 14 countries: measure on the first build
on the server.
+43 -13
View File
@@ -65,6 +65,17 @@ build, minus the trailing `sourceMappingURL` comment
| https://github.com/c0nsumer/maplibre-gl-lanes | https://github.com/c0nsumer/maplibre-gl-lanes
|=== |===
Also vendored under `public/vendor/mdi/` — Apache-2.0 (`LICENSE`
included alongside): the Material Design Icons (`@mdi/js`, version in
`package.json`, https://github.com/Templarian/MaterialDesign-JS) that
`public/js/icons.js` uses for the app's own UI icons. Only the icons
actually used are vendored, as `mdi.mjs`, generated by
`bin/vendor-sync.mjs`. The point and park4night glyphs stay the
National Park Service's: `public/vendor/nps-symbols/`, CC0, generated by
`bin/nps-symbols-sync.mjs` from
https://github.com/nationalparkservice/symbol-library (branch
`jakecoolidge-revision-2024`).
Also vendored under `public/vendor/` — MIT-licensed (© 2013 Panayiotis Also vendored under `public/vendor/` — MIT-licensed (© 2013 Panayiotis
Lipiridis), attribution required (this notice satisfies that): Lipiridis), attribution required (this notice satisfies that):
@@ -72,9 +83,9 @@ Lipiridis), attribution required (this notice satisfies that):
|=== |===
| Library | Version | Source | Library | Version | Source
| flag-icons (just the square `1x1/` crop, only the 39 European | flag-icons (just the square `1x1/` crop, only the countries the
countries `lib/maptool/data/europe_countries.geojson` lists — see offline region picker lists — `lib/maptool/data/geofabrik_regions.geojson`,
`public/js/offline_data.js`) see `bin/vendor-sync.mjs` and `public/js/offline_data.js`)
| `package.json` | `package.json`
| https://github.com/lipis/flag-icons | https://github.com/lipis/flag-icons
|=== |===
@@ -122,16 +133,24 @@ at runtime for the "Online" layer, and as a one-time vendored snapshot
(`public/vendor/liberty-style/liberty.json`) that the "Offline" layer (`public/vendor/liberty-style/liberty.json`) that the "Offline" layer
repoints at local data instead. Its icon sprite is vendored the same repoints at local data instead. Its icon sprite is vendored the same
way, under `public/vendor/liberty-sprite/` (`ofm.json`/`ofm.png` + way, under `public/vendor/liberty-sprite/` (`ofm.json`/`ofm.png` +
`@2x` variants, from `tiles.openfreemap.org/sprites/`). Neither has `@2x` variants, from `tiles.openfreemap.org/sprites/`).
been re-checked against a specific upstream version pin the way the
table above does — re-fetch both from `tiles.openfreemap.org` if The Noto Sans glyphs and the Liberty style/sprite are pinned to git
Liberty's own style/sprite ever visibly drifts from what's vendored. commits (protomaps/basemaps-assets, hyperknot/openfreemap-styles) in
`bin/assets-sync.mjs`. Renovate bumps those pins and runs the script in
the same PR, so the new files arrive with it. A new openfreemap-styles
commit only triggers the sync, which then saves whatever style
`tiles.openfreemap.org` currently serves.
`data/offline.pmtiles` (`lib/maptool/pmtiles_builder.rb`'s in-app `data/offline.pmtiles` (`lib/maptool/pmtiles_builder.rb`'s in-app
regeneration, or the manual recipe in `docs/development.adoc`) is regeneration, or the manual recipe in `docs/development.adoc`) is
built at build time, not vendored, from built at build time, not vendored, from
https://download.geofabrik.de[Geofabrik]'s per-country OpenStreetMap https://download.geofabrik.de[Geofabrik]'s per-country OpenStreetMap
extracts (ODbL). extracts (ODbL). The region list itself,
`lib/maptool/data/geofabrik_regions.geojson` (names, paths and boundary
polygons), is vendored from Geofabrik's index
(`download.geofabrik.de/index-v1.json`, OpenStreetMap-derived, ODbL) by
`bin/geofabrik-regions-sync.mjs`.
`terrain.pmtiles` (same regeneration mechanism) is extracted at build `terrain.pmtiles` (same regeneration mechanism) is extracted at build
time, not vendored, from https://mapterhorn.com[Mapterhorn] — a time, not vendored, from https://mapterhorn.com[Mapterhorn] — a
@@ -141,8 +160,20 @@ similar); see
https://download.mapterhorn.com/attribution.json[their own attribution https://download.mapterhorn.com/attribution.json[their own attribution
list] for the full provenance. list] for the full provenance.
Offline routing runs https://github.com/valhalla/valhalla[Valhalla]
(MIT) in its own container from Valhalla's published image
(`ghcr.io/valhalla/valhalla`, version pinned in `docker-compose.yaml`),
over the same Geofabrik extracts (ODbL). See `docs/routing-design.adoc`.
`public/can/esphome.eds`, the CANopen object dictionary of
https://github.com/mrk-its/esphome-canopen[esphome-canopen] nodes (the
CAN trace names SDO objects by it), is copied from
https://github.com/mrk-its/can2mqtt[can2mqtt]
(`src/can2mqtt/eds/esphome.eds`, commit `815ad0f`, MIT or Apache-2.0,
© mrk-its). Updated by hand.
Not a frontend asset like the above, but also baked into this app's own Not a frontend asset like the above, but also baked into this app's own
Docker image (not a separate container the way kiwix-serve/gpsd are — Docker image (not a separate container the way kiwix-serve is —
see `docs/deployment.adoc`/`docs/development.adoc`): three CLI tools see `docs/deployment.adoc`/`docs/development.adoc`): three CLI tools
`lib/maptool/pmtiles_builder.rb` shells out to for offline.pmtiles/ `lib/maptool/pmtiles_builder.rb` shells out to for offline.pmtiles/
terrain.pmtiles regeneration. terrain.pmtiles regeneration.
@@ -168,16 +199,15 @@ terrain.pmtiles regeneration.
|=== |===
Versions of the npm-published libraries above (MapLibre GL JS, pmtiles, Versions of the npm-published libraries above (MapLibre GL JS, pmtiles,
maplibre-contour, maplibre-gl-lanes, flag-icons, SunCalc) are pinned in maplibre-contour, maplibre-gl-lanes, flag-icons, SunCalc, Material Design Icons) are pinned in
`package.json` — the only thing it's for, the app itself has no JS `package.json` — the only thing it's for, the app itself has no JS
build step. Renovate (`renovate.json`) opens a PR per bump and its build step. Renovate (`renovate.json`) opens a PR per bump and its
`postUpgradeTasks` run `npm ci` + `node bin/vendor-sync.mjs`, so the PR `postUpgradeTasks` run `npm ci` + `node bin/vendor-sync.mjs`, so the PR
already contains the new files under `public/vendor/`. By hand: edit already contains the new files under `public/vendor/`. By hand: edit
`package.json`, then `npm install && node bin/vendor-sync.mjs`. `package.json`, then `npm install && node bin/vendor-sync.mjs`.
Everything else under `public/vendor/` (NPS plugins, Liberty The NPS plugins (patched, from an unmerged branch) and the National
style/sprite, fonts) isn't on npm or has no version to track — update Park typeface (no versioned source) are still updated by hand.
by hand and adjust this file.
go-pmtiles and Planetiler are pinned by `PMTILES_VERSION`/ go-pmtiles and Planetiler are pinned by `PMTILES_VERSION`/
`PLANETILER_VERSION` in the `Dockerfile`, which Renovate also bumps `PLANETILER_VERSION` in the `Dockerfile`, which Renovate also bumps
+259
View File
@@ -0,0 +1,259 @@
require "socket"
require "json"
module Maptool
# Native CAN for the van (the final setup; MQTT is the stopgap): raw
# SocketCAN frames off one or more interfaces (a USB adapter or the
# board's own controller, vcan0 for testing — all the same to Linux),
# CANopen's frame roles, and signals decoded from frames by a config —
# what goes on the bus (the car-CAN → CANopen bridge, own nodes, the
# GNSS node) isn't fixed yet, so nothing is hardcoded but CANopen itself.
#
# Config (data/can.json; CAN is off without it):
# { "interfaces": ["can0"],
# "nmt_start": true, // NMT "start all nodes" on connect
# "actions": [ // SDO writes, buttons beside the node in /can.html
# { "name": "Level IMU", "node": 33, "index": "0x2022", "subindex": 1, "data": "01" } ],
# "signals": [
# { "name": "gnss.lat", "id": "0x181", "byte": 0, "type": "i32", "scale": 1e-7 },
# { "name": "keypad.key1", "id": "0x195", "byte": 0, "bit": 0, "type": "bit" },
# { "name": "car.rpm", "id": "0x18FEF100", "mask": "0x00FFFF00", "byte": 3,
# "type": "u16", "scale": 0.125, "unit": "rpm" } ] }
# `id` matches the frame's id under `mask` (default: all bits); an id
# above 0x7FF is an extended (29-bit) one. Types are little-endian like
# CANopen: u8 i8 u16 i16 u32 i32 f32, or bit. value = raw * scale + offset;
# a raw `invalid` (e.g. 65535, esphome-canopen's "unknown") or a NaN float
# gives no value.
module Can
EFF_FLAG = 0x80000000 # extended frame
RTR_FLAG = 0x40000000
ERR_FLAG = 0x20000000
EFF_MASK = 0x1FFFFFFF
CAN_RAW = 1
FRAME = "LCx3a8" # struct can_frame: id, len, 3 bytes padding/reserved, data[8]
Frame = Struct.new(:id, :data, :extended) do
def self.unpack(bytes)
raw, len, data = bytes.unpack(FRAME)
return nil if raw & (ERR_FLAG | RTR_FLAG) != 0
new(raw & EFF_MASK, data.byteslice(0, [len, 8].min), raw & EFF_FLAG != 0)
end
def pack
[id | (extended ? EFF_FLAG : 0), data.bytesize, data.b.ljust(8, "\0")].pack(FRAME)
end
end
# A raw CAN socket bound to `interface` (struct sockaddr_can: family,
# padding, ifindex, 16 bytes of protocol-specific address).
def self.open(interface)
ifindex = Socket.getifaddrs.find { |i| i.name == interface }&.ifindex or raise SocketError, "no CAN interface #{interface}"
socket = Socket.new(Socket::AF_CAN, Socket::SOCK_RAW, CAN_RAW)
socket.bind([Socket::AF_CAN, ifindex].pack("Sx2lx16"))
socket
end
# CANopen's predefined connection set: what a COB-ID is.
def self.canopen_role(id, extended: false)
return nil if extended
node = id & 0x7F
case id >> 7
when 0x0 then id.zero? ? [:nmt, nil] : nil
when 0x1 then node.zero? ? [:sync, nil] : [:emcy, node]
when 0x2 then [:time, nil]
when 0x3, 0x5, 0x7, 0x9 then [:"tpdo#{((id >> 7) - 1) / 2}", node]
when 0x4, 0x6, 0x8, 0xA then [:"rpdo#{((id >> 7) - 2) / 2}", node]
when 0xB then [:sdo_tx, node]
when 0xC then [:sdo_rx, node]
when 0xE then [:heartbeat, node]
end
end
HEARTBEAT_STATES = { 0x00 => "boot-up", 0x04 => "stopped", 0x05 => "operational", 0x7F => "pre-operational" }.freeze
# NMT "start remote node" (node 0: all of them).
def self.nmt_start(node = 0)
Frame.new(0, [0x01, node].pack("CC"), false)
end
TYPES = { "u8" => ["C", 1], "i8" => ["c", 1], "u16" => ["S<", 2], "i16" => ["s<", 2],
"u32" => ["L<", 4], "i32" => ["l<", 4], "f32" => ["e", 4] }.freeze
# Frames → { "name" => value } by the config's signals, plus each
# discovered node's (#set_node, can_discovery.rb).
class Decoder
def initialize(signals)
@static = compile(signals)
@nodes = {}
@signals = @static
end
# A node's signals, replacing what it had (swapped in whole: the
# reader thread keeps decoding with the old list meanwhile).
def set_node(node, signals)
@nodes = @nodes.merge(node => compile(signals))
@signals = @static + @nodes.values.flatten
end
# { name => unit } of every signal that has one.
def units
@signals.each_with_object({}) { |s, units| units[s[:name]] = s[:unit] if s[:unit] }
end
def compile(signals)
signals.map do |s|
id = Integer(s.fetch("id"))
type = s.fetch("type", "u8")
raise ArgumentError, "#{s['name']}: unknown type #{type}" unless type == "bit" || TYPES.key?(type)
{ name: s.fetch("name"), id: id, mask: Integer(s.fetch("mask", "0x1FFFFFFF")), extended: id > 0x7FF,
byte: s.fetch("byte", 0), bit: s["bit"], type: type, scale: s.fetch("scale", 1), offset: s.fetch("offset", 0), invalid: s["invalid"],
unit: s["unit"] }
end
end
private :compile
def decode(frame)
@signals.each_with_object({}) do |s, values|
next unless s[:extended] == frame.extended && (frame.id & s[:mask]) == (s[:id] & s[:mask])
raw = if s[:type] == "bit"
byte = frame.data.getbyte(s[:byte])
byte && (byte >> s[:bit].to_i) & 1
else
format, size = TYPES.fetch(s[:type])
chunk = frame.data.byteslice(s[:byte], size)
chunk.unpack1(format) if chunk&.bytesize == size
end
next if raw.nil? || raw == s[:invalid] || (raw.is_a?(Float) && raw.nan?)
values[s[:name]] = s[:type] == "bit" ? raw : raw * s[:scale] + s[:offset]
end
end
end
# The latest of everything heard, for GET /api/can (and the /can.html
# diagnostics): interfaces, CANopen nodes (heartbeat state, last EMCY),
# every frame id seen (count, rate, last data) and the decoded signals.
class Store
MAX_FRAME_IDS = 2048 # ponytail: stops counting new ids past this, enough for a bus
LOG_SIZE = 5000 # the last frames as they came, for /trace.html (a few seconds of a busy bus)
# Signals starting with this aren't taken from the bus (the GNSS
# simulation's, put by #put, stand in for the node's meanwhile).
attr_accessor :override_prefix
def initialize
@mutex = Mutex.new
@signals = {}
@nodes = {}
@interfaces = {}
@frames = {}
@log = []
@seq = 0
end
def interface(name, **state)
@mutex.synchronize { (@interfaces[name] ||= { frames: 0 }).merge!(state) }
end
def record(interface, frame, values, at: Time.now.to_f)
@mutex.synchronize do
entry = (@interfaces[interface] ||= { frames: 0 })
entry[:frames] += 1
entry[:last_frame_at] = at
role, node = Can.canopen_role(frame.id, extended: frame.extended)
if node
n = (@nodes[node] ||= {})
if n.delete(:silent)
warn "can: node #{node} back after #{(at - n[:seen_at]).round}s"
end
if role == :heartbeat
n[:heartbeat_interval] = at - n[:heartbeat_at] if n[:heartbeat_at]
n[:heartbeat_at] = at
end
n[:seen_at] = at
n[:state] = HEARTBEAT_STATES.fetch(frame.data.getbyte(0) & 0x7F, "unknown") if role == :heartbeat && frame.data.bytesize >= 1
# EMCY: error code (0 = errors reset), error register, 5 bytes vendor-specific
n[:emcy] = { code: frame.data.unpack1("S<"), register: frame.data.getbyte(2), at: at } if role == :emcy && frame.data.bytesize >= 3
end
@log << { seq: @seq += 1, at: at, interface: interface, id: frame.id, extended: frame.extended, data: frame.data.unpack1("H*") }
@log.shift if @log.size > LOG_SIZE
key = "#{interface}:#{frame.extended ? format('%08X', frame.id) : format('%03X', frame.id)}"
f = @frames[key]
if f.nil? && @frames.size < MAX_FRAME_IDS
f = @frames[key] = { interface: interface, id: frame.id, extended: frame.extended, role: role, node: node, count: 0 }
end
if f
if f[:at] # smoothed time between frames, for the rate
gap = at - f[:at]
f[:interval] = f[:interval] ? f[:interval] * 0.8 + gap * 0.2 : gap
end
f.merge!(count: f[:count] + 1, data: frame.data.unpack1("H*"), at: at)
end
values.each { |name, value| @signals[name] = { value: value, at: at } unless @override_prefix && name.start_with?(@override_prefix) }
mark_silent(at)
end
end
def put(values, at: Time.now.to_f)
@mutex.synchronize { values.each { |name, value| @signals[name] = { value: value, at: at } } }
end
# A node with a heartbeat that missed 3 of them: silent, warned once
# (in the journal, so the time it stopped is kept). Checked as other
# frames come in — with the whole bus quiet the interface says so.
def mark_silent(at)
return if @checked_at && at - @checked_at < 1
@checked_at = at
@nodes.each do |node, n|
next if n[:silent] || !n[:heartbeat_interval] || at - n[:heartbeat_at] < 3 * n[:heartbeat_interval]
n[:silent] = true
warn "can: node #{node} silent, last heartbeat #{Time.at(n[:heartbeat_at]).strftime('%F %T')}"
end
end
# log: the frames after seq `since` (none without it); log_seq: the last one's.
def snapshot(since: nil)
@mutex.synchronize do
snap = { interfaces: @interfaces.dup, nodes: @nodes.dup, signals: @signals.dup, frames: @frames.values.map(&:dup) }
since ? snap.merge(log: @log.select { |f| f[:seq] > since }, log_seq: @seq) : snap
end
end
end
# Reads `interface` forever, reconnecting (warned once per outage, not
# every retry): an adapter unplugged, not up yet or the bus gone down
# isn't fatal, nor is anything else going wrong in here — the thread
# never dies, it waits and starts over.
# on_frame: called with every frame (CANopen TIME heard, can_time.rb).
def self.listen(interface, decoder:, store:, start_nodes: false, retry_delay: 5, on_frame: nil)
down = false
loop do
socket = open(interface)
store.interface(interface, up: true, error: nil)
warn "can: #{interface} up" if down
down = false
socket.write(nmt_start.pack) if start_nodes
loop do
bytes = socket.read(16) or raise IOError, "#{interface} closed"
frame = Frame.unpack(bytes)
next unless frame
on_frame&.call(frame)
values = decoder.decode(frame)
store.record(interface, frame, values)
yield(values) if block_given? && !values.empty?
end
rescue StandardError => e
store.interface(interface, up: false, error: e.message)
warn "can: #{interface}: #{e.message} — retrying every #{retry_delay}s" unless down
down = true
socket&.close
sleep retry_delay
end
end
end
end
+199
View File
@@ -0,0 +1,199 @@
require "json"
require "fileutils"
require_relative "can_sdo"
module Maptool
module Can
# Our esphome-canopen nodes describe themselves (canopen_entities' OD,
# OBJECT_DICTIONARY.md): their TPDOs (0x1800+n COB-ID, 0x1A00+n mapping)
# and, per mapped entity N, its type (0x2001:N) and metadata
# (0x2000+0x10·N: name, unit, min/max — the scale of a 1/2-byte value).
# Read once over SDO, cached by the TPDO layout hash (0x3002:1), the
# node's signals go into the Decoder — no hand-written can.json for them.
module Discovery
LAYOUT_HASH = [0x3002, 1].freeze
SCALED = { 6 => 1, 7 => 2, 9 => 1, 10 => 2 }.freeze # sensor8/16, number8/16 → bytes
FLOATS = [1, 8].freeze # sensor, number: REAL32
RAW = { 8 => "u8", 16 => "u16", 32 => "u32" }.freeze
def self.layout_hash(sdo, node)
sdo.upload(node, *LAYOUT_HASH).unpack1("L<")
end
# { node:, name:, hash:, signals: [Decoder signal config] }; raises
# Sdo::Abort when it isn't an esphome-canopen node (no 0x3002).
def self.describe(sdo, node, aliases: {})
hash = layout_hash(sdo, node)
name = optional { text(sdo.upload(node, 0x1008, 0)) }
label = name || format("node%02X", node)
entities = {}
signals = []
8.times do |n|
cob = optional { sdo.upload(node, 0x1800 + n, 1).unpack1("L<") }
next if cob.nil? || cob & 0x80000000 != 0 # not there / disabled
bit = 0
sdo.upload(node, 0x1A00 + n, 0).getbyte(0).times do |k|
entry = sdo.upload(node, 0x1A00 + n, k + 1).unpack1("L<")
index, sub, bits = entry >> 16, (entry >> 8) & 0xFF, entry & 0xFF
signal = entity_signal(sdo, node, entities, index, sub, bits)
if signal && bit % 8 == 0
full = "#{label}.#{signal.delete(:entity)}"
signals << apply_alias(signal.merge("source" => full, "id" => format("0x%03X", cob & 0x7FF), "byte" => bit / 8), aliases)
end
bit += bits
end
end
{ node: node, name: name, hash: hash, signals: signals }
end
# One TPDO entry as a signal, nil if it isn't an entity's state.
def self.entity_signal(sdo, node, entities, index, sub, bits)
return nil unless index.between?(0x2011, 0x2FF1) && (index - 0x2001) % 0x10 == 0
n = (index - 0x2001) / 0x10
entity = entities[n] ||= begin
meta = 0x2000 + 0x10 * n
{ type: sdo.upload(node, 0x2001, n).unpack1("L<") & 0xFF,
name: optional { text(sdo.upload(node, meta, 1)) } || "entity#{n}",
unit: optional { text(sdo.upload(node, meta, 3)) },
min: optional { sdo.upload(node, meta, 7).unpack1("e") },
max: optional { sdo.upload(node, meta, 8).unpack1("e") } }
end
name = sub == 1 ? entity[:name] : "#{entity[:name]} #{sub}"
base = { entity: name, "unit" => entity[:unit] }.compact
if FLOATS.include?(entity[:type]) && bits == 32
base.merge("type" => "f32")
elsif (size = SCALED[entity[:type]]) && bits == size * 8
# value = min + (max - min) * raw / (2^n - 2); 2^n - 1 = unknown
top = (1 << bits) - 1
min = entity[:min] || 0.0
max = entity[:max] || (top - 1).to_f
base.merge("type" => RAW.fetch(bits), "scale" => (max - min) / (top - 1), "offset" => min, "invalid" => top)
elsif RAW.key?(bits)
base.merge("type" => RAW.fetch(bits)) # switch, light, binary sensor…: the raw state
end
end
# The signal under its alias: a name ("gnss.lat"), or {"name", "scale",
# "unit"} when the app wants another unit (the node's km/h → m/s:
# "scale": 0.2777…). Applied to the node's own encoding, so a cached
# description takes today's aliases.
def self.apply_alias(signal, aliases)
alias_ = aliases[signal["source"]]
alias_ = { "name" => alias_ } if alias_.is_a?(String)
signal = signal.merge("name" => signal["source"]).reject { |k, _| k.start_with?("alias_") }
return signal unless alias_
k = alias_.fetch("scale", 1)
signal.merge("name" => alias_.fetch("name"), "scale" => signal.fetch("scale", 1) * k, "offset" => signal.fetch("offset", 0) * k,
"unit" => alias_.fetch("unit", signal["unit"]), "alias_scale" => k).compact
end
def self.text(bytes)
bytes.force_encoding("UTF-8").delete("\0")
end
def self.optional
yield
rescue Sdo::Abort
nil
end
private_class_method :optional, :text
end
# Describes every node heard (Store's nodes) in the background, one at
# a time: the layout hash checked again every RECHECK_S (cheap: one SDO),
# the full description read only when it changed; cached in cache_dir
# (data/can_nodes/<node>.json). Anything failing — not our kind of node,
# another SDO client in the way, the bus gone — is just tried later.
class Discoverer
POLL_S = 5
RECHECK_S = 600
RETRY_S = 30
NOT_OURS_S = 3600
def initialize(store:, decoder:, cache_dir:, aliases: {}, sdo: nil, interface: nil)
@store = store
@decoder = decoder
@cache_dir = cache_dir
@aliases = aliases
@sdo = sdo
@interface = interface
@next_at = {}
@described = {}
load_cache
end
def start
Thread.new do
loop do
run_once
rescue StandardError => e
warn "can discovery: #{e.message}"
@sdo = nil # a new socket next round
ensure
sleep POLL_S
end
end
end
def run_once(now: Time.now.to_f)
@store.snapshot[:nodes].each_key do |node|
next if @next_at.fetch(node, 0) > now
check(node, now)
end
end
private
def check(node, now)
sdo = (@sdo ||= Sdo.new(Sdo::SocketTransport.new(@interface)))
hash = Discovery.layout_hash(sdo, node)
unless @described[node]&.dig(:hash) == hash
description = Discovery.describe(sdo, node, aliases: @aliases)
save(description)
use(description)
warn "can discovery: node #{node} (#{description[:name]}): #{description[:signals].size} signals"
end
@next_at[node] = now + RECHECK_S
rescue Sdo::Abort
@next_at[node] = now + NOT_OURS_S # no 0x3002: not an esphome-canopen node
rescue Sdo::Error
@next_at[node] = now + RETRY_S
end
def use(description)
@described[description[:node]] = description
@decoder.set_node(description[:node], description[:signals])
end
def path(node)
File.join(@cache_dir, format("%02x.json", node))
end
def save(description)
FileUtils.mkdir_p(@cache_dir)
File.write(path(description[:node]), JSON.pretty_generate(description))
end
def load_cache
Dir.glob(File.join(@cache_dir, "*.json")).each do |file|
description = JSON.parse(File.read(file), symbolize_names: true)
# by today's aliases, not the ones it was cached with: back to the
# node's own scale first
description[:signals] = description[:signals].map do |s|
s = s.transform_keys(&:to_s)
k = s.delete("alias_scale") || 1
s = s.merge("scale" => s.fetch("scale", 1) / k, "offset" => s.fetch("offset", 0) / k) if k != 1
Discovery.apply_alias(s, @aliases)
end
use(description)
rescue JSON::ParserError, KeyError, NoMethodError
next
end
end
end
end
end
+91
View File
@@ -0,0 +1,91 @@
require "fileutils"
module Maptool
module Can
# Recording the bus on the server: can-recorder (can-recorder/, Rust)
# writes every interface's frames into ASAM MDF4 files, one per segment
# (`<dir>/<UTC start>.mf4`, asammdf with a DBC, CSS Electronics' tools);
# this starts it, stops it (SIGTERM: the segment being recorded is
# written) and lists what it wrote. Segments older than `keep` seconds
# go (it's diagnostics, ~85 MB an hour at 1000 frames/s): when listed and
# every segment while recording; `keep` nil keeps them all.
class Recorder
NAME = /\A\d{8}-\d{6}\.mf4\z/
STOP_WAIT = 10 # s for the last segment to be written
attr_reader :dir, :error, :started_at
def initialize(dir, interfaces, binary: ENV.fetch("CAN_RECORDER", "can-recorder"), segment: 300,
keep: (ENV.fetch("CAN_REC_KEEP_HOURS", "24").to_f * 3600).then { |s| s.positive? ? s : nil })
@dir = dir
@keep = keep
@interfaces = interfaces
@binary = binary
@segment = segment
@mutex = Mutex.new
end
def running?
@waiter&.alive? || false
end
def start
@mutex.synchronize do
return if running?
FileUtils.mkdir_p(@dir)
pid = Process.spawn(@binary, "--segment", @segment.to_s, @dir, *@interfaces)
@waiter = Process.detach(pid)
@pid = pid
@started_at = Time.now.to_f
@error = nil
waiter = @waiter
Thread.new { loop { prune; break if waiter.join(@segment) } }
rescue SystemCallError => e
@error = "#{@binary}: #{e.message}"
raise
end
end
def stop
@mutex.synchronize do
return unless running?
Process.kill("TERM", @pid)
@waiter.join(STOP_WAIT) or Process.kill("KILL", @pid)
status = @waiter.value
@error = "#{@binary} exited with #{status.exitstatus}" unless status.success?
@started_at = nil
end
end
# The newest first.
def files
return [] unless Dir.exist?(@dir)
prune
Dir.children(@dir).grep(NAME).sort.reverse.map do |name|
stat = File.stat(File.join(@dir, name))
{ name: name, size: stat.size, at: stat.mtime.to_f }
end
end
def prune
return unless @keep && Dir.exist?(@dir)
old = Time.now - @keep
Dir.children(@dir).grep(NAME).each do |name|
path = File.join(@dir, name)
File.delete(path) if File.mtime(path) < old
rescue SystemCallError
nil # gone meanwhile
end
end
def path(name)
path = File.join(@dir, name)
path if NAME.match?(name) && File.file?(path)
end
end
end
end
+123
View File
@@ -0,0 +1,123 @@
require_relative "can"
module Maptool
module Can
# A minimal SDO client (CiA 301): expedited and segmented uploads,
# expedited downloads — enough to read a node's description and write a
# command. Over a transport (#send a Frame, #receive(timeout) → Frame or
# nil): SocketTransport on its own raw socket, next to the reader thread's.
class Sdo
TIMEOUT_S = 1.0
class Error < StandardError; end
class Timeout < Error; end
class Abort < Error
attr_reader :code
def initialize(code)
@code = code
super(format("SDO abort 0x%08X", code))
end
end
class SocketTransport
def initialize(interface)
@socket = Can.open(interface)
end
def send(frame)
@socket.write(frame.pack)
end
def receive(timeout)
return nil unless IO.select([@socket], nil, nil, timeout)
Frame.unpack(@socket.recv(16))
end
def close
@socket.close
end
end
def initialize(transport, timeout: TIMEOUT_S)
@transport = transport
@timeout = timeout
end
# The object's bytes (strings come back as bytes: force_encoding them).
def upload(node, index, sub)
response = request(node, [0x40, index, sub, 0].pack("CS<CL<"), index: index, sub: sub)
cs = response.getbyte(0)
raise Error, format("unexpected SDO reply 0x%02X", cs) unless cs & 0xE0 == 0x40
if cs & 0x02 != 0 # expedited: the data's in this frame
size = cs & 0x01 != 0 ? 4 - ((cs >> 2) & 3) : 4
return response.byteslice(4, size)
end
data = "".b
toggle = 0
loop do
segment = request(node, [0x60 | (toggle << 4)].pack("C") + ("\0" * 7))
scs = segment.getbyte(0)
raise Error, "SDO segment out of order" unless scs & 0xE0 == 0x00 && (scs >> 4) & 1 == toggle
data << segment.byteslice(1, 7 - ((scs >> 1) & 7))
return data if scs & 0x01 != 0
toggle ^= 1
end
end
# An expedited download of up to 4 bytes.
def download(node, index, sub, bytes)
raise ArgumentError, "expedited: 1 to 4 bytes" unless (1..4).cover?(bytes.bytesize)
cs = 0x23 | ((4 - bytes.bytesize) << 2)
response = request(node, [cs, index, sub].pack("CS<C") + bytes.b.ljust(4, "\0"), index: index, sub: sub)
raise Error, format("unexpected SDO reply 0x%02X", response.getbyte(0)) unless response.getbyte(0) == 0x60
end
# A command from can.json's "actions", written by an expedited download
# — /can.html's buttons beside a node, e.g. levelling its IMU:
# { "name": "Level IMU", "node": 33, "index": "0x2022", "subindex": 1, "data": "01" }
# `data`: the bytes in hex, little-endian like the OD (1 to 4 bytes).
Action = Struct.new(:name, :node, :index, :sub, :bytes) do
def self.parse(config)
int = ->(v) { Integer(v) } # "0x2022" or 8226
bytes = [config.fetch("data")].pack("H*")
raise ArgumentError, "#{config["name"]}: data must be 1 to 4 bytes in hex" unless (1..4).cover?(bytes.bytesize)
new(config.fetch("name"), int.(config.fetch("node")), int.(config.fetch("index")), int.(config.fetch("subindex", 0)), bytes)
end
def run(sdo)
sdo.download(node, index, sub, bytes)
end
end
private
# Sends to 0x600+node, waits for 0x580+node. index/sub: an initiate's
# answer must be for that object — another SDO client talking to the
# same node (can2mqtt) gets its own answers too.
def request(node, data, index: nil, sub: nil)
@transport.send(Frame.new(0x600 + node, data, false))
deadline = Process.clock_gettime(Process::CLOCK_MONOTONIC) + @timeout
loop do
remaining = deadline - Process.clock_gettime(Process::CLOCK_MONOTONIC)
raise Timeout, format("no SDO answer from node 0x%02X", node) if remaining <= 0
frame = @transport.receive(remaining)
next unless frame && !frame.extended && frame.id == 0x580 + node && frame.data.bytesize == 8
next if index && frame.data.byteslice(1, 3).unpack("S<C") != [index, sub]
raise Abort, frame.data.byteslice(4, 4).unpack1("L<") if frame.data.getbyte(0) == 0x80
return frame.data
end
end
end
end
end
+75
View File
@@ -0,0 +1,75 @@
require_relative "can"
module Maptool
module Can
# CANopen TIME (CiA 301, COB-ID 0x100): the nodes' clock off the bus.
# maptool sends it only while nobody else does — the GNSS node, once
# esphome-canopen has TIME, gives the real one off the satellites; heard
# from it, maptool stays quiet until it's gone for 3 intervals.
class TimeProducer
ID = 0x100
EPOCH = Time.utc(1984, 1, 1)
INTERVAL_S = 1
# ponytail: a clock before this is taken for unset (a Pi without its
# RTC or NTP yet) and nothing is sent; chrony's sync state if that's wrong
MIN_YEAR = 2025
# TIME_OF_DAY: ms after midnight (28 bits, u32 LE), days since 1984-01-01 (u16 LE), UTC.
def self.frame(time)
t = time.utc
midnight = Time.utc(t.year, t.month, t.day)
ms = ((t - midnight) * 1000).floor
Frame.new(ID, [ms & 0x0FFFFFFF, ((midnight - EPOCH) / 86_400).round].pack("L<S<"), false)
end
def self.parse(data)
ms, days = data.unpack("L<S<")
EPOCH + days * 86_400 + (ms & 0x0FFFFFFF) / 1000.0
end
def initialize(&send)
@send = send
@sent = []
@others_at = nil
end
# A TIME frame read off the bus: ours (just sent, the reader's socket
# gets it too) or someone else's.
def heard(frame, at: Time.now.to_f)
return unless frame.id == ID && !frame.extended
@others_at = at unless @sent.include?(frame.data)
end
def others? (at = Time.now.to_f) = !!@others_at && at - @others_at < 3 * INTERVAL_S
# Every INTERVAL_S: sends the time unless another producer is on or the clock isn't set.
def tick(now = Time.now)
return :others if others?(now.to_f)
return :unset if now.year < MIN_YEAR
f = self.class.frame(now)
@sent = (@sent + [f.data]).last(5)
@send&.call(f)
:sent
end
end
end
end
if $PROGRAM_NAME == __FILE__
t = Time.utc(2026, 12, 4, 13, 45, 30.25)
f = Maptool::Can::TimeProducer.frame(t)
raise f.data.unpack1("H*") unless f.id == 0x100 && f.data.bytesize == 6
raise Maptool::Can::TimeProducer.parse(f.data).inspect unless (Maptool::Can::TimeProducer.parse(f.data) - t).abs < 0.001
sent = []
p = Maptool::Can::TimeProducer.new { |x| sent << x }
raise "send" unless p.tick(t) == :sent
p.heard(sent.last, at: t.to_f) # our own echo
raise "own echo" unless p.tick(t + 1) == :sent
p.heard(Maptool::Can::TimeProducer.frame(t + 0.5), at: t.to_f + 1) # the GNSS node's
raise "quiet" unless p.tick(t + 2) == :others
raise "back" unless p.tick(t + 5) == :sent
raise "unset" unless Maptool::Can::TimeProducer.new.tick(Time.utc(1970, 1, 1)) == :unset
puts "ok"
end
+66
View File
@@ -0,0 +1,66 @@
module Maptool
# A corridor either side of a route ([[lon, lat], ...]): what a plugin run
# along the trip's route covers (lib/maptool/plugins.rb). Flat-earth
# distances (equirectangular per segment) — fine for a few km either side.
module Corridor
KM_PER_DEG = 111.32
def self.km(a, b)
Math.hypot((b[0] - a[0]) * Math.cos((a[1] + b[1]) / 2 * Math::PI / 180), b[1] - a[1]) * KM_PER_DEG
end
# The route's vertices at least step_km apart (its ends kept): a short
# enough line for a query (Overpass' around: takes a polyline).
def self.thin(coords, step_km)
kept = [coords.first]
coords.each { |c| kept << c if km(kept.last, c) >= step_km }
kept << coords.last unless kept.last == coords.last
kept
end
# Circles ([[lon, lat], radius km]) covering the corridor half_km either
# side: centers every 1.5 × half_km along the line, radius 1.25 × half_km
# (√(0.75² + 1²) = 1.25, so no gap between two of them at the corridor's edge).
def self.circles(coords, half_km)
step = 1.5 * half_km
centers = [coords.first]
left = step
coords.each_cons(2) do |a, b|
length = km(a, b)
at = 0.0
while length - at >= left
at += left
t = at / length
centers << [a[0] + (b[0] - a[0]) * t, a[1] + (b[1] - a[1]) * t]
left = step
end
left -= length - at
end
centers << coords.last unless centers.last == coords.last
centers.map { |c| [c, 1.25 * half_km] }
end
# Shortest distance (km) from a point to the line.
def self.distance_km(point, coords)
lat0 = point[1] * Math::PI / 180
xy = ->(c) { [(c[0] - point[0]) * Math.cos(lat0) * KM_PER_DEG, (c[1] - point[1]) * KM_PER_DEG] }
return Math.hypot(*xy.(coords.first)) if coords.size == 1
coords.each_cons(2).map do |a, b|
(ax, ay), (bx, by) = xy.(a), xy.(b)
dx, dy = bx - ax, by - ay
len2 = dx * dx + dy * dy
t = len2.zero? ? 0.0 : (-(ax * dx + ay * dy) / len2).clamp(0.0, 1.0)
Math.hypot(ax + t * dx, ay + t * dy)
end.min
end
# [south, west, north, east] around the line, half_km wider each way.
def self.bbox(coords, half_km)
lons, lats = coords.map(&:first), coords.map { |c| c[1] }
dlat = half_km / KM_PER_DEG
dlon = half_km / (KM_PER_DEG * Math.cos(lats.map(&:abs).max * Math::PI / 180))
[lats.min - dlat, lons.min - dlon, lats.max + dlat, lons.max + dlon]
end
end
end
@@ -1 +0,0 @@
{"type":"FeatureCollection","features":[{"type":"Feature","properties":{"name":"Albania","iso_a2":"AL","iso_a3":"ALB"},"geometry":{"type":"Polygon","coordinates":[[[21.02004,40.842727],[20.99999,40.580004],[20.674997,40.435],[20.615,40.110007],[20.150016,39.624998],[19.98,39.694993],[19.960002,39.915006],[19.406082,40.250773],[19.319059,40.72723],[19.40355,41.409566],[19.540027,41.719986],[19.371769,41.877548],[19.371768,41.877551],[19.304486,42.195745],[19.738051,42.688247],[19.801613,42.500093],[20.0707,42.58863],[20.283755,42.32026],[20.52295,42.21787],[20.590247,41.855409],[20.590247,41.855404],[20.463175,41.515089],[20.605182,41.086226],[21.02004,40.842727]]]}},{"type":"Feature","properties":{"name":"Austria","iso_a2":"AT","iso_a3":"AUT"},"geometry":{"type":"Polygon","coordinates":[[[16.979667,48.123497],[16.903754,47.714866],[16.340584,47.712902],[16.534268,47.496171],[16.202298,46.852386],[16.011664,46.683611],[15.137092,46.658703],[14.632472,46.431817],[13.806475,46.509306],[12.376485,46.767559],[12.153088,47.115393],[11.164828,46.941579],[11.048556,46.751359],[10.442701,46.893546],[9.932448,46.920728],[9.47997,47.10281],[9.632932,47.347601],[9.594226,47.525058],[9.896068,47.580197],[10.402084,47.302488],[10.544504,47.566399],[11.426414,47.523766],[12.141357,47.703083],[12.62076,47.672388],[12.932627,47.467646],[13.025851,47.637584],[12.884103,48.289146],[13.243357,48.416115],[13.595946,48.877172],[14.338898,48.555305],[14.901447,48.964402],[15.253416,49.039074],[16.029647,48.733899],[16.499283,48.785808],[16.960288,48.596982],[16.879983,48.470013],[16.979667,48.123497]]]}},{"type":"Feature","properties":{"name":"Belarus","iso_a2":"BY","iso_a3":"BLR"},"geometry":{"type":"Polygon","coordinates":[[[28.176709,56.16913],[29.229513,55.918344],[29.371572,55.670091],[29.896294,55.789463],[30.873909,55.550976],[30.971836,55.081548],[30.757534,54.811771],[31.384472,54.157056],[31.791424,53.974639],[31.731273,53.794029],[32.405599,53.618045],[32.693643,53.351421],[32.304519,53.132726],[31.49764,53.16743],[31.305201,53.073996],[31.540018,52.742052],[31.78597,52.10168],[31.785992,52.101678],[30.927549,52.042353],[30.619454,51.822806],[30.555117,51.319503],[30.157364,51.416138],[29.254938,51.368234],[28.992835,51.602044],[28.617613,51.427714],[28.241615,51.572227],[27.454066,51.592303],[26.337959,51.832289],[25.327788,51.910656],[24.553106,51.888461],[24.005078,51.617444],[23.527071,51.578454],[23.508002,52.023647],[23.199494,52.486977],[23.799199,52.691099],[23.804935,53.089731],[23.527536,53.470122],[23.484128,53.912498],[24.450684,53.905702],[25.536354,54.282423],[25.768433,54.846963],[26.588279,55.167176],[26.494331,55.615107],[27.10246,55.783314],[28.176709,56.16913]]]}},{"type":"Feature","properties":{"name":"Belgium","iso_a2":"BE","iso_a3":"BEL"},"geometry":{"type":"Polygon","coordinates":[[[6.156658,50.803721],[6.043073,50.128052],[5.782417,50.090328],[5.674052,49.529484],[4.799222,49.985373],[4.286023,49.907497],[3.588184,50.378992],[3.123252,50.780363],[2.658422,50.796848],[2.513573,51.148506],[3.314971,51.345781],[3.315011,51.345777],[3.314971,51.345755],[4.047071,51.267259],[4.973991,51.475024],[5.606976,51.037298],[6.156658,50.803721]]]}},{"type":"Feature","properties":{"name":"Bosnia and Herz.","iso_a2":"BA","iso_a3":"BIH"},"geometry":{"type":"Polygon","coordinates":[[[18.56,42.65],[17.674922,43.028563],[17.297373,43.446341],[16.916156,43.667722],[16.456443,44.04124],[16.23966,44.351143],[15.750026,44.818712],[15.959367,45.233777],[16.318157,45.004127],[16.534939,45.211608],[17.002146,45.233777],[17.861783,45.06774],[18.553214,45.08159],[19.005485,44.860234],[19.00548,44.86023],[19.36803,44.863],[19.11761,44.42307],[19.59976,44.03847],[19.454,43.5681],[19.21852,43.52384],[19.03165,43.43253],[18.70648,43.20011],[18.56,42.65]]]}},{"type":"Feature","properties":{"name":"Bulgaria","iso_a2":"BG","iso_a3":"BGR"},"geometry":{"type":"Polygon","coordinates":[[[22.65715,44.234923],[22.944832,43.823785],[23.332302,43.897011],[24.100679,43.741051],[25.569272,43.688445],[26.065159,43.943494],[27.2424,44.175986],[27.970107,43.812468],[28.558081,43.707462],[28.039095,43.293172],[27.673898,42.577892],[27.99672,42.007359],[27.135739,42.141485],[26.117042,41.826905],[26.106138,41.328899],[25.197201,41.234486],[24.492645,41.583896],[23.692074,41.309081],[22.952377,41.337994],[22.881374,41.999297],[22.380526,42.32026],[22.545012,42.461362],[22.436595,42.580321],[22.604801,42.898519],[22.986019,43.211161],[22.500157,43.642814],[22.410446,44.008063],[22.65715,44.234923]]]}},{"type":"Feature","properties":{"name":"Croatia","iso_a2":"HR","iso_a3":"HRV"},"geometry":{"type":"Polygon","coordinates":[[[16.564808,46.503751],[16.882515,46.380632],[17.630066,45.951769],[18.456062,45.759481],[18.829825,45.908872],[19.072769,45.521511],[19.390476,45.236516],[19.005485,44.860234],[18.553214,45.08159],[17.861783,45.06774],[17.002146,45.233777],[16.534939,45.211608],[16.318157,45.004127],[15.959367,45.233777],[15.750026,44.818712],[Line truncated
@@ -0,0 +1 @@
{"type":"FeatureCollection","continents":[{"id":"europe","name":"Europe"},{"id":"north-america","name":"North America"},{"id":"central-america","name":"Central America"},{"id":"south-america","name":"South America"},{"id":"asia","name":"Asia"},{"id":"russia","name":"Russia"},{"id":"africa","name":"Africa"},{"id":"australia-oceania","name":"Australia and Oceania"},{"id":"antarctica","name":"Antarctica"}],"features":[{"type":"Feature","properties":{"code":"AF","name":"Afghanistan","slug":"asia/afghanistan","continent":"asia"},"geometry":{"type":"MultiPolygon","coordinates":[[[[62.4748,29.3819],[60.8505,29.8583],[61.7868,30.8377],[61.7675,30.9246],[61.8225,31.0412],[61.7892,31.1795],[61.7492,31.2399],[61.7028,31.3631],[60.8286,31.4898],[60.7945,31.6517],[60.8129,31.7388],[60.7918,31.8578],[60.8044,31.941],[60.7796,32.0351],[60.8186,32.1026],[60.839,32.2353],[60.5642,33.0668],[60.4876,33.7385],[60.5353,33.8197],[60.4902,34.1405],[60.5314,34.2067],[60.7068,34.5337],[60.7443,34.5674],[60.8411,34.5837],[60.9035,34.6506],[60.9682,34.7415],[61.053,34.9325],[61.0783,35.1777],[61.0764,35.2639],[61.107,35.2987],[61.1778,35.4069],[61.2474,35.5333],[61.2625,35.6249],[61.3871,35.6493],[61.4261,35.5759],[61.6036,35.462],[61.7917,35.4325],[61.9597,35.4767],[62.0413,35.463],[62.165,35.3576],[62.2756,35.3063],[62.3065,35.2626],[62.3167,35.1736],[62.4604,35.3048],[62.5181,35.2914],[62.5679,35.2517],[62.6269,35.2466],[62.71,35.2704],[62.9059,35.3963],[63.1023,35.5328],[63.0822,35.5546],[63.0789,35.6324],[63.198,35.6997],[63.1156,35.7657],[63.0863,35.8268],[63.1088,35.8759],[63.3166,35.8709],[63.599,35.9826],[63.7699,35.9976],[63.8812,36.0485],[63.969,36.0581],[64.0555,36.1123],[64.1566,36.1808],[64.3257,36.2394],[64.6053,36.4494],[64.5983,36.6359],[64.7785,36.9327],[64.7122,37.1297],[65.0723,37.2625],[65.2371,37.2489],[65.5402,37.2712],[65.6282,37.3591],[65.6281,37.4576],[65.6651,37.5257],[65.7034,37.5552],[65.755,37.5523],[65.7789,37.5878],[65.8603,37.5186],[66.0933,37.45],[66.2255,37.3911],[66.2962,37.3442],[66.4078,37.3634],[66.448,37.3407],[66.5831,37.3872],[66.6947,37.375],[66.8428,37.3743],[66.956,37.4146],[67.0686,37.3871],[67.1269,37.3372],[67.1369,37.292],[67.2275,37.2629],[67.2635,37.2058],[67.407,37.2389],[67.4946,37.2867],[67.5677,37.2428],[67.6046,37.2552],[67.7344,37.2342],[67.8034,37.1849],[67.8007,37.106],[67.8942,37.0766],[68.0253,36.9445],[68.175,37.0348],[68.2611,37.0276],[68.2619,37.0905],[68.2866,37.1232],[68.3974,37.1597],[68.5292,37.2084],[68.5996,37.2188],[68.6567,37.2906],[68.7601,37.2947],[68.7965,37.2779],[68.7987,37.3348],[68.8837,37.3547],[69.0041,37.326],[69.1334,37.1827],[69.2226,37.1321],[69.304,37.1373],[69.3875,37.181],[69.41,37.2179],[69.366,37.3359],[69.3654,37.4587],[69.5062,37.5952],[69.6466,37.5894],[69.7338,37.6142],[69.8006,37.6021],[69.9042,37.6324],[70.0215,37.5636],[70.142,37.5521],[70.2021,37.6267],[70.2411,37.6357],[70.2738,37.7012],[70.2556,37.803],[70.1695,37.8439],[70.1617,37.9462],[70.2442,37.962],[70.2509,37.9909],[70.3543,38.0686],[70.5321,38.2543],[70.5969,38.356],[70.6606,38.3765],[70.674,38.4272],[70.7349,38.438],[70.7664,38.4721],[70.8409,38.4681],[70.878,38.4857],[70.9252,38.4568],[70.9354,38.4883],[70.9881,38.5067],[71.0408,38.4752],[71.1149,38.4362],[71.2285,38.3422],[71.3409,38.32],[71.39,38.2622],[71.3926,38.1554],[71.3559,38.1197],[71.2885,37.9496],[71.34,37.9118],[71.5355,37.9695],[71.606,37.9284],[71.6121,37.8008],[71.5628,37.7605],[71.5677,37.7123],[71.5159,37.5451],[71.5429,37.4752],[71.5061,37.3913],[71.5076,37.2781],[71.4674,37.2034],[71.4497,37.0691],[71.4803,36.9978],[71.4795,36.9428],[71.5462,36.857],[71.5675,36.7786],[71.6753,36.6954],[71.8392,36.7023],[72.0127,36.8281],[72.3373,37.0058],[72.6563,37.0405],[72.8012,37.2433],[73.0726,37.3355],[73.1401,37.4173],[73.2136,37.4262],[73.3074,37.4821],[73.3837,37.4696],[73.517,37.4917],[73.6314,37.4558],[73.7844,37.455],[74.2335,37.4306],[74.3629,37.4417],[74.4121,37.4118],[74.4682,37.4438],[74.579,37.396],[74.6967,37.4216],[74.8195,37.3649],[74.9002,37.2699],[74.8974,37.2079],[74.8287,37.197],[74.799,37.2008],[74.7382,37.2644],[74.6609,37.2174],[74.5774,37.2183],[74.5227,37.2237],[74.4875,37.14],[74.58,37.0403],[74.5481,37.0059],[74.5524,36.9506],[74.5171,36.9426],[74.439,36.9835],[74.3045,36.8973],[74.2366,36.8779],[74.124,36.8213],[73.9796,36.8153],[73.6824,36.8959],[73.5431,36.8555],[73.303,36.8524],[73.0832,36.8669],[73.0419,36.8422],[72.963,36.8534],[72.9356,36.8269],[72.8908,36.8221],[72.6451,36.8285],[72.5745,36.8105],[72.5014,36.7616],[72.2526,36.7287],[72.2138,36.7015],[72.22,36.6484],[72.091,36.5738],[71.956,36.5327],[71.9174,36.491],[71.8223,36.4858],[71.8468,36.432],[71.8111,36.383],[71.6296,36.3929],[71.594,36.367],[71.605,36.3493],[71.588,36.3147],[71.5404,36.3073],[71.3558,36.1527],[71.2736,36.1186],[71.2229,36.0508],[71.3345,35.9815],[71.3948,35.9695],[71.4431,35.9004],[71.5183,35.8094],[71.567,35.7336],[71.6338,35.5817],[71.6742,35.4444],[71.5734,35.3019],[71.6983,35.2087],[71.6346,35.1251],[71.5Line truncated
+43 -15
View File
@@ -5,7 +5,7 @@ module Maptool
# to a GeoJSON FeatureCollection, in the same shape Gpx.to_geojson produces # to a GeoJSON FeatureCollection, in the same shape Gpx.to_geojson produces
# for a <trk>: one Feature per file, geometry MultiLineString, "kind" => # for a <trk>: one Feature per file, geometry MultiLineString, "kind" =>
# "track". Only "record" messages (the track points) and one "sport"/ # "track". Only "record" messages (the track points) and one "sport"/
# "session" field (the activity type) are read — FIT also carries laps, # "session" field (the activity type) and lap start times are read — FIT also carries
# events, device info, developer fields, none of which this app has # events, device info, developer fields, none of which this app has
# anywhere to show, so they're skipped by byte-length rather than # anywhere to show, so they're skipped by byte-length rather than
# interpreted. # interpreted.
@@ -16,12 +16,16 @@ module Maptool
RECORD_MESSAGE_NUM = 20 RECORD_MESSAGE_NUM = 20
SPORT_MESSAGE_NUM = 12 SPORT_MESSAGE_NUM = 12
SESSION_MESSAGE_NUM = 18 SESSION_MESSAGE_NUM = 18
LAP_MESSAGE_NUM = 19
FIELD_LAP_START_TIME = 2
FIELD_POSITION_LAT = 0 FIELD_POSITION_LAT = 0
FIELD_POSITION_LONG = 1 FIELD_POSITION_LONG = 1
FIELD_ALTITUDE = 2 FIELD_ALTITUDE = 2
FIELD_HEART_RATE = 3 FIELD_HEART_RATE = 3
FIELD_CADENCE = 4 FIELD_CADENCE = 4
FIELD_SPEED = 6 FIELD_SPEED = 6
FIELD_POWER = 7
FIELD_TEMPERATURE = 13
FIELD_TIMESTAMP = 253 FIELD_TIMESTAMP = 253
FIELD_ENHANCED_ALTITUDE = 78 FIELD_ENHANCED_ALTITUDE = 78
SPORT_FIELD_BY_MESSAGE = { SPORT_MESSAGE_NUM => 0, SESSION_MESSAGE_NUM => 5 }.freeze SPORT_FIELD_BY_MESSAGE = { SPORT_MESSAGE_NUM => 0, SESSION_MESSAGE_NUM => 5 }.freeze
@@ -44,7 +48,7 @@ module Maptool
}.freeze }.freeze
Definition = Struct.new(:global_mesg_num, :little_endian, :fields, :total_size) Definition = Struct.new(:global_mesg_num, :little_endian, :fields, :total_size)
ParseResult = Struct.new(:records, :activity_type) ParseResult = Struct.new(:records, :activity_type, :lap_starts)
def self.kinds(path) def self.kinds(path)
to_geojson(path)["features"].empty? ? [] : ["track"] to_geojson(path)["features"].empty? ? [] : ["track"]
@@ -60,18 +64,28 @@ module Maptool
def self.track_feature(result) def self.track_feature(result)
coordinates = result.records.map { |r| r[:coordinate] } coordinates = result.records.map { |r| r[:coordinate] }
extras = result.records.map { |r| { speed_mps: r[:speed_mps], cadence_rpm: r[:cadence], heart_rate_bpm: r[:heart_rate] } } laps = lap_indices(result)
extras = result.records.map { |r| { speed_mps: r[:speed_mps], cadence_rpm: r[:cadence], heart_rate_bpm: r[:heart_rate], power_w: r[:power], temperature_c: r[:temperature] } }
{ {
"type" => "Feature", "type" => "Feature",
"geometry" => { "type" => "MultiLineString", "coordinates" => [coordinates] }, "geometry" => { "type" => "MultiLineString", "coordinates" => [coordinates] },
"properties" => { "kind" => "track", "name" => nil, "activity_type" => result.activity_type } "properties" => { "kind" => "track", "name" => nil, "activity_type" => result.activity_type }
.merge(TrackStats.compute(coordinates, times: result.records.map { |r| r[:time] })) .merge(TrackStats.compute(coordinates, times: result.records.map { |r| r[:time] }))
.merge("profile" => TrackStats.build_profile(coordinates, times: result.records.map { |r| r[:time] }, extras: extras)), .merge("profile" => TrackStats.build_profile(coordinates, times: result.records.map { |r| r[:time] }, extras: extras))
.merge(laps ? { "laps" => laps } : {}),
} }
end end
private_class_method :track_feature private_class_method :track_feature
# Index of the first record of each lap, nil for a single lap.
def self.lap_indices(result)
indices = result.lap_starts.sort.map { |t| result.records.index { |r| r[:time] && r[:time].to_i >= t } }.compact.uniq
indices[0] = 0 if indices.any?
indices.size > 1 ? indices : nil
end
private_class_method :lap_indices
def self.parse(data) def self.parse(data)
raise ParseError, "not a FIT file" if data.bytesize < 12 || data.byteslice(8, 4) != ".FIT" raise ParseError, "not a FIT file" if data.bytesize < 12 || data.byteslice(8, 4) != ".FIT"
@@ -83,6 +97,7 @@ module Maptool
offset = header_size offset = header_size
definitions = {} definitions = {}
records = [] records = []
lap_starts = []
activity_type = nil activity_type = nil
while offset < data_end while offset < data_end
@@ -92,7 +107,7 @@ module Maptool
if header & 0x80 != 0 if header & 0x80 != 0
local_type = (header >> 5) & 0x3 local_type = (header >> 5) & 0x3
definition = definitions[local_type] or raise ParseError, "data message before its definition" definition = definitions[local_type] or raise ParseError, "data message before its definition"
offset, sport = read_data_message(data, offset, definition, records) offset, sport = read_data_message(data, offset, definition, records, lap_starts)
activity_type ||= sport activity_type ||= sport
elsif header & 0x40 != 0 elsif header & 0x40 != 0
local_type = header & 0x0F local_type = header & 0x0F
@@ -101,12 +116,12 @@ module Maptool
else else
local_type = header & 0x0F local_type = header & 0x0F
definition = definitions[local_type] or raise ParseError, "data message before its definition" definition = definitions[local_type] or raise ParseError, "data message before its definition"
offset, sport = read_data_message(data, offset, definition, records) offset, sport = read_data_message(data, offset, definition, records, lap_starts)
activity_type ||= sport activity_type ||= sport
end end
end end
ParseResult.new(records, activity_type) ParseResult.new(records, activity_type, lap_starts)
rescue ArgumentError, NoMethodError => e rescue ArgumentError, NoMethodError => e
raise ParseError, e.message raise ParseError, e.message
end end
@@ -141,11 +156,14 @@ module Maptool
# Returns [next_offset, sport_name_or_nil] — the latter only set when # Returns [next_offset, sport_name_or_nil] — the latter only set when
# this message happens to be the one sport/session message carrying it. # this message happens to be the one sport/session message carrying it.
def self.read_data_message(data, offset, definition, records) def self.read_data_message(data, offset, definition, records, lap_starts)
sport = nil sport = nil
if definition.global_mesg_num == RECORD_MESSAGE_NUM if definition.global_mesg_num == RECORD_MESSAGE_NUM
record = extract_record(data, offset, definition) record = extract_record(data, offset, definition)
records << record if record records << record if record
elsif definition.global_mesg_num == LAP_MESSAGE_NUM
start = field_value(data, offset, definition, FIELD_LAP_START_TIME)
lap_starts << FIT_EPOCH + start if start && !invalid?(start, 4)
elsif (field_num = SPORT_FIELD_BY_MESSAGE[definition.global_mesg_num]) elsif (field_num = SPORT_FIELD_BY_MESSAGE[definition.global_mesg_num])
sport = extract_sport(data, offset, definition, field_num) sport = extract_sport(data, offset, definition, field_num)
end end
@@ -154,23 +172,27 @@ module Maptool
private_class_method :read_data_message private_class_method :read_data_message
def self.extract_sport(data, offset, definition, target_field_num) def self.extract_sport(data, offset, definition, target_field_num)
value = field_value(data, offset, definition, target_field_num)
value && SPORT_NAMES[value]
end
def self.field_value(data, offset, definition, target_field_num)
pos = offset pos = offset
definition.fields.each do |field_num, size| definition.fields.each do |field_num, size|
if field_num == target_field_num return unpack_int(data, pos, size, definition.little_endian, signed: false) if field_num == target_field_num
value = unpack_int(data, pos, size, definition.little_endian, signed: false)
return SPORT_NAMES[value]
end
pos += size pos += size
end end
nil nil
end end
private_class_method :field_value
private_class_method :extract_sport private_class_method :extract_sport
# Only reads the fields the map/its properties need; every other field # Only reads the fields the map/its properties need; every other field
# in the message (power, temperature, ...) is walked past via its # in the message (temperature, ...) is walked past via its
# declared size without being interpreted. # declared size without being interpreted.
def self.extract_record(data, offset, definition) def self.extract_record(data, offset, definition)
lat = lon = altitude = timestamp = heart_rate = cadence = speed = nil lat = lon = altitude = timestamp = heart_rate = cadence = speed = power = temperature = nil
pos = offset pos = offset
definition.fields.each do |field_num, size| definition.fields.each do |field_num, size|
@@ -189,6 +211,10 @@ module Maptool
cadence = unpack_int(data, pos, size, definition.little_endian, signed: false) cadence = unpack_int(data, pos, size, definition.little_endian, signed: false)
when FIELD_SPEED when FIELD_SPEED
speed = unpack_int(data, pos, size, definition.little_endian, signed: false) speed = unpack_int(data, pos, size, definition.little_endian, signed: false)
when FIELD_POWER
power = unpack_int(data, pos, size, definition.little_endian, signed: false)
when FIELD_TEMPERATURE
temperature = unpack_int(data, pos, size, definition.little_endian, signed: true)
end end
pos += size pos += size
end end
@@ -201,8 +227,10 @@ module Maptool
heart_rate = nil if heart_rate.nil? || invalid?(heart_rate, 1) heart_rate = nil if heart_rate.nil? || invalid?(heart_rate, 1)
cadence = nil if cadence.nil? || invalid?(cadence, 1) cadence = nil if cadence.nil? || invalid?(cadence, 1)
speed_mps = speed && !invalid?(speed, 2) ? speed / 1000.0 : nil speed_mps = speed && !invalid?(speed, 2) ? speed / 1000.0 : nil
power = nil if power.nil? || invalid?(power, 2)
temperature = nil if temperature.nil? || invalid?(temperature, 1)
{ coordinate: coordinate, time: time, heart_rate: heart_rate, cadence: cadence, speed_mps: speed_mps } { coordinate: coordinate, time: time, heart_rate: heart_rate, cadence: cadence, speed_mps: speed_mps, power: power, temperature: temperature }
end end
private_class_method :extract_record private_class_method :extract_record
+114
View File
@@ -0,0 +1,114 @@
require_relative "track_stats"
module Maptool
# A line (a planned route or a track) as a FIT course file, what Garmin
# and Wahoo devices follow: file_id, course, lap, timer start, one
# record per point (position, altitude, distance, a timestamp spread
# over `duration`), timer stop. https://developer.garmin.com/fit/file-types/course/
module FitCourse
FIT_EPOCH = Time.utc(1989, 12, 31).to_i
SEMICIRCLES = (2**31) / 180.0
SPORTS = { "running" => 1, "cycling" => 2, "walking" => 11, "hiking" => 17 }.freeze
CRC_TABLE = [0x0000, 0xCC01, 0xD801, 0x1400, 0xF001, 0x3C00, 0x2800, 0xE401,
0xA001, 0x6C00, 0x7800, 0xB401, 0x5000, 0x9C01, 0x8801, 0x4400].freeze
# [global message number, [[field number, base type, pack format], ...]]
FILE_ID = [0, [[0, 0x00, "C"], [1, 0x84, "S<"], [2, 0x84, "S<"], [4, 0x86, "L<"]]].freeze
COURSE = [31, [[4, 0x00, "C"], [5, 0x07, "a32"]]].freeze
LAP = [19, [[253, 0x86, "L<"], [2, 0x86, "L<"], [3, 0x85, "l<"], [4, 0x85, "l<"], [5, 0x85, "l<"], [6, 0x85, "l<"],
[7, 0x86, "L<"], [8, 0x86, "L<"], [9, 0x86, "L<"]]].freeze
EVENT = [21, [[253, 0x86, "L<"], [0, 0x00, "C"], [1, 0x00, "C"]]].freeze
RECORD = [20, [[253, 0x86, "L<"], [0, 0x85, "l<"], [1, 0x85, "l<"], [2, 0x84, "S<"], [5, 0x86, "L<"]]].freeze
COURSE_POINT = [32, [[254, 0x84, "S<"], [1, 0x86, "L<"], [2, 0x85, "l<"], [3, 0x85, "l<"], [4, 0x86, "L<"], [5, 0x00, "C"], [6, 0x07, "a16"]]].freeze
DEFAULT_SPEED = 4.0 # m/s, when the line has no time of its own
# FIT course_point types, guessed from a point's name/category/icon
# (English and Slovak words); anything else is generic (0).
POINT_TYPES = [
[3, /water|spring|fountain|drink|voda|prame|studni/i],
[4, /food|restaurant|caf|shop|bakery|jedlo|reštaur|krčm|obchod/i],
[9, /first.?aid|hospital|pharmac|doctor|lekár|nemocn/i],
[5, /danger|warning|caution|pozor|nebezpe/i],
[1, /summit|peak|top\b|vrch|štít|kopec/i],
[2, /valley|saddle|pass\b|údoli|sedlo/i],
].freeze
# coordinates: [[lon, lat(, ele)], ...]; duration: seconds or nil;
# points: [{ coordinate:, name:, hint: }] shown along the course (each
# placed at the nearest point of the line).
def self.encode(coordinates, name:, sport: nil, duration: nil, points: [])
raise ArgumentError, "a course needs at least two points" if coordinates.size < 2
distances = [0.0]
coordinates.each_cons(2) { |(lon1, lat1), (lon2, lat2)| distances << distances.last + TrackStats.haversine(lat1, lon1, lat2, lon2) }
total = distances.last
duration = duration.to_f.positive? ? duration.to_f : total / DEFAULT_SPEED
start = Time.now.to_i - FIT_EPOCH
finish = start + duration.round
first, last = coordinates.first, coordinates.last
body = message(0, FILE_ID, [6, 255, 0, start]) + # type 6: course; 255: development
message(1, COURSE, [SPORTS.fetch(sport, 0), name.to_s.byteslice(0, 31).scrub("")]) +
message(2, LAP, [finish, start, *semicircles(first), *semicircles(last), duration * 1000, duration * 1000, total * 100]) +
message(3, EVENT, [start, 0, 0]) # timer, start
body << definition(4, RECORD)
coordinates.each_with_index do |(lon, lat, ele), i|
at = start + (total.positive? ? duration * distances[i] / total : 0).round
body << data(4, RECORD, [at, *semicircles([lon, lat]), ele ? ((ele + 500) * 5).round.clamp(0, 0xFFFE) : 0xFFFF, (distances[i] * 100).round])
end
unless points.empty?
body << definition(5, COURSE_POINT)
at_index = ->(i) { start + (total.positive? ? duration * distances[i] / total : 0).round }
points.map { |point| [nearest(coordinates, point[:coordinate]), point] }.sort_by(&:first).each_with_index do |(i, point), n|
type = POINT_TYPES.find { |_, pattern| point[:hint].to_s.match?(pattern) }&.first || 0
label = point[:name].to_s.byteslice(0, 15).scrub("")
body << data(5, COURSE_POINT, [n, at_index.(i), *semicircles(point[:coordinate]), (distances[i] * 100).round, type, label])
end
end
body << data(3, EVENT, [finish, 0, 9]) # timer, stop_disable_all
header = [14, 0x10, 2132, body.bytesize].pack("CCS<L<") + ".FIT"
header += [crc(header)].pack("S<")
file = header + body
file + [crc(file)].pack("S<")
end
# ponytail: linear scan per point; fine for hundreds of points on a few thousand.
def self.nearest(coordinates, (lon, lat))
coordinates.each_index.min_by { |i| (coordinates[i][0] - lon)**2 + (coordinates[i][1] - lat)**2 }
end
private_class_method :nearest
def self.semicircles((lon, lat))
[(lat * SEMICIRCLES).round, (lon * SEMICIRCLES).round]
end
private_class_method :semicircles
def self.message(local, layout, values)
definition(local, layout) + data(local, layout, values)
end
private_class_method :message
SIZES = { "C" => 1, "S<" => 2, "L<" => 4, "l<" => 4, "a16" => 16, "a32" => 32 }.freeze
def self.definition(local, (global, fields))
[0x40 | local, 0, 0, global, fields.size].pack("CCCS<C") +
fields.map { |num, type, format| [num, SIZES.fetch(format), type].pack("CCC") }.join
end
private_class_method :definition
def self.data(local, (_, fields), values)
[local].pack("C") + fields.zip(values).map { |(_, _, format), value| [format.start_with?("a") ? value : value.round].pack(format) }.join
end
private_class_method :data
def self.crc(bytes)
bytes.each_byte.reduce(0) do |crc, byte|
[byte & 0xF, byte >> 4].reduce(crc) do |c, nibble|
tmp = CRC_TABLE[c & 0xF]
c = (c >> 4) & 0x0FFF
c ^ tmp ^ CRC_TABLE[nibble]
end
end
end
private_class_method :crc
end
end
+260
View File
@@ -0,0 +1,260 @@
require_relative "routing"
module Maptool
# Simulated driving, to try the dashboard and navigation without the car:
# from a start point it routes (our Valhalla) to a random point 2–8 km
# away and drives there at the road's speed limit, a fix every TICK_S, then
# on to the next random point. Its fixes go where the GNSS node's do
# (app.rb: the CAN store's gnss.* signals and GNSS_LATEST), the node's own
# are ignored meanwhile.
class GnssSim
TICK_S = 0.5 # finer than the clients poll (1.5 s), so each poll sees a fresh fix
DEST_KM = (2.0..8.0)
NO_LIMIT_KMH = 50 # an untagged road
UNLIMITED_KMH = 130
LIMIT_SHARE = 0.9 # drives a bit under the limit
attr_reader :error
# 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))
@valhalla_url = valhalla_url
@router = router
@vehicle = vehicle
@random = random
@sleep = sleep
@thread = nil
@mutex = Mutex.new
@speedup = 1
@clock = Time.now.to_f
end
def running?
@mutex.synchronize { @thread&.alive? || false }
end
RANDOM_START_TRIES = 20 # a random point at sea / off the routing tiles: another one
# Shorter: a road island the start snapped to (a lake's middle → a 0 km
# route), it'd drive the same few meters again and again — another try.
MIN_TRIP_KM = 1.0
# Drives from [lon, lat] until stopped — or, with bboxes
# ([[west, south, east, north], ...], the offline countries) instead,
# 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:, mode: 3, time: the simulation's epoch s }.
# With track ([[lon, lat, elapsed s], ...], a library track's) instead:
# that track replayed at its own speed, then it stops.
def start(lon = nil, lat = nil, bboxes: nil, route: nil, track: nil, &on_fix)
stop
@error = nil
@clock = Time.now.to_f
@mutex.synchronize do
@thread = Thread.new do
next replay(track, &on_fix) if track
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
loop do
position = drive(position, route, &on_fix)
route = nil
rescue Routing::RouteError
raise unless bboxes
position, route = random_start(bboxes) # no way on from here: somewhere else
end
rescue StandardError => e
@error = e.message
warn "gnss sim: #{e.message}"
end
end
end
def stop
thread = @mutex.synchronize { @thread.tap { @thread = nil } }
thread&.kill&.join
end
# A random place in one of the bboxes with a route out of it: [position, route].
def random_start(bboxes)
RANDOM_START_TRIES.times do
west, south, east, north = bboxes.sample(random: @random)
position = [west + @random.rand * (east - west), south + @random.rand * (north - south)]
return [position, random_route(position)]
rescue Routing::RouteError
next
end
raise Routing::RouteError, "no road found at #{RANDOM_START_TRIES} random places in the offline countries"
end
# One random trip from position (route: already planned); returns where it ended.
def drive(position, route = nil, &on_fix)
route ||= random_route(position)
coords = route[:geometry][:coordinates]
km = [0.0]
coords.each_cons(2) { |a, b| km << km.last + self.class.meters(a, b) / 1000 }
limits = route[:properties][:speed_limits] || [[0.0, nil]]
at = 0.0
i = 1
while i < coords.size
kmh = speed_kmh(limits.reverse.find { |start, _| start <= at }&.last)
at += kmh / 3600 * TICK_S * @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, mode: 3, time: @clock.round(1))
break if i == coords.size - 1 && t >= 1
@sleep.call(TICK_S)
end
coords.last
end
MAX_GAP_S = 30 # a stop longer than this in a replayed track: cut to it
# A recorded track driven again at its own pace (sped up like the
# rest): points [lon, lat, elapsed s]; long stops shortened to MAX_GAP_S.
def replay(points, &on_fix)
shift = 0.0
points = points.each_cons(2).each_with_object([[*points.first.first(2), 0.0]]) do |(a, b), out|
shift += [b[2] - a[2] - MAX_GAP_S, 0].max
out << [b[0], b[1], b[2] - points.first[2] - shift]
end
t = 0.0
i = 1
while i < points.size
t += TICK_S * @speedup
@clock += TICK_S * @speedup
i += 1 while i < points.size - 1 && points[i][2] < t
a, b = points[i - 1], points[i]
dt = b[2] - a[2]
f = dt.positive? ? ((t - a[2]) / dt).clamp(0.0, 1.0) : 1.0
lon, lat = a.first(2).zip(b.first(2)).map { |p, q| p + (q - p) * f }
speed = dt.positive? ? self.class.meters(a, b) / dt : 0.0
on_fix&.call(lat: lat, lon: lon, speed: speed, satellites: 12, hdop: 0.8, mode: 3, time: @clock.round(1))
break if i == points.size - 1 && f >= 1
@sleep.call(TICK_S)
end
end
def speed_kmh(limit)
(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
5.times do
bearing = @random.rand * 2 * Math::PI
distance = @random.rand(DEST_KM) * 1000
lon, lat = position
dest = [lon + distance * Math.sin(bearing) / (111_320 * Math.cos(lat * Math::PI / 180)), lat + distance * Math.cos(bearing) / 111_320]
route = @router.call(@valhalla_url, [position, dest], @vehicle)
return route if route[:geometry][:coordinates].size >= 2 && route[:properties][:distance_km].to_f >= MIN_TRIP_KM
last = Routing::RouteError.new("only #{route[:properties][:distance_km]} km")
rescue Routing::RouteError => e
last = e
end
raise Routing::RouteError, "no route from #{position.map { |v| v.round(5) }.join(', ')}: #{last&.message}"
end
# Initial bearing from one [lon, lat] to another, 0..360° from north.
def self.bearing((lon1, lat1), (lon2, lat2))
rad = Math::PI / 180
d = (lon2 - lon1) * rad
y = Math.sin(d) * Math.cos(lat2 * rad)
x = Math.cos(lat1 * rad) * Math.sin(lat2 * rad) - Math.sin(lat1 * rad) * Math.cos(lat2 * rad) * Math.cos(d)
(Math.atan2(y, x) / rad) % 360
end
def self.meters((lon1, lat1), (lon2, lat2))
Math.hypot((lon2 - lon1) * Math.cos((lat1 + lat2) / 2 * Math::PI / 180), lat2 - lat1) * 111_320
end
end
end
+150
View File
@@ -0,0 +1,150 @@
require "csv"
require "json"
require "net/http"
require "uri"
require "zip"
module Maptool
# Google Maps saved lists ("Want to go", "Norway 2026", …) from a Google
# Takeout export: product "Saved", one Takeout/Saved/<list>.csv each with
# Title,Note,URL,Tags,Comment. The URL carries no coordinates, only the
# place's feature id (…/data=!4m2!3m1!1s0x45de3cbf60603ce7:0x82f2b236d153558f),
# whose first half is an S2 cell id around the place: decoded offline it's
# within a few hundred metres to a few km (the low bits look hashed), then
# refined by a Nominatim name search around it. A place Nominatim can't
# find keeps the decoded spot and `approximate: true`.
module GoogleSaved
FEATURE_ID = /!1s(0x\h+):(0x\h+)/
SAVED_ENTRY = %r{\ATakeout/Saved/[^/]+\.csv\z}
NOMINATIM = "https://nominatim.openstreetmap.org/search"
# Search box around the decoded spot, degrees (~10 km).
REFINE_RADIUS = 0.1
# A CSV Google wrote (header Title,…,URL)? Other Takeout CSVs aren't lists.
def self.saved_list?(text)
text.sub(/\A/, "").start_with?("Title,Note,URL")
end
# CSV text → GeoJSON point features, unrefined. `source_id` is Google's
# feature id: Library updates a point with the same one in the same
# folder instead of adding it again.
def self.features(text)
CSV.parse(text.sub(/\A/, ""), headers: true).filter_map do |row|
url = row["URL"].to_s
match = url.match(FEATURE_ID)
coords = url[%r{/maps/search/(-?\d+\.\d+),[+\s]*(-?\d+\.\d+)}] && [Regexp.last_match(2).to_f, Regexp.last_match(1).to_f]
approximate = coords.nil?
coords ||= match && s2_lng_lat(match[1].to_i(16))
next unless coords
name = row["Title"].to_s.strip
name = "Saved place" if name.empty?
# One text the point popup shows and linkifies: the list's note and
# comment, then the way back to the place in Google Maps.
description = [row["Note"], row["Comment"], "Google Maps: #{url}"].map { |t| t.to_s.strip }.reject(&:empty?).join("\n\n")
props = { "name" => name, "description" => description,
"source_id" => (match ? "google:#{match[1]}:#{match[2]}" : "google:#{url}"),
"approximate" => (true if approximate) }.compact
{ "type" => "Feature", "geometry" => { "type" => "Point", "coordinates" => coords.map { |c| c.round(6) } }, "properties" => props }
end
end
# Moves each approximate feature onto `lookup.(name, lng, lat)` → [lng,
# lat] or nil; one that isn't found stays approximate.
def self.refine!(features, lookup: method(:nominatim))
features.each do |feature|
props = feature["properties"]
next unless props["approximate"]
found = lookup.call(props["name"], *feature["geometry"]["coordinates"])
next unless found
feature["geometry"]["coordinates"] = found.map { |c| c.round(6) }
props.delete("approximate")
end
end
# Nominatim's usage policy: at most 1 request a second, an identifying
# User-Agent.
def self.nominatim(name, lng, lat)
sleep 1
r = REFINE_RADIUS
uri = URI(NOMINATIM)
uri.query = URI.encode_www_form(q: name, format: "jsonv2", limit: 1, bounded: 1,
viewbox: [lng - r, lat + r, lng + r, lat - r].join(","))
response = Net::HTTP.start(uri.host, uri.port, use_ssl: true, open_timeout: 10, read_timeout: 20) do |http|
http.request(Net::HTTP::Get.new(uri, "User-Agent" => "maptool (Google saved lists import)"))
end
hit = response.is_a?(Net::HTTPSuccess) && JSON.parse(response.body).first
hit && [hit["lon"].to_f, hit["lat"].to_f]
rescue JSON::ParserError, Net::OpenTimeout, Net::ReadTimeout, SocketError, SystemCallError, OpenSSL::SSL::SSLError
nil
end
# Each Takeout zip in `dir` holding saved lists, newest first: only the
# zip's central directory is read, so the multi-GB photo parts of the
# same export are cheap to skip.
def self.takeout_zips(dir)
Dir.glob(File.join(dir, "*.zip")).select do |path|
Zip::File.open(path) { |zip| zip.entries.any? { |e| e.name.match?(SAVED_ENTRY) } }
rescue Zip::Error
false
end.sort_by { |path| -File.mtime(path).to_f }
end
# { "<list name>" => csv text } for the zip's saved lists.
def self.lists(zip_path)
Zip::File.open(zip_path) do |zip|
zip.entries.select { |e| e.name.match?(SAVED_ENTRY) }
.to_h { |e| [File.basename(e.name, ".csv"), e.get_input_stream.read.force_encoding("UTF-8")] }
.select { |_, text| saved_list?(text) }
end
end
# Imports the newest Takeout zip in `dir` with saved lists, once (its
# name, size and mtime are remembered in `state_path`), each list into
# "<folder>/<list name>". Returns the number of places, nil if nothing new.
def self.import_takeout(dir, library:, state_path:, folder: "Google Maps", lookup: method(:nominatim))
zip = takeout_zips(dir).first or return nil
stamp = [File.basename(zip), File.size(zip), File.mtime(zip).to_i].join(" ")
return nil if File.exist?(state_path) && File.read(state_path) == stamp
count = lists(zip).sum do |list, text|
places = features(text)
next 0 if places.empty? # Images / Saved for later: no places, no folder
refine!(places, lookup: lookup)
library.import_features(places, folder: "#{folder}/#{list.tr('/', '_')}")
places.size
end
File.write(state_path, stamp)
count
end
# S2 cell id → [lng, lat] of the cell's center (the S2 library's
# face/Hilbert-curve decoding, quadratic projection).
POS_TO_IJ = [[0, 1, 3, 2], [0, 2, 3, 1], [3, 2, 0, 1], [3, 1, 0, 2]].freeze
POS_TO_ORIENTATION = [1, 0, 0, 3].freeze
def self.s2_lng_lat(id)
face = id >> 61
i = j = 0
orientation = face & 1
30.times do |k|
bits = (id >> (59 - 2 * k)) & 3
ij = POS_TO_IJ[orientation][bits]
i = (i << 1) | (ij >> 1)
j = (j << 1) | (ij & 1)
orientation ^= POS_TO_ORIENTATION[bits]
end
uv = lambda do |n|
s = (n + 0.5) / (1 << 30)
s >= 0.5 ? (4 * s * s - 1) / 3.0 : (1 - 4 * (1 - s) * (1 - s)) / 3.0
end
u = uv.call(i)
v = uv.call(j)
x, y, z = [[1, u, v], [-u, 1, v], [-u, -v, 1], [-1, -v, -u], [v, -1, -u], [v, u, -1]][face]
[Math.atan2(y, x) * 180 / Math::PI, Math.atan2(z, Math.hypot(x, y)) * 180 / Math::PI]
end
end
end
-57
View File
@@ -1,57 +0,0 @@
require "socket"
require "json"
module Maptool
# A minimal client for gpsd's JSON protocol (https://gpsd.io/gpsd_json.html).
# Connects over TCP, asks gpsd to watch for reports, and yields a plain
# position hash for every TPV ("time-position-velocity") report — gpsd's
# term for a GNSS fix — for as long as the block keeps running.
class GpsdClient
RECONNECT_DELAY = 5 # seconds, after gpsd is unreachable or drops us
def initialize(host: "127.0.0.1", port: 2947)
@host = host
@port = port
end
# Never returns under normal operation: reconnects on any I/O error
# (gpsd not running yet, connection dropped, etc.) after a short delay,
# so a missing/disconnected receiver is not fatal to the caller.
def each_position
loop do
watch { |position| yield position }
rescue SystemCallError, EOFError, SocketError => e
warn "[gpsd] #{e.class}: #{e.message} — retrying in #{RECONNECT_DELAY}s"
sleep RECONNECT_DELAY
end
end
private
def watch
socket = TCPSocket.new(@host, @port)
socket.puts('?WATCH={"enable":true,"json":true};')
socket.each_line do |line|
report = JSON.parse(line)
next unless report["class"] == "TPV"
next unless report["lat"] && report["lon"]
yield(
lat: report["lat"],
lon: report["lon"],
# altHAE (height above ellipsoid) is gpsd's modern field; older
# gpsd versions only send "alt".
alt: report["altHAE"] || report["alt"],
speed: report["speed"],
track: report["track"],
mode: report["mode"], # 0/1 = no fix, 2 = 2D, 3 = 3D
eph: report["eph"], # estimated horizontal position error, metres
time: report["time"],
)
end
ensure
socket&.close
end
end
end
+86 -1
View File
@@ -57,6 +57,89 @@ module Maptool
end end
private_class_method :waypoint_feature private_class_method :waypoint_feature
# The other direction, for exporting to OsmAnd/Locus (Library#export):
# Point features → <wpt>, kind "route" lines → <rte>, every other line
# or polygon ring → <trk>. `group` replaces every waypoint's <type>
# (OsmAnd reads it as the favourites group); without it the point's own
# category is kept. Colors go out as <osmand:color> (what import reads
# back) and, on lines, gpx_style's <line><color>, which Locus reads.
def self.from_features(features, group: nil)
doc = REXML::Document.new
doc << REXML::XMLDecl.new("1.0", "UTF-8")
gpx = doc.add_element("gpx", "version" => "1.1", "creator" => "MapTool", "xmlns" => "http://www.topografix.com/GPX/1/1",
"xmlns:osmand" => OSMAND_NAMESPACE, "xmlns:gpx_style" => GPX_STYLE_NAMESPACE)
points, lines = features.partition { |f| f.dig("geometry", "type") == "Point" }
points.each { |f| write_waypoint(gpx, f, group) }
lines.each { |f| write_line(gpx, f) }
out = +""
doc.write(output: out)
out
end
GPX_STYLE_NAMESPACE = "http://www.topografix.com/GPX/gpx_style/0/2"
private_constant :GPX_STYLE_NAMESPACE
def self.write_waypoint(gpx, feature, group)
props = feature["properties"] || {}
wpt = gpx.add_element("wpt", position_attributes(feature["geometry"]["coordinates"]))
add_text(wpt, "ele", feature["geometry"]["coordinates"][2])
add_text(wpt, "time", props["time"])
add_text(wpt, "name", props["name"])
add_text(wpt, "desc", props["description"])
add_text(wpt, "type", group || props["category"])
return unless props["color"] || props["icon"]
extensions = wpt.add_element("extensions")
add_text(extensions, "osmand:color", props["color"])
add_text(extensions, "osmand:icon", props["icon"])
end
private_class_method :write_waypoint
def self.write_line(gpx, feature)
props = feature["properties"] || {}
geometry = feature["geometry"]
segments = case geometry["type"]
when "LineString" then [geometry["coordinates"]]
when "MultiLineString", "Polygon" then geometry["coordinates"]
when "MultiPolygon" then geometry["coordinates"].flatten(1)
else return
end
route = props["kind"] == "route"
element = gpx.add_element(route ? "rte" : "trk")
add_text(element, "name", props["name"])
add_text(element, "desc", props["description"])
add_text(element, "type", props["activity_type"])
if props["color"]
extensions = element.add_element("extensions")
add_text(extensions, "osmand:color", props["color"])
add_text(extensions.add_element("gpx_style:line"), "gpx_style:color", props["color"].delete("#"))
end
if route
segments.flatten(1).each { |c| add_text(element.add_element("rtept", position_attributes(c)), "ele", c[2]) }
else
times = props["times"] if segments.size == 1 # a LineString's: an ISO time per point
segments.each do |segment|
trkseg = element.add_element("trkseg")
segment.each_with_index do |c, i|
trkpt = trkseg.add_element("trkpt", position_attributes(c))
add_text(trkpt, "ele", c[2])
add_text(trkpt, "time", times&.[](i))
end
end
end
end
private_class_method :write_line
def self.position_attributes(coordinates)
{ "lat" => coordinates[1].to_s, "lon" => coordinates[0].to_s }
end
private_class_method :position_attributes
def self.add_text(parent, name, value)
parent.add_element(name).text = value.to_s unless value.nil? || value.to_s.empty?
end
private_class_method :add_text
# <link> is plain GPX 1.1 (a wpt/trk/rte can carry any number of them), # <link> is plain GPX 1.1 (a wpt/trk/rte can carry any number of them),
# not a vendor extension like waypoint_style's <osmand:*> — a newer # not a vendor extension like waypoint_style's <osmand:*> — a newer
# p4n2gpx export started emitting one per park4night listing photo. A # p4n2gpx export started emitting one per park4night listing photo. A
@@ -153,7 +236,7 @@ module Maptool
end end
private_class_method :process_point private_class_method :process_point
# Heart rate/cadence/speed live in a device-specific <extensions> block # Heart rate/cadence/speed/power/temperature live in a device-specific <extensions> block
# (usually Garmin's own TrackPointExtension) — matched by local element # (usually Garmin's own TrackPointExtension) — matched by local element
# name only (`Element#name` already strips the namespace prefix), so # name only (`Element#name` already strips the namespace prefix), so
# this doesn't care which extension schema a given file actually # this doesn't care which extension schema a given file actually
@@ -180,6 +263,8 @@ module Maptool
when "hr" then values[:heart_rate_bpm] = child.text&.strip&.to_i when "hr" then values[:heart_rate_bpm] = child.text&.strip&.to_i
when "cad" then values[:cadence_rpm] = child.text&.strip&.to_i when "cad" then values[:cadence_rpm] = child.text&.strip&.to_i
when "speed" then values[:speed_mps] = child.text&.strip&.to_f when "speed" then values[:speed_mps] = child.text&.strip&.to_f
when "power", "PowerInWatts" then values[:power_w] = child.text&.strip&.to_i
when "atemp", "temp" then values[:temperature_c] = child.text&.strip&.to_f
end end
collect_extension_values(child, values) collect_extension_values(child, values)
end end
+6
View File
@@ -128,6 +128,12 @@ module Maptool
File.read(cache) File.read(cache)
end end
# Drops a file's cached GeoJSON so the next read converts it again
# (Library#reparse, after a parser learned to read more).
def refresh(relative_path)
FileUtils.rm_f(geojson_cache_path(resolve_file(relative_path)))
end
# Appends one GeoJSON Feature (a hand-drawn point/note, see notes.js) to # Appends one GeoJSON Feature (a hand-drawn point/note, see notes.js) to
# the FeatureCollection at `path` — or, if `path` is nil, to a new or # the FeatureCollection at `path` — or, if `path` is nil, to a new or
# existing file named `name` inside `folder`. Deliberately overwrites in # existing file named `name` inside `folder`. Deliberately overwrites in
+42 -9
View File
@@ -37,6 +37,22 @@ module Maptool
class ExtractError < StandardError; end class ExtractError < StandardError; end
ROUTE_TAGS = %w[name description ref colour network operator].freeze ROUTE_TAGS = %w[name description ref colour network operator].freeze
# The OSM route types kept, each as a `kind` the map and the elevation
# profile filter by (an educational trail is a hiking route too, told
# apart below).
KINDS = { "hiking" => "hiking", "foot" => "hiking", "bicycle" => "bicycle", "mtb" => "bicycle", "ski" => "ski" }.freeze
# Bumped when the extract's shape changes, so PmtilesBuilder redoes a
# country's file even though its .osm.pbf hasn't changed.
VERSION = 2
# ponytail: OSM has no single educational-trail tag in practice; the
# name in the languages here, `educational=yes`, or the SK/CZ marking
# (a green diagonal stripe, osmc:symbol "…green_diagonal").
EDUCATIONAL = /náučn|naučn|lehrpfad|themenweg|dydaktycz|edukacyj|przyrodnicz|tanösvény|nature trail|sentiero natura|sendero (de )?interpretaci/i
# Current extract format? (see VERSION; the version is the first key).
def self.current?(path)
File.open(path) { |f| f.read(32) }.to_s.start_with?(%({"version":#{VERSION},))
end
def self.osmium_bin def self.osmium_bin
ENV.fetch("OSMIUM_BIN", "osmium") ENV.fetch("OSMIUM_BIN", "osmium")
@@ -51,7 +67,7 @@ module Maptool
def self.extract(pbf_path) def self.extract(pbf_path)
Dir.mktmpdir("maptool-hiking-trails") do |dir| Dir.mktmpdir("maptool-hiking-trails") do |dir|
filtered = File.join(dir, "hiking.osm.pbf") filtered = File.join(dir, "hiking.osm.pbf")
run!(osmium_bin, "tags-filter", pbf_path, "r/route=hiking", "-o", filtered) run!(osmium_bin, "tags-filter", pbf_path, "r/route=#{KINDS.keys.join(',')}", "-o", filtered)
located = File.join(dir, "hiking-located.osm.pbf") located = File.join(dir, "hiking-located.osm.pbf")
run!(osmium_bin, "add-locations-to-ways", filtered, "-o", located) run!(osmium_bin, "add-locations-to-ways", filtered, "-o", located)
@@ -81,20 +97,26 @@ module Maptool
ways[head[1..].to_i] = way_coordinates(fields) ways[head[1..].to_i] = way_coordinates(fields)
when "r" when "r"
tags = tags_field(fields) tags = tags_field(fields)
relations << { id: head[1..].to_i, tags: tags, members: members_field(fields) } if tags["route"] == "hiking" relations << { id: head[1..].to_i, tags: tags, members: members_field(fields) } if KINDS.key?(tags["route"])
end end
end end
features = relations.filter_map { |relation| relation_feature(relation, ways) } features = relations.filter_map { |relation| relation_feature(relation, ways) }
{ "type" => "FeatureCollection", "features" => features } { "version" => VERSION, "type" => "FeatureCollection", "features" => features }
end end
def self.relation_feature(relation, ways) def self.relation_feature(relation, ways)
lines = relation[:members] # A "forward"/"backward" member is walked one way only, along / against
.select { |member| member[:type] == "w" } # the way's own direction; reversed here so every line runs the way
.filter_map { |member| ways[member[:id]] } # it's walked, and listed in oneway_lines (indexes into the lines).
.select { |coords| coords.size >= 2 } members = relation[:members]
return nil if lines.empty? .select { |member| member[:type] == "w" }
.filter_map { |member| (coords = ways[member[:id]]) && [coords, member[:role]] }
.select { |coords, _| coords.size >= 2 }
return nil if members.empty?
lines = members.map { |coords, role| role == "backward" ? coords.reverse : coords }
oneway = members.each_index.select { |i| %w[forward backward].include?(members[i][1]) }
distance = lines.sum { |coords| TrackStats.compute(coords)["distance_meters"] } distance = lines.sum { |coords| TrackStats.compute(coords)["distance_meters"] }
tags = relation[:tags] tags = relation[:tags]
@@ -102,6 +124,8 @@ module Maptool
"id" => relation[:id], "id" => relation[:id],
"name" => tags["name"] || tags["description"], "name" => tags["name"] || tags["description"],
"distance_meters" => distance.round(1), "distance_meters" => distance.round(1),
"oneway_lines" => oneway.empty? ? nil : oneway,
"kind" => kind(tags),
} }
ROUTE_TAGS.each { |key| properties[key] ||= tags[key] } ROUTE_TAGS.each { |key| properties[key] ||= tags[key] }
@@ -117,6 +141,14 @@ module Maptool
end end
private_class_method :relation_feature private_class_method :relation_feature
def self.kind(tags)
kind = KINDS.fetch(tags["route"], "hiking")
educational = tags["educational"] == "yes" || tags["osmc:symbol"].to_s.include?("green_diagonal") ||
[tags["name"], tags["description"]].any? { |t| t.to_s.match?(EDUCATIONAL) }
kind == "hiking" && educational ? "educational" : kind
end
private_class_method :kind
def self.round_coordinates(lines) def self.round_coordinates(lines)
lines.map { |coords| coords.map { |lon, lat| [lon.round(5), lat.round(5)] } } lines.map { |coords| coords.map { |lon, lat| [lon.round(5), lat.round(5)] } }
end end
@@ -140,7 +172,8 @@ module Maptool
return [] if raw.empty? return [] if raw.empty?
raw.split(",").map do |member| raw.split(",").map do |member|
{ type: member[0], id: member[1..].split("@", 2).first.to_i } id, role = member[1..].split("@", 2)
{ type: member[0], id: id.to_i, role: unescape(role.to_s) }
end end
end end
private_class_method :members_field private_class_method :members_field
+153
View File
@@ -0,0 +1,153 @@
require_relative "can"
module Maptool
# Keypads as inputs, the way PDMs do it (docs/design.adoc, "Switches and
# the keypad: how others do it"): a device's keys and knobs become named
# channels — "pad.K1", "pad.E3" — and the screen profile binds a channel
# to a function ("bindings" in public/drive/road.json); nothing here knows
# what a key does. A device is any signals off the bus; a Blink Marine PKP
# (ours speak its protocol too, home-gitops docs/canopen-nodes.adoc) also
# brings its keys without signals and takes LED colours back.
#
# can.json: "keypads": [
# { "name": "pad", "protocol": "pkp", "node": 20, "keys": 8, "heartbeat_node": 32,
# "inputs": { "E1": "mcu-stm32-xiao-c5.encoder_1", "E1 press": "mcu-stm32-xiao-c5.encoder_button_1" } },
# { "name": "wheel", "heartbeat_node": 40, "inputs": { "K1": "wheel.Button 1" } } ]
# name the channels' prefix
# protocol "pkp": K1…K<keys> from its TPDO1 (0x180+node, a bit each), LEDs by RPDO
# heartbeat_node whose heartbeat says it's there (a real PKP has it off) — default node
# inputs channel → any signal (can.json's or a discovered node's, as /can.html
# names them): a key (0 → 1 is a press), a knob (a free-turning
# counter mod 256, a step per change) when its name starts with E,
# its button "<knob> press"
class Keypad
COLORS = { "off" => 0, "red" => 1, "green" => 2, "blue" => 4, "yellow" => 3, "cyan" => 6, "magenta" => 5, "white" => 7 }.freeze
PRESENT_S = 6 # heartbeat seen this recently (5 s interval): there
LOG_SIZE = 200
# One device: its channels by signal name, its LEDs if it has them.
Device = Struct.new(:name, :protocol, :node, :keys, :heartbeat_node, :inputs) do
def self.parse(config)
protocol = config["protocol"]
raise ArgumentError, "unknown protocol #{protocol}" unless [nil, "pkp"].include?(protocol)
node = config["node"] && Integer(config["node"])
raise ArgumentError, "a pkp keypad needs its node" if protocol == "pkp" && !node
new(config.fetch("name"), protocol, node, config.fetch("keys", 8), config["heartbeat_node"] ? Integer(config["heartbeat_node"]) : node,
config.fetch("inputs", {}))
end
# The PKP's keys as decoder signals (Decoder#set_node).
def signals
return [] unless protocol == "pkp"
(1..keys).map { |k| { "name" => "#{name}.K#{k}", "id" => format("0x%03X", 0x180 + node), "byte" => (k - 1) / 8, "bit" => (k - 1) % 8, "type" => "bit" } }
end
# signal name → channel
def channels
@channels ||= signals.to_h { |s| [s["name"], s["name"]] }.merge(inputs.to_h { |channel, signal| [signal, "#{name}.#{channel}"] })
end
end
attr_reader :devices
def initialize(configs)
@devices = configs.map { |c| Device.parse(c) }
@by_signal = @devices.flat_map { |d| d.channels.to_a }.to_h
@mutex = Mutex.new
@changed = ConditionVariable.new
@log = []
@seq = 0
@last = {}
end
def signals = @devices.flat_map(&:signals)
def device(name) = @devices.find { |d| d.name == name }
# Decoded values → events on channels (returned too): a key or a knob's
# button pressed (0 → 1) and let go ("… up"), a knob turned (a step
# each, "⟳" or "⟲", wrapping at 256).
def update(values)
events = []
values.each do |signal, value|
next unless (channel = @by_signal[signal])
previous = @last[channel]
@last[channel] = value
if channel.split(".").last.match?(/\AE\d+\z/)
next if previous.nil? # a knob's first value: where it is, no turn
delta = ((value.to_i - previous.to_i + 128) % 256) - 128
events.concat(["#{channel} #{delta.positive? ? '⟳' : '⟲'}"] * delta.abs)
elsif value.to_i == 1 && previous.to_i != 1
events << channel
elsif value.to_i != 1 && previous.to_i == 1
events << "#{channel} up" # let go (the outputs' Hold)
end
end
return events if events.empty?
@mutex.synchronize do
events.each { |input| @log << { seq: @seq += 1, input: input } }
@log.shift(@log.size - LOG_SIZE) if @log.size > LOG_SIZE
@changed.broadcast
end
events
end
# The events after seq `since`, waiting up to `wait` s for one (a long
# poll); since nil: none, just the last seq to start from.
def events(since, wait: 10)
@mutex.synchronize do
if since
deadline = Time.now + wait
while @seq <= since && (left = deadline - Time.now).positive?
@changed.wait(@mutex, left)
end
end
{ seq: @seq, events: since ? @log.select { |e| e[:seq] > since } : [] }
end
end
# A PKP's two LED frames (RPDO 0x200+node on, 0x300+node blink: bytes
# R, G, B, a bit per key) from { "K1" => "cyan", … } (nil, absent: off);
# on and blink both set alternate between the two colours.
def led_frames(name, on, blink = {})
d = device(name)
raise ArgumentError, "no keypad #{name}" unless d
raise ArgumentError, "#{name} has no LEDs" unless d.protocol == "pkp"
[[0x200, on], [0x300, blink]].map do |base, colors|
masks = [0, 0, 0]
(colors || {}).each do |channel, color|
k = channel[/\AK(\d+)\z/, 1]&.to_i
next unless k&.between?(1, d.keys)
rgb = COLORS.fetch(color.to_s.empty? ? "off" : color.to_s) { raise ArgumentError, "unknown colour #{color}" }
3.times { |c| masks[c] |= 1 << (k - 1) if rgb[c] == 1 }
end
bytes = (d.keys + 7) / 8
Can::Frame.new(base + d.node, masks.flat_map { |m| [m].pack("Q<").bytes.first(bytes) }.pack("C*"), false)
end
end
end
end
if $PROGRAM_NAME == __FILE__
pads = Maptool::Keypad.new([{ "name" => "pad", "protocol" => "pkp", "node" => 0x14, "inputs" => { "E3" => "x.Encoder 3", "E3 press" => "x.Button 3" } }])
pads.update("pad.K1" => 1)
pads.update("pad.K1" => 1) # held: no second press
pads.update("x.Encoder 3" => 250)
pads.update("x.Encoder 3" => 2) # +8 across the wrap
pads.update("x.Button 3" => 1)
pads.update("pad.K1" => 0)
inputs = pads.events(0)[:events].map { |e| e[:input] }
raise inputs.inspect unless inputs == ["pad.K1"] + ["pad.E3 ⟳"] * 8 + ["pad.E3 press", "pad.K1 up"]
on, blink = pads.led_frames("pad", { "K1" => "cyan", "K2" => "white", "K3" => "yellow" }, { "K2" => "red" })
raise on.data.unpack("C*").inspect unless on.id == 0x214 && on.data.unpack("C*") == [0b110, 0b111, 0b011]
raise blink.data.unpack("C*").inspect unless blink.id == 0x314 && blink.data.unpack("C*") == [0b10, 0, 0]
puts "ok"
end
+28 -6
View File
@@ -81,6 +81,23 @@ module Maptool
{ "type" => "FeatureCollection", "features" => features } { "type" => "FeatureCollection", "features" => features }
end end
# Full-text search of the ZIM for the search box (Search's "kiwix"
# source): [{ title:, link:, position: [lng, lat] or nil }]. position
# comes from each article's own page, same as .nearby above — hence a
# small default limit; an article with no coordinates is still a
# result, it just opens without a place on the map to jump to.
def self.search(base_url, text, limit: 10, open_timeout: 2, read_timeout: 10)
return [] if base_url.to_s.strip.empty? || text.to_s.strip.empty?
query = URI.encode_www_form(pattern: text, pageLength: limit, format: "xml")
response = proxy(base_url, "/kiwix/search", query, open_timeout: open_timeout, read_timeout: read_timeout)
return [] unless response&.code == "200"
parse_search_results(response.body).map do |result|
result.merge(position: position(base_url, result[:link], open_timeout, read_timeout))
end
end
def self.empty_collection def self.empty_collection
{ "type" => "FeatureCollection", "features" => [] } { "type" => "FeatureCollection", "features" => [] }
end end
@@ -104,20 +121,25 @@ module Maptool
# already-*decoded* splat, see its own comment above) doesn't double- # already-*decoded* splat, see its own comment above) doesn't double-
# encode the "%" and 404 the request. # encode the "%" and 404 the request.
def self.point_feature(base_url, result, open_timeout, read_timeout) def self.point_feature(base_url, result, open_timeout, read_timeout)
response = proxy(base_url, URI::RFC2396_PARSER.unescape(result[:link]), nil, open_timeout: open_timeout, read_timeout: read_timeout) coordinates = position(base_url, result[:link], open_timeout, read_timeout)
return nil unless response&.code == "200" return nil unless coordinates
match = response.body.match(GEO_POSITION_PATTERN)
return nil unless match
{ {
"type" => "Feature", "type" => "Feature",
"properties" => { "name" => result[:title], "link" => result[:link] }, "properties" => { "name" => result[:title], "link" => result[:link] },
"geometry" => { "type" => "Point", "coordinates" => [match[2].to_f, match[1].to_f] }, "geometry" => { "type" => "Point", "coordinates" => coordinates },
} }
end end
private_class_method :point_feature private_class_method :point_feature
# [lng, lat] from the article page's geo.position meta tag, or nil.
def self.position(base_url, link, open_timeout, read_timeout)
response = proxy(base_url, URI::RFC2396_PARSER.unescape(link), nil, open_timeout: open_timeout, read_timeout: read_timeout)
match = response&.code == "200" && response.body.match(GEO_POSITION_PATTERN)
match ? [match[2].to_f, match[1].to_f] : nil
end
private_class_method :position
def self.haversine_km(lat1, lng1, lat2, lng2) def self.haversine_km(lat1, lng1, lat2, lng2)
earth_radius_km = 6371.0 earth_radius_km = 6371.0
dlat = (lat2 - lat1) * Math::PI / 180 dlat = (lat2 - lat1) * Math::PI / 180
+815
View File
@@ -0,0 +1,815 @@
require "digest"
require "fileutils"
require "json"
require "securerandom"
require "sqlite3"
require "time"
require_relative "gpx"
require_relative "fit"
require_relative "tcx"
require_relative "fit_course"
require_relative "gpx_store"
module Maptool
# Tracks & Points as items in a folder tree (docs/library-design.adoc,
# phase 1): data/library.sqlite holds folders and items, each with a
# stable id, timestamps, a tombstone on delete and the global change
# counter (`rev`) a sync client will poll.
#
# Item types: point, track, route, shape (polygon / measured line note)
# and layer — a pre-library file from GpxStore (data/gpx/), migrated as a
# whole into a subfolder named after it and still drawn from that file.
# Points carry parent_id when they came in the same GPX as a single
# track (OsmAnd keeps those inside the track, Locus loose in the folder;
# this keeps both possible on export).
#
# The tree UI deals in "nodes", one checkbox each: every track/route/
# layer is one ("item:<id>", drawn with its child points), and a
# folder's loose points and shapes together are another
# ("points:<folder id>").
class Library
class NotFound < StandardError; end
class InvalidPath < StandardError; end
class ParseError < StandardError; end
class InvalidValue < StandardError; end
ROOT = "root" # folder id in a node key for items with no folder
EXTENSIONS = %w[.gpx .fit .tcx .geojson].freeze
# Bumped when a parser starts reading more (power, temperature, ...):
# tracks imported before get their profile re-read once (reparse).
PARSER_VERSION = 3
def initialize(db_path, gpx_store:, sources_dir:)
@path = db_path
@gpx_store = gpx_store
@sources_dir = sources_dir
fresh = !File.exist?(db_path)
FileUtils.mkdir_p(File.dirname(db_path))
connect do |db|
db.execute("PRAGMA journal_mode = WAL")
db.execute_batch(<<~SQL)
CREATE TABLE IF NOT EXISTS meta (rev INTEGER NOT NULL);
INSERT INTO meta (rev) SELECT 0 WHERE NOT EXISTS (SELECT 1 FROM meta);
CREATE TABLE IF NOT EXISTS folders (
id TEXT PRIMARY KEY, parent_id TEXT, name TEXT NOT NULL,
created_at TEXT NOT NULL, updated_at TEXT NOT NULL, deleted_at TEXT, rev INTEGER NOT NULL
);
CREATE TABLE IF NOT EXISTS items (
id TEXT PRIMARY KEY, folder_id TEXT, parent_id TEXT, type TEXT NOT NULL, name TEXT,
geometry TEXT, properties TEXT NOT NULL DEFAULT '{}', fingerprint TEXT, source_path TEXT,
created_at TEXT NOT NULL, updated_at TEXT NOT NULL, deleted_at TEXT, rev INTEGER NOT NULL
);
CREATE INDEX IF NOT EXISTS items_folder ON items(folder_id);
CREATE INDEX IF NOT EXISTS items_parent ON items(parent_id);
CREATE INDEX IF NOT EXISTS items_rev ON items(rev);
CREATE INDEX IF NOT EXISTS items_fingerprint ON items(folder_id, fingerprint);
CREATE INDEX IF NOT EXISTS folders_rev ON folders(rev);
SQL
db.execute("ALTER TABLE meta ADD COLUMN parser INTEGER NOT NULL DEFAULT 0") unless db.execute("PRAGMA table_info(meta)").any? { |c| c[1] == "parser" }
end
migrate if fresh
end
# Re-reads every imported track's/route's profile from its source file
# (and drops migrated layers' cached GeoJSON) when PARSER_VERSION went
# up; name, color and the rest stay. Returns how many were updated.
def reparse
return 0 if connect { |db| db.get_first_value("SELECT parser FROM meta") } >= PARSER_VERSION
rows = connect { |db| db.execute("SELECT id, type, name, geometry, properties, source_path FROM items WHERE deleted_at IS NULL AND source_path IS NOT NULL AND type IN ('track', 'route', 'layer')") }
updated = 0
rows.each do |id, type, name, geometry, props, source|
if type == "layer"
@gpx_store.refresh(source)
next
end
path = File.join(@sources_dir, source)
next if !File.file?(path) || path.downcase.end_with?(".geojson")
geometry = round(JSON.parse(geometry))
feature = parse(path).find { |f| item_type(f) == type && round(f["geometry"]) == geometry }
next unless feature&.dig("properties", "profile")
name = default_name(source) if name.to_s.empty?
props = JSON.parse(props).merge(feature["properties"].slice("profile", "laps"))
props["name"] = name if props["name"].to_s.empty?
write do |db, rev, now|
db.execute("UPDATE items SET name = ?, properties = ?, updated_at = ?, rev = ? WHERE id = ?",
[name, JSON.generate(props), now, rev, id])
end
updated += 1
rescue Gpx::ParseError, Fit::ParseError, Errno::ENOENT, JSON::ParserError, GpxStore::InvalidPath
next
end
connect { |db| db.execute("UPDATE meta SET parser = ?", [PARSER_VERSION]) }
updated
end
def rev
connect { |db| db.get_first_value("SELECT rev FROM meta") }
end
# GpxStore's tree → folders, each file → a subfolder named after it
# holding one layer item. Idempotent (a file already migrated, even if
# deleted since, is skipped); data/gpx/ itself is never touched.
def migrate
walk = lambda do |node, folder|
node["children"].each do |child|
if child["type"] == "folder"
walk.call(child, child["path"])
else
add_layer(child, [folder, File.basename(child["name"], ".*")].reject(&:empty?).join("/"))
end
end
create_folder(folder) unless folder.empty?
end
walk.call(@gpx_store.tree, "")
end
# --- tree ---------------------------------------------------------------
def tree
folders, items = connect do |db|
[db.execute("SELECT id, parent_id, name FROM folders WHERE deleted_at IS NULL ORDER BY name COLLATE NOCASE"),
db.execute(<<~SQL)]
SELECT id, folder_id, parent_id, type, name, source_path,
CASE WHEN type IN ('layer', 'track', 'route') THEN properties END,
CASE WHEN parent_id IS NOT NULL THEN geometry END
FROM items WHERE deleted_at IS NULL ORDER BY name COLLATE NOCASE
SQL
end
children_of = folders.group_by { |f| f[1] }
items_in = items.group_by { |i| i[1] }
children = items.select { |i| i[2] && i[3] == "point" }.group_by { |i| i[2] }
build = lambda do |id, path|
subfolders = (children_of[id] || []).map do |fid, _, name|
sub = path.empty? ? name : "#{path}/#{name}"
{ "type" => "folder", "id" => fid, "name" => name, "path" => sub, "children" => build.call(fid, sub) }
end
own = items_in[id] || []
nodes = own.select { |i| %w[track route layer].include?(i[3]) }.map do |iid, _, _, type, name, source, props|
props = JSON.parse(props)
points = (children[iid] || []).map { |pid, *, pname, _, _, geometry| { "id" => pid, "name" => pname.to_s.empty? ? "Point" : pname, "coordinates" => JSON.parse(geometry)["coordinates"] } }
kinds = type == "layer" ? props["kinds"] || [] : [type, *("waypoint" if points.any?)]
{ "type" => "file", "path" => "item:#{iid}", "name" => name.to_s.empty? ? type.capitalize : name,
"kinds" => kinds, "original" => !source.nil?, "layer" => type == "layer", "color" => props["color"],
"points" => (points if points.any?) }.compact
end
loose = own.count { |i| %w[point shape].include?(i[3]) && i[2].nil? }
if loose.positive?
nodes << { "type" => "file", "path" => "points:#{id || ROOT}", "name" => "Points (#{loose})",
"kinds" => ["waypoint"], "original" => false }
end
subfolders + nodes
end
{ "type" => "folder", "name" => "root", "path" => "", "children" => build.call(nil, "") }
end
# Every node as [label, key, stamp, reader] — Search's "layers" source.
# ponytail: stamp is the global rev, so any write re-reads every node on
# the next search; per-node revs if that ever gets slow.
def nodes
current = rev
flatten = lambda do |node, folder|
node["children"].flat_map do |child|
next flatten.call(child, child["path"]) if child["type"] == "folder"
[[[folder, child["name"]].reject(&:empty?).join(" / "), child["path"], current, -> { geojson(child["path"]) }]]
end
end
flatten.call(tree, "")
end
# A node's FeatureCollection as a JSON string, every feature's
# properties carrying its item id.
def geojson(key)
kind, id = key.to_s.split(":", 2)
rows = connect do |db|
case kind
when "item"
item = db.get_first_row("SELECT type, source_path, properties FROM items WHERE id = ? AND deleted_at IS NULL", [id])
raise NotFound unless item
return layer_geojson(item[1], JSON.parse(item[2])["color"]) if item[0] == "layer"
db.execute("#{FEATURE_SQL} AND (id = ? OR parent_id = ?) ORDER BY parent_id IS NOT NULL", [id, id])
when "points"
db.execute("#{FEATURE_SQL} AND folder_id IS ? AND parent_id IS NULL AND type IN ('point', 'shape')", [folder_param(id)])
else raise NotFound
end
end
JSON.generate("type" => "FeatureCollection", "features" => rows.map { |row| feature(*row) })
end
# The file a node came from, for "download original": the legacy file
# or the stored upload. nil when there is none (a folder's points).
def original(key)
kind, id = key.to_s.split(":", 2)
return nil unless kind == "item"
type, source = connect { |db| db.get_first_row("SELECT type, source_path FROM items WHERE id = ? AND deleted_at IS NULL", [id]) }
return nil unless source
source_file(type, source)
end
# --- writes -------------------------------------------------------------
# Stores the upload under sources/<uuid>/ and adds its features as
# items in `folder` (a "a/b" path, created if needed). Returns the node
# keys they show up under. A feature already in that folder (same
# fingerprint) isn't added twice — re-sharing a track from OsmAnd is a
# no-op — but its node is still returned.
def import(folder:, filename:, io:)
name = safe_filename(filename)
relative = File.join(SecureRandom.uuid, name)
path = File.join(@sources_dir, relative)
FileUtils.mkdir_p(File.dirname(path))
File.binwrite(path, io.read)
features = begin
parse(path)
rescue Gpx::ParseError, Fit::ParseError, JSON::ParserError => e
FileUtils.rm_rf(File.dirname(path))
raise ParseError, e.message
end
add_features(features, folder, source: relative)
end
# Already-parsed features (GoogleSaved) into `folder`, same rules as an
# upload minus the stored source file.
def import_features(features, folder:)
add_features(features, folder)
end
# FIT (and many TCX/GPX) tracks carry no name of their own: those take
# the file's, so the tree doesn't fill up with "Track".
def default_name(source)
File.basename(source, ".*")
end
# A point into a track/route (`key` "item:<id>"), kept with it like a
# GPX's own waypoints: shown, moved, deleted and exported together.
def add_point(key, feature)
kind, id = key.to_s.split(":", 2)
raise NotFound unless kind == "item"
raise InvalidValue unless feature.dig("geometry", "type") == "Point"
props = (feature["properties"] || {}).except("id").compact
write do |db, rev, now|
folder = db.get_first_row("SELECT folder_id FROM items WHERE id = ? AND type IN ('track', 'route') AND deleted_at IS NULL", [id]) or raise NotFound
point = SecureRandom.uuid
db.execute("INSERT INTO items VALUES (?, ?, ?, 'point', ?, ?, ?, ?, NULL, ?, ?, NULL, ?)",
[point, folder[0], id, props["name"], JSON.generate(feature["geometry"]), JSON.generate(props), point, now, now, rev])
point
end
end
# One hand-drawn note (notes.js) into `folder`; returns its node key.
def add_note(feature, folder)
add_features([feature], folder).first
end
# Rename and/or recolor a track, route or layer (nil leaves it as is,
# an empty color goes back to the default).
def update_node(key, name: nil, color: nil)
kind, id = key.to_s.split(":", 2)
raise NotFound unless kind == "item"
raise InvalidValue if color && !color.empty? && !color.match?(/\A#\h{6}\z/)
raise InvalidValue if name && name.strip.empty?
write do |db, rev, now|
row = db.get_first_row("SELECT name, properties FROM items WHERE id = ? AND type IN ('track', 'route', 'layer') AND deleted_at IS NULL", [id])
raise NotFound unless row
props = JSON.parse(row[1])
props = color.empty? ? props.except("color") : props.merge("color" => color) if color
db.execute("UPDATE items SET name = ?, properties = ?, updated_at = ?, rev = ? WHERE id = ?",
[name ? name.strip : row[0], JSON.generate(props), now, rev, id])
end
end
# A migrated layer → ordinary items in its folder (its notes included,
# keeping their ids), the legacy file copied as their original. The
# layer is tombstoned; data/gpx/ itself stays untouched.
def split_layer(key)
kind, id = key.to_s.split(":", 2)
row = connect { |db| db.get_first_row("SELECT folder_id, source_path, properties FROM items WHERE id = ? AND type = 'layer' AND deleted_at IS NULL", [id]) }
raise NotFound unless kind == "item" && row
folder, legacy, props = row
features = begin
JSON.parse(layer_geojson(legacy, JSON.parse(props)["color"]))["features"]
rescue Gpx::ParseError, Fit::ParseError, JSON::ParserError => e
raise ParseError, e.message
end
relative = File.join(SecureRandom.uuid, File.basename(legacy))
FileUtils.mkdir_p(File.join(@sources_dir, File.dirname(relative)))
FileUtils.cp(@gpx_store.resolve_file(legacy), File.join(@sources_dir, relative))
keys = add_features(features, folder, source: relative, by_id: true)
write { |db, rev, now| tombstone(db, "id = ?", [id], rev, now) }
keys
end
# Edit/delete one feature of a node (a note's popup). A layer's notes
# still live in its legacy .geojson file, so those go to GpxStore.
def update_feature(key, id, feature)
if (source = layer_source(key))
return @gpx_store.update_feature(path: source, id: id, feature: feature)
end
props = (feature["properties"] || {}).except("id")
write do |db, rev, now|
# Moved by hand: an imported approximate position (GoogleSaved) is checked now.
old, old_props = db.get_first_row("SELECT geometry, properties FROM items WHERE id = ?", [id])
props.delete("approximate") if old && round(JSON.parse(old)) != round(feature["geometry"])
# What the last import said stays, whatever the popup sent back
# (upsert_by_source_id tells a hand edit from it).
imported = old_props && JSON.parse(old_props)["imported"]
props["imported"] = imported if imported
db.execute("UPDATE items SET name = ?, geometry = ?, properties = ?, updated_at = ?, rev = ? WHERE id = ? AND deleted_at IS NULL",
[props["name"], JSON.generate(feature["geometry"]), JSON.generate(props), now, rev, id])
raise NotFound if db.changes.zero?
end
end
def delete_feature(key, id)
if (source = layer_source(key))
return @gpx_store.delete_feature(path: source, id: id)
end
write do |db, rev, now|
tombstone(db, "id = ? OR parent_id = ?", [id, id], rev, now)
raise NotFound if db.changes.zero?
end
end
# A whole node: a track with its points, a layer, or a folder's loose points.
def delete_node(key)
kind, id = key.to_s.split(":", 2)
write do |db, rev, now|
case kind
when "item" then tombstone(db, "id = ? OR parent_id = ?", [id, id], rev, now)
when "points" then tombstone(db, "folder_id IS ? AND parent_id IS NULL AND type IN ('point', 'shape')", [folder_param(id)], rev, now)
else raise NotFound
end
raise NotFound if db.changes.zero?
end
end
# Returns the node's key afterwards (a folder's points get a new one).
def move_node(key, to_folder)
kind, id = key.to_s.split(":", 2)
target = folder_id(to_folder, create: true)
write do |db, rev, now|
case kind
when "item"
db.execute("UPDATE items SET folder_id = ?, updated_at = ?, rev = ? WHERE (id = ? OR parent_id = ?) AND deleted_at IS NULL",
[target, now, rev, id, id])
when "points"
db.execute(<<~SQL, [target, now, rev, folder_param(id)])
UPDATE items SET folder_id = ?, updated_at = ?, rev = ?
WHERE folder_id IS ? AND parent_id IS NULL AND type IN ('point', 'shape') AND deleted_at IS NULL
SQL
end
raise NotFound if db.changes.zero?
end
kind == "points" ? "points:#{target || ROOT}" : key
end
def create_folder(path)
raise InvalidPath if path.to_s.strip.empty?
folder_id(path, create: true)
end
# Tombstones the folder, everything under it and all their items.
def delete_folder(path)
id = folder_id(path, create: false)
raise NotFound unless id
write do |db, rev, now|
ids = [id]
frontier = [id]
until frontier.empty?
frontier = db.execute("SELECT id FROM folders WHERE parent_id IN (#{(['?'] * frontier.size).join(',')}) AND deleted_at IS NULL", frontier).flatten
ids.concat(frontier)
end
marks = (["?"] * ids.size).join(",")
db.execute("UPDATE folders SET deleted_at = ?, updated_at = ?, rev = ? WHERE id IN (#{marks})", [now, now, rev, *ids])
tombstone(db, "folder_id IN (#{marks})", ids, rev, now)
end
end
# Returns the folder's new path.
def rename_folder(path, name)
name = name.to_s.strip
raise InvalidPath if name.empty? || name.include?("/") || %w[. ..].include?(name)
id = folder_id(path, create: false) or raise NotFound
write do |db, rev, now|
parent = db.get_first_value("SELECT parent_id FROM folders WHERE id = ?", [id])
raise InvalidValue if sibling?(db, parent, name, id)
db.execute("UPDATE folders SET name = ?, updated_at = ?, rev = ? WHERE id = ?", [name, now, rev, id])
end
[*path.split("/")[0...-1], name].join("/")
end
# Into `to_folder` ("" = top level); returns the folder's new path.
def move_folder(path, to_folder)
id = folder_id(path, create: false) or raise NotFound
target = folder_id(to_folder, create: true)
write do |db, rev, now|
ancestor = target
while ancestor
raise InvalidPath if ancestor == id # into itself or its own subfolder
ancestor = db.get_first_value("SELECT parent_id FROM folders WHERE id = ?", [ancestor])
end
name = db.get_first_value("SELECT name FROM folders WHERE id = ?", [id])
raise InvalidValue if sibling?(db, target, name, id)
db.execute("UPDATE folders SET parent_id = ?, updated_at = ?, rev = ? WHERE id = ?", [target, now, rev, id])
end
[*to_folder.to_s.split("/").map(&:strip).reject(&:empty?), path.split("/").last].join("/")
end
# --- sync / export ------------------------------------------------------
# Everything written after `since` (tombstones included) and the
# current rev: the feed a sync client polls (docs/library-design.adoc).
# A layer has no geometry of its own here (it's a legacy file).
def changes(since)
since = Integer(since || 0)
connect do |db|
db.transaction do
folders = db.execute("SELECT id, parent_id, name, updated_at, deleted_at, rev FROM folders WHERE rev > ? ORDER BY rev", [since])
items = db.execute("SELECT id, folder_id, parent_id, type, name, geometry, properties, updated_at, deleted_at, rev FROM items WHERE rev > ? ORDER BY rev", [since])
{ "rev" => db.get_first_value("SELECT rev FROM meta"),
"folders" => folders.map { |id, parent, name, updated, deleted, rev| { "id" => id, "parent_id" => parent, "name" => name, "updated_at" => updated, "deleted" => !deleted.nil?, "rev" => rev } },
"items" => items.map do |id, folder, parent, type, name, geometry, props, updated, deleted, rev|
{ "id" => id, "folder_id" => folder, "parent_id" => parent, "type" => type, "name" => name,
"geometry" => geometry && JSON.parse(geometry), "properties" => JSON.parse(props),
"updated_at" => updated, "deleted" => !deleted.nil?, "rev" => rev }
end }
end
end
rescue ArgumentError, TypeError
raise InvalidValue
end
# --- server ⇄ server sync (home ⇄ car) -----------------------------------
SYNC_FOLDER_COLUMNS = %w[id parent_id name created_at updated_at deleted_at].freeze
SYNC_ITEM_COLUMNS = %w[id folder_id parent_id type name geometry properties fingerprint source_path created_at updated_at deleted_at].freeze
# Whole rows written after `since`, tombstones included, at most `limit`
# of each table; "next" is the rev to ask from next time (below "rev"
# while there's more).
def sync_changes(since, limit: 500)
since = Integer(since)
connect do |db|
db.transaction do
rev = db.get_first_value("SELECT rev FROM meta")
tables = { "folders" => SYNC_FOLDER_COLUMNS, "items" => SYNC_ITEM_COLUMNS }.to_h do |table, columns|
rows = db.execute("SELECT #{columns.join(', ')}, rev FROM #{table} WHERE rev > ? ORDER BY rev LIMIT ?", [since, limit])
[table, rows.map { |row| (columns + ["rev"]).zip(row).to_h }]
end
full = tables.values.select { |rows| rows.size == limit }.map { |rows| rows.last["rev"] - 1 }
tables.merge("rev" => rev, "next" => [rev, *full].min)
end
end
end
# Takes the other server's rows (sync_changes): one newer than ours —
# or not here yet — replaces ours, else ours stays (last writer wins by
# updated_at; an echo of our own change ties and is skipped). Returns
# the source files (items' source_path) not here yet.
# ponytail: the losing version isn't kept; a history table if a lost
# edit ever matters.
def apply_sync(changes)
missing = []
write do |db, rev, _now|
{ "folders" => SYNC_FOLDER_COLUMNS, "items" => SYNC_ITEM_COLUMNS }.each do |table, columns|
(changes[table] || []).each do |row|
ours = db.get_first_value("SELECT updated_at FROM #{table} WHERE id = ?", [row["id"]])
next if ours && ours >= row["updated_at"].to_s
db.execute("INSERT OR REPLACE INTO #{table} (#{columns.join(', ')}, rev) VALUES (#{(['?'] * (columns.size + 1)).join(', ')})",
[*row.values_at(*columns), rev])
missing << row if table == "items" && row["source_path"] && !row["deleted_at"] && !File.exist?(source_file(row["type"], row["source_path"]))
end
end
end
missing
end
# Where an item's source file lives: a legacy layer's in GpxStore,
# an upload's under sources/.
# The path comes from the other server too: never outside sources/.
def source_file(type, source_path)
return @gpx_store.resolve_file(source_path) if type == "layer"
root = File.expand_path(@sources_dir)
path = File.expand_path(File.join(root, source_path.to_s))
raise InvalidValue unless path.start_with?("#{root}/")
path
end
# An item's source file (tombstoned or not: the other server may still
# need it), nil without one.
def item_source(id)
type, source = connect { |db| db.get_first_row("SELECT type, source_path FROM items WHERE id = ?", [id]) }
source && source_file(type, source)
end
# An item's type and source_path (where its file belongs), nil without one.
def source_row(id)
type, source = connect { |db| db.get_first_row("SELECT type, source_path FROM items WHERE id = ?", [id]) }
source && { "type" => type, "source_path" => source }
end
# The other server's copy of a source file, written into place.
def store_source(item, bytes)
path = source_file(item["type"], item["source_path"])
FileUtils.mkdir_p(File.dirname(path))
File.binwrite("#{path}.part", bytes)
File.rename("#{path}.part", path)
end
# A folder's own items (not its subfolders') as one GPX with points and
# tracks together — what Locus imports into one folder.
# A folder's own features (not its subfolders').
def folder_features(path)
export_entries(path).map { |e| e[:feature] }
end
def export_gpx(path)
Gpx.from_features(export_entries(path).map { |e| e[:feature] })
end
# The same folder the way OsmAnd keeps things: { filename => GPX }.
# Loose points → favourites.gpx in a group named after the folder path
# (names made unique, OsmAnd needs that per group); each track, route
# or layer → its own tracks/<name>.gpx with its own points.
def export_osmand(path)
group = path.to_s.split("/").reject(&:empty?).join(" / ")
group = "MapTool" if group.empty?
files = export_entries(path).group_by { |e| e[:file] }
favourites = (files.delete(nil) || []).map { |e| e[:feature] }
seen = Hash.new(0)
favourites = favourites.map do |f|
name = f["properties"]["name"].to_s.empty? ? "Point" : f["properties"]["name"]
seen[name] += 1
f.merge("properties" => f["properties"].merge("name" => seen[name] > 1 ? "#{name} (#{seen[name]})" : name))
end
out = {}
out["favourites.gpx"] = Gpx.from_features(favourites, group: group) if favourites.any?
dir = ["tracks", *group.split(" / ").map { |part| safe_name(part) }].join("/")
names = Hash.new(0)
files.each_value do |entries|
base = safe_name(File.basename(entries.first[:file_name].to_s, ".*"))
names[base] += 1
out["#{dir}/#{names[base] > 1 ? "#{base} (#{names[base]})" : base}.gpx"] = Gpx.from_features(entries.map { |e| e[:feature] })
end
out
end
# "a/b" → folder id (nil for the top level), created along the way if
# `create`; nil when it doesn't exist and isn't created.
def folder_id(path, create:)
parts = path.to_s.split("/").map(&:strip).reject(&:empty?)
raise InvalidPath if parts.any? { |part| %w[. ..].include?(part) }
parts.reduce(nil) do |parent, name|
found = connect { |db| db.get_first_value("SELECT id FROM folders WHERE parent_id IS ? AND name = ? AND deleted_at IS NULL", [parent, name]) }
next found if found
return nil unless create
id = SecureRandom.uuid
write do |db, rev, now|
db.execute("INSERT INTO folders VALUES (?, ?, ?, ?, ?, NULL, ?)", [id, parent, name, now, now, rev])
end
id
end
end
private
FEATURE_SQL = "SELECT id, name, geometry, properties FROM items WHERE deleted_at IS NULL AND type != 'layer'".freeze
def feature(id, name, geometry, properties)
{ "type" => "Feature", "geometry" => JSON.parse(geometry),
"properties" => JSON.parse(properties).merge("id" => id, "name" => name) }
end
def folder_param(id)
id == ROOT ? nil : id
end
# Each feature in a folder (layers expanded) with the OsmAnd file it
# goes into: nil = favourites, else the id of the track/route/layer it
# belongs with (a polygon or a measured line gets a file of its own).
def export_entries(path)
id = path.to_s.empty? ? nil : (folder_id(path, create: false) or raise NotFound)
rows = connect do |db|
db.execute("SELECT id, parent_id, type, name, geometry, properties, source_path FROM items WHERE folder_id IS ? AND deleted_at IS NULL ORDER BY name COLLATE NOCASE", [id])
end
rows.flat_map do |iid, parent, type, name, geometry, props, source|
if type == "layer"
features = begin
JSON.parse(layer_geojson(source, JSON.parse(props)["color"]))["features"]
rescue Gpx::ParseError, Fit::ParseError, Errno::ENOENT
[] # an unreadable legacy file doesn't sink the whole folder
end
lines = features.any? { |f| f.dig("geometry", "type") != "Point" }
features.map { |f| { feature: f, file: lines ? iid : nil, file_name: name } }
else
f = feature(iid, name, geometry, props)
file = parent || (type == "point" ? nil : iid)
[{ feature: f, file: file, file_name: file && (file == iid ? name : nil) }]
end
end.then do |entries|
# A track's points name their file after the track.
names = entries.filter_map { |e| [e[:file], e[:file_name]] if e[:file_name] }.to_h
entries.each { |e| e[:file_name] ||= names[e[:file]] }
end
end
def sibling?(db, parent, name, except)
db.get_first_value("SELECT 1 FROM folders WHERE parent_id IS ? AND name = ? AND id != ? AND deleted_at IS NULL", [parent, name, except])
end
# A layer's legacy GeoJSON with its node color on the lines.
def layer_geojson(source, color)
body = @gpx_store.geojson(source)
return body unless color
data = JSON.parse(body)
data["features"].each { |f| f["properties"] = (f["properties"] || {}).merge("color" => color) unless f.dig("geometry", "type") == "Point" }
JSON.generate(data)
end
def layer_source(key)
kind, id = key.to_s.split(":", 2)
return nil unless kind == "item"
connect { |db| db.get_first_value("SELECT source_path FROM items WHERE id = ? AND type = 'layer'", [id]) }
end
def add_layer(node, folder)
exists = connect { |db| db.get_first_value("SELECT 1 FROM items WHERE type = 'layer' AND source_path = ?", [node["path"]]) }
return if exists
target = folder_id(folder, create: true)
begin
@gpx_store.geojson(node["path"]) # warm GpxStore's conversion cache once, not on first view
rescue Gpx::ParseError, Fit::ParseError
nil
end
write do |db, rev, now|
db.execute("INSERT INTO items (id, folder_id, type, name, properties, source_path, created_at, updated_at, rev) VALUES (?, ?, 'layer', ?, ?, ?, ?, ?, ?)",
[SecureRandom.uuid, target, node["name"], JSON.generate("kinds" => node["kinds"]), node["path"], now, now, rev])
end
end
def parse(path)
case File.extname(path).downcase
when ".fit" then Fit.to_geojson(path)["features"]
when ".tcx" then Tcx.to_geojson(path)["features"]
when ".geojson" then JSON.parse(File.read(path)).fetch("features", [])
else Gpx.to_geojson(path)["features"]
end
end
# `folder` is a path, or with by_id: true already an id (nil = top).
def add_features(features, folder, source: nil, by_id: false)
target = by_id ? folder : folder_id(folder, create: true)
features = features.select { |f| f.is_a?(Hash) && f.dig("geometry", "coordinates").is_a?(Array) }
lines = features.count { |f| %w[track route].include?(item_type(f)) }
parent = nil
keys = []
write do |db, rev, now|
# Lines first, so a GPX's waypoints can point at its one track.
features.sort_by { |f| f.dig("geometry", "type") == "Point" ? 1 : 0 }.each do |f|
type = item_type(f)
props = (f["properties"] || {}).compact
props["name"] = default_name(source) if source && props["name"].to_s.empty? && %w[track route].include?(type)
fingerprint = Digest::SHA1.hexdigest(JSON.generate([type, props["name"], round(f["geometry"])]))
if props["source_id"]
id = upsert_by_source_id(db, target, props, f["geometry"], rev, now)
keys << "points:#{target || ROOT}" if id
next
end
existing = db.get_first_value("SELECT id FROM items WHERE folder_id IS ? AND fingerprint = ? AND deleted_at IS NULL", [target, fingerprint])
id = existing
unless existing
id = props["id"].to_s
id = SecureRandom.uuid if id.empty? || db.get_first_value("SELECT 1 FROM items WHERE id = ?", [id])
point_parent = parent if lines == 1 && %w[point shape].include?(type)
db.execute("INSERT INTO items VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NULL, ?)",
[id, target, point_parent, type, props["name"], JSON.generate(f["geometry"]),
JSON.generate(props.except("id")), fingerprint, source, now, now, rev])
end
parent = id if %w[track route].include?(type)
keys << (%w[track route].include?(type) ? "item:#{id}" : "points:#{target || ROOT}") unless lines == 1 && %w[point shape].include?(type)
end
end
keys.uniq
end
# A feature that names where it came from (`source_id`, e.g. a Google
# saved place's id) is kept once per folder: importing the list again
# refreshes the point's name and Google's fields, keeping what was
# changed here (color, icon, a moved position — only an approximate
# position gives way to an exact one, a renamed or redescribed point
# keeps its own text). One deleted here stays deleted.
# Returns the id, nil when skipped.
IMPORTED_TEXT = %w[name description].freeze
def upsert_by_source_id(db, folder, props, geometry, rev, now)
props = props.merge("imported" => props.slice(*IMPORTED_TEXT))
row = db.get_first_row("SELECT id, geometry, properties, deleted_at FROM items WHERE folder_id IS ? AND json_extract(properties, '$.source_id') = ?",
[folder, props["source_id"]])
unless row
id = SecureRandom.uuid
db.execute("INSERT INTO items VALUES (?, ?, NULL, 'point', ?, ?, ?, NULL, NULL, ?, ?, NULL, ?)",
[id, folder, props["name"], JSON.generate(geometry), JSON.generate(props.except("id")), now, now, rev])
return id
end
id, old_geometry, old_props, deleted = row
return nil if deleted
old = JSON.parse(old_props)
merged = old.merge(props.except("id", "approximate"))
# A field differing from what the last import said was edited here.
# Points imported before "imported" was kept: any difference counts
# as an edit, the safe guess.
last = old["imported"] || {}
IMPORTED_TEXT.each { |f| merged[f] = old[f] if old.key?(f) && old[f] != last.fetch(f, props[f]) }
exact = old["approximate"] && !props["approximate"]
merged.delete("approximate") if exact
new_geometry = exact ? JSON.generate(geometry) : old_geometry
return id if merged == old && new_geometry == old_geometry
db.execute("UPDATE items SET name = ?, geometry = ?, properties = ?, updated_at = ?, rev = ? WHERE id = ?",
[merged["name"], new_geometry, JSON.generate(merged), now, rev, id])
id
end
def item_type(feature)
geometry = feature.dig("geometry", "type").to_s
props = feature["properties"] || {}
return "point" if geometry == "Point"
return "shape" if geometry.include?("Polygon") || props["category"] == "Note"
props["kind"] == "route" ? "route" : "track"
end
def round(value)
case value
when Hash then value.transform_values { |v| round(v) }
when Array then value.map { |v| round(v) }
when Float then value.round(6)
else value
end
end
def tombstone(db, where, params, rev, now)
db.execute("UPDATE items SET deleted_at = ?, updated_at = ?, rev = ? WHERE (#{where}) AND deleted_at IS NULL", [now, now, rev, *params])
end
def safe_name(name)
name = name.to_s.gsub(%r{[/\\:*?"<>|]}, "_").strip
name.empty? || %w[. ..].include?(name) ? "track" : name
end
def safe_filename(filename)
base = File.basename(filename.to_s)
base = "upload.gpx" if base.empty? || base == "." || base == ".."
base = "#{base}.gpx" unless EXTENSIONS.include?(File.extname(base).downcase)
base
end
# One write transaction: bumps the change counter and hands every row
# written in it the same rev.
def write
connect do |db|
db.transaction(:immediate) do
rev = db.get_first_value("UPDATE meta SET rev = rev + 1 RETURNING rev")
yield db, rev, Time.now.utc.iso8601
end
end
end
# ponytail: a connection per call — simple and thread-safe under Puma;
# a per-thread connection if opening ever shows up in a profile.
def connect
db = SQLite3::Database.new(@path)
db.busy_timeout = 5000
yield db
ensure
db&.close
end
end
end
+107
View File
@@ -0,0 +1,107 @@
require "net/http"
require "uri"
require "ipaddr"
require "resolv"
require "cgi"
module Maptool
# A link pasted into the search (the Design canvas' Plan) → a place:
# { name:, lat:, lng:, url: }, or nil. The coordinates come from the URL
# itself (Google Maps' @lat,lng / !3d!4d / ?q=, geo:), else from the page
# it leads to (redirects followed: maps.app.goo.gl): its geo meta tags,
# JSON-LD, or a map link in it — the way a chat app unfurls a link, one
# page the user pasted. Only public addresses are fetched (never this
# server's LAN).
module LinkPlace
MAX_BYTES = 2_000_000
MAX_REDIRECTS = 5
TIMEOUT_S = 10
LAT_LNG = /(-?\d{1,2}\.\d+)\s*[,;]\s*(-?\d{1,3}\.\d+)/
class Error < StandardError; end
def self.resolve(url)
place = from_url(url)
return place if place
html, final = fetch(url)
from_url(final) || from_html(html)&.then { |p| p.merge(url: final) }
end
# Coordinates in the link itself.
def self.from_url(url)
text = CGI.unescape(url.to_s)
lat, lng = text.match(/!3d(-?\d+\.\d+)!4d(-?\d+\.\d+)/)&.captures ||
text.match(/[?&](?:q|query|ll|destination|daddr|center)=(?:loc:)?#{LAT_LNG}/)&.captures ||
text.match(/@#{LAT_LNG}/)&.captures ||
text.match(/\Ageo:#{LAT_LNG}/)&.captures ||
text.match(%r{/place/#{LAT_LNG}})&.captures
return nil unless lat
name = text[%r{/place/([^/@]+)/}, 1]&.tr("+", " ")
place(name, lat, lng, url)
end
# Coordinates in the page: meta tags, JSON-LD, then a map link.
def self.from_html(html)
meta = ->(key) { html[/<meta[^>]+(?:property|name)=["']#{Regexp.escape(key)}["'][^>]*content=["']([^"']+)/i, 1] || html[/<meta[^>]+content=["']([^"']+)["'][^>]*(?:property|name)=["']#{Regexp.escape(key)}["']/i, 1] }
name = meta.("og:title") || html[%r{<title[^>]*>([^<]+)</title>}i, 1]
name = CGI.unescapeHTML(name.strip) if name
lat, lng = [meta.("place:location:latitude") || meta.("og:latitude"), meta.("place:location:longitude") || meta.("og:longitude")]
lat, lng = (meta.("geo.position") || meta.("ICBM"))&.match(LAT_LNG)&.captures unless lat && lng
lat, lng = html.match(/"latitude"\s*:\s*"?(-?\d+\.\d+)"?\s*,\s*"longitude"\s*:\s*"?(-?\d+\.\d+)/)&.captures unless lat && lng
lat, lng = html.scan(%r{https?://(?:www\.)?google\.[a-z.]+/maps[^"'\s<>]*}).lazy.filter_map { |u| from_url(CGI.unescapeHTML(u)) }.first&.values_at(:lat, :lng) unless lat && lng
lat && lng ? place(name, lat, lng, nil) : nil
end
def self.place(name, lat, lng, url)
lat = Float(lat)
lng = Float(lng)
return nil unless lat.between?(-90, 90) && lng.between?(-180, 180)
{ name: name&.strip&.then { |n| n.empty? ? nil : n[0, 160] }, lat: lat, lng: lng, url: url }.compact
end
# [body, final url]; raises Error.
def self.fetch(url, redirects = MAX_REDIRECTS)
uri = URI.parse(url)
raise Error, "only http(s) links" unless %w[http https].include?(uri.scheme) && uri.host
ip = public_ip(uri.host)
http = Net::HTTP.new(uri.host, uri.port)
http.ipaddr = ip # the address checked, not a second lookup
http.use_ssl = uri.scheme == "https"
http.open_timeout = http.read_timeout = TIMEOUT_S
request = Net::HTTP::Get.new(uri, "User-Agent" => "Mozilla/5.0 (maptool link preview)", "Accept" => "text/html")
http.request(request) do |response|
case response
when Net::HTTPRedirection
raise Error, "too many redirects" if redirects.zero?
return fetch(URI.join(url, response["location"]).to_s, redirects - 1)
when Net::HTTPSuccess
body = +""
response.read_body do |chunk|
body << chunk
break if body.bytesize > MAX_BYTES
end
return [body.force_encoding("UTF-8").scrub, url]
else
raise Error, "the page answered #{response.code}"
end
end
rescue URI::InvalidURIError, SocketError, Timeout::Error, SystemCallError, OpenSSL::SSL::SSLError, Net::HTTPBadResponse => e
raise Error, e.message
end
def self.public_ip(host)
address = Resolv.getaddress(host)
ip = IPAddr.new(address)
raise Error, "not a public address" if ip.private? || ip.loopback? || ip.link_local? || address.start_with?("0.") || ip == IPAddr.new("::") ||
IPAddr.new("100.64.0.0/10").include?(ip) # CGNAT: Tailscale
address
rescue Resolv::ResolvError
raise Error, "unknown host #{host}"
end
end
end
+144
View File
@@ -0,0 +1,144 @@
require "json"
require "fileutils"
module Maptool
# Live data off the home MQTT broker (app.rb wires the topics in): the GNSS
# tracker's position, its USB power state and the trail behind it, and the
# ITS-G5 stations its receiver hears. Thread-safe — the MQTT thread writes,
# requests read.
#
# The trail is kept in memory for TRAIL_KEEP; with logging on (a setting)
# every trail point is also appended to tracker.jsonl, which is read back
# on start, so the trail survives a restart/redeploy. The tracker's
# settings (name, icon, color, logging, trail_hours) live in settings.json
# next to it — the same for every device viewing the map.
class LiveStore
ITS_STALE_AFTER = 60 # seconds
TRAIL_KEEP = 24 * 3600 # seconds
# A trail point is only added once the tracker has moved this far, or
# this long has passed — a parked tracker repeating its position doesn't
# grow it.
TRAIL_MIN_METERS = 10
TRAIL_MIN_SECONDS = 300
DEFAULT_SETTINGS = {
"name" => "Tracker", "icon" => "automobiles", "color" => "#1a1a1a", "logging" => false, "trail_hours" => 1,
}.freeze
TRAIL_HOURS = [0, 1, 2, 4, 8, 24].freeze
def initialize(dir)
@dir = dir
@mutex = Mutex.new
@tracker = nil
@usb_power = nil
@its = {}
@settings = DEFAULT_SETTINGS.merge(read_json(settings_path) || {})
@trail = load_trail
end
def record_tracker(data, at: Time.now.to_f)
return unless data.is_a?(Hash) && data["latitude"] && data["longitude"]
@mutex.synchronize do
@tracker = data.merge("received_at" => at)
add_trail_point([at.round, data["longitude"].to_f.round(6), data["latitude"].to_f.round(6)])
end
end
# ESPHome's binary sensor state: "ON" / "OFF".
def record_usb_power(payload)
@mutex.synchronize { @usb_power = payload.to_s.strip.upcase == "ON" }
end
def record_its(data, at: Time.now.to_f)
return unless data.is_a?(Hash) && data["id"] && data["lat"] && data["lon"]
@mutex.synchronize do
@its[data["id"]] = data.merge("received_at" => at)
@its.delete_if { |_, station| at - station["received_at"] > ITS_STALE_AFTER }
end
end
# What /api/live returns: the tracker (with its age, settings, USB power
# and the trail of the last trail_hours) and the fresh ITS-G5 stations.
def snapshot(now: Time.now.to_f)
@mutex.synchronize do
tracker = @tracker && @tracker.except("received_at").merge(
"age" => (now - @tracker["received_at"]).round,
"usb_power" => @usb_power,
"trail" => @trail.select { |t, _, _| now - t <= @settings["trail_hours"] * 3600 }.map { |_, lon, lat| [lon, lat] },
)
stations = @its.values.select { |s| now - s["received_at"] <= ITS_STALE_AFTER }
.map { |s| s.except("received_at").merge("age" => (now - s["received_at"]).round) }
{ tracker: tracker, settings: @settings.dup, its: stations }
end
end
def settings
@mutex.synchronize { @settings.dup }
end
# Only known keys, sanitized; returns the new settings.
def update_settings(changes)
@mutex.synchronize do
changes = changes.to_h.transform_keys(&:to_s)
@settings["name"] = changes["name"].to_s.strip[0, 40] if changes.key?("name") && !changes["name"].to_s.strip.empty?
@settings["icon"] = changes["icon"].to_s[0, 60] if changes.key?("icon")
@settings["color"] = changes["color"] if changes["color"].to_s.match?(/\A#\h{6}\z/)
@settings["logging"] = [true, "true", "1", "on"].include?(changes["logging"]) if changes.key?("logging")
hours = changes["trail_hours"].to_s
@settings["trail_hours"] = hours.to_i if TRAIL_HOURS.include?(hours.to_i) && hours.match?(/\A\d+\z/)
FileUtils.mkdir_p(@dir)
File.write(settings_path, JSON.generate(@settings))
@settings.dup
end
end
private
def add_trail_point(point)
last = @trail.last
return if last && point[0] - last[0] < TRAIL_MIN_SECONDS && meters(last, point) < TRAIL_MIN_METERS
@trail << point
@trail.shift while @trail.first && point[0] - @trail.first[0] > TRAIL_KEEP
append_log(point) if @settings["logging"]
end
def append_log(point)
FileUtils.mkdir_p(@dir)
File.open(log_path, "a") { |f| f.puts(JSON.generate(point)) }
rescue SystemCallError => e
warn "[live] could not log the trail: #{e.message}"
end
# The last TRAIL_KEEP of the log, if there is one.
def load_trail
return [] unless File.exist?(log_path)
cutoff = Time.now.to_f - TRAIL_KEEP
File.foreach(log_path).filter_map do |line|
point = JSON.parse(line)
point if point.is_a?(Array) && point.size == 3 && point[0] >= cutoff
rescue JSON::ParserError
nil
end
end
# Equirectangular approximation; plenty for "has it moved 10 m".
def meters(a, b)
_, lon1, lat1 = a
_, lon2, lat2 = b
x = (lon2 - lon1) * Math.cos((lat1 + lat2) * Math::PI / 360)
Math.sqrt((x**2) + ((lat2 - lat1)**2)) * 111_320
end
def read_json(path)
JSON.parse(File.read(path)) if File.exist?(path)
rescue JSON::ParserError
nil
end
def settings_path = File.join(@dir, "settings.json")
def log_path = File.join(@dir, "tracker.jsonl")
end
end
+153
View File
@@ -0,0 +1,153 @@
require "socket"
require "openssl"
require "securerandom"
require "uri"
module Maptool
# A minimal MQTT 3.1.1 subscriber (stdlib only): connects,
# subscribes to a few topics at QoS 0 and yields every message, for as long
# as the block keeps running. Enough for reading sensor topics off the home
# broker; no publishing, no QoS 1/2 delivery guarantees, no persistent
# session. mqtt:// is plain TCP, mqtts:// is TLS.
class MqttClient
class ProtocolError < StandardError; end
RECONNECT_DELAY = 5 # seconds
KEEPALIVE = 30 # seconds, sent in CONNECT; a PINGREQ goes out at half of it
def initialize(url:, topics:, username: nil, password: nil, client_id: "maptool-#{SecureRandom.hex(4)}")
@uri = URI(url)
raise ArgumentError, "unsupported MQTT URL #{url}" unless %w[mqtt mqtts].include?(@uri.scheme)
@topics = topics
@username = username.to_s.empty? ? nil : username
@password = password.to_s.empty? ? nil : password
@client_id = client_id
end
# Never returns under normal operation: reconnects after any I/O or
# protocol error, so a broker that's down or restarting isn't fatal.
def each_message(&block)
loop do
session(&block)
rescue SystemCallError, IOError, SocketError, OpenSSL::SSL::SSLError, ProtocolError => e
warn "[mqtt] #{e.class}: #{e.message} — retrying in #{RECONNECT_DELAY}s"
sleep RECONNECT_DELAY
end
end
private
def session
socket = open_socket
write_packet(socket, 0x10, connect_payload)
type, _flags, body = read_packet(socket)
raise ProtocolError, "no CONNACK" unless type == 2
raise ProtocolError, "connection refused (code #{body.getbyte(1)})" unless body.getbyte(1).zero?
write_packet(socket, 0x82, [1].pack("n") + @topics.map { |t| utf8(t) + "\x00".b }.join)
last_sent = last_received = now
loop do
if readable?(socket, 1)
type, flags, body = read_packet(socket)
last_received = now
yield(*parse_publish(socket, flags, body)) if type == 3
end
if now - last_sent >= KEEPALIVE / 2
write_packet(socket, 0xC0, "".b)
last_sent = now
end
raise ProtocolError, "broker silent for #{KEEPALIVE * 2}s" if now - last_received > KEEPALIVE * 2
end
ensure
socket&.close
end
def open_socket
tls = @uri.scheme == "mqtts"
tcp = Socket.tcp(@uri.host, @uri.port || (tls ? 8883 : 1883), connect_timeout: 10)
return tcp unless tls
context = OpenSSL::SSL::SSLContext.new
context.set_params(verify_mode: OpenSSL::SSL::VERIFY_PEER)
ssl = OpenSSL::SSL::SSLSocket.new(tcp, context)
ssl.hostname = @uri.host
ssl.sync_close = true
ssl.connect
ssl
end
def connect_payload
flags = 0x02 # clean session
flags |= 0x80 if @username
flags |= 0x40 if @password
utf8("MQTT") + [4, flags, KEEPALIVE].pack("CCn") + utf8(@client_id) +
(@username ? utf8(@username) : "".b) + (@password ? utf8(@password) : "".b)
end
# [topic, payload]; a QoS 1 message (the broker may downgrade to our 0,
# but don't count on it) is acknowledged so it isn't redelivered.
def parse_publish(socket, flags, body)
qos = (flags >> 1) & 0x03
length = body.unpack1("n")
topic = body.byteslice(2, length).force_encoding("UTF-8")
offset = 2 + length
if qos.positive?
packet_id = body.byteslice(offset, 2)
write_packet(socket, 0x40, packet_id) if qos == 1
offset += 2
end
[topic, body.byteslice(offset..).force_encoding("UTF-8")]
end
def write_packet(socket, header, body)
socket.write([header].pack("C") + encode_length(body.bytesize) + body)
end
def read_packet(socket)
header = read_exactly(socket, 1).ord
length = 0
multiplier = 1
loop do
byte = read_exactly(socket, 1).ord
length += (byte & 0x7F) * multiplier
break if byte < 0x80
multiplier *= 128
raise ProtocolError, "bad remaining length" if multiplier > 128**3
end
[header >> 4, header & 0x0F, length.zero? ? "".b : read_exactly(socket, length)]
end
def read_exactly(socket, count)
data = socket.read(count)
raise EOFError, "connection closed" if data.nil? || data.bytesize < count
data
end
def encode_length(length)
bytes = []
loop do
byte = length % 128
length /= 128
bytes << (length.positive? ? byte | 0x80 : byte)
break unless length.positive?
end
bytes.pack("C*")
end
def utf8(string)
[string.bytesize].pack("n") + string.b
end
# An SSLSocket may hold already-decrypted bytes IO.select can't see.
def readable?(socket, timeout)
(socket.respond_to?(:pending) && socket.pending.positive?) || IO.select([socket], nil, nil, timeout)
end
def now
Process.clock_gettime(Process::CLOCK_MONOTONIC)
end
end
end
+273
View File
@@ -0,0 +1,273 @@
require "json"
require_relative "can"
module Maptool
# Outputs on the bus — relay modules for now, no current measured — and
# the bindings that drive them from a keypad's channels (docs/design.adoc,
# "Switches and the keypad"): maptool is the controller, the module only
# switches. The bindings are the screen profile's (public/drive/road.json)
# or this car's (data/drive/bindings.json) with an "output" in place of an "action":
# { "input": "pad.K6", "output": "relays.2", "mode": "hold", "led": "red" }
# Modes (after Garmin PowerSwitch, OnDeck, MaxxECU — docs/design.adoc):
# toggle, on, off
# hold on while the key is held — off when it's let go or the keypad goes silent
# pulse on for "pulse_s" (1 s)
# positions "outputs": [a, b, …] — a press steps off → a → b → … → off, a knob
# turns up and down; one on at a time, the last off before the next on
# strobe a press starts / stops it blinking, "period_s" (1 s) a whole on + off
# dimmer a knob sets the level by "step" % (10), a press switches it on / off;
# only a "dimmable" module dims, a relay is on above 0
#
# can.json: "outputs": [ { "name": "relays", "node": 48, "channels": 8, "simulated": true,
# "labels": { "1": "Lights", "2": "Winch in" } },
# { "name": "dim", "node": 49, "channels": 4, "dimmable": true, "simulated": true } ]
# A module's protocol, ours (after LD's native CAN control): RPDO1
# 0x200+node, a bit per channel (byte 0: 1–8, byte 1: 9–16) — a dimmable
# one a byte per channel instead (0–255, up to 8) — the whole state in
# every frame, sent on a change and every REPEAT_S; the module turns
# everything off after 2 s without one. "simulated": no frames, the state
# is just kept here (/sim.html shows it).
class Outputs
REPEAT_S = 0.1
MODES = %w[toggle on off hold pulse positions strobe dimmer].freeze
Module = Struct.new(:name, :node, :channels, :simulated, :dimmable, :labels, :state, :level, keyword_init: true)
attr_reader :modules
# send: a block that puts a Frame on the bus (not called for simulated modules)
def initialize(configs, &send)
@modules = configs.map do |c|
n = c.fetch("channels", 8)
raise ArgumentError, "#{c['name']}: a dimmable module has 8 channels at most" if c["dimmable"] && n > 8
Module.new(name: c.fetch("name"), node: Integer(c.fetch("node", 0)), channels: n, simulated: c.fetch("simulated", false),
dimmable: c.fetch("dimmable", false), labels: c.fetch("labels", {}), state: Array.new(n, false), level: Array.new(n, 100))
end
@send = send
@mutex = Mutex.new
@pulses = {}
@held = {} # channel (the key) → outputs it holds on
@positions = {} # channel → its position, 0 = all off
@strobes = {} # output → [since, period]
end
def find(output)
name, ch = output.to_s.split(".", 2)
m = @modules.find { |x| x.name == name }
i = Integer(ch, exception: false)
[m, i - 1] if m && i&.between?(1, m.channels)
end
def on?(output)
m, i = find(output)
m ? @mutex.synchronize { m.state[i] } : nil
end
def level(output)
m, i = find(output)
m ? @mutex.synchronize { m.level[i] } : nil
end
def set(output, value)
m, i = find(output)
raise ArgumentError, "no output #{output}" unless m
changed = @mutex.synchronize do
next false if m.state[i] == value
m.state[i] = value
@pulses.delete(output) unless value
true
end
transmit(m) if changed
changed
end
# By hand (/sim.html, a screen tile): a strobe stops.
def manual(output, value)
@mutex.synchronize { @strobes.delete(output) }
set(output, value)
end
# The binding's outputs: "outputs" (positions) or "output".
def self.outputs_of(binding) = Array(binding["outputs"] || binding["output"])
# Whether a binding's function is on (its key's LED): a position chosen, a strobe running, else its output on.
def active?(binding)
outs = self.class.outputs_of(binding)
case binding["mode"]
when "positions" then @mutex.synchronize { @positions.fetch(binding["input"], 0) }.positive?
when "strobe" then @mutex.synchronize { @strobes.key?(outs.first) }
else !!on?(outs.first)
end
end
# A keypad event ("pad.K6", "pad.K6 up", "pad.E4 ⟳") through the bindings that have an output.
def input(event, bindings, at: Time.now.to_f)
turn = event[/ ([⟳⟲])\z/, 1]
up = event.end_with?(" up")
channel = event.sub(/ (up|⟳|⟲)\z/, "")
bindings.each do |b|
outs = self.class.outputs_of(b)
# a profile's output this car hasn't: skipped
next unless b["input"] == channel && outs.any? && outs.all? { |o| find(o) }
output = outs.first
mode = b.fetch("mode", "toggle")
if turn
step = turn == "⟳" ? 1 : -1
if mode == "positions" then position(channel, outs, @mutex.synchronize { @positions.fetch(channel, 0) } + step)
elsif mode == "dimmer" then dim(output, step * b.fetch("step", 10).to_f)
end
next
end
case mode
when "toggle", "dimmer" then switch(output, !on?(output)) unless up
when "on" then set(output, true) unless up
when "off" then set(output, false) unless up
when "hold"
set(output, !up)
up ? @held.delete(channel) : (@held[channel] ||= []) << output
when "pulse"
next if up
set(output, true)
@mutex.synchronize { @pulses[output] = at + b.fetch("pulse_s", 1).to_f }
when "positions" then position(channel, outs, (@mutex.synchronize { @positions.fetch(channel, 0) } + 1) % (outs.size + 1)) unless up
when "strobe"
next if up
started = @mutex.synchronize { @strobes.delete(output) ? false : (@strobes[output] = [at, b.fetch("period_s", 1).to_f]) && true }
set(output, started) # started: on now; stopped: off
end
end
end
# A keypad gone silent: what it held goes off (the fail-safe).
def keypad_lost(device)
@held.select { |channel, _| channel.start_with?("#{device}.") }.each do |channel, outputs|
outputs.each { |o| set(o, false) }
@held.delete(channel)
end
end
# Every REPEAT_S: pulses ending, strobes blinking, the state sent again (the module's watchdog).
def tick(at: Time.now.to_f)
ended, strobes = @mutex.synchronize { [@pulses.select { |_, till| till <= at }.keys, @strobes.dup] }
ended.each { |o| set(o, false) }
strobes.each { |o, (since, period)| set(o, ((at - since) / (period / 2)).floor.even?) }
@modules.each { |m| transmit(m) }
end
def frame(m)
data = if m.dimmable
m.state.each_with_index.map { |on, i| on ? (m.level[i] * 255 / 100.0).round : 0 }.pack("C*")
else
[m.state.each_with_index.sum { |on, i| on ? 1 << i : 0 }].pack("Q<").byteslice(0, (m.channels + 7) / 8)
end
Can::Frame.new(0x200 + m.node, data, false)
end
def snapshot
@mutex.synchronize do
@modules.map do |m|
{ name: m.name, node: m.node, simulated: m.simulated, dimmable: m.dimmable,
channels: (1..m.channels).map do |n|
{ n: n, label: m.labels[n.to_s], on: m.state[n - 1], level: m.dimmable ? m.level[n - 1] : nil, strobe: @strobes.key?("#{m.name}.#{n}") }.compact
end }
end
end
end
private
# on with its level above 0 (a dimmer switched on at 0 comes back at 100)
def switch(output, value)
m, i = find(output)
@mutex.synchronize { m.level[i] = 100 if value && m.level[i].zero? }
set(output, value)
end
def dim(output, delta)
m, i = find(output)
level = @mutex.synchronize { m.level[i] = (m.level[i] + delta).clamp(0, 100) }
transmit(m) unless set(output, level.positive?)
end
# The channel's position n (clamped to 0..outputs): the others off first, then its own on.
def position(channel, outs, n)
n = n.clamp(0, outs.size)
@mutex.synchronize { @positions[channel] = n }
outs.each_with_index { |o, i| set(o, false) unless i == n - 1 }
set(outs[n - 1], true) if n.positive?
end
def transmit(m)
return if m.simulated || !@send
@send.call(frame(m))
rescue StandardError => e
warn "outputs: #{m.name}: #{e.message}"
end
end
end
if $PROGRAM_NAME == __FILE__
sent = []
out = Maptool::Outputs.new([{ "name" => "relays", "node" => 48 }, { "name" => "dim", "node" => 49, "channels" => 2, "dimmable" => true }]) { |f| sent << f }
b = [{ "input" => "pad.K1", "output" => "relays.1" }, { "input" => "pad.K6", "output" => "relays.2", "mode" => "hold" },
{ "input" => "pad.K7", "output" => "relays.3", "mode" => "pulse", "pulse_s" => 2 }]
out.input("pad.K1", b)
raise "toggle" unless out.on?("relays.1")
out.input("pad.K6", b)
raise "hold" unless out.on?("relays.2")
out.keypad_lost("pad")
raise "fail-safe" if out.on?("relays.2")
out.input("pad.K7", b, at: 100)
out.tick(at: 101)
raise "pulse early" unless out.on?("relays.3")
out.tick(at: 102.1)
raise "pulse" if out.on?("relays.3")
out.input("pad.K1", [{ "input" => "pad.K1", "output" => "winch.1" }]) # no such module: nothing, no error
relay_frame = sent.reverse.find { |f| f.id == 0x230 }
raise relay_frame.inspect unless relay_frame.data == "\x01".b
# positions: off → 4 → 5 → off by presses; a knob up and down, clamped
pos = [{ "input" => "pad.K2", "outputs" => ["relays.4", "relays.5"], "mode" => "positions" },
{ "input" => "pad.E4", "outputs" => ["relays.4", "relays.5"], "mode" => "positions" }]
states = -> { [out.on?("relays.4"), out.on?("relays.5")] }
out.input("pad.K2", pos)
raise "pos 1" unless states.call == [true, false] && out.active?(pos[0])
out.input("pad.K2", pos)
raise "pos 2" unless states.call == [false, true]
out.input("pad.K2", pos)
raise "pos 0" unless states.call == [false, false] && !out.active?(pos[0])
3.times { out.input("pad.E4 ⟳", pos) }
raise "knob clamp" unless states.call == [false, true]
out.input("pad.E4 ⟲", pos)
raise "knob down" unless states.call == [true, false]
# strobe: blinks at half the period, a press stops it off
st = [{ "input" => "pad.K3", "output" => "relays.6", "mode" => "strobe", "period_s" => 1 }]
out.input("pad.K3", st, at: 200)
out.tick(at: 200.6)
raise "strobe off phase" if out.on?("relays.6")
out.tick(at: 201.1)
raise "strobe on phase" unless out.on?("relays.6") && out.active?(st[0])
out.input("pad.K3", st, at: 201.2)
out.tick(at: 201.6)
raise "strobe stopped" if out.on?("relays.6") || out.active?(st[0])
# dimmer: a knob down to 0 is off, up is on again; a dimmable module sends bytes
dm = [{ "input" => "pad.E5", "output" => "dim.1", "mode" => "dimmer", "step" => 50 }, { "input" => "pad.E5 press", "output" => "dim.1", "mode" => "dimmer" }]
out.input("pad.E5 press", dm)
raise "dimmer on" unless out.on?("dim.1") && out.level("dim.1") == 100
out.input("pad.E5 ⟲", dm)
raise sent.last.data.bytes.inspect unless sent.last.id == 0x231 && sent.last.data.bytes == [128, 0]
out.input("pad.E5 ⟲", dm)
raise "dimmer 0 off" if out.on?("dim.1")
out.input("pad.E5 ⟳", dm)
raise "dimmer up" unless out.on?("dim.1") && out.level("dim.1") == 50
puts "ok"
end
+11 -5
View File
@@ -58,9 +58,10 @@ module Maptool
["operator", "Operator"], ["operator", "Operator"],
].freeze ].freeze
# bbox: [south, west, north, east] (Overpass's own axis order). # bbox: [south, west, north, east] (Overpass's own axis order); or
def self.fetch(bbox, timeout: 60) # around: [radius m, [[lon, lat], ...]] — a corridor along a line.
query = build_query(bbox, timeout: timeout) def self.fetch(bbox, timeout: 60, around: nil)
query = build_query(bbox, timeout: timeout, around: around)
errors = OVERPASS_APIS.map do |url| errors = OVERPASS_APIS.map do |url|
return post(URI(url), query, timeout) return post(URI(url), query, timeout)
rescue FetchError, Net::OpenTimeout, Net::ReadTimeout, SystemCallError, SocketError, OpenSSL::SSL::SSLError, JSON::ParserError => e rescue FetchError, Net::OpenTimeout, Net::ReadTimeout, SystemCallError, SocketError, OpenSSL::SSL::SSLError, JSON::ParserError => e
@@ -83,8 +84,13 @@ module Maptool
JSON.parse(response.body) JSON.parse(response.body)
end end
def self.build_query(bbox, timeout: 60) def self.build_query(bbox, timeout: 60, around: nil)
bbox_str = bbox.join(",") bbox_str = if around
radius, line = around
"around:#{radius.round},#{line.map { |lon, lat| "#{lat.round(5)},#{lon.round(5)}" }.join(',')}"
else
bbox.join(",")
end
filters = CATEGORIES.keys.map do |tags| filters = CATEGORIES.keys.map do |tags|
conditions = tags.map { |k, v| %(["#{k}"="#{v}"]) }.join conditions = tags.map { |k, v| %(["#{k}"="#{v}"]) }.join
"node#{conditions}(#{bbox_str});" "node#{conditions}(#{bbox_str});"
+172
View File
@@ -0,0 +1,172 @@
require "json"
require "open3"
require "set"
require "sqlite3"
require "tmpdir"
module Maptool
# Offline place-name search: every named OSM object in a country's
# Geofabrik .osm.pbf (towns, streets, peaks, POIs, ...) in a SQLite FTS5
# index, one data/places/<CODE>.sqlite per country — built during the
# offline build next to hiking trails, from the same already-downloaded
# PBF. offline.pmtiles itself is tiles, not searchable by name.
module Places
class ExtractError < StandardError; end
# Bumped whenever the table layout or what goes into it changes —
# PmtilesBuilder rebuilds an index whose user_version is older, so a
# plain `rake places:index` picks the change up.
SCHEMA_VERSION = 3
# Most to least important; the first key a feature carries decides
# its kind and rank. Within "place", the value refines it further.
KIND_KEYS = %w[place natural tourism amenity historic leisure shop aeroway railway highway waterway
boundary landuse man_made office building].freeze
# Named buildings and land-use areas (a farm's fields, an industrial
# estate) are noise in results — nobody looks for them by name — so
# they're dropped, but only when that's what the object *is*: a
# supermarket drawn as a building is still shop=supermarket. (Measured:
# only ~1-7% of an index's size, so this is about result quality.)
SKIPPED_KEYS = %w[landuse building].freeze
# Same idea, measured on France (5.3M rows): place=locality (~10%,
# mostly cadastral names of fields and woods) and isolated_dwelling
# (~5%, single farms/houses) — plus anything named but with none of
# KIND_KEYS (~4%: bus route relations and the like).
SKIPPED_PLACES = %w[locality isolated_dwelling].freeze
APOSTROPHES = "'’ʼ`"
PLACE_RANK = { "city" => 0, "town" => 1, "village" => 2, "suburb" => 3, "hamlet" => 3 }.freeze
# How much closer a settlement counts as when results are ordered by
# distance from the map center (Search) — so typing a city's name finds
# the city, not a same-named street around the corner, while a shop or
# a street is purely nearest-first. Keyed by importance (PLACE_RANK).
# ponytail: fixed multipliers, tune if real searches rank oddly.
DISTANCE_WEIGHT = Hash.new(1.0).merge(0 => 0.01, 1 => 0.03, 2 => 0.1, 3 => 0.3).freeze
KEY_RANK = Hash.new(7).merge("place" => 4, "natural" => 5, "tourism" => 5, "amenity" => 5, "historic" => 5,
"leisure" => 5, "shop" => 5, "aeroway" => 5, "railway" => 6, "highway" => 6, "waterway" => 6)
def self.osmium_bin
ENV.fetch("OSMIUM_BIN", "osmium")
end
def self.extract(pbf_path, db_path)
Dir.mktmpdir("maptool-places") do |dir|
named = File.join(dir, "named.osm.pbf")
run!(osmium_bin, "tags-filter", pbf_path, "nwr/name", "-o", named)
seq = File.join(dir, "named.geojsonseq")
run!(osmium_bin, "export", named, "-f", "geojsonseq", "-x", "print_record_separator=false", "-o", seq)
File.open(seq) { |io| import(io, db_path) }
end
end
# Pure apart from SQLite — one GeoJSON feature per line in, index out —
# so it's testable without osmium installed (same split as
# HikingTrails.extract/parse_opl).
def self.import(io, db_path)
File.delete(db_path) if File.exist?(db_path)
db = SQLite3::Database.new(db_path)
db.execute(<<~SQL)
CREATE VIRTUAL TABLE places USING fts5(
name, extra, kind UNINDEXED, importance UNINDEXED, lon UNINDEXED, lat UNINDEXED, bbox UNINDEXED,
tokenize = 'unicode61 remove_diacritics 2', prefix = '2 3'
)
SQL
db.execute("PRAGMA user_version = #{SCHEMA_VERSION}")
# A street is many way segments, all named the same — one row per
# name/kind per ~2 km cell keeps a town's "Hlavná" from filling the
# whole result list. ponytail: grid dedupe, a long road still shows
# once per cell it crosses.
seen = Set.new
insert = db.prepare("INSERT INTO places VALUES (?, ?, ?, ?, ?, ?, ?)")
db.transaction do
io.each_line do |line|
row = row(JSON.parse(line))
next unless row && seen.add?([row[0], row[2], (row[5] * 50).round, (row[4] * 50).round])
insert.execute(row)
rescue JSON::ParserError
next
end
end
insert.close
db.execute("INSERT INTO places(places) VALUES ('optimize')")
db.close
end
def self.current?(db_path)
return false unless File.exist?(db_path)
db = SQLite3::Database.new(db_path, readonly: true)
db.get_first_value("PRAGMA user_version") >= SCHEMA_VERSION
rescue SQLite3::Exception
false
ensure
db&.close
end
# [name, extra, kind, importance, lon, lat, bbox json] or nil. extra is
# searched too but never shown: the name with its apostrophes dropped
# (FTS5 splits "McDonald's" into "mcdonald" + "s", so "mcdonalds" would
# otherwise find nothing — Search.normalize drops them from the query
# the same way) and the brand tag ("Lidl" for "Lidl Petržalka").
def self.row(feature)
tags = feature["properties"] || {}
name = tags["name"].to_s.strip
geometry = feature["geometry"] || {}
coords = geometry["coordinates"]
key = KIND_KEYS.find { |k| tags[k] }
return nil if name.empty? || !coords.is_a?(Array) || coords.empty? || key.nil? || SKIPPED_KEYS.include?(key)
return nil if key == "place" && SKIPPED_PLACES.include?(tags["place"])
points = positions(coords)
lngs, lats = points.map { |p| p.first(2) }.transpose
bbox = [lngs.min, lats.min, lngs.max, lats.max]
# A label point that's actually on the thing: the middle vertex of a
# line (a curved street's bbox center can be off the street), the
# bbox center of an area.
lon, lat = geometry["type"] == "LineString" ? points[points.size / 2] : [(bbox[0] + bbox[2]) / 2, (bbox[1] + bbox[3]) / 2]
value = tags[key].to_s
kind = if key == "highway" && geometry["type"] != "Point" then "street"
else value.tr("_", " ")
end
importance = key == "place" ? PLACE_RANK.fetch(value, KEY_RANK["place"]) : KEY_RANK[key]
extra = [(name.delete(APOSTROPHES) if name.count(APOSTROPHES).positive?), tags["brand"]].compact.uniq - [name]
[name, extra.join(" "), kind, importance, lon, lat, JSON.generate(bbox)]
end
def self.positions(coords)
coords.first.is_a?(Numeric) ? [coords] : coords.flat_map { |c| positions(c) }
end
# words: already lowercased/diacritics-stripped (Search.normalize);
# every one must match as a word prefix. Nearest to `center` ([lat,
# lng], the map's) first, settlements weighted closer (DISTANCE_WEIGHT);
# with no center, most important kinds first.
def self.search(db_path, words, center: nil, limit: 50)
match = words.map { |word| %("#{word.gsub('"', '""')}"*) }.join(" ")
order, params =
if center
weight = DISTANCE_WEIGHT.map { |importance, w| "WHEN #{importance} THEN #{w * w}" }.join(" ")
["((lat - ?) * (lat - ?) + (lon - ?) * (lon - ?)) * CASE importance #{weight} ELSE 1 END",
[center[0], center[0], center[1], center[1]]]
else
["importance, rank", []]
end
db = SQLite3::Database.new(db_path, readonly: true)
db.execute("SELECT name, kind, bbox, importance FROM places WHERE places MATCH ? ORDER BY #{order} LIMIT ?", [match, *params, limit])
.map { |name, kind, bbox, importance| { name: name, kind: kind, bbox: JSON.parse(bbox), importance: importance } }
rescue SQLite3::Exception
[]
ensure
db&.close
end
def self.run!(*args)
stdout, stderr, status = Open3.capture3(*args)
raise ExtractError, "#{args.first} exited with status #{status.exitstatus}: #{[stdout, stderr].map(&:strip).reject(&:empty?).join("\n")}" unless status.success?
rescue Errno::ENOENT, Errno::EACCES => e
raise ExtractError, "could not run '#{args.first}' (#{e.message}) — is osmium-tool installed and on PATH?"
end
private_class_method :run!
end
end
+49 -9
View File
@@ -1,5 +1,6 @@
require "json" require "json"
require "open3" require "open3"
require "fileutils"
module Maptool module Maptool
# Runs an external "importer" script that turns a bbox into a GeoJSON # Runs an external "importer" script that turns a bbox into a GeoJSON
@@ -33,26 +34,64 @@ module Maptool
Dir.glob(File.join(dir, "*", "plugin.json")).filter_map do |manifest_path| Dir.glob(File.join(dir, "*", "plugin.json")).filter_map do |manifest_path|
name = File.basename(File.dirname(manifest_path)) name = File.basename(File.dirname(manifest_path))
manifest = JSON.parse(File.read(manifest_path)) manifest = JSON.parse(File.read(manifest_path))
{ "name" => name, "label" => manifest["label"] || name } { "name" => name, "label" => manifest["label"] || name, "route" => manifest["route"] == true,
"settings" => setting_fields(manifest) }
rescue JSON::ParserError rescue JSON::ParserError
nil nil
end end
end.uniq { |plugin| plugin["name"] }.sort_by { |p| p["label"] } end.uniq { |plugin| plugin["name"] }.sort_by { |p| p["label"] }
end end
# bbox: [south, west, north, east]. Raises RunError with a short # The settings a plugin asks for in its plugin.json ("settings": [{"key":
# "P4N_COOKIE", "label": "…", "help": "…"}]) — a login cookie, a key —
# set in the panel, kept server-side (never sent back to a browser) and
# handed to the plugin's command as environment variables. A key is an
# env var name; anything else in the list is ignored.
SETTING_KEY = /\A[A-Z][A-Z0-9_]*\z/
def self.setting_fields(manifest)
Array(manifest["settings"]).select { |f| f.is_a?(Hash) && f["key"].to_s =~ SETTING_KEY }
.map { |f| f.slice("key", "label", "help") }
end
# Saved settings: { name => { KEY => value } } in one JSON file (mode 600).
def self.saved_settings(path)
File.file?(path) ? JSON.parse(File.read(path)) : {}
rescue JSON::ParserError
{}
end
# Sets (or, empty, clears) the plugin's declared keys only.
def self.save_settings(path, dirs, name, values)
plugin_dir = find(dirs, name)
fields = setting_fields(JSON.parse(File.read(File.join(plugin_dir, "plugin.json")))).map { |f| f["key"] }
all = saved_settings(path)
mine = (all[name] || {}).merge(values.to_h.slice(*fields).transform_values { |v| v.to_s.strip })
all[name] = mine.reject { |_, v| v.empty? }
FileUtils.mkdir_p(File.dirname(path))
File.write("#{path}.part", JSON.generate(all), perm: 0o600)
File.rename("#{path}.part", path)
all[name].keys
end
def self.find(dirs, name)
raise RunError, "unknown plugin" unless name =~ NAME_PATTERN
Array(dirs).map { |dir| File.join(dir, name) }.find { |dir| File.file?(File.join(dir, "plugin.json")) } or raise RunError, "unknown plugin"
end
# bbox: [south, west, north, east]. With route (a GeoJSON file's path,
# the trip's route) and corridor_km, a plugin with "route": true in its
# plugin.json also gets --route=<path> --corridor-km=<km> (the bbox is
# then the corridor's). env: its saved settings. Raises RunError with a short
# message on anything that isn't a clean run — an unknown plugin, a # message on anything that isn't a clean run — an unknown plugin, a
# non-zero exit, or output that isn't a GeoJSON FeatureCollection — so # non-zero exit, or output that isn't a GeoJSON FeatureCollection — so
# the route can turn it into a single error response without knowing # the route can turn it into a single error response without knowing
# any of these details itself. When the same name exists under more # any of these details itself. When the same name exists under more
# than one of `dirs`, the first one that has it wins — same precedence # than one of `dirs`, the first one that has it wins — same precedence
# as list's `uniq` above. # as list's `uniq` above.
def self.run(dirs, name, bbox) def self.run(dirs, name, bbox, route: nil, corridor_km: nil, env: {})
raise RunError, "unknown plugin" unless name =~ NAME_PATTERN plugin_dir = find(dirs, name)
plugin_dir = Array(dirs).map { |dir| File.join(dir, name) }.find { |dir| File.file?(File.join(dir, "plugin.json")) }
raise RunError, "unknown plugin" unless plugin_dir
manifest_path = File.join(plugin_dir, "plugin.json") manifest_path = File.join(plugin_dir, "plugin.json")
command = begin command = begin
@@ -64,8 +103,9 @@ module Maptool
south, west, north, east = bbox south, west, north, east = bbox
args = ["--south=#{south}", "--west=#{west}", "--north=#{north}", "--east=#{east}"] args = ["--south=#{south}", "--west=#{west}", "--north=#{north}", "--east=#{east}"]
args += ["--route=#{route}", "--corridor-km=#{corridor_km}"] if route
stdout, stderr, status = Open3.capture3(command, *args, chdir: plugin_dir) stdout, stderr, status = Open3.capture3(env.to_h, command, *args, chdir: plugin_dir)
# First stderr line too — for a Ruby plugin that's the exception # First stderr line too — for a Ruby plugin that's the exception
# message (e.g. "...: unexpected response 406"), the only clue to why. # message (e.g. "...: unexpected response 406"), the only clue to why.
unless status.success? unless status.success?
+236 -83
View File
@@ -6,11 +6,12 @@ require "tmpdir"
require "fileutils" require "fileutils"
require "etc" require "etc"
require_relative "hiking_trails" require_relative "hiking_trails"
require_relative "places"
module Maptool module Maptool
# Regenerates data/offline.pmtiles and data/terrain.pmtiles for the # Regenerates data/offline.pmtiles and data/terrain.pmtiles for the
# currently *selected* regions (data/offline_regions.json, an array of # currently *selected* regions (data/offline_regions.json, an array of
# Natural Earth iso_a2 country codes — see available_regions/ # region codes from REGIONS_FILE — see available_regions/
# selected_regions/set_selected_regions below). No job queue: each build # selected_regions/set_selected_regions below). No job queue: each build
# runs on its own background Thread and reports into a Mutex-guarded # runs on its own background Thread and reports into a Mutex-guarded
# status Hash a route can poll, the same shape app.rb's own GNSS poller # status Hash a route can poll, the same shape app.rb's own GNSS poller
@@ -18,73 +19,23 @@ module Maptool
module PmtilesBuilder module PmtilesBuilder
class BuildError < StandardError; end class BuildError < StandardError; end
# Natural Earth (public domain, no attribution required) 110m admin-0 # Every region the offline map can be built from: Geofabrik's own index
# countries, filtered to Europe and trimmed to name/iso_a2/iso_a3 — # (download.geofabrik.de/index-v1.json), trimmed by
# see the plan this was built from for the exact filter. 110m is # bin/geofabrik-regions-sync.mjs to the countries per continent plus one
# deliberately coarse (a km or so of border precision, not # level of subregions (US states, German Länder, ...). Each feature has a
# survey-grade) — fine for "which country to grab," a same-schema swap # code (a country's ISO 3166-1 alpha-2 — the codes the old Europe-only
# to Natural Earth's 50m/10m cut if that ever needs to be tighter. # list used, so caches/selections carry over — a subregion's ISO 3166-2
REGIONS_FILE = File.join(__dir__, "data", "europe_countries.geojson") # code or <country>-<id>, else the Geofabrik id), its name, its Geofabrik
# path (https://download.geofabrik.de/<slug>-latest.osm.pbf), continent,
# Every iso_a2 code in REGIONS_FILE mapped to its Geofabrik download # parent country for a subregion, and its boundary polygon (Geofabrik's
# slug (https://download.geofabrik.de/<slug>-latest.osm.pbf) — Geofabrik # own clip polygon — what terrain extraction clips to).
# names regions, not ISO codes, and doesn't always split the way a REGIONS_FILE = File.join(__dir__, "data", "geofabrik_regions.geojson")
# country border does, so this table exists rather than deriving the
# slug from the country name. Two known quirks worth knowing about,
# not worth working around:
# - RU has no "europe/" prefix (Russia is its own top-level index,
# and unlike every other entry here is a single ~4GB file covering
# the whole country rather than a European-only slice).
# - GB's "great-britain" slug is England/Scotland/Wales only —
# Northern Ireland lives in "ireland-and-northern-ireland" instead
# (bundled with IE, not GB). Selecting GB alone won't include NI.
GEOFABRIK_SLUGS = {
"AL" => "europe/albania",
"AT" => "europe/austria",
"BY" => "europe/belarus",
"BE" => "europe/belgium",
"BA" => "europe/bosnia-herzegovina",
"BG" => "europe/bulgaria",
"HR" => "europe/croatia",
"CZ" => "europe/czech-republic",
"DK" => "europe/denmark",
"EE" => "europe/estonia",
"FI" => "europe/finland",
"FR" => "europe/france",
"DE" => "europe/germany",
"GR" => "europe/greece",
"HU" => "europe/hungary",
"IS" => "europe/iceland",
"IE" => "europe/ireland-and-northern-ireland",
"IT" => "europe/italy",
"XK" => "europe/kosovo",
"LV" => "europe/latvia",
"LT" => "europe/lithuania",
"LU" => "europe/luxembourg",
"MD" => "europe/moldova",
"ME" => "europe/montenegro",
"NL" => "europe/netherlands",
"MK" => "europe/macedonia",
"NO" => "europe/norway",
"PL" => "europe/poland",
"PT" => "europe/portugal",
"RO" => "europe/romania",
"RU" => "russia",
"RS" => "europe/serbia",
"SK" => "europe/slovakia",
"SI" => "europe/slovenia",
"ES" => "europe/spain",
"SE" => "europe/sweden",
"CH" => "europe/switzerland",
"UA" => "europe/ukraine",
"GB" => "europe/great-britain",
}.freeze
# Mapterhorn (a Protomaps-affiliated project) publishes Terrarium- # Mapterhorn (a Protomaps-affiliated project) publishes Terrarium-
# encoded terrain as pre-built PMTiles archives: one global # encoded terrain as pre-built PMTiles archives: one global
# planet.pmtiles (z0-12) plus ~450 regional chunks (z13 up to a # planet.pmtiles (z0-12) plus ~450 regional chunks (z13 up to a
# per-region max, 13-18) — extract_offline below no longer touches # per-region max, 13-18) — extract_offline below no longer touches
# Protomaps at all (see GEOFABRIK_SLUGS above), but terrain stays on # Protomaps at all (Geofabrik extracts, see REGIONS_FILE), but terrain stays on
# this same "extract only the region's byte ranges from a remote # this same "extract only the region's byte ranges from a remote
# archive" story via go-pmtiles, unrelated to the basemap swap. # archive" story via go-pmtiles, unrelated to the basemap swap.
MAPTERHORN_MANIFEST_URL = "https://download.mapterhorn.com/download_urls.json" MAPTERHORN_MANIFEST_URL = "https://download.mapterhorn.com/download_urls.json"
@@ -105,26 +56,81 @@ module Maptool
TERRAIN_MUTEX = Mutex.new TERRAIN_MUTEX = Mutex.new
def self.offline_status def self.offline_status
OFFLINE_MUTEX.synchronize { OFFLINE_STATUS.dup } OFFLINE_MUTEX.synchronize { with_live_timings(OFFLINE_STATUS) }
end end
def self.terrain_status def self.terrain_status
TERRAIN_MUTEX.synchronize { TERRAIN_STATUS.dup } TERRAIN_MUTEX.synchronize { with_live_timings(TERRAIN_STATUS) }
end end
# While running, status[:steps] holds raw [label, monotonic start]
# pairs — rendered here into per-step seconds, the running one counting
# up, so the debug panel shows where a build is spending its time.
def self.with_live_timings(status)
copy = status.dup
steps = copy.delete(:steps)
copy[:timings] = step_durations(steps, monotonic_now) if steps
copy
end
private_class_method :with_live_timings
# --- build history ("benchmark") ---
# One JSON line per finished build (offline or terrain, done or error)
# with per-step timings — a record to compare later builds against,
# e.g. after tuning Planetiler's JVM heap. Kept across redeploys since
# it lives in data/.
def self.build_history_path(data_dir)
File.join(data_dir, "build_history.jsonl")
end
# Newest first.
def self.build_history(data_dir, limit: 50)
path = build_history_path(data_dir)
return [] unless File.exist?(path)
File.readlines(path).last(limit).reverse.filter_map do |line|
JSON.parse(line)
rescue JSON::ParserError
nil
end
end
def self.monotonic_now
Process.clock_gettime(Process::CLOCK_MONOTONIC)
end
private_class_method :monotonic_now
def self.step_durations(steps, finished)
steps.each_with_index.map do |(label, started), i|
{ step: label, seconds: ((steps[i + 1]&.last || finished) - started).round(1) }
end
end
private_class_method :step_durations
# Test-only: the status hashes are process-wide state (same caveat as # Test-only: the status hashes are process-wide state (same caveat as
# GPX_STORE/LIVETRACK_STORE in app.rb), so the suite needs a way to # GPX_STORE/LIVETRACK_STORE in app.rb), so the suite needs a way to
# reset them between tests the way AppTestHelper#teardown already does # reset them between tests the way AppTestHelper#teardown already does
# for those. # for those.
def self.reset! def self.reset!
OFFLINE_MUTEX.synchronize { OFFLINE_STATUS.replace(state: "idle") } OFFLINE_MUTEX.synchronize { OFFLINE_STATUS.replace(state: "idle") }
@fetching_extracts = false
TERRAIN_MUTEX.synchronize { TERRAIN_STATUS.replace(state: "idle") } TERRAIN_MUTEX.synchronize { TERRAIN_STATUS.replace(state: "idle") }
end end
# --- region selection --- # --- region selection ---
# [{code:, name:, continent:, parent:}] — parent is nil for a country.
def self.available_regions def self.available_regions
region_features.map { |f| { code: f["properties"]["iso_a2"], name: f["properties"]["name"] } }.sort_by { |r| r[:name] } region_features.map do |f|
p = f["properties"]
{ code: p["code"], name: p["name"], continent: p["continent"], parent: p["parent"] }
end.sort_by { |r| r[:name] }
end
# [{id:, name:}] in the picker's order.
def self.continents
region_catalog["continents"]
end end
def self.selected_regions(data_dir) def self.selected_regions(data_dir)
@@ -148,11 +154,21 @@ module Maptool
end end
private_class_method :selected_regions_path private_class_method :selected_regions_path
def self.region_catalog
@region_catalog ||= JSON.parse(File.read(REGIONS_FILE))
end
private_class_method :region_catalog
def self.region_features def self.region_features
@region_features ||= JSON.parse(File.read(REGIONS_FILE))["features"] region_catalog["features"]
end end
private_class_method :region_features private_class_method :region_features
def self.geofabrik_slug(code)
region_features.find { |f| f["properties"]["code"] == code }&.dig("properties", "slug")
end
private_class_method :geofabrik_slug
# Still used by terrain (below) to compute the aggregate bbox Mapterhorn # Still used by terrain (below) to compute the aggregate bbox Mapterhorn
# chunk intersection needs — offline.pmtiles no longer needs this at # chunk intersection needs — offline.pmtiles no longer needs this at
# all, since each Geofabrik country file is already clipped to that # all, since each Geofabrik country file is already clipped to that
@@ -160,7 +176,7 @@ module Maptool
# less), so there's no separate "--region=" precision step for it # less), so there's no separate "--region=" precision step for it
# anymore. # anymore.
def self.region_bbox(codes) def self.region_bbox(codes)
selected = region_features.select { |f| codes.include?(f["properties"]["iso_a2"]) } selected = region_features.select { |f| codes.include?(f["properties"]["code"]) }
raise BuildError, "no matching regions for #{codes.join(", ")}" if selected.empty? raise BuildError, "no matching regions for #{codes.join(", ")}" if selected.empty?
coords = selected.flat_map { |f| ring_coordinates(f["geometry"]) } coords = selected.flat_map { |f| ring_coordinates(f["geometry"]) }
@@ -170,6 +186,14 @@ module Maptool
end end
private_class_method :region_bbox private_class_method :region_bbox
# [west, south, east, north] of one region, nil for an unknown code.
def self.country_bbox(code)
south, west, north, east = region_bbox([code])
[west, south, east, north]
rescue BuildError
nil
end
def self.ring_coordinates(geometry) def self.ring_coordinates(geometry)
case geometry["type"] case geometry["type"]
when "Polygon" then geometry["coordinates"].flatten(1) when "Polygon" then geometry["coordinates"].flatten(1)
@@ -195,13 +219,30 @@ module Maptool
raise BuildError, "select at least one region first" if codes.empty? raise BuildError, "select at least one region first" if codes.empty?
begin_run!(OFFLINE_MUTEX, OFFLINE_STATUS) begin_run!(OFFLINE_MUTEX, OFFLINE_STATUS)
@fetching_extracts = true
Thread.new do Thread.new do
run_job(OFFLINE_MUTEX, OFFLINE_STATUS) do |report_step| run_job(OFFLINE_MUTEX, OFFLINE_STATUS, kind: "offline", data_dir: data_dir, regions: codes) do |report_step|
extract_offline(codes, data_dir, download_extract, fetch_last_modified, report_step) extract_offline(codes, data_dir, download_extract, fetch_last_modified, report_step)
end end
extracts_ready(data_dir) # no-op unless the build failed before its extracts were in
end end
end end
# True while an offline build may still be replacing the extracts that
# a routing build reads; Planetiler afterwards doesn't touch them.
def self.fetching_extracts?
@fetching_extracts
end
# A routing build requested meanwhile waited for these extracts.
def self.extracts_ready(data_dir)
return unless @fetching_extracts
@fetching_extracts = false
Routing.extracts_ready(data_dir) if defined?(Routing)
end
private_class_method :extracts_ready
# fetch_manifest: same injectable-seam reasoning as download_extract # fetch_manifest: same injectable-seam reasoning as download_extract
# above, for the one Mapterhorn manifest lookup this needs. # above, for the one Mapterhorn manifest lookup this needs.
def self.build_terrain(data_dir:, fetch_manifest: method(:fetch_mapterhorn_manifest)) def self.build_terrain(data_dir:, fetch_manifest: method(:fetch_mapterhorn_manifest))
@@ -210,7 +251,7 @@ module Maptool
begin_run!(TERRAIN_MUTEX, TERRAIN_STATUS) begin_run!(TERRAIN_MUTEX, TERRAIN_STATUS)
Thread.new do Thread.new do
run_job(TERRAIN_MUTEX, TERRAIN_STATUS) do |report_step| run_job(TERRAIN_MUTEX, TERRAIN_STATUS, kind: "terrain", data_dir: data_dir, regions: codes) do |report_step|
build_terrain_pmtiles(codes, data_dir, fetch_manifest, report_step) build_terrain_pmtiles(codes, data_dir, fetch_manifest, report_step)
end end
end end
@@ -229,15 +270,44 @@ module Maptool
# SK (1/2)", "tiling with planetiler", ...) — surfaced as status[:step] # SK (1/2)", "tiling with planetiler", ...) — surfaced as status[:step]
# so GET .../build-status can show progress beyond just "running since # so GET .../build-status can show progress beyond just "running since
# X" (see docs/development.adoc). # X" (see docs/development.adoc).
def self.run_job(mutex, status) #
report_step = ->(text) { mutex.synchronize { status[:step] = text } } # Each step's wall time is recorded too (label without its "— done: …"
yield report_step # progress suffix) and the whole run appended to the build history
# above. The block may return { log: "..." } — Planetiler's own closing
# summary, with its per-phase breakdown — to keep alongside.
def self.run_job(mutex, status, kind:, data_dir:, regions:)
started = monotonic_now
steps = []
report_step = lambda do |text|
mutex.synchronize do
steps << [text.split(" — ").first, monotonic_now]
status[:step] = text
status[:steps] = steps
end
end
result = yield report_step
mutex.synchronize { status.merge!(state: "done", finished_at: Time.now.utc.iso8601).delete(:message) } mutex.synchronize { status.merge!(state: "done", finished_at: Time.now.utc.iso8601).delete(:message) }
rescue => e rescue => e
mutex.synchronize { status.merge!(state: "error", finished_at: Time.now.utc.iso8601, message: e.message) } mutex.synchronize { status.merge!(state: "error", finished_at: Time.now.utc.iso8601, message: e.message) }
ensure ensure
mutex.synchronize { status.delete(:step) } mutex.synchronize do
status.delete(:step)
status.delete(:steps)
finished = monotonic_now
status[:timings] = step_durations(steps, finished)
status[:total_seconds] = (finished - started).round(1)
record_build(data_dir, kind: kind, regions: regions, status: status, log: result.is_a?(Hash) ? result[:log] : nil)
end
end end
def self.record_build(data_dir, kind:, regions:, status:, log:)
entry = { kind: kind, regions: regions, threads: Etc.nprocessors, log: log }
.merge(status.slice(:state, :started_at, :finished_at, :total_seconds, :timings, :message)).compact
File.open(build_history_path(data_dir), "a") { |f| f.puts(JSON.generate(entry)) }
rescue SystemCallError
nil # a history write failing must never turn a finished build into an error
end
private_class_method :record_build
private_class_method :run_job private_class_method :run_job
# --- offline.pmtiles --- # --- offline.pmtiles ---
@@ -253,10 +323,11 @@ module Maptool
def self.extract_offline(codes, data_dir, download_extract, fetch_last_modified, report_step) def self.extract_offline(codes, data_dir, download_extract, fetch_last_modified, report_step)
scratch_dir = Dir.mktmpdir("maptool-offline") scratch_dir = Dir.mktmpdir("maptool-offline")
sources = codes.each_with_index.map do |code, i| sources = codes.each_with_index.map do |code, i|
slug = GEOFABRIK_SLUGS.fetch(code) { raise BuildError, "no Geofabrik source known for region #{code}" } slug = geofabrik_slug(code) or raise BuildError, "no Geofabrik source known for region #{code}"
report_step.call(progress_step("fetching #{code}", codes, i)) report_step.call(progress_step("fetching #{code}", codes, i))
cached_extract(code, slug, data_dir, download_extract, fetch_last_modified) cached_extract(code, slug, data_dir, download_extract, fetch_last_modified)
end end
extracts_ready(data_dir)
osm_path = osm_path =
if sources.size == 1 if sources.size == 1
@@ -287,12 +358,15 @@ module Maptool
# leaving most of a many-core host idle — Etc.nprocessors asks the # leaving most of a many-core host idle — Etc.nprocessors asks the
# OS directly (sched_getaffinity on Linux), which correctly reflects # OS directly (sched_getaffinity on Linux), which correctly reflects
# whatever's actually usable by this process even under a container. # whatever's actually usable by this process even under a container.
run_planetiler!("--osm-path=#{osm_path}", "--output=#{tmp_path}", "--download", "--threads=#{Etc.nprocessors}") planetiler_log = run_planetiler!("--osm-path=#{osm_path}", "--output=#{tmp_path}", "--download", "--threads=#{Etc.nprocessors}")
File.rename(tmp_path, File.join(data_dir, "offline.pmtiles")) File.rename(tmp_path, File.join(data_dir, "offline.pmtiles"))
File.write(offline_meta_path(data_dir), JSON.generate(sources: sources.map { |s| s.slice("code", "slug", "last_modified") })) File.write(offline_meta_path(data_dir), JSON.generate(sources: sources.map { |s| s.slice("code", "slug", "last_modified") }))
report_step.call("extracting hiking trails") report_step.call("extracting hiking trails")
extract_hiking_trails(sources, data_dir) extract_hiking_trails(sources, data_dir)
report_step.call("indexing places")
extract_places(sources, data_dir)
{ log: planetiler_log }
ensure ensure
FileUtils.remove_entry(scratch_dir) if scratch_dir && Dir.exist?(scratch_dir) FileUtils.remove_entry(scratch_dir) if scratch_dir && Dir.exist?(scratch_dir)
File.delete(tmp_path) if tmp_path && File.exist?(tmp_path) File.delete(tmp_path) if tmp_path && File.exist?(tmp_path)
@@ -320,7 +394,7 @@ module Maptool
FileUtils.mkdir_p(hiking_trails_dir(data_dir)) FileUtils.mkdir_p(hiking_trails_dir(data_dir))
sources.each do |source| sources.each do |source|
out_path = hiking_trails_country_path(data_dir, source["code"]) out_path = hiking_trails_country_path(data_dir, source["code"])
next if File.exist?(out_path) && File.mtime(out_path) >= File.mtime(source["path"]) next if File.exist?(out_path) && File.mtime(out_path) >= File.mtime(source["path"]) && HikingTrails.current?(out_path)
tmp_path = "#{out_path}.tmp" tmp_path = "#{out_path}.tmp"
begin begin
@@ -334,6 +408,50 @@ module Maptool
end end
private_class_method :extract_hiking_trails private_class_method :extract_hiking_trails
# The place-name search index (Places), one SQLite file per country —
# same per-country, cached-by-mtime, best-effort story as hiking trails
# above, from the same PBFs.
def self.extract_places(sources, data_dir)
FileUtils.mkdir_p(places_dir(data_dir))
sources.each do |source|
out_path = places_country_path(data_dir, source["code"])
next if File.exist?(out_path) && File.mtime(out_path) >= File.mtime(source["path"]) && Places.current?(out_path)
tmp_path = "#{out_path}.tmp"
begin
Places.extract(source["path"], tmp_path)
File.rename(tmp_path, out_path)
rescue Places::ExtractError, SQLite3::Exception => e
File.delete(tmp_path) if File.exist?(tmp_path)
warn "places index failed for #{source["code"]}, skipping: #{e.message}"
end
end
end
private_class_method :extract_places
# Same, for every already-downloaded country, without a whole offline
# build — `rake places:index`, e.g. right after this index was added
# and offline.pmtiles itself was already up to date.
def self.index_cached_places(data_dir)
sources = cached_extracts(data_dir).map do |extract|
extract.merge("path" => File.join(geofabrik_cache_dir(data_dir), "#{extract["code"]}.osm.pbf"))
end
extract_places(sources, data_dir)
places_countries(data_dir)
end
def self.places_dir(data_dir)
File.join(data_dir, "places")
end
def self.places_country_path(data_dir, code)
File.join(places_dir(data_dir), "#{code}.sqlite")
end
def self.places_countries(data_dir)
Dir.glob(File.join(places_dir(data_dir), "*.sqlite")).map { |path| File.basename(path, ".sqlite") }.sort
end
def self.hiking_trails_dir(data_dir) def self.hiking_trails_dir(data_dir)
File.join(data_dir, "hiking_trails") File.join(data_dir, "hiking_trails")
end end
@@ -412,18 +530,37 @@ module Maptool
# meta / update-check below. Geofabrik 302s (e.g. .../europe/austria # meta / update-check below. Geofabrik 302s (e.g. .../europe/austria
# redirecting to wherever actually serves it) — followed manually # redirecting to wherever actually serves it) — followed manually
# since request_get's block form doesn't do this itself. # since request_get's block form doesn't do this itself.
def self.download_extract(url, dest, limit: 5) # Geofabrik's mirrors stall now and then (Net::ReadTimeout after 60 s
# without a byte); a stall shouldn't fail an hour-long build, so the
# download starts over a few times before giving up.
# ponytail: restarts from zero, add a Range resume if multi-GB extracts keep stalling.
NETWORK_ERRORS = [Net::OpenTimeout, Net::ReadTimeout, EOFError, IOError, SocketError, SystemCallError, OpenSSL::SSL::SSLError].freeze
DOWNLOAD_ATTEMPTS = 3
def self.download_extract(url, dest, limit: 5, attempt: 1)
raise BuildError, "too many redirects downloading #{url}" if limit.zero? raise BuildError, "too many redirects downloading #{url}" if limit.zero?
uri = URI(url) uri = URI(url)
last_modified = nil last_modified = nil
redirect_to = nil redirect_to = nil
Net::HTTP.start(uri.host, uri.port, use_ssl: uri.scheme == "https") do |http| Net::HTTP.start(uri.host, uri.port, use_ssl: uri.scheme == "https", read_timeout: 120) do |http|
# Net::HTTP's default (true) quietly accepts a body cut short of
# its Content-Length; a dropped connection must fail the download.
http.ignore_eof = false
http.request_get(uri) do |response| http.request_get(uri) do |response|
case response case response
when Net::HTTPSuccess when Net::HTTPSuccess
last_modified = response["last-modified"] last_modified = response["last-modified"]
File.open(dest, "wb") { |file| response.read_body { |chunk| file.write(chunk) } } # Into a .part file renamed at the end: an interrupted download
# never leaves a truncated extract behind its old stamp, and a
# routing build that hard-linked the old file keeps reading
# that complete old file (see docs/routing-design.adoc).
begin
File.open("#{dest}.part", "wb") { |file| response.read_body { |chunk| file.write(chunk) } }
File.rename("#{dest}.part", dest)
ensure
FileUtils.rm_f("#{dest}.part")
end
when Net::HTTPRedirection when Net::HTTPRedirection
redirect_to = URI.join(url, response["location"]).to_s redirect_to = URI.join(url, response["location"]).to_s
else else
@@ -434,6 +571,11 @@ module Maptool
return download_extract(redirect_to, dest, limit: limit - 1) if redirect_to return download_extract(redirect_to, dest, limit: limit - 1) if redirect_to
last_modified last_modified
rescue *NETWORK_ERRORS => e
raise BuildError, "downloading #{url} failed #{attempt}× (#{e.class})" if attempt >= DOWNLOAD_ATTEMPTS
sleep 10 * attempt
download_extract(url, dest, limit: limit, attempt: attempt + 1)
end end
# Sidecar recording which Geofabrik sources (country code, slug, and # Sidecar recording which Geofabrik sources (country code, slug, and
@@ -460,7 +602,7 @@ module Maptool
return nil if codes.empty? return nil if codes.empty?
current = codes.map do |code| current = codes.map do |code|
slug = GEOFABRIK_SLUGS[code] slug = geofabrik_slug(code)
return nil unless slug return nil unless slug
{ "code" => code, "last_modified" => fetch_last_modified.call(geofabrik_url(slug)) } { "code" => code, "last_modified" => fetch_last_modified.call(geofabrik_url(slug)) }
@@ -475,7 +617,11 @@ module Maptool
raise BuildError, "too many redirects reaching #{url}" if limit.zero? raise BuildError, "too many redirects reaching #{url}" if limit.zero?
uri = URI(url) uri = URI(url)
response = Net::HTTP.start(uri.host, uri.port, use_ssl: uri.scheme == "https") { |http| http.head(uri) } response = begin
Net::HTTP.start(uri.host, uri.port, use_ssl: uri.scheme == "https") { |http| http.head(uri) }
rescue *NETWORK_ERRORS => e
raise BuildError, "could not reach #{url} (#{e.class})"
end
case response case response
when Net::HTTPSuccess then response["last-modified"] when Net::HTTPSuccess then response["last-modified"]
when Net::HTTPRedirection then fetch_geofabrik_last_modified(URI.join(url, response["location"]).to_s, limit: limit - 1) when Net::HTTPRedirection then fetch_geofabrik_last_modified(URI.join(url, response["location"]).to_s, limit: limit - 1)
@@ -498,6 +644,7 @@ module Maptool
File.delete(File.join(data_dir, "offline.pmtiles")) if File.exist?(File.join(data_dir, "offline.pmtiles")) File.delete(File.join(data_dir, "offline.pmtiles")) if File.exist?(File.join(data_dir, "offline.pmtiles"))
File.delete(offline_meta_path(data_dir)) if File.exist?(offline_meta_path(data_dir)) File.delete(offline_meta_path(data_dir)) if File.exist?(offline_meta_path(data_dir))
FileUtils.remove_entry(hiking_trails_dir(data_dir)) if Dir.exist?(hiking_trails_dir(data_dir)) FileUtils.remove_entry(hiking_trails_dir(data_dir)) if Dir.exist?(hiking_trails_dir(data_dir))
FileUtils.remove_entry(places_dir(data_dir)) if Dir.exist?(places_dir(data_dir))
cache_dir = geofabrik_cache_dir(data_dir) cache_dir = geofabrik_cache_dir(data_dir)
FileUtils.remove_entry(cache_dir) if Dir.exist?(cache_dir) FileUtils.remove_entry(cache_dir) if Dir.exist?(cache_dir)
end end
@@ -508,6 +655,8 @@ module Maptool
def self.delete_cached_extract(data_dir, code) def self.delete_cached_extract(data_dir, code)
OFFLINE_MUTEX.synchronize { raise BuildError, "a build is already running" if OFFLINE_STATUS[:state] == "running" } OFFLINE_MUTEX.synchronize { raise BuildError, "a build is already running" if OFFLINE_STATUS[:state] == "running" }
raise BuildError, "unknown region #{code}" unless geofabrik_slug(code)
cache_dir = geofabrik_cache_dir(data_dir) cache_dir = geofabrik_cache_dir(data_dir)
path = File.join(cache_dir, "#{code}.osm.pbf") path = File.join(cache_dir, "#{code}.osm.pbf")
File.delete(path) if File.exist?(path) File.delete(path) if File.exist?(path)
@@ -559,7 +708,7 @@ module Maptool
scratch_dir = Dir.mktmpdir("maptool-terrain") scratch_dir = Dir.mktmpdir("maptool-terrain")
south, west, north, east = region_bbox(codes) south, west, north, east = region_bbox(codes)
region_path = File.join(scratch_dir, "region.geojson") region_path = File.join(scratch_dir, "region.geojson")
selected = region_features.select { |f| codes.include?(f["properties"]["iso_a2"]) } selected = region_features.select { |f| codes.include?(f["properties"]["code"]) }
File.write(region_path, JSON.generate(type: "FeatureCollection", features: selected)) File.write(region_path, JSON.generate(type: "FeatureCollection", features: selected))
chunks = items.select { |item| item["name"] != MAPTERHORN_PLANET_NAME && bbox_intersects?(item, south, west, north, east) } chunks = items.select { |item| item["name"] != MAPTERHORN_PLANET_NAME && bbox_intersects?(item, south, west, north, east) }
@@ -734,9 +883,13 @@ module Maptool
end end
private_class_method :run_osmium! private_class_method :run_osmium!
# Returns the output's tail — on success that's Planetiler's closing
# summary (per-phase times, memory), kept in the build history.
def self.run_planetiler!(*args) def self.run_planetiler!(*args)
stdout, stderr, status = Open3.capture3(java_bin, "-jar", planetiler_jar, *args) stdout, stderr, status = Open3.capture3(java_bin, "-jar", planetiler_jar, *args)
raise BuildError, "planetiler exited with status #{status.exitstatus}: #{command_output(stdout, stderr)}" unless status.success? raise BuildError, "planetiler exited with status #{status.exitstatus}: #{command_output(stdout, stderr)}" unless status.success?
command_output(stdout, stderr)
rescue Errno::ENOENT, Errno::EACCES => e rescue Errno::ENOENT, Errno::EACCES => e
raise BuildError, "could not run '#{java_bin} -jar #{planetiler_jar}' (#{e.message}) — is Java and planetiler.jar installed? See docs/development.adoc." raise BuildError, "could not run '#{java_bin} -jar #{planetiler_jar}' (#{e.message}) — is Java and planetiler.jar installed? See docs/development.adoc."
end end
+517
View File
@@ -0,0 +1,517 @@
require "fileutils"
require "json"
require "net/http"
require "open3"
require "time"
require_relative "pmtiles_builder"
module Maptool
# maptool's side of offline routing (docs/routing-design.adoc). Valhalla
# runs in its own container (bin/routing-service.sh); the two talk
# through files in data/routing/: maptool writes build-request.json, the
# container writes status.json, built.json and tiles.tar.
module Routing
SERVICE_SCRIPT = File.expand_path("../../bin/routing-service.sh", __dir__)
MUTEX = Mutex.new
@pending = false
@merging = nil # status while osmium merges the extracts, then nil (or the error)
def self.dir(data_dir)
File.join(data_dir, "routing")
end
def self.tiles_path(data_dir)
File.join(dir(data_dir), "tiles.tar")
end
# At boot: the container runs whatever script is in data/routing/, so it
# always matches the deployed app.
def self.install_service_script(data_dir)
FileUtils.mkdir_p(dir(data_dir))
FileUtils.cp(SERVICE_SCRIPT, File.join(dir(data_dir), "service.sh"))
end
# Routing covers the offline map's selected countries. While an offline
# build is running (it may be downloading those very extracts), the
# request waits for its downloads — PmtilesBuilder calls extracts_ready.
def self.request_build(data_dir)
codes = PmtilesBuilder.selected_regions(data_dir)
raise PmtilesBuilder::BuildError, "select at least one region first" if codes.empty?
MUTEX.synchronize do
if PmtilesBuilder.fetching_extracts?
@pending = true
return
end
missing = codes.reject { |code| File.exist?(extract_path(data_dir, code)) }
raise PmtilesBuilder::BuildError, "no downloaded map data for #{missing.join(", ")}, build the offline map first" if missing.any?
# Apply again while the same countries are building: nothing to queue.
running = read_json(File.join(dir(data_dir), "staging", "request.json"))
return if running && running[:regions] == codes && running.key?(:pbf) == (codes.size > 1) && read_json(File.join(dir(data_dir), "status.json"))&.dig(:state) == "running"
return if @merging&.dig(:state) == "running"
@merging = nil
if codes.size == 1
write_request(data_dir, codes, nil)
else
@merging = { state: "running", step: "merging extracts with osmium", started_at: Time.now.utc.iso8601 }
Thread.new { merge_and_request(data_dir, codes) }
end
end
end
# Valhalla breaks on several overlapping country extracts (border ways
# in each: "Failed tile ... _M_range_check", valhalla#3925), so it gets
# one merged file. Its image has no osmium; this container does.
def self.merge_and_request(data_dir, codes)
merged = File.join(dir(data_dir), "merged.osm.pbf")
part = File.join(dir(data_dir), "merged.part.osm.pbf") # osmium picks the format by extension
inputs = codes.map { |code| extract_path(data_dir, code) }
stdout, stderr, status = Open3.capture3(PmtilesBuilder.osmium_bin, "merge", "-O", *inputs, "-o", part)
raise PmtilesBuilder::BuildError, "osmium merge failed: #{(stderr + stdout)[-2000..] || stderr + stdout}" unless status.success?
File.rename(part, merged)
MUTEX.synchronize do
write_request(data_dir, codes, "routing/merged.osm.pbf")
@merging = nil
end
rescue StandardError => e
FileUtils.rm_f(part)
MUTEX.synchronize { @merging = { state: "error", message: e.message, finished_at: Time.now.utc.iso8601 } }
end
private_class_method :merge_and_request
# pbf: the file to build from, relative to data/ (nil: the one extract).
def self.write_request(data_dir, codes, pbf)
write_json(File.join(dir(data_dir), "build-request.json"), { regions: codes, pbf: pbf, requested_at: Time.now.utc.iso8601 }.compact)
end
private_class_method :write_request
def self.extracts_ready(data_dir)
pending = MUTEX.synchronize { @pending.tap { @pending = false } }
request_build(data_dir) if pending
rescue PmtilesBuilder::BuildError
nil # the offline build failed to download something; its own row shows that
end
# The DataFileRow build-status shape (offline_data.js): state, step,
# started_at, message.
def self.build_status(data_dir)
pending, merging = MUTEX.synchronize { [@pending, @merging] }
return { state: "running", step: "waiting for the offline map downloads" } if pending
return merging if merging
status = read_json(File.join(dir(data_dir), "status.json"))
return status if status&.dig(:state) == "running" # the container is building; a queued request runs next
return { state: "running", step: "waiting for the routing container" } if File.exist?(File.join(dir(data_dir), "build-request.json"))
status || { state: "idle" }
end
# The DataFileRow status shape, plus whether Valhalla answers.
def self.tiles_status(data_dir, valhalla_url)
path = tiles_path(data_dir)
return { available: false } unless File.exist?(path)
built = read_json(File.join(dir(data_dir), "built.json")) || {}
{ available: true, size: File.size(path), mtime: File.mtime(path).utc.iso8601,
meta: { sources: (built[:regions] || []).map { |code| { code: code } }, serving: serving?(valhalla_url) } }
end
# nil = never built, true = other countries selected or a newer
# extract downloaded since, false = up to date.
def self.update_available?(data_dir)
path = tiles_path(data_dir)
return nil unless File.exist?(path)
built = (read_json(File.join(dir(data_dir), "built.json")) || {})[:regions] || []
codes = PmtilesBuilder.selected_regions(data_dir)
return true unless built.sort == codes.sort
codes.any? { |code| File.exist?(extract_path(data_dir, code)) && File.mtime(extract_path(data_dir, code)) > File.mtime(path) }
end
def self.serving?(valhalla_url)
return false if valhalla_url.to_s.empty?
uri = URI("#{valhalla_url}/status")
Net::HTTP.start(uri.host, uri.port, open_timeout: 1, read_timeout: 2) { |http| http.get(uri.path).is_a?(Net::HTTPSuccess) }
rescue StandardError
false
end
def self.extract_path(data_dir, code)
File.join(data_dir, "geofabrik_cache", "#{code}.osm.pbf")
end
private_class_method :extract_path
def self.read_json(path)
JSON.parse(File.read(path), symbolize_names: true)
rescue Errno::ENOENT, JSON::ParserError
nil
end
private_class_method :read_json
def self.write_json(path, data)
File.write("#{path}.tmp", JSON.generate(data))
File.rename("#{path}.tmp", path)
end
private_class_method :write_json
class RouteError < StandardError; end
class Unavailable < StandardError; end
# Profiles: a name, a type (car, bicycle, foot) and that type's
# settings, nil meaning Valhalla's default (no limit for a car's size).
# No type: a car.
# Stored for everyone, picked per browser (route.js).
DEFAULT_VEHICLES = [
{ id: "car", name: "Car" },
{ id: "camper", name: "Camper", height: 3.0, width: 2.3, length: 7.0, weight: 3.5 },
].freeze
ACTIVE_VEHICLES = [
{ id: "bike", name: "Bicycle", type: "bicycle", bicycle_type: "Hybrid" },
{ id: "mtb", name: "Mountain bike", type: "bicycle", bicycle_type: "Mountain" },
{ id: "run", name: "Run", type: "foot", speed: 10.0, sac: 2.0 },
{ id: "hike", name: "Hike", type: "foot", speed: 4.5, sac: 3.0 },
].freeze
TYPES = %w[car bicycle foot].freeze
# A car's fuel and emissions (low-emission zones) and what it has paid
# for: vignettes / toll units per country, until a date (YYYY-MM-DD).
FUELS = %w[petrol diesel lpg cng electric hybrid].freeze
EUROS = %w[3 4 5 6 6d].freeze
PAYMENT_KINDS = %w[vignette toll].freeze
BICYCLE_TYPES = %w[Road Hybrid Cross Mountain].freeze
# speed: km/h (bicycle, foot); hills: 0 avoid .. 1 seek (Valhalla's
# use_hills); sac: the hardest SAC hiking grade allowed on foot.
# wheelbase, track (m): the level gauge's geometry (drive_menus.js levelMenu).
VEHICLE_LIMITS = { height: 1..6, width: 1..4, length: 2..25, weight: 0.5..60, wheelbase: 1..10, track: 1..3, consumption: 1..100, speed: 1..60, hills: 0..1, sac: 1..6 }.freeze
# Up to this weight Valhalla's "auto" costing (with height/width) fits
# better than "truck": a camper isn't kept off roads closed to lorries.
CAR_MAX_WEIGHT = 3.5
def self.vehicles(data_dir)
list = read_json(File.join(data_dir, "vehicles.json")) || begin
# The single vehicle stored before profiles became the camper.
old = read_json(File.join(data_dir, "vehicle.json"))
old ? [DEFAULT_VEHICLES[0], DEFAULT_VEHICLES[1].merge(old.slice(:height, :width, :length, :weight))] : DEFAULT_VEHICLES
end
# A list saved before types existed gets the bicycle/foot profiles
# once; every save stores the type, so deleting them sticks.
list.none? { |v| v.key?(:type) } ? list + ACTIVE_VEHICLES : list
end
# The profile with this id, or the first one.
def self.vehicle(data_dir, id = nil)
list = vehicles(data_dir)
list.find { |v| v[:id] == id } || list.first
end
# Replaces the whole list: [{ "id", "name", "type", "height", ... }, ...].
def self.save_vehicles(data_dir, list)
raise ArgumentError, "at least one vehicle is needed" unless list.is_a?(Array) && list.any? && list.size <= 20
vehicles = list.map do |values|
raise ArgumentError, "invalid vehicle" unless values.is_a?(Hash)
name = values["name"].to_s.strip
id = values["id"].to_s
type = values["type"] || "car"
raise ArgumentError, "every vehicle needs a name" if name.empty? || name.size > 40
raise ArgumentError, "invalid vehicle id" unless id.match?(/\A[\w-]{1,40}\z/)
raise ArgumentError, "#{name}: invalid type" unless TYPES.include?(type)
bicycle_type = values["bicycle_type"] if type == "bicycle"
raise ArgumentError, "#{name}: invalid bicycle type" unless bicycle_type.nil? || BICYCLE_TYPES.include?(bicycle_type)
limits = VEHICLE_LIMITS.to_h do |key, range|
raw = values[key.to_s]
next [key, nil] if raw.nil? || raw.to_s.strip.empty?
value = Float(raw, exception: false)
raise ArgumentError, "#{name}: #{key} must be between #{range.min} and #{range.max}" unless value && range.cover?(value)
[key, value]
end
car = type == "car" ? car_details(name, values) : {}
{ id: id, name: name, type: type, bicycle_type: bicycle_type, **limits, **car }.compact
end
raise ArgumentError, "vehicle ids must be unique" unless vehicles.map { |v| v[:id] }.uniq.size == vehicles.size
write_json(File.join(data_dir, "vehicles.json"), vehicles)
vehicles
end
def self.car_details(name, values)
fuel = values["fuel"].to_s.empty? ? nil : values["fuel"].to_s
euro = values["euro"].to_s.empty? ? nil : values["euro"].to_s
raise ArgumentError, "#{name}: invalid fuel" unless fuel.nil? || FUELS.include?(fuel)
raise ArgumentError, "#{name}: invalid Euro class" unless euro.nil? || EUROS.include?(euro)
stickers = values["stickers"].to_s.strip[0, 80]
# the levelling ramps' steps, cm ("3 6 9"), for the level gauge
ramps = values["ramps"].to_s.scan(/\d+(?:[.,]\d+)?/).map { |s| s.tr(",", ".").to_f }
raise ArgumentError, "#{name}: ramps: up to 6 steps of 1 to 40 cm" unless ramps.size <= 6 && ramps.all? { |cm| (1..40).cover?(cm) }
list = values["vignettes"] || []
raise ArgumentError, "#{name}: invalid vignettes" unless list.is_a?(Array) && list.size <= 30
vignettes = list.map do |v|
country = v.is_a?(Hash) && v["country"].to_s.upcase
kind = v.is_a?(Hash) ? (v["kind"] || "vignette").to_s : nil
until_date = v.is_a?(Hash) ? v["until"].to_s : ""
raise ArgumentError, "#{name}: a vignette needs a country code" unless country&.match?(/\A[A-Z]{2}\z/)
raise ArgumentError, "#{name}: invalid vignette kind" unless PAYMENT_KINDS.include?(kind)
raise ArgumentError, "#{name}: invalid date #{until_date}" unless until_date.empty? || until_date.match?(/\A\d{4}-\d{2}-\d{2}\z/)
{ country: country, kind: kind, until: (until_date unless until_date.empty?) }.compact
end
{ fuel: fuel, euro: euro, stickers: (stickers unless stickers.empty?), vignettes: (vignettes unless vignettes.empty?),
ramps: (ramps.sort.map { |cm| cm % 1 == 0 ? cm.to_i : cm }.join(" ") unless ramps.empty?) }
end
private_class_method :car_details
# [[lon, lat], ...] → a GeoJSON Feature (the route line) with distance
# (km), time (s), the turn-by-turn instructions and, per country, the
# km on motorways and toll roads (for vignettes and tolls).
# avoid: {"tolls" => true, "highways" => true}, for the whole route.
def self.route(valhalla_url, locations, vehicle, avoid = {})
raise RouteError, "at least two points are needed" if locations.size < 2
costing, options = costing(vehicle, avoid)
data = valhalla(valhalla_url, "/route",
locations: locations.map { |lon, lat| { lon: Float(lon), lat: Float(lat) } },
costing: costing, costing_options: { costing => options }, units: "kilometers", turn_lanes: true)
legs = data["trip"]["legs"]
along = (along_route(valhalla_url, legs, costing, options) if %w[auto truck].include?(costing)) || {}
{ type: "Feature",
geometry: { type: "LineString", coordinates: legs.flat_map { |leg| decode_polyline(leg["shape"]) } },
properties: { kind: "route", costing: costing, distance_km: data["trip"]["summary"]["length"],
time_s: data["trip"]["summary"]["time"], countries: along[:countries],
speed_limits: along[:speed_limits], signals: along[:signals], roads: along[:roads],
legs_km: legs.map { |leg| leg.dig("summary", "length") }, # to each via point, for rerouting
legs_s: legs.map { |leg| leg.dig("summary", "time") }, # the time of each, for the stops list
# lanes: Valhalla's [{directions:, valid:, active:}] bitmasks, at junctions that have them
# type: Valhalla's maneuver type (the arrow), street: the road it leads onto
maneuvers: legs.flat_map { |leg| leg["maneuvers"].map { |m| maneuver(m) } } } }
rescue ArgumentError, TypeError
raise RouteError, "invalid coordinates"
end
# Routes of consecutive pieces (a trip's days with avoids of their own,
# TripStore) as one: the lines joined, km along it shifted by the pieces
# before, the countries summed.
def self.merge(parts)
return parts.first if parts.size <= 1
km = 0.0
coords = []
out = { distance_km: 0.0, time_s: 0.0, legs_km: [], legs_s: [], maneuvers: [], speed_limits: [], signals: [], roads: [] }
countries = {}
parts.each do |part|
props = part[:properties]
line = part[:geometry][:coordinates]
coords.concat(coords.empty? ? line : line.drop(1))
out[:distance_km] += props[:distance_km]
out[:time_s] += props[:time_s]
%i[legs_km legs_s maneuvers].each { |key| out[key].concat(props[key] || []) }
out[:speed_limits].concat((props[:speed_limits] || []).map { |at, limit| [(at + km).round(3), limit] })
out[:signals].concat((props[:signals] || []).map { |lon, lat, at| [lon, lat, (at + km).round(3)] })
out[:roads].concat((props[:roads] || []).map { |at, *rest| [(at + km).round(3), *rest] })
(props[:countries] || []).each do |row|
sum = countries[row[:code]] ||= { code: row[:code], km: 0.0, motorway_km: 0.0, toll_km: 0.0 }
%i[km motorway_km toll_km].each { |key| sum[key] = (sum[key] + row[key].to_f).round(1) }
end
km += props[:distance_km]
end
first = parts.first
{ type: "Feature", geometry: { type: "LineString", coordinates: coords },
properties: first[:properties].merge(out, distance_km: out[:distance_km].round(3), countries: countries.values) }
end
def self.maneuver(m)
{ text: m["instruction"], km: m["length"], type: m["type"], street: (m["begin_street_names"] || m["street_names"])&.first,
exit: m["roundabout_exit_count"], lanes: m["lanes"],
alert: m["verbal_transition_alert_instruction"], say: m["verbal_pre_transition_instruction"] }.compact
end
private_class_method :maneuver
# From Valhalla's per-edge attributes along the route:
# countries: [{ code: "AT", km:, motorway_km:, toll_km: }, ...] in route
# order (vignettes, tolls);
# speed_limits: [[km from the start, km/h | "unlimited" | nil], ...], an
# entry where the limit changes (nil: not tagged);
# signals: [[lon, lat, km from the start], ...], the traffic signals;
# roads: [[km from the start, road class, country code], ...], an entry
# where either changes (a vehicle's limits by country and road class).
# nil if that lookup fails: it's extra.
def self.along_route(valhalla_url, legs, costing, options)
totals = {}
limits = []
signals = []
roads = []
km = 0.0
legs.each do |leg|
shape = decode_polyline(leg["shape"])
data = valhalla(valhalla_url, "/trace_attributes",
encoded_polyline: leg["shape"], shape_match: "edge_walk", costing: costing,
costing_options: { costing => options },
filters: { attributes: %w[edge.length edge.road_class edge.toll edge.speed_limit edge.end_shape_index
node.admin_index node.traffic_signal admin.country_code], action: "include" })
codes = data["admins"].map { |admin| admin["country_code"] }
data["edges"].each do |edge|
code = codes[edge.dig("end_node", "admin_index").to_i] || "?"
row = totals[code] ||= { code: code, km: 0.0, motorway_km: 0.0, toll_km: 0.0 }
row[:km] += edge["length"]
row[:motorway_km] += edge["length"] if edge["road_class"] == "motorway"
row[:toll_km] += edge["length"] if edge["toll"]
limit = speed_limit(edge["speed_limit"])
limits << [km.round(3), limit] if limits.empty? || limits.last[1] != limit
road = [km.round(3), edge["road_class"], code]
roads << road if roads.empty? || roads.last.drop(1) != road.drop(1)
km += edge["length"]
point = shape[edge["end_shape_index"].to_i] if edge.dig("end_node", "traffic_signal")
signals << [*point, km.round(3)] if point
end
end
{ countries: totals.values.each { |row| row.transform_values! { |v| v.is_a?(Float) ? v.round(1) : v } },
speed_limits: limits, signals: signals, roads: roads }
rescue RouteError, Unavailable, Net::ReadTimeout, NoMethodError, TypeError
nil
end
private_class_method :along_route
# Valhalla's speed_limit: km/h, "unlimited" (a German Autobahn), else nil
# (0 or missing = not tagged).
def self.speed_limit(value)
value == "unlimited" || (value.is_a?(Integer) && value.positive?) ? value : nil
end
# The road at the end of a short trace ([[lon, lat], ...] oldest first,
# the last few fixes) for driving without a route: its name, class,
# speed limit and surface (Valhalla's: paved_smooth … impassable — the
# driving grid's Terrain view switches itself on past "paved_rough"). Map-matched, so the road actually driven, not just the
# nearest one (a bridge over the motorway).
def self.road(valhalla_url, points)
raise RouteError, "at least two points are needed" if points.size < 2
data = valhalla(valhalla_url, "/trace_attributes",
shape: points.map { |lon, lat| { lon: Float(lon), lat: Float(lat) } }, costing: "auto", shape_match: "map_snap",
filters: { attributes: %w[edge.names edge.road_class edge.speed_limit edge.surface node.admin_index admin.country_code],
action: "include" })
edge = data["edges"]&.last or raise RouteError, "no road here"
country = data["admins"]&.dig(edge.dig("end_node", "admin_index").to_i, "country_code")
{ name: edge["names"]&.first, road_class: edge["road_class"], speed_limit: speed_limit(edge["speed_limit"]), surface: edge["surface"], country: country,
signals: signals_ahead(valhalla_url, points) }.compact
rescue ArgumentError, TypeError
raise RouteError, "invalid coordinates"
end
AHEAD_KM = 1.5
# The traffic signals on the road ahead with no route: a route from the
# last fix, leaving in the direction driven, to AHEAD_KM straight on;
# [[lon, lat, km from the fix], ...], nil if that fails (it's extra).
# ponytail: "straight on" picks the way at a junction, a signal past a
# turn the driver then takes is missed until the next fix's lookup
def self.signals_ahead(valhalla_url, points)
(lon0, lat0), (lon, lat) = points.last(2).map { |p| p.map { |v| Float(v) } }
rad = Math::PI / 180
dx = (lon - lon0) * Math.cos(lat * rad)
dy = lat - lat0
return nil if dx.zero? && dy.zero?
heading = (Math.atan2(dx, dy) / rad) % 360
deg = AHEAD_KM / 111.32
to = { lon: lon + deg * Math.sin(heading * rad) / Math.cos(lat * rad), lat: lat + deg * Math.cos(heading * rad) }
data = valhalla(valhalla_url, "/route", locations: [{ lon: lon, lat: lat, heading: heading.round, heading_tolerance: 45 }, to],
costing: "auto", directions_type: "none")
along_route(valhalla_url, data.dig("trip", "legs"), "auto", {})&.dig(:signals)
rescue RouteError, Unavailable, Net::ReadTimeout, NoMethodError, TypeError, ArgumentError
nil
end
private_class_method :signals_ahead
ISOCHRONE_MAX_MINUTES = 240 # Valhalla's own default limit
# How far the vehicle gets from [lon, lat] in each of `minutes`: a
# GeoJSON FeatureCollection of polygons, largest first.
def self.isochrone(valhalla_url, center, minutes, vehicle, avoid = {})
lon, lat = center
minutes = Array(minutes).map { |m| Integer(m) }.uniq.sort
raise RouteError, "1 to 4 times between 1 and #{ISOCHRONE_MAX_MINUTES} minutes" unless (1..4).cover?(minutes.size) && minutes.all? { |m| (1..ISOCHRONE_MAX_MINUTES).cover?(m) }
costing, options = costing(vehicle, avoid)
valhalla(valhalla_url, "/isochrone",
locations: [{ lon: Float(lon), lat: Float(lat) }], costing: costing, costing_options: { costing => options },
contours: minutes.map { |m| { time: m } }, polygons: true)
rescue ArgumentError, TypeError
raise RouteError, "invalid center or times"
end
# bicycle / pedestrian from the profile's own settings; a car is "auto"
# with height/width up to CAR_MAX_WEIGHT, "truck" above it. avoid only
# applies to a car.
def self.costing(vehicle, avoid = {})
case vehicle[:type]
when "bicycle"
return ["bicycle", { bicycle_type: vehicle[:bicycle_type], cycling_speed: vehicle[:speed], use_hills: vehicle[:hills] }.compact]
when "foot"
return ["pedestrian", { walking_speed: vehicle[:speed], max_hiking_difficulty: vehicle[:sac]&.to_i, use_hills: vehicle[:hills] }.compact]
end
limits = vehicle.slice(:height, :width, :length, :weight).compact
costing, options = limits[:weight].to_f <= CAR_MAX_WEIGHT ? ["auto", limits.slice(:height, :width)] : ["truck", limits]
avoid = {} unless avoid.is_a?(Hash)
options = options.merge(use_tolls: 0.0) if avoid["tolls"]
options = options.merge(use_highways: 0.0) if avoid["highways"]
options = options.merge(use_ferry: 0.0) if avoid["ferries"]
options = options.merge(exclude_unpaved: true) if avoid["unpaved"]
[costing, options]
end
private_class_method :costing
def self.valhalla(valhalla_url, path, body)
raise Unavailable, "routing is not set up" if valhalla_url.to_s.empty?
uri = URI("#{valhalla_url}#{path}")
response = begin
Net::HTTP.start(uri.host, uri.port, open_timeout: 2, read_timeout: 60) do |http|
http.post(uri.path, JSON.generate(body), "Content-Type" => "application/json")
end
rescue SystemCallError, Net::OpenTimeout, SocketError
raise Unavailable, "the routing service is not running"
end
data = JSON.parse(response.body)
raise RouteError, data["error"] || "no result" unless response.is_a?(Net::HTTPSuccess)
data
end
private_class_method :valhalla
# Valhalla's encoded polyline (precision 6) → [[lon, lat], ...].
def self.decode_polyline(encoded)
values = []
value = shift = 0
encoded.each_byte do |byte|
byte -= 63
value |= (byte & 0x1f) << shift
shift += 5
next if byte >= 0x20
values << ((value & 1).zero? ? value >> 1 : ~(value >> 1))
value = shift = 0
end
lat = lon = 0
values.each_slice(2).map do |dlat, dlon|
lat += dlat
lon += dlon
[lon / 1e6, lat / 1e6]
end
end
def self.reset!
MUTEX.synchronize { @pending = false; @merging = nil }
end
end
end
+139
View File
@@ -0,0 +1,139 @@
require "json"
require_relative "gpx"
require_relative "fit"
require_relative "kiwix"
require_relative "library"
require_relative "places"
require_relative "pmtiles_builder"
module Maptool
# Server-side half of the search box (public/js/search.js): every saved
# layer (shown on the map or not), offline hiking trails, the offline
# place-name index (Places) and the offline Wikipedia (Kiwix). Online
# providers (Nominatim) are queried by the browser itself, so this route
# keeps working with no uplink at all.
#
# A source is a name -> lambda(words, ctx) returning results, each capped
# at LIMIT on its own so one busy source can't crowd out the rest — the
# LIMIT nearest to the map center when there is one: every result then
# carries distance_km (shown) and score (sorted by; distance, except a
# settlement counts as closer, see Places::DISTANCE_WEIGHT). ctx
# carries :text, :library, :data_dir, :center ([lat, lng] or nil) and
# :kiwix_url. `ref` in a result is what the browser needs to act on it
# (switch a layer on, open an article).
module Search
LIMIT = 50
KIWIX_LIMIT = 10 # each result costs kiwix-serve one more page fetch, see Kiwix.search
SOURCES = {
"layers" => lambda do |words, ctx|
scan(words, "layers", ctx[:library].nodes)
end,
"hiking_trails" => lambda do |words, ctx|
countries = PmtilesBuilder.hiking_trails_countries(ctx[:data_dir]).map do |code|
path = PmtilesBuilder.hiking_trails_country_path(ctx[:data_dir], code)
["Hiking trails #{code}", code, File.mtime(path), -> { File.read(path) }]
end
scan(words, "hiking_trails", countries)
end,
"places" => lambda do |words, ctx|
PmtilesBuilder.places_countries(ctx[:data_dir]).flat_map do |code|
Places.search(PmtilesBuilder.places_country_path(ctx[:data_dir], code), words, center: ctx[:center], limit: LIMIT).map do |place|
label = [place[:kind], "Offline map #{code}"].reject(&:empty?).join(" · ")
place.merge(source: "places", source_label: label, ref: code)
end
end
end,
"kiwix" => lambda do |_words, ctx|
Kiwix.search(ctx[:kiwix_url], ctx[:text], limit: KIWIX_LIMIT).map do |article|
{ name: article[:title], bbox: article[:position] && (article[:position] * 2),
source: "kiwix", source_label: "Wikipedia", ref: article[:link] }
end
end,
}.freeze
# ref => [stamp, entries] — a country's hiking-trails file runs to tens
# of MB, so it's parsed once per change (its mtime, a library node's
# rev), not once per keystroke.
# ponytail: unbounded in-memory cache, fine for a handful of layer files.
@cache = {}
def self.query(text, library:, data_dir:, sources: SOURCES.keys, center: nil, kiwix_url: "")
words = normalize(text).split
# No words: only "what's saved near here" (the driving grid's Points) —
# every library feature, nearest first; the other sources need a query.
sources &= ["layers"] if words.empty?
return [] if words.empty? && (center.nil? || sources.empty?)
ctx = { text: text.to_s.strip, library: library, data_dir: data_dir, center: center, kiwix_url: kiwix_url.to_s }
(sources & SOURCES.keys).flat_map do |source|
results = SOURCES[source].call(words, ctx)
results = nearest_first(results, center) if center
results.first(LIMIT).map { |result| result.except(:importance) }
end
end
# Results without a position (a Wikipedia article with no coordinates)
# go last.
def self.nearest_first(results, center)
results.each do |result|
next unless (bbox = result[:bbox])
result[:distance_km] = haversine_km(center, [(bbox[1] + bbox[3]) / 2.0, (bbox[0] + bbox[2]) / 2.0]).round(1)
result[:score] = result[:distance_km] * Places::DISTANCE_WEIGHT[result[:importance]]
end
results.sort_by { |result| result[:score] || Float::INFINITY }
end
def self.haversine_km((lat1, lng1), (lat2, lng2))
rad = Math::PI / 180
a = (Math.sin((lat2 - lat1) * rad / 2)**2) + (Math.cos(lat1 * rad) * Math.cos(lat2 * rad) * (Math.sin((lng2 - lng1) * rad / 2)**2))
2 * 6371.0 * Math.asin(Math.sqrt(a))
end
# files: [label, ref, stamp, reader] — every matching feature of each,
# found in memory (all of them, so query can pick the nearest).
def self.scan(words, source, files)
files.flat_map do |label, ref, stamp, read|
entries(ref, stamp, label, read).filter_map do |entry|
entry.except(:text).merge(source: source, source_label: label, ref: ref) if words.all? { |word| entry[:text].include?(word) }
end
end
end
# Lowercased, diacritics and apostrophes stripped — "kosice" finds
# "Košice", "mcdonalds" finds "McDonald's" (see Places.row's extra).
def self.normalize(text)
text.to_s.unicode_normalize(:nfkd).gsub(/\p{Mn}/, "").delete(Places::APOSTROPHES).downcase
end
def self.entries(ref, stamp, label, read)
cached = @cache[ref]
return cached[1] if cached && cached[0] == stamp
entries = begin
JSON.parse(read.call).fetch("features", []).filter_map { |feature| entry(feature, label) }
rescue JSON::ParserError, Gpx::ParseError, Fit::ParseError, Errno::ENOENT, Library::NotFound
[]
end
@cache[ref] = [stamp, entries]
entries
end
def self.entry(feature, fallback_name)
coords = feature.dig("geometry", "coordinates")
return nil unless coords.is_a?(Array) && !coords.empty?
props = feature["properties"] || {}
name = props["name"].to_s.strip
name = fallback_name if name.empty?
lngs, lats = Places.positions(coords).map { |p| p.first(2) }.transpose
{
name: name,
kind: props["kind"] || feature.dig("geometry", "type"),
bbox: [lngs.min, lats.min, lngs.max, lats.max],
text: normalize("#{name} #{props["description"]}"),
}
end
end
end
+79
View File
@@ -0,0 +1,79 @@
require "json"
require "net/http"
require "uri"
module Maptool
# Library sync of a client server (the car's) against the main one
# (brick, the "cloud"), like OsmAnd's cloud sync: the client syncs when
# asked (the Sync button), the main server only answers. One run pulls
# what the server has that we haven't seen (Library#sync_changes over
# GET /api/sync/changes, applied by Library#apply_sync), then pushes ours
# (POST /api/sync/apply) with the source files the server lacks. Newer
# updated_at wins either way; the echo of a synced change ties and stops.
# Map data isn't synced here (bin/pull-maps.sh, one way).
class Sync
class Error < StandardError; end
NETWORK_ERRORS = [Error, JSON::ParserError, SocketError, SystemCallError, IOError,
Net::OpenTimeout, Net::ReadTimeout, OpenSSL::SSL::SSLError].freeze
def initialize(server:, token:, library:, state_path:)
@server = server.chomp("/")
@token = token
@library = library
@state_path = state_path
end
# { pulled:, pushed: } rows.
def run
{ pulled: pull, pushed: push }
end
def pull
count = 0
loop do
changes = JSON.parse(request(Net::HTTP::Get, "/api/sync/changes?since=#{state.fetch('pull', 0)}"))
@library.apply_sync(changes).each { |item| @library.store_source(item, request(Net::HTTP::Get, "/api/sync/source/#{item['id']}")) }
count += rows(changes)
save("pull" => changes["next"])
return count if changes["next"] >= changes["rev"]
end
end
def push
count = 0
loop do
changes = @library.sync_changes(state.fetch("push", 0))
missing = JSON.parse(request(Net::HTTP::Post, "/api/sync/apply", JSON.generate(changes)))["missing"]
missing.each { |id| request(Net::HTTP::Put, "/api/sync/source/#{id}", File.binread(@library.item_source(id))) }
count += rows(changes)
save("push" => changes["next"])
return count if changes["next"] >= changes["rev"]
end
end
private
def rows(changes) = changes.values_at("folders", "items").sum { |r| r&.size || 0 }
def request(kind, path, body = nil)
uri = URI("#{@server}#{path}")
req = kind.new(uri, "Authorization" => "Bearer #{@token}", "Content-Type" => "application/octet-stream")
req.body = body if body
response = Net::HTTP.start(uri.host, uri.port, use_ssl: uri.scheme == "https", open_timeout: 10, read_timeout: 120) { |http| http.request(req) }
raise Error, "#{path.split('?').first}: HTTP #{response.code}" unless response.is_a?(Net::HTTPSuccess)
response.body
end
# { "pull" => the server's rev we have up to, "push" => our rev it has up to }
def state
File.exist?(@state_path) ? JSON.parse(File.read(@state_path)) : {}
end
def save(values)
File.write("#{@state_path}.tmp", JSON.generate(state.merge(values)))
File.rename("#{@state_path}.tmp", @state_path)
end
end
end
+75
View File
@@ -0,0 +1,75 @@
require "rexml/document"
require "time"
require_relative "gpx"
require_relative "track_stats"
module Maptool
# Garmin's older Training Center XML (.tcx), still what some apps
# export: each <Activity> becomes one track Feature, shaped like
# Gpx/Fit's (MultiLineString, "kind" => "track", the same profile).
# Points without a position (indoor, GPS lost) are skipped.
module Tcx
ParseError = Gpx::ParseError # every caller already rescues that one
SPORTS = { "Running" => "running", "Biking" => "cycling" }.freeze
def self.to_geojson(path)
root = REXML::Document.new(File.read(path)).root
raise ParseError, "not a TCX file" unless root&.name == "TrainingCenterDatabase"
features = []
root.each_element("Activities/Activity") do |activity|
points = []
times = []
extras = []
laps = [] # index of each lap's first positioned point
activity.each_element("Lap") do |lap|
laps << points.size
lap.each_element("Track/Trackpoint") do |pt|
lat = text(pt, "Position/LatitudeDegrees")
lon = text(pt, "Position/LongitudeDegrees")
next unless lat && lon
ele = text(pt, "AltitudeMeters")
points << (ele ? [lon.to_f, lat.to_f, ele.to_f] : [lon.to_f, lat.to_f])
times << (Time.iso8601(text(pt, "Time")) rescue nil)
extras << extensions(pt).merge({ heart_rate_bpm: text(pt, "HeartRateBpm/Value")&.to_i, cadence_rpm: text(pt, "Cadence")&.to_i }.compact)
end
end
next if points.empty?
laps = laps.uniq.reject { |i| i >= points.size }
features << {
"type" => "Feature",
"geometry" => { "type" => "MultiLineString", "coordinates" => [points] },
"properties" => { "kind" => "track", "name" => nil, "activity_type" => SPORTS.fetch(activity.attributes["Sport"], activity.attributes["Sport"]&.downcase) }
.merge(TrackStats.compute(points, times: times))
.merge("profile" => TrackStats.build_profile(points, times: times, extras: extras))
.merge(laps.size > 1 ? { "laps" => laps } : {}),
}
end
{ "type" => "FeatureCollection", "features" => features }
rescue REXML::ParseException => e
raise ParseError, e.message
end
# Speed/Watts/RunCadence in Garmin's ActivityExtension (TPX), by local name.
def self.extensions(pt)
values = {}
pt.elements["Extensions"]&.each_recursive do |el|
case el.name
when "Speed" then values[:speed_mps] = el.text.to_f
when "Watts" then values[:power_w] = el.text.to_i
when "RunCadence" then values[:cadence_rpm] = el.text.to_i
end
end
values
end
private_class_method :extensions
def self.text(el, path)
el.elements[path]&.text&.strip
end
private_class_method :text
end
end
+3 -2
View File
@@ -31,7 +31,7 @@ module Maptool
# (computed the same way for every format, rather than trusting a # (computed the same way for every format, rather than trusting a
# device's own odometer field — keeps a GPX and a FIT file directly # device's own odometer field — keeps a GPX and a FIT file directly
# comparable), elapsed time since the first known timestamp, elevation, # comparable), elapsed time since the first known timestamp, elevation,
# and whatever per-point extras (speed/cadence/heart rate) the caller # and whatever per-point extras (speed/cadence/heart rate/power/temperature) the caller
# has — nil wherever a format/file doesn't carry it. # has — nil wherever a format/file doesn't carry it.
# `extras`: array of hashes parallel to `coordinates`, or shorter/empty. # `extras`: array of hashes parallel to `coordinates`, or shorter/empty.
# `times`: array of Time (or nil) parallel to `coordinates`, or []. # `times`: array of Time (or nil) parallel to `coordinates`, or [].
@@ -53,6 +53,8 @@ module Maptool
"speed_mps" => extra[:speed_mps], "speed_mps" => extra[:speed_mps],
"cadence_rpm" => extra[:cadence_rpm], "cadence_rpm" => extra[:cadence_rpm],
"heart_rate_bpm" => extra[:heart_rate_bpm], "heart_rate_bpm" => extra[:heart_rate_bpm],
"power_w" => extra[:power_w],
"temperature_c" => extra[:temperature_c],
"lon" => lon, "lon" => lon,
"lat" => lat, "lat" => lat,
} }
@@ -66,6 +68,5 @@ module Maptool
a = (Math.sin(dlat / 2)**2) + (Math.cos(lat1 * rad) * Math.cos(lat2 * rad) * (Math.sin(dlon / 2)**2)) a = (Math.sin(dlat / 2)**2) + (Math.cos(lat1 * rad) * Math.cos(lat2 * rad) * (Math.sin(dlon / 2)**2))
2 * EARTH_RADIUS_METERS * Math.asin(Math.sqrt(a)) 2 * EARTH_RADIUS_METERS * Math.asin(Math.sqrt(a))
end end
private_class_method :haversine
end end
end end
+214
View File
@@ -0,0 +1,214 @@
require "json"
require_relative "routing"
module Maptool
# The trip being driven, one for every screen of this server (the cab's
# display, the tablet in the back, the phone): its points, vehicle and
# avoids, and the route through them. Any screen edits it (PUT
# /api/trip), the server routes it again and bumps the version; every
# screen polls GET /api/trip and swaps the route in without touching its
# camera. Kept in data/trip.json across restarts.
class TripStore
EMPTY = { version: 0, points: [], vehicle: nil, avoid: {}, editing: nil, route: nil, error: nil }.freeze
# The itinerary: the trip's name, when it starts (local "YYYY-MM-DDTHH:MM")
# and when a day after a night stop starts ("HH:MM"); per point a night
# stop (the day ends there), the stay in minutes, a note, its type (an
# NPS pictogram's name, public/js/route.js STOP_TYPES) and, on a day's
# first point, the day's note; park: where the car stays ({ lngLat:,
# name: }, the route goes there, the place is a walk away); on a day's
# first point avoid: the day's own (AVOIDS), else the trip's; cost / paid:
# € planned there and paid; the trip's own note, budget and fuel price.
MAX_STAY_MIN = 7 * 24 * 60
AVOIDS = %i[tolls highways ferries unpaved].freeze
DATE_TIME = /\A\d{4}-\d{2}-\d{2}T\d{2}:\d{2}\z/
TIME = /\A\d{2}:\d{2}\z/
def self.point(p)
stay = p[:stay].nil? || p[:stay].to_s.empty? ? nil : Integer(p[:stay], exception: false)
raise ArgumentError, "stay must be 0–#{MAX_STAY_MIN} minutes" if stay && !(0..MAX_STAY_MIN).cover?(stay)
note, day_note = [p[:note], p[:day_note]].map { |n| n.to_s.strip[0, 500] }
type = p[:type].to_s
raise ArgumentError, "type must be an icon name" unless type.empty? || type.match?(/\A[a-z0-9-]{1,60}\z/)
cost, paid = [p[:cost], p[:paid]].map { |v| money(v) }
avoid = (p[:avoid].to_h.slice(*AVOIDS).to_h { |k, v| [k, !!v] } if p[:avoid].is_a?(Hash))
park = ({ lngLat: p[:park].fetch(:lngLat).map { |v| Float(v) }, name: p[:park][:name]&.to_s&.strip&.[](0, 120) }.compact if p[:park].is_a?(Hash))
{ lngLat: p.fetch(:lngLat).map { |v| Float(v) }, name: p[:name], nav: !!p[:nav], passed: !!p[:passed],
night: (true if p[:night]), stay: (stay if stay&.positive?), note: (note unless note.empty?),
type: (type unless type.empty?), day_note: (day_note unless day_note.empty?), park: park, avoid: avoid, cost: cost, paid: paid }.compact
end
# € or nil; ArgumentError past MAX_MONEY or below 0.
MAX_MONEY = 1_000_000
def self.money(value)
return nil if value.nil? || value.to_s.strip.empty?
amount = Float(value, exception: false)
raise ArgumentError, "amounts must be 0–#{MAX_MONEY}" unless amount && (0..MAX_MONEY).cover?(amount)
amount.round(2)
end
def self.itinerary(name:, start:, day_start:, note: nil, budget: nil, fuel_price: nil)
name = name.to_s.strip[0, 80]
note = note.to_s.strip[0, 2000]
raise ArgumentError, "start must be YYYY-MM-DDTHH:MM" unless start.to_s.empty? || start.to_s.match?(DATE_TIME)
raise ArgumentError, "day_start must be HH:MM" unless day_start.to_s.empty? || day_start.to_s.match?(TIME)
{ name: (name unless name.empty?), start: (start unless start.to_s.empty?), day_start: (day_start unless day_start.to_s.empty?),
note: (note unless note.empty?), budget: money(budget), fuel_price: money(fuel_price) }.compact
end
def initialize(path)
@path = path
@mutex = Mutex.new
@trip = begin
EMPTY.merge(JSON.parse(File.read(path), symbolize_names: true))
rescue Errno::ENOENT, JSON::ParserError
EMPTY.dup
end
end
def get
@mutex.synchronize { @trip.dup }
end
ON_ROUTE_M = 30 # as the dashboard's
OFF_ROUTE_FIXES = 3
MAX_HDOP = 5
MIN_SPEED = 1.5 # m/s: standing next to the route isn't a detour
REROUTE_EVERY_S = 15
# Every GNSS fix (App.gnss_update): off the trip's route for
# OFF_ROUTE_FIXES fixes while driving, routes again from here to the
# points not reached yet — on the server, so it happens with no screen
# open; the screens pick the new version up by polling. The block routes
# (as #update's). In a thread of its own: CAN's reader doesn't wait.
def follow(position, speed:, hdop: nil, now: Time.now.to_f, &router)
trip = get
route = trip[:route]
return unless route && trip[:points].count { |p| !p[:passed] } >= 2
at, off = self.class.locate(route[:geometry][:coordinates], position)
if off <= ON_ROUTE_M
@off_fixes = 0
@last_at = at
return
end
return if (hdop || 0) > MAX_HDOP
@off_fixes = (@off_fixes || 0) + 1
return if @off_fixes < OFF_ROUTE_FIXES || speed.to_f < MIN_SPEED || (@reroute_at && now - @reroute_at < REROUTE_EVERY_S) || @rerouting
@reroute_at = now
@rerouting = true
leg = 0
passed = (route[:properties][:legs_km] || [])[0...-1].map { |km| leg += km }.count { |km| km <= (@last_at || 0) }
points = self.class.passed_on(trip[:points], passed, position)
Thread.new do
update(points: points, vehicle: trip[:vehicle], avoid: trip[:avoid], editing: trip[:editing], &router)
rescue StandardError => e
warn "trip reroute: #{e.message}"
ensure
@rerouting = false
@off_fixes = 0
end
end
# The points after a detour: the start and the `passed` vias reached so
# far marked passed (the start dropped if it was an earlier "My
# position", not a stop), then the position as the new start, then the rest.
def self.passed_on(points, passed, position)
done, ahead = points.partition { |p| p[:passed] }
ahead = ahead.dup
reached = ahead.shift(1 + passed)
reached.shift if reached.first&.dig(:name) == "My position"
done + reached.map { |p| p.merge(passed: true) } + [{ lngLat: position, name: "My position", nav: false, passed: false }] + ahead
end
# Nearest point on the line ([[lon, lat], ...]): [km along it, meters off it].
def self.locate(coords, (lon, lat))
cos = Math.cos(lat * Math::PI / 180)
along = 0.0
best = [0.0, Float::INFINITY]
coords.each_cons(2) do |(ax, ay), (bx, by)|
ax *= cos
bx *= cos
px = lon * cos
len2 = (bx - ax)**2 + (by - ay)**2
t = len2.zero? ? 0.0 : (((px - ax) * (bx - ax) + (lat - ay) * (by - ay)) / len2).clamp(0.0, 1.0)
off = Math.hypot(px - (ax + t * (bx - ax)), lat - (ay + t * (by - ay))) * 111_320
length = Math.sqrt(len2) * 111.32
best = [along + t * length, off] if off < best[1]
along += length
end
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
# The points to route, in pieces of the same avoids: [[locations,
# avoid], ...] — one piece unless a day has avoids of its own (on its
# first point in the list, the one after the night spot). A leg takes
# the avoids of the day it's driven in.
def self.pieces(points, avoid)
day = points.first&.dig(:avoid) || avoid
legs = points.each_with_index.filter_map do |p, i|
day = points[i + 1]&.dig(:avoid) || avoid if p[:night] # the next day leaves from the night spot
[p.dig(:park, :lngLat) || p[:lngLat], day] unless p[:passed]
end
legs.each_cons(2).chunk_while { |x, y| x[0][1] == y[0][1] }.map do |run|
[[run.first[0][0], *run.map { |_, to| to[0] }], run.first[0][1]]
end
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
# changed — the old route stays then. Passed points stay in the trip
# (shown dimmed, still editable: a stop missed out added afterwards),
# just not routed. Last write wins.
def update(points:, vehicle:, avoid:, editing:, name: nil, start: nil, day_start: nil, note: nil, budget: nil, fuel_price: nil)
points = points.map { |p| self.class.point(p) }
itinerary = self.class.itinerary(name: name, start: start, day_start: day_start, note: note, budget: budget, fuel_price: fuel_price)
avoid = (avoid || {}).to_h { |k, v| [k.to_sym, !!v] }
before = get
routed = ->(list) { list.reject { |p| p[:passed] }.map { |p| p.dig(:park, :lngLat) || p[:lngLat] } }
same_route = self.class.pieces(before[:points], before[:avoid]) == self.class.pieces(points, avoid) &&
before[:vehicle] == vehicle && before[:avoid] == avoid && !before[:error]
route, error = if same_route then [before[:route], nil]
elsif routed.(points).size < 2 then [nil, nil]
else
begin
pieces = self.class.pieces(points, avoid)
[Routing.merge(pieces.map { |locations, day_avoid| yield(locations, vehicle, day_avoid) }), nil]
rescue Routing::RouteError, Routing::Unavailable => e
[nil, e.message]
end
end
@mutex.synchronize do
@trip = { version: @trip[:version] + 1, points: points, vehicle: vehicle, avoid: avoid, editing: editing,
**itinerary, route: route, error: error, updated_at: Time.now.to_f }.compact
@trip[:route] = route # nil kept: the client reads it
@trip[:error] = error
File.write("#{@path}.tmp", JSON.generate(@trip))
File.rename("#{@path}.tmp", @path)
@trip.dup
end
end
end
end
+94
View File
@@ -0,0 +1,94 @@
require "time"
require_relative "track_stats"
require_relative "gpx"
module Maptool
# The days of a recorded trip (the Design canvas' GridRecording): the log
# stays one continuous journal (lib/maptool/trip_log.rb), the days are only
# cuts in it — where the car stood ≥ STOOD_S, else at NIGHT_HOUR local time
# (a drive through the night with no long stop), plus the cuts made by
# hand, minus the ones joined. A cut is the index of a day's first point.
# points: [[lon, lat, alt, t], ...] (t: epoch s), as the journal has them.
module TripDays
STOOD_S = 4 * 3600
NIGHT_HOUR = 3
PAUSE_S = 300 # this long between two fixes: standing (a fix comes every 10 m moved)
# [[index, "auto" | "night" | "hand"], ...], sorted. hand / joined: epoch
# s — a hand cut starts the day at the first point from then on; a join
# names the cut by its day's first point's time.
# ponytail: NIGHT_HOUR in the server's time zone, the client's if they differ
def self.cuts(points, hand: [], joined: [])
t = points.map { |p| p[3] }
auto = (1...points.size).select { |i| t[i] - t[i - 1] >= STOOD_S }
night = (1...points.size).select do |i|
crossed = Time.at(t[i]).then { |b| Time.new(b.year, b.month, b.day, NIGHT_HOUR) }
crossed = crossed - 86_400 if crossed.to_f > t[i]
crossed.to_f > t[i - 1] && auto.none? { |j| (t[j] - t[i]).abs < 12 * 3600 }
end
by_hand = hand.filter_map { |h| t.index { |x| x >= h } }.select { |i| i.positive? }
all = auto.map { |i| [i, "auto"] } + night.map { |i| [i, "night"] } + by_hand.map { |i| [i, "hand"] }
all.reject { |i, _| joined.any? { |j| (t[i] - j).abs < 0.05 } }.uniq(&:first).sort_by(&:first)
end
# The days: { index:, from:, to: (exclusive), started_at:, ended_at:,
# distance_m:, driving_s:, ascent_m:, max_alt_m:, cut: (what ends it:
# { kind:, stood_s:, at: [lon, lat], next: its time }) }.
def self.days(points, cuts)
bounds = [0, *cuts.map(&:first), points.size]
bounds.each_cons(2).each_with_index.map do |(from, to), n|
piece = points[from...to]
day = { index: n + 1, from: from, to: to, started_at: piece.first[3], ended_at: piece.last[3] }.merge(stats(piece))
if to < points.size
day[:cut] = { kind: cuts[n][1], stood_s: (points[to][3] - piece.last[3]).round, at: piece.last.first(2), next: points[to][3] }
end
day
end
end
def self.stats(piece)
coords = piece.map { |lon, lat, alt| alt ? [lon, lat, alt] : [lon, lat] }
gaps = piece.each_cons(2).map { |a, b| b[3] - a[3] }
{
distance_m: TrackStats.compute(coords)["distance_meters"],
driving_s: gaps.select { |g| g < PAUSE_S }.sum.round,
standing_s: gaps.select { |g| g >= PAUSE_S }.sum.round,
stops: gaps.count { |g| g >= PAUSE_S },
ascent_m: TrackStats.compute(coords)["elevation_gain_meters"],
max_alt_m: piece.filter_map { |p| p[2] }.max,
}
end
# [west, south, east, north] of a piece.
def self.bbox(piece)
lons, lats = piece.map(&:first), piece.map { |p| p[1] }
[lons.min, lats.min, lons.max, lats.max]
end
# A GPX of tracks — pieces: [[name, points], ...] — with each point's
# time; extras: Features to add (the planned route, stops, pauses).
def self.gpx(pieces, extras = [])
tracks = pieces.map do |name, piece|
{ "type" => "Feature", "geometry" => { "type" => "LineString", "coordinates" => piece.map { |lon, lat, alt| alt ? [lon, lat, alt] : [lon, lat] } },
"properties" => { "kind" => "track", "name" => name, "activity_type" => "driving",
"times" => piece.map { |p| Time.at(p[3]).utc.iso8601 } } }
end
Gpx.from_features(extras + tracks)
end
# The stands (≥ PAUSE_S) in a piece as waypoints.
def self.pauses(piece)
piece.each_cons(2).filter_map do |a, b|
next if b[3] - a[3] < PAUSE_S
{ "type" => "Feature", "geometry" => { "type" => "Point", "coordinates" => a.first(2) },
"properties" => { "name" => "Stood #{duration(b[3] - a[3])}", "time" => Time.at(a[3]).utc.iso8601 } }
end
end
def self.duration(seconds)
h, m = (seconds / 60).round.divmod(60)
h.positive? ? format("%d h %02d", h, m) : "#{m} min"
end
end
end
+220
View File
@@ -0,0 +1,220 @@
require "json"
require "time"
require "fileutils"
require_relative "track_stats"
require_relative "gnss_sim"
module Maptool
# The trip being driven, recorded (docs: TODO "The trip as plan + log"):
# a trip is a library folder, Trips/<date> <name>. Start makes it — with
# the planned route and its named stops in it — and from then on every
# GNSS fix (App.gnss_update) that moved MIN_STEP_M goes into the car's
# track there.
#
# Crash-safe like a FIT file, by being append-only: each point is a line
# appended to the trip's journal (<dir>/<started_at>.ndjson), fsynced
# every FSYNC_EVERY_S — a power cut loses those few seconds at most, a
# torn last line is skipped. The journal's first line says which trip it
# is, a line names the library track once made, the last one ends it; so
# a restart (or a lost state file) picks the running trip up again from
# the newest journal with no end. The library's track is built from it
# every LIBRARY_EVERY_S and at the end (each build rewrites it — the
# journal is what's kept per point).
class TripLog
MIN_STEP_M = 10
FSYNC_EVERY_S = 5
LIBRARY_EVERY_S = 300
ROOT = "Trips".freeze
def initialize(dir, library:)
@dir = dir
@library = library
@mutex = Mutex.new
FileUtils.mkdir_p(dir)
@trip = resume
@synced_at = @built_at = 0
end
def active?
@mutex.synchronize { !!@trip }
end
# { active:, folder:, started_at:, points:, distance_m: } — coordinates
# from index `since` on with `since:` (the map draws the line as it grows).
def status(since: nil)
@mutex.synchronize do
points = @trip ? @trip[:points] : []
result = { active: !!@trip, folder: @trip&.dig(:folder), started_at: @trip&.dig(:started_at), points: points.size,
distance_m: TrackStats.compute(points.map { |p| p.first(2) })["distance_meters"] }
result[:coordinates] = points[since.to_i..].to_a.map { |p| p.first(2) } if since
result
end
end
# plan: the trip's route Feature (or nil) and its points, kept in the
# folder as a route and points. Returns the folder.
def start(name, plan: nil, stops: [], now: Time.now)
@mutex.synchronize do
raise ArgumentError, "a trip is already running (#{@trip[:folder]})" if @trip
folder = "#{ROOT}/#{[now.strftime('%Y-%m-%d'), name.to_s.strip].reject(&:empty?).join(' ')}"
@library.create_folder(folder)
features = []
if plan
props = (plan[:properties] || {}).slice(:distance_km, :time_s, :costing).transform_keys(&:to_s)
features << { "type" => "Feature", "geometry" => JSON.parse(JSON.generate(plan[:geometry])),
"properties" => props.merge("kind" => "route", "name" => "Plan") }
end
stops.select { |s| s[:name] && s[:name] != "My position" }.each do |s|
features << { "type" => "Feature", "geometry" => { "type" => "Point", "coordinates" => s[:lngLat] }, "properties" => { "name" => s[:name] } }
end
@library.import_features(features, folder: folder) unless features.empty?
started = now.to_i
@trip = { folder: folder, started_at: started, points: [], item: nil, path: File.join(@dir, "#{started}.ndjson") }
journal(trip: folder, started_at: started)
sync
File.open(@dir, &:fsync) # the new journal's name on disk too
folder
end
end
# A fix: [lon, lat], altitude (m, or nil), at (epoch seconds).
def record(lon, lat, alt, at)
@mutex.synchronize do
return unless @trip
last = @trip[:points].last
return if last && GnssSim.meters(last, [lon, lat]) < MIN_STEP_M
point = [lon, lat, alt, at.to_f.round(1)]
@trip[:points] << point
journal(point)
now = Process.clock_gettime(Process::CLOCK_MONOTONIC)
if now - @synced_at >= FSYNC_EVERY_S
sync
@synced_at = now
end
if now - @built_at >= LIBRARY_EVERY_S
build
@built_at = now
end
end
end
# Ends it: the track built a last time, the journal closed. Returns the folder.
def stop
@mutex.synchronize do
return nil unless @trip
build
journal(end: Time.now.to_i)
sync
@file&.close
@file = nil
folder = @trip[:folder]
@trip = nil
folder
end
end
# The running trip's journal, else the newest (the trip just ended), read
# whole: { folder:, started_at:, points:, hand:, joined:, active: } — or nil.
def recording
path = @mutex.synchronize do
@file&.flush
@trip ? @trip[:path] : Dir[File.join(@dir, "*.ndjson")].max_by { |p| File.basename(p, ".ndjson").to_i }
end
return nil unless path
out = { points: [], hand: [], joined: [], active: false, path: path }
File.foreach(path) do |line|
entry = JSON.parse(line) rescue next
case entry
when Array then out[:points] << entry
when Hash
out[:folder] ||= entry["trip"]
out[:started_at] ||= entry["started_at"]
out[:hand] << entry["cut"] if entry["cut"]
out[:joined] << entry["join"] if entry["join"]
end
end
out[:active] = @mutex.synchronize { @trip&.dig(:path) == path }
out
end
# A day cut by hand at `at` (epoch s), or a cut joined (`at`: its day's
# first point's time): a line in the journal, the trip itself untouched.
def mark(kind, at)
raise ArgumentError, "cut or join" unless %i[cut join].include?(kind)
path = recording&.dig(:path) or raise ArgumentError, "no trip recorded"
@mutex.synchronize do
if @trip && @trip[:path] == path
journal(kind => at.to_f)
sync
else
File.open(path, "a") { |f| f.puts(JSON.generate(kind => at.to_f)) }
end
end
end
private
# The newest journal with no end: the trip still running.
def resume
Dir[File.join(@dir, "*.ndjson")].max_by { |path| File.basename(path, ".ndjson").to_i }&.then do |path|
trip = nil
File.foreach(path) do |line|
entry = JSON.parse(line) rescue next # a line torn by a power cut
case entry
when Array then trip&.dig(:points)&.push(entry)
when Hash
trip = { folder: entry["trip"], started_at: entry["started_at"], points: [], item: nil, path: path } if entry["trip"]
trip[:item] = entry["item"] if trip && entry["item"]
trip = nil if entry["end"]
end
end
trip
end
end
def journal(entry)
unless @file
@file = File.open(@trip[:path], "a+")
# a line torn by a power cut: the next one starts on a line of its own
if @file.size.positive?
@file.seek(-1, IO::SEEK_END)
@file.write("\n") unless @file.read(1) == "\n"
end
end
@file.puts(JSON.generate(entry))
end
def sync
@file&.flush
@file&.fsync
end
# The car's track into the library from the points so far (made on the
# first build, its key journaled, replaced after).
def build
points = @trip[:points]
return if points.size < 2
coordinates = points.map { |lon, lat, alt| alt ? [lon, lat, alt] : [lon, lat] }
times = points.map { |p| Time.at(p[3]) }
name = "Car #{Time.at(@trip[:started_at]).strftime('%Y-%m-%d %H:%M')}"
feature = { "type" => "Feature", "geometry" => { "type" => "LineString", "coordinates" => coordinates },
"properties" => { "kind" => "track", "name" => name, "activity_type" => "driving" }
.merge(TrackStats.compute(coordinates, times: times))
.merge("profile" => TrackStats.build_profile(coordinates, times: times)) }
if @trip[:item]
@library.update_feature(@trip[:item], @trip[:item].delete_prefix("item:"), feature)
else
@trip[:item] = @library.import_features([feature], folder: @trip[:folder]).find { |key| key.start_with?("item:") }
journal(item: @trip[:item])
sync
end
end
end
end
+65
View File
@@ -0,0 +1,65 @@
require "json"
require "fileutils"
require "net/http"
module Maptool
# Self-update of the car's server (SELF_UPDATE=1; brick deploys by CI):
# is there a newer commit on main that passed CI (Gitea's API, the repo
# is public), and asking the host to install it — data/update/request.json,
# picked up by maptool-update.path → bin/update-maptool.sh, which reports
# back in data/update/status.json.
module Updater
CHECK_EVERY_S = 600
RETRY_AFTER_S = 60 # a check that failed (offline, a commit CI hasn't seen yet)
MUTEX = Mutex.new
def self.dir(data_dir)
File.join(data_dir, "update")
end
# { sha:, ci: "success" | "pending" | "failure" | … } of main, cached
# CHECK_EVERY_S; nil while Gitea can't be reached (no internet on the road).
def self.latest(gitea_url, repo, fetch: method(:get_json))
MUTEX.synchronize do
# CI still running (or the check failed): sooner, so the button shows when it's through
return @latest if @checked_at && Time.now.to_f - @checked_at < (@latest&.dig(:ci) == "success" ? CHECK_EVERY_S : RETRY_AFTER_S)
@checked_at = Time.now.to_f
sha = fetch.call("#{gitea_url}/api/v1/repos/#{repo}/branches/main").dig("commit", "id")
ci = begin
fetch.call("#{gitea_url}/api/v1/repos/#{repo}/commits/#{sha}/status")["state"]
rescue StandardError
nil # no status yet: not offered, asked again in a minute
end
@latest = ci ? { sha: sha, ci: ci } : nil
rescue StandardError
@latest = nil
end
end
def self.reset!
MUTEX.synchronize { @checked_at = @latest = nil }
end
def self.request(data_dir, sha)
raise ArgumentError, "not a commit" unless sha.to_s.match?(/\A[0-9a-f]{40}\z/)
FileUtils.mkdir_p(dir(data_dir))
File.write(File.join(dir(data_dir), "request.json"), JSON.generate(sha: sha, at: Time.now.to_i))
end
def self.status(data_dir)
JSON.parse(File.read(File.join(dir(data_dir), "status.json")), symbolize_names: true)
rescue Errno::ENOENT, JSON::ParserError
nil
end
def self.get_json(url)
uri = URI(url)
response = Net::HTTP.start(uri.host, uri.port, use_ssl: uri.scheme == "https", open_timeout: 5, read_timeout: 10) { |http| http.get(uri.request_uri) }
raise "HTTP #{response.code}" unless response.is_a?(Net::HTTPSuccess)
JSON.parse(response.body)
end
end
end
+73 -44
View File
@@ -6,12 +6,13 @@
"": { "": {
"name": "maptool-vendor", "name": "maptool-vendor",
"devDependencies": { "devDependencies": {
"@mdi/js": "7.4.47",
"flag-icons": "7.6.0", "flag-icons": "7.6.0",
"maplibre-contour": "0.1.1", "maplibre-contour": "0.2.0",
"maplibre-gl": "6.17.0", "maplibre-gl": "6.21.0",
"maplibre-gl-lanes": "1.4.1", "maplibre-gl-lanes": "1.7.0",
"pmtiles": "4.5.0", "pmtiles": "4.5.0",
"suncalc": "2.1.3" "suncalc": "2.1.4"
} }
}, },
"node_modules/@mapbox/jsonlint-lines-primitives": { "node_modules/@mapbox/jsonlint-lines-primitives": {
@@ -58,9 +59,9 @@
} }
}, },
"node_modules/@maplibre/geojson-vt": { "node_modules/@maplibre/geojson-vt": {
"version": "6.3.0", "version": "7.0.1",
"resolved": "https://registry.npmjs.org/@maplibre/geojson-vt/-/geojson-vt-6.3.0.tgz", "resolved": "https://registry.npmjs.org/@maplibre/geojson-vt/-/geojson-vt-7.0.1.tgz",
"integrity": "sha512-3Zw2jsU9pIJG3G2CQFbLjWj2MlAHodhD7cSY+15iywUuLmmkgzcKRnueVRZ4AcC/5wOtfhidcJAAzBpoBNs3Xg==", "integrity": "sha512-xq3+TiG4hZtx9lHjq/oZginEBtJLJTJqRVmEIhPDSznlkl231z/p4foorEqASpD233EHO9+GVnnu6GNA4Pl+YQ==",
"dev": true, "dev": true,
"license": "ISC", "license": "ISC",
"dependencies": { "dependencies": {
@@ -68,9 +69,9 @@
} }
}, },
"node_modules/@maplibre/maplibre-gl-style-spec": { "node_modules/@maplibre/maplibre-gl-style-spec": {
"version": "26.5.1", "version": "27.1.0",
"resolved": "https://registry.npmjs.org/@maplibre/maplibre-gl-style-spec/-/maplibre-gl-style-spec-26.5.1.tgz", "resolved": "https://registry.npmjs.org/@maplibre/maplibre-gl-style-spec/-/maplibre-gl-style-spec-27.1.0.tgz",
"integrity": "sha512-9ufQ5LR+Ldn87SILPVyRNz4wVm/sBrM2ZRv9VfjLRKYKIGAcvC1VFw/DEkJLAHqfMV8m03zDz1DUNTIUj/GvdA==", "integrity": "sha512-8EkIhwOdhjhX6HdugboL0JEGQejqln7Xuve7X2sFFU35IUaCgucHRuuO0+0yWSzYEmEa/z4knkpwOYZdrF/wFA==",
"dev": true, "dev": true,
"license": "ISC", "license": "ISC",
"dependencies": { "dependencies": {
@@ -88,9 +89,9 @@
} }
}, },
"node_modules/@maplibre/mlt": { "node_modules/@maplibre/mlt": {
"version": "1.3.0", "version": "1.4.0",
"resolved": "https://registry.npmjs.org/@maplibre/mlt/-/mlt-1.3.0.tgz", "resolved": "https://registry.npmjs.org/@maplibre/mlt/-/mlt-1.4.0.tgz",
"integrity": "sha512-7M2O7ABM80Oi8XPkfkrjKB8mOBIxGoVgkA52Mu4RMWoBvvMdagQ522+WxVYujZsMpqIr3BpzrTbXrm4k8lCzCQ==", "integrity": "sha512-kDjapA8mGAkSAAZr+ZF875w38PdJg7xS79oEADD7S/QdXELmd4hNHgZR/o5WRkWLBgWjKHJdHj/yRyYmU9Inbg==",
"dev": true, "dev": true,
"license": "(MIT OR Apache-2.0)", "license": "(MIT OR Apache-2.0)",
"dependencies": { "dependencies": {
@@ -109,6 +110,13 @@
"pbf": "^5.1.2" "pbf": "^5.1.2"
} }
}, },
"node_modules/@mdi/js": {
"version": "7.4.47",
"resolved": "https://registry.npmjs.org/@mdi/js/-/js-7.4.47.tgz",
"integrity": "sha512-KPnNOtm5i2pMabqZxpUz7iQf+mfrYZyKCZ8QNz85czgEt7cuHcGorWfdzUMWYA0SD+a6Hn4FmJ+YhzzzjkTZrQ==",
"dev": true,
"license": "Apache-2.0"
},
"node_modules/@types/geojson": { "node_modules/@types/geojson": {
"version": "7946.0.16", "version": "7946.0.16",
"resolved": "https://registry.npmjs.org/@types/geojson/-/geojson-7946.0.16.tgz", "resolved": "https://registry.npmjs.org/@types/geojson/-/geojson-7946.0.16.tgz",
@@ -169,16 +177,16 @@
"license": "ISC" "license": "ISC"
}, },
"node_modules/maplibre-contour": { "node_modules/maplibre-contour": {
"version": "0.1.1", "version": "0.2.0",
"resolved": "https://registry.npmjs.org/maplibre-contour/-/maplibre-contour-0.1.1.tgz", "resolved": "https://registry.npmjs.org/maplibre-contour/-/maplibre-contour-0.2.0.tgz",
"integrity": "sha512-0m267124bx+LJ5zM1mpB23uvO4sCrgOb4dWgwbUbGWGsDsWNA4g93XTXPoRQga6GAD6TDI7tzyowBzdADSPusg==", "integrity": "sha512-C5MV4+wLkDkCh851/HkQYCTCtEMfkVaLymkYtsc4Bp7ziBLPfKrNhlXrw2IAblo1/Y3xjzgg0dO2bxRSjcAuZQ==",
"dev": true, "dev": true,
"license": "BSD-3-Clause" "license": "BSD-3-Clause"
}, },
"node_modules/maplibre-gl": { "node_modules/maplibre-gl": {
"version": "6.17.0", "version": "6.21.0",
"resolved": "https://registry.npmjs.org/maplibre-gl/-/maplibre-gl-6.17.0.tgz", "resolved": "https://registry.npmjs.org/maplibre-gl/-/maplibre-gl-6.21.0.tgz",
"integrity": "sha512-2chIZwpLGenoUQOcnm9Pk4SLbA8ppNFq8jlpXiq9vcYm3Y1wJ3fc82FL0GLwBaPYJCLzPv/mC46KEupVov75rQ==", "integrity": "sha512-mjMFzw99R1kvuWo3xj6XKcFFbVpwTPhO7g2TeyJyT5DdM1E6zKIC/uWG17WpXO6dnRFZ/3un9k44+KtDNjD2Hw==",
"dev": true, "dev": true,
"license": "BSD-3-Clause", "license": "BSD-3-Clause",
"dependencies": { "dependencies": {
@@ -186,9 +194,9 @@
"@mapbox/tiny-sdf": "^2.3.0", "@mapbox/tiny-sdf": "^2.3.0",
"@mapbox/unitbezier": "^1.0.0", "@mapbox/unitbezier": "^1.0.0",
"@mapbox/vector-tile": "^3.0.0", "@mapbox/vector-tile": "^3.0.0",
"@maplibre/geojson-vt": "^6.3.0", "@maplibre/geojson-vt": "^7.0.1",
"@maplibre/maplibre-gl-style-spec": "^26.5.1", "@maplibre/maplibre-gl-style-spec": "^27.0.0",
"@maplibre/mlt": "^1.3.0", "@maplibre/mlt": "^1.4.0",
"@maplibre/vt-pbf": "^4.3.3", "@maplibre/vt-pbf": "^4.3.3",
"@types/geojson": "^7946.0.16", "@types/geojson": "^7946.0.16",
"bidi-js": "^1.1.0", "bidi-js": "^1.1.0",
@@ -196,10 +204,11 @@
"gl-matrix": "^3.4.4", "gl-matrix": "^3.4.4",
"kdbush": "^4.1.0", "kdbush": "^4.1.0",
"murmurhash-js": "^1.0.0", "murmurhash-js": "^1.0.0",
"pbf": "^5.1.2", "pbf": "^5.2.1",
"potpack": "^2.1.0", "potpack": "^2.1.0",
"quickselect": "^3.0.0", "quickselect": "^3.0.0",
"tinyqueue": "^3.0.0" "tinyqueue": "^3.0.0",
"zustand": "^5.1.0"
}, },
"engines": { "engines": {
"node": ">=16.14.0", "node": ">=16.14.0",
@@ -210,9 +219,9 @@
} }
}, },
"node_modules/maplibre-gl-lanes": { "node_modules/maplibre-gl-lanes": {
"version": "1.4.1", "version": "1.7.0",
"resolved": "https://registry.npmjs.org/maplibre-gl-lanes/-/maplibre-gl-lanes-1.4.1.tgz", "resolved": "https://registry.npmjs.org/maplibre-gl-lanes/-/maplibre-gl-lanes-1.7.0.tgz",
"integrity": "sha512-xlq/bUfbRG/7dXd+P5jZkXOW0FA2RwadNNv8KR8LLzNuiZUWuqQxXmPlk3PXNoCWNMFQ3aaro6BSgFQpNomlhg==", "integrity": "sha512-inQQtbA67gtPuC5naeeMGmqbS0K1FzKxvo2aXhTKD80NbVr8qckltqTqXArLxZVT4WRV54HXjhwfDGFydYDKJA==",
"dev": true, "dev": true,
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
@@ -240,13 +249,13 @@
"license": "MIT" "license": "MIT"
}, },
"node_modules/pbf": { "node_modules/pbf": {
"version": "5.1.2", "version": "5.2.1",
"resolved": "https://registry.npmjs.org/pbf/-/pbf-5.1.2.tgz", "resolved": "https://registry.npmjs.org/pbf/-/pbf-5.2.1.tgz",
"integrity": "sha512-mnvGdvOrIvJOBGUEdGkrVXjN8E/VkIJCkf2eS1DH2yv82ORUlLttmDt0rWY38yYZmVwciZwBUvHM20qxBZf40w==", "integrity": "sha512-5s6y6g3akGMF98eemb+3QZAWTCUHyox40TJOwcY4M1w40RvoXrfbRUVmY02RlRiEPyE6KVaM0xxfF4+4vjSJTQ==",
"dev": true, "dev": true,
"license": "BSD-3-Clause", "license": "BSD-3-Clause",
"dependencies": { "dependencies": {
"resolve-protobuf-schema": "^2.1.0" "protocol-buffers-schema": "^3.6.1"
}, },
"bin": { "bin": {
"pbf": "bin/pbf" "pbf": "bin/pbf"
@@ -293,20 +302,10 @@
"node": ">=0.10.0" "node": ">=0.10.0"
} }
}, },
"node_modules/resolve-protobuf-schema": {
"version": "2.1.0",
"resolved": "https://registry.npmjs.org/resolve-protobuf-schema/-/resolve-protobuf-schema-2.1.0.tgz",
"integrity": "sha512-kI5ffTiZWmJaS/huM8wZfEMer1eRd7oJQhDuxeCLe3t7N7mX3z94CN0xPxBQxFYQTSNz9T0i+v6inKqSdK8xrQ==",
"dev": true,
"license": "MIT",
"dependencies": {
"protocol-buffers-schema": "^3.3.1"
}
},
"node_modules/suncalc": { "node_modules/suncalc": {
"version": "2.1.3", "version": "2.1.4",
"resolved": "https://registry.npmjs.org/suncalc/-/suncalc-2.1.3.tgz", "resolved": "https://registry.npmjs.org/suncalc/-/suncalc-2.1.4.tgz",
"integrity": "sha512-7DWCsxPKRPMtylyGqSrgNBr+pseyczJGqb4NCpW2EziwNHaSuHc9w1lL4i91IyDw5CnPUWqBNBWyd/vFjr4rTw==", "integrity": "sha512-V7oSdbSezigEpbqnNWKujDlZaE/QA/0w5IbP/vXX+eIF+EtiE8e9BkSapsOFZc84jJkI3QlklYTWtMqzj9tZQg==",
"dev": true "dev": true
}, },
"node_modules/tinyqueue": { "node_modules/tinyqueue": {
@@ -315,6 +314,36 @@
"integrity": "sha512-gRa9gwYU3ECmQYv3lslts5hxuIa90veaEcxDYuu3QGOIAEM2mOZkVHp48ANJuu1CURtRdHKUBY5Lm1tHV+sD4g==", "integrity": "sha512-gRa9gwYU3ECmQYv3lslts5hxuIa90veaEcxDYuu3QGOIAEM2mOZkVHp48ANJuu1CURtRdHKUBY5Lm1tHV+sD4g==",
"dev": true, "dev": true,
"license": "ISC" "license": "ISC"
},
"node_modules/zustand": {
"version": "5.1.0",
"resolved": "https://registry.npmjs.org/zustand/-/zustand-5.1.0.tgz",
"integrity": "sha512-ciJZlP48M1PTQbVQq81CGVFxHTLpZNrFjKqwjtCU34AWuXTZT/jrF3p9+fI84Cf1eSCMLapxqBy/SNTfwOBuqA==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=12.20.0"
},
"peerDependencies": {
"@types/react": ">=18.0.0",
"immer": ">=9.0.6",
"react": ">=18.0.0",
"use-sync-external-store": ">=1.2.0"
},
"peerDependenciesMeta": {
"@types/react": {
"optional": true
},
"immer": {
"optional": true
},
"react": {
"optional": true
},
"use-sync-external-store": {
"optional": true
}
}
} }
} }
} }
+5 -4
View File
@@ -3,11 +3,12 @@
"private": true, "private": true,
"description": "Version pins for public/vendor/ only, synced by bin/vendor-sync.mjs. Not a build step, the app serves the vendored copies.", "description": "Version pins for public/vendor/ only, synced by bin/vendor-sync.mjs. Not a build step, the app serves the vendored copies.",
"devDependencies": { "devDependencies": {
"@mdi/js": "7.4.47",
"flag-icons": "7.6.0", "flag-icons": "7.6.0",
"maplibre-contour": "0.1.1", "maplibre-contour": "0.2.0",
"maplibre-gl": "6.17.0", "maplibre-gl": "6.21.0",
"maplibre-gl-lanes": "1.4.1", "maplibre-gl-lanes": "1.7.0",
"pmtiles": "4.5.0", "pmtiles": "4.5.0",
"suncalc": "2.1.3" "suncalc": "2.1.4"
} }
} }
+2 -1
View File
@@ -1,4 +1,5 @@
{ {
"label": "Camper POIs (Overpass)", "label": "Camper POIs (Overpass)",
"command": "./run.rb" "command": "./run.rb",
"route": true
} }
+10 -1
View File
@@ -7,10 +7,19 @@
# did all the real work for the "rake overpass:pois" dev-time task this # did all the real work for the "rake overpass:pois" dev-time task this
# plugin now sits alongside as a second way to run the same query. # plugin now sits alongside as a second way to run the same query.
# Along the trip's route (--route=<GeoJSON LineString file> --corridor-km):
# Overpass' around: with the route thinned to a vertex every half corridor.
require_relative "../../lib/maptool/overpass_pois" require_relative "../../lib/maptool/overpass_pois"
require_relative "../../lib/maptool/corridor"
args = ARGV.to_h { |arg| arg.sub(/\A--/, "").split("=", 2) } args = ARGV.to_h { |arg| arg.sub(/\A--/, "").split("=", 2) }
bbox = %w[south west north east].map { |key| Float(args.fetch(key)) } bbox = %w[south west north east].map { |key| Float(args.fetch(key)) }
around = if args["route"]
corridor = Float(args.fetch("corridor-km"))
line = Maptool::Corridor.thin(JSON.parse(File.read(args["route"]))["coordinates"], [corridor / 2, 0.5].max)
[corridor * 1000, line]
end
response = Maptool::OverpassPois.fetch(bbox) response = Maptool::OverpassPois.fetch(bbox, timeout: around ? 180 : 60, around: around)
puts JSON.generate(Maptool::OverpassPois.to_geojson(response)) puts JSON.generate(Maptool::OverpassPois.to_geojson(response))
+169
View File
@@ -0,0 +1,169 @@
[DeviceInfo]
VendorName=ESPHome
VendorNumber=1
BaudRate_10=0
BaudRate_20=0
BaudRate_50=0
BaudRate_125=1
BaudRate_250=1
BaudRate_500=1
BaudRate_800=0
BaudRate_1000=1
SimpleBootUpMaster=0
SimpleBootUpSlave=1
Granularity=8
DynamicChannelsSupported=0
CompactPDO=0
GroupMessaging=0
NrOfRXPDO=0
NrOfTXPDO=4
LSS_Supported=0
[1008]
ParameterName=DeviceName
ObjectType=7
DataType=9
AccessType=R
[1009]
ParameterName=HardwareVersion
ObjectType=7
DataType=9
AccessType=R
[100a]
ParameterName=SoftwareVersion
ObjectType=7
DataType=9
AccessType=R
[1010]
ParameterName=ParamStore
ObjectType=9
[1010sub0]
ParameterName=Number of ParamStore Entries
ObjectType=7
DataType=5
AccessType=R
[1010sub1]
ParameterName=Store All
ObjectType=7
DataType=7
AccessType=RW
[1010sub2]
ParameterName=Store Comm
ObjectType=7
DataType=7
AccessType=RW
[1011]
ParameterName=ParamReset
ObjectType=9
[1011sub0]
ParameterName=Number of ParamStore Entries
ObjectType=7
DataType=5
AccessType=R
[1011sub1]
ParameterName=Reset All Params
ObjectType=7
DataType=7
AccessType=RW
[1011sub2]
ParameterName=Reset Comm Params
ObjectType=7
DataType=7
AccessType=RW
[1017]
ParameterName=ProducerHeartbeatTime
ObjectType=7
DataType=6
AccessType=RW
[1018]
ParameterName=Identity
ObjectType=9
[1018sub0]
ParameterName=Number of Entries
ObjectType=7
DataType=5
AccessType=R
[1018sub1]
ParameterName=VendorId
ObjectType=7
DataType=7
AccessType=R
[1018sub2]
ParameterName=ProductCode
ObjectType=7
DataType=7
AccessType=R
[1018sub3]
ParameterName=RevisionNumber
ObjectType=7
DataType=7
AccessType=R
[1018sub4]
ParameterName=SerialNumber
ObjectType=7
DataType=7
AccessType=R
[3000]
ParameterName=Firmware
ObjectType=9
[3000sub0]
ParameterName=Firmware Max Index
ObjectType=7
DataType=5
AccessType=R
DefaultValue=0
[3000sub1]
ParameterName=Firmware Command
ObjectType=7
DataType=7
AccessType=RW
DefaultValue=0
[3000sub2]
ParameterName=Firmware Size
ObjectType=7
DataType=7
AccessType=RW
DefaultValue=0
[3000sub3]
ParameterName=Firmware MD5
ObjectType=7
DataType=0xf
AccessType=W
[3000sub4]
ParameterName=Firmware Data
ObjectType=7
DataType=0xf
AccessType=W
[3000sub5]
ParameterName=Firmware Flags
ObjectType=7
DataType=7
AccessType=R
+3278 -195
View File
File diff suppressed because it is too large. Load diff
+52
View File
@@ -0,0 +1,52 @@
{
"name": "Road",
"screen": "16 × 10 cells (the navigator's 16″, 1280 × 800)",
"columns": 16,
"rows": 10,
"cell": 80,
"map": "2 / 1 / 10 / 14",
"menu": { "area": "2 / 10 / 10 / 17", "map": "2 / 1 / 10 / 10" },
"cells": [
{ "area": "1 / 1 / 2 / 5", "widget": "maneuver" },
{ "area": "1 / 5 / 2 / 9", "widget": "field", "value": "speed" },
{ "area": "1 / 9 / 2 / 11", "widget": "field", "value": "altitude" },
{ "area": "1 / 11 / 2 / 13", "widget": "field", "value": "time" },
{ "area": "1 / 13 / 2 / 15", "widget": "field", "value": "sun" },
{ "area": "1 / 15 / 2 / 17", "widget": "status" },
{ "area": "2 / 1 / 3 / 5", "widget": "ahead" },
{ "area": "2 / 1 / 5 / 6", "widget": "border" },
{ "area": "2 / 14 / 3 / 17", "widget": "field", "value": "nextStop", "small": true },
{ "area": "3 / 14 / 4 / 17", "widget": "field", "value": "toNextStop" },
{ "area": "4 / 14 / 5 / 17", "widget": "field", "value": "etaNextStop" },
{ "area": "5 / 14 / 6 / 17", "widget": "field", "value": "toEnd" },
{ "area": "6 / 14 / 9 / 17", "widget": "elevation", "km": 10 },
{ "area": "9 / 14 / 10 / 17", "widget": "compass" },
{ "area": "10 / 1 / 11 / 3", "widget": "key", "action": "trip", "key": "F1" },
{ "area": "10 / 3 / 11 / 5", "widget": "key", "action": "points", "key": "F2" },
{ "area": "10 / 5 / 11 / 7", "widget": "key", "action": "layers", "key": "F3" },
{ "area": "10 / 7 / 11 / 9", "widget": "key", "action": "search", "key": "/" },
{ "area": "10 / 9 / 11 / 11", "widget": "key", "action": "menu", "key": "F5" },
{ "area": "10 / 11 / 11 / 12", "widget": "key", "action": "zoomOut", "key": "-" },
{ "area": "10 / 12 / 11 / 13", "widget": "key", "action": "zoomIn", "key": "+" },
{ "area": "10 / 13 / 11 / 14", "widget": "key", "action": "pitch", "key": "3" },
{ "area": "10 / 14 / 11 / 15", "widget": "key", "action": "follow", "key": "f" },
{ "area": "10 / 15 / 11 / 16", "widget": "key", "action": "terrain", "key": "t" },
{ "area": "10 / 16 / 11 / 17", "widget": "key", "action": "palette", "key": "n" }
],
"bindings": [
{ "input": "pad.K1", "action": "trip", "led": "cyan" },
{ "input": "pad.K2", "action": "points", "led": "cyan" },
{ "input": "pad.K3", "action": "layers", "led": "cyan" },
{ "input": "pad.K4", "action": "search", "led": "cyan" },
{ "input": "pad.K5", "action": "menu", "menu": "close", "led": "cyan" },
{ "input": "pad.K6", "action": "pitch", "led": "white" },
{ "input": "pad.K7", "action": "terrain", "led": "yellow" },
{ "input": "pad.K8", "action": "palette", "led": "yellow" },
{ "input": "pad.E1", "action": "panX", "menu": "rows" },
{ "input": "pad.E1 press", "menu": "enter" },
{ "input": "pad.E2", "action": "panY" },
{ "input": "pad.E2 press", "output": "relays.1" },
{ "input": "pad.E3", "action": "zoom" },
{ "input": "pad.E3 press", "action": "follow" }
]
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 3.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 11 KiB

+9
View File
@@ -0,0 +1,9 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512">
<!-- Full-bleed background so the same file works as a maskable icon;
the artwork stays inside the central 80% safe zone. -->
<rect width="512" height="512" fill="#1a1a1a"/>
<path d="M120 380 C 170 330, 200 400, 250 350 S 330 300, 300 250" fill="none" stroke="#f2b632"
stroke-width="18" stroke-linecap="round" stroke-dasharray="2 34"/>
<path d="M330 110 a 70 70 0 0 1 70 70 c 0 52 -70 128 -70 128 s -70 -76 -70 -128 a 70 70 0 0 1 70 -70 z" fill="#fff"/>
<circle cx="330" cy="180" r="26" fill="#1a1a1a"/>
</svg>

After

Width:  |  Height:  |  Size: 599 B

+569
View File
@@ -0,0 +1,569 @@
import { isLoggedIn } from "/js/auth.js";
import { onRouteChanged, requestReroute, notifyRouteProgress, currentVehicle } from "/js/panels.js";
import { effectiveLimit } from "/js/speed_limits.js";
import { elevationAt } from "/js/dem.js";
// The car's dashboard over the map, off the CAN signals (GET /api/can,
// names from data/can.json): one inclinometer — compass ring around a rear
// view (roll) and a side view (pitch) — and the speed. Which widgets show
// is per device (localStorage); levelling is the node's own (its offsets,
// set from /can.html). Turn signals / brake: when they're on the bus.
// Heading: driving, the GNSS course (from consecutive fixes); standing
// still, the compass (imu.heading, once the node sends it) — else the
// last course stays, dimmed.
const SIGNALS = { pitch: "imu.pitch", roll: "imu.roll", heading: "imu.heading", speed: "gnss.speed", alt: "gnss.alt", lat: "gnss.lat", lon: "gnss.lon", hdop: "gnss.hdop" };
const MOVING_MS = 1.5; // m/s: above this the GNSS course counts
const COURSE_MIN_M = 5; // fixes closer than this: too noisy for a course
const POLL_MS = 500;
// Simulated tilt: the terrain's slope along the course (pitch) and across
// it (roll), from the DEM 2·TILT_HALF_M apart — the terrain, not the road:
// a road cut into a hillside is flatter across than this reads.
const TILT_ZOOM = 12; // ~20–40 m pixels (offline terrain goes to 13)
const TILT_HALF_M = 15;
const STALE_S = 5; // older signal: shown as missing
const WARN = { roll: 20, pitch: 25 }; // ° — amber past these, red past 1.5×
const STORE_KEY = "maptool.dashboard";
// Navigation (the speed limit, what's ahead): along the route panel's route
// while on it (its speed_limits / signals / maneuvers from /api/route),
// else the limit of the road being driven (POST /api/road, map-matched).
const OVER_KMH = 3; // over the limit by more than this: warning
// Off the route → rerouting, after Ferrostar's split: deviation detected
// (farther than ON_ROUTE_M for OFF_ROUTE_FIXES fixes in a row, fixes with an
// HDOP over MAX_HDOP don't count), then a new route from the position to
// the points not reached yet — at most every REROUTE_EVERY_MS, only moving.
const ON_ROUTE_M = 30; // farther from the route line: off it
const OFF_ROUTE_FIXES = 3;
const MAX_HDOP = 5; // ~ over 10 m off at the NEO-6M's few m UERE
const REROUTE_EVERY_MS = 15000;
const ROAD_EVERY_MS = 4000; // /api/road at most this often, only while moving
const TRACE_STEP_M = 10; // fixes kept for /api/road at least this far apart
const LANES_AHEAD_M = 1000; // the next maneuver's lanes from this close (or LANES_AHEAD_S at the speed driven)
const LANES_AHEAD_S = 45;
const ARRIVE_M = 30; // this close to the end: arrived (navigation goes on: past it, the route turns back)
const ARRIVE_TYPES = [4, 5, 6]; // Valhalla's destination maneuvers
const DEFAULT_WIDGETS = { inclinometer: true, speed: true, altitude: true, navigation: true, banner: true };
// Step advance after Ferrostar's DistanceEntryExit: a maneuver stays the next one
// until the position is this far past it (not before reaching it: at the turn the
// turn is still shown, "now"), then the one after it
const STEP_EXIT_M = 5;
const THEN_M = 300; // the maneuver after the next one shown with it when it follows this closely
// Voice prompts (speechSynthesis, Valhalla's verbal instructions), on/off in
// drive mode's Menu: "In 400 m, turn right…" from SOON_S ahead, the
// instruction itself NOW_S before the maneuver (at least the metres given).
export const VOICE_KEY = "maptool.voice";
const SOON_S = 25, SOON_M = 400;
const NOW_S = 7, NOW_M = 60;
const DEFAULT_OPACITY = 0.45; // the card's background, the map shows through
const load = () => {
try { const saved = JSON.parse(localStorage.getItem(STORE_KEY)) || {}; return { ...saved, widgets: { ...DEFAULT_WIDGETS, ...saved.widgets } }; }
catch { return { widgets: { ...DEFAULT_WIDGETS } }; }
};
const RAD = Math.PI / 180;
// meters between two [lon, lat] (equirectangular: fine at these distances)
const meters = ([lon1, lat1], [lon2, lat2]) => Math.hypot((lon2 - lon1) * Math.cos(((lat1 + lat2) / 2) * RAD), lat2 - lat1) * 111320;
export const distance = (m) => (m >= 1000 ? `${(m / 1000).toFixed(1)} km` : `${Math.round(m / 10) * 10} m`);
const esc = (text) => String(text ?? "").replace(/[&<>"]/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;" })[c]);
// An arrow from the bottom center turning by `angle` (° from straight on),
// in a 24 × 32 box: a lane's, and the banner's maneuver.
function arrowPath(angle, cls) {
const a = (angle * Math.PI) / 180;
const [x, y] = [12 + 9 * Math.sin(a), 15 - 9 * Math.cos(a)];
const back = (side) => `${(x - 5 * Math.sin(a + side)).toFixed(1)} ${(y + 5 * Math.cos(a + side)).toFixed(1)}`;
return `<path class="${cls}" d="M12 30 V15 L${x.toFixed(1)} ${y.toFixed(1)} M${back(0.6)} L${x.toFixed(1)} ${y.toFixed(1)} L${back(-0.6)}"/>`;
}
const uturnPath = (cls) => `<path class="${cls}" d="M14 30 V14 A5 5 0 0 0 4 14 V20 M1 17 L4 21 L7 17"/>`;
// Valhalla's maneuver types (its API docs) → the banner's arrow angle;
// "uturn", "arrive", "roundabout" drawn their own way.
const MANEUVER_ANGLES = { 1: 0, 2: 45, 3: -45, 7: 0, 8: 0, 9: 45, 10: 90, 11: 135, 14: -135, 15: -90, 16: -45, 17: 0, 18: 45, 19: -45,
20: 45, 21: -45, 22: 0, 23: 30, 24: -30, 25: 0, 37: 30, 38: -30 };
export function maneuverSvg(type) {
let body;
if (type === 12 || type === 13) body = uturnPath("dash-banner__arrow");
else if (type >= 4 && type <= 6) body = `<path class="dash-banner__arrow" d="M8 30 V4 M8 5 H19 L16 9 L19 13 H8"/>`; // a flag: arriving
else if (type === 26 || type === 27) body = `<circle class="dash-banner__arrow" cx="12" cy="14" r="6"/><path class="dash-banner__arrow" d="M12 30 V20 M12 8 V2 M9 5 L12 2 L15 5"/>`;
else body = arrowPath(MANEUVER_ANGLES[type] ?? 0, "dash-banner__arrow");
return `<svg viewBox="0 0 24 32" class="dash-banner__icon">${body}</svg>`;
}
// Valhalla's lane direction bits → the arrow's angle (° from straight on)
const LANE_ANGLES = { 2: 0, 16: -45, 8: -90, 4: -135, 32: 45, 64: 90, 128: 135, 512: -25, 1024: 25 };
const LANE_REVERSE = 256;
// One lane as an SVG: an arrow per direction it allows; `active` (the
// directions to take, a bitmask too) drawn bold.
export function laneSvg({ directions, active = 0 }) {
const arrow = (bit) => {
const cls = `dash-lane__arrow${active & bit ? " dash-lane__take" : ""}`;
return bit === LANE_REVERSE ? uturnPath(cls) : arrowPath(LANE_ANGLES[bit], cls);
};
const bits = [2, 16, 8, 4, 32, 64, 128, 512, 1024, LANE_REVERSE].filter((bit) => directions & bit);
return `<svg viewBox="0 0 24 32" class="dash-lane${active ? " dash-lane--go" : ""}">${(bits.length ? bits : [2]).map(arrow).join("")}</svg>`;
}
// A route prepared for "where am I on it": km at every vertex, maneuvers' start km.
function prepareRoute(route) {
if (!route?.properties?.speed_limits) return null;
const coords = route.geometry.coordinates;
const km = [0];
for (let i = 1; i < coords.length; i++) km.push(km[i - 1] + meters(coords[i - 1], coords[i]) / 1000);
let start = 0;
const maneuvers = route.properties.maneuvers.map((m) => { const at = start; start += m.km; return { ...m, at }; });
let leg = 0;
const viaKm = (route.properties.legs_km || []).slice(0, -1).map((length) => (leg += length)); // km at each via point
return { coords, km, limits: route.properties.speed_limits, roads: route.properties.roads || [], signals: route.properties.signals || [], maneuvers, viaKm };
}
// Nearest point on the route: [km along it, meters off it]. Near the last
// one first (fromKm: LOCATE_BACK_KM behind to LOCATE_AHEAD_KM ahead), so a
// route that comes back along the same road or crosses itself doesn't jump
// to the other pass — progress goes forward, as Ferrostar's does; the whole
// route only when that window has nothing close (a reroute, a restart).
const LOCATE_BACK_KM = 0.1;
const LOCATE_AHEAD_KM = 3;
function locate(route, position, fromKm = null) {
if (fromKm != null) {
const near = locateIn(route, position, fromKm - LOCATE_BACK_KM, fromKm + LOCATE_AHEAD_KM);
if (near[1] <= ON_ROUTE_M) return near;
}
return locateIn(route, position, -Infinity, Infinity);
}
function locateIn(route, position, fromKm, toKm) {
let best = [0, Infinity];
const { coords, km } = route;
const cos = Math.cos(position[1] * RAD);
for (let i = 1; i < coords.length; i++) {
if (km[i] < fromKm || km[i - 1] > toKm) continue;
const [ax, ay] = [coords[i - 1][0] * cos, coords[i - 1][1]];
const [bx, by] = [coords[i][0] * cos, coords[i][1]];
const [px, py] = [position[0] * cos, position[1]];
const len2 = (bx - ax) ** 2 + (by - ay) ** 2;
const t = len2 ? Math.max(0, Math.min(1, ((px - ax) * (bx - ax) + (py - ay) * (by - ay)) / len2)) : 0;
const off = Math.hypot(px - (ax + t * (bx - ax)), py - (ay + t * (by - ay))) * 111320;
if (off < best[1]) best = [km[i - 1] + t * (km[i] - km[i - 1]), off];
}
return best;
}
const ticks = Array.from({ length: 36 }, (_, i) => {
const a = i * 10;
const long = a % 30 === 0;
return `<line x1="0" y1="-95" x2="0" y2="${long ? -86 : -90}" transform="rotate(${a})"/>`;
}).join("");
const labels = ["N", "E", "S", "W"].map((l, i) => `<text y="-74" transform="rotate(${i * 90})" class="${l === "N" ? "dash-n" : ""}">${l}</text>`).join("");
const INCLINOMETER = `
<svg viewBox="-100 -100 200 200" class="dash-incl">
<circle r="97" class="dash-face"/>
<g class="dash-ring">${ticks}${labels}</g>
<path d="M0,-99 l-6,-0 l6,12 l6,-12 z" class="dash-lubber"/>
<text y="-46" class="dash-heading"></text>
<line x1="-62" y1="16" x2="-8" y2="16" class="dash-ground"/>
<line x1="8" y1="16" x2="62" y2="16" class="dash-ground"/>
<g transform="translate(-35,14)"><g class="dash-roll">
<path d="M-20,0 h40 v-9 l-5,-14 h-30 l-5,14 z" class="dash-car"/>
<rect x="-20" y="-1" width="9" height="5" rx="1" class="dash-wheel"/><rect x="11" y="-1" width="9" height="5" rx="1" class="dash-wheel"/>
</g></g>
<g transform="translate(35,14)"><g class="dash-pitch">
<path d="M-26,-4 h52 v-9 l-9,-2 l-7,-10 h-21 l-5,10 l-10,2 z" class="dash-car"/>
<circle cx="-15" cy="-2" r="5" class="dash-wheel"/><circle cx="15" cy="-2" r="5" class="dash-wheel"/>
</g></g>
<text x="-35" y="44" class="dash-value dash-roll-value"></text>
<text x="35" y="44" class="dash-value dash-pitch-value"></text>
<text x="-35" y="60" class="dash-caption">roll</text>
<text x="35" y="60" class="dash-caption">pitch</text>
</svg>`;
// The driving grid (driving.js) reads the dashboard: watchDashboard(cb)
// polls the bus while it's on, the overlay's card or not, and hands each
// poll's state to cb; watchDashboard(null) stops that.
let instance = null;
export function watchDashboard(callback) {
if (!instance || !isLoggedIn()) return; // /api/can wants a login
instance._watch = callback;
if (callback && !instance._timer) instance._poll();
}
export class DashboardControl {
constructor(map) {
instance = this;
this._map = map;
this._settings = load();
this._timer = null;
this._values = {};
this._fix = null; // last fix a course was measured from
this._course = null;
this._route = prepareRoute(onRouteChanged((route) => {
this._route = prepareRoute(route);
this._lastAt = 0;
this._offFixes = 0;
this._sentKm = undefined; // the new route drawn by the next fix
this._said = new Set();
}));
this._said = new Set(); // voice prompts given: "maneuver index:soon|now"
this._trace = []; // [lon, lat] fixes TRACE_STEP_M apart, for /api/road
this._road = null; // its last answer
this._roadAt = 0;
this._lastAt = 0; // km along the route at the last fix on it
this._offFixes = 0;
this._rerouteAt = 0;
}
// What the simulation doesn't send, from the terrain at its position: the
// altitude, and pitch / roll in degrees (nose up and right side down
// positive, as the inclinometer draws them) — unless a node sends them.
async _simulateTerrain() {
const { lat, lon } = this._values;
if (lat == null) return;
this._offlineTerrain ??= fetch("/api/terrain-tiles").then((r) => r.json()).then((d) => d.available).catch(() => false);
const offline = await this._offlineTerrain;
const rad = Math.PI / 180;
const at = (bearing) => {
const dx = TILT_HALF_M * Math.sin(bearing * rad);
const dy = TILT_HALF_M * Math.cos(bearing * rad);
return elevationAt(lon + dx / (111320 * Math.cos(lat * rad)), lat + dy / 111320, offline, { zoom: TILT_ZOOM, smooth: true });
};
if (this._values.alt == null) {
this._values.alt = await elevationAt(lon, lat, offline, { zoom: TILT_ZOOM, smooth: true });
}
if (this._course == null) return;
const [front, back, right, left] = await Promise.all([0, 180, 90, 270].map((b) => at(this._course + b)));
if ([front, back, right, left].includes(null)) return;
const deg = (rise) => Math.atan(rise / (2 * TILT_HALF_M)) / rad;
this._values.pitch = deg(front - back);
this._values.roll = deg(left - right);
}
// To the route panel (the driven part dimmed), when it moved ≥ 10 m.
_progress(km) {
if (km === this._sentKm || (km != null && this._sentKm != null && Math.abs(km - this._sentKm) < 0.01)) return;
this._sentKm = km;
notifyRouteProgress(km);
}
// With no route: the nearest of /api/road's signals ahead that's still in
// front (within 90° of the heading), straight-line metres.
_signalAhead(position) {
const heading = this._heading()?.deg;
if (heading == null || !this._road?.signals?.length) return null;
const ahead = this._road.signals
.map(([lon, lat]) => {
const dx = (lon - position[0]) * Math.cos(position[1] * RAD), dy = lat - position[1];
const off = Math.abs((((Math.atan2(dx, dy) / RAD - heading) % 360) + 540) % 360 - 180);
return off < 90 ? meters(position, [lon, lat]) : null;
})
.filter((m) => m != null);
return ahead.length ? Math.min(...ahead) : null;
}
_speak(index, maneuver, m, speed) {
let voiceOn = false;
try { voiceOn = localStorage.getItem(VOICE_KEY) === "on"; } catch { /* private window */ }
if (!voiceOn || !window.speechSynthesis) return;
const now = Math.max(NOW_M, speed * NOW_S);
let stage = null, text = null;
if (m <= now) [stage, text] = ["now", maneuver.say];
else if (m <= Math.max(SOON_M, speed * SOON_S) && m > 2 * now && maneuver.alert) {
[stage, text] = ["soon", `In ${distance(m).replace(" m", " meters").replace(" km", " kilometers")}, ${maneuver.alert[0].toLowerCase()}${maneuver.alert.slice(1)}`];
}
if (!text || this._said.has(`${index}:${stage}`)) return;
this._said.add(`${index}:soon`).add(`${index}:${stage}`);
speechSynthesis.speak(new SpeechSynthesisUtterance(text));
}
// The limit and what's ahead: from the route while on it, else the road.
_navigate() {
const { lat, lon, speed } = this._values;
if (lat == null || lon == null) return (this._nav = null);
const position = [lon, lat];
if (!this._trace.length || meters(this._trace.at(-1), position) >= TRACE_STEP_M) this._trace = [...this._trace.slice(-7), position];
const [at, off] = this._route ? locate(this._route, position, this._lastAt || null) : [0, Infinity];
const fresh = position.join() !== this._lastFix; // polled faster than the fixes come
this._lastFix = position.join();
if (fresh && this._route && off > ON_ROUTE_M && (this._values.hdop ?? 0) <= MAX_HDOP) this._offFixes++;
else if (off <= ON_ROUTE_M) this._offFixes = 0;
if (this._route && this._offFixes < OFF_ROUTE_FIXES) {
const { limits, roads, signals, maneuvers } = this._route;
// the road's sign capped by the profile's own limit for that country and road class
const limitAt = (k) => {
const road = roads.findLast(([km]) => km <= k);
const sign = limits.findLast(([km]) => km <= k)?.[1] ?? null;
return road ? effectiveLimit(sign, road[2], road[1], currentVehicle) : sign;
};
const limit = limitAt(at);
const nextKm = [...limits, ...roads].map(([km]) => km).filter((km) => km > at).sort((a, b) => a - b).find((km) => limitAt(km) !== limit);
const next = nextKm != null ? [nextKm, limitAt(nextKm)] : null;
const signal = signals.find(([, , km]) => km > at);
const index = maneuvers.findIndex((m) => m.at > at - STEP_EXIT_M / 1000);
const maneuver = maneuvers[index];
const then = maneuvers[index + 1];
const onStreet = maneuvers[index - 1]?.street; // the one being driven: the last maneuver's
if (off <= ON_ROUTE_M) {
this._lastAt = at;
this._progress(at);
}
this._nav = {
limit,
next: next && { limit: next[1], m: (next[0] - at) * 1000 },
country: roads.findLast(([km]) => km <= at)?.[2] ?? null,
signal: signal && (signal[2] - at) * 1000,
maneuver: maneuver && { ...maneuver, m: Math.max(0, (maneuver.at - at) * 1000) },
then: maneuver && then && then.at - maneuver.at <= THEN_M / 1000 ? then : null,
street: onStreet,
arrived: ARRIVE_TYPES.includes(maneuvers.at(-1)?.type) && (!maneuver || (index === maneuvers.length - 1 && (maneuver.at - at) * 1000 <= ARRIVE_M)),
lanesM: Math.max(LANES_AHEAD_M, (speed ?? 0) * LANES_AHEAD_S),
};
if (maneuver && off <= ON_ROUTE_M) this._speak(index, maneuver, (maneuver.at - at) * 1000, speed ?? 0);
return;
}
this._progress(null);
const road = this._road;
this._nav = { limit: road ? effectiveLimit(road.speed_limit ?? null, road.country, road.road_class, currentVehicle) : null,
offRoute: !!this._route, street: road?.name, signal: this._signalAhead(position), country: road?.country ?? null };
if (this._route && (speed ?? 0) >= MOVING_MS && Date.now() - this._rerouteAt >= REROUTE_EVERY_MS) {
this._rerouteAt = Date.now();
requestReroute(position, this._route.viaKm.filter((km) => km <= this._lastAt).length);
}
if ((speed ?? 0) < MOVING_MS || this._trace.length < 2 || Date.now() - this._roadAt < ROAD_EVERY_MS) return;
this._roadAt = Date.now();
fetch("/api/road", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ points: this._trace }) })
.then((response) => (response.ok ? response.json() : null))
.then((road) => { this._road = road; })
.catch(() => { this._road = null; });
}
// Course over ground from the fix COURSE_MIN_M back, while moving.
_updateCourse({ lat, lon, speed }) {
if (lat == null || lon == null) return;
if (!this._fix || speed == null || speed < MOVING_MS) {
this._fix = { lat, lon };
return;
}
const rad = Math.PI / 180;
const dLon = (lon - this._fix.lon) * rad;
const y = Math.sin(dLon) * Math.cos(lat * rad);
const x = Math.cos(this._fix.lat * rad) * Math.sin(lat * rad) - Math.sin(this._fix.lat * rad) * Math.cos(lat * rad) * Math.cos(dLon);
const north = (lat - this._fix.lat) * 111320;
const east = (lon - this._fix.lon) * 111320 * Math.cos(lat * rad);
if (Math.hypot(north, east) < COURSE_MIN_M) return;
this._course = (Math.atan2(y, x) / rad + 360) % 360;
this._fix = { lat, lon };
}
mount(li) {
li.innerHTML = `
<div class="overlays-panel__row">
<input type="checkbox" class="overlays-panel__toggle">
<button type="button" class="overlays-panel__name" aria-expanded="false">Dashboard</button>
</div>
<p class="live-panel__status" hidden></p>
<div class="overlays-panel__details" hidden>
<label class="live-tracker__row"><input type="checkbox" data-widget="inclinometer"> Inclinometer &amp; compass</label>
<label class="live-tracker__row"><input type="checkbox" data-widget="speed"> Speed</label>
<label class="live-tracker__row"><input type="checkbox" data-widget="altitude"> Altitude</label>
<label class="live-tracker__row"><input type="checkbox" data-widget="navigation"> Speed limit &amp; 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>
<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");
const name = li.querySelector(".overlays-panel__name");
const details = li.querySelector(".overlays-panel__details");
name.addEventListener("click", () => {
details.hidden = !details.hidden;
name.setAttribute("aria-expanded", String(!details.hidden));
});
if (!isLoggedIn()) {
this._toggle.disabled = true;
li.title = "Log in to see the car's dashboard";
return;
}
for (const box of li.querySelectorAll("[data-widget]")) {
box.checked = !!this._settings.widgets[box.dataset.widget];
box.addEventListener("change", () => {
this._settings.widgets[box.dataset.widget] = box.checked;
this._save();
this._render();
});
}
this._toggle.addEventListener("change", () => (this._toggle.checked ? this._enable() : this._disable()));
const opacity = li.querySelector(".dash-opacity");
opacity.value = this._settings.opacity ?? DEFAULT_OPACITY;
opacity.addEventListener("input", () => {
this._settings.opacity = +opacity.value;
this._save();
this._card?.style.setProperty("--dash-alpha", opacity.value);
});
}
_save() {
try { localStorage.setItem(STORE_KEY, JSON.stringify(this._settings)); } catch { /* private window: just not kept */ }
}
_enable() {
this._card = document.createElement("div");
this._card.className = "dash-card";
this._card.style.setProperty("--dash-alpha", this._settings.opacity ?? DEFAULT_OPACITY);
this._card.innerHTML = `<div class="dash-nav"><div class="dash-limit"></div><div class="dash-ahead"></div></div>${INCLINOMETER}<div class="dash-speed"><span></span> km/h</div><div class="dash-alt"><span></span> m</div>`;
this._map.getContainer().appendChild(this._card);
// the next turn across the top, as in a car navigation
this._banner = document.createElement("div");
this._banner.className = "dash-banner";
this._banner.hidden = true;
this._map.getContainer().appendChild(this._banner);
this._status.hidden = false;
this._status.textContent = "Connecting…";
if (!this._timer) this._poll();
}
_disable() {
if (!this._watch) {
this._progress(null);
clearTimeout(this._timer);
this._timer = null;
}
this._card?.remove();
this._card = null;
this._banner?.remove();
this._banner = null;
this._status.hidden = true;
}
async _poll() {
if (this._busy) return; // the grid and the card both asked
this._busy = true;
try {
const response = await fetch("/api/can", { cache: "no-store" });
if (!response.ok) throw new Error(`HTTP ${response.status}`);
const data = await response.json();
const now = Date.parse(response.headers.get("Date")) / 1000 || Date.now() / 1000;
this._values = Object.fromEntries(Object.entries(SIGNALS).map(([key, name]) => {
const s = data.signals[name];
// Date has 1 s resolution: +1 so a fresh value isn't "stale"
return [key, s && now - s.at < STALE_S + 1 ? s.value : null];
}));
this._updateCourse(this._values);
this._simRunning = !!data.simulated; // /sim.html runs it
this._actions = data.actions || []; // can.json's SDO actions (levelling), POST /api/can/actions/<n>
if (this._simRunning) {
// simulated driving: the tilt of the terrain under it, not the IMU of the car standing at home
this._values.pitch = this._values.roll = null;
await this._simulateTerrain();
}
this._navigate();
this._status.textContent = this._simRunning ? "Simulated GNSS" : data.available ? "" : "CAN is off on this server";
this._status.hidden = !this._status.textContent;
} catch (e) {
this._values = {};
this._status.hidden = false;
this._status.textContent = `Can't reach the server: ${e.message}`;
}
this._render();
this._busy = false;
this._watch?.(this.state());
this._timer = this._card || this._watch ? setTimeout(() => this._poll(), POLL_MS) : null;
}
// What the driving grid shows: the signals, the navigation, the heading
// ({ deg, live }), the road's surface (off a route, /api/road), the CAN
// actions, and the km along the route (null off it).
state() {
const onRoute = this._route && this._offFixes < OFF_ROUTE_FIXES;
// the road's surface only off the route: back on it the last road's would stay (the terrain view never closed)
return { values: this._values, nav: this._nav, heading: this._heading(), simulated: !!this._simRunning, actions: this._actions || [],
surface: onRoute ? null : this._road?.surface ?? null, course: this._course, atKm: onRoute ? this._lastAt : null };
}
// Driving, the GNSS course; standing, the compass — else the last of either, not live.
_heading() {
const v = this._values;
const moving = v.speed != null && v.speed >= MOVING_MS;
const deg = moving ? this._course ?? v.heading : v.heading ?? this._course;
return deg == null ? null : { deg: (deg + 360) % 360, live: moving ? this._course != null : v.heading != null };
}
_render() {
if (!this._card) return;
const { widgets } = this._settings;
const v = this._values;
const svg = this._card.querySelector(".dash-incl");
svg.style.display = widgets.inclinometer ? "" : "none";
const speed = this._card.querySelector(".dash-speed");
speed.style.display = widgets.speed ? "" : "none";
const nav = this._card.querySelector(".dash-nav");
nav.style.display = widgets.navigation ? "" : "none";
const alt = this._card.querySelector(".dash-alt");
alt.style.display = widgets.altitude ? "" : "none";
alt.querySelector("span").textContent = v.alt == null ? "—" : Math.round(v.alt);
this._card.hidden = !widgets.inclinometer && !widgets.speed && !widgets.altitude && !widgets.navigation;
this._renderNav(nav);
this._renderBanner();
const severity = (key, value) => (value == null ? "" : Math.abs(value) >= WARN[key] * 1.5 ? "dash-bad" : Math.abs(value) >= WARN[key] ? "dash-warn" : "");
for (const key of ["roll", "pitch"]) {
const value = v[key];
// the pitch car faces right: nose up = counter-clockwise
svg.querySelector(`.dash-${key}`).setAttribute("transform", `rotate(${value == null ? 0 : key === "pitch" ? -value : value})`);
const text = svg.querySelector(`.dash-${key}-value`);
text.textContent = value == null ? "—" : `${value > 0 ? "+" : ""}${Math.round(value)}°`;
text.setAttribute("class", `dash-value dash-${key}-value ${severity(key, value)}`);
}
const heading = this._heading();
svg.querySelector(".dash-ring").setAttribute("transform", `rotate(${heading ? -heading.deg : 0})`);
svg.querySelector(".dash-ring").style.opacity = !heading ? 0.3 : heading.live ? 1 : 0.55;
svg.querySelector(".dash-heading").textContent = heading ? `${Math.round(heading.deg)}°` : "";
speed.querySelector("span").textContent = v.speed == null ? "—" : Math.round(v.speed * 3.6);
}
_renderNav(nav) {
const n = this._nav;
const limit = n?.limit;
const kmh = this._values.speed == null ? null : this._values.speed * 3.6;
const over = typeof limit === "number" && kmh != null && kmh > limit + OVER_KMH;
this._card.classList.toggle("dash-card--over", over);
const sign = nav.querySelector(".dash-limit");
sign.hidden = limit == null;
sign.className = `dash-limit${limit === "unlimited" ? " dash-limit--none" : ""}`;
sign.textContent = typeof limit === "number" ? limit : "";
const rows = [];
if (n?.offRoute) rows.push(`<div class="dash-offroute">Off the route — rerouting</div>`);
if (n?.next) rows.push(`<div><span class="dash-limit dash-limit--small${n.next.limit === "unlimited" ? " dash-limit--none" : ""}">${typeof n.next.limit === "number" ? n.next.limit : n.next.limit ? "" : "?"}</span> in ${distance(n.next.m)}</div>`);
if (n?.signal != null) rows.push(`<div><span class="dash-signal"></span> ${distance(n.signal)}</div>`);
if (n?.maneuver && !this._settings.widgets.banner) {
const { text, m, lanes } = n.maneuver;
rows.push(`<div class="dash-maneuver">${distance(m)} · ${esc(text)}</div>`);
if (lanes && m <= (n.lanesM ?? LANES_AHEAD_M)) {
rows.push(`<div class="dash-lanes">${lanes.map(laneSvg).join("")}</div>`);
}
}
nav.querySelector(".dash-ahead").innerHTML = rows.join("");
}
// Across the top: the next maneuver's arrow, distance and street (its
// instruction when it has no street), "then …" when the one after follows
// closely, its lanes from LANES_AHEAD_M, and the street being driven.
_renderBanner() {
const n = this._nav;
const show = this._settings.widgets.banner && !!(n?.maneuver || n?.arrived);
this._banner.hidden = !show;
if (!show) return;
this._banner.style.setProperty("--dash-alpha", Math.max(0.8, this._settings.opacity ?? DEFAULT_OPACITY));
if (n.arrived) {
this._banner.innerHTML = `<div class="dash-banner__main">${maneuverSvg(4)}<div><div class="dash-banner__distance">Arrived</div>` +
`<div class="dash-banner__street">${esc(n.street || "")}</div></div></div>`;
return;
}
const { m, type, street, text, exit, lanes } = n.maneuver;
const what = street ? `${exit ? `${exit}. exit · ` : ""}${esc(street)}` : esc(text);
const then = n.then ? `<div class="dash-banner__then">then ${maneuverSvg(n.then.type)} ${esc(n.then.street || n.then.text)}</div>` : "";
const lanesRow = lanes && m <= (n.lanesM ?? LANES_AHEAD_M) ? `<div class="dash-lanes dash-banner__lanes">${lanes.map(laneSvg).join("")}</div>` : "";
const onStreet = n.street ? `<div class="dash-banner__on">on ${esc(n.street)}</div>` : "";
this._banner.innerHTML = `<div class="dash-banner__main">${maneuverSvg(type)}<div><div class="dash-banner__distance">${distance(m)}</div>` +
`<div class="dash-banner__street">${what}</div></div></div>${lanesRow}${then}${onStreet}`;
}
}
+28
View File
@@ -0,0 +1,28 @@
import { DEBUG_ICON } from "/js/icons.js";
import { notifySidePanelOpen, onlyOneSidePanelOpen } from "/js/panels.js";
// Sidebar icon pinned to the bottom of the rail, logged-in only (map.js):
// a panel of links — every endpoint's state on the full-screen
// /status.html, the CANopen diagnostics — and the update check.
export class DebugControl {
mount(sidebar) {
this._container = document.createElement("div");
this._container.className = "sidebar-item sidebar-item--bottom";
this._container.innerHTML = `<button type="button" class="sidebar-icon" title="Status / debug" aria-label="Status / debug">${DEBUG_ICON}</button>`;
this._icon = this._container.querySelector(".sidebar-icon");
this._icon.addEventListener("click", () => this._togglePanel());
this._panel = document.getElementById("debug-panel");
this._panel.querySelector(".basemap-panel__close").addEventListener("click", () => this._togglePanel(false));
onlyOneSidePanelOpen(this._panel, () => this._icon.classList.remove("active"));
sidebar.appendChild(this._container);
}
_togglePanel(force) {
const open = force === undefined ? this._panel.hidden : force;
this._panel.hidden = !open;
this._icon.classList.toggle("active", open);
if (open) notifySidePanelOpen(this._panel);
}
}
+18 -6
View File
@@ -63,12 +63,24 @@ function fetchTile(z, x, y, offlineAvailable) {
// -> Promise<number|null> — null on a fetch/decode failure, or a point // -> Promise<number|null> — null on a fetch/decode failure, or a point
// falling outside a partial offline extract's zoom range. // falling outside a partial offline extract's zoom range.
export async function elevationAt(lng, lat, offlineAvailable) { // smooth: bilinear between the four pixels around the point (within the
const { tileX, tileY, fracX, fracY } = lngLatToTile(lng, lat, DEM_ZOOM); // tile) instead of the nearest one — for slopes over a few meters, where
const tile = await fetchTile(DEM_ZOOM, tileX, tileY, offlineAvailable); // nearest-pixel steps would read as 0° then a jump.
export async function elevationAt(lng, lat, offlineAvailable, { zoom = DEM_ZOOM, smooth = false } = {}) {
const { tileX, tileY, fracX, fracY } = lngLatToTile(lng, lat, zoom);
const tile = await fetchTile(zoom, tileX, tileY, offlineAvailable);
if (!tile) return null; if (!tile) return null;
const px = Math.min(tile.size - 1, Math.floor(fracX * tile.size)); const { elevations: e, size } = tile;
const py = Math.min(tile.size - 1, Math.floor(fracY * tile.size)); if (!smooth) {
return tile.elevations[py * tile.size + px]; const px = Math.min(size - 1, Math.floor(fracX * size));
const py = Math.min(size - 1, Math.floor(fracY * size));
return e[py * size + px];
}
const x = Math.min(size - 1.001, Math.max(0, fracX * size - 0.5));
const y = Math.min(size - 1.001, Math.max(0, fracY * size - 0.5));
const [x0, y0] = [Math.floor(x), Math.floor(y)];
const [tx, ty] = [x - x0, y - y0];
const at = (i, j) => e[(y0 + j) * size + x0 + i];
return (at(0, 0) * (1 - tx) + at(1, 0) * tx) * (1 - ty) + (at(0, 1) * (1 - tx) + at(1, 1) * tx) * ty;
} }
File diff suppressed because it is too large. Load diff
+817
View File
@@ -0,0 +1,817 @@
import { LngLatBounds, Marker } from "/vendor/maplibre-gl/maplibre-gl.mjs";
import { requestGnssFollow, onRouteChanged } from "/js/panels.js";
import { pauseFollow, resumeFollow, isFollowing } from "/js/gnss.js";
import { formatDuration } from "/js/route.js";
import { isLoggedIn } from "/js/auth.js";
import { watchDashboard, maneuverSvg, laneSvg, distance, VOICE_KEY } from "/js/dashboard.js";
import { SPEED_LIMITS, COUNTRY_NAMES, isHeavy, motorwayPayment } from "/js/speed_limits.js";
import { currentVehicle, onVehicle } from "/js/panels.js";
import { formatSunInfo } from "/js/sun.js";
import { pointsMenu, layersMenu, terrainMenu, levelMenu, recordingMenu, todayMenu, switchesMenu, elevationHtml, cellButton, bindKey, emptyRow as empty, escapeHtml } from "/js/drive_menus.js";
// Driving mode: the grid of docs/design.adoc ("Layout: a grid, not floating
// panels"; the Design canvas' Grid) — the page becomes cells, the map one
// of them, nothing over it; values in cells around it, keys in the bottom
// row, a menu opens in place of the right column and the map narrows.
// Which cell shows what is the screen profile's (public/drive/road.json:
// {area, widget, ...} per cell), to be edited in the app later. Per device
// (localStorage).
const KEY = "drivingMode";
const PROFILE_URL = "/drive/road.json";
const PITCH_3D = 60; // as map.js's 3D toggle
const RENDER_MS = 1000;
const BORDER_MS = 20000; // the border card's time on the screen // the clock, the follow state; the dashboard's polls render too
const SEARCH_DELAY_MS = 300; // after the last key
const LOG_POLL_MS = 5000; // the trip log's state and new points
const DRIVEN_SOURCE = "trip-driven";
const OVER_KMH = 3; // as dashboard.js: over the limit by more than this
// key action → [icon, label, title]
const KEYS = {
trip: ["⚑", "Trip", "The trip's stops: add, move, remove"],
points: ["◉", "Points", "Saved points and tracks near the car"],
layers: ["◫", "Layers", "Layers on the map, presets"],
search: ["⌕", "Search", "Search saved points and places"],
menu: ["☰", "Menu", "Menu: the whole route, leave driving"],
zoomOut: ["−", "", "Zoom out"],
zoomIn: ["+", "", "Zoom in"],
pitch: ["3D", "", "2D or 3D"],
follow: ["⌖", "", "Follow the position, heading up in 3D"],
terrain: ["⛰", "", "Terrain view: roll, pitch, the slope ahead"],
palette: ["", "", "Day, dusk, night"],
};
const NOT_YET = new Set();
// A knob's function → the screen keys it stands for (their labels: ⟳ ⟲)
const KNOB_KEYS = { zoom: ["zoomIn", "zoomOut"] };
const KEYPAD_ABSENT_MS = 5000; // no keypad on the bus: asked again after this
// The Terrain view switches itself on off-road (docs/design.adoc, Screen
// profiles): an unpaved surface (/api/road, off a route) or roll / pitch past
// TILT_DEG for TILT_S; back to the road view after PAVED_BACK_M on paved road.
// Closed by hand while still off-road: not again until back on the road.
const UNPAVED = new Set(["compacted", "dirt", "gravel", "path", "impassable"]);
const TILT_DEG = 10;
const TILT_S = 10;
const PAVED_BACK_M = 2000;
const TERRAIN_AUTO_KEY = "maptool.terrainAuto";
const FIELDS = { speed: "Speed", limit: "Limit", altitude: "Altitude", time: "Time", sun: "Sun", nextStop: "Next stop",
toNextStop: "To next stop", etaNextStop: "ETA next stop", toEnd: "To the end" };
const CARDINALS = ["N", "NE", "E", "SE", "S", "SW", "W", "NW"];
const clock = (date) => date.toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" });
export function setupDriving(map, nightButton, routePanel, gpxPanel) {
const app = document.getElementById("app");
let route = onRouteChanged((r) => { route = r; render(); });
let dash = null; // the dashboard's last state
let profile = null;
const cells = []; // [{ cell, el }]
let openPanel = null;
const toggle = document.createElement("button");
toggle.type = "button";
toggle.className = "topbar__drive";
toggle.title = "Driving mode: the cockpit grid, no planning panels";
toggle.textContent = "Drive";
nightButton.before(toggle);
const overview = () => {
const coords = route?.geometry?.coordinates;
if (!coords?.length) return;
pauseFollow(map);
map.fitBounds(coords.reduce((b, c) => b.extend(c), new LngLatBounds(coords[0], coords[0])), { padding: 80, pitch: 0, bearing: 0 });
};
// The Trip menu (the navigator's, docs/design.adoc; the canvas' GridTrip
// and GridSearch): the menu area as cells too — the stops a row each (name
// over 3 cells, ✓ ↑ ↓ ✕ a cell each), recording on top, the actions at the
// foot. Typing a search turns it into results (+ adds one as a stop), with
// their pins on the map. One level, no dragging.
const tripPanel = document.createElement("section");
tripPanel.className = "drive-panel drive-trip";
tripPanel.setAttribute("aria-label", "Trip");
tripPanel.hidden = true;
tripPanel.dataset.mode = "trip";
tripPanel.innerHTML = `<div class="drive-panel__head">Trip <small class="drive-trip__total"></small></div>
<button type="button" class="drive-panel__close" aria-label="Close">✕</button>
<button type="button" class="drive-trip__log" data-action="log"></button>
<button type="button" class="drive-trip__log-state" data-action="recording" title="The recording: its days, export"><span class="drive-cell__label">Recording ▸</span><span class="drive-trip__log-text"></span></button>
<div class="drive-trip__search"><input type="search" aria-label="Search" placeholder="Search saved points and places…" enterkeyhint="search"></div>
<div class="drive-trip__stops"></div>
<div class="drive-trip__results"></div>
<button type="button" class="drive-panel__primary drive-trip__add" data-action="add">+ Stop at the crosshair</button>
<button type="button" class="drive-trip__start" data-action="start">Start from the car</button>
<button type="button" class="drive-trip__back" data-action="back">← Back to the stops</button>`;
// The Menu: what has no key of its own (yet).
const menuPanel = document.createElement("section");
menuPanel.className = "drive-panel drive-menu";
menuPanel.setAttribute("aria-label", "Menu");
menuPanel.hidden = true;
menuPanel.innerHTML = `<div class="drive-panel__head">Menu</div>
<button type="button" class="drive-panel__close" aria-label="Close">✕</button>
<button type="button" class="drive-menu__row" data-action="today">Today ▸ <small>the stops left, tonight, the weather, the day's notes</small></button>
<button type="button" class="drive-menu__row" data-action="switches" hidden>Switches ▸ <small>the relays and lights, what drives them</small></button>
<button type="button" class="drive-menu__row" data-action="overview">The whole route <small>the follow pauses</small></button>
<button type="button" class="drive-menu__row" data-action="terrain-auto"></button>
<button type="button" class="drive-menu__row" data-action="voice"></button>
<button type="button" class="drive-menu__row" data-action="profile"></button>
<button type="button" class="drive-menu__row" data-action="leave">Leave driving mode</button>`;
// auto: opens off-road and closes back on the road; stay: opens and stays (the inclinometer all along); hand: neither
const TERRAIN_MODES = { auto: "opens and closes by itself", stay: "opens by itself, stays", hand: "by hand" };
const terrainMode = () => { try { const m = localStorage.getItem(TERRAIN_AUTO_KEY); return m in TERRAIN_MODES ? m : "auto"; } catch { return "auto"; } };
const terrainAuto = () => terrainMode() !== "hand";
const autoButton = menuPanel.querySelector('[data-action="terrain-auto"]');
const renderAuto = () => { autoButton.innerHTML = `Terrain view: ${TERRAIN_MODES[terrainMode()]} <small>tap to switch</small>`; };
autoButton.addEventListener("click", () => {
const modes = Object.keys(TERRAIN_MODES);
try { localStorage.setItem(TERRAIN_AUTO_KEY, modes[(modes.indexOf(terrainMode()) + 1) % modes.length]); } catch { /* private window: not kept */ }
renderAuto();
});
renderAuto();
const voiceButton = menuPanel.querySelector('[data-action="voice"]');
const voiceOn = () => { try { return localStorage.getItem(VOICE_KEY) === "on"; } catch { return false; } };
const renderVoice = () => { voiceButton.innerHTML = `Voice prompts: ${voiceOn() ? "on" : "off"} <small>tap to switch</small>`; };
voiceButton.addEventListener("click", () => {
try { localStorage.setItem(VOICE_KEY, voiceOn() ? "off" : "on"); } catch { /* private window: not kept */ }
if (voiceOn()) window.speechSynthesis?.speak(new SpeechSynthesisUtterance("Voice prompts on"));
renderVoice();
});
renderVoice();
// the profile: a tap goes to the next one (re-routes); the dialog is the desktop's
const profileButton = menuPanel.querySelector('[data-action="profile"]');
const renderProfile = () => {
const { current } = routePanel?.profiles() || {};
profileButton.innerHTML = `Profile: ${escapeHtml(current?.name ?? "—")} <small>tap for the next one</small>`;
};
profileButton.addEventListener("click", () => {
const { list, current } = routePanel?.profiles() || { list: [] };
if (!list.length) return;
routePanel.pickProfile(list[(list.indexOf(current) + 1) % list.length].id);
});
onVehicle(renderProfile);
renderProfile();
menuPanel.querySelector('[data-action="overview"]').addEventListener("click", overview);
menuPanel.querySelector('[data-action="today"]').addEventListener("click", () => open(today.el));
menuPanel.querySelector('[data-action="switches"]').addEventListener("click", () => open(switches.el));
menuPanel.querySelector('[data-action="leave"]').addEventListener("click", () => set(false));
const crosshair = document.createElement("div");
crosshair.className = "drive-crosshair";
crosshair.hidden = true;
// Search: saved points (the library) and places (the offline POI
// database), nearest the crosshair first.
const input = tripPanel.querySelector(".drive-trip__search input");
let results = null;
let pins = [];
let searchTimer = null;
let searchSeq = 0;
let searching = false;
const setResults = (list) => {
results = list;
tripPanel.dataset.mode = results ? "search" : "trip";
for (const pin of pins) pin.remove();
pins = (results || []).map((r) => {
const el = document.createElement("div");
el.className = `drive-pin drive-pin--${r.kind}`;
return new Marker({ element: el }).setLngLat(r.lngLat).addTo(map);
});
renderTrip();
render();
};
const backToStops = () => {
input.value = "";
clearTimeout(searchTimer);
searchSeq++;
searching = false;
setResults(null);
};
input.addEventListener("input", () => {
clearTimeout(searchTimer);
if (!input.value.trim()) return setResults(null);
searching = true;
if (!results) setResults([]); // the search layout at once, the input stays focused
searchTimer = setTimeout(async () => {
const mine = ++searchSeq;
const { lng, lat } = map.getCenter();
const url = new URL("/api/search", window.location.origin);
url.search = new URLSearchParams({ q: input.value, sources: "layers,places", lat, lng });
let found = [];
try { found = (await (await fetch(url)).json()).results; } catch { /* offline for a moment: nothing */ }
if (mine !== searchSeq) return;
searching = false;
setResults(found.filter(({ bbox }) => bbox).map(({ name, bbox, source, source_label: where }) => {
const lngLat = [(bbox[0] + bbox[2]) / 2, (bbox[1] + bbox[3]) / 2];
return { name, where, lngLat, kind: source === "places" ? "place" : "saved", away: distance(map.getCenter().distanceTo({ lng: lngLat[0], lat: lngLat[1] })) };
}));
}, SEARCH_DELAY_MS);
});
tripPanel.querySelector('[data-action="back"]').addEventListener("click", backToStops);
const lookAt = (lngLat) => {
pauseFollow(map);
map.easeTo({ center: lngLat, zoom: Math.max(map.getZoom(), 14) });
};
const renderResults = (list) => {
list.replaceChildren(...results.flatMap((r) => [
cellButton("result", `<span class="drive-pin drive-pin--${r.kind}"></span><span class="drive-panel__text"><b>${escapeHtml(r.name)}</b><small>${escapeHtml(r.where || "")} · ${r.away}</small></span>`,
"Show it on the map", () => lookAt(r.lngLat)),
cellButton("add", "+", "Add as a stop", () => {
backToStops(); // back to the stops, the new one among them
routePanel.addStop(r.lngLat, r.name);
}),
]));
if (!results.length) list.append(empty(searching ? "Searching…" : input.value.trim() ? "Nothing found." : "Type a name — saved points and places, nearest first."));
};
const renderTrip = () => {
if (tripPanel.hidden || !routePanel) return;
if (results) return renderResults(tripPanel.querySelector(".drive-trip__results"));
const stops = routePanel.stops();
const list = tripPanel.querySelector(".drive-trip__stops");
list.replaceChildren(...stops.flatMap((stop, i) => {
const leg = stop.leg ? `+${stop.leg.km.toFixed(1)} km${stop.leg.s != null ? ` · ${formatDuration(stop.leg.s)}` : ""}` : "";
const name = cellButton("stop", `<span class="drive-panel__text"><small class="drive-cell__label">${escapeHtml(stop.label)}${leg ? ` · ${leg}` : ""}</small>` +
`<b>${escapeHtml(stop.name || `${stop.lngLat[1].toFixed(4)}, ${stop.lngLat[0].toFixed(4)}`)}</b></span>`, "Show it on the map", () => lookAt(stop.lngLat));
name.classList.toggle("drive-panel__passed", !!stop.passed || stop.behind);
const done = cellButton("done", "✓", stop.passed ? "Passed — tap to route through it again" : "Mark as passed (not routed any more)", () => routePanel.togglePassed(i));
done.classList.toggle("active", !!stop.passed);
const up = cellButton("up", "↑", "Earlier", () => routePanel.moveStop(i, -1));
const down = cellButton("down", "↓", "Later", () => routePanel.moveStop(i, 1));
const drop = cellButton("drop", "✕", "Remove this stop", () => routePanel.removeStop(i));
up.disabled = i === 0;
down.disabled = i === stops.length - 1;
return [name, done, up, down, drop];
}));
if (!stops.length) list.append(empty("No stops yet — pan the map to a place and add it, or search."));
const p = route?.properties;
tripPanel.querySelector(".drive-trip__total").textContent = p && stops.length > 1 ? `${p.distance_km.toFixed(1)} km · ${formatDuration(p.time_s)}` : "";
};
// One panel at a time, in the profile's menu area; the map narrows to its
// other area (its center — the follow, the crosshair — stays in view).
// Points and Layers (drive_menus.js): the car's position, else the map's center.
const menuCtx = {
map, gpxPanel, routePanel, lookAt,
position: () => (dash?.values?.lon != null && dash?.values?.lat != null ? [dash.values.lon, dash.values.lat] : map.getCenter().toArray()),
route: () => route,
atKm: () => dash?.atKm,
close: () => open(null),
};
const points = pointsMenu(menuCtx);
const layers = layersMenu(menuCtx);
const terrain = terrainMenu({ ...menuCtx, state: () => dash, openLevel: () => open(level.el) });
const level = levelMenu({ ...menuCtx, state: () => dash, openTerrain: () => open(terrain.el) });
const recording = recordingMenu({
...menuCtx,
showBounds: ([w, s, e, n]) => { pauseFollow(map); map.fitBounds([[w, s], [e, n]], { padding: 60, pitch: 0, maxZoom: 15 }); },
endTrip: () => endTrip(),
});
const today = todayMenu(menuCtx);
const switches = switchesMenu(menuCtx);
switches.available().then((yes) => { menuPanel.querySelector('[data-action="switches"]').hidden = !yes; });
const menus = [points, layers, terrain, level, recording, today, switches];
let offRoad = false;
let tiltSince = null;
let pavedM = 0;
let autoOpened = false;
let suppressed = false;
let lastState = Date.now();
const autoTerrain = (state) => {
const v = state.values || {};
const now = Date.now();
const dt = (now - lastState) / 1000;
lastState = now;
// simulated, the tilt is the DEM's slope round the car — on a road cut into a hillside that's the
// hill's, not the car's, so it doesn't count (the surface still does); the dials still show it
const tilted = !state.simulated && Math.max(Math.abs(v.roll ?? 0), Math.abs(v.pitch ?? 0)) >= TILT_DEG;
tiltSince = tilted ? tiltSince ?? now : null;
offRoad = UNPAVED.has(state.surface) || (tiltSince != null && now - tiltSince >= TILT_S * 1000);
if (offRoad) pavedM = 0;
else {
suppressed = false;
pavedM += (v.speed ?? 0) * dt;
}
if (!terrainAuto()) return;
if (offRoad && !suppressed && !openPanel) {
open(terrain.el);
autoOpened = true;
} else if (terrainMode() === "auto" && autoOpened && openPanel === terrain.el && pavedM >= PAVED_BACK_M) open(null);
};
function open(panel) {
if (openPanel === terrain.el && panel !== terrain.el) {
if (offRoad) suppressed = true; // closed by hand off-road: stays closed until the road
autoOpened = false;
}
if (panel !== tripPanel && results) backToStops(); // the pins go with the search
menus.find((m) => m.el === openPanel && m.el !== panel)?.closed?.();
openPanel = panel;
row = 0;
tripPanel.hidden = panel !== tripPanel;
menuPanel.hidden = panel !== menuPanel;
for (const menu of menus) {
menu.el.hidden = panel !== menu.el;
if (panel === menu.el) menu.opened();
}
crosshair.hidden = panel !== tripPanel;
if (profile) app.style.setProperty("--drive-map", panel ? profile.menu.map : profile.map);
map.resize();
renderTrip();
render();
}
const togglePanel = (panel) => open(openPanel === panel ? null : panel);
for (const panel of [tripPanel, menuPanel]) panel.querySelector(".drive-panel__close").addEventListener("click", () => open(null));
tripPanel.querySelector('[data-action="add"]').addEventListener("click", () => {
const { lng, lat } = map.getCenter();
routePanel?.addStop([lng, lat]);
});
tripPanel.querySelector('[data-action="start"]').addEventListener("click", () => routePanel?.startHere());
routePanel?.onStopsChanged(() => { renderTrip(); render(); });
// The trip log (lib/maptool/trip_log.rb): Start makes the trip's library
// folder and records the car's GNSS into it, End closes it; the line
// really driven drawn in --route-driven, grown by polling ?since=N.
const logButton = tripPanel.querySelector('[data-action="log"]');
const logState = tripPanel.querySelector(".drive-trip__log-text");
let log = null;
let driven = [];
const drawDriven = () => {
const data = { type: "Feature", geometry: { type: "LineString", coordinates: driven }, properties: {} };
const source = map.getSource(DRIVEN_SOURCE);
if (source) return source.setData(data);
if (!map.isStyleLoaded()) return;
map.addSource(DRIVEN_SOURCE, { type: "geojson", data });
map.addLayer({ id: DRIVEN_SOURCE, type: "line", source: DRIVEN_SOURCE, layout: { "line-cap": "round", "line-join": "round" },
paint: { "line-color": getComputedStyle(document.documentElement).getPropertyValue("--route-driven").trim() || "#c2410c", "line-width": 4 } });
};
map.on("style.load", () => driven.length && drawDriven());
const refreshLog = async () => {
try {
const response = await fetch(`/api/trip/log?since=${driven.length}`, { cache: "no-store" });
if (response.ok) {
log = await response.json();
if (!log.active) driven = [];
else driven = driven.concat(log.coordinates || []);
drawDriven();
}
} catch { /* offline for a moment: the next poll */ }
renderLog();
};
const pollLog = async () => {
await refreshLog();
setTimeout(pollLog, LOG_POLL_MS);
};
const renderLog = () => {
logButton.textContent = log?.active ? "End the trip" : "Start the trip";
logButton.classList.toggle("drive-trip__log--on", !!log?.active);
logState.textContent = log?.active ? `● ${log.folder.replace(/^Trips\//, "")} · ${(log.distance_m / 1000).toFixed(1)} km` : "Not recording";
logState.classList.toggle("drive-trip__log-text--on", !!log?.active);
document.documentElement.classList.toggle("trip-rec", !!log?.active);
};
const endTrip = async () => {
if (!log?.active || !window.confirm(`End the trip "${log.folder}"? Its track stays in the library.`)) return;
await fetch("/api/trip/log", { method: "DELETE" });
driven = [];
refreshLog();
};
tripPanel.querySelector('[data-action="recording"]').addEventListener("click", () => open(recording.el));
logButton.addEventListener("click", async () => {
if (log?.active) return endTrip();
const ends = routePanel?.stops().at(-1)?.name || "";
const name = window.prompt("The trip's name:", ends);
if (name === null) return;
const response = await fetch("/api/trip/log", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ name }) });
if (!response.ok) window.alert((await response.json().catch(() => ({}))).error || `HTTP ${response.status}`);
driven = [];
refreshLog();
});
if (isLoggedIn()) pollLog();
else {
logButton.disabled = true;
logButton.textContent = "Start the trip";
logState.textContent = "Log in to record";
}
map.getContainer().append(crosshair);
app.append(tripPanel, menuPanel, points.el, layers.el, terrain.el, level.el, recording.el, today.el, switches.el);
// --- the grid's cells ---------------------------------------------------
const keyAction = {
trip: () => {
if (openPanel === tripPanel && results) return backToStops();
togglePanel(tripPanel);
},
search: () => {
if (openPanel === tripPanel && results) return open(null);
open(tripPanel);
if (!results) setResults([]);
input.focus();
},
menu: () => togglePanel(menuPanel),
points: () => togglePanel(points.el),
layers: () => togglePanel(layers.el),
terrain: () => togglePanel(terrain.el),
zoomOut: () => map.zoomOut(),
zoomIn: () => map.zoomIn(),
pitch: () => map.easeTo({ pitch: map.getPitch() > 0 ? 0 : PITCH_3D, ...(map.getPitch() > 0 && { bearing: 0 }), duration: 300 }),
follow: () => {
requestGnssFollow();
resumeFollow(map);
if (map.getPitch() === 0) map.easeTo({ pitch: PITCH_3D, duration: 300 });
render();
},
palette: () => nightButton.click(),
};
const make = (cell) => {
let el;
if (cell.widget === "key") {
const [icon, label, title] = KEYS[cell.action] || ["?", cell.action, cell.action];
el = document.createElement("button");
el.type = "button";
el.title = title;
el.setAttribute("aria-label", label || title);
el.innerHTML = `<span class="drive-key__icon">${icon}</span>${label ? `<span class="drive-key__label">${label}</span>` : ""}`;
el.disabled = NOT_YET.has(cell.action) || !keyAction[cell.action];
el.addEventListener("click", () => keyAction[cell.action]?.());
if (cell.action === "zoomIn" || cell.action === "zoomOut") el.classList.add("drive-key--big");
if (cell.key) bindKey(el, cell.key);
} else {
el = document.createElement("div");
}
el.classList.add("drive-cell", `drive-cell--${cell.widget}`);
if (cell.small) el.classList.add("drive-cell--small");
el.style.gridArea = cell.area;
return el;
};
// To the next stop and to the end, from the km along the route (the start
// of it while not on it): the leg's time in proportion to what's left of it.
// ponytail: a straight share of the leg's time, Valhalla's per-maneuver times if it's off
const ahead = () => {
const p = route?.properties;
const stops = routePanel?.stops().filter((s) => !s.passed) || [];
if (!p?.legs_km?.length || stops.length !== p.legs_km.length + 1) return null;
const at = dash?.atKm ?? 0;
let end = 0;
let i = 0;
for (; i < p.legs_km.length; i++) {
end += p.legs_km[i];
if (end > at + 0.05) break;
}
i = Math.min(i, p.legs_km.length - 1);
const toNext = Math.max(0, end - at);
const sNext = p.legs_s?.[i] != null && p.legs_km[i] ? (p.legs_s[i] * toNext) / p.legs_km[i] : null;
const toEnd = Math.max(0, p.distance_km - at);
const sEnd = sNext != null ? sNext + p.legs_s.slice(i + 1).reduce((a, b) => a + b, 0) : (p.time_s * toEnd) / p.distance_km;
const stop = stops[i + 1];
return { name: stop.name || stop.label, toNext, sNext, toEnd, sEnd };
};
// [value, unit, class]
const fieldValue = (name, a) => {
const v = dash?.values || {};
const nav = dash?.nav;
const kmh = v.speed == null ? null : v.speed * 3.6;
const limit = nav?.limit;
const now = new Date();
switch (name) {
case "speed": {
// the limit as a sign at the field's end, the next one under it; the speed red past the limit
const next = nav?.next ? `${typeof nav.next.limit === "number" ? nav.next.limit : "∞"} in ${distance(nav.next.m)}` : "";
const sign = typeof limit === "number" || limit === "unlimited"
? `<span class="drive-speed__limit" aria-label="Limit ${limit}"><b>${limit === "unlimited" ? "∞" : limit}</b>${next ? `<small>${escapeHtml(next)}</small>` : ""}</span>` : "";
return [kmh == null ? "—" : Math.round(kmh), "km/h", typeof limit === "number" && kmh > limit + OVER_KMH ? "drive-cell--warn" : "", sign];
}
case "limit": {
const next = nav?.next ? `· ${typeof nav.next.limit === "number" ? nav.next.limit : "∞"} in ${distance(nav.next.m)}` : "";
return [typeof limit === "number" ? limit : limit === "unlimited" ? "∞" : "—", next, "drive-cell--limit"];
}
case "altitude":
return [v.alt == null ? "—" : Math.round(v.alt), "m"];
case "time":
return [clock(now), ""];
case "sun": {
const { lng, lat } = map.getCenter();
const info = formatSunInfo(lat, lng, now);
if (!info) return ["—", ""];
if (info.polar) return [info.polar, ""];
return info.countdown?.endsWith("sunrise") ? [info.sunrise, "rise"] : [info.sunset, "set"];
}
case "nextStop":
return [a?.name ?? "—", ""];
case "toNextStop":
return a ? [a.toNext.toFixed(1), `km${a.sNext != null ? ` · ${formatDuration(a.sNext)}` : ""}`] : ["—", ""];
case "etaNextStop":
return [a?.sNext != null ? clock(new Date(now.getTime() + a.sNext * 1000)) : "—", ""];
case "toEnd":
return a ? [a.toEnd.toFixed(1), `km · ${clock(new Date(now.getTime() + a.sEnd * 1000))}`] : ["—", ""];
default:
return ["?", ""];
}
};
// Under the maneuver, over the map, only when there's something: the next
// maneuver's lanes (from 1 km, further at speed) and the next traffic signal.
const renderAhead = (el) => {
const n = dash?.nav;
const lanes = !n?.arrived && n?.maneuver?.lanes && n.maneuver.m <= n.lanesM ? n.maneuver.lanes : null;
const signal = n?.signal != null && n.signal <= 1000 ? n.signal : null;
el.hidden = !lanes && signal == null;
if (el.hidden) return;
el.innerHTML = (lanes ? `<div class="dash-lanes drive-ahead__lanes">${lanes.map(laneSvg).join("")}</div>` : "") +
(signal != null ? `<span class="drive-ahead__signal"><span class="dash-signal"></span>${distance(signal)}</span>` : "");
};
// Past a border (the country along the route, or of the road driven):
// the new country's limits for the profile and how its motorways are
// paid, for BORDER_MS or until tapped (the Design canvas' GridBorder).
let country = null;
let border = null; // { code, until }
const renderBorder = (el) => {
const code = dash?.nav?.country;
if (code && code !== country) {
if (country) border = { code, until: Date.now() + BORDER_MS };
country = code;
}
el.hidden = !border || Date.now() > border.until;
if (el.hidden) return;
if (!el.dataset.wired) {
el.dataset.wired = "1";
el.addEventListener("click", () => { border = null; el.hidden = true; });
}
const heavy = isHeavy(currentVehicle);
const row = SPEED_LIMITS[border.code]?.[heavy ? "heavy" : "car"];
const pay = motorwayPayment(border.code, currentVehicle);
const sign = (v, k) => `<span class="drive-border__limit"><span class="drive-speed__limit"><b>${v ?? "–"}</b></span><small>${k}</small></span>`;
let name = border.code;
try { name = COUNTRY_NAMES.of(border.code); } catch { /* not a region code */ }
el.innerHTML = `<div class="drive-border__head"><b>${escapeHtml(name)}</b><span class="drive-cell__muted">${border.code}${currentVehicle ? ` · ${escapeHtml(currentVehicle.name)}` : ""}</span></div>` +
(row ? `<div class="drive-border__signs">${sign(row[0], "Motorway")}${sign(row[2], "Outside towns")}${sign(row[3], "In towns")}</div>` : `<span class="drive-cell__muted">No limits known for ${border.code}</span>`) +
(pay.how ? `<span class="drive-border__pays">Motorways: ${pay.how} ${pay.has ? "✓" : "— not in the profile"}</span>` : "");
};
const renderManeuver = (el) => {
const n = dash?.nav;
if (n?.offRoute) {
el.innerHTML = `<div><span class="drive-cell__value drive-cell--caution">Off the route</span><span class="drive-cell__label">rerouting</span></div>`;
} else if (n?.arrived) {
el.innerHTML = `${maneuverSvg(4)}<div class="drive-cell__text"><span class="drive-cell__value">Arrived</span><span class="drive-cell__street">${escapeHtml(n.street || "")}</span></div>`;
} else if (n?.maneuver) {
const { m, type, street, text, exit } = n.maneuver;
const what = street ? `${exit ? `${exit}. exit · ` : ""}${escapeHtml(street)}` : escapeHtml(text);
const then = n.then ? ` <span class="drive-cell__muted">· then ${escapeHtml(n.then.street || n.then.text)}</span>` : "";
el.innerHTML = `${maneuverSvg(type)}<div class="drive-cell__text"><span class="drive-cell__value">${distance(m)}</span><span class="drive-cell__street">${what}${then}</span></div>`;
} else {
el.innerHTML = `<div class="drive-cell__text"><span class="drive-cell__label">On</span><span class="drive-cell__street">${escapeHtml(n?.street ?? "—")}</span></div>`;
}
};
const renderElevation = (el, cell) => { el.innerHTML = elevationHtml(route, dash?.atKm, cell.km || 10); };
const renderCompass = (el) => {
const h = dash?.heading;
const deg = h ? Math.round(h.deg) % 360 : null;
el.innerHTML = `<svg class="drive-compass${h && !h.live ? " drive-compass--stale" : ""}" viewBox="-50 -50 100 100" role="img" aria-label="${deg == null ? "No heading" : `Heading ${deg}°`}">
<circle r="46" class="drive-compass__ring"/>
<g transform="rotate(${-(deg ?? 0)})">
<path d="M0 -40 L6 0 L0 -6 L-6 0 Z" class="drive-compass__north"/>
<path d="M0 40 L6 0 L0 6 L-6 0 Z" class="drive-compass__south"/>
<text y="-22" transform="rotate(${deg ?? 0} 0 -27)" class="drive-compass__n">N</text>
</g>
<path d="M0 -50 l-5 0 l5 10 l5 -10 z" class="drive-compass__lubber"/>
</svg>
<span class="drive-cell__text"><span class="drive-cell__label">Heading</span><span class="drive-cell__value drive-cell__value--mid">${deg == null ? "—" : String(deg).padStart(3, "0") + "°"} <small>${deg == null ? "" : CARDINALS[Math.round(deg / 45) % 8]}</small></span></span>`;
};
const renderKey = (el, cell) => {
const pressed = { trip: openPanel === tripPanel && !results, search: openPanel === tripPanel && !!results, points: openPanel === points.el, layers: openPanel === layers.el, terrain: openPanel === terrain.el, menu: openPanel === menuPanel, pitch: map.getPitch() > 0, follow: isFollowing(map) }[cell.action];
el.setAttribute("aria-pressed", String(!!pressed));
if (cell.action === "palette") el.querySelector(".drive-key__icon").textContent = nightButton.textContent;
};
function render() {
if (!document.documentElement.classList.contains("driving")) return;
if (openPanel === terrain.el) terrain.render();
if (openPanel === level.el) level.render();
const a = ahead();
for (const { cell, el } of cells) {
if (cell.widget === "field") {
const name = cell.value;
const [value, unit, cls = "", extra = ""] = fieldValue(name, a);
el.innerHTML = `${extra}<span class="drive-cell__label">${FIELDS[name] || name}</span><span class="drive-cell__value ${cls}">${escapeHtml(value)} <small>${escapeHtml(unit)}</small></span>`;
} else if (cell.widget === "maneuver") renderManeuver(el);
else if (cell.widget === "ahead") renderAhead(el);
else if (cell.widget === "border") renderBorder(el);
else if (cell.widget === "status") {
el.innerHTML = `<b class="drive-status__brand">MAPTOOL</b><span class="drive-cell__muted"><span class="${navigator.onLine ? "drive-status--ok" : ""}">●</span> ${navigator.onLine ? "online" : "offline"}${log?.active ? ` · <span class="drive-status--rec">● rec</span>` : ""}</span>`;
} else if (cell.widget === "elevation") renderElevation(el, cell);
else if (cell.widget === "compass") renderCompass(el);
else if (cell.widget === "key") renderKey(el, cell);
}
sendLeds();
}
map.on("pitchend", render);
setInterval(render, RENDER_MS);
// the keypads' bindings: this car's own (saved in /keypad.html) over the profile's
const savedBindings = fetch("/api/keypad/bindings", { cache: "no-store" }).then((r) => (r.ok ? r.json() : null)).catch(() => null);
fetch(PROFILE_URL, { cache: "no-cache" }).then((r) => r.json()).then(async (p) => {
p.bindings = (await savedBindings)?.bindings || p.bindings;
profile = p;
// Cells of p.cell px at most; on a bigger screen only the map's columns
// and rows (beside an open menu) stretch, the rest stays cell-sized.
const [mr1, mc1, mr2, mc2] = p.menu.map.split("/").map(Number);
const track = (n, from, to) => Array.from({ length: n }, (_, i) => (i + 1 >= from && i + 1 < to ? "minmax(0, 1fr)" : "var(--cell)")).join(" ");
// One scale for everything (--s): the cells, the type, the icons — the
// same elements on a 7″ as on the 16″, only smaller; never bigger than drawn.
const fit = () => {
const scale = Math.min(1, window.innerWidth / (p.columns * (p.cell || 80)), window.innerHeight / (p.rows * (p.cell || 80)));
app.style.setProperty("--s", scale.toFixed(3));
app.style.setProperty("--cell", `${((p.cell || 80) * scale).toFixed(1)}px`);
};
fit();
window.addEventListener("resize", fit);
app.style.setProperty("--drive-columns", track(p.columns, mc1, mc2));
app.style.setProperty("--drive-row-sizes", track(p.rows, mr1, mr2));
app.style.setProperty("--drive-map", openPanel ? p.menu.map : p.map);
app.style.setProperty("--drive-menu", p.menu.area);
const [r1, c1, r2, c2] = p.menu.area.split("/").map(Number);
app.style.setProperty("--drive-menu-cols", c2 - c1);
app.style.setProperty("--drive-menu-mid", r2 - r1 - 4); // the list rows between the 3 on top and the foot
for (const cell of p.cells) {
const el = make(cell);
app.append(el);
cells.push({ cell, el });
}
labelKeys(); // a keypad heard before the profile came
render();
map.resize();
});
function set(on) {
if (!on) open(null);
document.documentElement.classList.toggle("driving", on);
toggle.classList.toggle("active", on);
try { localStorage.setItem(KEY, on ? "on" : "off"); } catch { /* private window: not kept */ }
watchDashboard(on ? (state) => {
dash = state;
autoTerrain(state);
render();
} : null);
render();
map.resize(); // the grid came or went
}
toggle.addEventListener("click", () => set(!document.documentElement.classList.contains("driving")));
// Keys (canvas GridKeys): a screen key's "key" in the profile clicks it, a
// menu's [data-key] buttons too (1 2 3, H); in an open menu ↑ ↓ move the row
// (the keypad's encoder will send the same arrows), Enter its first button,
// Space its eye, + adds it, ⌫ up a folder, Esc closes. The labels in the
// corners show from the first key pressed on, so a touch-only screen stays clean.
// (The keypads' channels: the profile's bindings, further down.)
const KEYS_SEEN = "maptool.driveKeys";
let row = 0;
try { if (localStorage.getItem(KEYS_SEEN)) document.documentElement.classList.add("drive-keys"); } catch { /* nothing kept */ }
const norm = (k) => (k.length === 1 ? k.toLowerCase() : k);
const visible = (b) => b.offsetParent && !b.disabled;
const rowsOf = (panel) => {
const rows = new Map();
for (const b of panel.querySelectorAll("button:not(.drive-panel__close)")) {
if (!visible(b)) continue;
const top = Math.round(b.getBoundingClientRect().top);
rows.set(top, [...(rows.get(top) || []), b]);
}
return [...rows].sort((a, b) => a[0] - b[0]).map(([, r]) => r);
};
const markRow = (scroll) => {
for (const b of document.querySelectorAll(".drive-focus")) b.classList.remove("drive-focus", "drive-focus--main");
if (!openPanel || !document.documentElement.classList.contains("drive-keys")) return [];
const rows = rowsOf(openPanel);
row = Math.max(0, Math.min(row, rows.length - 1));
const current = rows[row] || [];
for (const b of current) b.classList.add("drive-focus");
current[0]?.classList.add("drive-focus--main");
if (scroll) current[0]?.scrollIntoView({ block: "nearest" });
return current;
};
let marking = 0; // the menus re-render their rows: the highlight follows, once a frame
new MutationObserver(() => { marking ||= requestAnimationFrame(() => { marking = 0; markRow(false); }); }).observe(app, { childList: true, subtree: true });
document.addEventListener("keydown", (e) => {
if (!document.documentElement.classList.contains("driving") || e.ctrlKey || e.altKey || e.metaKey) return;
const key = norm(e.key);
const move = key === "ArrowUp" ? -1 : key === "ArrowDown" ? 1 : 0;
if (e.target.matches?.("input, textarea, select")) {
if (key === "Escape" || move) e.target.blur(); else return; // typing a search
}
if (!document.documentElement.classList.contains("drive-keys")) {
document.documentElement.classList.add("drive-keys");
try { localStorage.setItem(KEYS_SEEN, "1"); } catch { /* private window: not kept */ }
}
const current = markRow(false);
const press = (b) => (b && visible(b) ? (b.click(), true) : false);
const bound = (scope) => [...(scope?.querySelectorAll("[data-key]") || [])].find((b) => norm(b.dataset.key) === key && visible(b));
let done = false;
if (key === "Escape") done = !!openPanel && (open(null), true);
else if (openPanel && move) { row += move; markRow(true); done = true; }
else if (openPanel && key === "Enter") done = press(current[0]);
else if (openPanel && key === " ") done = press(current.find((b) => b.classList.contains("drive-panel__eye")));
else if (openPanel && key === "Backspace") done = press(openPanel.querySelector(".drive-panel__up"));
if (!done && openPanel && key === "+") done = press(current.find((b) => b.classList.contains("drive-panel__add")));
if (!done) done = press(bound(openPanel) || bound(app));
if (done) e.preventDefault(); // F1, F5, / are the browser's otherwise
});
// Keypads (can.json's "keypads", GET /api/keypad, a long poll) and the
// profile's "bindings" (docs/design.adoc, Switches and the keypad): a
// channel ("pad.K1", "pad.E3" — a key, a knob, its "press") → an action,
// another one while a menu is open ("menu"). A screen key's action clicks
// it; knobs turn: zoom, panX / panY, rows (the menu's ↑ ↓); enter, close.
// A keypad's heartbeat on the bus labels the screen keys with its
// channels (none = touch only) and the line under them in the binding's
// LED colour; its key LEDs follow them, "led_on" (green) while on.
// ponytail: screen functions only — outputs (relays), the modes (hold,
// pulse, positions…) and the mapping UI (the canvas' GridBinding) to come.
const bindings = () => profile?.bindings || [];
let present = [];
let ledsSent = {};
const keyEl = (action) => cells.find((c) => c.cell.widget === "key" && c.cell.action === action)?.el;
const shortName = (input) => input.slice(input.indexOf(".") + 1).replace(/ press$/, " ⏎");
function labelKeys() {
for (const { cell, el } of cells) {
if (cell.widget !== "key") continue;
delete el.dataset.keypad;
delete el.dataset.led;
}
for (const b of bindings()) {
if (!present.some((d) => b.input.startsWith(`${d.name}.`)) || !b.action) continue;
const knob = KNOB_KEYS[b.action];
for (const [i, action] of (knob || [b.action]).entries()) {
const el = keyEl(action);
if (!el) continue;
el.dataset.keypad = shortName(b.input) + (knob ? (i ? " ⟲" : " ⟳") : "");
if (b.led) el.dataset.led = b.led;
}
}
}
function sendLeds() {
for (const d of present.filter((p) => p.leds)) {
const on = {};
for (const b of bindings()) {
const k = b.input.startsWith(`${d.name}.`) && /^K\d+$/.exec(b.input.slice(d.name.length + 1))?.[0];
const el = k && b.led && keyEl(b.action);
if (el) on[k] = el.disabled ? null : el.getAttribute("aria-pressed") === "true" ? b.led_on || "green" : b.led;
}
const body = JSON.stringify({ keypad: d.name, on });
if (body === ledsSent[d.name]) continue;
ledsSent[d.name] = body;
fetch("/api/keypad/leds", { method: "PUT", headers: { "Content-Type": "application/json" }, body }).catch(() => { ledsSent[d.name] = ""; });
}
}
const navKey = (key) => document.dispatchEvent(new KeyboardEvent("keydown", { key }));
const PAN_PX = 80;
const knobAction = {
zoom: (dir) => keyEl(dir > 0 ? "zoomIn" : "zoomOut")?.click(),
panX: (dir) => map.panBy([dir * PAN_PX, 0], { duration: 100 }),
panY: (dir) => map.panBy([0, dir * PAN_PX], { duration: 100 }),
rows: (dir) => navKey(dir > 0 ? "ArrowDown" : "ArrowUp"),
enter: () => navKey("Enter"),
close: () => navKey("Escape"),
};
const onInput = (event) => {
if (!document.documentElement.classList.contains("driving")) return;
const [, channel, turn] = /^(.*?)(?: (⟳|⟲))?$/.exec(event);
const b = bindings().find((x) => x.input === channel);
const action = (openPanel && b?.menu) || b?.action;
if (!action) return;
if (knobAction[action]) return knobAction[action](turn === "⟲" ? -1 : 1);
const el = keyEl(action);
if (el && visible(el)) el.click();
};
(async function keypadLoop() {
let since = null;
for (;;) {
let answer = null;
try {
const response = await fetch(`/api/keypad${since == null ? "" : `?since=${since}`}`, { cache: "no-store" });
if (response.status === 404) return; // no keypads configured on this server
if (response.ok) answer = await response.json();
} catch { /* the server restarting, offline for a moment */ }
const now = answer?.present || [];
if (JSON.stringify(now) !== JSON.stringify(present)) {
present = now;
document.documentElement.classList.toggle("drive-keypad", present.length > 0);
if (present.length) document.documentElement.classList.add("drive-keys");
ledsSent = {};
labelKeys();
sendLeds();
}
if (!present.length) {
since = null;
await new Promise((r) => setTimeout(r, KEYPAD_ABSENT_MS));
continue;
}
if (since != null) for (const e of answer.events) onInput(e.input);
since = answer.seq;
}
})();
let saved = null;
try { saved = localStorage.getItem(KEY); } catch { /* nothing kept */ }
set(saved === "on");
}
+163 -11
View File
@@ -1,15 +1,135 @@
import { Marker } from "/vendor/maplibre-gl/maplibre-gl.mjs"; import { Marker } from "/vendor/maplibre-gl/maplibre-gl.mjs";
import { GNSS_ICON } from "/js/icons.js"; import { GNSS_ICON } from "/js/icons.js";
import { isLoggedIn } from "/js/auth.js"; import { isLoggedIn } from "/js/auth.js";
import { onGnssFollow } from "/js/panels.js";
const POSITION_URL = "/api/gnss/position"; const POSITION_URL = "/api/gnss/position";
const POLL_INTERVAL_MS = 1500; const POLL_INTERVAL_MS = 1500;
const JUMP_M = 1000; // farther than this from the marker: jump there, not glide (a new simulation)
// The position as an arrow, turned by the course once there is one.
const ARROW = `<svg viewBox="0 0 24 24" width="26" height="26"><path d="M12 2 L20 21 L12 16.5 L4 21 Z" fill="#2a9d8f" stroke="#fff" stroke-width="2" stroke-linejoin="round"/></svg>`;
// A sidebar icon that polls /api/gnss/position (backed server-side by a // A sidebar icon that polls /api/gnss/position (the car's receiver, fed
// gpsd connection, see lib/maptool/gpsd_client.rb) and shows the fix as a // server-side into GNSS_LATEST in app.rb) and shows the fix as a
// marker, with fix status in a flyout. Polling rather than a push channel // marker, with fix status in a flyout. Polling rather than a push channel
// is deliberate — see the comment in app.rb next to GNSS_LATEST — and fits // is deliberate — see the comment in app.rb next to GNSS_LATEST — and fits
// gpsd's own ~1Hz report rate fine. // a receiver's ~1Hz report rate fine.
// One follow step for a moving position (this receiver, the browser's own
// geolocation). In the 3D (pitched) view it turns heading-up like a car
// navigation, with the position in the lower part of the screen; the last
// heading stays while standing still (speed in m/s, heading in degrees).
// duration (ms): a linear glide over that long — the time until the next
// fix, so a 1 Hz receiver moves the camera smoothly, not in 10 m jumps.
// Moving the map by hand (drag, zoom, rotate, tilt) pauses the follow, as a
// car navigation does — to look around, change the route — the position
// keeps moving; "Back to the position" or FREE_LOOK_MS without touching the
// map resumes it.
const FREE_LOOK_MS = 15000;
const FOLLOWING_MS = 5000; // a follow step this recently: the map is following
const freeLook = new WeakMap(); // map -> { until, button }
function freeLookState(map) {
let state = freeLook.get(map);
if (state) return state;
const button = document.createElement("button");
button.type = "button";
button.className = "follow-resume";
button.textContent = "Back to the position";
button.hidden = true;
map.getContainer().appendChild(button);
state = { until: 0, button, followedAt: 0 };
button.addEventListener("click", () => resumeFollow(map));
const touched = (e) => {
// our own easeTo, or nothing being followed (GNSS off)
if (e.originalEvent && Date.now() - state.followedAt <= FOLLOWING_MS) pauseFollow(map);
};
for (const type of ["dragstart", "zoomstart", "rotatestart", "pitchstart", "move"]) map.on(type, touched);
freeLook.set(map, state);
return state;
}
// Also for a view the app moves to itself (the driving bar's route overview).
export function pauseFollow(map) {
const state = freeLookState(map);
state.until = Date.now() + FREE_LOOK_MS;
state.button.hidden = false;
clearTimeout(state.timer);
state.timer = setTimeout(() => (state.button.hidden = true), FREE_LOOK_MS);
}
// Is the map following a position right now (a follow step lately, not
// paused by hand)? For the driving bar's recenter button.
export function isFollowing(map) {
const state = freeLookState(map);
return Date.now() - state.followedAt <= FOLLOWING_MS && Date.now() >= state.until;
}
export function resumeFollow(map) {
const state = freeLookState(map);
state.until = 0;
state.button.hidden = true;
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 = 17;
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();
// following in 3D like a navigation: the overview map out of the way
// (style.css), back once the follow stops or the view goes 2D
document.documentElement.classList.toggle("follow-3d", map.getPitch() > 0);
clearTimeout(free.followTimer);
free.followTimer = setTimeout(() => document.documentElement.classList.remove("follow-3d"), FOLLOWING_MS);
if (Date.now() < free.until) return;
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
// (up to 20 km/h z18, 50 z17.3, 90 z16.3, 120+ z15.6). 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.max(15.5, 18 - Math.max(0, speed * 3.6 - 20) * 0.024);
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;
}
// The marker moved to lngLat the same way: a linear glide over duration ms.
function glideMarker(marker, lngLat, duration) {
cancelAnimationFrame(marker._glide);
const from = marker.getLngLat();
const start = performance.now();
const step = (now) => {
const t = Math.min(1, (now - start) / duration);
marker.setLngLat([from.lng + (lngLat[0] - from.lng) * t, from.lat + (lngLat[1] - from.lat) * t]);
if (t < 1) marker._glide = requestAnimationFrame(step);
};
marker._glide = requestAnimationFrame(step);
}
export class GnssControl { export class GnssControl {
constructor(map) { constructor(map) {
this._map = map; this._map = map;
@@ -41,6 +161,7 @@ export class GnssControl {
this._flyout = this._container.querySelector(".sidebar-flyout"); this._flyout = this._container.querySelector(".sidebar-flyout");
this._status = this._container.querySelector(".gnss-control__status"); this._status = this._container.querySelector(".gnss-control__status");
this._icon.addEventListener("click", () => this._setEnabled(!this._enabled)); this._icon.addEventListener("click", () => this._setEnabled(!this._enabled));
onGnssFollow(() => !this._enabled && !this._container.hidden && this._setEnabled(true));
// GET /api/gnss/position itself requires login too (app.rb) — hidden // GET /api/gnss/position itself requires login too (app.rb) — hidden
// here rather than shown and failing on click, same reasoning as // here rather than shown and failing on click, same reasoning as
@@ -89,15 +210,18 @@ export class GnssControl {
return; 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]; const lngLat = [data.lon, data.lat];
// Recenters on every fix while enabled — this is the app's own // Recenters on every fix while enabled — this is the app's own
// receiver, so "GNSS on" means "follow it", the same way LocateControl // 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. // (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 // startFollow (zooming in) only for the first fix, since that's the
// one jumping from wherever the map already was; easeTo for later // one jumping from wherever the map already was; a plain follow for
// updates, a plain follow rather than repeating that swoop every poll. // 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) { if (!this._marker) {
const el = document.createElement("div"); const el = document.createElement("div");
el.className = "gnss-marker"; el.className = "gnss-marker";
@@ -105,15 +229,43 @@ export class GnssControl {
// style's sources/layers, so — unlike the radar/GPX layers — this // style's sources/layers, so — unlike the radar/GPX layers — this
// survives map.setStyle() (switching Online/Offline) with no extra // survives map.setStyle() (switching Online/Offline) with no extra
// re-add handling needed. // re-add handling needed.
this._marker = new Marker({ element: el }).setLngLat(lngLat).addTo(this._map); 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 { } else {
this._marker.setLngLat(lngLat); glideMarker(this._marker, lngLat, POLL_INTERVAL_MS);
this._map.easeTo({ center: lngLat }); followPosition(this._map, lngLat, data.track, data.speed, POLL_INTERVAL_MS);
} }
// an arrow turned by the course, once there is one (a dot until then)
if (Number.isFinite(data.track)) {
const el = this._marker.getElement();
if (!el.classList.contains("gnss-marker--arrow")) {
el.classList.add("gnss-marker--arrow");
el.innerHTML = ARROW;
}
this._marker.setRotation(data.track);
}
this._marker.getElement().classList.toggle("gnss-marker--estimated", !!data.estimated);
this._showTag(lngLat, data);
}
// The status pill above the car (pypilot's note in the Design canvas' SidePanel): REC while
// drive mode records the trip (it sets .trip-rec on <html>), estimated / no fix; none when all is well
_showTag(lngLat, data) {
const rec = document.documentElement.classList.contains("trip-rec");
const fix = data.estimated ? "estimated" : data.mode >= 2 ? "" : "no fix";
if (!rec && !fix) return this._tag?.getElement().replaceChildren();
if (!this._tag) {
const el = document.createElement("div");
el.className = "gnss-tag";
this._tag = new Marker({ element: el, anchor: "bottom", offset: [0, -16] }).setLngLat(lngLat).addTo(this._map);
}
glideMarker(this._tag, lngLat, POLL_INTERVAL_MS);
this._tag.getElement().innerHTML = (rec ? `<span class="gnss-tag__rec">● REC</span>` : "") + (fix ? `<span>${fix}</span>` : "");
} }
_removeMarker() { _removeMarker() {
this._tag?.remove();
this._tag = null;
if (this._marker) { if (this._marker) {
this._marker.remove(); this._marker.remove();
this._marker = null; this._marker = null;
+834 -213
View File
File diff suppressed because it is too large. Load diff
+215 -12
View File
@@ -62,6 +62,9 @@ const OPACITY = 0.85;
// 3D terrain (sinks under raised ground, warns on the console) — a known // 3D terrain (sinks under raised ground, warns on the console) — a known
// limitation of the library, not worth working around for an overlay. // limitation of the library, not worth working around for an overlay.
const LANES_LAYER_ID = "hiking-trails-lanes"; const LANES_LAYER_ID = "hiking-trails-lanes";
// Zoomed out further, a whole country's lanes took seconds per frame/zoom
// build and froze the map — and a trail line at that scale tells nothing.
const LANES_MIN_ZOOM = 11;
const LANE_SIZES = () => ({ spacing: 3.5, width: 3, casingWidth: 0.5 }); const LANE_SIZES = () => ({ spacing: 3.5, width: 3, casingWidth: 0.5 });
function offlineUrl(code) { function offlineUrl(code) {
return `/tiles/hiking_trails/${code}.geojson`; return `/tiles/hiking_trails/${code}.geojson`;
@@ -83,6 +86,74 @@ function normalizedTrailColor(raw) {
return /^#[0-9a-fA-F]{3,8}$/.test(trimmed) ? trimmed : DEFAULT_TRAIL_COLOR; return /^#[0-9a-fA-F]{3,8}$/.test(trimmed) ? trimmed : DEFAULT_TRAIL_COLOR;
} }
// Route kinds (Maptool::HikingTrails#kind; a file extracted before kinds
// existed has none: hiking), the ones the map shows picked by the viewer.
const KIND_LABELS = { hiking: "Hiking", educational: "Educational", bicycle: "Cycling", ski: "Ski" };
const DEFAULT_KINDS = ["hiking", "educational"];
const kindOf = (properties) => properties.kind || "hiking";
// The offline trails of every ticked country (all kinds), for
// trailColorsAlong.
let shownTrails = [];
const TRAIL_MATCH_M = 20; // GPS/OSM offset a point may be off its trail
const GRID_DEG = 0.001; // ~100 m cells
// For each {lon, lat} point, the colors of the trails of `kinds` within
// TRAIL_MATCH_M of it ([] off-trail), for the elevation profile's trail
// band; null when no point is on one. Only the countries the hiking
// trails overlay has loaded, so ticking a country there turns it on.
export function trailColorsAlong(points, kinds) {
const trails = shownTrails.filter(({ properties }) => kinds.includes(kindOf(properties)));
if (!trails.length || !points.length) return null;
const lons = points.map((p) => p.lon);
const lats = points.map((p) => p.lat);
const [w, e] = [Math.min(...lons) - GRID_DEG, Math.max(...lons) + GRID_DEG];
const [s, n] = [Math.min(...lats) - GRID_DEG, Math.max(...lats) + GRID_DEG];
// Only segments near the points, bucketed by cell.
const grid = new Map();
for (const { geometry, properties } of trails) {
const lines = geometry.type === "LineString" ? [geometry.coordinates] : geometry.coordinates;
for (const line of lines) {
for (let i = 1; i < line.length; i++) {
const [a, b] = [line[i - 1], line[i]];
if (Math.max(a[0], b[0]) < w || Math.min(a[0], b[0]) > e || Math.max(a[1], b[1]) < s || Math.min(a[1], b[1]) > n) continue;
for (let x = Math.floor(Math.min(a[0], b[0]) / GRID_DEG); x <= Math.floor(Math.max(a[0], b[0]) / GRID_DEG); x++) {
for (let y = Math.floor(Math.min(a[1], b[1]) / GRID_DEG); y <= Math.floor(Math.max(a[1], b[1]) / GRID_DEG); y++) {
const key = `${x},${y}`;
if (!grid.has(key)) grid.set(key, []);
grid.get(key).push({ a, b, color: properties.color });
}
}
}
}
}
let any = false;
const colors = points.map(({ lon, lat }) => {
const found = new Set();
const [cx, cy] = [Math.floor(lon / GRID_DEG), Math.floor(lat / GRID_DEG)];
for (let dx = -1; dx <= 1; dx++) {
for (let dy = -1; dy <= 1; dy++) {
for (const { a, b, color } of grid.get(`${cx + dx},${cy + dy}`) || []) {
if (!found.has(color) && segmentDistanceM([lon, lat], a, b) <= TRAIL_MATCH_M) found.add(color);
}
}
}
if (found.size) any = true;
return [...found];
});
return any ? colors : null;
}
// Point to segment, on a local flat projection (fine at these distances).
function segmentDistanceM([lon, lat], a, b) {
const kx = 111320 * Math.cos((lat * Math.PI) / 180);
const ky = 110540;
const [ax, ay, bx, by] = [(a[0] - lon) * kx, (a[1] - lat) * ky, (b[0] - lon) * kx, (b[1] - lat) * ky];
const [dx, dy] = [bx - ax, by - ay];
const t = Math.max(0, Math.min(1, -(ax * dx + ay * dy) / (dx * dx + dy * dy || 1)));
return Math.hypot(ax + t * dx, ay + t * dy);
}
// Online mode's highlight outline for whichever route(s) the last click // Online mode's highlight outline for whichever route(s) the last click
// matched — drawn as its own separate source/layer (real geometry, from the // matched — drawn as its own separate source/layer (real geometry, from the
// Overpass response), since the raster tiles have no paintable features to // Overpass response), since the raster tiles have no paintable features to
@@ -106,6 +177,19 @@ export class HikingTrailsControl {
this._trailData = new Map(); // code -> fetched GeoJSON, kept across toggles/style swaps this._trailData = new Map(); // code -> fetched GeoJSON, kept across toggles/style swaps
this._routeInfo = new Map(); // String(relation id) -> feature properties, for the panel this._routeInfo = new Map(); // String(relation id) -> feature properties, for the panel
this._lanes = null; // the current LaneLayer, null when no country is shown this._lanes = null; // the current LaneLayer, null when no country is shown
this._bboxes = {}; // code -> [w, s, e, n]
this._inView = false; // main checkbox, offline: the countries in view
this._kinds = DEFAULT_KINDS;
try {
this._kinds = JSON.parse(localStorage.getItem("hikingTrailKinds")) || DEFAULT_KINDS;
} catch {}
// Each country entered while the main checkbox is on joins in.
// ponytail: a country left behind stays loaded until unticked.
map.on("moveend", () => {
if (this._inView) this._addCountriesInView();
if (this._selectedCountries.size > 0 && this._needsRebuild()) this._rebuildLanes();
});
map.on("click", (event) => this._handleClick(event)); map.on("click", (event) => this._handleClick(event));
@@ -133,15 +217,20 @@ export class HikingTrailsControl {
<button type="button" class="overlays-panel__name">Hiking trails</button> <button type="button" class="overlays-panel__name">Hiking trails</button>
</div> </div>
<div class="overlays-panel__details" hidden> <div class="overlays-panel__details" hidden>
<ul class="hiking-trail-countries hiking-trail-kinds"></ul>
<ul class="hiking-trail-countries"></ul> <ul class="hiking-trail-countries"></ul>
</div> </div>
`; `;
this._checkbox = li.querySelector(".overlays-panel__toggle"); this._checkbox = li.querySelector(".overlays-panel__toggle");
this._nameButton = li.querySelector(".overlays-panel__name"); this._nameButton = li.querySelector(".overlays-panel__name");
this._details = li.querySelector(".overlays-panel__details"); this._details = li.querySelector(".overlays-panel__details");
this._countryList = li.querySelector(".hiking-trail-countries"); this._kindList = li.querySelector(".hiking-trail-kinds");
this._countryList = li.querySelector(".hiking-trail-countries:not(.hiking-trail-kinds)");
this._checkbox.addEventListener("change", (event) => this._toggleOnline(event.target.checked)); this._checkbox.addEventListener("change", (event) => {
if (this._offlineCountries.length) this._toggleInView(event.target.checked);
else this._toggleOnline(event.target.checked);
});
this._nameButton.addEventListener("click", () => { this._nameButton.addEventListener("click", () => {
if (this._offlineCountries.length === 0) return; // nothing to expand into yet if (this._offlineCountries.length === 0) return; // nothing to expand into yet
const expanding = this._details.hidden; const expanding = this._details.hidden;
@@ -156,12 +245,29 @@ export class HikingTrailsControl {
// both offered at once, since once a real local extract exists there's // both offered at once, since once a real local extract exists there's
// no reason to still fall back to a third-party tile server for any of // no reason to still fall back to a third-party tile server for any of
// it. // it.
setOfflineCountries(countries) { setOfflineCountries(countries, bboxes = {}) {
this._offlineCountries = countries; this._offlineCountries = countries;
this._bboxes = bboxes;
if (countries.length === 0) return; if (countries.length === 0) return;
if (this._active) this._toggleOnline(false); if (this._active) this._toggleOnline(false);
this._checkbox.hidden = true; // The main checkbox stays: offline it shows the countries in view,
// never all at once (together they're ~1 GB of GeoJSON, more than a
// browser parses); the name opens the list to pick some by hand.
this._checkbox.checked = false;
this._checkbox.title = `Countries in view, from zoom ${LANES_MIN_ZOOM} — click the name to pick some`;
this._kindList.innerHTML = Object.entries(KIND_LABELS)
.map(([kind, label]) => `<li class="hiking-trail-countries__item"><label><input type="checkbox" value="${kind}"${this._kinds.includes(kind) ? " checked" : ""}> ${label}</label></li>`)
.join("");
this._kindList.addEventListener("change", () => {
this._kinds = [...this._kindList.querySelectorAll("input:checked")].map((input) => input.value);
try {
localStorage.setItem("hikingTrailKinds", JSON.stringify(this._kinds));
} catch {}
this._builtArea = null;
if (this._selectedCountries.size > 0) this._rebuildLanes();
});
this._countryList.innerHTML = countries this._countryList.innerHTML = countries
.map( .map(
@@ -176,10 +282,53 @@ export class HikingTrailsControl {
) )
.join(""); .join("");
this._countryList.querySelectorAll(".hiking-trail-countries__toggle").forEach((input) => { this._countryList.querySelectorAll(".hiking-trail-countries__toggle").forEach((input) => {
input.addEventListener("change", (event) => this._toggleCountry(event.target.value, event.target.checked)); input.addEventListener("change", (event) => {
this._toggleCountry(event.target.value, event.target.checked);
this._syncMainCheckbox();
});
}); });
} }
// Search box (search.js) picked a trail from a country that isn't ticked.
showCountry(code) {
const input = [...this._countryList.querySelectorAll("input")].find((el) => el.value === code);
if (!input || input.checked) return;
input.checked = true;
this._toggleCountry(code, true);
this._syncMainCheckbox();
}
_toggleInView(active) {
this._inView = active;
if (active) {
this._addCountriesInView();
} else {
this._countryList.querySelectorAll(".hiking-trail-countries__toggle:checked").forEach((input) => {
input.checked = false;
this._toggleCountry(input.value, false);
});
}
this._syncMainCheckbox();
}
// Trails are drawn from LANES_MIN_ZOOM only, so nothing loads before.
_addCountriesInView() {
if (this._map.getZoom() < LANES_MIN_ZOOM) return;
const view = this._map.getBounds();
this._countryList.querySelectorAll(".hiking-trail-countries__toggle:not(:checked)").forEach((input) => {
const [w, s, e, n] = this._bboxes[input.value] || [];
if (n === undefined || w > view.getEast() || e < view.getWest() || s > view.getNorth() || n < view.getSouth()) return;
input.checked = true;
this._toggleCountry(input.value, true);
});
}
_syncMainCheckbox() {
const on = this._countryList.querySelectorAll(".hiking-trail-countries__toggle:checked").length;
this._checkbox.checked = this._inView;
this._checkbox.indeterminate = !this._inView && on > 0;
}
_toggleOnline(active) { _toggleOnline(active) {
this._active = active; this._active = active;
if (active) this._addOnlineLayer(); if (active) this._addOnlineLayer();
@@ -212,16 +361,29 @@ export class HikingTrailsControl {
this._rebuildLanes(); this._rebuildLanes();
} }
// Rebuilt from scratch on every country toggle and style swap (setStyle // Rebuilt from scratch on every country toggle, style swap (setStyle
// drops custom layers too) — lane order depends on every route drawn, so // drops custom layers too) and when the view leaves the area built for —
// there's no cheaper incremental path. Ordering runs in a worker; a newer // lane order depends on every route drawn, so there's no cheaper
// rebuild started meanwhile wins, same token guard as _handleOnlineClick. // incremental path. Only the route pieces around the view (half a view
// around it): a whole country's graph took seconds on the main thread
// per rebuild and froze the browser; at zoom 11 this is ~0.5 s. Ordering runs in a worker; a newer rebuild started
// meanwhile wins, same token guard as _handleOnlineClick.
async _rebuildLanes() { async _rebuildLanes() {
const build = (this._lanesBuild = {}); const build = (this._lanesBuild = {});
const features = [...this._selectedCountries].flatMap((code) => this._trailData.get(code)?.features || []); const all = [...this._selectedCountries].flatMap((code) => this._trailData.get(code)?.features || []);
shownTrails = all;
let features = [];
this._builtArea = null;
if (all.length > 0 && this._map.getZoom() >= LANES_MIN_ZOOM) {
const view = this._map.getBounds();
const [dx, dy] = [view.getEast() - view.getWest(), view.getNorth() - view.getSouth()];
const area = [view.getWest() - dx / 2, view.getSouth() - dy / 2, view.getEast() + dx / 2, view.getNorth() + dy / 2];
this._builtArea = area;
features = all.filter(({ properties }) => this._kinds.includes(kindOf(properties))).flatMap((feature) => clipToArea(feature, area));
}
let graph = null; let graph = null;
if (features.length > 0) { if (features.length > 0) {
graph = buildLineGraph(features, { routeProperty: "id" }); graph = buildLineGraph(features.flatMap(splitOneway), { routeProperty: "id", onewayProperty: "oneway" });
await orderLanesAsync(graph); await orderLanesAsync(graph);
} }
if (this._lanesBuild !== build) return; if (this._lanesBuild !== build) return;
@@ -236,6 +398,16 @@ export class HikingTrailsControl {
// Below labels (same firstSymbolLayerId spot contour.js/radar.js use), // Below labels (same firstSymbolLayerId spot contour.js/radar.js use),
// so place names/POI icons stay readable on top of the trail lines. // so place names/POI icons stay readable on top of the trail lines.
this._map.addLayer(this._lanes, firstSymbolLayerId(this._map)); this._map.addLayer(this._lanes, firstSymbolLayerId(this._map));
this._map.setLayerZoomRange(LANES_LAYER_ID, LANES_MIN_ZOOM, 24);
}
// Zoomed in from below LANES_MIN_ZOOM, or out of the built area.
_needsRebuild() {
if (this._map.getZoom() < LANES_MIN_ZOOM) return false;
if (!this._builtArea) return true;
const view = this._map.getBounds();
const [w, s, e, n] = this._builtArea;
return view.getWest() < w || view.getSouth() < s || view.getEast() > e || view.getNorth() > n;
} }
_handleClick(event) { _handleClick(event) {
@@ -249,7 +421,7 @@ export class HikingTrailsControl {
// miss just closes an already-open panel rather than showing a "not // miss just closes an already-open panel rather than showing a "not
// found" message, same as clicking empty space anywhere else on the map. // found" message, same as clicking empty space anywhere else on the map.
_handleOfflineClick(event) { _handleOfflineClick(event) {
const hit = this._lanes?.queryLane(event.point, 8); const hit = this._map.getZoom() >= LANES_MIN_ZOOM && this._lanes?.queryLane(event.point, 8);
const info = hit && this._routeInfo.get(String(hit.route)); const info = hit && this._routeInfo.get(String(hit.route));
if (!info) { if (!info) {
this._hidePanel(); this._hidePanel();
@@ -440,3 +612,34 @@ function routeHtml(info) {
); );
return parts.join(""); return parts.join("");
} }
// A route's one-way lines (oneway_lines, already pointing the way they're
// walked: lib/maptool/hiking_trails.rb) as a feature of their own marked
// oneway, so maplibre-gl-lanes keeps the route on them in that direction.
// The route's lines (its member ways) with a vertex in `area` [w, s, e,
// n], [] when none; oneway_lines renumbered to match.
function clipToArea(feature, area) {
const [w, s, e, n] = area;
const lines = feature.geometry.type === "LineString" ? [feature.geometry.coordinates] : feature.geometry.coordinates;
const oneway = new Set(feature.properties.oneway_lines);
const kept = [];
const keptOneway = [];
lines.forEach((line, i) => {
if (!line.some(([x, y]) => x >= w && x <= e && y >= s && y <= n)) return;
if (oneway.has(i)) keptOneway.push(kept.length);
kept.push(line);
});
if (kept.length === 0) return [];
return [{ ...feature, properties: { ...feature.properties, oneway_lines: keptOneway }, geometry: { type: "MultiLineString", coordinates: kept } }];
}
function splitOneway(feature) {
const oneway = new Set(feature.properties.oneway_lines);
if (oneway.size === 0) return [feature];
const lines = feature.geometry.coordinates;
const part = (coordinates, properties) => ({ ...feature, properties, geometry: { type: "MultiLineString", coordinates } });
return [
part(lines.filter((_, i) => !oneway.has(i)), feature.properties),
part(lines.filter((_, i) => oneway.has(i)), { ...feature.properties, oneway: "yes" }),
].filter((f) => f.geometry.coordinates.length > 0);
}
+131 -420
View File
@@ -1,136 +1,77 @@
// Small hand-authored monoline SVG icons for the sidebar, so the app // The app's icons as inline SVG strings (fill currentColor, so CSS
// doesn't need to vendor an icon font/library for four glyphs. // colors them and gpx.js can recolor a copy for map markers).
// Material Design Icons (Apache-2.0, public/vendor/mdi/) for the UI;
// the National Park Service pictograms further down (CC0) for points.
// bin/vendor-sync.mjs vendors only the mdi* names used in public/js/.
import {
mdiBacteriaOutline,
mdiBugOutline,
mdiClockOutline,
mdiCloudDownloadOutline,
mdiCloudSyncOutline,
mdiContentSaveOutline,
mdiCrosshairsGps,
mdiDeleteSweepOutline,
mdiFolderPlusOutline,
mdiLayersOutline,
mdiLayersPlus,
mdiLock,
mdiLockOpenVariantOutline,
mdiMagnify,
mdiMapMarkerOutline,
mdiMapMarkerPath,
mdiMapMarkerPlusOutline,
mdiMapMarkerRadiusOutline,
mdiMapMarkerStarOutline,
mdiPuzzleOutline,
mdiRadar,
mdiRoutes,
mdiRuler,
mdiSunAngleOutline,
mdiSwapVertical,
mdiTrayArrowDown,
mdiTrayArrowUp,
mdiWeatherSunsetDown,
mdiWeatherSunsetUp,
mdiWikipedia,
} from "/vendor/mdi/mdi.mjs";
import { NPS_SYMBOLS } from "/vendor/nps-symbols/nps-symbols.mjs";
export const LAYERS_ICON = ` const mdi = (path) => `<svg viewBox="0 0 24 24"><path fill="currentColor" d="${path}"/></svg>`;
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linejoin="round" stroke-linecap="round">
<path d="M12 3 2 9l10 6 10-6-10-6z"/>
<path d="M2 14l10 6 10-6"/>
</svg>`;
// Two overlapping circles — distinct from LAYERS_ICON's stacked-planes
// look (that one picks a *base* map; this one is for the sidebar flyout
// toggling live overlay layers, e.g. Wikipedia, on top of whichever base
// map is showing) while still reading as "layers combining."
export const OVERLAYS_ICON = `
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linejoin="round" stroke-linecap="round">
<circle cx="9" cy="12" r="6"/>
<circle cx="15" cy="12" r="6"/>
</svg>`;
export const NOTE_PIN_ICON = `
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round">
<path d="M12 21s7-7.58 7-12a7 7 0 0 0-14 0c0 4.42 7 12 7 12z"/>
<path d="M12 6.5v5M9.5 9h5"/>
</svg>`;
export const GPX_ICON = `
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round">
<circle cx="5" cy="6" r="2"/>
<circle cx="19" cy="18" r="2"/>
<path d="M6.5 7.5C10 11 8 13 12 13s2 5 6.5 5"/>
</svg>`;
export const GNSS_ICON = `
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round">
<circle cx="12" cy="12" r="5.5"/>
<circle cx="12" cy="12" r="1.4" fill="currentColor" stroke="none"/>
<path d="M12 2v3M12 19v3M2 12h3M19 12h3"/>
</svg>`;
export const RULER_ICON = `
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linejoin="round" stroke-linecap="round">
<path d="M4 15 15 4l5 5-11 11-5-5z"/>
<path d="M9 10l1.5 1.5M12 7l1.5 1.5M15 4l1.5 1.5M6 13l1.5 1.5"/>
</svg>`;
// Toolbar readout glyphs (public/js/sun.js's text, assembled with these by
// map.js) — same monoline style as the sidebar icons above, no NPS source
// for either (that set has no sunrise/sunset pictogram).
export const SUNRISE_ICON = `
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round">
<path d="M3 18h18"/>
<path d="M6 18a6 6 0 0 1 12 0"/>
<path d="M12 13V5"/>
<path d="M9 8l3-3 3 3"/>
</svg>`;
export const SUNSET_ICON = `
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round">
<path d="M3 18h18"/>
<path d="M6 18a6 6 0 0 1 12 0"/>
<path d="M12 5v8"/>
<path d="M9 10l3 3 3-3"/>
</svg>`;
export const SEARCH_ICON = `
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round">
<circle cx="11" cy="11" r="7"/>
<path d="M20 20l-4.35-4.35"/>
</svg>`;
export const NEW_FOLDER_ICON = `
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round">
<path d="M3 7a2 2 0 0 1 2-2h4l2 2h8a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V7z"/>
<path d="M12 11v5M9.5 13.5h5"/>
</svg>`;
export const UPLOAD_ICON = `
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round">
<path d="M12 15V4M8 8l4-4 4 4"/>
<path d="M4 15v3a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-3"/>
</svg>`;
// The inverse of UPLOAD_ICON (arrow into the tray, not out of it) — used
// for the import plugins panel (plugins.js), which pulls data in from
// somewhere else rather than sending a file out.
export const PLUGIN_ICON = `
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round">
<path d="M12 4v11M8 11l4 4 4-4"/>
<path d="M4 15v3a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-3"/>
</svg>`;
// Shown next to each file in the GPX tree, indicating whether it has
// waypoints, a track, or both.
export const WAYPOINT_ICON = `
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round">
<path d="M12 21s7-7.58 7-12a7 7 0 0 0-14 0c0 4.42 7 12 7 12z"/>
<circle cx="12" cy="9" r="2.2"/>
</svg>`;
export const LAYERS_ICON = mdi(mdiLayersOutline);
export const OVERLAYS_ICON = mdi(mdiLayersPlus);
export const NOTE_PIN_ICON = mdi(mdiMapMarkerPlusOutline);
export const GPX_ICON = mdi(mdiMapMarkerPath);
export const GNSS_ICON = mdi(mdiCrosshairsGps);
export const RULER_ICON = mdi(mdiRuler);
export const SUNRISE_ICON = mdi(mdiWeatherSunsetUp);
export const SUNSET_ICON = mdi(mdiWeatherSunsetDown);
export const SEARCH_ICON = mdi(mdiMagnify);
export const NEW_FOLDER_ICON = mdi(mdiFolderPlusOutline);
export const UPLOAD_ICON = mdi(mdiTrayArrowUp);
export const PLUGIN_ICON = mdi(mdiPuzzleOutline);
export const WAYPOINT_ICON = mdi(mdiMapMarkerOutline);
export const PENDING_ICON = mdi(mdiClockOutline);
export const DOWNLOAD_ICON = mdi(mdiTrayArrowDown);
export const ROUTE_ICON = mdi(mdiRoutes);
export const RADAR_CLOUD_ICON = mdi(mdiRadar);
export const TERRAIN_SHADOW_ICON = mdi(mdiSunAngleOutline);
export const CONTOUR_ICON = mdi(mdiBacteriaOutline);
export const OFFLINE_DATA_ICON = mdi(mdiCloudDownloadOutline);
export const SYNC_ICON = mdi(mdiCloudSyncOutline);
export const DEBUG_ICON = mdi(mdiBugOutline);
export const WIKI_ICON = mdi(mdiWikipedia);
export const LIVETRACK_ICON = mdi(mdiMapMarkerRadiusOutline);
export const POSITION_ICON = mdi(mdiCrosshairsGps);
export const SAVED_POINT_ICON = mdi(mdiMapMarkerStarOutline);
export const REVERSE_ICON = mdi(mdiSwapVertical);
export const CLEAR_ICON = mdi(mdiDeleteSweepOutline);
export const SAVE_ICON = mdi(mdiContentSaveOutline);
export const LOCK_ICON = mdi(mdiLock);
export const UNLOCK_ICON = mdi(mdiLockOpenVariantOutline);
export const TRACK_ICON = GPX_ICON; export const TRACK_ICON = GPX_ICON;
// Shown next to a file whose GeoJSON conversion is NOT yet cached on disk
// (GpxStore#geojson) — the uncommon case, since GpxStore#save converts
// eagerly at upload time; this only happens for a .gpx/.fit dropped
// straight into data/gpx/ on the filesystem, bypassing the app, and not
// yet opened. Everything uploaded normally is cached almost immediately,
// so badging the common case would just be noise — this badges the
// exception instead.
export const PENDING_ICON = `
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round">
<circle cx="12" cy="12" r="8"/>
<path d="M12 8v4l3 2"/>
</svg>`;
// A small download button next to each tree file's delete button — the
// name link (see gpx.js's _renderFile) does the same thing, but isn't
// obviously clickable at a glance, so this is the discoverable version.
export const DOWNLOAD_ICON = `
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round">
<path d="M12 4v11M8 11l4 4 4-4"/>
<path d="M4 15v3a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-3"/>
</svg>`;
// Same shape as TRACK_ICON, dashed — a route is planned rather than
// recorded, the same visual convention most map apps use for the
// distinction.
export const ROUTE_ICON = `
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round">
<circle cx="5" cy="6" r="2"/>
<circle cx="19" cy="18" r="2"/>
<path d="M6.5 7.5C10 11 8 13 12 13s2 5 6.5 5" stroke-dasharray="2 2.2"/>
</svg>`;
// A rounded-square badge — used as the map marker for individual waypoints, // A rounded-square badge — used as the map marker for individual waypoints,
// tinted by category color via icon-color (see gpx.js). Not a plain dot, // tinted by category color via icon-color (see gpx.js). Not a plain dot,
// which blended in with a base map style's own small circular POI icons, // which blended in with a base map style's own small circular POI icons,
@@ -143,217 +84,46 @@ export const ROUTE_ICON = `
export const MAP_MARKER_ICON = ` export const MAP_MARKER_ICON = `
<svg viewBox="0 0 24 24"><rect x="1" y="1" width="22" height="22" rx="5" fill="currentColor"/></svg>`; <svg viewBox="0 0 24 24"><rect x="1" y="1" width="22" height="22" rx="5" fill="currentColor"/></svg>`;
// POI category glyphs (park4night/OsmAnd exports), keyed by the OsmAnd icon // The National Park Service's map pictograms for points: every symbol of
// name a file's <osmand:icon> extension carries — a small curated set for // their symbol-library, vendored by bin/nps-symbols-sync.mjs (CC0, 22 px,
// the categories park4night actually uses (see waypoint_style in // filled shapes — they render at ~14px on the map, where a hairline stroke
// lib/maptool/gpx.rb), not an exhaustive OsmAnd icon set. // disappears). Rasterized for the map (non-SDF, see gpx.js's
// // _registerCategoryGlyphs), so only the alpha shape matters there.
// These are the National Park Service's own map pictograms, not export { NPS_SYMBOLS };
// hand-drawn — a professional, widely-recognized icon set built for const nps = (name) => NPS_SYMBOLS[name];
// exactly this job (small monochrome map markers) beats reinventing "fuel export const WILDERNESS_ICON = nps("wilderness"); // also the Overlays panel's Terrain shading glyph
// pump"/"picnic table" glyphs from scratch. Pulled from export const WALKING_ICON = nps("walking"); // also the Overlays panel's Hiking trails glyph
// github.com/nationalparkservice/npmap5-plugins's bundled `symbol-library`
// (src/<name>-22.svg) — an actively-maintained monorepo that's the
// designated replacement for the same org's older standalone
// `symbol-library` repo (confirmed by its maintainer:
// github.com/nationalparkservice/npmap5-plugins/issues/4), with a much
// larger icon vocabulary. CC0-licensed (public domain) — no attribution
// required.
//
// All filled shapes — these render at ~14px on the map, where a hairline
// stroke disappears — and rasterized (non-SDF; a plain colored raster, not
// tinted at render time, see gpx.js's _registerCategoryGlyphs) so only the
// alpha shape matters, not the actual `currentColor` value.
// src/wilderness-22.svg — exported (unlike BICYCLE_TRAIL_ICON below, this
// one's also used outside this file) as the Overlays panel's Terrain
// shading glyph (overlays.js): the closest honest match in NPS's set for
// "mountains/terrain" — it has no weather or elevation-specific pictogram.
export const WILDERNESS_ICON = `
<svg viewBox="0 0 22 22" fill="currentColor"><polygon points="18,18 13,15 17,15 13,11 16,11 12,7 15,7 12,4 14,4 11,0 8,4 10,4 7,7 10,7 6,11 9,11 5,15 9,15 4,18 10,18 10,22 12,22 12,18 "/></svg>`;
// Hand-drawn, not NPS-sourced — that set has no weather/precipitation
// pictogram to reuse for the Overlays panel's Radar item, unlike Wikipedia
// (WIKI_ICON) and Terrain shading (WILDERNESS_ICON) above.
export const RADAR_CLOUD_ICON = `
<svg viewBox="0 0 22 22" fill="currentColor">
<path d="M17,10.1c-0.4-3-2.9-5.3-6-5.3c-2.5,0-4.7,1.5-5.6,3.8C3.4,8.9,1,11.1,1,13.9C1,16.7,3.3,19,6.1,19h10.3
c2.5,0,4.6-2,4.6-4.5C21,12.2,19.3,10.4,17,10.1z"/>
<rect x="6" y="20" width="1.6" height="2"/>
<rect x="10.2" y="20" width="1.6" height="2"/>
<rect x="14.4" y="20" width="1.6" height="2"/>
</svg>`;
// Hand-drawn, not NPS-sourced — same story as RADAR_CLOUD_ICON above, no
// terrain-shadow/sun-behind-a-ridge pictogram in that set either. Used as
// the Overlays panel's Terrain shadow glyph (shadow.js via overlays.js).
export const TERRAIN_SHADOW_ICON = `
<svg viewBox="0 0 22 22" fill="currentColor">
<circle cx="16" cy="6" r="3"/>
<polygon points="0,19 6,9 9,13 13,6 22,19"/>
</svg>`;
// Hand-drawn, not NPS-sourced — no contour-line pictogram in that set
// either. Concentric rings via fill-rule evenodd, same solid-glyph
// convention as WILDERNESS_ICON/RADAR_CLOUD_ICON/TERRAIN_SHADOW_ICON above —
// used as the Overlays panel's Contour lines glyph (contour.js).
export const CONTOUR_ICON = `
<svg viewBox="0 0 22 22" fill="currentColor" fill-rule="evenodd">
<path d="M21,11 A10,10 0 1,0 1,11 A10,10 0 1,0 21,11 Z
M18.5,11 A7.5,7.5 0 1,0 3.5,11 A7.5,7.5 0 1,0 18.5,11 Z
M16,11 A5,5 0 1,0 6,11 A5,5 0 1,0 16,11 Z
M13.5,11 A2.5,2.5 0 1,0 8.5,11 A2.5,2.5 0 1,0 13.5,11 Z"/>
</svg>`;
// src/bicycle-trail-22.svg — pulled out to its own constant since it's also
// used unrasterized, inline, as PARK4NIGHT_TAGS.vtt below.
const BICYCLE_TRAIL_ICON = `
<svg viewBox="0 0 22 22" fill="currentColor">
<circle cx="13.9" cy="3" r="2"/>
<path d="M4.5,20C6.4,20,8,18.4,8,16.5S6.4,13,4.5,13S1,14.6,1,16.5S2.6,20,4.5,20z M0,16.5C0,14,2,12,4.5,12S9,14,9,16.5
S7,21,4.5,21S0,19,0,16.5z"/>
<path d="M17.5,20c1.9,0,3.5-1.6,3.5-3.5S19.4,13,17.5,13S14,14.6,14,16.5S15.6,20,17.5,20z M13,16.5c0-2.5,2-4.5,4.5-4.5
s4.5,2,4.5,4.5S20,21,17.5,21S13,19,13,16.5z"/>
<path d="M13.1,9.8c-0.2,0-0.5-0.1-0.7-0.4l-1.1-1.7L9.1,9.9l2.1,1.1c0.9,0.4,0.9,1,0.9,1v5c0,0.5-0.6,0.9-1.2,0.9S10,17.6,10,17v-4
l-3.8-1.9c-0.4-0.3-0.7-0.7-0.7-1.2C5.6,9.5,5.7,9.2,6,9l3.5-3.5C9.9,4.9,10.6,5,10.6,5c0.7,0,1.1,0.6,1.1,0.6l1.8,2.9h2.8
c1,0,1,1.3,0,1.3H13.1L13.1,9.8z"/>
</svg>`;
// src/store-22.svg — NPS's generic shop pictogram, the closest match in
// their set for both a supermarket and a convenience store (no separate
// grocery-specific glyph exists there).
const STORE_ICON = `
<svg viewBox="0 0 22 22" fill="currentColor">
<path d="M20,9c0,0-0.8,3-4,3C16,12,15.8,9.9,20,9z"/>
<path d="M17,14.3c0.5-0.5,1.3-0.9,2.1-0.9c1.6,0,2.9,1.3,2.9,3v0.2l0,0c-0.1,0.6-0.3,1.5-0.7,2.4c0,0-0.8,1.6-1.5,2.3l-0.1,0.1
c-0.3,0.3-0.8,0.5-1.3,0.5c-0.6,0-1.1-0.5-1.5-1c-0.3,0.5-0.9,1-1.5,1c-0.5,0-0.9-0.2-1.3-0.5L14,21.3c-0.7-0.7-1.5-2.3-1.5-2.3
c-0.5-1-0.7-1.8-0.7-2.4l0,0v-0.2c0-1.7,1.3-3,2.9-3C15.7,13.5,16.5,13.8,17,14.3"/>
<polygon points="4,0 8,0 8,2 4,2 "/>
<path d="M7,3H3c0,0-0.7,0.2-1.2,0.7L0.2,5.8C0.1,6,0,5.9,0,6.1V21c0,0.4,0.6,1,1,1h8c0.4,0,1-0.6,1-1V6C10,6,9.6,3.3,7,3z M4,4v5H3
v1H2l-1,1v-1V6h1V5h1L4,4z"/>
</svg>`;
// A point's `icon` property names its glyph: any NPS symbol name
// ("drinking-water", "campground", …), or one of these OsmAnd icon names a
// park4night/OsmAnd export (lib/maptool/gpx.rb's waypoint_style) and the
// Overpass POIs (lib/maptool/overpass_pois.rb) carry. These come first in
// the note icon picker.
export const POI_ICONS = { export const POI_ICONS = {
// src/parking-22.svg amenity_parking: nps("parking"),
amenity_parking: ` tourism_camp_site: nps("campground"),
<svg viewBox="0 0 22 22"><path fill="currentColor" d="M11.9,11c1.8,0,3.5-1.8,3.5-3.6S13.7,4,11.9,4h-5v7H11.9z M12.1,0C16.2,0,20,3.3,20,7.5c0,4.1-3.9,7.5-8.1,7.5h-5v7H3V0 leisure_picnic_table: nps("picnic-area"),
H12.1z"/></svg>`, amenity_fuel: nps("gas-station"),
tourism_hotel: nps("lodging"),
// src/campground-22.svg
tourism_camp_site: `
<svg viewBox="0 0 22 22" fill="currentColor">
<path d="M17,21L9.4,5.8L2,21H0v1h19v-1H17z M5,21l4.5-8.5L14,21H5z"/>
<polygon points="20,18 20,18 12.3,2.9 11.5,4.7 19,19 20.5,19 "/>
<polygon points="15.5,0 14.7,1.7 22,16 22,13 "/>
</svg>`,
// src/picnic-area-22.svg
leisure_picnic_table: `
<svg viewBox="0 0 22 22"><path fill="currentColor" d="M22,11h-6l-2-5h4V4H4v2h4l-2,5H0v2h5l-2,5h2l2-5h8l2,5h2l-2-5h5V11z M8,11l2-5h2l2,5H8z"/></svg>`,
// src/gas-station-22.svg
amenity_fuel: `
<svg viewBox="0 0 22 22"><path fill="currentColor" d="M19,14.4L19,14.4v-1.5V6.2c0-0.7-0.4-1.3-0.9-1.8L15,1.5c-0.2,0-0.8,0.4-0.8,0.4c0,0.2,1.5,1.8,1.5,1.8v2.6
c0,0.9,0.8,1.8,1.7,1.8L18,7.9v5v1.7l1,5.1c0,0.8-0.9,1.3-1.5,1.3C17,21,16,20.5,16,20v-8.9C16,10,15.4,9,14.4,9H12V1h-1V0H3v1H2
v21h10V10.4h2.4c0.4,0,0.6,0.3,0.6,0.7V20c0,1.2,1.2,2,2.5,2c1.2,0,2.5-0.8,2.5-2C20,19.7,19,14.4,19,14.4z M18,7h-1V5h1V7z
M10.5,5.8L9.6,6.6H4.4L3.5,5.8V2.2l0.9-0.9h5.2l0.9,0.9V5.8z"/></svg>`,
// src/lodging-22.svg
tourism_hotel: `
<svg viewBox="0 0 22 22" fill="currentColor">
<polygon points="0,4 2,4 2,12 22,12 22,17 20,17 20,14 2,14 2,17 0,17 "/>
<polygon points="3,11 22,11 22,8 21,7 13,6 7,6 7,9 3,9 "/>
<circle cx="4.5" cy="6.5" r="1.5"/>
</svg>`,
// src/wilderness-22.svg
forest: WILDERNESS_ICON, forest: WILDERNESS_ICON,
sport_cycling: nps("bicycle-trail"),
// src/bicycle-trail-22.svg amenity_drinking_water: nps("drinking-water"),
sport_cycling: BICYCLE_TRAIL_ICON, amenity_sanitary_dump_station: nps("sanitary-disposal-station"),
amenity_toilets: nps("restrooms"),
shop_gas: nps("propane"),
amenity_electricity: nps("electrical-hookup"),
shop_laundry: nps("laundry"),
leisure_playground: nps("playground"),
tourism_viewpoint: nps("scenic-viewpoint"),
leisure_swimming: nps("swimming"),
leisure_fishing: nps("fishing"),
sport_climbing: nps("climbing"),
route_hiking: WALKING_ICON,
shop_supermarket: nps("store"),
shop_convenience: nps("store"),
...NPS_SYMBOLS,
}; };
// National Park Service map symbols (same source/license as POI_ICONS above)
// used as small inline glyphs next to a park4night waypoint's Services/
// Activities tags (see PARK4NIGHT_TAGS and formatDescription in
// public/js/gpx.js) — pulled into named constants first since a few codes
// share the same real-world facility (eau_noire/eau_usee are both a dump
// station, gaz/gpl are both a propane refill, peche/peche_pied are both
// fishing) and BICYCLE_TRAIL_ICON is also POI_ICONS.sport_cycling above.
const PETS_ON_LEASH_ICON = `
<svg viewBox="0 0 22 22" fill="currentColor"><g><polygon points="3,12 3,21 4,21 4,22 5,22 5,21 6,21 6,18 9,22 10,22 11,20 8,16 14,16 14,21 15,21 15,22 16,22 16,21 17,21 17,11 13,9 3,9 2,8 1,9 "/><polygon points="13,7 13,1 14,1 14,2 22,6 22,8 17,9 "/><polygon points="0,1 0,2.5 13,8.5 13,7 "/></g></svg>`;
const SHOWERS_ICON = `
<svg viewBox="0 0 22 22" fill="currentColor"><path d="M4.9,12.8c-0.1,0.4,0.2,0.7,0.6,0.8s0.7-0.2,0.8-0.6c0.1-0.4-0.2-0.7-0.6-0.8C5.3,12.1,4.9,12.4,4.9,12.8z M5.5,11.2 c0.1-0.4-0.2-0.7-0.5-0.7S4.3,10.7,4.2,11c-0.1,0.4,0.2,0.7,0.5,0.7C5.1,11.8,5.4,11.6,5.5,11.2z M4.1,8.8c0.3,0,0.6,0.3,0.6,0.6 S4.4,10,4.1,10S3.5,9.7,3.5,9.4S3.8,8.8,4.1,8.8z M3.4,7C3.7,7,4,7.3,4,7.6S3.7,8.2,3.4,8.2S2.8,7.9,2.8,7.6S3.1,7,3.4,7z M2.7,5.4 c0.3,0,0.5,0.2,0.5,0.5S3,6.4,2.7,6.4S2.2,6.2,2.2,5.9S2.4,5.4,2.7,5.4z M2,3.6c0.3,0,0.5,0.2,0.5,0.5S2.3,4.6,2,4.6 S1.5,4.4,1.5,4.1S1.7,3.6,2,3.6z M7.4,10.3c0-0.4,0.3-0.7,0.7-0.6c0.4,0,0.7,0.3,0.6,0.7c0,0.4-0.3,0.7-0.7,0.6 C7.7,11,7.4,10.7,7.4,10.3z M7,8.3c0.3,0,0.6,0.3,0.6,0.6S7.3,9.5,7,9.5S6.4,9.2,6.4,8.9S6.7,8.3,7,8.3z M6,6.9 c0.3,0,0.6,0.3,0.6,0.6S6.3,8.1,6,8.1S5.4,7.8,5.4,7.5S5.7,6.9,6,6.9z M4.9,5.5c0.3,0,0.6,0.3,0.6,0.6S5.2,6.7,4.9,6.7 S4.3,6.4,4.3,6.1S4.6,5.5,4.9,5.5z M3.9,4.2c0.3,0,0.5,0.2,0.5,0.5S4.2,5.2,3.9,5.2S3.4,5,3.4,4.7S3.6,4.2,3.9,4.2z M2.8,2.8 c0.3,0,0.5,0.2,0.5,0.5S3.1,3.8,2.8,3.8S2.3,3.6,2.3,3.3S2.5,2.8,2.8,2.8z M9.3,7.4c-0.4,0-0.7-0.3-0.7-0.6c0-0.4,0.3-0.7,0.6-0.7 c0.4,0,0.7,0.3,0.7,0.6C9.9,7.1,9.6,7.4,9.3,7.4z M8.5,5.7c0,0.3-0.2,0.6-0.6,0.7S7.2,6.1,7.2,5.7S7.5,5.1,7.8,5 C8.1,5,8.4,5.3,8.5,5.7z M7,4.6c0,0.3-0.2,0.6-0.6,0.6C6.1,5.2,5.8,5,5.8,4.6C5.8,4.3,6.1,4,6.4,4C6.7,4,7,4.3,7,4.6z M5,3 c0.3,0,0.6,0.3,0.6,0.6S5.3,4.2,5,4.2S4.4,3.9,4.4,3.6S4.7,3,5,3z M3.6,2c0.3,0,0.5,0.2,0.5,0.5S3.9,3,3.6,3S3.1,2.8,3.1,2.5 S3.3,2,3.6,2z M4.4,1.2c0.3,0,0.5,0.2,0.5,0.5S4.7,2.2,4.4,2.2S3.9,2,3.9,1.7S4.1,1.2,4.4,1.2z M6.3,1.9c0.3,0,0.5,0.2,0.5,0.5 S6.6,2.9,6.3,2.9S5.8,2.7,5.8,2.4S6,1.9,6.3,1.9z M8.1,2.6c0.3,0,0.6,0.3,0.6,0.6S8.4,3.8,8.1,3.8c-0.3,0-0.6-0.3-0.6-0.6 S7.8,2.6,8.1,2.6z M9.9,3.3c0.3,0,0.6,0.3,0.6,0.6s-0.3,0.6-0.6,0.6S9.3,4.2,9.3,3.9S9.6,3.3,9.9,3.3z M11.7,4.1 c0.3,0,0.6,0.3,0.6,0.6S12,5.3,11.7,5.3S11.1,5,11.1,4.7S11.4,4.1,11.7,4.1z M0,1h1V0h4v1H4v1H3v1H2v1H1v1H0V1z M11.5,7 C12.9,7,14,8.1,14,9.5S12.9,12,11.5,12S9,10.9,9,9.5S10.1,7,11.5,7z M14,13v-1h1v-1h1v-1h1V9h1V8h1V7h1V6h1l1,1v1v1h-1v1h-1v1h-1v1 h-1v1h-1v1h-1v8H9v-4H5v-2h1v-1h1v-1h1v-1H14z M10,16h1v2h-1v1h2v-4h-2V16z"/></svg>`;
const SANITARY_DISPOSAL_ICON = `
<svg viewBox="0 0 22 22" fill="currentColor"><g><path d="M20,10V2h-1V1H4v1H3v8h1v1h5V9h1V8h3v1h1v2h8v-1H20z M11,5H6L5,4l1-1h5l1,1L11,5z M17,5h-2l-1-1l1-1h2l1,1L17,5z"/><path d="M10,9h3v3h-3V9z M11,11h1v-1h-1V11z"/><polygon points="8,13 21,13 22,14 22,19 21,20 1,20 0,19 0,14 1,13 4,13 4,14 2,14 1,15 1,18 2,19 10,19 11,18 11,15 10,14 8,14 "/><polygon points="5.5,12 6.5,12 6.5,16 8,16 6,18 4,16 5.5,16 "/></g></svg>`;
const ELECTRICAL_HOOKUP_ICON = `
<svg viewBox="0 0 22 22" fill="currentColor"><path d="M16,6.3V1.1C16,0.5,15.2,0,14.5,0C13.8,0,13,0.5,13,1.1v5.2H8.8V1.1C8.8,0.5,8.2,0,7.5,0C6.8,0,6,0.5,6,1.1v5.2H3.5 c0,0,0,1.4,0,2.2c0,3.1,2.5,5.7,5.7,6.4l0.3,0V22h2.9v-7.1l0.1,0c3.4-0.7,5.9-3.2,5.9-6.4c0-0.8,0-2.2,0-2.2H16z"/></svg>`;
const PROPANE_ICON = `
<svg viewBox="0 0 22 22" fill="currentColor"><path d="M15,4V0H7v4C4.9,4.4,3,6.3,3,8.4v7c0,2.2,1.6,4,3.7,4.4V22h8.6v-2.2c2.1-0.4,3.7-2.2,3.7-4.4v-7C19,6.3,17.1,4.4,15,4z M12,1h2v3h-2V1z M8,1h2v3H8V1z M13,13.6c-0.5,0.8-2.2,1.7-1.7,3.5h-1.1c-0.8-0.9-3.5-3.9-1.3-6c2.2-2,2.5-3.7,1.7-4.5 C10.7,6.6,16.2,8.7,13,13.6z"/></svg>`;
const LAUNDRY_ICON = `
<svg viewBox="0 0 22 22" fill="currentColor"><path d="M3,0v4h16V0H3z M6,3H4V1h2V3z M10,3H8V1h2V3z"/><path d="M3,5v17h16V5H3z M11,19c-3.3,0-6-2.7-6-6s2.7-6,6-6s6,2.7,6,6S14.3,19,11,19z"/><path d="M6.5,11c-0.6-0.4-0.4,1.3-0.4,2c0,2.7,2.2,4.9,4.9,4.9s4.9-2.2,4.9-4.9c0-0.7,0.1-1.6-0.4-2C10.2,6.7,11.9,14.7,6.5,11z"/></svg>`;
const SWIMMING_ICON = `
<svg viewBox="0 0 22 22" fill="currentColor"><g><polygon points="0,16 1,16 3,17 4,17 6,16 7,16 9,17 10,17 12,16 13,16 15,17 16,17 18,16 19,16 21,17 22,17 22,19 21,19 19,18 18,18 16,19 15,19 13,18 12,18 10,19 9,19 7,18 6,18 4,19 3,19 1,18 0,18 "/><polygon points="6,14 7,14 9,15 10,15 12,14 13,14 15,15 16,15 17.5,14.2 13,7 18,6 20,5 20,4 18,3 10,4 9,5 9,6 11,10 3,15 4,15 "/><circle cx="19.5" cy="10.5" r="2.5"/></g></svg>`;
const DRINKING_WATER_ICON = `
<svg viewBox="0 0 22 22" fill="currentColor"><polygon points="20,0 18,0 15,20 7,20 4,0 2,0 5.5,22 16.5,22 "/><path d="M15.9,2c-0.4,0.4-0.9,1-1.4,1c-0.7,0-1.3-0.8-1.7-1.4C12.5,2.2,11.7,3,11,3c-0.7,0-1.2-0.8-1.5-1.4C9.1,2.2,8.7,3,8,3 C7.5,3,6.8,2.3,6.4,2L6.2,0.1C6.5,0.6,7.3,1,8,1c0.7,0,1.1-0.4,1.5-1c0.4,0.5,0.8,1,1.5,1c0.7,0,1.5-0.4,1.8-1c0.4,0.5,1,1,1.7,1 c0.7,0,1.3-0.5,1.7-1L15.9,2z"/></svg>`;
const TRASH_DUMPSTER_ICON = `
<svg viewBox="0 0 22 22" fill="currentColor"><path d="M13,7h-2c-1.1,0-1.1,2,0,2h3c0.2,0,1-2,1-2v14c0,0.5,0.5,1,1,1s1-0.4,1-1v-8h1v8c0,0.5,0.5,1,1,1s1-0.4,1-1V7h1v5 c0,1.1,0.5,1.1,1,0V6c0-1.2-1.6-1-3-1h-3c-0.8,0-1.6,0.4-2,1L13,7z M3,16c1.6,0,3,1.4,3,3v3h2l3.5-8.9v-2.9H1.2L1,16H3z M9.6,5.8 L9.6,5.8L9.2,6L9,5.6l0,0L8.6,5.8L8.4,5.4l0,0L8,5.6L7.8,5.2l0,0L7.4,5.4L7.2,5l0,0L6.8,5.2L6.6,4.7L5.4,8.2 C5.3,8.5,5.5,8.8,5.8,8.9l2,0.7C8,9.7,8.3,9.5,8.4,9.3L9.6,5.8z M7.9,2.3L7.3,1.8L0.7,9.7l0.5,0.5L7.9,2.3z M18,0c1.1,0,2,0.9,2,2 s-0.9,2-2,2s-2-0.9-2-2S16.9,0,18,0z M2.5,17C1.1,17,0,18.1,0,19.5S1.1,22,2.5,22S5,20.9,5,19.5S3.9,17,2.5,17z M2.5,21 C1.7,21,1,20.3,1,19.5S1.7,18,2.5,18S4,18.7,4,19.5S3.3,21,2.5,21z"/></svg>`;
const RESTROOMS_ICON = `
<svg viewBox="0 0 22 22" fill="currentColor"><g><rect x="11" y="2" width="2" height="18"/><polygon points="21,7 21,6 20,6 19,6 18,6 17,6 16,6 16,7 15,7 15,8 15,13 16,13 16,8 17,8 17,20 18,20 18,14 19,14 19,20 20,20 20,8 21,8 21,13 22,13 22,8 22,7 "/><polygon points="8,7 6,6 3,6 1,7 1,8 0,12 1,12 2,8 3,8 3,9 1,15 3,15 3,20 4,20 4,15 5,15 5,20 6,20 6,15 8,15 6,9 6,8 7,8 8,12 9,12 8,8 "/><circle cx="4.5" cy="3.5" r="1.5"/><circle cx="18.5" cy="3.5" r="1.5"/></g></svg>`;
const RIVER_RAFTING_ICON = `
<svg viewBox="0 0 22 22" fill="currentColor"><path d="M20.4,17.4c-0.5,0.3-0.9,0.8-1.6,0.8c-0.7,0-1.1-0.5-1.6-0.8c-0.4-0.3-1-0.8-1.6-0.8c-0.6,0-1.2,0.4-1.6,0.8 c-0.3,0.3-0.9,0.8-1.6,0.8c-0.7,0-1.2-0.5-1.6-0.8c-0.4-0.3-0.8-0.8-1.6-0.8c-0.7,0-1.2,0.5-1.6,0.8c-0.4,0.3-0.8,0.8-1.6,0.8 c-0.7,0-1.2-0.5-1.6-0.8c-0.4-0.2-0.7-0.8-1.6-0.8c-0.8,0-1.2,0.5-1.6,0.8C1.2,17.7,0,18.2,0,18.2v1.6v1.6c0,0,1.2-0.5,1.6-0.8 c0.4-0.3,0.8-0.8,1.6-0.8c0.9,0,1.2,0.5,1.6,0.8c0.4,0.3,0.9,0.8,1.6,0.8c0.8,0,1.2-0.5,1.6-0.8c0.4-0.3,0.8-0.8,1.6-0.8 c0.8,0,1.2,0.5,1.6,0.8c0.4,0.3,0.9,0.8,1.6,0.8c0.7,0,1.2-0.5,1.6-0.8c0.4-0.3,1-0.8,1.6-0.8c0.6,0,1.2,0.5,1.6,0.8 c0.5,0.3,0.9,0.8,1.6,0.8c0.6,0,1-0.5,1.6-0.8c0.5-0.3,1.6-0.8,1.6-0.8v-1.6v-1.6C22,16.6,21,17.1,20.4,17.4z"/><path d="M3.1,15c0.9,0,1.2,0.5,1.6,0.8c0.4,0.3,0.9,0.8,1.6,0.8c0.8,0,1.2-0.5,1.6-0.8C8.2,15.6,8.7,15,9.4,15 c0.8,0,1.2,0.5,1.6,0.8c0.4,0.3,0.9,0.8,1.6,0.8c0.7,0,1.2-0.5,1.6-0.8c0.4-0.3,1-0.8,1.6-0.8c0.6,0,1.2,0.5,1.6,0.8 c0.1,0.1,0.2,0.2,0.3,0.2l1.4-0.4c0,0,3,0,3-2.9c0-0.1,0-0.2,0-0.3c-1.9,1.3-6.8,1.6-7.4,1.6H0v2.6c0,0,1.2-0.5,1.6-0.8 C2,15.5,2.3,15,3.1,15z"/><path d="M11.1,2.2l-0.2,0.5C10.7,3,10.4,3.2,10,3.2H9.4C9.8,3.7,10.3,4,10.9,4c1,0,1.8-0.8,1.8-1.8V2.1L11.1,2.2 C11.1,2.1,11.1,2.1,11.1,2.2z"/><path d="M10,2.8c0.2,0,0.4-0.1,0.4-0.3L10.7,2c0.1-0.2,0.3-0.3,0.5-0.3H13c-0.2-1-1.1-1.7-2.1-1.7C9.7,0,8.7,1,8.7,2.2 c0,0.2,0,0.4,0.1,0.6H10z"/><g><path d="M9.4,10C9,10,8.7,9.7,8.6,9.3c0-0.4,0.3-0.8,0.7-0.8L15,8.2c0.5,0,0.8,0.3,0.8,0.7c0,0.4-0.3,0.8-0.7,0.8L9.4,10 C9.5,10,9.4,10,9.4,10z"/></g><path d="M17.2,10.9c-0.3,0.1-0.8,0.3-1.3,0.4l-0.7,0.1c-2,0.3-4.6,0.3-5.8,0.3c0,0,0,0,0,0L9.8,10l0,0l0.6-1.9c0,0,0,0,0,0L10.7,7 L11,6.1l3.4-0.2c0.4,0,0.8-0.4,0.7-0.8c0-0.4-0.3-0.8-0.8-0.7L8.7,4.6c-0.4,0-2.1,3.3-2.1,3.3l-1.2,3.7H0v1.8h14.5 c1.7-0.1,6.1-0.5,7.3-1.6C20.4,10.3,19.2,10,17.2,10.9z"/><g><path d="M15.9,14.6c-0.2,0-0.4-0.1-0.4-0.3L14,4.9c0-0.2,0.1-0.4,0.3-0.5c0.2,0,0.4,0.1,0.5,0.3l1.6,9.4 C16.4,14.4,16.2,14.6,15.9,14.6C16,14.6,16,14.6,15.9,14.6z"/></g></svg>`;
const CLIMBING_ICON = `
<svg viewBox="0 0 22 22" fill="currentColor"><path d="M2.5,9.4c-0.1,0.2-0.2,0.4-0.2,0.7c0,0.1,0,0.2,0,0.4L2.4,16l-1.9,4.1c-0.1,0.1-0.1,0.3-0.1,0.4c-0.1,0.7,0.4,1.3,1,1.4 c0.5,0.1,1-0.2,1.3-0.6l2.1-4.5c0-0.1,0.1-0.2,0.1-0.3c0-0.1,0-0.1,0-0.2l0-3.4l3.2,1.4l0.5,3.4c0.1,0.5,0.5,0.9,1,1 c0.7,0.1,1.3-0.4,1.4-1c0-0.1,0-0.2,0-0.3l-0.6-4.1c-0.1-0.4-0.3-0.7-0.7-0.9L6.8,11l1.8-3.2l0.9,1.2C9.7,9,9.8,9.1,10,9.2l3.5,1 c0.5,0.1,0.9-0.1,1.1-0.6c0.2-0.5,0-1.1-0.5-1.3c0,0,0,0,0,0l-3-0.9L8.7,4.7C8.3,4.3,7.9,4.1,7.3,4C6.4,3.8,5.5,4.3,5.1,5L2.5,9.4z" /><path d="M12.5,17.4l-0.2,1.7l-6,1.5l0.1,1H21c0.5,0,0.9-0.4,0.9-0.9l0-19.7l-2-0.5l-1.2,5.2l-1.9,0.8l-1.7,4.8l1.6,3.7l-0.5,1.4 L12.5,17.4z"/><ellipse transform="matrix(0.9871 -0.1602 0.1602 0.9871 -0.1902 1.3795)" cx="8.5" cy="1.9" rx="1.9" ry="1.9"/><path d="M4.7,4c0.1-0.3,0.1-0.6-0.2-0.7L3.6,2.8C3.4,2.6,3.1,2.7,2.9,3L0.1,7.8C0,8,0.1,8.4,0.3,8.5L1.2,9C1.5,9.2,1.8,9.1,2,8.8 L4.7,4z"/></svg>`;
const PLAYGROUND_ICON = `
<svg viewBox="0 0 22 22" fill="currentColor"><path d="M4.4,11.7c1.2,0,2.2-1,2.2-2.2c0-1.2-1-2.2-2.2-2.2c-1.2,0-2.2,1-2.2,2.2 C2.2,10.8,3.2,11.7,4.4,11.7z M17,15.4c0.1-0.1,0.2,0,0.3,0l0.4,0.6c0.1,0.1,0,0.2-0.1,0.3l-3,2.1c-0.1,0.1-0.2,0-0.3,0l-0.4-0.6 c-0.1-0.1,0-0.2,0.1-0.3L17,15.4z M13.5,12.7l-1.2-2l-0.6,0.4l1.2,2L13.5,12.7z M10.7,7.9L6,0L5.1,0l4.9,8.4L10.7,7.9z M15.1,12.1 c0.3-0.2,0.6-0.3,0.9-0.3l4.3,0c0.8,0,1.5,0.7,1.5,1.5c0,0.8-0.7,1.5-1.5,1.5l-3.6,0l-4.6,3.2c-1.6,1.1-2.6-0.1-2.6-0.1l-3.6-3.5 c-0.6-0.7-0.5-2,0.3-2.6l5-3.5c0.5-0.4,1.2-0.3,1.7,0.1c0.4,0.5,0.4,1.2-0.1,1.6l-3.2,2.3l2.3,2.2L15.1,12.1z"/></svg>`;
const MOTOR_BIKE_TRAIL_ICON = `
<svg viewBox="0 0 22 22" fill="currentColor"><g><path d="M12.1,16.9c-0.3,0.3-0.7,0.5-1.1,0.5V12l4-1v2L12.1,16.9z"/><path d="M9,5H8V4.1c0,0-0.9,0.2-1.2,0.5l-3,4.6C3.7,9.3,3.7,9.6,3.7,9.8c0,0.5,0.2,0.9,0.6,1.1l4,2.2V17c0,0.5,0.4,1,1,1 c0.5,0,0.8-0.4,0.8-1v-4.7c0,0,0.3-0.8-0.5-1.2L7,9.8L8.8,7l1,1.5C10,8.8,10.2,9,10.5,9H13c1,0,1-1.4,0-1.4h-2l-2-3V5z"/><path d="M19.9,10.7l0.1,0.2c0,0.1-0.1,0.2-0.2,0.2h-0.1c-0.4-0.2-0.7-0.3-1.2-0.3c-0.3,0-0.7,0.1-1.2,0.5l-0.4-0.9 c0.5-0.2,1-0.4,1.5-0.4C19,10,19.4,10.3,19.9,10.7z"/><path d="M3.2,11.4L7,13.7v0.9L2.6,12c-0.3-0.2-0.8-0.3-1.1-0.3c-0.5,0-0.3,0.1-0.7,0.3H0.7c-0.1,0-0.2-0.1-0.2-0.2l0.1-0.2 C1.1,11.2,1,11,1.8,11C2.2,11,2.6,11.1,3.2,11.4L3.2,11.4z"/><path d="M3.5,19.9c1.3,0,2.4-1.1,2.4-2.5s-1.1-2.5-2.4-2.5S1.1,16,1.1,17.4S2.2,19.9,3.5,19.9z M0,17.4c0-2,1.6-3.6,3.5-3.6 S7,15.4,7,17.4S5.4,21,3.5,21S0,19.4,0,17.4z"/><path d="M18.4,19.9c1.4,0,2.5-1.1,2.5-2.5s-1.1-2.5-2.5-2.5s-2.5,1.1-2.5,2.5S17.1,19.9,18.4,19.9z M14.8,17.4c0-2,1.6-3.6,3.6-3.6 s3.6,1.6,3.6,3.6S20.4,21,18.4,21S14.8,19.4,14.8,17.4z"/><path d="M17.6,13L16,9.8C15.8,9.4,15.2,9,14.7,9h-1.1c-0.2,0-0.4,0.3-0.4,0.6s0.2,0.4,0.4,0.4h1.1c0.2,0,0.4,0.1,0.5,0.3l1.6,2.7 H17.6z"/><path d="M12,3h0.9C13,2.8,13,2.7,13,2.5C13,1.1,11.9,0,10.5,0S8,1.1,8,2.5C8,3.1,8.2,3.6,8.5,4H12V3z"/><circle cx="10.5" cy="3.5" r="1.5"/></g></svg>`;
const FISHING_ICON = `
<svg viewBox="0 0 22 22" fill="currentColor"><g><path d="M6.1,13.6L6,13.8L6.1,14l3.9,1c0.2,0.1,0.2,1,0,1H6.1L6,16.1v0.1c4.3,3.4,9.2,4.8,15,4.8V9C11,9,6.1,13.6,6.1,13.6z M13,14 h-1v-1h1V14z"/><path d="M19,1c-3.3,0-5.7,1.5-9.3,4.5c-0.1,0-0.4-0.1-0.4-0.1c-0.6,0-1,0.5-1,1c0,0,0,0.2,0.1,0.3C8.1,6.8,5.3,9.5,5.3,9.5L3,12 c-0.2,0.2-0.7,0-1,0s-0.6,0-0.8-0.3c-0.2-0.2-0.3-0.5-0.3-0.8S1,10.3,1.3,10c0,0,0.2-0.1,0.3-0.2c0,0.2,0.1,0.9,0.1,0.9L4,8 L1.5,8.9C0.9,9.1,0.7,9.4,0.6,9.4c-0.8,0.7-0.9,1.8-0.1,2.9C2,12.9,1.4,12.8,3,13l1-1l1.8-1.8c0,0,2.9-2.8,3-2.8 c0.1,0,0.4,0.1,0.4,0.1c0.6,0,1-0.5,1-1c0,0,0-0.2,0-0.3C13.7,3.3,15.9,2,19,2c0.6,0,3,0,3,0V1H19z"/></g></svg>`;
const SCENIC_VIEWPOINT_ICON = `
<svg viewBox="0 0 22 22" fill="currentColor"><g transform="translate(4.000000, 0.000000)"><path d="M3.2,11c0,1.2-0.9,2.2-2.1,2.2c-1.2,0-2.1-1-2.1-2.2 c0-1.2,0.9-2.2,2.1-2.2C2.2,8.8,3.2,9.8,3.2,11"/><path d="M4.6,10.4v1.3l10.6,0.8v-3L4.6,10.4"/><path d="M2.3,7.5l1.1,0.7L7.7,2L5.3,0.5L2.3,7.5"/><path d="M4.4,9.8l7.9-3.8l-1.4-2.6L3.8,8.6L4.4,9.8z"/><path d="M2.3,14.5l1.1-0.7l4.3,6.2l-2.4,1.5L2.3,14.5"/><path d="M3.8,13.4l0.6-1.2l7.9,3.8l-1.4,2.6L3.8,13.4"/></g></svg>`;
// Exported (unlike the other POI glyphs around it) — also used as the
// Overlays panel's Hiking trails glyph (hiking_trails.js), same "reuse an
// existing NPS-sourced pictogram" story as WILDERNESS_ICON above rather
// than hand-drawing another one.
export const WALKING_ICON = `
<svg viewBox="0 0 22 22" fill="currentColor"><path d="M10.4,3.6c1,0,1.8-0.8,1.7-1.8c0-1-0.8-1.8-1.8-1.7c-1,0-1.8,0.8-1.7,1.8C8.6,2.8,9.5,3.6,10.4,3.6z"/><path d="M16.5,9.5L13.9,8l-2.2-3.4c-0.3-0.4-0.9-0.8-1.5-0.7C9.7,4,9.3,4.2,9,4.4L5.8,7.7C5.7,7.8,5.6,8,5.6,8.1l-0.4,3.6 c0,0,0,0.1,0,0.1c0,0.4,0.4,0.8,0.8,0.8c0.4,0,0.7-0.4,0.8-0.8l0.3-3.1l1.1-1.1l-1,8.6l-1.9,4.1c-0.1,0.1-0.1,0.3-0.1,0.5 c0,0.7,0.6,1.2,1.2,1.2c0.5,0,0.9-0.3,1.1-0.7l2-4.4c0-0.1,0.2-0.4,0.2-0.5l0.2-2.1l2.1,6.9c0.2,0.5,0.6,0.8,1.2,0.8 c0.7,0,1.2-0.6,1.2-1.2c0-0.1,0-0.1,0-0.2L11.5,11l0.4-3.1l0.8,1.3c0.1,0.1,0.1,0.2,0.2,0.2l2.8,1.6c0.1,0,0.2,0.1,0.4,0.1 c0.4,0,0.8-0.4,0.8-0.8C16.9,9.8,16.7,9.6,16.5,9.5z"/></svg>`;
const GUIDED_TOURS_ICON = `
<svg viewBox="0 0 22 22" fill="currentColor"><polygon points="19,7 19,6 14,6 14,7 13,7 13,8 13,13 14,13 14,8 15,8 15,20 16,20 16,14 17,14 17,20 18,20 18,8 19,8 20,8 20,7 "/><circle cx="16.5" cy="3.5" r="1.5"/><polygon points="4,7 4,6 1,6 1,7 0,7 0,8 0,13 1,13 1,20 2,20 2,14 3,14 3,20 4,20 4,13 5,13 5,7 "/><circle cx="2.5" cy="3.5" r="1.5"/><polygon points="10,7 10,6 7,6 7,7 6,7 6,8 6,13 7,13 7,20 8,20 8,14 9,14 9,20 10,20 10,13 11,13 11,7 "/><circle cx="8.5" cy="3.5" r="1.5"/><rect x="21" y="4" width="1" height="4"/><rect x="19" y="7" width="2" height="1"/></svg>`;
const WIND_SURFING_ICON = `
<svg viewBox="0 0 22 22" fill="currentColor"><polygon points="21,20 19,19 18,19 16,20 15,20 13,19 12,19 10,20 9,20 8,20 8,19.5 7,19 6,19 4,20 3,20 1,19 1,21 3,22 4,22 6,21 7,21 9,22 10,22 12,21 13,21 15,22 16,22 18,21 19,21 21,22 22,22 22,20 "/><path d="M10.7,17.5l-2.5-2.4C8.1,15,7.9,15,7.7,15H5l-0.4-1H4v-1h0.2L4,12.4h1.4c0,0,0.3,0,0.4-0.1l2.3-1c0.2-0.1,0.3-0.3,0.3-0.5 c0-0.4-0.3-0.7-0.6-0.7c-0.1,0-0.2,0-0.2,0l-2.1,1h-3c-0.1,0-0.2,0-0.4,0.1V12h-1C1,12.1,1,12.2,1,12.4c0,0.1,0,0.2,0,0.3l1.4,3.2 c0.2,0.5,0.7,0.8,1.2,0.8h3.7l2.2,2.1c0.3,0.3,0.9,0.3,1.2,0C11.1,18.4,11.1,17.8,10.7,17.5z"/><path d="M7,0l7.1,18l7.9-4.9C21.5,5.7,13.4,0.8,7,0z M18,10c-1.5,0-6,0-6,0V9c0,0,4.5,0,6,0c1.8,0,3,2,3,2v1h-1C20,12,18.8,10,18,10 z"/><circle cx="1.5" cy="9.5" r="1.5"/></svg>`;
// These three have no equivalent in the older standalone symbol-library
// repo (see POI_ICONS above) — pulled from npmap5-plugins' bundled,
// actively-maintained symbol-library instead (CC0-licensed), which has a
// much larger vocabulary.
const WIFI_ICON = `
<svg viewBox="0 0 22 22" fill="currentColor"><g><path d="M11,11.9c-1.9,0-3.6,0.8-4.8,2l1.6,1.6c0.8-0.8,1.9-1.3,3.1-1.3c1.2,0,2.3,0.5,3.1,1.3l1.6-1.6 C14.6,12.7,12.9,11.9,11,11.9z"/><path d="M11,7c-3.1,0-5.9,1.3-7.9,3.3l1.6,1.6c1.6-1.6,3.8-2.6,6.2-2.6c2.4,0,4.6,1,6.2,2.6l1.6-1.6C16.9,8.3,14.1,7,11,7z"/><path d="M11,4.5c3.7,0,7,1.5,9.4,3.9L22,6.7c-2.8-2.8-6.7-4.6-11-4.6c-4.3,0-8.2,1.7-11,4.6l1.6,1.6C4,6,7.3,4.5,11,4.5z"/><circle cx="11" cy="18.3" r="1.6"/></g></svg>`;
const CELLULAR_SIGNAL_ICON = `
<svg viewBox="0 0 22 22" fill="currentColor"><path d="M18.8,3.2l-1.4,1.4C19,6.3,20,8.5,20,11s-1,4.7-2.6,6.4l1.4,1.4c2-2,3.2-4.7,3.2-7.8C22,8,20.8,5.2,18.8,3.2 z"/><path d="M2,11c0-2.5,1-4.7,2.6-6.4L3.2,3.2C1.2,5.2,0,8,0,11c0,3,1.2,5.8,3.2,7.8l1.4-1.4C3,15.7,2,13.5,2,11z"/><path d="M6.1,15.9l1.4-1.4C6.6,13.6,6,12.4,6,11c0-1.4,0.6-2.6,1.5-3.5L6.1,6.1C4.8,7.3,4,9.1,4,11 S4.8,14.7,6.1,15.9z"/><path d="M16,11c0,1.4-0.6,2.6-1.5,3.5l1.4,1.4c1.3-1.3,2.1-3,2.1-4.9c0-1.9-0.8-3.7-2.1-4.9l-1.4,1.4 C15.4,8.4,16,9.6,16,11z"/><path d="M12,13.8c1.2-0.4,2-1.5,2-2.8c0-1.7-1.3-3-3-3s-3,1.3-3,3c0,1.3,0.8,2.4,2,2.8L8.9,20H8v2h0.6h1h2.9h1H14v-2 h-0.9L12,13.8z M9.9,20l1.1-6c0,0,0,0,0,0s0,0,0,0l1.1,6H9.9z"/></svg>`;
const WINTER_RECREATION_AREA_ICON = `
<svg viewBox="0 0 22 22" fill="currentColor"><path d="M10.1,21.4v-2.9l-1.6,0.9l-0.8-0.5v-1l2.4-1.4v-1.9l-1.7,1.1v-2l-1.7,1v2.7L5.7,18l-0.8-0.5v-1.8l-2.5,1.4l-1.1-0.5v-1.2 L4,14l-1.7-0.8v-1.1l0.9-0.5L5.6,13l1.7-1l0,0l-1.7-1l1.6-1l-1.7-1l-2.4,1.4L2.3,10V9l1.6-0.9L1.3,6.7V5.5l1-0.5l2.5,1.5V4.6 l0.8-0.5l0.9,0.5l0,2.8l1.7,1l0-2l1.8,1V5.5L7.6,4.1v-1l0.8-0.5l1.6,0.9V0.6L11,0l0.9,0.6v2.9l1.7-0.9l0.8,0.6V4L12,5.5v1.9l1.7-1 v2.1l1.8-1v-3l0.8-0.4l0.9,0.4v1.9L19.8,5l0.9,0.6v1.1l-2.6,1.5l1.6,0.9v1l-0.8,0.5L16.5,9l-1.7,1.1l1.6,1l-1.7,1l1.7,0.9l2.5-1.4 l0.8,0.6v1L18.2,14l2.5,1.5v1.1l-1,0.5l-2.4-1.4v1.8L16.3,18l-0.8-0.5v-2.8l-1.8-1v1.9l-1.7-1v1.9l2.4,1.4V19l-0.8,0.4l-1.6-0.9v2.9 L11,22L10.1,21.4z M9.4,11.1l0.9,1.3h1.6l0.7-1.3l-0.8-1.4h-1.6L9.4,11.1z"/></svg>`;
// park4night's fixed vocabulary of Services/Activities codes (the ones // park4night's fixed vocabulary of Services/Activities codes (the ones
// p4n2gpx exports actually use — not necessarily park4night's entire API), // p4n2gpx exports actually use — not necessarily park4night's entire API),
// each with a human label (always shown) and an icon where the NPS set has // each with a human label (always shown) and an icon where the NPS set has
@@ -362,94 +132,35 @@ const WINTER_RECREATION_AREA_ICON = `
// existed, so nothing p4n2gpx might add later is ever hidden. // existed, so nothing p4n2gpx might add later is ever hidden.
export const PARK4NIGHT_TAGS = { export const PARK4NIGHT_TAGS = {
// Services // Services
animaux: { icon: PETS_ON_LEASH_ICON, label: "Pets allowed" }, animaux: { icon: nps("pets-on-leash"), label: "Pets allowed" },
boulangerie: { label: "Bakery nearby" }, boulangerie: { label: "Bakery nearby" },
caravaneige: { icon: WINTER_RECREATION_AREA_ICON, label: "Winter/snow camping" }, caravaneige: { icon: nps("winter-recreation-area"), label: "Winter/snow camping" },
donnees_mobile: { icon: CELLULAR_SIGNAL_ICON, label: "Mobile data coverage" }, donnees_mobile: { icon: nps("cellular-signal"), label: "Mobile data coverage" },
douche: { icon: SHOWERS_ICON, label: "Showers" }, douche: { icon: nps("showers"), label: "Showers" },
eau_noire: { icon: SANITARY_DISPOSAL_ICON, label: "Black water disposal" }, eau_noire: { icon: nps("sanitary-disposal-station"), label: "Black water disposal" },
eau_usee: { icon: SANITARY_DISPOSAL_ICON, label: "Grey water disposal" }, eau_usee: { icon: nps("sanitary-disposal-station"), label: "Grey water disposal" },
electricite: { icon: ELECTRICAL_HOOKUP_ICON, label: "Electricity" }, electricite: { icon: nps("electrical-hookup"), label: "Electricity" },
gaz: { icon: PROPANE_ICON, label: "Gas/propane refill" }, gaz: { icon: nps("propane"), label: "Gas/propane refill" },
gpl: { icon: PROPANE_ICON, label: "LPG refill" }, gpl: { icon: nps("propane"), label: "LPG refill" },
lavage: { label: "Vehicle wash" }, lavage: { label: "Vehicle wash" },
laverie: { icon: LAUNDRY_ICON, label: "Laundry" }, laverie: { icon: nps("laundry"), label: "Laundry" },
piscine: { icon: SWIMMING_ICON, label: "Swimming pool" }, piscine: { icon: nps("swimming"), label: "Swimming pool" },
point_eau: { icon: DRINKING_WATER_ICON, label: "Drinking water" }, point_eau: { icon: nps("drinking-water"), label: "Drinking water" },
poubelle: { icon: TRASH_DUMPSTER_ICON, label: "Trash disposal" }, poubelle: { icon: nps("trash-dumpster"), label: "Trash disposal" },
wc_public: { icon: RESTROOMS_ICON, label: "Public toilet" }, wc_public: { icon: nps("restrooms"), label: "Public toilet" },
wifi: { icon: WIFI_ICON, label: "Wi-Fi" }, wifi: { icon: nps("wifi"), label: "Wi-Fi" },
// Activities // Activities
baignade: { icon: SWIMMING_ICON, label: "Swimming" }, baignade: { icon: nps("swimming"), label: "Swimming" },
eaux_vives: { icon: RIVER_RAFTING_ICON, label: "Whitewater sports" }, eaux_vives: { icon: nps("river-rafting"), label: "Whitewater sports" },
escalade: { icon: CLIMBING_ICON, label: "Climbing" }, escalade: { icon: nps("climbing"), label: "Climbing" },
jeux_enfants: { icon: PLAYGROUND_ICON, label: "Playground" }, jeux_enfants: { icon: nps("playground"), label: "Playground" },
moto: { icon: MOTOR_BIKE_TRAIL_ICON, label: "Motorcycling" }, moto: { icon: nps("motorbike-trail"), label: "Motorcycling" },
peche: { icon: FISHING_ICON, label: "Fishing" }, peche: { icon: nps("fishing"), label: "Fishing" },
peche_pied: { icon: FISHING_ICON, label: "Shore fishing" }, peche_pied: { icon: nps("fishing"), label: "Shore fishing" },
point_de_vue: { icon: SCENIC_VIEWPOINT_ICON, label: "Scenic viewpoint" }, point_de_vue: { icon: nps("scenic-viewpoint"), label: "Scenic viewpoint" },
rando: { icon: WALKING_ICON, label: "Hiking" }, rando: { icon: WALKING_ICON, label: "Hiking" },
visites: { icon: GUIDED_TOURS_ICON, label: "Sightseeing" }, visites: { icon: nps("guided-tours"), label: "Sightseeing" },
vtt: { icon: BICYCLE_TRAIL_ICON, label: "Mountain biking" }, vtt: { icon: nps("bicycle-trail"), label: "Mountain biking" },
windsurf: { icon: WIND_SURFING_ICON, label: "Windsurfing" }, windsurf: { icon: nps("wind-surfing"), label: "Windsurfing" },
}; };
// Extends POI_ICONS (and so POI_ICON_KEYS, and what a marker badge can
// show — see gpx.js's _registerCategoryGlyphs) with a handful of the same
// symbols PARK4NIGHT_TAGS above already vendors, reused rather than
// duplicated — this app's own hand-drawn notes (notes.js's icon picker)
// need marker-badge glyphs for "water source"/"dump station"/"viewpoint"
// far more than the original OSM-POI-upload set (parking/hotel/fuel) ever
// covered. Object.assign, not more entries in the POI_ICONS literal
// itself, since these constants are declared below it in this file.
Object.assign(POI_ICONS, {
amenity_drinking_water: DRINKING_WATER_ICON,
amenity_sanitary_dump_station: SANITARY_DISPOSAL_ICON,
amenity_toilets: RESTROOMS_ICON,
shop_gas: PROPANE_ICON,
amenity_electricity: ELECTRICAL_HOOKUP_ICON,
shop_laundry: LAUNDRY_ICON,
leisure_playground: PLAYGROUND_ICON,
tourism_viewpoint: SCENIC_VIEWPOINT_ICON,
leisure_swimming: SWIMMING_ICON,
leisure_fishing: FISHING_ICON,
sport_climbing: CLIMBING_ICON,
route_hiking: WALKING_ICON,
shop_supermarket: STORE_ICON,
shop_convenience: STORE_ICON,
});
// Hand-drawn, not NPS-sourced — no "download offline map data" pictogram
// in that set either. A tray with a downward arrow into it, same solid
// 22x22 currentColor convention as CONTOUR_ICON/TERRAIN_SHADOW_ICON above
// — used for the "Offline data" sidebar icon (offline_data.js).
export const OFFLINE_DATA_ICON = `
<svg viewBox="0 0 22 22" fill="currentColor">
<path d="M10,0h2v10.5l3-3l1.4,1.4L11,14.3L5.6,8.9L7,7.5l3,3V0z"/>
<path d="M2,15h18v2H2z M2,18h18v2H2z"/>
</svg>`;
// src/bookstore-22.svg (NPS symbol library, same source/license as
// POI_ICONS above) — used as the fixed marker glyph for the "Wikipedia"
// map layer (gpx.js), not part of POI_ICONS itself: that set is keyed by
// OSM/p4n2gpx category and doubles as the note icon-picker's option list
// (notes.js), neither of which applies here — every point on this layer
// gets the same one glyph, there's no per-feature category to key it by.
export const WIKI_ICON = `
<svg viewBox="0 0 22 22" fill="currentColor">
<path d="M16.6,20.7c-0.6,0-0.9-0.4-0.9-0.9c0-0.5,0.3-0.9,0.9-0.9c0.3,0,0.5-0.2,0.5-0.5
S16.9,18,16.6,18c-1.1,0-1.9,0.8-1.9,1.9c0,1,0.7,1.9,1.9,1.9c0.3,0,0.5-0.2,0.5-0.5S16.9,20.7,16.6,20.7L16.6,20.7z"/>
<path d="M5,18c0,0,0,0,0,0c0,3.1,0.5,4,2.7,4l8.9,0c0.3,0,0.5-0.2,0.5-0.5
c0-0.3-0.2-0.5-0.5-0.5H8c-1.5,0-2-0.5-2-3c0,0,0,0,0-0.1c0-0.3-0.2-0.5-0.5-0.5S5,17.7,5,18L5,18z"/>
<path d="M5,8c0-0.6,5-5,5-5h5h1c0.6,0,1,0.4,1,1v14c0,0.6-0.4,1-1,1H6c-0.6,0-1-0.4-1-1
V8z M9,4L6,18c0,0,10,0,10,0c0,0,0-14,0-14C16,4,9,4,9,4z"/>
<path d="M5,6.8c0-0.5,0.4-1.3,0.8-1.6l6.4-4.7C12.7,0.2,13,0.4,13,1v10
c0,0.6-0.3,1.7-0.7,2.1l-6.5,5.3C5.4,18.8,5,18.6,5,18V6.8z"/>
</svg>`;
export const LIVETRACK_ICON = `
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round">
<path d="M12 21s7-7.58 7-12a7 7 0 0 0-14 0c0 4.42 7 12 7 12z"/>
<path d="M8.5 9a3.5 3.5 0 0 1 7 0" stroke-dasharray="1.5 2.2"/>
</svg>`;
+566
View File
@@ -0,0 +1,566 @@
import { Popup } from "/vendor/maplibre-gl/maplibre-gl.mjs";
import { NPS_SYMBOLS, POI_ICONS, MAP_MARKER_ICON } from "/js/icons.js";
import { svgToImageData, badgeImageId, escapeHtml } from "/js/gpx.js";
import { isLoggedIn } from "/js/auth.js";
import { PointStyleFields } from "/js/notes.js";
// Live data off the home MQTT broker (app.rb's /api/live, LiveStore): two
// Overlays items, "Tracker" (the GNSS tracker: position, trail, an optional
// floating info card) and "ITS-G5" (stations its receiver hears). One
// shared poller feeds both, running only while either is on.
const POLL_INTERVAL_MS = 2000;
const ICON_IMAGE_SIZE = 48;
const TRAIL_CHOICES = [0, 1, 2, 4, 8, 24];
const DENM_COLOR = "#e63946";
// ITS stations by ETSI station type (mcu-its-g5's decode.h names).
const STATION_COLORS = {
passengerCar: "#5a55e0",
bus: "#e0a32e",
lightTruck: "#9058d6",
heavyTruck: "#9058d6",
trailer: "#9058d6",
specialVehicle: "#e0a32e",
tram: "#e0a32e",
motorcycle: "#2aa7a0",
moped: "#2aa7a0",
cyclist: "#7cc957",
pedestrian: "#7cc957",
roadSideUnit: "#546619",
};
function ago(seconds) {
if (seconds < 60) return `${seconds} s ago`;
if (seconds < 3600) return `${Math.round(seconds / 60)} min ago`;
return `${Math.round(seconds / 3600)} h ago`;
}
function stationLabel(station) {
return String(station || "unknown").replace(/([a-z])([A-Z])/g, "$1 $2").toLowerCase();
}
function stored(key, fallback) {
try {
const value = localStorage.getItem(key);
return value === null ? fallback : JSON.parse(value);
} catch {
return fallback;
}
}
function store(key, value) {
try {
localStorage.setItem(key, JSON.stringify(value));
} catch {
// private window / blocked storage: not remembered
}
}
function removeLayers(map, layers, sources) {
for (const id of layers) if (map.getLayer(id)) map.removeLayer(id);
for (const id of sources) if (map.getSource(id)) map.removeSource(id);
}
function popupTable(title, rows) {
return `<strong>${title}</strong><table class="live-popup">${rows
.filter(Boolean)
.map(([k, v]) => `<tr><th>${k}</th><td>${escapeHtml(String(v))}</td></tr>`)
.join("")}</table>`;
}
// One /api/live poll for every subscriber.
const poller = {
listeners: new Set(),
timer: null,
last: null,
subscribe(fn) {
this.listeners.add(fn);
if (this.last) fn(this.last);
if (this.listeners.size === 1) this.poll();
},
unsubscribe(fn) {
this.listeners.delete(fn);
if (!this.listeners.size) clearTimeout(this.timer);
},
async poll() {
clearTimeout(this.timer);
let data = null;
try {
const response = await fetch("/api/live");
if (response.ok) data = await response.json();
} catch {
// network hiccup: listeners get null and say so
}
this.last = data;
this.listeners.forEach((fn) => fn(data));
if (this.listeners.size) this.timer = setTimeout(() => this.poll(), POLL_INTERVAL_MS);
},
refresh() {
if (this.listeners.size) this.poll();
},
};
// --- Tracker -------------------------------------------------------------
const TRACKER_SOURCE = "live-tracker";
const TRAIL_SOURCE = "live-tracker-trail";
const TRACKER_LAYERS = ["live-tracker-trail", "live-tracker-badge", "live-tracker-icon", "live-tracker-vehicle", "live-tracker-label"];
// Below this speed the GNSS course is noise: the vehicle keeps its last one.
const MOVING_KMH = 3;
const NAV_PITCH = 60;
const NAV_ZOOM = 16;
// Top-down shapes pointing north, rotated on the map by the course (like
// OpenTrafficMap's vehicles): picked from the tracker's icon.
const VEHICLE_SHAPES = {
car: `<svg viewBox="0 0 24 24"><rect x="6" y="2" width="12" height="20" rx="4" fill="currentColor" stroke="#fff" stroke-width="1.5"/><path d="M8 8.5h8l-1-2.5H9zM8.5 17h7l.5 2h-8z" fill="#fff" opacity=".85"/></svg>`,
moto: `<svg viewBox="0 0 24 24"><rect x="10" y="1.5" width="4" height="5" rx="2" fill="currentColor" stroke="#fff"/><rect x="10" y="17.5" width="4" height="5" rx="2" fill="currentColor" stroke="#fff"/><path d="M6 8h12M9 8l1.5 9h3L15 8" fill="currentColor" stroke="#fff" stroke-width="1.5" stroke-linecap="round"/></svg>`,
bike: `<svg viewBox="0 0 24 24"><path d="M12 2v20M7 7h10" stroke="currentColor" stroke-width="3" stroke-linecap="round"/><path d="M12 2v20M7 7h10" stroke="#fff" stroke-width=".8" stroke-linecap="round"/></svg>`,
};
function vehicleShape(icon) {
if (/moto/.test(icon)) return "moto";
if (/bicycle|cycl|vtt|bike/.test(icon)) return "bike";
return "car";
}
export class TrackerControl {
constructor(map) {
this._map = map;
this._enabled = false;
this._data = null;
this._centered = false;
this._onData = (data) => this._render(data);
map.on("style.load", () => {
if (this._enabled) this._addLayers().then(() => this._render(this._data));
});
}
mount(li) {
li.innerHTML = `
<div class="overlays-panel__row">
<input type="checkbox" class="overlays-panel__toggle">
<span class="overlays-panel__icon live-tracker__icon">${NPS_SYMBOLS.automobiles}</span>
<button type="button" class="overlays-panel__name live-tracker__name" aria-expanded="false">Tracker</button>
</div>
<p class="live-panel__status" hidden></p>
<div class="overlays-panel__details live-tracker__settings" hidden>
<label class="live-tracker__row"><input type="checkbox" class="live-tracker__card-toggle"> Info card on the map</label>
<label class="live-tracker__row">Card opacity <input type="range" class="live-tracker__card-opacity" min="0.2" max="1" step="0.05"></label>
<label class="live-tracker__row">Trail <select class="live-tracker__trail">${TRAIL_CHOICES.map((h) => `<option value="${h}">${h ? `last ${h} h` : "off"}</option>`).join("")}</select></label>
<label class="live-tracker__row"><input type="checkbox" class="live-tracker__logging"> Log positions (keeps the trail across restarts)</label>
<input type="text" class="live-tracker__name-input" maxlength="40" placeholder="Name">
<div class="live-tracker__style"></div>
<button type="button" class="live-tracker__save">Save</button>
</div>
`;
this._toggle = li.querySelector(".overlays-panel__toggle");
this._iconEl = li.querySelector(".live-tracker__icon");
this._nameButton = li.querySelector(".live-tracker__name");
this._status = li.querySelector(".live-panel__status");
this._settingsEl = li.querySelector(".live-tracker__settings");
this._cardToggle = li.querySelector(".live-tracker__card-toggle");
this._cardOpacity = li.querySelector(".live-tracker__card-opacity");
this._trailSelect = li.querySelector(".live-tracker__trail");
this._logging = li.querySelector(".live-tracker__logging");
this._nameInput = li.querySelector(".live-tracker__name-input");
this._style = new PointStyleFields(li.querySelector(".live-tracker__style"));
this._status.addEventListener("click", (event) => {
if (event.target.closest(".live-panel__show")) this._showTracker();
if (event.target.closest(".live-panel__follow")) this._setFollow(true);
});
if (!isLoggedIn()) {
this._toggle.disabled = true;
li.title = "Log in to see the tracker";
return;
}
this._toggle.addEventListener("change", () => (this._toggle.checked ? this._enable() : this._disable()));
this._nameButton.addEventListener("click", () => {
const open = this._settingsEl.hidden;
this._settingsEl.hidden = !open;
this._nameButton.setAttribute("aria-expanded", String(open));
});
// The card is per device (localStorage); the rest is the server's.
this._cardToggle.checked = stored("trackerCard", true);
this._cardOpacity.value = stored("trackerCardOpacity", 0.85);
this._cardToggle.addEventListener("change", () => {
store("trackerCard", this._cardToggle.checked);
this._renderCard();
});
this._cardOpacity.addEventListener("input", () => {
store("trackerCardOpacity", +this._cardOpacity.value);
if (this._card) this._card.style.opacity = this._cardOpacity.value;
});
this._trailSelect.addEventListener("change", () => this._saveSettings({ trail_hours: this._trailSelect.value }));
this._logging.addEventListener("change", () => this._saveSettings({ logging: this._logging.checked }));
li.querySelector(".live-tracker__save").addEventListener("click", () =>
this._saveSettings({ name: this._nameInput.value, icon: this._style.icon, color: this._style.color || "#1a1a1a" }),
);
}
async _saveSettings(changes) {
const body = new URLSearchParams(Object.entries(changes).map(([k, v]) => [k, String(v)]));
try {
const response = await fetch("/api/live/settings", { method: "PUT", body });
if (!response.ok) throw new Error(response.status);
poller.refresh();
} catch {
window.alert("Could not save the tracker settings.");
}
}
async _enable() {
this._enabled = true;
this._centered = false;
this._status.hidden = false;
this._status.textContent = "Connecting…";
await this._addLayers();
poller.subscribe(this._onData);
}
_disable() {
this._setFollow(false);
this._enabled = false;
poller.unsubscribe(this._onData);
this._status.hidden = true;
this._card?.remove();
this._card = null;
removeLayers(this._map, TRACKER_LAYERS, [TRACKER_SOURCE, TRAIL_SOURCE]);
}
// Navigation mode: the map follows the tracker heading-up, tilted, with
// the vehicle in the lower third so more road ahead shows.
_setFollow(on) {
if (!this._follow === !on) return;
this._follow = on;
this._renderCard();
const t = this._data?.tracker;
if (on && t) this._navigate(t);
if (!on) this._map.easeTo({ padding: { top: 0, bottom: 0, left: 0, right: 0 }, duration: 300 });
}
_navigate(t) {
this._map.easeTo({
center: [t.longitude, t.latitude],
bearing: this._course ?? this._map.getBearing(),
pitch: NAV_PITCH,
zoom: Math.max(this._map.getZoom(), NAV_ZOOM),
padding: { top: this._map.getContainer().clientHeight * 0.4, bottom: 0, left: 0, right: 0 },
duration: Math.min(POLL_INTERVAL_MS, 1000),
});
}
_showTracker() {
const t = this._data?.tracker;
if (t) this._map.flyTo({ center: [t.longitude, t.latitude], zoom: Math.max(this._map.getZoom(), 14) });
}
async _addLayers() {
if (this._map.getSource(TRACKER_SOURCE)) return;
const empty = { type: "FeatureCollection", features: [] };
this._map.addSource(TRAIL_SOURCE, { type: "geojson", data: empty });
this._map.addSource(TRACKER_SOURCE, { type: "geojson", data: empty });
this._map.addLayer({
id: "live-tracker-trail",
type: "line",
source: TRAIL_SOURCE,
layout: { "line-cap": "round", "line-join": "round" },
paint: { "line-color": ["get", "color"], "line-width": 3, "line-opacity": 0.75 },
});
// Badge + glyph until a course is known, then the rotated vehicle.
const still = ["!", ["has", "course"]];
this._map.addLayer({
id: "live-tracker-badge",
type: "symbol",
source: TRACKER_SOURCE,
filter: still,
layout: { "icon-image": ["get", "badge"], "icon-size": 0.7, "icon-allow-overlap": true },
});
this._map.addLayer({
id: "live-tracker-icon",
type: "symbol",
source: TRACKER_SOURCE,
filter: still,
layout: { "icon-image": ["get", "glyph"], "icon-size": 0.4, "icon-allow-overlap": true },
});
this._map.addLayer({
id: "live-tracker-vehicle",
type: "symbol",
source: TRACKER_SOURCE,
filter: ["has", "course"],
layout: {
"icon-image": ["get", "vehicle"],
"icon-size": 0.9,
"icon-rotate": ["get", "course"],
"icon-rotation-alignment": "map",
"icon-pitch-alignment": "map",
"icon-allow-overlap": true,
},
});
this._map.addLayer({
id: "live-tracker-label",
type: "symbol",
source: TRACKER_SOURCE,
layout: { "text-field": ["get", "label"], "text-font": ["Noto Sans Regular"], "text-size": 12, "text-offset": [0, 1.6], "text-anchor": "top", "text-allow-overlap": true },
paint: { "text-color": "#1a1a1a", "text-halo-color": "#fff", "text-halo-width": 1.5 },
});
if (!this._interactive) {
this._interactive = true;
for (const layer of ["live-tracker-badge", "live-tracker-vehicle"]) {
this._map.on("click", layer, (event) => this._popup(event.lngLat));
this._map.on("mouseenter", layer, () => (this._map.getCanvas().style.cursor = "pointer"));
this._map.on("mouseleave", layer, () => (this._map.getCanvas().style.cursor = ""));
}
// Panning by hand ends navigation mode (zoom/pinch keeps it).
this._map.on("dragstart", () => this._setFollow(false));
}
}
// The badge in the tracker's color and its icon in white, each image
// registered once per color/icon.
async _ensureImages(color, icon) {
const badge = badgeImageId(color);
if (!this._map.hasImage(badge)) {
const image = await svgToImageData(MAP_MARKER_ICON.replace(/currentColor/g, color), ICON_IMAGE_SIZE);
if (!this._map.hasImage(badge)) this._map.addImage(badge, image);
}
const glyph = `live-glyph-${icon}`;
if (!this._map.hasImage(glyph)) {
const svg = POI_ICONS[icon] || NPS_SYMBOLS.automobiles;
const image = await svgToImageData(svg.replace(/currentColor/g, "#fff"), ICON_IMAGE_SIZE);
if (!this._map.hasImage(glyph)) this._map.addImage(glyph, image);
}
const shape = vehicleShape(icon);
const vehicle = `live-vehicle-${shape}-${color}`;
if (!this._map.hasImage(vehicle)) {
const image = await svgToImageData(VEHICLE_SHAPES[shape].replace(/currentColor/g, color), ICON_IMAGE_SIZE);
if (!this._map.hasImage(vehicle)) this._map.addImage(vehicle, image);
}
return { badge, glyph, vehicle };
}
async _render(data) {
if (!this._enabled) return;
this._data = data;
if (!data) {
this._status.textContent = "Live data unavailable";
return;
}
const settings = data.settings;
this._applySettings(settings);
if (!data.available) {
this._status.textContent = "No MQTT broker configured on the server";
return;
}
const t = data.tracker;
this._status.innerHTML = t
? `${escapeHtml(settings.name)} ${ago(t.age)} · <button type="button" class="live-panel__show">show</button> · <button type="button" class="live-panel__follow">navigate</button>`
: `No ${escapeHtml(settings.name)} position yet`;
if (t?.course != null && (t.speed ?? MOVING_KMH) >= MOVING_KMH) this._course = t.course;
this._renderCard();
if (!t) return;
const { badge, glyph, vehicle } = await this._ensureImages(settings.color, settings.icon);
const properties = { badge, glyph, vehicle, label: `${settings.name} · ${ago(t.age)}` };
if (this._course != null) properties.course = this._course;
this._map.getSource(TRACKER_SOURCE)?.setData({
type: "FeatureCollection",
features: [{ type: "Feature", geometry: { type: "Point", coordinates: [t.longitude, t.latitude] }, properties }],
});
if (this._follow) this._navigate(t);
const trail = [...(t.trail || []), [t.longitude, t.latitude]];
this._map.getSource(TRAIL_SOURCE)?.setData({
type: "FeatureCollection",
features: trail.length > 1 ? [{ type: "Feature", geometry: { type: "LineString", coordinates: trail }, properties: { color: settings.color } }] : [],
});
if (!this._centered) {
this._centered = true;
this._showTracker();
}
}
// Server settings into the controls, unless the user is mid-edit there.
_applySettings(settings) {
const key = JSON.stringify(settings);
if (key === this._settingsKey) return;
this._settingsKey = key;
this._nameButton.textContent = settings.name;
this._iconEl.innerHTML = POI_ICONS[settings.icon] || NPS_SYMBOLS.automobiles;
this._trailSelect.value = String(settings.trail_hours);
this._logging.checked = settings.logging;
if (document.activeElement !== this._nameInput) this._nameInput.value = settings.name;
this._style.set(settings.icon, settings.color);
}
// The floating info card (per-device on/off and opacity).
_renderCard() {
const t = this._data?.tracker;
if (!this._enabled || !this._cardToggle.checked || !t) {
this._card?.remove();
this._card = null;
return;
}
if (!this._card) {
this._card = document.createElement("div");
this._card.className = "live-tracker-card";
this._card.addEventListener("click", (event) => {
if (event.target.closest(".live-tracker-card__nav")) this._setFollow(!this._follow);
else this._showTracker();
});
this._map.getContainer().appendChild(this._card);
}
this._card.style.opacity = this._cardOpacity.value;
const s = this._data.settings;
const battery = t.battery_level != null ? `${Math.round(t.battery_level)} %` : null;
const rows = [
t.speed != null && ["Speed", `${Math.round(t.speed)} km/h`],
battery && ["Battery", `${battery}${t.usb_power ? " ⚡ charging" : ""}`],
!battery && t.usb_power && ["Power", "⚡ USB"],
t.altitude != null && ["Altitude", `${Math.round(t.altitude)} m`],
t.gps_accuracy != null && ["Accuracy", `±${t.gps_accuracy} m`],
["Updated", ago(t.age)],
].filter(Boolean);
this._card.innerHTML = `<div class="live-tracker-card__title"><span class="live-tracker-card__icon" style="background:${escapeHtml(s.color)}">${POI_ICONS[s.icon] || NPS_SYMBOLS.automobiles}</span>${escapeHtml(s.name)}</div>
<table>${rows.map(([k, v]) => `<tr><th>${k}</th><td>${escapeHtml(v)}</td></tr>`).join("")}</table>
<button type="button" class="live-tracker-card__nav${this._follow ? " active" : ""}">${this._follow ? "Stop navigating" : "Navigate"}</button>`;
}
_popup(lngLat) {
const t = this._data?.tracker;
if (!t) return;
const html = popupTable(escapeHtml(this._data.settings.name), [
["Position", `${(+t.latitude).toFixed(5)}, ${(+t.longitude).toFixed(5)}`],
t.speed != null && ["Speed", `${Math.round(t.speed)} km/h`],
t.course != null && ["Course", `${Math.round(t.course)}°`],
t.altitude != null && ["Altitude", `${Math.round(t.altitude)} m`],
t.gps_accuracy != null && ["Accuracy", `±${t.gps_accuracy} m`],
t.battery_level != null && ["Battery", `${Math.round(t.battery_level)} %${t.usb_power ? " ⚡" : ""}`],
["Updated", ago(t.age)],
]);
new Popup({ maxWidth: "260px" }).setLngLat(lngLat).setHTML(html).addTo(this._map);
}
}
// --- ITS-G5 --------------------------------------------------------------
const ITS_SOURCE = "live-its";
const ITS_LAYERS = ["live-its", "live-its-label"];
export class ItsControl {
constructor(map) {
this._map = map;
this._enabled = false;
this._data = null;
this._onData = (data) => this._render(data);
map.on("style.load", () => {
if (this._enabled) {
this._addLayers();
this._render(this._data);
}
});
}
mount(li) {
li.innerHTML = `
<label>
<input type="checkbox" class="overlays-panel__toggle">
<span class="overlays-panel__icon">${NPS_SYMBOLS.radios}</span>
<span>ITS-G5</span>
</label>
<p class="live-panel__status" hidden></p>
`;
this._toggle = li.querySelector(".overlays-panel__toggle");
this._status = li.querySelector(".live-panel__status");
if (!isLoggedIn()) {
this._toggle.disabled = true;
li.title = "Log in to see ITS-G5 stations";
return;
}
this._toggle.addEventListener("change", () => (this._toggle.checked ? this._enable() : this._disable()));
}
_enable() {
this._enabled = true;
this._status.hidden = false;
this._status.textContent = "Connecting…";
this._addLayers();
poller.subscribe(this._onData);
}
_disable() {
this._enabled = false;
poller.unsubscribe(this._onData);
this._status.hidden = true;
removeLayers(this._map, ITS_LAYERS, [ITS_SOURCE]);
}
_addLayers() {
if (this._map.getSource(ITS_SOURCE)) return;
this._map.addSource(ITS_SOURCE, { type: "geojson", data: { type: "FeatureCollection", features: [] } });
this._map.addLayer({
id: "live-its",
type: "circle",
source: ITS_SOURCE,
paint: {
"circle-radius": ["case", ["==", ["get", "msg"], "DENM"], 8, 6],
"circle-color": ["get", "color"],
"circle-stroke-color": "#fff",
"circle-stroke-width": 1.5,
},
});
this._map.addLayer({
id: "live-its-label",
type: "symbol",
source: ITS_SOURCE,
minzoom: 12,
layout: { "text-field": ["get", "label"], "text-font": ["Noto Sans Regular"], "text-size": 11, "text-offset": [0, 1.2], "text-anchor": "top" },
paint: { "text-color": "#333", "text-halo-color": "#fff", "text-halo-width": 1.5 },
});
if (!this._interactive) {
this._interactive = true;
this._map.on("click", "live-its", (event) => this._popup(event.features[0].properties, event.lngLat));
this._map.on("mouseenter", "live-its", () => (this._map.getCanvas().style.cursor = "pointer"));
this._map.on("mouseleave", "live-its", () => (this._map.getCanvas().style.cursor = ""));
}
}
_render(data) {
if (!this._enabled) return;
this._data = data;
if (!data) {
this._status.textContent = "Live data unavailable";
return;
}
if (!data.available) {
this._status.textContent = "No MQTT broker configured on the server";
return;
}
const stations = data.its || [];
this._status.textContent = stations.length ? `${stations.length} station${stations.length === 1 ? "" : "s"} heard` : "No stations heard";
this._map.getSource(ITS_SOURCE)?.setData({
type: "FeatureCollection",
features: stations.map((station) => ({
type: "Feature",
geometry: { type: "Point", coordinates: [station.lon, station.lat] },
properties: {
...station,
color: station.msg === "DENM" ? DENM_COLOR : STATION_COLORS[station.station] || "#888",
label: `${station.msg} · ${stationLabel(station.station)}${station.speed > 1 ? ` · ${Math.round(station.speed)} km/h` : ""}`,
},
})),
});
}
_popup(p, lngLat) {
const html = popupTable(`ITS-G5 ${escapeHtml(p.msg)}`, [
["Station", stationLabel(p.station)],
["Speed", `${Math.round(p.speed)} km/h`],
["Heading", `${Math.round(p.heading)}°`],
["Signal", `${p.rssi} dBm${p.secured === true || p.secured === "true" ? " · signed" : ""}`],
["Heard", ago(p.age)],
]);
new Popup({ maxWidth: "260px" }).setLngLat(lngLat).setHTML(html).addTo(this._map);
}
}
+8 -8
View File
@@ -1,4 +1,5 @@
import { Marker } from "/vendor/maplibre-gl/maplibre-gl.mjs"; import { Marker } from "/vendor/maplibre-gl/maplibre-gl.mjs";
import { followPosition, startFollow } from "/js/gnss.js";
// Replaces MapLibre's own GeolocateControl (browser Geolocation API only) // Replaces MapLibre's own GeolocateControl (browser Geolocation API only)
// with one that prefers this app's own GNSS receiver when it's turned on // with one that prefers this app's own GNSS receiver when it's turned on
@@ -95,7 +96,7 @@ export class LocateControl {
_jumpToGnss({ alertIfNoFix = false } = {}) { _jumpToGnss({ alertIfNoFix = false } = {}) {
const position = this._gnssControl.getPosition(); const position = this._gnssControl.getPosition();
if (position) { if (position) {
this._map.flyTo({ center: position, zoom: Math.max(this._map.getZoom(), 15) }); startFollow(this._map, position);
} else if (alertIfNoFix) { } else if (alertIfNoFix) {
window.alert("Waiting for a GNSS fix…"); window.alert("Waiting for a GNSS fix…");
} }
@@ -105,7 +106,7 @@ export class LocateControl {
this._active = true; this._active = true;
this._button.classList.add("maplibregl-ctrl-geolocate-active"); this._button.classList.add("maplibregl-ctrl-geolocate-active");
this._watchId = navigator.geolocation.watchPosition( this._watchId = navigator.geolocation.watchPosition(
(position) => this._setPosition(position.coords.longitude, position.coords.latitude, position.coords.accuracy), ({ coords }) => this._setPosition(coords.longitude, coords.latitude, coords.accuracy, coords.heading, coords.speed),
() => { () => {
window.alert("Could not determine your location."); window.alert("Could not determine your location.");
this._stop(); this._stop();
@@ -117,10 +118,9 @@ export class LocateControl {
} }
// Recenters on every fix, following the position the way GeolocateControl // 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 // first fix, since that's the one jumping from wherever the map already
// was; easeTo for later updates, a plain pan/zoom-preserving follow // was; a plain follow zooming by the speed (autoZoom) for later updates.
// rather than repeating that same swoop on every update.
// //
// MapLibre's own blue pulsing "user location" dot styling // MapLibre's own blue pulsing "user location" dot styling
// (.maplibregl-user-location-dot, maplibre-gl.css — the exact look // (.maplibregl-user-location-dot, maplibre-gl.css — the exact look
@@ -128,7 +128,7 @@ export class LocateControl {
// .gnss-marker — reusing that green for a browser-estimated position too // .gnss-marker — reusing that green for a browser-estimated position too
// looked like this control was somehow still using GNSS data even when // looked like this control was somehow still using GNSS data even when
// it very much wasn't; distinct colors for distinct sources. // it very much wasn't; distinct colors for distinct sources.
_setPosition(lon, lat, accuracy) { _setPosition(lon, lat, accuracy, heading, speed) {
this._accuracy = accuracy; this._accuracy = accuracy;
if (!this._marker) { if (!this._marker) {
const el = document.createElement("div"); const el = document.createElement("div");
@@ -137,11 +137,11 @@ export class LocateControl {
const circleEl = document.createElement("div"); const circleEl = document.createElement("div");
circleEl.className = "maplibregl-user-location-accuracy-circle"; circleEl.className = "maplibregl-user-location-accuracy-circle";
this._circleMarker = new Marker({ element: circleEl, pitchAlignment: "map" }).setLngLat([lon, lat]).addTo(this._map); 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 { } else {
this._marker.setLngLat([lon, lat]); this._marker.setLngLat([lon, lat]);
this._circleMarker.setLngLat([lon, lat]); this._circleMarker.setLngLat([lon, lat]);
this._map.easeTo({ center: [lon, lat] }); followPosition(this._map, [lon, lat], heading, speed);
} }
this._updateCircleRadius(); this._updateCircleRadius();
} }
+336 -333
View File
@@ -16,161 +16,30 @@ import { PluginsControl } from "/js/plugins.js";
import { LocateControl } from "/js/locate.js"; import { LocateControl } from "/js/locate.js";
import { SearchControl } from "/js/search.js"; import { SearchControl } from "/js/search.js";
import { OfflineDataControl } from "/js/offline_data.js"; import { OfflineDataControl } from "/js/offline_data.js";
import { LAYERS_ICON, WAYPOINT_ICON, SUNRISE_ICON, SUNSET_ICON, PENDING_ICON } from "/js/icons.js"; import { RoutePanelControl } from "/js/route.js";
import { formatCoords, formatSunInfo } from "/js/sun.js"; import { WAYPOINT_ICON, SUNRISE_ICON, SUNSET_ICON, PENDING_ICON, LOCK_ICON, UNLOCK_ICON } from "/js/icons.js";
import { notifySidePanelOpen, onlyOneSidePanelOpen } from "/js/panels.js"; import { formatCoords, formatSunInfo, sunChartHtml } from "/js/sun.js";
import { getPosition } from "/vendor/suncalc/suncalc.js";
import { addRoutePoint, setupSidePanelModes } from "/js/panels.js";
import { isLoggedIn } from "/js/auth.js"; import { isLoggedIn } from "/js/auth.js";
import { DebugControl } from "/js/debug.js";
import { setupUpdate } from "/js/update.js";
import { patchOnlineStyle, patternImage, PATTERN_IDS, NightMap } from "/js/map_themes.js";
import { offerSharedFiles } from "/js/share_import.js";
import HomeButton from "/vendor/npmap-home-button/home-button.esm.js"; import HomeButton from "/vendor/npmap-home-button/home-button.esm.js";
import OverviewMap from "/vendor/npmap-overview/overview.esm.js"; import OverviewMap from "/vendor/npmap-overview/overview.esm.js";
import * as maplibregl from "/vendor/maplibre-gl/maplibre-gl.mjs"; import * as maplibregl from "/vendor/maplibre-gl/maplibre-gl.mjs";
import { setupDriving } from "/js/driving.js";
import { elevationAt } from "/js/dem.js";
const CENTER = [17.1077, 48.1486]; const CENTER = [17.1077, 48.1486];
const ZOOM = 13; const ZOOM = 13;
const ONLINE_STYLE_URL = "https://tiles.openfreemap.org/styles/liberty"; const ONLINE_STYLE_URL = "https://tiles.openfreemap.org/styles/liberty";
// Recolors OpenFreeMap Liberty to a warm, NPS-Park-Tiles-inspired palette —
// cream ground, muted roads/boundaries — mapped onto Liberty's OpenMapTiles
// layer ids. Applied identically regardless of which PMTiles data actually
// backs the "openmaptiles" source (see offlineStyle() below): offline tiles
// are built by Planetiler's own OpenMapTiles profile (docs/development.adoc),
// the same schema Liberty already expects, so one patch serves both —
// no separate offline theme/palette to keep in sync. Only the layers that
// dominate the map's overall color read are touched; labels, halos, rail,
// and minor overlays (cemetery/hospital/school/pitch/track shading,
// building outlines) are left at Liberty's own defaults.
//
// wood/grass are deliberately left unpatched — Liberty's own green (a
// translucent landcover_wood/landcover_grass wash) already reads well over
// the patched cream background.
const ONLINE_STYLE_PATCH = {
background: { "background-color": "#f9f6ef" },
// Liberty washes every built-up area in a translucent gray-tan below
// z12 (landuse_residential, maxzoom 12 — gone by this app's default
// z13) that the offline schema has no equivalent of; protomaps just
// leaves that ground as plain background/earth. Matched to background
// here rather than left alone, so a zoomed-out view doesn't read as
// visibly dingier online than offline.
landuse_residential: { "fill-color": "#f9f6ef" },
landcover_sand: { "fill-color": "#f0e4c4" },
water: { "fill-color": "#a3cedf" },
// fill-outline-color isn't touched by a plain fill-color patch — Liberty
// draws it separately, defaulting to a bright green that reads as a
// distinct border around named conservation areas (e.g. the Malé
// Karpaty CHKO). Matched to the fill itself, and park_outline's own
// dashed line hidden below, so a reserve blends in as ordinary forest —
// offline has no equivalent stroke at all (see park_a/park_b below),
// and the point was never to call reserves out as visibly different,
// on either side.
park: { "fill-color": "#b3e378", "fill-outline-color": "#b3e378" },
park_outline: { "line-opacity": 0 },
// fill-opacity: 0.5 matches the offline theme's own "buildings" layer —
// without it, Liberty's dense individual building footprints (each with
// its own outline) paint fully opaque and read much heavier/grayer than
// offline's softer, half-transparent fill over the same cream ground.
building: { "fill-color": "#ded7cc", "fill-opacity": 0.5 },
boundary_2: { "line-color": "#546619" },
boundary_3: { "line-color": "#546619" },
// Highway (motorway/trunk/primary), major (secondary/tertiary/link),
// minor (residential/service/track), pedestrian — each repeated for its
// tunnel_/bridge_ counterpart so a road doesn't change color when it
// dips into a tunnel or crosses a bridge. Rail is left alone.
//
// line-width below is a flat number, not Liberty's own zoom-interpolated
// expression — picked to match the offline theme's actual rendered width
// at this app's default zoom (13; verified live via queryRenderedFeatures
// on both sides), since without it Liberty's own curve draws surface
// roads roughly twice as thick as offline at street level, reading as a
// much bolder road network online.
// ponytail: tuned for z13 only, not a matching curve across all zooms —
// will drift back apart at very different zoom levels. Upgrade path:
// sample offline's width at a few more zooms and replace with a matching
// ["interpolate", ["linear"], ["zoom"], ...] expression.
road_motorway: { "line-color": "#fdefbe", "line-width": 2.26 },
road_trunk_primary: { "line-color": "#fdefbe", "line-width": 2.26 },
road_secondary_tertiary: { "line-color": "#fef7dd", "line-width": 1.87 },
road_link: { "line-color": "#fef7dd", "line-width": 1 },
road_motorway_link: { "line-color": "#fef7dd", "line-width": 1 },
road_minor: { "line-color": "#fffdf8" },
road_service_track: { "line-color": "#fffdf8" },
road_path_pedestrian: { "line-color": "#e9e2d8" },
road_motorway_casing: { "line-color": "#c9a66b", "line-width": 1.48 },
road_trunk_primary_casing: { "line-color": "#c9a66b", "line-width": 1.48 },
road_secondary_tertiary_casing: { "line-color": "#c9a66b", "line-width": 1 },
road_link_casing: { "line-color": "#c9a66b", "line-width": 1.5 },
road_motorway_link_casing: { "line-color": "#c9a66b", "line-width": 1.5 },
road_minor_casing: { "line-color": "#c9a66b" },
road_service_track_casing: { "line-color": "#c9a66b" },
tunnel_motorway: { "line-color": "#fdefbe" },
tunnel_trunk_primary: { "line-color": "#fdefbe" },
tunnel_secondary_tertiary: { "line-color": "#fef7dd" },
tunnel_link: { "line-color": "#fef7dd" },
tunnel_motorway_link: { "line-color": "#fef7dd" },
tunnel_minor: { "line-color": "#fffdf8" },
tunnel_service_track: { "line-color": "#fffdf8" },
tunnel_path_pedestrian: { "line-color": "#e9e2d8" },
tunnel_motorway_casing: { "line-color": "#c9a66b" },
tunnel_trunk_primary_casing: { "line-color": "#c9a66b" },
tunnel_secondary_tertiary_casing: { "line-color": "#c9a66b" },
tunnel_link_casing: { "line-color": "#c9a66b" },
tunnel_motorway_link_casing: { "line-color": "#c9a66b" },
tunnel_street_casing: { "line-color": "#c9a66b" },
bridge_motorway: { "line-color": "#fdefbe" },
bridge_trunk_primary: { "line-color": "#fdefbe" },
bridge_secondary_tertiary: { "line-color": "#fef7dd" },
bridge_link: { "line-color": "#fef7dd" },
bridge_motorway_link: { "line-color": "#fef7dd" },
bridge_street: { "line-color": "#fffdf8" },
bridge_service_track: { "line-color": "#fffdf8" },
bridge_path_pedestrian: { "line-color": "#e9e2d8" },
bridge_motorway_casing: { "line-color": "#c9a66b" },
bridge_trunk_primary_casing: { "line-color": "#c9a66b" },
bridge_secondary_tertiary_casing: { "line-color": "#c9a66b" },
bridge_link_casing: { "line-color": "#c9a66b" },
bridge_motorway_link_casing: { "line-color": "#c9a66b" },
bridge_street_casing: { "line-color": "#c9a66b" },
bridge_path_pedestrian_casing: { "line-color": "#c9a66b" },
};
function patchOnlineStyle(style) {
for (const layer of style.layers) {
const patch = ONLINE_STYLE_PATCH[layer.id];
if (patch) Object.assign((layer.paint ??= {}), patch);
}
return insertTrackOnlyLayer(style);
}
// Liberty's own "road_service_track" layer paints service roads (paved
// driveways/parking aisles) and actual unpaved tracks the same color —
// fine for a general-purpose map, not for this app's "can the camper get
// there" use case. The underlying OpenMapTiles data does carry `class:
// "track"` separately from `"service"` (see the filter below), so rather
// than recoloring the merged layer (which would mislabel paved driveways
// as unpaved), this clones it into a second layer scoped to `class ==
// "track"` only, dashed and dirt-brown — matching how the offline theme
// already renders protomaps' own separate "other"/"path" road kind.
// Surface-level only (excludes tunnel_/bridge_ variants): an unpaved track
// in a tunnel or on a bridge is rare enough not to be worth a third layer.
function insertTrackOnlyLayer(style) {
const index = style.layers.findIndex((layer) => layer.id === "road_service_track");
if (index === -1) return style;
const base = style.layers[index];
const trackOnly = {
...base,
id: "road_track_only",
filter: ["all", base.filter, ["==", ["get", "class"], "track"]],
paint: { ...base.paint, "line-color": "#c9a66b", "line-dasharray": [2, 2] },
};
style.layers.splice(index + 1, 0, trackOnly);
return style;
}
// Fetched (not just referenced by URL) so its colors can be patched before // Fetched (not just referenced by URL) so its colors can be patched before
// the map ever sees it — MapLibre accepts a style object anywhere it'd // the map ever sees it — MapLibre accepts a style object anywhere it'd
// accept a style URL, so every other use of ONLINE_STYLE (applyStyle's // accept a style URL, so every use of onlineStyle() (applyStyle's
// map.setStyle) needs no change. This runs before the map — and the rest // map.setStyle) needs no change. This runs before the map — and the rest
// of the page's setup — is constructed (see the top-level await below), so // of the page's setup — is constructed (see the top-level await below), so
// it falls back to the plain URL, letting MapLibre fetch and render it // it falls back to the plain URL, letting MapLibre fetch and render it
@@ -178,18 +47,24 @@ function insertTrackOnlyLayer(style) {
// (a 3s timeout): this app is meant to work offline in the field, and // (a 3s timeout): this app is meant to work offline in the field, and
// blocking the entire page on a remote style server would undermine that // blocking the entire page on a remote style server would undermine that
// even though this particular fetch is only for the online map. // even though this particular fetch is only for the online map.
// Kept unpatched; onlineStyle() patches a fresh copy for each setStyle.
async function loadOnlineStyle() { async function loadOnlineStyle() {
try { try {
const response = await fetch(ONLINE_STYLE_URL, { signal: AbortSignal.timeout(3000) }); const response = await fetch(ONLINE_STYLE_URL, { signal: AbortSignal.timeout(3000) });
return patchOnlineStyle(await response.json()); return await response.json();
} catch (err) { } catch (err) {
return ONLINE_STYLE_URL; return ONLINE_STYLE_URL;
} }
} }
const ONLINE_STYLE = await loadOnlineStyle(); const ONLINE_STYLE_TEMPLATE = await loadOnlineStyle();
// A vendored copy of the same Liberty style ONLINE_STYLE fetches live function onlineStyle() {
if (typeof ONLINE_STYLE_TEMPLATE === "string") return ONLINE_STYLE_TEMPLATE;
return patchOnlineStyle(structuredClone(ONLINE_STYLE_TEMPLATE));
}
// A vendored copy of the same Liberty style ONLINE_STYLE_TEMPLATE fetches live
// (public/vendor/liberty-style/liberty.json — a point-in-time snapshot, not // (public/vendor/liberty-style/liberty.json — a point-in-time snapshot, not
// auto-updated) that offlineStyle() below patches+repoints the exact same // auto-updated) that offlineStyle() below patches+repoints the exact same
// way. Offline mode can't depend on ONLINE_STYLE_URL actually being // way. Offline mode can't depend on ONLINE_STYLE_URL actually being
@@ -202,14 +77,14 @@ const protocol = new pmtiles.Protocol();
addProtocol("pmtiles", protocol.tile); addProtocol("pmtiles", protocol.tile);
// Builds the offline style from OFFLINE_STYLE_TEMPLATE — the identical // Builds the offline style from OFFLINE_STYLE_TEMPLATE — the identical
// Liberty JSON + ONLINE_STYLE_PATCH recolor as the online map, just // Liberty JSON + patchOnlineStyle recolor (map_themes.js) as the online map, just
// repointed at a local PMTiles source instead of tiles.openfreemap.org. // repointed at a local PMTiles source instead of tiles.openfreemap.org.
// This works because data/offline.pmtiles is now built by Planetiler's own // This works because data/offline.pmtiles is now built by Planetiler's own
// OpenMapTiles profile (see docs/development.adoc), the same vector schema // OpenMapTiles profile (see docs/development.adoc), the same vector schema
// Liberty expects — before that, offline tiles used a different schema // Liberty expects — before that, offline tiles used a different schema
// (protomaps' own basemaps) needing a completely separate hand-tuned // (protomaps' own basemaps) needing a completely separate hand-tuned
// theme (protomaps-themes-base + OFFLINE_THEME) that could never be made // theme (protomaps-themes-base + OFFLINE_THEME) that could never be made
// to match ONLINE_STYLE_PATCH's look exactly, no matter how much either // to match the online look exactly, no matter how much either
// side got tuned. // side got tuned.
// //
// glyphs/sprite point at vendored local copies (public/vendor/fonts, // glyphs/sprite point at vendored local copies (public/vendor/fonts,
@@ -230,49 +105,18 @@ function offlineStyle() {
return style; return style;
} }
// A sidebar icon that opens a full-height side panel (like the GPX one) // The Online/Offline choice: the first group of the On the map panel
// with the Online/Offline choice — modelled after OsmAnd's "Configure map" // (the Overlays one, overlays.js), no rail item or panel of its own.
// panel, rather than a small dropdown flyout.
class LayerToggleControl { class LayerToggleControl {
constructor(onSelect) { constructor(onSelect) {
this._onSelect = onSelect; this._onSelect = onSelect;
this._panel = document.querySelector(".onthemap-map");
} }
mount(sidebar) { mount() {
this._container = document.createElement("div");
this._container.className = "sidebar-item";
this._container.innerHTML = `<button type="button" class="sidebar-icon" title="Base map" aria-label="Base map">${LAYERS_ICON}</button>`;
this._icon = this._container.querySelector(".sidebar-icon");
this._icon.addEventListener("click", () => this._togglePanel());
this._panel = document.getElementById("basemap-panel");
this._panel
.querySelector(".basemap-panel__close")
.addEventListener("click", () => this._togglePanel(false));
this._panel.querySelectorAll(".basemap-panel__option").forEach((button) => { this._panel.querySelectorAll(".basemap-panel__option").forEach((button) => {
button.addEventListener("click", () => { button.addEventListener("click", () => this._onSelect(button.dataset.style));
this._onSelect(button.dataset.style);
this._togglePanel(false);
});
}); });
onlyOneSidePanelOpen(this._panel, () => this._icon.classList.remove("active"));
sidebar.appendChild(this._container);
}
_togglePanel(force) {
const open = force === undefined ? this._panel.hidden : force;
this._panel.hidden = !open;
this._icon.classList.toggle("active", open);
if (open) notifySidePanelOpen(this._panel);
}
// Public wrapper so a second entry point (MapLayersButton, a map corner
// control) can open/close the same panel without reaching into a
// "private" method by convention only.
toggle() {
this._togglePanel();
} }
setActive(name) { setActive(name) {
@@ -283,85 +127,18 @@ class LayerToggleControl {
// Called once it's known there's no offline map to switch to (see the // Called once it's known there's no offline map to switch to (see the
// /api/offline-tiles check below) — an Online/Offline switch doesn't make // /api/offline-tiles check below) — an Online/Offline switch doesn't make
// sense to show at all when Offline was never going to work. // sense to show at all when Offline was never going to work. The legend
remove() { // link stays.
this._container.remove(); hideSources() {
this._panel.hidden = true; this._panel.querySelector(".basemap-panel__sources").hidden = true;
}
}
// A small map-corner button (grouped with Home/zoom, see below) that's a
// second entry point to the same panel LayerToggleControl already manages
// in the page's own sidebar — matching the National Park Service's own
// map control layout, which keeps zoom/home/base-map together on the map
// rather than split between the map and a separate side rail.
class MapLayersButton {
constructor(layerToggle) {
this._layerToggle = layerToggle;
}
onAdd() {
this._container = document.createElement("div");
this._container.className = "maplibregl-ctrl maplibregl-ctrl-group";
const button = document.createElement("button");
button.type = "button";
button.title = "Base map";
button.setAttribute("aria-label", "Base map");
button.innerHTML = LAYERS_ICON;
button.addEventListener("click", () => this._layerToggle.toggle());
this._container.appendChild(button);
return this._container;
}
onRemove() {
this._container.remove();
}
getDefaultPosition() {
return "top-left";
}
}
// A passive zoom-level readout, sitting in the same stack as the buttons
// around it — the National Park Service's own control layout has one (the
// small numbered square next to their zoom buttons). Not a button: no
// click behavior, just a live display, so it's a plain div rather than a
// <button> (no hover/focus affordance implying it does something).
class ZoomLevelControl {
onAdd(map) {
this._map = map;
this._container = document.createElement("div");
this._container.className = "maplibregl-ctrl maplibregl-ctrl-group zoom-level-ctrl";
this._label = document.createElement("div");
this._label.className = "zoom-level-ctrl__value";
this._container.appendChild(this._label);
this._update = () => {
this._label.textContent = Math.round(map.getZoom());
};
this._update();
map.on("zoom", this._update);
return this._container;
}
onRemove() {
this._map.off("zoom", this._update);
this._container.remove();
}
getDefaultPosition() {
return "top-left";
} }
} }
// Tilts the camera between a flat top-down view and a fixed 3D-perspective // Tilts the camera between a flat top-down view and a fixed 3D-perspective
// pitch — bearing stays untouched (this map never rotates, see the // pitch — bearing stays untouched, so this is purely "look at it from an
// NavigationControl comment below), so this is purely "look at it from an // angle", not a rotate/compass control. Tilted, the ground is raised into
// angle", not a rotate/compass control. Independent of the "Terrain // real 3D relief (OverlaysControl.syncTerrain, overlays.js), with or
// shading" overlay toggle (overlays.js) — that adds a raster-dem hillshade/ // without the "Terrain shading" overlay.
// color-relief layer, this just moves the camera; combining both gives a
// real sense of relief but neither depends on the other.
const PITCH_3D = 60; const PITCH_3D = 60;
class PitchToggleControl { class PitchToggleControl {
@@ -414,9 +191,51 @@ class PitchToggleControl {
} }
} }
// Locks the map north-up (on by default): a two-finger gesture on a
// tablet rotates it far too easily. Unlocked, it rotates like any map and
// NavigationControl's compass turns it back north.
class RotationLockControl {
onAdd(map) {
this._map = map;
this._container = document.createElement("div");
this._container.className = "maplibregl-ctrl maplibregl-ctrl-group rotation-lock-ctrl";
this._button = document.createElement("button");
this._button.type = "button";
this._button.addEventListener("click", () => this._set(!this._locked));
this._container.appendChild(this._button);
let stored = null;
try {
stored = localStorage.getItem("rotationLocked");
} catch {}
this._set(stored !== "false");
return this._container;
}
onRemove() {
this._container.remove();
}
_set(locked) {
this._locked = locked;
const action = locked ? "disableRotation" : "enableRotation";
this._map.touchZoomRotate[action]();
this._map.keyboard[action]();
this._map.dragRotate[locked ? "disable" : "enable"]();
if (locked && this._map.getBearing() !== 0) this._map.easeTo({ bearing: 0, duration: 300 });
this._button.innerHTML = locked ? LOCK_ICON : UNLOCK_ICON;
this._button.title = locked ? "Rotation locked (north up), click to allow rotating" : "Rotation allowed, click to lock north up";
this._button.setAttribute("aria-label", this._button.title);
this._button.classList.toggle("active", locked);
try {
localStorage.setItem("rotationLocked", String(locked));
} catch {}
}
}
const initialStyle = onlineStyle();
const map = new MaplibreMap({ const map = new MaplibreMap({
container: "map", container: "map",
style: ONLINE_STYLE, style: initialStyle,
center: CENTER, center: CENTER,
zoom: ZOOM, zoom: ZOOM,
// MapLibre's built-in Hash control: keeps #map=zoom/lat/lon in the URL in // MapLibre's built-in Hash control: keeps #map=zoom/lat/lon in the URL in
@@ -427,13 +246,7 @@ const map = new MaplibreMap({
hash: "map", hash: "map",
}); });
// A compact top-left stack — Home, zoom, zoom-level readout, measure, // Home's bounds (rather than homePosition/zoom) so Home resets to an overview of
// locate-me, base map — matching the National Park Service's own map
// control layout,
// all grouped together rather than split across corners. Added in this
// order since MapLibre stacks same-position controls in add order.
//
// bounds (rather than homePosition/zoom) so Home resets to an overview of
// the whole country, not back to CENTER/ZOOM's initial Bratislava view — // the whole country, not back to CENTER/ZOOM's initial Bratislava view —
// now that the URL hash can restore any view on load (see the Hash option // now that the URL hash can restore any view on load (see the Hash option
// above), "current view" and "the default view" are no longer the same // above), "current view" and "the default view" are no longer the same
@@ -444,33 +257,76 @@ const SLOVAKIA_BOUNDS = [
[16.83, 47.73], [16.83, 47.73],
[22.57, 49.61], [22.57, 49.61],
]; ];
map.addControl(new SearchControl(), "top-left"); // The Design canvas' Desktop: search in the topbar, the map's own buttons
map.addControl(new HomeButton({ bounds: SLOVAKIA_BOUNDS }), "top-left"); // in one column on the right — zoom and compass, the view (north lock, 3D,
// showCompass: false — this map never rotates, so a bearing-reset button // my position), the tools (measure, note, home); the zoom level, the scale
// (NavigationControl's default third button) would just be dead weight. // and the coordinates in the status bar under the map.
map.addControl(new NavigationControl({ showCompass: false }), "top-left"); const searchControl = new SearchControl();
map.addControl(new ZoomLevelControl(), "top-left"); searchControl.mount(map, document.querySelector(".topbar__search"));
// The compass shows the bearing; a click turns the map back north.
map.addControl(new NavigationControl({ visualizePitch: false }), "top-right");
map.addControl(new RotationLockControl(), "top-right");
const pitchToggle = new PitchToggleControl(); const pitchToggle = new PitchToggleControl();
map.addControl(pitchToggle, "top-left"); map.addControl(pitchToggle, "top-right");
map.addControl(new MeasureControl(), "top-left");
// Writing a note needs a login (POST /api/gpx/notes) — no point adding a
// button that can only ever end in a 401 for a logged-out viewer, same
// "hide the write-only affordance" story as GpxPanelControl's own
// upload/new-folder buttons.
if (isLoggedIn()) map.addControl(new NotesControl(), "top-left");
// Constructed here (rather than down where it's mounted, alongside the // Constructed here (rather than down where it's mounted, alongside the
// other sidebar controls) so LocateControl can hold the same instance — // other sidebar controls) so LocateControl can hold the same instance —
// its constructor only touches `map`, mount() (which needs the sidebar // its constructor only touches `map`, mount() (which needs the sidebar
// element) can still happen later. // element) can still happen later.
const gnssControl = new GnssControl(map); const gnssControl = new GnssControl(map);
// Not MapLibre's own GeolocateControl (browser Geolocation API only) — // Not MapLibre's own GeolocateControl (browser Geolocation API only) —
// this app has its own GNSS receiver (gpsd, possibly a simulated one, see // this app has its own GNSS receiver (the car's, see app.rb's
// bin/gnss_simulator.rb), and "find my location" should prefer that over a // GNSS_LATEST), and "find my location" should prefer that over a
// device's separate, often less accurate location service, but only once // device's separate, often less accurate location service, but only once
// the "GNSS" sidebar icon actually turns it on — not just whenever a // the "GNSS" sidebar icon actually turns it on — not just whenever a
// receiver happens to have a fix. See locate.js. // receiver happens to have a fix. See locate.js.
map.addControl(new LocateControl(gnssControl), "top-left"); map.addControl(new LocateControl(gnssControl), "top-right");
map.addControl(new ScaleControl({ unit: "metric" }), "bottom-left"); map.addControl(new MeasureControl(), "top-right");
// Writing a note needs a login (POST /api/library/notes) — no point adding a
// button that can only ever end in a 401 for a logged-out viewer, same
// "hide the write-only affordance" story as GpxPanelControl's own
// upload/new-folder buttons.
let notesControl = null; // what's here's "Save a point" (below)
if (isLoggedIn()) map.addControl((notesControl = new NotesControl()), "top-right");
map.addControl(new HomeButton({ bounds: SLOVAKIA_BOUNDS }), "top-right");
// ...as the artboard's three cards: zoom; the view (compass, north lock, 3D,
// my position); the tools (measure, note, home). Each control keeps its own
// container (their popovers hang off it), the card only groups them.
{
const corner = map.getContainer().querySelector(".maplibregl-ctrl-top-right");
const [nav, ...rest] = corner.children;
const card = (...controls) => {
const div = document.createElement("div");
div.className = "maplibregl-ctrl map-card";
div.append(...controls);
corner.appendChild(div);
return div;
};
const view = card(...rest.slice(0, 3));
view.prepend(nav.querySelector(".maplibregl-ctrl-compass"));
card(...rest.slice(3));
}
// The status bar: the map's center (click to copy), the point under the
// mouse, the zoom level.
const cursorLabel = document.querySelector(".statusbar__cursor");
let terrainOffline = false; // set once /api/terrain-tiles answers (below)
let elevationTimer = null;
map.on("mousemove", ({ lngLat }) => {
const at = `Cursor ${formatCoords(lngLat.lat, lngLat.lng)}`;
cursorLabel.textContent = at;
// the ground's height there, once the mouse rests a moment
clearTimeout(elevationTimer);
elevationTimer = setTimeout(async () => {
const metres = await elevationAt(lngLat.lng, lngLat.lat, terrainOffline).catch(() => null);
if (metres != null && cursorLabel.textContent === at) cursorLabel.textContent = `${at} · ${Math.round(metres)} m`;
}, 150);
});
map.getCanvasContainer().addEventListener("mouseleave", () => (cursorLabel.textContent = ""));
const zoomLabel = document.querySelector(".statusbar__zoom");
const updateZoom = () => (zoomLabel.textContent = `Zoom ${map.getZoom().toFixed(1)}`);
updateZoom();
map.on("zoom", updateZoom);
map.addControl(new ScaleControl({ unit: "metric" }), "bottom-left"); // over the map, as in the canvas' Desktop
// A small inset map showing where the current view sits in context — NPS's // A small inset map showing where the current view sits in context — NPS's
// own overview plugin (docs/nps-resources.adoc's "overview" entry, still on // own overview plugin (docs/nps-resources.adoc's "overview" entry, still on
@@ -487,7 +343,7 @@ map.once("style.load", () => {
map.addControl(new OverviewMapControl({}), "top-right"); map.addControl(new OverviewMapControl({}), "top-right");
}); });
const coordsLabel = document.querySelector(".topbar__coords"); const coordsLabel = document.querySelector(".statusbar__coords");
const updateCoords = () => { const updateCoords = () => {
const { lng, lat } = map.getCenter(); const { lng, lat } = map.getCenter();
coordsLabel.innerHTML = `<span class="topbar__icon">${WAYPOINT_ICON}</span><span>${formatCoords(lat, lng)}</span>`; coordsLabel.innerHTML = `<span class="topbar__icon">${WAYPOINT_ICON}</span><span>${formatCoords(lat, lng)}</span>`;
@@ -515,12 +371,18 @@ coordsLabel.addEventListener("click", async () => {
// barely moves between two nearby spots, not worth recomputing constantly) // barely moves between two nearby spots, not worth recomputing constantly)
// plus a periodic tick so the "Xh Ym to sunset" countdown keeps counting // plus a periodic tick so the "Xh Ym to sunset" countdown keeps counting
// down even while the map sits still. // down even while the map sits still.
const sunLabel = document.querySelector(".topbar__sun"); const sunLabel = document.querySelector(".statusbar__sun");
const sunChart = document.querySelector(".sun-chart");
const updateSun = () => { const updateSun = () => {
const { lng, lat } = map.getCenter(); const { lng, lat } = map.getCenter();
if (!sunChart.hidden) sunChart.innerHTML = sunChartHtml(lat, lng);
const info = formatSunInfo(lat, lng); const info = formatSunInfo(lat, lng);
sunLabel.hidden = info === null; sunLabel.hidden = info === null;
if (!info) return; if (!info) return;
if (info.polar) {
sunLabel.innerHTML = `<span class="topbar__group"><span class="topbar__icon">${SUNRISE_ICON}</span><span>${info.polar}</span></span>`;
return;
}
const countdownGroup = info.countdown const countdownGroup = info.countdown
? `<span class="topbar__group"><span class="topbar__icon">${PENDING_ICON}</span><span>${info.countdown}</span></span>` ? `<span class="topbar__group"><span class="topbar__icon">${PENDING_ICON}</span><span>${info.countdown}</span></span>`
@@ -530,48 +392,136 @@ const updateSun = () => {
`<span class="topbar__group"><span class="topbar__icon">${SUNSET_ICON}</span><span>${info.sunset}</span></span>` + `<span class="topbar__group"><span class="topbar__icon">${SUNSET_ICON}</span><span>${info.sunset}</span></span>` +
countdownGroup; countdownGroup;
}; };
// Click opens the horizon-style sun & moon chart (sun.js), kept in sync by
// the same moveend/minute tick as the label itself.
sunLabel.addEventListener("click", (event) => {
event.stopPropagation();
sunChart.hidden = !sunChart.hidden;
updateSun();
});
document.addEventListener("click", (event) => {
if (!sunChart.contains(event.target)) sunChart.hidden = true;
});
document.addEventListener("keydown", (event) => {
if (event.key === "Escape") sunChart.hidden = true;
});
updateSun(); updateSun();
map.on("moveend", updateSun); map.on("moveend", updateSun);
setInterval(updateSun, 60000); setInterval(updateSun, 60000);
// Night mode so the screen doesn't glare in the car: "auto" follows the sun
// at the map center, or by hand — the topbar button cycles them,
// remembered per device.
// The UI's palette (style.css, after S-52: Day, Dusk, Night) and the map's
// night style: automatic by the sun, or by hand — Dusk the dark UI over the
// day map, "for optional use by day as well" (docs/design.adoc).
const NIGHT_MODES = {
auto: ["◐", "Night mode: automatic (after sunset)"],
on: ["☾", "Night mode: on"],
dusk: ["◑", "Dusk: the dark UI over the day map"],
off: ["☀", "Night mode: off"],
};
const nightButton = document.querySelector(".topbar__night");
// On the map's Theme row: the same cycle as the topbar's button
const themeButton = document.querySelector(".onthemap-theme");
themeButton.addEventListener("click", () => nightButton.click());
const nightMap = new NightMap(map);
// The base style's texture patterns (grass, scrub, military hatch) and the
// peak triangle are drawn at runtime rather than shipped in a sprite
// sheet, added with every style before its tiles ask for them: since
// MapLibre 6 an image added on styleimagemissing (or from the missing-image
// resolver) misses the tiles that asked for it.
const addPatterns = () => {
for (const id of PATTERN_IDS) {
const pattern = !map.hasImage(id) && patternImage(id);
if (pattern) map.addImage(id, pattern.image, pattern.options);
}
};
map.on("style.load", addPatterns);
if (map.isStyleLoaded()) addPatterns();
// Still the fallback for one asked for before that.
map.on("styleimagemissing", ({ id }) => {
const pattern = !map.hasImage(id) && patternImage(id);
if (pattern) map.addImage(id, pattern.image, pattern.options);
});
nightMap.base(initialStyle);
let nightMode = "auto";
try {
nightMode = localStorage.getItem("nightMode") || "auto";
} catch {}
// The sun is checked where the map looks; zoomed out to a continent or
// the world the center is meaningless (night on the other side of the
// globe), so below zoom 5 the last real place is kept.
let sunAt = map.getCenter();
const updateNight = () => {
if (map.getZoom() >= 5) sunAt = map.getCenter();
const { lng, lat } = sunAt;
const dark = nightMode === "on" || (nightMode === "auto" && getPosition(new Date(), lat, lng).altitude < 0);
document.documentElement.classList.toggle("night", dark);
const palette = dark ? "night" : nightMode === "dusk" ? "dusk" : null;
if (palette) document.documentElement.dataset.palette = palette;
else delete document.documentElement.dataset.palette;
nightMap.set(dark);
[nightButton.textContent, nightButton.title] = NIGHT_MODES[nightMode] || NIGHT_MODES.auto;
themeButton.textContent = `${{ auto: "Auto", on: "Night", dusk: "Dusk", off: "Day" }[nightMode] || "Auto"} ›`;
};
nightButton.addEventListener("click", () => {
const modes = Object.keys(NIGHT_MODES);
nightMode = modes[(modes.indexOf(nightMode) + 1) % modes.length];
try {
localStorage.setItem("nightMode", nightMode);
} catch {}
updateNight();
});
updateNight();
map.on("moveend", updateNight);
setInterval(updateNight, 60000);
const sidebar = document.getElementById("sidebar"); const sidebar = document.getElementById("sidebar");
// Grouped into the TODO's planned 4-module menu (Explorer / Offline hub / // The rail of the Design canvas' Desktop, labelled: On the map (the map,
// Navigation / Camper & HW) ahead of that split actually happening — // overlays), the library and imports; the route; offline data; live
// Camper & HW has no sidebar item yet (leveling/solar/telemetry are all // (GNSS, LiveTrack); Status pinned at the bottom.
// still unbuilt), so it's left out rather than shown empty.
const layerToggle = new LayerToggleControl(applyStyle); const layerToggle = new LayerToggleControl(applyStyle);
const profilePanel = new TrackProfilePanel(map); const profilePanel = new TrackProfilePanel(map);
profilePanel.mount(); profilePanel.mount();
sidebar.insertAdjacentHTML("beforeend", `<div class="sidebar-group-label" title="Explorer"></div>`); layerToggle.mount();
new GpxPanelControl(map, profilePanel).mount(sidebar); layerToggle.setActive("online");
const overlaysControl = new OverlaysControl(map); const overlaysControl = new OverlaysControl(map);
overlaysControl.mount(sidebar); overlaysControl.mount(sidebar);
const gpxPanel = new GpxPanelControl(map, profilePanel);
gpxPanel.mount(sidebar);
offerSharedFiles(gpxPanel);
searchControl.setLayerOpeners({
layers: (path, result) => gpxPanel.showFeature(path, result.bbox.slice(0, 2)),
hiking_trails: (code) => overlaysControl.showHikingTrailsCountry(code),
});
pitchToggle.setOverlaysControl(overlaysControl); pitchToggle.setOverlaysControl(overlaysControl);
// Running a plugin needs a login (POST /api/plugins/:name/run) — same // Running a plugin needs a login (POST /api/plugins/:name/run) — same
// "hide the write-only affordance" story as NotesControl above. // "hide the write-only affordance" story as NotesControl above.
if (isLoggedIn()) new PluginsControl(map).mount(sidebar); if (isLoggedIn()) new PluginsControl(map).mount(sidebar);
sidebar.insertAdjacentHTML("beforeend", `<div class="sidebar-group-label" title="Offline hub"></div>`); sidebar.insertAdjacentHTML("beforeend", `<div class="sidebar-group-label"></div>`);
layerToggle.mount(sidebar); const routePanel = new RoutePanelControl(map, gnssControl, profilePanel);
layerToggle.setActive("online"); routePanel.mount(sidebar);
setupDriving(map, nightButton, routePanel, gpxPanel);
new OfflineDataControl().mount(sidebar); new OfflineDataControl().mount(sidebar);
sidebar.insertAdjacentHTML("beforeend", `<div class="sidebar-group-label" title="Navigation"></div>`); sidebar.insertAdjacentHTML("beforeend", `<div class="sidebar-group-label"></div>`);
gnssControl.mount(sidebar); gnssControl.mount(sidebar);
new LiveTrackPanelControl(map).mount(sidebar); new LiveTrackPanelControl(map).mount(sidebar);
// The sidebar already has a "Base map" icon (opens the same panel) — if (isLoggedIn()) new DebugControl().mount(sidebar);
// this is a second entry point for it, grouped with Home/zoom on the map if (isLoggedIn()) setupUpdate(document.querySelector(".topbar__update"), document.querySelector(".debug-panel__update-check"));
// itself rather than off in the page's own side rail, matching NPS's // A short name under each icon (CSS ::after), the title stays the tooltip.
// layout. layerToggle only needs to exist (not be mounted yet) for this. const RAIL_LABELS = { "Import plugins": "Import", "Offline data": "Offline", LiveTrack: "Live", "Status / debug": "Status" };
const mapLayersButton = new MapLayersButton(layerToggle); sidebar.querySelectorAll(".sidebar-icon").forEach((icon) => (icon.dataset.label = RAIL_LABELS[icon.title] ?? icon.title));
map.addControl(mapLayersButton, "top-left"); setupSidePanelModes();
function applyStyle(name) { function applyStyle(name) {
layerToggle.setActive(name); layerToggle.setActive(name);
map.setStyle(name === "offline" ? offlineStyle() : ONLINE_STYLE); map.setStyle(nightMap.base(name === "offline" ? offlineStyle() : onlineStyle()));
} }
// If a local PMTiles file is present, prefer it as the default style — its // If a local PMTiles file is present, prefer it as the default style — its
@@ -580,69 +530,122 @@ function applyStyle(name) {
// switch to), so it's removed entirely rather than left sitting there // switch to), so it's removed entirely rather than left sitting there
// offering a choice that can't work. // offering a choice that can't work.
const offlineStatus = document.querySelector(".topbar__offline-status"); const offlineStatus = document.querySelector(".topbar__offline-status");
fetch("/api/offline-tiles") const ready = [];
ready.push(fetch("/api/offline-tiles")
.then((response) => response.json()) .then((response) => response.json())
.then(({ available }) => { .then(({ available }) => {
if (available) { if (available) {
applyStyle("offline"); applyStyle("offline");
} else { } else {
layerToggle.remove(); layerToggle.hideSources();
map.removeControl(mapLayersButton);
} }
offlineStatus.hidden = false; offlineStatus.hidden = false;
offlineStatus.classList.toggle("topbar__offline-status--ready", available); offlineStatus.classList.toggle("topbar__offline-status--ready", available);
offlineStatus.title = available ? "Offline map data ready" : "No offline map data on this server"; offlineStatus.title = available ? "Offline map data ready" : "No offline map data on this server";
offlineStatus.textContent = available ? "Offline ready" : "Online only";
}) })
.catch(() => { .catch(() => {
// Backend check failed; keep the online style and leave the switch as // Backend check failed; keep the online style and leave the switch as
// is rather than guessing — this is the same-origin request itself // is rather than guessing — this is the same-origin request itself
// failing, not evidence offline tiles are actually unavailable. // failing, not evidence offline tiles are actually unavailable.
}); }));
fetch("/api/terrain-tiles") ready.push(fetch("/api/terrain-tiles")
.then((response) => response.json()) .then((response) => response.json())
.then(({ available }) => { .then(({ available }) => {
terrainOffline = available;
overlaysControl.setHillshadeOfflineAvailable(available); overlaysControl.setHillshadeOfflineAvailable(available);
overlaysControl.setShadowOfflineAvailable(available); overlaysControl.setShadowOfflineAvailable(available);
}) })
.catch(() => {}); .catch(() => {}));
fetch("/api/hiking-trails") ready.push(fetch("/api/hiking-trails")
.then((response) => response.json()) .then((response) => response.json())
.then(({ countries }) => overlaysControl.setHikingTrailsOfflineCountries(countries)) .then(({ countries, bboxes }) => overlaysControl.setHikingTrailsOfflineCountries(countries, bboxes))
.catch(() => {}); .catch(() => {}));
fetch("/api/kiwix") ready.push(fetch("/api/kiwix")
.then((response) => response.json()) .then((response) => response.json())
.then(({ available }) => overlaysControl.setWikiAvailable(available)) .then(({ available }) => overlaysControl.setWikiAvailable(available))
.catch(() => {}); .catch(() => {}));
// Alt+click anywhere shows every rendered feature at that point — base map // What was on before the reload / update (localStorage, per device): once
// (OSM tags via OpenFreeMap/protomaps), GPX/FIT layers, radar, all of it — // the checks above are in (offline or online terrain, trails, wiki) and the
// with its raw properties, inspired by NPMap4's infoboxControl (a generic // base map they switched to has loaded.
// "show me everything here" debug view, kept separate from the curated Promise.allSettled(ready).then(() => {
// popups those same features already have via their own layer-specific const restore = () => {
// click handlers, e.g. gpx.js's waypoint popups — both can fire on the same overlaysControl.restore();
// click, which is fine, this is a power-user/debugging affordance, not gpxPanel.restore();
// something replacing the normal popups). No dedicated UI for this };
// deliberately — a keyboard-modified click needs no button, state, or if (map.loaded()) restore();
// cursor change of its own. else map.once("idle", restore);
map.on("click", (event) => { });
if (!event.originalEvent.altKey) return;
// Right click, a long press (touch browsers fire contextmenu for it) or
// Alt+click: what's here (the Design canvas' Desktop). The position on top,
// a click copies it; Route here / Add to the trip / Save a point; every
// rendered feature's raw properties folded under it (the debug view it
// was). C copies the position under the mouse with no popup.
const copyPosition = async ({ lng, lat }) => {
try {
await navigator.clipboard.writeText(`${lat.toFixed(6)}, ${lng.toFixed(6)}`);
return true;
} catch {
return false; // clipboard API unavailable (an insecure context)
}
};
const whatsHere = (event) => {
const { lngLat } = event;
const features = map.queryRenderedFeatures(event.point); const features = map.queryRenderedFeatures(event.point);
if (features.length === 0) return; const rows = features
const html = features
.map((feature) => { .map((feature) => {
const rows = Object.entries(feature.properties) const cells = Object.entries(feature.properties)
.map(([key, value]) => `<tr><th>${escapeHtml(key)}</th><td>${escapeHtml(String(value))}</td></tr>`) .map(([key, value]) => `<tr><th>${escapeHtml(key)}</th><td>${escapeHtml(String(value))}</td></tr>`)
.join(""); .join("");
return `<div class="debug-popup__feature"><strong>${escapeHtml(feature.layer.id)}</strong><table>${rows || "<tr><td>(no properties)</td></tr>"}</table></div>`; return `<div class="debug-popup__feature"><strong>${escapeHtml(feature.layer.id)}</strong><table>${cells || "<tr><td>(no properties)</td></tr>"}</table></div>`;
}) })
.join(""); .join("");
const el = document.createElement("div");
new Popup({ maxWidth: "320px", className: "debug-popup" }).setLngLat(event.lngLat).setHTML(html).addTo(map); el.className = "here";
el.innerHTML = `
<button type="button" class="here__position" title="Copy">
<span><b>${lngLat.lat.toFixed(5)}, ${lngLat.lng.toFixed(5)}</b><small>${formatCoords(lngLat.lat, lngLat.lng)}<span class="here__alt"></span></small></span>
<em>Copy</em>
</button>
<div class="here__actions">
<button type="button" data-do="route">Route here</button>
<button type="button" data-do="trip">Add to the trip</button>
${notesControl ? `<button type="button" data-do="note">Save a point</button>` : ""}
</div>
<details class="here__features"><summary>${features.length} feature${features.length === 1 ? "" : "s"} here</summary>${rows}</details>
<div class="here__hint">C copies the position under the cursor</div>`;
const popup = new Popup({ maxWidth: "320px", className: "debug-popup here-popup" }).setLngLat(lngLat).setDOMContent(el).addTo(map);
elevationAt(lngLat.lng, lngLat.lat, terrainOffline)
.then((metres) => metres != null && (el.querySelector(".here__alt").textContent = ` · ${Math.round(metres)} m`))
.catch(() => {});
el.querySelector(".here__position").addEventListener("click", async () => {
if (await copyPosition(lngLat)) el.querySelector(".here__position em").textContent = "Copied ✓";
});
const at = [lngLat.lng, lngLat.lat];
const actions = { route: () => addRoutePoint(at, null), trip: () => routePanel.addStop(at), note: () => notesControl.placeAt(lngLat) };
el.querySelector(".here__actions").addEventListener("click", (e) => {
const action = actions[e.target.dataset?.do];
if (!action) return;
popup.remove();
action();
});
};
map.on("click", (event) => event.originalEvent.altKey && whatsHere(event));
map.on("contextmenu", (event) => {
event.originalEvent.preventDefault();
whatsHere(event);
});
let mouseAt = null;
map.on("mousemove", ({ lngLat }) => (mouseAt = lngLat));
map.getCanvasContainer().addEventListener("mouseleave", () => (mouseAt = null));
document.addEventListener("keydown", async (e) => {
if (e.key !== "c" || !mouseAt || e.ctrlKey || e.altKey || e.metaKey || e.target.closest("input, textarea, select, [contenteditable]")) return;
if (await copyPosition(mouseAt)) cursorLabel.textContent = "Copied ✓";
}); });
// Feature properties can come straight from an uploaded GPX/FIT file (an // Feature properties can come straight from an uploaded GPX/FIT file (an
+542
View File
@@ -0,0 +1,542 @@
// The base map's look: OpenFreeMap Liberty recolored after the National Park
// Service's Park Tiles "Standard" style. Colors sampled from the Park Tiles
// legend swatches (nps.gov/maps/web/img/legend/*-standard.png) and their
// public Imagery style JSON (docs/nps-resources.adoc) — only the colors,
// none of their data or tiles. Line widths stay Liberty's own. Applied
// identically to the online style and the offline one (offline.pmtiles is
// built with Planetiler's OpenMapTiles profile, the schema Liberty expects).
// map.js styles the map with it and /symbols.html draws its legend from the
// same patched style, so the two can't drift apart.
// The driving view (the map tilted to 3D, as following does): route
// numbers and minor roads' / paths' names hidden, the main roads' names
// left — what's needed at a glance. Back as soon as the map is flat.
// A ["pitch"] in the layers' filters (MapLibre ≥ 6.21), so they go already
// while tilting, and come back with every style without a listener.
const DRIVE_HIDDEN_LABELS = /^(highway-shield|road_shield|highway-name-(minor|path))/;
const DRIVE_PITCH = 30;
function declutterWhenDriving(style) {
for (const layer of style.layers) {
if (!DRIVE_HIDDEN_LABELS.test(layer.id)) continue;
const flat = ["<", ["pitch"], DRIVE_PITCH];
layer.filter = layer.filter ? ["all", flat, layer.filter] : flat;
}
return style;
}
export function patchOnlineStyle(style) {
return insertTrackOnlyLayer(protectedAreasAndTextures(roadLabelSpacing(declutterWhenDriving(parkTilesStyle(style)))));
}
// Road names and route numbers repeat every symbol-spacing *pixels*, so
// zoomed in close (z22) a street got its name every few meters. 1.5×
// Liberty's spacing, and past z15 it grows with the zoom: the same
// distance on the ground (~900 m) at every zoom.
const ROAD_LABEL_FIXED_ZOOM = 15;
const ROAD_LABEL_SPACING = 1.5;
function roadLabelSpacing(style) {
for (const layer of style.layers) {
if (layer.type !== "symbol" || layer["source-layer"] !== "transportation_name") continue;
const spacing = (layer.layout?.["symbol-spacing"] ?? 250) * ROAD_LABEL_SPACING; // 250: the style spec's default
layer.layout = { ...layer.layout, "symbol-spacing": ["interpolate", ["exponential", 2], ["zoom"], ROAD_LABEL_FIXED_ZOOM, spacing, 22, spacing * 64] };
}
return style;
}
const PARK_TILES_PATCH = {
background: { "background-color": "#f7eee8" },
natural_earth: { "raster-opacity": 0 },
landuse_residential: { "fill-color": "#f7eee8" },
landcover_wood: { "fill-color": "#dfe0c9", "fill-opacity": 0.6 },
landcover_grass: { "fill-color": "#e9e7d6", "fill-opacity": 0.5 },
landcover_wetland: { "fill-color": "#d5dcc9", "fill-opacity": 0.6 },
landcover_ice: { "fill-color": "#ffffff" },
landcover_sand: { "fill-color": "#f1e7d0" },
water: { "fill-color": "#b5d0de" },
waterway_river: { "line-color": "#b5d0de" },
waterway_other: { "line-color": "#b5d0de" },
// Park Tiles' area fill is this muted sage (#b3e378 is their park *point* color).
park: { "fill-color": "#ced2b7", "fill-opacity": 1, "fill-outline-color": "#ced2b7" },
park_outline: { "line-color": "#8ba35a", "line-width": 1.3, "line-opacity": 1 },
building: { "fill-color": "#e7e4d5", "fill-outline-color": "#b8b1a0" },
boundary_2: { "line-color": "#bdb8b0" },
boundary_3: { "line-color": "#d6d0c8" },
road_motorway: { "line-color": "#f8ecbe" },
road_trunk_primary: { "line-color": "#f8ecbe" },
road_secondary_tertiary: { "line-color": "#f9f9f6" },
road_link: { "line-color": "#f9f9f6" },
road_motorway_link: { "line-color": "#f9f9f6" },
road_minor: { "line-color": "#f5f3e5" },
road_service_track: { "line-color": "#f5f3e5" },
road_motorway_casing: { "line-color": "#8f867a" },
road_trunk_primary_casing: { "line-color": "#8f867a" },
road_secondary_tertiary_casing: { "line-color": "#857f7a" },
road_link_casing: { "line-color": "#857f7a" },
road_motorway_link_casing: { "line-color": "#857f7a" },
road_minor_casing: { "line-color": "#a5a197" },
road_service_track_casing: { "line-color": "#a5a197" },
road_path_pedestrian: { "line-color": "#8e827b", "line-width": 1, "line-dasharray": [2, 1.5] },
water_name_point_label: { "text-color": "#31505f", "text-halo-color": "#ffffff" },
water_name_line_label: { "text-color": "#31505f", "text-halo-color": "#ffffff" },
waterway_line_label: { "text-color": "#31505f", "text-halo-color": "#ffffff" },
"highway-name-major": { "text-color": "#636363", "text-halo-color": "#ffffff" },
"highway-name-minor": { "text-color": "#636363", "text-halo-color": "#ffffff" },
"highway-name-path": { "text-color": "#636363", "text-halo-color": "#ffffff" },
};
// tunnel_*/bridge_* layers reuse their surface road's colors.
function parkTilesPatchFor(id) {
const match = id.match(/^(tunnel|bridge)_(.+)$/);
if (!match) return PARK_TILES_PATCH[id];
const alias = { street: "minor", street_casing: "minor_casing" }[match[2]] ?? match[2];
return PARK_TILES_PATCH[`road_${alias}`];
}
function parkTilesStyle(style) {
for (const layer of style.layers) {
const patch = parkTilesPatchFor(layer.id);
if (patch) Object.assign((layer.paint ??= {}), patch);
}
const take = (id) => {
const index = style.layers.findIndex((layer) => layer.id === id);
return index === -1 ? null : style.layers.splice(index, 1)[0];
};
const park = take("park");
const outline = take("park_outline");
if (!park || !outline) return style;
delete outline.paint["line-dasharray"];
// Park Tiles paints a whole NPS unit one flat sage, so the park fill moves
// above landcover (wood/grass would mottle it), just below water — with a
// light-green tint band inside the boundary line, like theirs.
const band = {
...outline,
id: "park_tintband",
paint: { "line-color": "#b2c294", "line-width": 5, "line-offset": 2.5, "line-opacity": 0.8 },
};
const index = style.layers.findIndex((layer) => layer.id === "waterway_tunnel");
style.layers.splice(index === -1 ? style.layers.length : index, 0, park, band, outline);
return style;
}
// OpenMapTiles' park `class` is the OSM protection_title lowercased when
// there is one ("národný_park", "nationalpark", …), else the boundary/leisure
// tag ("national_park", "nature_reserve", "protected_area"), so national
// parks are told apart by substring.
// ponytail: a handful of languages; add a word when a park shows up gray.
const NATIONAL_PARK = ["any", ...["nation", "národn", "narodn", "nemzeti", "nazional", "nacional"].map((word) => ["in", word, ["coalesce", ["get", "class"], ""]])];
// National parks keep the flat Park Tiles sage; other protected areas
// (nature reserves, landscape areas, Natura 2000, …) get a translucent
// gray-green with a dashed edge, so the map tells "national park rules"
// from "some protection" at a glance; strict reserves and monuments (where
// you mostly can't leave the marked trail) a step darker than landscape
// areas / Natura 2000. Military areas red-hatched. Meadows get a grass
// texture from zoom 13, scrub / dwarf pine its own bushes from 11 (no forest texture: OSM rarely says what kind, and
// trees everywhere were too busy).
// The pattern images are drawn at runtime (patternImage below, on
// map.js adds them with every style), so there's no sprite sheet to extend and
// they work offline alike.
// ponytail: same substring trick as NATIONAL_PARK, a word per language.
const STRICT_RESERVE = ["any", ...["rezerv", "reserv", "wilderness", "wildnis", "pamiatk", "památk", "monument", "denkmal"].map((word) => ["in", word, ["coalesce", ["get", "class"], ""]])];
const protectedFill = (strict, other, nationalPark) => ["case", NATIONAL_PARK, nationalPark, STRICT_RESERVE, strict, other];
const PROTECTED_LINE = "#7d9468";
function protectedAreasAndTextures(style) {
const find = (id) => style.layers.find((layer) => layer.id === id);
const park = find("park");
const outline = find("park_outline");
const band = find("park_tintband");
if (!park || !outline) return style;
const sage = park.paint["fill-color"];
park.paint["fill-color"] = protectedFill("rgba(130, 160, 110, 0.32)", "rgba(140, 165, 120, 0.14)", sage);
park.paint["fill-outline-color"] = ["case", ["!", NATIONAL_PARK], "rgba(0, 0, 0, 0)", sage];
const protectedOutline = {
...outline,
id: "park_outline_protected",
filter: ["all", outline.filter, ["!", NATIONAL_PARK]],
paint: { "line-color": PROTECTED_LINE, "line-width": 1.2, "line-dasharray": [3, 2] },
};
outline.filter = ["all", outline.filter, NATIONAL_PARK];
if (band) band.filter = ["all", band.filter, NATIONAL_PARK];
const textures = [
{ id: "landcover_grass_pattern", source: "landcover", class: "grass", pattern: "grass", minzoom: 13, not: "scrub" },
{ id: "landcover_scrub_pattern", source: "landcover", class: "grass", pattern: "scrub", minzoom: 11, only: "scrub" },
{ id: "landuse_military", source: "landuse", class: "military", pattern: "military", minzoom: 8 },
].map((t) => ({
id: t.id,
type: "fill",
source: park.source,
"source-layer": t.source,
minzoom: t.minzoom,
filter: ["all", ["==", ["get", "class"], t.class],
...(t.not ? [["!=", ["get", "subclass"], t.not]] : []),
...(t.only ? [["==", ["get", "subclass"], t.only]] : [])],
paint: { "fill-pattern": `maptool-pattern-${t.pattern}` },
}));
const military = {
...textures.find((t) => t.id === "landuse_military"),
id: "landuse_military_outline",
type: "line",
paint: { "line-color": "#c0392b", "line-width": 1.2, "line-opacity": 0.7 },
};
// Above the park group (a national park's sage is opaque), below water.
const index = style.layers.indexOf(outline) + 1;
style.layers.splice(index, 0, protectedOutline, ...textures, military);
// Park names while zoomed out (as OsmAnd does); from z11 village, peak
// and other local names take over. Before the place labels, so towns win
// a collision. The OpenMapTiles park layer carries a label point per area.
const label = {
id: "park_label",
type: "symbol",
source: park.source,
"source-layer": "park",
minzoom: 6,
maxzoom: 11,
filter: ["==", ["geometry-type"], "Point"],
layout: {
"text-field": ["coalesce", ["get", "name"], ["get", "name_en"]],
"text-font": ["Noto Sans Italic"],
"text-size": ["interpolate", ["linear"], ["zoom"], 6, 10, 10, 13],
"text-max-width": 8,
"text-letter-spacing": 0.05,
"symbol-sort-key": ["coalesce", ["get", "rank"], 99],
},
paint: { "text-color": "#3f5a2e", "text-halo-color": "#ffffff", "text-halo-width": 1.5 },
};
// Peaks from z7, great for orientation zoomed out (Liberty has none):
// the highest win a collision, names and towns take precedence.
const peaks = {
id: "mountain_peak_label",
type: "symbol",
source: park.source,
"source-layer": "mountain_peak",
minzoom: 7,
filter: ["match", ["get", "class"], ["peak", "volcano"], true, false],
layout: {
"icon-image": "maptool-pattern-peak",
"text-field": ["case", ["has", "ele"],
["format", ["coalesce", ["get", "name"], ""], {}, "\n", {}, ["concat", ["get", "ele"], " m"], { "font-scale": 0.8 }],
["coalesce", ["get", "name"], ""]],
"text-font": ["Noto Sans Regular"],
"text-size": ["interpolate", ["linear"], ["zoom"], 7, 10, 12, 12],
"text-anchor": "top",
"text-offset": [0, 0.5],
"text-max-width": 8,
"text-optional": true,
"text-padding": 6,
"symbol-sort-key": ["-", 0, ["coalesce", ["get", "ele"], 0]],
},
paint: { "icon-color": "#6b4f3a", "text-color": "#6b4f3a", "text-halo-color": "#ffffff", "text-halo-width": 1.5 },
};
// Ski lifts and cable cars (Liberty draws none): a thin line with the
// topo map's cross ticks, the lift's name along it.
const aerialway = ["==", ["get", "class"], "aerialway"];
const lift = { type: "line", source: park.source, "source-layer": "transportation", minzoom: 12, filter: aerialway };
const lifts = [
{ ...lift, id: "aerialway", paint: { "line-color": "#4a4a4a", "line-width": 1.2 } },
{ ...lift, id: "aerialway_ticks", paint: { "line-color": "#4a4a4a", "line-width": 6, "line-dasharray": [0.2, 8] } },
{
id: "aerialway_name", type: "symbol", source: park.source, "source-layer": "transportation_name", minzoom: 13, filter: aerialway,
layout: { "symbol-placement": "line", "text-field": ["get", "name"], "text-font": ["Noto Sans Regular"], "text-size": 11, "text-offset": [0, 0.8] },
paint: { "text-color": "#4a4a4a", "text-halo-color": "#ffffff", "text-halo-width": 1.5 },
},
];
const firstSymbol = style.layers.findIndex((layer) => layer.type === "symbol");
style.layers.splice(firstSymbol === -1 ? style.layers.length : firstSymbol, 0, ...lifts.slice(0, 2));
const placeIndex = style.layers.findIndex((layer) => layer["source-layer"] === "place");
style.layers.splice(placeIndex === -1 ? style.layers.length : placeIndex, 0, lifts[2], peaks, label);
return style;
}
const PATTERNS = {
// Not a pattern: the peak triangle, drawn by the same on-demand path as
// an SDF so night mode recolors it with icon-color.
peak: { day: "#000000", sdf: true },
grass: { day: "rgba(130, 140, 95, 0.45)", night: "rgba(120, 140, 105, 0.3)" },
// Scrub, incl. dwarf pine (kosodrevina) above the tree line: its own
// tint (bg) plus bushes, so it reads apart from both meadow and forest.
scrub: { day: "rgba(95, 125, 80, 0.55)", night: "rgba(110, 140, 100, 0.4)", bg: "rgba(150, 170, 120, 0.3)", bgNight: "rgba(60, 80, 55, 0.35)" },
military: { day: "rgba(192, 57, 43, 0.4)", night: "rgba(192, 57, 43, 0.35)" },
};
export const PATTERN_IDS = Object.keys(PATTERNS).flatMap((name) => [`maptool-pattern-${name}`, `maptool-pattern-${name}-night`]);
// "maptool-pattern-<name>[-night]" → { width, height, data } for
// map.addImage, drawn on a canvas at 2× (pixelRatio 2); null for other ids.
export function patternImage(id) {
const match = id.match(/^maptool-pattern-(\w+?)(-night)?$/);
const colors = match && PATTERNS[match[1]];
if (!colors) return null;
const size = match[1] === "peak" ? 20 : 48;
const ctx = document.createElement("canvas").getContext("2d", { willReadFrequently: true });
ctx.canvas.width = ctx.canvas.height = size;
ctx.strokeStyle = ctx.fillStyle = match[2] ? colors.night : colors.day;
ctx.lineWidth = 2;
ctx.lineCap = "round";
if (colors.bg) {
ctx.fillStyle = match[2] ? colors.bgNight : colors.bg;
ctx.fillRect(0, 0, size, size);
ctx.fillStyle = match[2] ? colors.night : colors.day;
}
if (match[1] === "peak") {
ctx.beginPath();
ctx.moveTo(10, 3);
ctx.lineTo(18, 17);
ctx.lineTo(2, 17);
ctx.fill();
} else if (match[1] === "scrub") {
// Low bushes: three overlapping dots each, staggered.
for (const [x, y] of [[12, 16], [36, 40], [34, 14], [10, 38]]) {
for (const dx of [-3, 0, 3]) {
ctx.beginPath();
ctx.arc(x + dx, y - (dx ? 0 : 2), 3, 0, 2 * Math.PI);
ctx.fill();
}
}
} else if (match[1] === "grass") {
for (const [x, y] of [[10, 16], [34, 40], [30, 12]]) {
ctx.beginPath();
for (const dx of [-4, 0, 4]) {
ctx.moveTo(x + dx * 0.4, y);
ctx.lineTo(x + dx, y - 6);
}
ctx.stroke();
}
} else {
// Diagonal hatch, seamless across tile edges.
ctx.lineWidth = 3;
ctx.beginPath();
for (const offset of [-size, 0, size]) {
ctx.moveTo(offset, size);
ctx.lineTo(offset + size, 0);
}
ctx.stroke();
}
return { image: ctx.getImageData(0, 0, size, size), options: { pixelRatio: 2, sdf: !!colors.sdf } };
}
// Liberty's own "road_service_track" layer paints service roads (paved
// driveways/parking aisles) and actual unpaved tracks the same color —
// fine for a general-purpose map, not for this app's "can the camper get
// there" use case. The underlying OpenMapTiles data does carry `class:
// "track"` separately from `"service"` (see the filter below), so rather
// than recoloring the merged layer (which would mislabel paved driveways
// as unpaved), this clones it into a second layer scoped to `class ==
// "track"` only, dashed and dirt-brown.
// Surface-level only (excludes tunnel_/bridge_ variants): an unpaved track
// in a tunnel or on a bridge is rare enough not to be worth a third layer.
function insertTrackOnlyLayer(style) {
const index = style.layers.findIndex((layer) => layer.id === "road_service_track");
if (index === -1) return style;
const base = style.layers[index];
const trackOnly = {
...base,
id: "road_track_only",
filter: ["all", base.filter, ["==", ["get", "class"], "track"]],
paint: { ...base.paint, "line-color": "#c9a66b", "line-dasharray": [2, 2] },
};
style.layers.splice(index + 1, 0, trackOnly);
return style;
}
// --- Night palette ----------------------------------------------------------
// What car navigations do instead of inverting: a dark blue-gray ground (not
// black), low contrast, roads a step lighter than the ground, motorways a
// muted ochre, light-gray labels on dark halos; rasters dimmed, not inverted.
// Switched live with setPaintProperty (no setStyle), so overlays stay put.
// The main layers have hand-picked colors; every other base-style color goes
// through nightColor(), and overlays only get their rasters dimmed and their
// labels' halos darkened — their own colors are the point of them.
const NIGHT_GROUND = "#1d2329";
const NIGHT_LABEL = { "text-color": "#a8b0b8", "text-halo-color": NIGHT_GROUND };
const NIGHT_WATER_LABEL = { "text-color": "#6f8fa3", "text-halo-color": NIGHT_GROUND };
const NIGHT_CASING = { "line-color": "#121619" };
const NIGHT_PATCH = {
background: { "background-color": NIGHT_GROUND },
landuse_residential: { "fill-color": "#20262c" },
landcover_wood: { "fill-color": "#1f2a24" },
landcover_grass: { "fill-color": "#222a25" },
landcover_wetland: { "fill-color": "#1f2a2a" },
landcover_ice: { "fill-color": "#2a3036" },
landcover_sand: { "fill-color": "#2a2823" },
water: { "fill-color": "#12202b" },
waterway_river: { "line-color": "#1a3040" },
waterway_other: { "line-color": "#1a3040" },
park: {
"fill-color": protectedFill("rgba(120, 150, 110, 0.2)", "rgba(120, 150, 110, 0.09)", "#1f2b22"),
"fill-outline-color": ["case", ["!", NATIONAL_PARK], "rgba(0, 0, 0, 0)", "#1f2b22"],
},
park_outline: { "line-color": "#4f6b3a" },
park_outline_protected: { "line-color": "#46593a" },
landcover_grass_pattern: { "fill-pattern": "maptool-pattern-grass-night" },
landcover_scrub_pattern: { "fill-pattern": "maptool-pattern-scrub-night" },
landuse_military: { "fill-pattern": "maptool-pattern-military-night" },
landuse_military_outline: { "line-color": "#8a3a30" },
park_tintband: { "line-color": "#2b3a26" },
park_label: { "text-color": "#8fae7a", "text-halo-color": NIGHT_GROUND },
aerialway: { "line-color": "#8a8f96" },
aerialway_ticks: { "line-color": "#8a8f96" },
aerialway_name: NIGHT_LABEL,
mountain_peak_label: { "icon-color": "#b8a48c", "text-color": "#b8a48c", "text-halo-color": NIGHT_GROUND },
building: { "fill-color": "#262c32", "fill-outline-color": "#30373e" },
boundary_2: { "line-color": "#4a4f55" },
boundary_3: { "line-color": "#3a3f45" },
road_motorway: { "line-color": "#6b5a35" },
road_trunk_primary: { "line-color": "#6b5a35" },
road_secondary_tertiary: { "line-color": "#4a5058" },
road_link: { "line-color": "#4a5058" },
road_motorway_link: { "line-color": "#4a5058" },
road_minor: { "line-color": "#3a4047" },
road_service_track: { "line-color": "#343a40" },
road_track_only: { "line-color": "#7a6440" },
road_path_pedestrian: { "line-color": "#5a5650" },
road_motorway_casing: NIGHT_CASING,
road_trunk_primary_casing: NIGHT_CASING,
road_secondary_tertiary_casing: NIGHT_CASING,
road_link_casing: NIGHT_CASING,
road_motorway_link_casing: NIGHT_CASING,
road_minor_casing: NIGHT_CASING,
road_service_track_casing: NIGHT_CASING,
water_name_point_label: NIGHT_WATER_LABEL,
water_name_line_label: NIGHT_WATER_LABEL,
waterway_line_label: NIGHT_WATER_LABEL,
"highway-name-major": NIGHT_LABEL,
"highway-name-minor": NIGHT_LABEL,
"highway-name-path": NIGHT_LABEL,
};
// tunnel_*/bridge_* layers reuse their surface road's colors.
function nightPatchFor(id) {
const match = id.match(/^(tunnel|bridge)_(.+)$/);
if (!match) return NIGHT_PATCH[id];
const alias = { street: "minor", street_casing: "minor_casing" }[match[2]] ?? match[2];
return NIGHT_PATCH[`road_${alias}`];
}
// The color paint properties per layer type, and how each darkens.
const COLOR_PROPS = {
background: { "background-color": "area" },
fill: { "fill-color": "area", "fill-outline-color": "area" },
line: { "line-color": "area" },
"fill-extrusion": { "fill-extrusion-color": "area" },
circle: { "circle-color": "area", "circle-stroke-color": "area" },
symbol: { "text-color": "text", "text-halo-color": "halo" },
"color-relief": { "color-relief-color": "area" },
};
let probe = null;
// Any CSS color → [r, g, b, a] (the browser parses it), null if not a color.
function parseColor(value) {
probe ??= document.createElement("canvas").getContext("2d");
probe.fillStyle = "#010203";
probe.fillStyle = value;
const out = probe.fillStyle;
if (out === "#010203" && value.toLowerCase() !== "#010203") return null;
const hex = out.match(/^#(..)(..)(..)$/);
if (hex) return [...hex.slice(1).map((h) => parseInt(h, 16)), 1];
const [r, g, b, a = 1] = out.match(/\(([^)]+)\)/)[1].split(",").map(Number);
return [r, g, b, a];
}
function toHsl([r, g, b]) {
[r, g, b] = [r / 255, g / 255, b / 255];
const max = Math.max(r, g, b);
const min = Math.min(r, g, b);
const l = (max + min) / 2;
if (max === min) return [0, 0, l];
const d = max - min;
const s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
const h = max === r ? (g - b) / d + (g < b ? 6 : 0) : max === g ? (b - r) / d + 2 : (r - g) / d + 4;
return [h * 60, s, l];
}
// The fallback for layers NIGHT_PATCH doesn't list: lightness flipped and
// squeezed into the dark end, colors desaturated; dark text goes light,
// halos become the ground. (Roads need the hand-picked colors: flipping
// would draw white roads darker than a cream ground.)
export function nightColor(value, role) {
const rgba = typeof value === "string" && parseColor(value);
if (!rgba) return value;
const alpha = rgba[3];
if (role === "halo") return `rgba(29, 35, 41, ${alpha})`;
const [h, s, l] = toHsl(rgba);
const night = role === "text" ? [s * 0.5, 0.55 + (1 - l) * 0.25] : [s * 0.55, 0.08 + (1 - l) * 0.3];
return `hsla(${h.toFixed(1)}, ${(night[0] * 100).toFixed(1)}%, ${(night[1] * 100).toFixed(1)}%, ${alpha})`;
}
// Colors inside expressions too (interpolate stops, match outputs) and in
// legacy {stops: [[zoom, color], …]} functions, which Liberty still uses.
function nightValue(value, role) {
if (Array.isArray(value)) return value.map((v) => nightValue(v, role));
if (value?.stops) return { ...value, stops: value.stops.map(([zoom, v]) => [zoom, nightValue(v, role)]) };
return nightColor(value, role);
}
export class NightMap {
constructor(map) {
this._map = map;
this._on = false;
this._base = new Set();
this._day = new Map(); // layer id -> its day values of what night changed
map.on("styledata", () => this._on && this._apply());
}
// The base style's layers (passed through on its way to setStyle).
base(style) {
this._base = new Set(style.layers.map((layer) => layer.id));
this._day.clear();
return style;
}
set(on) {
if (on === this._on) return;
this._on = on;
if (on) this._apply();
else this._restore();
}
_apply() {
const ids = this._map.getLayersOrder();
for (const id of this._day.keys()) if (!ids.includes(id)) this._day.delete(id); // removed overlays
for (const id of ids) {
if (this._day.has(id)) continue;
const night = this._nightFor(id);
const day = Object.fromEntries(Object.keys(night).map((prop) => [prop, this._map.getPaintProperty(id, prop)]));
try {
for (const [prop, value] of Object.entries(night)) this._map.setPaintProperty(id, prop, value);
} catch {
return; // a style still loading: its own styledata comes once it's done
}
this._day.set(id, day);
}
}
_restore() {
for (const [id, props] of this._day) {
if (this._map.getLayer(id)) for (const [prop, value] of Object.entries(props)) this._map.setPaintProperty(id, prop, value);
}
this._day.clear();
}
_nightFor(id) {
const type = this._map.getLayer(id).type;
if (type === "raster") return { "raster-brightness-max": 0.6, "raster-saturation": -0.3 };
if (type === "hillshade") return { "hillshade-highlight-color": "rgba(255, 255, 255, 0.06)" };
const base = this._base.has(id);
if (!base && type !== "symbol" && type !== "color-relief") return {};
const night = { ...(base && nightPatchFor(id)) };
for (const [prop, role] of Object.entries(COLOR_PROPS[type] || {})) {
if (prop in night) continue;
const day = this._map.getPaintProperty(id, prop);
if (day !== undefined) night[prop] = nightValue(day, role);
}
return night;
}
}
+159 -52
View File
@@ -1,5 +1,5 @@
import { Marker } from "/vendor/maplibre-gl/maplibre-gl.mjs"; import { Marker } from "/vendor/maplibre-gl/maplibre-gl.mjs";
import { NOTE_PIN_ICON, POI_ICONS } from "/js/icons.js"; import { NOTE_PIN_ICON, NPS_SYMBOLS, POI_ICONS } from "/js/icons.js";
import { notifyGpxStoreChanged } from "/js/panels.js"; import { notifyGpxStoreChanged } from "/js/panels.js";
// Human labels for the icon picker's title attribute — POI_ICONS' own keys // Human labels for the icon picker's title attribute — POI_ICONS' own keys
@@ -28,7 +28,113 @@ const ICON_LABELS = {
shop_convenience: "Convenience store", shop_convenience: "Convenience store",
}; };
const NEW_LAYER_VALUE = "__new__"; // The picker: the labelled everyday ones first, then every other NPS symbol
// (named after its file, "drinking-water" → "drinking water").
const CURATED = Object.keys(ICON_LABELS);
const PICKER_ICONS = [
...CURATED.map((key) => [key, ICON_LABELS[key]]),
...Object.keys(NPS_SYMBOLS)
.filter((name) => !CURATED.some((key) => POI_ICONS[key] === NPS_SYMBOLS[name]))
.map((name) => [name, name.replace(/-/g, " ")]),
];
// Badge colors a point can take: the track palette plus NPS olive, brown and
// black. "" = no color of its own (the layer's default badge color).
const POINT_COLORS = ["#e63946", "#e0a32e", "#7cc957", "#2aa7a0", "#5a55e0", "#9058d6", "#546619", "#5e4b3c", "#1a1a1a"];
// Icon + color for a point — shared by the new-note form and the Edit form
// in a point's popup (gpx.js), so both offer the same choices.
export class PointStyleFields {
constructor(container, { onIconChange } = {}) {
this._onIconChange = onIconChange;
this.el = document.createElement("div");
this.el.className = "notes-panel__style";
this.el.innerHTML = `
<div class="notes-panel__colors" role="radiogroup" aria-label="Color">
<button type="button" class="notes-panel__color" data-color="" title="Default color" aria-label="Default color"></button>
${POINT_COLORS.map((c) => `<button type="button" class="notes-panel__color" data-color="${c}" style="--swatch:${c}" title="${c}" aria-label="${c}"></button>`).join("")}
</div>
<div class="notes-panel__icon-picker">
<input type="search" class="notes-panel__icon-filter" placeholder="Find an icon (${PICKER_ICONS.length})">
<div class="notes-panel__icons">
<button type="button" class="notes-panel__icon-option" data-icon="" title="No icon">${NOTE_PIN_ICON}</button>
${PICKER_ICONS.map(
([key, label]) =>
`<button type="button" class="notes-panel__icon-option" data-icon="${key}" title="${escapeAttr(label)}">${POI_ICONS[key]}</button>`,
).join("")}
</div>
</div>
`;
container.appendChild(this.el);
this._filter = this.el.querySelector(".notes-panel__icon-filter");
this._filter.addEventListener("input", () => {
const query = this._filter.value.trim().toLowerCase();
this.el.querySelectorAll(".notes-panel__icon-option").forEach((b) => {
b.hidden = query !== "" && !`${b.title} ${b.dataset.icon}`.toLowerCase().includes(query);
});
});
this.el.querySelectorAll(".notes-panel__icon-option").forEach((button) =>
button.addEventListener("click", () => {
this._setIcon(button.dataset.icon);
this._onIconChange?.(this.icon);
}),
);
this.el.querySelectorAll(".notes-panel__color").forEach((button) => button.addEventListener("click", () => this._setColor(button.dataset.color)));
this.set();
}
// Resets the filter too; an unknown color/icon just leaves none selected.
set(icon = "", color = "") {
this._filter.value = "";
this.el.querySelectorAll(".notes-panel__icon-option").forEach((b) => (b.hidden = false));
this._setIcon(icon);
this._setColor(color);
}
// An icon only makes sense on a single point (not a measured line/area).
set iconsVisible(visible) {
this.el.querySelector(".notes-panel__icon-picker").hidden = !visible;
}
_setIcon(icon) {
this.icon = icon;
this.el.querySelectorAll(".notes-panel__icon-option").forEach((b) => b.classList.toggle("active", b.dataset.icon === icon));
}
_setColor(color) {
this.color = color;
this.el.querySelectorAll(".notes-panel__color").forEach((b) => b.classList.toggle("active", b.dataset.color === color));
}
// Writes icon/color into a feature's properties (removing the ones unset).
applyTo(properties) {
for (const [key, value] of [["icon", this.icon], ["color", this.color]]) {
if (value) properties[key] = value;
else delete properties[key];
}
return properties;
}
}
// B / I buttons above a note's textarea: wrap the selection in the light
// markdown formatNoteBody renders (**bold**, *italic*), or insert an empty
// pair with the cursor in between.
export function formatToolbar(textarea) {
const bar = document.createElement("div");
bar.className = "notes-panel__format";
bar.innerHTML = `<button type="button" data-mark="**" title="Bold" aria-label="Bold"><b>B</b></button><button type="button" data-mark="*" title="Italic" aria-label="Italic"><i>I</i></button>`;
bar.addEventListener("click", (event) => {
const mark = event.target.closest("button")?.dataset.mark;
if (!mark) return;
const { selectionStart: start, selectionEnd: end, value } = textarea;
textarea.value = value.slice(0, start) + mark + value.slice(start, end) + mark + value.slice(end);
textarea.focus();
textarea.setSelectionRange(start + mark.length, end + mark.length);
});
return bar;
}
const NEW_FOLDER_VALUE = "__new__";
// Every hand-drawn note (from here or measure.js's "Save as note") gets one // Every hand-drawn note (from here or measure.js's "Save as note") gets one
// of these — the only stable way to find a specific feature again for // of these — the only stable way to find a specific feature again for
@@ -57,18 +163,10 @@ export class NoteSaveForm {
this._el.hidden = true; this._el.hidden = true;
this._el.innerHTML = ` this._el.innerHTML = `
<input type="text" class="notes-panel__title" placeholder="Title"> <input type="text" class="notes-panel__title" placeholder="Title">
<div class="notes-panel__icons"> <div class="notes-panel__style-slot"></div>
<button type="button" class="notes-panel__icon-option active" data-icon="" title="No icon">${NOTE_PIN_ICON}</button>
${Object.keys(POI_ICONS)
.map(
(key) =>
`<button type="button" class="notes-panel__icon-option" data-icon="${key}" title="${escapeAttr(ICON_LABELS[key] || key)}">${POI_ICONS[key]}</button>`,
)
.join("")}
</div>
<textarea class="notes-panel__body" rows="3" placeholder="Details (optional) — **bold**, *italic*, links"></textarea> <textarea class="notes-panel__body" rows="3" placeholder="Details (optional) — **bold**, *italic*, links"></textarea>
<select class="notes-panel__target"></select> <select class="notes-panel__target"></select>
<input type="text" class="notes-panel__new-name" placeholder="Layer name" hidden> <input type="text" class="notes-panel__new-name" placeholder="Folder name" hidden>
<div class="notes-panel__actions"> <div class="notes-panel__actions">
<button type="button" class="notes-panel__save">Save</button> <button type="button" class="notes-panel__save">Save</button>
<button type="button" class="notes-panel__cancel">Cancel</button> <button type="button" class="notes-panel__cancel">Cancel</button>
@@ -77,22 +175,14 @@ export class NoteSaveForm {
container.appendChild(this._el); container.appendChild(this._el);
this._title = this._el.querySelector(".notes-panel__title"); this._title = this._el.querySelector(".notes-panel__title");
this._iconPicker = this._el.querySelector(".notes-panel__icons"); this._style = new PointStyleFields(this._el.querySelector(".notes-panel__style-slot"), { onIconChange: (icon) => this._onIconChange?.(icon) });
this._body = this._el.querySelector(".notes-panel__body"); this._body = this._el.querySelector(".notes-panel__body");
this._body.before(formatToolbar(this._body));
this._target = this._el.querySelector(".notes-panel__target"); this._target = this._el.querySelector(".notes-panel__target");
this._newName = this._el.querySelector(".notes-panel__new-name"); this._newName = this._el.querySelector(".notes-panel__new-name");
this._saveButton = this._el.querySelector(".notes-panel__save"); this._saveButton = this._el.querySelector(".notes-panel__save");
this._selectedIcon = "";
this._iconPicker.querySelectorAll(".notes-panel__icon-option").forEach((button) => {
button.addEventListener("click", () => {
this._selectedIcon = button.dataset.icon;
this._iconPicker.querySelectorAll(".notes-panel__icon-option").forEach((b) => b.classList.toggle("active", b === button));
this._onIconChange?.(this._selectedIcon);
});
});
this._target.addEventListener("change", () => { this._target.addEventListener("change", () => {
this._newName.hidden = this._target.value !== NEW_LAYER_VALUE; this._newName.hidden = this._target.value !== NEW_FOLDER_VALUE;
if (!this._newName.hidden) this._newName.focus(); if (!this._newName.hidden) this._newName.focus();
}); });
this._saveButton.addEventListener("click", () => this._save()); this._saveButton.addEventListener("click", () => this._save());
@@ -108,13 +198,12 @@ export class NoteSaveForm {
this._el.hidden = false; this._el.hidden = false;
this._title.value = ""; this._title.value = "";
this._body.value = ""; this._body.value = "";
this._selectedIcon = ""; this._style.set();
this._iconPicker.querySelectorAll(".notes-panel__icon-option").forEach((b, i) => b.classList.toggle("active", i === 0)); this._onIconChange?.("");
this._onIconChange?.(this._selectedIcon);
// An icon only makes sense on a single point — Measure's "Save as // An icon only makes sense on a single point — Measure's "Save as
// note" can hand this a LineString/Polygon, which has no one spot for // note" can hand this a LineString/Polygon, which has no one spot for
// a badge glyph to sit at. // a badge glyph to sit at.
this._iconPicker.hidden = geometry.type !== "Point"; this._style.iconsVisible = geometry.type === "Point";
this._title.focus(); this._title.focus();
await this._populateTargets(); await this._populateTargets();
} }
@@ -129,20 +218,25 @@ export class NoteSaveForm {
async _populateTargets() { async _populateTargets() {
const previousValue = this._target.value; const previousValue = this._target.value;
let files = []; let folders = [];
let lines = [];
try { try {
const tree = await (await fetch("/api/gpx/tree")).json(); const tree = await (await fetch("/api/library/tree")).json();
files = geojsonFiles(tree); folders = folderPaths(tree);
lines = this._geometry?.type === "Point" ? trackNodes(tree) : [];
} catch (err) { } catch (err) {
// Tree fetch failed — target select just falls back to "new layer" // Tree fetch failed — still usable with the top level or a new folder.
// only, still usable.
} }
this._target.innerHTML = this._target.innerHTML =
files.map((file) => `<option value="${escapeAttr(file.path)}">${escapeText(file.path)}</option>`).join("") + `<option value="">Top level</option>` +
`<option value="${NEW_LAYER_VALUE}">+ New layer…</option>`; folders.map((path) => `<option value="${escapeAttr(path)}">${escapeText(path)}</option>`).join("") +
this._target.value = files.some((file) => file.path === previousValue) ? previousValue : NEW_LAYER_VALUE; `<option value="${NEW_FOLDER_VALUE}">+ New folder…</option>` +
this._newName.hidden = this._target.value !== NEW_LAYER_VALUE; // A point can go straight into a track/route (kept and exported with it).
(lines.length ? `<optgroup label="Into a track / route">${lines.map(([key, label]) => `<option value="${escapeAttr(key)}">${escapeText(label)}</option>`).join("")}</optgroup>` : "");
const values = [...this._target.options].map((o) => o.value);
this._target.value = values.includes(previousValue) ? previousValue : "";
this._newName.hidden = this._target.value !== NEW_FOLDER_VALUE;
} }
async _save() { async _save() {
@@ -150,9 +244,9 @@ export class NoteSaveForm {
const details = this._body.value.trim(); const details = this._body.value.trim();
if (!title || !this._geometry) return; if (!title || !this._geometry) return;
const isNewLayer = this._target.value === NEW_LAYER_VALUE; const isNewFolder = this._target.value === NEW_FOLDER_VALUE;
const name = isNewLayer ? this._newName.value.trim() : ""; const folder = isNewFolder ? this._newName.value.trim() : this._target.value;
if (isNewLayer && !name) { if (isNewFolder && !folder) {
this._newName.focus(); this._newName.focus();
return; return;
} }
@@ -165,21 +259,21 @@ export class NoteSaveForm {
category: "Note", category: "Note",
time: new Date().toISOString(), time: new Date().toISOString(),
...(details ? { description: details } : {}), ...(details ? { description: details } : {}),
...(this._selectedIcon ? { icon: this._selectedIcon } : {}),
}, },
geometry: this._geometry, geometry: this._geometry,
}; };
this._style.applyTo(feature.properties);
const requestBody = new URLSearchParams({ feature: JSON.stringify(feature) }); const intoLine = folder.startsWith("item:");
if (isNewLayer) requestBody.set("name", name); const requestBody = new URLSearchParams({ feature: JSON.stringify(feature), ...(intoLine ? {} : { folder }) });
else requestBody.set("path", this._target.value);
this._saveButton.disabled = true; this._saveButton.disabled = true;
try { try {
const response = await fetch("/api/gpx/notes", { method: "POST", body: requestBody }); const url = intoLine ? `/api/library/node/${encodeURIComponent(folder)}/points` : "/api/library/notes";
const response = await fetch(url, { method: "POST", body: requestBody });
if (!response.ok) throw new Error(`save failed: ${response.status}`); if (!response.ok) throw new Error(`save failed: ${response.status}`);
const { path } = await response.json(); const { path } = await response.json();
notifyGpxStoreChanged(path); notifyGpxStoreChanged(intoLine ? folder : path);
this.close(); this.close();
this._onSaved?.(); this._onSaved?.();
} catch (err) { } catch (err) {
@@ -191,7 +285,7 @@ export class NoteSaveForm {
} }
// A quick "pin it with a note" tool — click the map, write a short note, // A quick "pin it with a note" tool — click the map, write a short note,
// pick which .geojson "layer" file it joins (or start a new one). Point // pick which folder it goes into (or start a new one). Point
// only: for a distance/area shape, draw it with the Measure tool and use // only: for a distance/area shape, draw it with the Measure tool and use
// its own "Save as note" button instead of duplicating that click-to-place // its own "Save as note" button instead of duplicating that click-to-place
// UX here — see measure.js. // UX here — see measure.js.
@@ -248,6 +342,14 @@ export class NotesControl {
return this._container; return this._container;
} }
// "Save a point" from what's here (map.js): the note's form at that spot.
placeAt(lngLat) {
if (!this._active) this._setActive(true);
this._form.close();
this._removeMarker();
this._onClick({ lngLat });
}
_removeMarker() { _removeMarker() {
this._marker?.remove(); this._marker?.remove();
this._marker = null; this._marker = null;
@@ -274,12 +376,17 @@ export class NotesControl {
} }
} }
function geojsonFiles(node, results = []) { function folderPaths(node) {
if (node.type === "file" && node.path.toLowerCase().endsWith(".geojson")) { return (node.children || []).filter((child) => child.type === "folder").flatMap((child) => [child.path, ...folderPaths(child)]);
results.push({ path: node.path }); }
}
(node.children || []).forEach((child) => geojsonFiles(child, results)); // Tracks/routes of the library as [key, "folder / name"].
return results; function trackNodes(node, folder = "") {
return (node.children || []).flatMap((child) => {
if (child.type === "folder") return trackNodes(child, child.path);
const line = child.path.startsWith("item:") && !child.layer && child.kinds?.some((k) => k === "track" || k === "route");
return line ? [[child.path, [folder, child.name].filter(Boolean).join(" / ")]] : [];
});
} }
function escapeAttr(value) { function escapeAttr(value) {
+248
View File
@@ -0,0 +1,248 @@
import { Popup } from "/vendor/maplibre-gl/maplibre-gl.mjs";
import { NPS_SYMBOLS } from "/js/icons.js";
import { escapeHtml } from "/js/gpx.js";
// NPS park maps: the National Park Service's own (Harpers Ferry Center)
// brochure maps, public domain. An Overlays item. app.rb serves the index
// (/api/nps: every park with maps, every map with its download links) and
// the files under /nps/. The 289 georeferenced maps can be laid over the
// base map: each is an image source with four corners (nps.json's
// `corners`, computed from the map's geoTransform when it was built).
const SOURCE_PARKS = "nps-parks";
const SOURCE_FOOTPRINTS = "nps-footprints";
const SOURCE_OVERLAY = "nps-overlay";
const PARK_COLOR = "#546619";
const FOOTPRINT_COLOR = "#a65523";
const MAX_RESULTS = 8;
export class NpsControl {
constructor(map) {
this._map = map;
this._enabled = false;
this._data = null;
this._overlay = null; // the map shown over the base map, if any
map.on("style.load", () => {
if (!this._enabled) return;
this._addLayers();
if (this._overlay) this._showOverlay(this._overlay, { fit: false });
});
}
mount(li) {
li.innerHTML = `
<label>
<input type="checkbox" class="overlays-panel__toggle">
<span class="overlays-panel__icon">${NPS_SYMBOLS.maps}</span>
<span>NPS park maps</span>
</label>
<div class="nps-panel" hidden>
<input type="search" class="nps-panel__search" placeholder="Find a park">
<ul class="nps-panel__results"></ul>
<div class="nps-panel__shown" hidden>
<span class="nps-panel__shown-title"></span>
<label>Opacity <input type="range" class="nps-panel__opacity" min="0" max="1" step="0.05" value="0.9"></label>
<button type="button" class="nps-panel__hide" title="Remove this map">✕</button>
</div>
</div>
`;
this._li = li;
this._toggle = li.querySelector(".overlays-panel__toggle");
this._panel = li.querySelector(".nps-panel");
this._search = li.querySelector(".nps-panel__search");
this._results = li.querySelector(".nps-panel__results");
this._shown = li.querySelector(".nps-panel__shown");
this._opacity = li.querySelector(".nps-panel__opacity");
this._toggle.addEventListener("change", () => (this._toggle.checked ? this._enable() : this._disable()));
this._search.addEventListener("input", () => this._renderResults());
this._results.addEventListener("click", (event) => {
const code = event.target.closest("[data-park]")?.dataset.park;
if (code) this._goToPark(code);
});
this._opacity.addEventListener("input", () => {
if (this._map.getLayer(SOURCE_OVERLAY)) this._map.setPaintProperty(SOURCE_OVERLAY, "raster-opacity", +this._opacity.value);
});
li.querySelector(".nps-panel__hide").addEventListener("click", () => this._showOverlay(null));
}
async _enable() {
this._enabled = true;
this._panel.hidden = false;
if (!this._data) {
try {
const response = await fetch("/api/nps");
if (!response.ok) throw new Error(response.status);
this._index(await response.json());
} catch (err) {
this._toggle.checked = false;
this._toggle.disabled = true;
this._panel.hidden = true;
this._li.title = "No NPS map data on this server";
this._enabled = false;
return;
}
}
this._addLayers();
this._renderResults();
}
_disable() {
this._enabled = false;
this._panel.hidden = true;
this._showOverlay(null);
for (const id of ["nps-footprints", "nps-park-labels", "nps-parks"]) if (this._map.getLayer(id)) this._map.removeLayer(id);
for (const id of [SOURCE_PARKS, SOURCE_FOOTPRINTS]) if (this._map.getSource(id)) this._map.removeSource(id);
}
// Parks that have maps, each with its maps (georeferenced ones first).
_index(data) {
const byPark = new Map();
for (const m of data.maps) for (const code of m.parks) byPark.set(code, [...(byPark.get(code) || []), m]);
this._parks = [...byPark.keys()]
.filter((code) => data.parks[code])
.map((code) => ({
code,
...data.parks[code],
maps: byPark.get(code).sort((a, b) => !!b.corners - !!a.corners || a.title.localeCompare(b.title)),
}))
.sort((a, b) => a.name.localeCompare(b.name));
this._parkByCode = new Map(this._parks.map((p) => [p.code, p]));
this._data = data;
}
_addLayers() {
if (this._map.getSource(SOURCE_PARKS)) return;
this._map.addSource(SOURCE_PARKS, {
type: "geojson",
data: {
type: "FeatureCollection",
features: this._parks.map((p) => {
const [w, s, e, n] = p.bbox;
return {
type: "Feature",
properties: { code: p.code, name: p.name },
geometry: { type: "Point", coordinates: [(w + e) / 2, (s + n) / 2] },
};
}),
},
});
this._map.addSource(SOURCE_FOOTPRINTS, {
type: "geojson",
data: {
type: "FeatureCollection",
features: this._data.maps
.filter((m) => m.corners)
.map((m) => ({
type: "Feature",
properties: { park: m.parks[0] },
geometry: { type: "Polygon", coordinates: [[...m.corners, m.corners[0]]] },
})),
},
});
this._map.addLayer({
id: "nps-footprints",
type: "line",
source: SOURCE_FOOTPRINTS,
minzoom: 5,
paint: { "line-color": FOOTPRINT_COLOR, "line-width": 1.2, "line-dasharray": [3, 2] },
});
this._map.addLayer({
id: "nps-parks",
type: "circle",
source: SOURCE_PARKS,
paint: {
"circle-radius": ["interpolate", ["linear"], ["zoom"], 3, 4, 8, 7],
"circle-color": PARK_COLOR,
"circle-stroke-color": "#fff",
"circle-stroke-width": 1.5,
},
});
this._map.addLayer({
id: "nps-park-labels",
type: "symbol",
source: SOURCE_PARKS,
minzoom: 5,
layout: { "text-field": ["get", "name"], "text-font": ["Noto Sans Regular"], "text-size": 12, "text-offset": [0, 1.1], "text-anchor": "top" },
paint: { "text-color": PARK_COLOR, "text-halo-color": "#fff", "text-halo-width": 1.5 },
});
if (!this._interactive) {
this._interactive = true;
const open = (event) => this._openPark(event.features[0].properties.code || event.features[0].properties.park, event.lngLat);
for (const id of ["nps-parks", "nps-footprints"]) {
this._map.on("click", id, open);
this._map.on("mouseenter", id, () => (this._map.getCanvas().style.cursor = "pointer"));
this._map.on("mouseleave", id, () => (this._map.getCanvas().style.cursor = ""));
}
}
}
_renderResults() {
const query = this._search.value.trim().toLowerCase();
if (!query) {
this._results.innerHTML = "";
return;
}
const hits = this._parks.filter((p) => p.name.toLowerCase().includes(query) || p.code === query).slice(0, MAX_RESULTS);
this._results.innerHTML = hits.length
? hits.map((p) => `<li><button type="button" data-park="${p.code}">${escapeHtml(p.name)} <small>${p.maps.length}</small></button></li>`).join("")
: `<li class="nps-panel__none">No park found</li>`;
}
_goToPark(code) {
const park = this._parkByCode.get(code);
const [w, s, e, n] = park.bbox;
// Listening first: without animation (reduced motion) fitBounds fires
// moveend before it returns.
this._map.once("moveend", () => this._openPark(code, [(w + e) / 2, (s + n) / 2]));
this._map.fitBounds([[w, s], [e, n]], { padding: 40, maxZoom: 12 });
}
// A popup listing the park's maps: lay a georeferenced one over the map,
// or open/download it.
_openPark(code, lngLat) {
const park = this._parkByCode.get(code);
if (!park) return;
const item = (m) => {
const links = [
m.pdf ? `<a href="/nps/${m.pdf}" target="_blank">PDF</a>` : m.dl.pdf && `<a href="${m.dl.pdf}" target="_blank" rel="noopener">PDF ↗</a>`,
m.tif && `<a href="/nps/${m.tif}" download>GeoTIFF</a>`,
m.dl.jpg && `<a href="${m.dl.jpg}" target="_blank" rel="noopener">JPG ↗</a>`,
].filter(Boolean);
return `<li>
<div class="nps-popup__title">${escapeHtml(m.title)}</div>
<div class="nps-popup__links">${m.corners ? `<button type="button" data-map="${m.id}" class="${this._overlay?.id === m.id ? "active" : ""}">On map</button>` : ""}${links.join("")}</div>
</li>`;
};
const element = document.createElement("div");
element.className = "nps-popup";
element.innerHTML = `<strong>${escapeHtml(park.name)}</strong><ul>${park.maps.map(item).join("")}</ul>`;
element.addEventListener("click", (event) => {
const id = event.target.closest("button[data-map]")?.dataset.map;
if (!id) return;
const m = park.maps.find((x) => x.id === id);
this._showOverlay(this._overlay?.id === id ? null : m);
element.querySelectorAll("button[data-map]").forEach((b) => b.classList.toggle("active", b.dataset.map === this._overlay?.id));
});
new Popup({ maxWidth: "300px" }).setLngLat(lngLat).setDOMContent(element).addTo(this._map);
}
// One brochure map at a time over the base map (null = none).
_showOverlay(m, { fit = true } = {}) {
if (this._map.getLayer(SOURCE_OVERLAY)) this._map.removeLayer(SOURCE_OVERLAY);
if (this._map.getSource(SOURCE_OVERLAY)) this._map.removeSource(SOURCE_OVERLAY);
this._overlay = m;
this._shown.hidden = !m;
if (!m) return;
this._shown.querySelector(".nps-panel__shown-title").textContent = m.title;
this._map.addSource(SOURCE_OVERLAY, { type: "image", url: `/nps/overlay/${m.id}.jpg`, coordinates: m.corners });
this._map.addLayer(
{ id: SOURCE_OVERLAY, type: "raster", source: SOURCE_OVERLAY, paint: { "raster-opacity": +this._opacity.value } },
this._map.getLayer("nps-footprints") ? "nps-footprints" : undefined,
);
if (fit) {
const xs = m.corners.map((c) => c[0]);
const ys = m.corners.map((c) => c[1]);
this._map.fitBounds([[Math.min(...xs), Math.min(...ys)], [Math.max(...xs), Math.max(...ys)]], { padding: 20 });
}
}
}
+111 -20
View File
@@ -35,8 +35,12 @@ function formatRunning(status) {
// earlier — see icons.js). Framed in a small rounded-square badge in the // earlier — see icons.js). Framed in a small rounded-square badge in the
// markup below, the same convention icons.js's MAP_MARKER_ICON already // markup below, the same convention icons.js's MAP_MARKER_ICON already
// uses for framing a category glyph, rather than a new visual language. // uses for framing a category glyph, rather than a new visual language.
function flagIconUrl(code) { // A country's flag (a subregion shows its country's: "US-CA" → us); none
return `/vendor/flag-icons/1x1/${code.toLowerCase()}.svg`; // for a region without an ISO code (Canary Islands, ...).
function flagImg(code) {
const iso = code.match(/^([A-Z]{2})(-|$)/)?.[1];
if (!iso) return `<span class="offline-data-panel__flag"></span>`;
return `<img class="offline-data-panel__flag" src="/vendor/flag-icons/1x1/${iso.toLowerCase()}.svg" alt="" width="18" height="18" loading="lazy">`;
} }
// meta.sources is one entry per country the current build covers (see // meta.sources is one entry per country the current build covers (see
@@ -48,6 +52,13 @@ function formatOfflineMeta(meta) {
return ` · ${meta.sources.map((s) => s.code).join(", ")}`; return ` · ${meta.sources.map((s) => s.code).join(", ")}`;
} }
// Routing tiles live in the valhalla container's hands (see
// lib/maptool/routing.rb); "serving" says whether it actually answers.
function formatRoutingMeta(meta) {
if (!meta) return "";
return `${formatOfflineMeta(meta)} · ${meta.serving ? "routing ready" : "routing service not running"}`;
}
function formatTerrainMeta(meta) { function formatTerrainMeta(meta) {
if (!meta) return ""; if (!meta) return "";
const count = meta.sources.length; const count = meta.sources.length;
@@ -68,10 +79,12 @@ class RegionPicker {
section.className = "offline-data-panel__regions"; section.className = "offline-data-panel__regions";
section.innerHTML = ` section.innerHTML = `
<p class="offline-data-panel__regions-label">Regions</p> <p class="offline-data-panel__regions-label">Regions</p>
<ul class="offline-data-panel__region-list"><li class="offline-data-panel__region-status">Loading…</li></ul> <input type="search" class="offline-data-panel__region-filter" placeholder="Find a country or region">
<div class="offline-data-panel__region-list"><p class="offline-data-panel__region-status">Loading…</p></div>
<button type="button" class="offline-data-panel__apply" hidden>Apply changes</button> <button type="button" class="offline-data-panel__apply" hidden>Apply changes</button>
`; `;
this._list = section.querySelector(".offline-data-panel__region-list"); this._list = section.querySelector(".offline-data-panel__region-list");
this._filter = section.querySelector(".offline-data-panel__region-filter");
this._applyButton = section.querySelector(".offline-data-panel__apply"); this._applyButton = section.querySelector(".offline-data-panel__apply");
// Viewing/ticking works for anyone; only saving needs a login — same // Viewing/ticking works for anyone; only saving needs a login — same
// finer-grained gating measure.js/gpx.js use for their own // finer-grained gating measure.js/gpx.js use for their own
@@ -88,20 +101,23 @@ class RegionPicker {
fetch("/api/offline-tiles/cache").then((r) => r.json()), fetch("/api/offline-tiles/cache").then((r) => r.json()),
]); ]);
} catch { } catch {
this._list.innerHTML = `<li class="offline-data-panel__region-status">Could not load the region list.</li>`; this._list.innerHTML = `<p class="offline-data-panel__region-status">Could not load the region list.</p>`;
return; return;
} }
const selected = new Set(data.selected); const selected = new Set(data.selected);
const cached = new Map(cache.extracts.map((e) => [e.code, e])); const cached = new Map(cache.extracts.map((e) => [e.code, e]));
this._list.innerHTML = data.available const subregions = new Map();
.map((region) => { for (const region of data.available) {
const extract = cached.get(region.code); if (region.parent) subregions.set(region.parent, [...(subregions.get(region.parent) || []), region]);
// Downloaded-but-not-(yet)-built is a real state (ticked, not }
// Applied yet) as is built-but-no-longer-selected (unticked since) const row = (region) => {
// — this badge reflects the cache on disk, independent of either. const extract = cached.get(region.code);
const cacheInfo = extract // Downloaded-but-not-(yet)-built is a real state (ticked, not
? ` // Applied yet) as is built-but-no-longer-selected (unticked since)
// — this badge reflects the cache on disk, independent of either.
const cacheInfo = extract
? `
<span class="offline-data-panel__cache-info"> <span class="offline-data-panel__cache-info">
${formatBytes(extract.size)} ${formatBytes(extract.size)}
${ ${
@@ -110,24 +126,72 @@ class RegionPicker {
: "" : ""
} }
</span>` </span>`
: ""; : "";
return ` return `
<li> <div class="offline-data-panel__region" data-search="${escapeHtml(`${region.name} ${region.code}`.toLowerCase())}">
<label> <label>
<input type="checkbox" value="${escapeHtml(region.code)}" ${selected.has(region.code) ? "checked" : ""}> <input type="checkbox" value="${escapeHtml(region.code)}" ${selected.has(region.code) ? "checked" : ""}>
<img class="offline-data-panel__flag" src="${flagIconUrl(region.code)}" alt="" width="18" height="18"> ${flagImg(region.code)}
${escapeHtml(region.name)} <span class="offline-data-panel__region-name">${escapeHtml(region.name)}</span>
</label> </label>
${cacheInfo} ${cacheInfo}
</li>`; </div>`;
};
// Continents (collapsible, open when something in them is selected),
// countries, and a country's subregions (US states, ...) folded under it.
this._list.innerHTML = data.continents
.map((continent) => {
const countries = data.available.filter((r) => r.continent === continent.id && !r.parent);
if (!countries.length) return "";
const codes = data.available.filter((r) => r.continent === continent.id).map((r) => r.code);
return `
<details class="offline-data-panel__continent" ${codes.some((c) => selected.has(c)) ? "open" : ""}>
<summary>${escapeHtml(continent.name)} <span class="offline-data-panel__count"></span></summary>
${countries
.map((country) => {
const subs = subregions.get(country.code);
if (!subs) return row(country);
return `${row(country)}
<details class="offline-data-panel__subregions" ${subs.some((r) => selected.has(r.code)) ? "open" : ""}>
<summary>${subs.length} regions of ${escapeHtml(country.name)}</summary>
${subs.map(row).join("")}
</details>`;
})
.join("")}
</details>`;
}) })
.join(""); .join("");
this._list.addEventListener("change", () => this._updateCounts());
this._updateCounts();
this._filter.addEventListener("input", () => this._applyFilter());
this._list.querySelectorAll(".offline-data-panel__cache-delete").forEach((button) => { this._list.querySelectorAll(".offline-data-panel__cache-delete").forEach((button) => {
button.addEventListener("click", () => this._deleteCache(button)); button.addEventListener("click", () => this._deleteCache(button));
}); });
} }
// "(2 selected)" on each continent, so a folded one still shows it holds a choice.
_updateCounts() {
this._list.querySelectorAll(".offline-data-panel__continent").forEach((details) => {
const n = details.querySelectorAll("input:checked").length;
details.querySelector(".offline-data-panel__count").textContent = n ? `(${n} selected)` : "";
});
}
// Hides non-matching rows and opens whatever holds a match; empty = as before.
_applyFilter() {
const query = this._filter.value.trim().toLowerCase();
this._list.querySelectorAll(".offline-data-panel__region").forEach((el) => {
el.hidden = query !== "" && !el.dataset.search.includes(query);
});
this._list.querySelectorAll(".offline-data-panel__subregions, .offline-data-panel__continent").forEach((details) => {
const visible = [...details.querySelectorAll(".offline-data-panel__region")].some((el) => !el.hidden);
details.hidden = query !== "" && !visible;
if (query !== "") details.open = visible;
});
}
// Removes just this row's cache badge on success, rather than re-fetching // Removes just this row's cache badge on success, rather than re-fetching
// and re-rendering the whole list — that would also overwrite whatever // and re-rendering the whole list — that would also overwrite whatever
// unticked/ticked-but-not-yet-Applied state the user has pending. // unticked/ticked-but-not-yet-Applied state the user has pending.
@@ -204,6 +268,18 @@ class DataFileRow {
this._deleteButton.addEventListener("click", () => this._delete()); this._deleteButton.addEventListener("click", () => this._delete());
container.appendChild(row); container.appendChild(row);
this._refreshStatus(); this._refreshStatus();
this._resumePolling();
}
// A build started earlier (a routing build runs for hours) keeps showing
// its progress after a page reload.
async _resumePolling() {
try {
const status = await (await fetch(this._buildStatusUrl)).json();
if (status.state === "running") this._poll();
} catch {
// status stays whatever _refreshStatus shows
}
} }
// Single place that writes to _statusEl, so the error styling (pre-wrap, // Single place that writes to _statusEl, so the error styling (pre-wrap,
@@ -231,7 +307,7 @@ class DataFileRow {
const updated = new Date(data.mtime).toLocaleString([], { dateStyle: "short", timeStyle: "short" }); const updated = new Date(data.mtime).toLocaleString([], { dateStyle: "short", timeStyle: "short" });
this._setStatus(`${formatBytes(data.size)} · updated ${updated}${this._formatMeta(data.meta)}`); this._setStatus(`${formatBytes(data.size)} · updated ${updated}${this._formatMeta(data.meta)}`);
this._deleteButton.hidden = !isLoggedIn(); this._deleteButton.hidden = !isLoggedIn() || !this._deleteUrl;
this._checkUpdate(); this._checkUpdate();
} }
@@ -368,8 +444,23 @@ export class OfflineDataControl {
checkUpdateUrl: "/api/terrain-tiles/check-update", checkUpdateUrl: "/api/terrain-tiles/check-update",
formatMeta: formatTerrainMeta, formatMeta: formatTerrainMeta,
}), }),
// No delete: the tiles are in use by the routing container.
new DataFileRow({
label: "Offline routing",
statusUrl: "/api/routing-tiles",
buildUrl: "/api/routing-tiles/build",
buildStatusUrl: "/api/routing-tiles/build-status",
checkUpdateUrl: "/api/routing-tiles/check-update",
formatMeta: formatRoutingMeta,
}),
]; ];
this._regionPicker = new RegionPicker(() => this._rows.forEach((row) => row.triggerBuild())); // One after another (each returns once its build has started, not
// finished): the routing request must reach the server after the
// offline build has, so it waits for the extracts that build downloads
// (Routing.request_build) instead of building from half-written ones.
this._regionPicker = new RegionPicker(async () => {
for (const row of this._rows) await row.triggerBuild();
});
} }
mount(sidebar) { mount(sidebar) {
+108 -52
View File
@@ -6,6 +6,9 @@ import { RadarControl } from "/js/radar.js";
import { ShadowControl } from "/js/shadow.js"; import { ShadowControl } from "/js/shadow.js";
import { ContourControl } from "/js/contour.js"; import { ContourControl } from "/js/contour.js";
import { HikingTrailsControl } from "/js/hiking_trails.js"; import { HikingTrailsControl } from "/js/hiking_trails.js";
import { TrackerControl, ItsControl } from "/js/live.js";
import { NpsControl } from "/js/nps.js";
import { DashboardControl } from "/js/dashboard.js";
const ICON_IMAGE_SIZE = 48; // rasterized once at this size, rendered much smaller by icon-size below const ICON_IMAGE_SIZE = 48; // rasterized once at this size, rendered much smaller by icon-size below
const ICON_SIZE = 0.3; // 48 * 0.3 = ~14px, sized to sit inside the marker badge below const ICON_SIZE = 0.3; // 48 * 0.3 = ~14px, sized to sit inside the marker badge below
@@ -16,6 +19,13 @@ const WIKI_ICON_ID = "wiki-icon";
const WIKI_BADGE_COLOR = "#795548"; const WIKI_BADGE_COLOR = "#795548";
const HILLSHADE_ID = "hillshade-dem"; const HILLSHADE_ID = "hillshade-dem";
// Raised 3D relief (map.setTerrain) has a DEM source of its own, so the 3D
// button shows it with or without the Terrain shading overlay (MapLibre
// also advises against sharing one source between hillshade and terrain).
const TERRAIN_ID = "terrain-dem";
// Real heights look flat from a car-navigation tilt; 3× (before) turned
// the Tatras into needles.
const TERRAIN_EXAGGERATION = 1.5;
const COLOR_RELIEF_ID = "elevation-tint"; const COLOR_RELIEF_ID = "elevation-tint";
// MapLibre's own default light ({anchor:"viewport", intensity:0.5, // MapLibre's own default light ({anchor:"viewport", intensity:0.5,
// position:[1.15,210,30]}) sits the sun almost overhead (polar 30°) — fine // position:[1.15,210,30]}) sits the sun almost overhead (polar 30°) — fine
@@ -35,7 +45,7 @@ const DEFAULT_LIGHT = { anchor: "viewport", color: "#fff", intensity: 0.5, posit
const ELEVATION_COLOR_RAMP = [ const ELEVATION_COLOR_RAMP = [
"interpolate", "interpolate",
["linear"], ["linear"],
["raster-value"], ["elevation"],
0, "#c3e8ab", 0, "#c3e8ab",
400, "#dcd08f", 400, "#dcd08f",
900, "#c9a66b", 900, "#c9a66b",
@@ -85,34 +95,31 @@ class HillshadeControl {
_toggle(active) { _toggle(active) {
this._active = active; this._active = active;
// Clear first: setTerrain may still be pointing at HILLSHADE_ID from
// before, and removing that source out from under it is worth avoiding
// even for the instant before syncTerrain below re-evaluates it.
if (this._map.getTerrain()) this._map.setTerrain(null);
if (active) this._addLayer(); if (active) this._addLayer();
else this._removeLayer(); else this._removeLayer();
this.syncTerrain(this._map.getPitch() > 0); this.syncTerrain(this._map.getPitch() > 0);
} }
// Real terrain displacement (map.setTerrain), not just the flat // Real terrain displacement (map.setTerrain), not just the flat
// hillshade/color-relief paint above — called both when this checkbox // hillshade/color-relief paint above — whenever the map is tilted (the
// changes and when the 3D pitch toggle changes (map.js's // 3D button, map.js's PitchToggleControl, via OverlaysControl.syncTerrain
// PitchToggleControl, via OverlaysControl.syncTerrain below), since // below), like OsmAnd's 3D relief.
// showing raised terrain needs both "tilted enough to see it" and "the
// DEM source this checkbox controls is actually loaded".
syncTerrain(pitched) { syncTerrain(pitched) {
// setLight/setTerrain throw if the style isn't loaded yet — called // Not isStyleLoaded(): that's false while any tile is still loading —
// synchronously from map.js's setOverlaysControl during page init, // always the case right after tilting — so the terrain never came on.
// before the first style.load; that listener re-invokes this once it // Before the first style.load these throw; that listener calls again.
// actually is loaded, so bailing here just skips the premature call. try {
if (!this._map.isStyleLoaded()) return; if (pitched) {
const terrainOn = pitched && this._active && this._map.getSource(HILLSHADE_ID); if (!this._map.getSource(TERRAIN_ID)) this._map.addSource(TERRAIN_ID, this._demSource());
if (terrainOn) { this._map.setTerrain({ source: TERRAIN_ID, exaggeration: TERRAIN_EXAGGERATION });
this._map.setTerrain({ source: HILLSHADE_ID, exaggeration: 3 }); } else if (this._map.getTerrain()) {
} else if (this._map.getTerrain()) { this._map.setTerrain(null);
this._map.setTerrain(null); }
this._map.setLight(pitched ? TERRAIN_LIGHT : DEFAULT_LIGHT);
} catch {
return;
} }
this._map.setLight(terrainOn ? TERRAIN_LIGHT : DEFAULT_LIGHT); const terrainOn = pitched;
// The raster hillshade layer fakes relief by shading a flat texture — // The raster hillshade layer fakes relief by shading a flat texture —
// once real 3D geometry is doing that job (with its own lit shading // once real 3D geometry is doing that job (with its own lit shading
// for free), the raster version just looks like a blurry, low-res // for free), the raster version just looks like a blurry, low-res
@@ -133,7 +140,23 @@ class HillshadeControl {
// (docs/development.adoc), so this credits them regardless of how it // (docs/development.adoc), so this credits them regardless of how it
// got there — their own site lists the full per-region source // got there — their own site lists the full per-region source
// provenance (CC-BY-4.0 and similar), not practical to reproduce here. // provenance (CC-BY-4.0 and similar), not practical to reproduce here.
const source = this._offlineAvailable this._map.addSource(HILLSHADE_ID, this._demSource());
// Elevation tint under, hillshade on top: the tint sets the base color
// per elevation band, hillshade multiplies slope-shading over it — the
// combined "characteristic relief look" the TODO asked for, not two
// independent layers.
this._map.addLayer({
id: COLOR_RELIEF_ID,
type: "color-relief",
source: HILLSHADE_ID,
paint: { "color-relief-color": ELEVATION_COLOR_RAMP, "color-relief-opacity": 0.7 },
});
this._map.addLayer({ id: HILLSHADE_ID, type: "hillshade", source: HILLSHADE_ID, paint: { "hillshade-exaggeration": 0.4 } });
}
// The offline terrain.pmtiles when there is one, else the public tiles.
_demSource() {
return this._offlineAvailable
? { ? {
type: "raster-dem", type: "raster-dem",
url: `pmtiles://${window.location.origin}/tiles/terrain.pmtiles`, url: `pmtiles://${window.location.origin}/tiles/terrain.pmtiles`,
@@ -148,18 +171,6 @@ class HillshadeControl {
maxzoom: 15, maxzoom: 15,
attribution: "Terrain tiles: Mapzen, SRTM, ArcticDEM", attribution: "Terrain tiles: Mapzen, SRTM, ArcticDEM",
}; };
this._map.addSource(HILLSHADE_ID, source);
// Elevation tint under, hillshade on top: the tint sets the base color
// per elevation band, hillshade multiplies slope-shading over it — the
// combined "characteristic relief look" the TODO asked for, not two
// independent layers.
this._map.addLayer({
id: COLOR_RELIEF_ID,
type: "color-relief",
source: HILLSHADE_ID,
paint: { "color-relief-color": ELEVATION_COLOR_RAMP, "color-relief-opacity": 0.7 },
});
this._map.addLayer({ id: HILLSHADE_ID, type: "hillshade", source: HILLSHADE_ID, paint: { "hillshade-exaggeration": 0.4 } });
} }
_removeLayer() { _removeLayer() {
@@ -178,6 +189,12 @@ class HillshadeControl {
// here since neither has anything to "manage," just on/off (Radar's own // here since neither has anything to "manage," just on/off (Radar's own
// scrub/forecast controls live behind expanding its item, not a factor in // scrub/forecast controls live behind expanding its item, not a factor in
// where it's mounted). // where it's mounted).
const OVERLAYS_ON_KEY = "overlaysOn";
function readOn() {
try { return JSON.parse(localStorage.getItem(OVERLAYS_ON_KEY)) || {}; } catch { return {}; }
}
export class OverlaysControl { export class OverlaysControl {
constructor(map) { constructor(map) {
this._map = map; this._map = map;
@@ -186,6 +203,10 @@ export class OverlaysControl {
this._shadow = new ShadowControl(map); this._shadow = new ShadowControl(map);
this._contour = new ContourControl(map); this._contour = new ContourControl(map);
this._hikingTrails = new HikingTrailsControl(map); this._hikingTrails = new HikingTrailsControl(map);
this._tracker = new TrackerControl(map);
this._its = new ItsControl(map);
this._nps = new NpsControl(map);
this._dashboard = new DashboardControl(map);
this._wikiEnabled = false; // the checkbox's own state this._wikiEnabled = false; // the checkbox's own state
this._wikiMoveHandler = null; // the moveend listener driving its live refetch, while enabled this._wikiMoveHandler = null; // the moveend listener driving its live refetch, while enabled
this._wikiRequestSeq = 0; // ignores an in-flight refetch a newer one has already superseded this._wikiRequestSeq = 0; // ignores an in-flight refetch a newer one has already superseded
@@ -203,7 +224,7 @@ export class OverlaysControl {
mount(sidebar) { mount(sidebar) {
this._container = document.createElement("div"); this._container = document.createElement("div");
this._container.className = "sidebar-item"; this._container.className = "sidebar-item";
this._container.innerHTML = `<button type="button" class="sidebar-icon" title="Overlays" aria-label="Overlays">${OVERLAYS_ICON}</button>`; this._container.innerHTML = `<button type="button" class="sidebar-icon" title="On the map" aria-label="On the map">${OVERLAYS_ICON}</button>`;
this._icon = this._container.querySelector(".sidebar-icon"); this._icon = this._container.querySelector(".sidebar-icon");
this._icon.addEventListener("click", () => this._togglePanel()); this._icon.addEventListener("click", () => this._togglePanel());
@@ -212,28 +233,59 @@ export class OverlaysControl {
.querySelector(".basemap-panel__close") .querySelector(".basemap-panel__close")
.addEventListener("click", () => this._togglePanel(false)); .addEventListener("click", () => this._togglePanel(false));
// Items grouped under a heading each; [heading, [[mount, expandable]]].
const groups = [
["Terrain", [[(li) => this._hillshade.mount(li)], [(li) => this._shadow.mount(li), true], [(li) => this._contour.mount(li)]]],
["Weather", [[(li) => this._radar.mount(li), true]]],
["Places & trails", [[(li) => this._hikingTrails.mount(li), true], [(li) => this._mountWiki(li)], [(li) => this._nps.mount(li)]]],
["Live", [[(li) => this._tracker.mount(li)], [(li) => this._its.mount(li)], [(li) => this._dashboard.mount(li), true]]],
];
const list = this._panel.querySelector(".overlays-panel__list"); const list = this._panel.querySelector(".overlays-panel__list");
list.innerHTML = ` list.innerHTML = "";
<li class="overlays-panel__item"></li> for (const [heading, items] of groups) {
<li class="overlays-panel__item"></li> const head = document.createElement("li");
<li class="overlays-panel__item overlays-panel__item--expandable"></li> head.className = "overlays-panel__group";
<li class="overlays-panel__item overlays-panel__item--expandable"></li> head.textContent = heading;
<li class="overlays-panel__item"></li> list.appendChild(head);
<li class="overlays-panel__item overlays-panel__item--expandable"></li> for (const [mount, expandable] of items) {
`; const li = document.createElement("li");
const [hillshadeItem, wikiItem, radarItem, shadowItem, contourItem, hikingTrailsItem] = list.children; li.className = `overlays-panel__item${expandable ? " overlays-panel__item--expandable" : ""}`;
this._hillshade.mount(hillshadeItem); list.appendChild(li);
this._mountWiki(wikiItem); mount(li);
this._radar.mount(radarItem); this._remember(li, `${heading}/${li.querySelector(".overlays-panel__name, label")?.textContent.trim()}`);
this._shadow.mount(shadowItem); }
this._contour.mount(contourItem); }
this._hikingTrails.mount(hikingTrailsItem);
onlyOneSidePanelOpen(this._panel, () => this._icon.classList.remove("active")); onlyOneSidePanelOpen(this._panel, () => this._icon.classList.remove("active"));
sidebar.appendChild(this._container); sidebar.appendChild(this._container);
} }
// Which overlays are on, per device (localStorage), so a reload or an
// update doesn't switch them all off: saved on every change, turned back
// on by restore() — once map.js knows what's available offline.
_remember(li, key) {
const toggle = li.querySelector(".overlays-panel__toggle");
if (!toggle) return;
(this._toggles ??= []).push([key, toggle, li]);
toggle.addEventListener("change", () => {
const on = readOn();
if (toggle.checked) on[key] = true;
else delete on[key];
try { localStorage.setItem(OVERLAYS_ON_KEY, JSON.stringify(on)); } catch { /* private window: not kept */ }
});
}
restore() {
const on = readOn();
for (const [key, toggle, li] of this._toggles ?? []) {
const hidden = toggle.closest("[hidden]"); // within the item: not for this login (the closed panel doesn't count)
if (!on[key] || toggle.checked || toggle.disabled || (hidden && li.contains(hidden))) continue;
toggle.checked = true;
toggle.dispatchEvent(new Event("change"));
}
}
_togglePanel(force) { _togglePanel(force) {
const open = force === undefined ? this._panel.hidden : force; const open = force === undefined ? this._panel.hidden : force;
this._panel.hidden = !open; this._panel.hidden = !open;
@@ -245,8 +297,12 @@ export class OverlaysControl {
this._hillshade.setOfflineAvailable(available); this._hillshade.setOfflineAvailable(available);
} }
setHikingTrailsOfflineCountries(countries) { setHikingTrailsOfflineCountries(countries, bboxes) {
this._hikingTrails.setOfflineCountries(countries); this._hikingTrails.setOfflineCountries(countries, bboxes);
}
showHikingTrailsCountry(code) {
this._hikingTrails.showCountry(code);
} }
// Called by map.js's PitchToggleControl whenever the 3D pitch toggle // Called by map.js's PitchToggleControl whenever the 3D pitch toggle
+147
View File
@@ -16,6 +16,65 @@ export function onlyOneSidePanelOpen(panel, onClosedByOther) {
}); });
} }
// Two ways a side panel sits next to the map, switched by the pin button
// every panel's header gets (remembered per browser):
// - pinned (default): stays open and the map shrinks beside it (CSS on
// body.side-pinned, see style.css; MapLibre resizes itself on that);
// - overlay: floats over the map and closes once the mouse has been in it
// and left — not while typing in one of its fields, and never on touch.
const PANELS = ".basemap-panel, .gpx-panel";
const MODE_KEY = "sidePanelMode";
const HIDE_DELAY_MS = 400;
export function setupSidePanelModes() {
let pinned = true;
try {
pinned = localStorage.getItem(MODE_KEY) !== "overlay";
} catch {}
const apply = () => {
document.body.classList.toggle("side-pinned", pinned);
document.querySelectorAll(".side-panel-pin").forEach((btn) => {
btn.classList.toggle("active", pinned);
btn.title = pinned ? "Pinned beside the map (click: float over it, hide on mouse out)" : "Floats over the map (click: pin beside it)";
btn.setAttribute("aria-pressed", pinned);
});
};
document.querySelectorAll(PANELS).forEach((panel) => {
const close = panel.querySelector(".basemap-panel__close, .gpx-panel__close");
const pin = document.createElement("button");
pin.type = "button";
pin.className = "side-panel-pin";
pin.setAttribute("aria-label", "Pin panel");
pin.innerHTML = `<svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 17v5M9 3h6l-1 6 3 3v2H7v-2l3-3z"/></svg>`;
pin.addEventListener("click", () => {
pinned = !pinned;
try {
localStorage.setItem(MODE_KEY, pinned ? "pinned" : "overlay");
} catch {}
apply();
});
close.before(pin);
let entered = false;
let timer = null;
new MutationObserver(() => (entered = false)).observe(panel, { attributes: true, attributeFilter: ["hidden"] });
panel.addEventListener("pointerenter", (event) => {
if (event.pointerType !== "mouse") return;
entered = true;
clearTimeout(timer);
});
panel.addEventListener("pointerleave", (event) => {
if (pinned || !entered || event.pointerType !== "mouse") return;
timer = setTimeout(() => {
const typing = panel.contains(document.activeElement) && document.activeElement.matches("input:not([type=checkbox]):not([type=radio]), textarea, select");
if (!pinned && !panel.hidden && !typing) close.click();
}, HIDE_DELAY_MS);
});
});
apply();
}
// Lets a control that writes into the GPX store (e.g. notes.js saving a // Lets a control that writes into the GPX store (e.g. notes.js saving a
// drawn point) tell GpxPanelControl its tree is stale, without either one // drawn point) tell GpxPanelControl its tree is stale, without either one
// holding a reference to the other. path (the .geojson file just written // holding a reference to the other. path (the .geojson file just written
@@ -31,3 +90,91 @@ export function notifyGpxStoreChanged(path) {
export function onGpxStoreChanged(callback) { export function onGpxStoreChanged(callback) {
document.addEventListener(STORE_CHANGED_EVENT, (event) => callback(event.detail)); document.addEventListener(STORE_CHANGED_EVENT, (event) => callback(event.detail));
} }
// Anything with a location (a search result, a library point) hands it to
// the route panel (route.js) the same decoupled way.
const ROUTE_POINT_EVENT = "route-point";
const ROUTE_EDIT_EVENT = "route-edit";
export function addRoutePoint(lngLat, name) {
document.dispatchEvent(new CustomEvent(ROUTE_POINT_EVENT, { detail: { lngLat, name } }));
}
export function onRoutePoint(callback) {
document.addEventListener(ROUTE_POINT_EVENT, (event) => callback(event.detail));
}
// A saved route (its library node key and feature) back into the panel.
export function editRoute(key, feature) {
document.dispatchEvent(new CustomEvent(ROUTE_EDIT_EVENT, { detail: { key, feature } }));
}
export function onRouteEdit(callback) {
document.addEventListener(ROUTE_EDIT_EVENT, (event) => callback(event.detail));
}
// The route the route panel shows (its /api/route Feature, or null when
// cleared), for the dashboard's speed limits, signals and lanes ahead.
const ROUTE_CHANGED_EVENT = "route-changed";
let currentRoute = null;
export function notifyRouteChanged(route) {
currentRoute = route;
document.dispatchEvent(new CustomEvent(ROUTE_CHANGED_EVENT, { detail: route }));
}
// The profile in use (route.js; its /api/vehicles entry): the dashboard's
// and the driving grid's limits for it, the border card's "how it pays".
const VEHICLE_EVENT = "vehicle-changed";
export let currentVehicle = null;
export function notifyVehicle(vehicle) {
currentVehicle = vehicle;
document.dispatchEvent(new CustomEvent(VEHICLE_EVENT, { detail: vehicle }));
}
export function onVehicle(callback) {
document.addEventListener(VEHICLE_EVENT, (event) => callback(event.detail));
}
// How far along the route the position is, while the dashboard follows it
// (km, or null once it's off it / not navigating): the route panel draws
// the driven part dimmed and the rest as the active route.
const ROUTE_PROGRESS_EVENT = "route-progress";
export function notifyRouteProgress(km) {
document.dispatchEvent(new CustomEvent(ROUTE_PROGRESS_EVENT, { detail: km }));
}
export function onRouteProgress(callback) {
document.addEventListener(ROUTE_PROGRESS_EVENT, (event) => callback(event.detail));
}
// Off the route while navigating: the route panel routes again from `from`
// ([lon, lat]) to the points not yet reached (`passed` via points skipped).
const REROUTE_EVENT = "route-reroute";
export function requestReroute(from, passed) {
document.dispatchEvent(new CustomEvent(REROUTE_EVENT, { detail: { from, passed } }));
}
export function onReroute(callback) {
document.addEventListener(REROUTE_EVENT, (event) => callback(event.detail));
}
// Something that moves the GNSS position (the simulation) wants the map
// to follow it: the GNSS control turns itself on.
const GNSS_FOLLOW_EVENT = "gnss-follow";
export function requestGnssFollow() {
document.dispatchEvent(new CustomEvent(GNSS_FOLLOW_EVENT));
}
export function onGnssFollow(callback) {
document.addEventListener(GNSS_FOLLOW_EVENT, callback);
}
export function onRouteChanged(callback) {
document.addEventListener(ROUTE_CHANGED_EVENT, (event) => callback(event.detail));
return currentRoute;
}
+61 -20
View File
@@ -1,7 +1,10 @@
import { PLUGIN_ICON } from "/js/icons.js"; import { PLUGIN_ICON } from "/js/icons.js";
import { notifyGpxStoreChanged } from "/js/panels.js"; import { notifyGpxStoreChanged, notifySidePanelOpen, onlyOneSidePanelOpen } from "/js/panels.js";
// A sidebar flyout listing whatever import plugins are on disk (see const CORRIDORS_KM = [1, 2, 5, 10, 20];
const CORRIDOR_KEY = "maptool.pluginCorridorKm";
// A side panel (#plugins-panel) listing whatever import plugins are on disk (see
// lib/maptool/plugins.rb for the contract) — each one just a "Run for // lib/maptool/plugins.rb for the contract) — each one just a "Run for
// this area" button using the current map viewport as the bbox, so there's // this area" button using the current map viewport as the bbox, so there's
// no separate area-picker to build: pan/zoom to where you want, click Run. // no separate area-picker to build: pan/zoom to where you want, click Run.
@@ -16,27 +19,28 @@ export class PluginsControl {
mount(sidebar) { mount(sidebar) {
this._container = document.createElement("div"); this._container = document.createElement("div");
this._container.className = "sidebar-item"; this._container.className = "sidebar-item";
this._container.innerHTML = ` this._container.innerHTML = `<button type="button" class="sidebar-icon" title="Import plugins" aria-label="Import plugins">${PLUGIN_ICON}</button>`;
<button type="button" class="sidebar-icon" title="Import plugins" aria-label="Import plugins">${PLUGIN_ICON}</button>
<div class="sidebar-flyout" hidden>
<p class="plugins-panel__hint">Runs for whatever area is currently on screen.</p>
<ul class="plugins-panel__list"></ul>
</div>
`;
this._icon = this._container.querySelector(".sidebar-icon"); this._icon = this._container.querySelector(".sidebar-icon");
this._flyout = this._container.querySelector(".sidebar-flyout"); this._icon.addEventListener("click", () => this._togglePanel());
this._list = this._container.querySelector(".plugins-panel__list");
this._icon.addEventListener("click", () => { this._panel = document.getElementById("plugins-panel");
const opening = this._flyout.hidden; this._list = this._panel.querySelector(".plugins-panel__list");
this._flyout.hidden = !opening; this._panel.querySelector(".basemap-panel__close").addEventListener("click", () => this._togglePanel(false));
this._icon.classList.toggle("active", opening); onlyOneSidePanelOpen(this._panel, () => this._icon.classList.remove("active"));
if (opening) this._loadPlugins();
});
sidebar.appendChild(this._container); sidebar.appendChild(this._container);
} }
_togglePanel(force) {
const open = force === undefined ? this._panel.hidden : force;
this._panel.hidden = !open;
this._icon.classList.toggle("active", open);
if (open) {
notifySidePanelOpen(this._panel);
this._loadPlugins();
}
}
async _loadPlugins() { async _loadPlugins() {
this._list.innerHTML = `<li class="plugins-panel__empty">Loading…</li>`; this._list.innerHTML = `<li class="plugins-panel__empty">Loading…</li>`;
let plugins; let plugins;
@@ -55,28 +59,65 @@ export class PluginsControl {
plugins.forEach((plugin) => this._list.appendChild(this._renderItem(plugin))); plugins.forEach((plugin) => this._list.appendChild(this._renderItem(plugin)));
} }
// Per plugin: "Run for this area"; with "route" in its plugin.json also
// "Along the trip's route" N km either side (the corridor remembered); with
// "settings" (a login cookie) their fields — a value set shows as "set",
// never sent back from the server.
_renderItem(plugin) { _renderItem(plugin) {
const li = document.createElement("li"); const li = document.createElement("li");
li.className = "plugins-panel__item"; li.className = "plugins-panel__item";
li.innerHTML = ` li.innerHTML = `
<span class="plugins-panel__label"></span> <span class="plugins-panel__label"></span>
<button type="button" class="plugins-panel__run">Run for this area</button> <button type="button" class="plugins-panel__run">Run for this area</button>
${plugin.route ? `<span class="plugins-panel__route"><button type="button" class="plugins-panel__run plugins-panel__run--route">Along the trip's route</button>
<select class="plugins-panel__corridor" aria-label="How far either side of the route">${CORRIDORS_KM.map((km) => `<option value="${km}">± ${km} km</option>`).join("")}</select></span>` : ""}
<span class="plugins-panel__status"></span> <span class="plugins-panel__status"></span>
${plugin.settings?.length ? `<details class="plugins-panel__settings"><summary>Settings</summary>${plugin.settings.map(() => `<label class="plugins-panel__setting"><span></span><input type="password" autocomplete="off" spellcheck="false"><small></small></label>`).join("")}
<button type="button" class="plugins-panel__save">Save</button></details>` : ""}
`; `;
li.querySelector(".plugins-panel__label").textContent = plugin.label; li.querySelector(".plugins-panel__label").textContent = plugin.label;
const button = li.querySelector(".plugins-panel__run"); const button = li.querySelector(".plugins-panel__run");
const status = li.querySelector(".plugins-panel__status"); const status = li.querySelector(".plugins-panel__status");
button.addEventListener("click", () => this._run(plugin, button, status)); button.addEventListener("click", () => this._run(plugin, button, status));
const routeButton = li.querySelector(".plugins-panel__run--route");
if (routeButton) {
const corridor = li.querySelector(".plugins-panel__corridor");
corridor.value = localStorage.getItem(CORRIDOR_KEY) || "5";
corridor.addEventListener("change", () => localStorage.setItem(CORRIDOR_KEY, corridor.value));
routeButton.addEventListener("click", () => this._run(plugin, routeButton, status, { route: "1", corridor_km: corridor.value }));
}
const fields = [...li.querySelectorAll(".plugins-panel__setting")];
fields.forEach((label, i) => {
const field = plugin.settings[i];
label.querySelector("span").textContent = field.label || field.key;
label.querySelector("small").textContent = field.help || "";
label.querySelector("input").placeholder = plugin.set?.includes(field.key) ? "set — paste to replace" : "not set";
});
li.querySelector(".plugins-panel__save")?.addEventListener("click", async () => {
const values = Object.fromEntries(plugin.settings.map((f, i) => [f.key, fields[i].querySelector("input").value]).filter(([, v]) => v));
try {
const response = await fetch(`/api/plugins/${encodeURIComponent(plugin.name)}/settings`, { method: "PUT", headers: { "Content-Type": "application/json" }, body: JSON.stringify(values) });
const data = await response.json().catch(() => ({}));
if (!response.ok) throw new Error(data.error || `save failed: ${response.status}`);
plugin.set = data.set;
fields.forEach((label, i) => { const input = label.querySelector("input"); input.value = ""; input.placeholder = data.set.includes(plugin.settings[i].key) ? "set — paste to replace" : "not set"; });
status.textContent = "Settings saved";
status.classList.remove("plugins-panel__status--error");
} catch (err) {
status.textContent = err.message;
status.classList.add("plugins-panel__status--error");
}
});
return li; return li;
} }
async _run(plugin, button, status) { async _run(plugin, button, status, along = null) {
button.disabled = true; button.disabled = true;
status.textContent = "Running…"; status.textContent = "Running…";
try { try {
const bounds = this._map.getBounds(); const bounds = this._map.getBounds();
const body = new URLSearchParams({ const body = new URLSearchParams(along || {
south: bounds.getSouth(), south: bounds.getSouth(),
west: bounds.getWest(), west: bounds.getWest(),
north: bounds.getNorth(), north: bounds.getNorth(),
@@ -90,7 +131,7 @@ export class PluginsControl {
const data = await response.json().catch(() => ({})); const data = await response.json().catch(() => ({}));
if (!response.ok) throw new Error(data.error || `run failed: ${response.status}`); if (!response.ok) throw new Error(data.error || `run failed: ${response.status}`);
notifyGpxStoreChanged(data.path); notifyGpxStoreChanged(data.path);
status.textContent = "Done"; status.textContent = `Done · ${data.count} found`;
status.classList.remove("plugins-panel__status--error"); status.classList.remove("plugins-panel__status--error");
} catch (err) { } catch (err) {
// Plugins::RunError's message (e.g. "plugin exited with status 1") // Plugins::RunError's message (e.g. "plugin exited with status 1")
+97
View File
@@ -0,0 +1,97 @@
import { Marker } from "/vendor/maplibre-gl/maplibre-gl.mjs";
// Hovering a list item with a place (mouse), or pressing and holding it
// (touch), shows that place on the map for a moment; leaving or letting go
// puts the map back where it was. A click or tap commits: the item's own
// click handler moves the map for good, and nothing is restored.
const HOLD_MS = 400;
const RESTORE_DELAY_MS = 150; // moving straight to the next item doesn't bounce back in between
const DURATION_MS = 300;
let saved = null; // the camera before the first preview
let restoreTimer = null;
let marker = null;
const wiredMaps = new WeakSet();
// target() → { lngLat: [lon, lat] } or { bbox: [w, s, e, n] }.
export function wirePreview(map, element, target) {
// Panning the map yourself during a preview keeps where you are now.
if (!wiredMaps.has(map)) {
wiredMaps.add(map);
map.on("dragstart", commit);
}
let holdTimer = null;
let held = false;
element.addEventListener("pointerenter", (event) => {
if (event.pointerType === "mouse") show(map, target());
});
element.addEventListener("pointerleave", (event) => {
if (event.pointerType === "mouse") restoreSoon(map);
});
element.addEventListener("pointerdown", (event) => {
if (event.pointerType === "mouse") return;
held = false;
holdTimer = setTimeout(() => {
held = true;
show(map, target());
}, HOLD_MS);
});
const release = () => {
clearTimeout(holdTimer);
if (held) restoreSoon(map);
};
element.addEventListener("pointerup", release);
element.addEventListener("pointercancel", release); // the list scrolled instead
element.addEventListener("contextmenu", (event) => event.preventDefault()); // the long press is ours
// Capture, so this runs before the item's own click handler.
element.addEventListener(
"click",
(event) => {
if (held) {
// The end of a hold, not a tap.
held = false;
event.preventDefault();
event.stopImmediatePropagation();
return;
}
commit();
},
true,
);
}
function show(map, { lngLat, bbox }) {
clearTimeout(restoreTimer);
saved ||= { center: map.getCenter(), zoom: map.getZoom(), bearing: map.getBearing(), pitch: map.getPitch() };
const point = bbox && (bbox[0] !== bbox[2] || bbox[1] !== bbox[3]) ? null : lngLat || bbox.slice(0, 2);
if (point) {
map.easeTo({ center: point, zoom: Math.max(saved.zoom, 14), duration: DURATION_MS });
if (!marker) {
const element = document.createElement("div");
element.className = "search-highlight preview-highlight";
marker = new Marker({ element });
}
marker.setLngLat(point).addTo(map);
} else {
map.fitBounds(bbox, { padding: 40, maxZoom: 15, duration: DURATION_MS });
marker?.remove();
}
}
function restoreSoon(map) {
clearTimeout(restoreTimer);
restoreTimer = setTimeout(() => {
if (saved) map.easeTo({ ...saved, duration: DURATION_MS });
saved = null;
marker?.remove();
}, RESTORE_DELAY_MS);
}
function commit() {
clearTimeout(restoreTimer);
saved = null;
marker?.remove();
}
+1468
View File
File diff suppressed because it is too large. Load diff
Loaded 100 of 296 files, more files were not shown because too many files have changed in this diff. Show more