Compare commits

...
75 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 / check (push) Successful in 23s
CI / deploy (push) Successful in 18s
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 / check (push) Successful in 25s
CI / deploy (push) Successful in 17s
2026-12-05 14:36:11 +01:00
randy f85785c61d Update dependency maplibre-gl to v6.21.0
CI / check (push) Successful in 23s
CI / deploy (push) Successful in 17s
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 / check (push) Successful in 27s
CI / deploy (push) Successful in 38s
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 / check (push) Successful in 23s
CI / deploy (push) Successful in 18s
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 / check (push) Successful in 23s
CI / deploy (push) Successful in 17s
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 / check (push) Successful in 23s
CI / deploy (push) Successful in 18s
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 / check (push) Successful in 22s
CI / deploy (push) Successful in 18s
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 / check (push) Successful in 23s
CI / deploy (push) Successful in 17s
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 / check (push) Successful in 23s
CI / deploy (push) Successful in 17s
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 / check (push) Successful in 23s
CI / deploy (push) Successful in 18s
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 / check (push) Successful in 24s
CI / deploy (push) Successful in 17s
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 / check (push) Successful in 1m22s
CI / deploy (push) Successful in 17s
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 / check (push) Successful in 25s
CI / deploy (push) Successful in 17s
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 / check (push) Successful in 25s
CI / deploy (push) Successful in 17s
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 / check (push) Successful in 23s
CI / deploy (push) Successful in 2m41s
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 / check (push) Successful in 22s
CI / deploy (push) Successful in 18s
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 / check (push) Successful in 23s
CI / deploy (push) Successful in 18s
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 / check (push) Successful in 27s
CI / deploy (push) Successful in 17s
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 / check (push) Successful in 23s
CI / deploy (push) Successful in 17s
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 / check (push) Successful in 28s
CI / deploy (push) Successful in 18s
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 / check (push) Successful in 22s
CI / deploy (push) Successful in 18s
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 / check (push) Successful in 22s
CI / deploy (push) Successful in 17s
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 / check (push) Successful in 24s
CI / deploy (push) Successful in 17s
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 / check (push) Successful in 22s
CI / deploy (push) Successful in 18s
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 / check (push) Successful in 23s
CI / deploy (push) Successful in 1m37s
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 / check (push) Successful in 23s
CI / deploy (push) Successful in 18s
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 / check (push) Successful in 22s
CI / deploy (push) Successful in 17s
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 / check (push) Successful in 23s
CI / deploy (push) Successful in 17s
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 / check (push) Successful in 23s
CI / deploy (push) Successful in 47s
2026-12-02 15:16:17 +00:00
randy c101c7441f Update dependency onthegomap/planetiler to v0.11.0
CI / check (push) Successful in 25s
CI / deploy (push) Successful in 3m0s
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 / check (push) Successful in 31s
CI / deploy (push) Successful in 38s
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 / check (push) Successful in 43s
CI / deploy (push) Successful in 17s
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 / check (push) Successful in 21s
CI / deploy (push) Successful in 17s
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 / check (push) Successful in 22s
CI / deploy (push) Successful in 17s
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 / check (push) Successful in 21s
CI / deploy (push) Successful in 17s
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 / check (push) Successful in 21s
CI / deploy (push) Successful in 17s
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 / check (push) Successful in 21s
CI / deploy (push) Successful in 17s
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 / check (push) Successful in 24s
CI / deploy (push) Successful in 17s
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 / check (push) Successful in 23s
CI / deploy (push) Successful in 17s
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 / check (push) Successful in 21s
CI / deploy (push) Successful in 18s
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 / check (push) Successful in 22s
CI / deploy (push) Successful in 18s
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 / check (push) Successful in 21s
CI / deploy (push) Successful in 17s
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 / check (push) Successful in 22s
CI / deploy (push) Successful in 17s
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 / check (push) Successful in 22s
CI / deploy (push) Successful in 18s
2026-11-30 20:00:39 +01:00
randy 4c58c9351f Update dependency rubyzip to v3.7.1
CI / check (push) Successful in 27s
CI / deploy (push) Successful in 37s
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 / check (push) Successful in 23s
CI / deploy (push) Successful in 17s
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 / check (push) Successful in 22s
CI / deploy (push) Successful in 18s
2026-11-30 19:26:32 +01:00
randy e03e426eb6 SELF_UPDATE passed into the container
CI / check (push) Successful in 21s
CI / deploy (push) Successful in 18s
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 / check (push) Successful in 22s
CI / deploy (push) Successful in 17s
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 / check (push) Successful in 22s
CI / deploy (push) Successful in 18s
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 / check (push) Successful in 22s
CI / deploy (push) Successful in 17s
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 / check (push) Successful in 23s
CI / deploy (push) Successful in 17s
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 / check (push) Successful in 24s
CI / deploy (push) Successful in 17s
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 / check (push) Successful in 21s
CI / deploy (push) Successful in 17s
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 / check (push) Successful in 21s
CI / deploy (push) Successful in 23s
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 / check (push) Successful in 22s
CI / deploy (push) Successful in 17s
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 / check (push) Successful in 21s
CI / deploy (push) Successful in 17s
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 / check (push) Successful in 20s
CI / deploy (push) Successful in 17s
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 / check (push) Successful in 42s
CI / deploy (push) Successful in 18s
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 / check (push) Successful in 22s
CI / deploy (push) Successful in 18s
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 / check (push) Successful in 22s
CI / deploy (push) Successful in 18s
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 / check (push) Successful in 20s
CI / deploy (push) Successful in 17s
2026-11-27 22:48:46 +01:00
91 changed files with 14965 additions and 1187 deletions

No files matched your search

+1
View File
@@ -5,3 +5,4 @@ data
.ruby-lsp
.env
node_modules
can-recorder/target
+1
View File
@@ -118,6 +118,7 @@ jobs:
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
chmod 600 /srv/podman/maptool/.env
+3
View File
@@ -68,3 +68,6 @@
/REVISION
node_modules/
# can-recorder's cargo build
/can-recorder/target/
+11 -1
View File
@@ -1,3 +1,11 @@
# 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
# 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.
@@ -47,10 +55,12 @@ RUN set -eux; \
# unlike go-pmtiles above. Default PLANETILER_JAR path (pmtiles_builder.rb)
# expects it here.
# 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" \
-o /usr/local/lib/planetiler.jar
COPY --from=can-recorder /src/target/release/can-recorder /usr/local/bin/can-recorder
WORKDIR /app
COPY Gemfile Gemfile.lock ./
+6 -6
View File
@@ -65,7 +65,7 @@ GEM
snaky_hash (~> 2.0, >= 2.0.9)
version_gem (~> 1.1, >= 1.1.17)
prism (1.9.0)
puma (8.1.3)
puma (8.1.4)
nio4r (~> 2.0)
rack (3.2.8)
rack-protection (4.2.2)
@@ -81,8 +81,8 @@ GEM
ffi (~> 1.0)
rerun (0.14.0)
listen (~> 3.0)
rexml (3.4.4)
rubyzip (3.7.0)
rexml (3.4.5)
rubyzip (3.7.1)
sinatra (4.2.2)
logger (>= 1.6.0)
mustermann (~> 3.0)
@@ -177,7 +177,7 @@ CHECKSUMS
nio4r (2.7.5) sha256=6c90168e48fb5f8e768419c93abb94ba2b892a1d0602cb06eef16d8b7df1dca1
oauth2 (2.1.0) sha256=69925a45030c231cdca3ef4a54a8e848e5319f12c3fdbbfa5065dfbeb4efe835
prism (1.9.0) sha256=7b530c6a9f92c24300014919c9dcbc055bf4cdf51ec30aed099b06cd6674ef85
puma (8.1.3) sha256=a12de11fb2f20f8a3ef25a5b1447eabe7142846719eeb9672ee8ec0705b8c3a8
puma (8.1.4) sha256=71859def3f0e055cd10307b608eb629b58d318b38af2e6fbb3aa6f8846c4b912
rack (3.2.8) sha256=1fecc85e463ebc7a2a945fff829ffcd549babeb1556384796fad946c28dc4ec7
rack-protection (4.2.2) sha256=0e75764dae462c4041544452ce568bb1f1ced556b791cd32ac479d0781065a99
rack-session (2.1.2) sha256=595434f8c0c3473ae7d7ac56ecda6cc6dfd9d37c0b2b5255330aa1576967ffe8
@@ -185,8 +185,8 @@ CHECKSUMS
rb-fsevent (0.11.2) sha256=43900b972e7301d6570f64b850a5aa67833ee7d87b458ee92805d56b7318aefe
rb-inotify (0.11.1) sha256=a0a700441239b0ff18eb65e3866236cd78613d6b9f78fea1f9ac47a85e47be6e
rerun (0.14.0) sha256=996a5af2b2b34dcb30146c6c728addab9113e07c119003370daa9bf27feb88fd
rexml (3.4.4) sha256=19e0a2c3425dfbf2d4fc1189747bdb2f849b6c5e74180401b15734bc97b5d142
rubyzip (3.7.0) sha256=65c19294da75297a939006f3516deacc33185fbd721ff1954f7a231db6d3e121
rexml (3.4.5) sha256=65533089925a7cdfd416ba865d44f5bb1d13e106a3d7f2551de678e7bcd3be24
rubyzip (3.7.1) sha256=483aa0f698822a290c0edf2aee6f41bc80870878cb5cd74af03b48d006c85e9e
sinatra (4.2.2) sha256=3a0e63c600eb65d7ad6fa0d597a9533f2870d1862cc63ab7b0f7f0ad449ad42f
sinatra-contrib (4.2.2) sha256=3d629cfb3647e363cfca6609d0dcde63aa45db664645fe947f0eeddb9cca1620
snaky_hash (2.0.9) sha256=e93e6ec80632f8c8c4a3fe6e25d51eaef253e0e58dc7100f0f8370320feb3128
+426 -21
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] 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
* [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] 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] 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] 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)
@@ -85,16 +91,97 @@ independence from connectivity.
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.
* [ ] Touch targets ≥ 44 px (tree rows, panel buttons, icon grids)
* [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
* [ ] Nothing reachable only by hover — tooltips and flyouts must open on tap too
* [ ] A touch substitute for the Alt+click debug inspector (e.g. long-press)
* [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
* [ ] 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
* [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
** [ ] The rest of the UI is still one invert+dim filter — CSS color tokens and a real dark set instead
** [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
@@ -157,22 +244,322 @@ already reaches the home MQTT broker (`mqtt_ext`) from ESPHome nodes in `~/espho
* [ ] 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
* [ ] Later in the van: CANopen (or plain CAN with own IDs) to the server, a small CAN → MQTT
bridge on the host (SocketCAN; `can0` lives in the host's network namespace), maptool stays
on MQTT
* [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
** [ ] Real 3D relief from the raster-dem terrain and Liberty's `building-3d` extrusions while navigating
* [ ] While following a planned route: the route ahead highlighted, distance to the next
maneuver from Valhalla's directions
** [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
* [ ] 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
* [ ] Plot GPS track with historical battery/speed data
@@ -183,15 +570,30 @@ server into the car (on the car's Wi-Fi, next to the MQTT broker) makes everythi
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
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
* [ ] 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
* [ ] 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 (USB touchscreen, Chromium in kiosk mode on
* [ ] 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
@@ -210,11 +612,12 @@ already offline work on the road. The Pi only serves; heavy builds stay on brick
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
* [ ] Hardware buttons: keyboard shortcuts in the page (zoom, Navigate, night mode, …) — the
cheap way with any BLE/USB keypad that sends plain keys
* [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 (SocketCAN `can0`) → the small CAN → MQTT bridge on the host (see "Later in the
van" above; NMT start, key bitmap from `0x180+node`, LEDs via `0x200+node`) → maptool → the
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)
@@ -227,3 +630,5 @@ already offline work on the road. The Pi only serves; heavy builds stay on brick
* [ ] 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) —
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)
+887 -22
View File
File diff suppressed because it is too large. Load diff
+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 ]
+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)"
+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
}
+21 -6
View File
@@ -43,9 +43,9 @@ services:
# as the other optional secrets here. P4N_USER/P4N_PASSWORD alone
# don't actually work here — park4night's login form is behind
# invisible reCAPTCHA, which no browserless login can satisfy — so
# P4N_SESSION_COOKIE (a real logged-in browser's session cookie,
# copied out by hand and refreshed whenever it expires) is what
# p4n2gpx.rb's make_session actually ends up using.
# the cookies of a Firefox logged in on the host (the plugin's own
# firefox_cookie.py on a host timer, docs/deployment.adoc) or P4N_SESSION_COOKIE (a browser's Cookie header, by hand —
# also settable in the plugins panel) are what it ends up using.
P4N_USER: ${P4N_USER:-}
P4N_PASSWORD: ${P4N_PASSWORD:-}
P4N_SESSION_COOKIE: ${P4N_SESSION_COOKIE:-}
@@ -64,6 +64,15 @@ services:
# 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:
# Uploaded GPX files and the offline PMTiles extract — kept outside
# the image so a rebuild/redeploy doesn't wipe them (see
@@ -89,7 +98,8 @@ services:
# SELinux and the backup tree is unlabeled_t, unreadable for a
# container; the root sync job is unaffected by the relabel and new
# files inherit the directory's label.
- /srv/backup/gdrive/my-drive/current/Takeout:/app/takeout:ro,z
# TAKEOUT_HOST_DIR: another server (the car's) points it at an empty dir.
- ${TAKEOUT_HOST_DIR:-/srv/backup/gdrive/my-drive/current/Takeout}:/app/takeout:ro,z
# 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 —
@@ -97,8 +107,11 @@ services:
# offline.pmtiles/terrain.pmtiles). On the default compose network (not
# network_mode: "service:maptool" — KIWIX_URL above reaches it by this
# service's own name), so maptool and kiwix stay independent containers.
# Keeps restarting (harmlessly) if data/kiwix/wikipedia.zim isn't there
# yet — GET /api/kiwix just reports unavailable until it comes up.
# Waits (entrypoint below) while data/kiwix/wikipedia.zim is missing or
# 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 —
# deliberately, so data/kiwix/wikipedia.zim can be a symlink to wherever
@@ -123,6 +136,8 @@ services:
# this same prefix off incoming request paths, so both ends agree on
# it) — no ports: mapping needed, nothing outside the compose network
# 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"]
volumes:
# :z, shared for the same reason as maptool's own ./data mount above.
+287
View File
@@ -175,6 +175,293 @@ 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.
== The car's server (rpi-dev, later the van's CM5)
A second maptool on a Raspberry Pi (Debian, arm64, rootful podman +
podman-compose), laid out like brick's: `/srv/podman/maptool/{build,data,.env}`,
the same `podman-compose@.service` unit. Deployed by hand for now (the
working tree rsynced into `build/`), not by CI.
Its `.env` adds:
* `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
`POST /api/livetrack/session` (`session_id`, `session_token`, `secret` form
+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).
+7
View File
@@ -165,6 +165,13 @@ Offline routing runs https://github.com/valhalla/valhalla[Valhalla]
(`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
Docker image (not a separate container the way kiwix-serve is —
see `docs/deployment.adoc`/`docs/development.adoc`): three CLI tools
+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
+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
+6 -1
View File
@@ -117,9 +117,14 @@ module Maptool
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 { |c| add_text(trkseg.add_element("trkpt", position_attributes(c)), "ele", c[2]) }
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
+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
+86 -1
View File
@@ -209,7 +209,7 @@ module Maptool
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
type == "layer" ? @gpx_store.resolve_file(source) : File.join(@sources_dir, source)
source_file(type, source)
end
# --- writes -------------------------------------------------------------
@@ -457,8 +457,93 @@ module Maptool
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
+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
+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"],
].freeze
# bbox: [south, west, north, east] (Overpass's own axis order).
def self.fetch(bbox, timeout: 60)
query = build_query(bbox, timeout: timeout)
# bbox: [south, west, north, east] (Overpass's own axis order); or
# around: [radius m, [[lon, lat], ...]] — a corridor along a line.
def self.fetch(bbox, timeout: 60, around: nil)
query = build_query(bbox, timeout: timeout, around: around)
errors = OVERPASS_APIS.map do |url|
return post(URI(url), query, timeout)
rescue FetchError, Net::OpenTimeout, Net::ReadTimeout, SystemCallError, SocketError, OpenSSL::SSL::SSLError, JSON::ParserError => e
@@ -83,8 +84,13 @@ module Maptool
JSON.parse(response.body)
end
def self.build_query(bbox, timeout: 60)
bbox_str = bbox.join(",")
def self.build_query(bbox, timeout: 60, around: nil)
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|
conditions = tags.map { |k, v| %(["#{k}"="#{v}"]) }.join
"node#{conditions}(#{bbox_str});"
+49 -9
View File
@@ -1,5 +1,6 @@
require "json"
require "open3"
require "fileutils"
module Maptool
# 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|
name = File.basename(File.dirname(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
nil
end
end.uniq { |plugin| plugin["name"] }.sort_by { |p| p["label"] }
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
# non-zero exit, or output that isn't a GeoJSON FeatureCollection — so
# the route can turn it into a single error response without knowing
# 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
# as list's `uniq` above.
def self.run(dirs, name, bbox)
raise RunError, "unknown plugin" unless name =~ NAME_PATTERN
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
def self.run(dirs, name, bbox, route: nil, corridor_km: nil, env: {})
plugin_dir = find(dirs, name)
manifest_path = File.join(plugin_dir, "plugin.json")
command = begin
@@ -64,8 +103,9 @@ module Maptool
south, west, north, east = bbox
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
# message (e.g. "...: unexpected response 406"), the only clue to why.
unless status.success?
+164 -12
View File
@@ -177,10 +177,16 @@ module Maptool
{ 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.
VEHICLE_LIMITS = { height: 1..6, width: 1..4, length: 2..25, weight: 0.5..60, speed: 1..60, hills: 0..1, sac: 1..6 }.freeze
# 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
@@ -228,7 +234,8 @@ module Maptool
[key, value]
end
{ id: id, name: name, type: type, bicycle_type: bicycle_type, **limits }.compact
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
@@ -236,6 +243,34 @@ module Maptool
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).
@@ -246,27 +281,83 @@ module Maptool
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")
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: (countries(valhalla_url, legs, costing, options) if %w[auto truck].include?(costing)),
maneuvers: legs.flat_map { |leg| leg["maneuvers"].map { |m| { text: m["instruction"], km: m["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
# [{ code: "AT", km:, motorway_km:, toll_km: }, ...] in route order, from
# Valhalla's per-edge attributes. nil if that lookup fails: it's extra.
def self.countries(valhalla_url, legs, costing, options)
# 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 node.admin_index admin.country_code], action: "include" })
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] || "?"
@@ -274,13 +365,72 @@ module Maptool
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
totals.values.each { |row| row.transform_values! { |v| v.is_a?(Float) ? v.round(1) : v } }
{ 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 :countries
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
@@ -315,6 +465,8 @@ module Maptool
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
+4 -1
View File
@@ -60,7 +60,10 @@ module Maptool
def self.query(text, library:, data_dir:, sources: SOURCES.keys, center: nil, kiwix_url: "")
words = normalize(text).split
return [] if words.empty?
# 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|
+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
+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
+21 -31
View File
@@ -9,7 +9,7 @@
"@mdi/js": "7.4.47",
"flag-icons": "7.6.0",
"maplibre-contour": "0.2.0",
"maplibre-gl": "6.19.0",
"maplibre-gl": "6.21.0",
"maplibre-gl-lanes": "1.7.0",
"pmtiles": "4.5.0",
"suncalc": "2.1.4"
@@ -59,9 +59,9 @@
}
},
"node_modules/@maplibre/geojson-vt": {
"version": "6.3.3",
"resolved": "https://registry.npmjs.org/@maplibre/geojson-vt/-/geojson-vt-6.3.3.tgz",
"integrity": "sha512-sfftN4326foT7uex0aN0jqr+vq/lfgeTfASOd+kvdUd0uMMIgXZDPdntCazKFKKcxPH002NPCy4j396peanWCg==",
"version": "7.0.1",
"resolved": "https://registry.npmjs.org/@maplibre/geojson-vt/-/geojson-vt-7.0.1.tgz",
"integrity": "sha512-xq3+TiG4hZtx9lHjq/oZginEBtJLJTJqRVmEIhPDSznlkl231z/p4foorEqASpD233EHO9+GVnnu6GNA4Pl+YQ==",
"dev": true,
"license": "ISC",
"dependencies": {
@@ -69,9 +69,9 @@
}
},
"node_modules/@maplibre/maplibre-gl-style-spec": {
"version": "26.8.0",
"resolved": "https://registry.npmjs.org/@maplibre/maplibre-gl-style-spec/-/maplibre-gl-style-spec-26.8.0.tgz",
"integrity": "sha512-EClj+0m624zGw5gdCOsI5f88bYzkXfgoP2Sj5VGs2AYg9hZaPxvCumX5KDDs6aKFwl2ut+3jAeLhvrSz7hEsBQ==",
"version": "27.1.0",
"resolved": "https://registry.npmjs.org/@maplibre/maplibre-gl-style-spec/-/maplibre-gl-style-spec-27.1.0.tgz",
"integrity": "sha512-8EkIhwOdhjhX6HdugboL0JEGQejqln7Xuve7X2sFFU35IUaCgucHRuuO0+0yWSzYEmEa/z4knkpwOYZdrF/wFA==",
"dev": true,
"license": "ISC",
"dependencies": {
@@ -89,9 +89,9 @@
}
},
"node_modules/@maplibre/mlt": {
"version": "1.3.0",
"resolved": "https://registry.npmjs.org/@maplibre/mlt/-/mlt-1.3.0.tgz",
"integrity": "sha512-7M2O7ABM80Oi8XPkfkrjKB8mOBIxGoVgkA52Mu4RMWoBvvMdagQ522+WxVYujZsMpqIr3BpzrTbXrm4k8lCzCQ==",
"version": "1.4.0",
"resolved": "https://registry.npmjs.org/@maplibre/mlt/-/mlt-1.4.0.tgz",
"integrity": "sha512-kDjapA8mGAkSAAZr+ZF875w38PdJg7xS79oEADD7S/QdXELmd4hNHgZR/o5WRkWLBgWjKHJdHj/yRyYmU9Inbg==",
"dev": true,
"license": "(MIT OR Apache-2.0)",
"dependencies": {
@@ -184,9 +184,9 @@
"license": "BSD-3-Clause"
},
"node_modules/maplibre-gl": {
"version": "6.19.0",
"resolved": "https://registry.npmjs.org/maplibre-gl/-/maplibre-gl-6.19.0.tgz",
"integrity": "sha512-3bOrnfddggUYudLGJFsYFvqulUyvSxy4iQzd/uURI7ZhgYEZifdSrECujRSghaCpc+v/ZsFI0Y6ZsGSilEtE+w==",
"version": "6.21.0",
"resolved": "https://registry.npmjs.org/maplibre-gl/-/maplibre-gl-6.21.0.tgz",
"integrity": "sha512-mjMFzw99R1kvuWo3xj6XKcFFbVpwTPhO7g2TeyJyT5DdM1E6zKIC/uWG17WpXO6dnRFZ/3un9k44+KtDNjD2Hw==",
"dev": true,
"license": "BSD-3-Clause",
"dependencies": {
@@ -194,9 +194,9 @@
"@mapbox/tiny-sdf": "^2.3.0",
"@mapbox/unitbezier": "^1.0.0",
"@mapbox/vector-tile": "^3.0.0",
"@maplibre/geojson-vt": "^6.3.1",
"@maplibre/maplibre-gl-style-spec": "^26.8.0",
"@maplibre/mlt": "^1.3.0",
"@maplibre/geojson-vt": "^7.0.1",
"@maplibre/maplibre-gl-style-spec": "^27.0.0",
"@maplibre/mlt": "^1.4.0",
"@maplibre/vt-pbf": "^4.3.3",
"@types/geojson": "^7946.0.16",
"bidi-js": "^1.1.0",
@@ -204,7 +204,7 @@
"gl-matrix": "^3.4.4",
"kdbush": "^4.1.0",
"murmurhash-js": "^1.0.0",
"pbf": "^5.1.2",
"pbf": "^5.2.1",
"potpack": "^2.1.0",
"quickselect": "^3.0.0",
"tinyqueue": "^3.0.0",
@@ -249,13 +249,13 @@
"license": "MIT"
},
"node_modules/pbf": {
"version": "5.1.2",
"resolved": "https://registry.npmjs.org/pbf/-/pbf-5.1.2.tgz",
"integrity": "sha512-mnvGdvOrIvJOBGUEdGkrVXjN8E/VkIJCkf2eS1DH2yv82ORUlLttmDt0rWY38yYZmVwciZwBUvHM20qxBZf40w==",
"version": "5.2.1",
"resolved": "https://registry.npmjs.org/pbf/-/pbf-5.2.1.tgz",
"integrity": "sha512-5s6y6g3akGMF98eemb+3QZAWTCUHyox40TJOwcY4M1w40RvoXrfbRUVmY02RlRiEPyE6KVaM0xxfF4+4vjSJTQ==",
"dev": true,
"license": "BSD-3-Clause",
"dependencies": {
"resolve-protobuf-schema": "^2.1.0"
"protocol-buffers-schema": "^3.6.1"
},
"bin": {
"pbf": "bin/pbf"
@@ -302,16 +302,6 @@
"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": {
"version": "2.1.4",
"resolved": "https://registry.npmjs.org/suncalc/-/suncalc-2.1.4.tgz",
+1 -1
View File
@@ -6,7 +6,7 @@
"@mdi/js": "7.4.47",
"flag-icons": "7.6.0",
"maplibre-contour": "0.2.0",
"maplibre-gl": "6.19.0",
"maplibre-gl": "6.21.0",
"maplibre-gl-lanes": "1.7.0",
"pmtiles": "4.5.0",
"suncalc": "2.1.4"
+2 -1
View File
@@ -1,4 +1,5 @@
{
"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
# 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/corridor"
args = ARGV.to_h { |arg| arg.sub(/\A--/, "").split("=", 2) }
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))
+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
+2084 -297
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" }
]
}
+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}`;
}
}
+6 -70
View File
@@ -1,28 +1,9 @@
import { DEBUG_ICON } from "/js/icons.js";
import { escapeHtml } from "/js/gpx.js";
import { notifySidePanelOpen, onlyOneSidePanelOpen } from "/js/panels.js";
// Every read-only status endpoint, dumped as raw JSON. No check-update
// routes here — those reach out to Geofabrik/the internet, not just report
// local state.
const ENDPOINTS = [
"/api/health",
"/api/offline-tiles",
"/api/offline-tiles/build-status",
"/api/offline-regions",
"/api/offline-tiles/cache",
"/api/terrain-tiles",
"/api/terrain-tiles/build-status",
"/api/build-history",
"/api/hiking-trails",
"/api/kiwix",
"/api/plugins",
"/api/gnss/position",
"/api/livetrack/sessions",
];
const REFRESH_MS = 5000; // while open — a running build's progress shows up live
// Sidebar icon pinned to the bottom of the rail, logged-in only (map.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");
@@ -32,9 +13,8 @@ export class DebugControl {
this._icon.addEventListener("click", () => this._togglePanel());
this._panel = document.getElementById("debug-panel");
this._body = this._panel.querySelector(".debug-panel__body");
this._panel.querySelector(".basemap-panel__close").addEventListener("click", () => this._togglePanel(false));
onlyOneSidePanelOpen(this._panel, () => this._stop());
onlyOneSidePanelOpen(this._panel, () => this._icon.classList.remove("active"));
sidebar.appendChild(this._container);
}
@@ -42,51 +22,7 @@ export class DebugControl {
_togglePanel(force) {
const open = force === undefined ? this._panel.hidden : force;
this._panel.hidden = !open;
if (!open) return this._stop();
this._icon.classList.add("active");
notifySidePanelOpen(this._panel);
this._refresh();
this._timer = setInterval(() => this._refresh(), REFRESH_MS);
}
_stop() {
this._icon.classList.remove("active");
clearInterval(this._timer);
}
async _refresh() {
const sections = await Promise.all(
ENDPOINTS.map(async (url) => {
let text;
try {
const response = await fetch(url);
const body = await response.text();
try {
text = JSON.stringify(JSON.parse(body), null, 2);
} catch {
text = body;
}
if (!response.ok) text = `HTTP ${response.status}\n${text}`;
} catch (error) {
text = `request failed: ${error.message}`;
}
return { url, text };
}),
);
if (this._panel.hidden) return;
// Keep whichever sections the user collapsed collapsed across refreshes.
const closed = new Set([...this._body.querySelectorAll("details:not([open])")].map((el) => el.dataset.url));
this._body.innerHTML = sections
.map(
({ url, text }) => `
<details data-url="${url}" ${closed.has(url) ? "" : "open"}>
<summary>${url}</summary>
<pre>${escapeHtml(text)}</pre>
</details>
`,
)
.join("");
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
// falling outside a partial offline extract's zoom range.
export async function elevationAt(lng, lat, offlineAvailable) {
const { tileX, tileY, fracX, fracY } = lngLatToTile(lng, lat, DEM_ZOOM);
const tile = await fetchTile(DEM_ZOOM, tileX, tileY, offlineAvailable);
// smooth: bilinear between the four pixels around the point (within the
// tile) instead of the nearest one — for slopes over a few meters, where
// 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;
const px = Math.min(tile.size - 1, Math.floor(fracX * tile.size));
const py = Math.min(tile.size - 1, Math.floor(fracY * tile.size));
return tile.elevations[py * tile.size + px];
const { elevations: e, size } = tile;
if (!smooth) {
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");
}
+147 -9
View File
@@ -1,9 +1,13 @@
import { Marker } from "/vendor/maplibre-gl/maplibre-gl.mjs";
import { GNSS_ICON } from "/js/icons.js";
import { isLoggedIn } from "/js/auth.js";
import { onGnssFollow } from "/js/panels.js";
const POSITION_URL = "/api/gnss/position";
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 (the car's receiver, fed
// server-side into GNSS_LATEST in app.rb) and shows the fix as a
@@ -14,16 +18,118 @@ const POLL_INTERVAL_MS = 1500;
// 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).
export function followPosition(map, lngLat, heading, speed) {
// 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 {
constructor(map) {
this._map = map;
@@ -55,6 +161,7 @@ export class GnssControl {
this._flyout = this._container.querySelector(".sidebar-flyout");
this._status = this._container.querySelector(".gnss-control__status");
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
// here rather than shown and failing on click, same reasoning as
@@ -103,15 +210,18 @@ export class GnssControl {
return;
}
this._status.textContent = fixLabel(data);
// no fix, carried along the route (a tunnel: App.gnss_position)
this._status.textContent = data.estimated ? "estimated (no fix)" : fixLabel(data);
const lngLat = [data.lon, data.lat];
// Recenters on every fix while enabled — this is the app's own
// receiver, so "GNSS on" means "follow it", the same way LocateControl
// (public/js/locate.js) follows it when GNSS is what it's using too.
// flyTo (with its zoom swoop) only for the first fix, since that's the
// one jumping from wherever the map already was; easeTo for later
// updates, a plain follow rather than repeating that swoop every poll.
// startFollow (zooming in) only for the first fix, since that's the
// one jumping from wherever the map already was; a plain follow for
// later updates, zooming by the speed (autoZoom).
const far = this._marker && distanceM(this._marker.getLngLat(), lngLat) > JUMP_M;
if (far) this._removeMarker();
if (!this._marker) {
const el = document.createElement("div");
el.className = "gnss-marker";
@@ -119,15 +229,43 @@ export class GnssControl {
// style's sources/layers, so — unlike the radar/GPX layers — this
// survives map.setStyle() (switching Online/Offline) with no extra
// re-add handling needed.
this._marker = new Marker({ element: el }).setLngLat(lngLat).addTo(this._map);
this._map.flyTo({ center: lngLat, zoom: Math.max(this._map.getZoom(), 15) });
this._marker = new Marker({ element: el, rotationAlignment: "map", pitchAlignment: "map" }).setLngLat(lngLat).addTo(this._map);
startFollow(this._map, lngLat);
} else {
this._marker.setLngLat(lngLat);
followPosition(this._map, lngLat, data.track, data.speed);
glideMarker(this._marker, lngLat, POLL_INTERVAL_MS);
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() {
this._tag?.remove();
this._tag = null;
if (this._marker) {
this._marker.remove();
this._marker = null;
+352 -167
View File
@@ -4,10 +4,8 @@ import {
GPX_ICON,
NEW_FOLDER_ICON,
UPLOAD_ICON,
WAYPOINT_ICON,
TRACK_ICON,
ROUTE_ICON,
DOWNLOAD_ICON,
SYNC_ICON,
MAP_MARKER_ICON,
POI_ICONS,
PARK4NIGHT_TAGS,
@@ -30,13 +28,25 @@ const POI_ICON_KEYS = Object.keys(POI_ICONS);
const POI_ICON_IMAGE_SIZE = 48; // rasterized once at this size, rendered much smaller by icon-size below
const POI_ICON_SIZE = 0.3; // 48 * 0.3 = ~14px, sized to sit inside the marker badge below
const MAP_MARKER_SIZE = 0.55;
// The clusters as the same rounded-square badge, light -> dark by count
// (16 / 20 / 26 px "radius" before, now that half the side).
const CLUSTER_COLORS = ["#a8c8ea", "#5b9bd5", "#2e6da4"];
const BADGE_IMAGE_PREFIX = "badge-"; // one registered image per distinct badge color actually seen, see _registerBadgeColors
// Custom drag payload MIME type for moving an already-uploaded file between
// folders, as opposed to an OS file drag (type "Files") for uploading a new
// one — both land on the same drop targets, told apart by this.
const MOVE_MIME = "application/x-gpx-path";
const FOLDER_DRAG_PREFIX = "folder:"; // a dragged folder's MOVE_MIME payload, vs. a node key
const GPX_VISIBLE_KEY = "gpxVisible";
// The kinds the Library filters by: chip label, a row's word for one, glyph and colour.
const KINDS = {
waypoint: { label: "Points", one: "points", glyph: "●", color: "#12bedf" },
track: { label: "Tracks", one: "track", glyph: "〰", color: "#c2410c" },
route: { label: "Routes", one: "route", glyph: "↝", color: "#1d6fdc" },
layer: { label: "Layers", one: "layer", glyph: "▤", color: "#6b6b66" },
};
const FOLDER_DRAG_PREFIX = "folder:";
const plural = (n, word) => `${n} ${word}${n === 1 ? "" : "s"}`; // a dragged folder's MOVE_MIME payload, vs. a node key
// A sidebar icon that opens a side panel for uploading GPX files (via
// drag & drop, stored server-side in a folder hierarchy the user can add to
@@ -117,7 +127,7 @@ export class GpxPanelControl {
mount(sidebar) {
this._container = document.createElement("div");
this._container.className = "sidebar-item";
this._container.innerHTML = `<button type="button" class="sidebar-icon" title="Tracks &amp; Points" aria-label="Tracks &amp; Points">${GPX_ICON}</button>`;
this._container.innerHTML = `<button type="button" class="sidebar-icon" title="Library" aria-label="Library">${GPX_ICON}</button>`;
this._icon = this._container.querySelector(".sidebar-icon");
this._icon.addEventListener("click", () => this._togglePanel());
@@ -134,6 +144,17 @@ export class GpxPanelControl {
// The top level's own items have no folder row with a menu of its own.
const close = this._panel.querySelector(".gpx-panel__close");
close.before(this._menuButton(DOWNLOAD_ICON, "Export the top level", this._exportEntries("", "MapTool")));
// A sync client (the car's server) syncs with the main one on demand.
if ("syncClient" in this._panel.dataset) {
const sync = document.createElement("button");
sync.type = "button";
sync.className = "gpx-panel__action";
sync.title = "Sync with the main server";
sync.setAttribute("aria-label", sync.title);
sync.innerHTML = SYNC_ICON;
sync.addEventListener("click", () => this._sync(sync));
close.before(sync);
}
}
this._panel
.querySelector(".gpx-panel__close")
@@ -149,6 +170,7 @@ export class GpxPanelControl {
// panels.
document.addEventListener("click", () => this._closeDownloadMenu());
this._setupFind();
this._setupToolbarActions();
this._setupRootDropTarget();
this._setupMapDropTarget();
@@ -171,13 +193,13 @@ export class GpxPanelControl {
_setupToolbarActions() {
const fileInput = this._panel.querySelector(".gpx-file-input");
fileInput.addEventListener("change", () => {
this._uploadFiles(fileInput.files, "");
this._uploadFiles(fileInput.files, this._cwd);
fileInput.value = "";
});
this._panel.querySelector('[data-action="upload"]').addEventListener("click", () => fileInput.click());
this._panel.querySelector('[data-action="new-folder"]').addEventListener("click", async () => {
const path = window.prompt("New folder name (e.g. Hiking/2026):");
const path = window.prompt("New folder name (e.g. Hiking/2026):", this._cwd ? `${this._cwd}/` : "");
if (!path || !path.trim()) return;
const response = await fetch(FOLDER_URL, {
@@ -210,11 +232,11 @@ export class GpxPanelControl {
event.preventDefault();
this._treeContainer.classList.remove("gpx-drop-hover");
if (event.dataTransfer.files?.length > 0) {
this._uploadFiles(event.dataTransfer.files, "");
this._uploadFiles(event.dataTransfer.files, this._cwd);
return;
}
const from = event.dataTransfer.getData(MOVE_MIME);
if (from) this._moveFile(from, "");
if (from) this._moveFile(from, this._cwd);
});
}
@@ -245,67 +267,266 @@ export class GpxPanelControl {
this._renderTree(tree);
}
// The Design canvas' Library (after Locus Map): find on top — the text,
// what kinds, only the shown ones — then one folder level at a time (← up,
// the path), or, while searching or in List view, every match flat with
// the folder it lives in. An eye per row: ● shown, ◐ some (a folder), ○ not.
_renderTree(node) {
this._root = node;
this._files = new Map();
const index = (n) => (n.children || []).forEach((c) => (c.type === "folder" ? index(c) : this._files.set(c.path, c)));
index(node);
this._treeContainer.innerHTML = "";
this._treeContainer.appendChild(this._renderChildren(node.children));
}
_renderChildren(children) {
const ul = document.createElement("ul");
if (children.length === 0) {
const li = document.createElement("li");
li.className = "gpx-tree__empty";
li.textContent = "No files yet";
ul.appendChild(li);
return ul;
}
children.forEach((child) => {
const li = document.createElement("li");
if (child.type === "folder") {
li.appendChild(this._renderFolder(child));
} else if (child.points) {
li.appendChild(this._renderTrackWithPoints(child));
this._folders = new Map([["", node]]);
const index = (n) => (n.children || []).forEach((c) => {
if (c.type === "folder") {
this._folders.set(c.path, c);
index(c);
} else {
li.appendChild(this._renderFile(child));
c.folder = n.path;
this._files.set(c.path, c);
}
ul.appendChild(li);
});
return ul;
index(node);
if (!this._folders.has(this._cwd ?? "")) this._cwd = "";
if (this._openTrack && !this._files.has(this._openTrack)) this._openTrack = null;
this._renderView();
}
// A track/route holding points: collapsed by default (there can be many),
// each point zooms to itself and can be taken out again.
_renderTrackWithPoints(file) {
this._openTracks ||= new Set();
const details = document.createElement("details");
details.className = "gpx-tree__track";
details.open = this._openTracks.has(file.path);
details.addEventListener("toggle", () => (details.open ? this._openTracks.add(file.path) : this._openTracks.delete(file.path)));
const summary = document.createElement("summary");
summary.appendChild(this._renderFile(file));
details.appendChild(summary);
_setupFind() {
this._cwd = "";
this._query = "";
this._mode = "folders";
this._kindsOn = new Set(Object.keys(KINDS));
this._shownOnly = false;
const find = this._panel.querySelector(".lib-find");
const input = find.querySelector(".lib-find__input");
input.addEventListener("input", () => {
this._query = input.value.trim().toLowerCase();
this._renderView();
});
find.querySelector(".lib-find__kinds").addEventListener("click", (event) => {
const chip = event.target.closest("[data-kind]");
if (!chip) return;
const kind = chip.dataset.kind;
if (this._kindsOn.has(kind) && this._kindsOn.size > 1) this._kindsOn.delete(kind);
else this._kindsOn.add(kind);
this._renderView();
});
find.querySelector('[data-find="shown"]').addEventListener("click", () => {
this._shownOnly = !this._shownOnly;
this._renderView();
});
find.querySelectorAll("[data-mode]").forEach((button) => button.addEventListener("click", () => {
this._mode = button.dataset.mode;
this._renderView();
}));
this._crumb = this._panel.querySelector(".lib-crumb");
this._footer = this._panel.querySelector(".lib-foot__text");
this._panel.querySelector('[data-action="hide-all"]').addEventListener("click", () => {
[...this._visible].forEach((path) => this._toggleFileOnly(path, false));
this._saveVisible();
this._renderView();
});
}
_kindOf(file) {
if (file.layer) return "layer";
if (file.kinds?.includes("route")) return "route";
if (file.kinds?.includes("track")) return "track";
return "waypoint";
}
_matches(file) {
if (!this._kindsOn.has(this._kindOf(file))) return false;
if (this._shownOnly && !this._visible.has(file.path)) return false;
return !this._query || `${file.folder} ${file.name}`.toLowerCase().includes(this._query);
}
// Every file under a folder (all levels).
_filesUnder(path) {
return [...this._files.values()].filter((f) => f.folder === path || f.folder.startsWith(`${path}/`) || path === "");
}
_renderView() {
if (!this._root) return;
const find = this._panel.querySelector(".lib-find");
const counts = {};
this._files.forEach((f) => (counts[this._kindOf(f)] = (counts[this._kindOf(f)] || 0) + 1));
find.querySelector(".lib-find__kinds").innerHTML = Object.entries(KINDS)
.map(([kind, { label, color }]) => `<button type="button" class="lib-chip" data-kind="${kind}" aria-pressed="${this._kindsOn.has(kind)}"><span style="color: ${color}">●</span> ${label} <small>${counts[kind] || 0}</small></button>`)
.join("");
find.querySelector('[data-find="shown"]').setAttribute("aria-pressed", this._shownOnly);
const flat = this._mode === "list" || this._query;
find.querySelectorAll("[data-mode]").forEach((button) => button.setAttribute("aria-pressed", (button.dataset.mode === "list") === Boolean(flat)));
const ul = document.createElement("ul");
ul.className = "gpx-tree__points";
file.points.forEach((point) => {
const li = document.createElement("li");
li.className = "gpx-tree__point";
const name = document.createElement("button");
name.type = "button";
name.className = "gpx-tree__point-name";
name.textContent = point.name;
name.addEventListener("click", () => this._goToPoint(file.path, point));
li.appendChild(name);
if (isLoggedIn()) li.appendChild(this._deleteButton(() => this._removePoint(file, point)));
ul.appendChild(li);
ul.className = "lib-list";
if (flat) {
this._crumb.hidden = true;
if (this._query) {
[...this._folders.values()]
.filter((f) => f.path && f.name.toLowerCase().includes(this._query))
.forEach((f) => ul.appendChild(this._folderRow(f, true)));
}
[...this._files.values()].filter((f) => this._matches(f)).forEach((f) => ul.appendChild(this._fileRow(f, true)));
} else if (this._openTrack) {
const track = this._files.get(this._openTrack);
this._renderCrumb(track.folder, track.name, plural(track.points.length, "point"), () => (this._openTrack = null));
track.points.forEach((point) => ul.appendChild(this._pointRow(track, point)));
} else {
const folder = this._folders.get(this._cwd);
const subfolders = folder.children.filter((c) => c.type === "folder");
const files = folder.children.filter((c) => c.type !== "folder" && this._matches(c));
if (this._cwd) {
const parent = this._cwd.includes("/") ? this._cwd.slice(0, this._cwd.lastIndexOf("/")) : "";
this._renderCrumb(parent, folder.name, `${plural(subfolders.length, "folder")} · ${plural(files.length, "item")}`, () => (this._cwd = parent), parent);
} else {
this._crumb.hidden = true;
}
subfolders.forEach((f) => ul.appendChild(this._folderRow(f)));
files.forEach((f) => ul.appendChild(this._fileRow(f)));
}
if (!ul.children.length) {
ul.innerHTML = `<li class="gpx-tree__empty">${this._query ? "Nothing found" : "Nothing here yet"}</li>`;
}
this._treeContainer.innerHTML = "";
this._treeContainer.appendChild(ul);
this._footer.textContent = `${plural(this._folders.size - 1, "folder")} · ${plural(this._files.size, "item")} · ${this._visible.size} shown`;
}
// ← up, the path to here and its name; `dropTo` (the parent) also takes a
// dragged item, to move it a level up.
_renderCrumb(path, name, meta, up, dropTo) {
this._crumb.hidden = false;
this._crumb.innerHTML = "";
const back = Object.assign(document.createElement("button"), { type: "button", className: "lib-crumb__up", textContent: "←", title: "Up" });
back.addEventListener("click", () => {
up();
this._renderView();
});
details.appendChild(ul);
return details;
if (dropTo !== undefined && isLoggedIn()) this._wireFolderDropTarget(back, dropTo);
const where = Object.assign(document.createElement("span"), { className: "lib-crumb__path", textContent: path ? `${path.replaceAll("/", " › ")} › ` : "" });
this._crumb.append(back, where, Object.assign(document.createElement("b"), { textContent: name }), Object.assign(document.createElement("small"), { textContent: meta }));
}
_row({ icon, color, name, meta, aside, eye, onOpen, onEye, bold }) {
const li = document.createElement("li");
li.className = "lib-row";
li.innerHTML = `<span class="lib-row__icon" aria-hidden="true"></span><span class="lib-row__text"><span class="lib-row__name"></span><small class="lib-row__meta"></small></span><span class="lib-row__aside"></span>`;
const iconEl = li.querySelector(".lib-row__icon");
iconEl.textContent = icon;
iconEl.style.color = color || "";
li.querySelector(".lib-row__name").textContent = name;
li.querySelector(".lib-row__name").classList.toggle("lib-row__name--folder", Boolean(bold));
li.querySelector(".lib-row__meta").textContent = meta || "";
li.querySelector(".lib-row__aside").textContent = aside || "";
li.querySelector(".lib-row__text").addEventListener("click", onOpen);
if (eye) {
const button = Object.assign(document.createElement("button"), { type: "button", className: `lib-eye lib-eye--${eye}`, textContent: { all: "●", some: "◐", none: "○" }[eye] });
button.title = eye === "none" ? "Show on the map" : "Hide from the map";
button.setAttribute("aria-label", button.title);
button.setAttribute("aria-pressed", eye !== "none");
button.addEventListener("click", onEye);
li.appendChild(button);
}
return li;
}
_folderRow(folder, withPath = false) {
const files = this._filesUnder(folder.path);
const shown = files.filter((f) => this._visible.has(f.path)).length;
const subfolders = folder.children.filter((c) => c.type === "folder").length;
const items = folder.children.length - subfolders;
const parent = folder.path.includes("/") ? folder.path.slice(0, folder.path.lastIndexOf("/")).replaceAll("/", " › ") : "";
const li = this._row({
icon: "▣",
name: folder.name,
bold: true,
meta: [withPath && parent, subfolders && plural(subfolders, "folder"), plural(items, "item")].filter(Boolean).join(" · "),
aside: "›",
eye: files.length ? (shown === 0 ? "none" : shown === files.length ? "all" : "some") : null,
onOpen: () => {
this._cwd = folder.path;
this._openTrack = null;
this._query = "";
this._mode = "folders";
this._panel.querySelector(".lib-find__input").value = "";
this._renderView();
},
onEye: async () => {
const show = shown === 0;
await Promise.all(files.map((f) => this._toggleFileOnly(f.path, show)));
this._saveVisible();
this._renderView();
},
});
if (isLoggedIn()) {
li.appendChild(this._menuButton("⋯", "Actions", [
{ label: "Rename…", run: () => this._renameFolder(folder) },
...this._exportEntries(folder.path, folder.name),
{ label: "Delete…", run: () => this._deleteFolder(folder.path) },
]));
li.draggable = true;
li.addEventListener("dragstart", (event) => {
event.dataTransfer.setData(MOVE_MIME, `${FOLDER_DRAG_PREFIX}${folder.path}`);
event.dataTransfer.effectAllowed = "move";
});
this._wireFolderDropTarget(li, folder.path);
}
return li;
}
_fileRow(file, withPath = false) {
const kind = this._kindOf(file);
const visible = this._visible.has(file.path);
const li = this._row({
icon: KINDS[kind].glyph,
color: file.color || KINDS[kind].color,
name: file.name,
meta: [withPath && (file.folder ? file.folder.replaceAll("/", " › ") : "Top level"), KINDS[kind].one, file.points && plural(file.points.length, "point")].filter(Boolean).join(" · "),
aside: file.points ? "›" : "",
eye: visible ? "all" : "none",
// the name zooms to it, shown first if needed; a track's points open
// from its ›
onOpen: async (event) => {
if (file.points && event.target.closest(".lib-row__aside, .lib-row__meta")) {
this._openTrack = file.path;
return this._renderView();
}
if (!this._visible.has(file.path)) await this._toggleFile(file.path, true);
if (this._visible.has(file.path)) this._zoomTo(file.path);
this._renderView();
},
onEye: async () => {
await this._toggleFile(file.path, !visible);
this._renderView();
},
});
if (file.points) {
li.querySelector(".lib-row__aside").addEventListener("click", () => {
this._openTrack = file.path;
this._renderView();
});
}
li.draggable = true;
li.addEventListener("dragstart", (event) => {
event.dataTransfer.setData(MOVE_MIME, file.path);
event.dataTransfer.effectAllowed = "move";
});
// Every action behind one ⋯ menu (as OsmAnd does), shown only once
// logged in: they all require login (app.rb).
if (isLoggedIn()) li.appendChild(this._fileMenu(file));
return li;
}
_pointRow(track, point) {
const li = this._row({
icon: "●",
color: KINDS.waypoint.color,
name: point.name,
meta: "point",
onOpen: () => this._goToPoint(track.path, point),
});
if (isLoggedIn()) li.appendChild(this._deleteButton(() => this._removePoint(track, point)));
return li;
}
async _goToPoint(path, point) {
@@ -334,95 +555,6 @@ export class GpxPanelControl {
await this._reloadFile(target);
}
_renderFolder(folder) {
const details = document.createElement("details");
details.open = true;
const summary = document.createElement("summary");
const row = document.createElement("span");
row.className = "gpx-tree__folder-row";
const name = document.createElement("span");
name.textContent = folder.name;
row.appendChild(name);
if (isLoggedIn()) {
row.appendChild(
this._menuButton("⋯", "Actions", [
{ label: "Rename…", run: () => this._renameFolder(folder) },
...this._exportEntries(folder.path, folder.name),
{ label: "Delete…", run: () => this._deleteFolder(folder.path) },
]),
);
// Dragged onto another folder (or the tree's blank space) moves it.
summary.draggable = true;
summary.addEventListener("dragstart", (event) => {
event.dataTransfer.setData(MOVE_MIME, `${FOLDER_DRAG_PREFIX}${folder.path}`);
event.dataTransfer.effectAllowed = "move";
});
}
summary.appendChild(row);
this._wireFolderDropTarget(summary, folder.path);
details.appendChild(summary);
details.appendChild(this._renderChildren(folder.children));
return details;
}
_renderFile(file) {
const row = document.createElement("div");
row.className = "gpx-tree__file";
row.draggable = true;
row.addEventListener("dragstart", (event) => {
event.dataTransfer.setData(MOVE_MIME, file.path);
event.dataTransfer.effectAllowed = "move";
});
const label = document.createElement("label");
const checkbox = document.createElement("input");
checkbox.type = "checkbox";
checkbox.checked = this._visible.has(file.path);
checkbox.dataset.path = file.path;
checkbox.addEventListener("change", () => this._toggleFile(file.path, checkbox.checked, checkbox));
const loggedIn = isLoggedIn();
const name = document.createElement("span");
name.className = "gpx-tree__file-name";
name.textContent = file.name;
label.appendChild(checkbox);
(file.kinds || []).forEach((kind) => label.appendChild(this._kindIcon(kind)));
label.appendChild(name);
// The name zooms to it (showing it first if needed); the checkbox
// alone shows/hides.
name.addEventListener("click", async (event) => {
event.preventDefault();
if (!checkbox.checked) {
checkbox.checked = true;
await this._toggleFile(file.path, true, checkbox);
}
if (checkbox.checked) this._zoomTo(file.path);
});
row.appendChild(label);
// Every action behind one ⋯ menu (as OsmAnd does), shown only once
// logged in: they all require login (app.rb).
if (loggedIn) row.appendChild(this._fileMenu(file));
return row;
}
_kindIcon(kind) {
const icon = document.createElement("span");
icon.className = "gpx-tree__kind-icon";
if (kind === "waypoint") {
icon.innerHTML = WAYPOINT_ICON;
icon.title = "Has waypoints";
} else if (kind === "route") {
icon.innerHTML = ROUTE_ICON;
icon.title = "Has a route";
} else {
icon.innerHTML = TRACK_ICON;
icon.title = "Has a track";
}
return icon;
}
_fileMenu(file) {
const geojsonUrl = `${gpxFileUrl(file.path)}?${new URLSearchParams({ download: "geojson", name: file.name })}`;
// A folder's "Points (N)" node has no name or color of its own.
@@ -572,9 +704,28 @@ export class GpxPanelControl {
// that isn't shown yet — same as ticking its box in the tree by hand.
async show(path) {
if (this._visible.has(path)) return;
const checkbox = [...this._treeContainer.querySelectorAll("input[data-path]")].find((input) => input.dataset.path === path);
if (checkbox) checkbox.checked = true;
await this._toggleFile(path, true, checkbox);
await this._toggleFile(path, true);
this._renderView();
}
// For the driving grid's Points (driving.js): the tree as indexed by
// _renderTree, whether a node is shown, and showing / hiding nodes.
libraryTree() {
return { folders: this._folders || new Map(), files: this._files || new Map(), filesUnder: (path) => this._filesUnder(path) };
}
isShown(path) {
return this._visible.has(path);
}
async setShown(paths, visible) {
await Promise.all(paths.map((path) => this._toggleFileOnly(path, visible)));
this._saveVisible();
this._renderView();
}
zoomTo(path) {
return this._zoomTo(path);
}
// Search result picked: show its file, then open the matching point's
@@ -589,7 +740,23 @@ export class GpxPanelControl {
if (feature) this._openPointPopup(path, feature, [lng, lat]);
}
// The shown files, per device (localStorage) — back after a reload by restore().
_saveVisible() {
try { localStorage.setItem(GPX_VISIBLE_KEY, JSON.stringify([...this._visible])); } catch { /* private window: not kept */ }
}
async restore() {
let paths = [];
try { paths = JSON.parse(localStorage.getItem(GPX_VISIBLE_KEY)) || []; } catch { /* nothing kept */ }
await Promise.all(paths.map((path) => this.show(path)));
}
async _toggleFile(path, visible, checkbox) {
await this._toggleFileOnly(path, visible, checkbox);
this._saveVisible();
}
async _toggleFileOnly(path, visible, checkbox) {
if (visible) {
this._visible.add(path);
const ok = await this._addLayers(path);
@@ -733,7 +900,7 @@ export class GpxPanelControl {
// clusterRadius/clusterMaxZoom are harmless when there's nothing dense
// enough to cluster (a handful of waypoints just render individually).
this._map.addSource(pointsId, { type: "geojson", data: points, cluster: true, clusterRadius: 50, clusterMaxZoom: 14 });
const badgeColors = new Set(points.features.map((f) => f.properties.color));
const badgeColors = new Set([...points.features.map((f) => f.properties.color), ...CLUSTER_COLORS]);
await Promise.all([this._registerCategoryGlyphs(new Set(points.features.map((f) => f.properties.icon))), this._registerBadgeColors(badgeColors)]);
if (!this._map.getSource(pointsId)) return true; // a style.load (basemap switch) tore it down while icons were loading
@@ -748,21 +915,21 @@ export class GpxPanelControl {
}
// A single-hue, light->dark ramp keyed on point_count (magnitude, not
// category) for the clustered circles; individual points below that use
// category) for the cluster badges; individual points below that use
// each waypoint's own category color (see Maptool::Gpx#waypoint_color),
// falling back to the plain track color for waypoints with no category
// (e.g. a hand-placed GNSS pin, not from a POI export).
_addClusterLayers(pointsId, path) {
this._map.addLayer({
id: `${pointsId}-clusters`,
type: "circle",
type: "symbol",
source: pointsId,
filter: ["has", "point_count"],
paint: {
"circle-radius": ["step", ["get", "point_count"], 16, 25, 20, 100, 26],
"circle-color": ["step", ["get", "point_count"], "#a8c8ea", 25, "#5b9bd5", 100, "#2e6da4"],
"circle-stroke-color": "#fff",
"circle-stroke-width": 1.5,
layout: {
"icon-image": ["step", ["get", "point_count"], badgeImageId(CLUSTER_COLORS[0]), 25, badgeImageId(CLUSTER_COLORS[1]), 100, badgeImageId(CLUSTER_COLORS[2])],
"icon-size": ["step", ["get", "point_count"], 32 / POI_ICON_IMAGE_SIZE, 25, 40 / POI_ICON_IMAGE_SIZE, 100, 52 / POI_ICON_IMAGE_SIZE],
"icon-allow-overlap": true,
"icon-ignore-placement": true,
},
});
this._map.addLayer({
@@ -783,20 +950,20 @@ export class GpxPanelControl {
// default center anchoring is simplest and also means the glyph layer
// below needs no offset, just the same center anchor.
// A point with no NPS symbol (a Google saved place, a bare GPX
// waypoint) is a small dot instead, like a place on an NPS map — an
// waypoint) is a small badge instead, about half the size — a full-size
// empty badge read as a big red square.
const single = ["!", ["has", "point_count"]];
const hasSymbol = ["in", ["get", "icon"], ["literal", POI_ICON_KEYS]];
this._map.addLayer({
id: `${pointsId}-dot`,
type: "circle",
type: "symbol",
source: pointsId,
filter: ["all", single, ["!", hasSymbol]],
paint: {
"circle-radius": ["interpolate", ["linear"], ["zoom"], 6, 3.5, 14, 6],
"circle-color": ["get", "color"],
"circle-stroke-color": "#fff",
"circle-stroke-width": 1.5,
layout: {
"icon-image": ["concat", BADGE_IMAGE_PREFIX, ["get", "color"]],
"icon-size": ["interpolate", ["linear"], ["zoom"], 6, 8 / POI_ICON_IMAGE_SIZE, 14, 13 / POI_ICON_IMAGE_SIZE],
"icon-allow-overlap": true,
"icon-ignore-placement": true,
},
});
this._map.addLayer({
@@ -1403,6 +1570,24 @@ export class GpxPanelControl {
}
}
async _sync(button) {
button.disabled = true;
this._setStatus("Syncing…");
try {
const response = await fetch("/api/sync/run", { method: "POST" });
if (redirectIfUnauthorized(response)) return;
const body = await response.json();
if (!response.ok) return this._setStatus(body.error || "Sync failed.");
this._setStatus(`Synced: ${body.pulled} from the server, ${body.pushed} sent.`);
await this._loadTree();
await Promise.all([...this._visible].map((path) => this._reloadFile(path)));
} catch {
this._setStatus("Sync failed: the server is unreachable.");
} finally {
button.disabled = false;
}
}
_setStatus(text) {
this._uploadStatus.hidden = false;
this._uploadStatus.textContent = text;
+2
View File
@@ -8,6 +8,7 @@ import {
mdiBugOutline,
mdiClockOutline,
mdiCloudDownloadOutline,
mdiCloudSyncOutline,
mdiContentSaveOutline,
mdiCrosshairsGps,
mdiDeleteSweepOutline,
@@ -58,6 +59,7 @@ 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);
+5 -6
View File
@@ -1,5 +1,5 @@
import { Marker } from "/vendor/maplibre-gl/maplibre-gl.mjs";
import { followPosition } from "/js/gnss.js";
import { followPosition, startFollow } from "/js/gnss.js";
// Replaces MapLibre's own GeolocateControl (browser Geolocation API only)
// with one that prefers this app's own GNSS receiver when it's turned on
@@ -96,7 +96,7 @@ export class LocateControl {
_jumpToGnss({ alertIfNoFix = false } = {}) {
const position = this._gnssControl.getPosition();
if (position) {
this._map.flyTo({ center: position, zoom: Math.max(this._map.getZoom(), 15) });
startFollow(this._map, position);
} else if (alertIfNoFix) {
window.alert("Waiting for a GNSS fix…");
}
@@ -118,10 +118,9 @@ export class LocateControl {
}
// Recenters on every fix, following the position the way GeolocateControl
// itself does while tracking — flyTo (with its zoom swoop) only for the
// itself does while tracking — startFollow (zooming in) only for the
// first fix, since that's the one jumping from wherever the map already
// was; easeTo for later updates, a plain pan/zoom-preserving follow
// rather than repeating that same swoop on every update.
// was; a plain follow zooming by the speed (autoZoom) for later updates.
//
// MapLibre's own blue pulsing "user location" dot styling
// (.maplibregl-user-location-dot, maplibre-gl.css — the exact look
@@ -138,7 +137,7 @@ export class LocateControl {
const circleEl = document.createElement("div");
circleEl.className = "maplibregl-user-location-accuracy-circle";
this._circleMarker = new Marker({ element: circleEl, pitchAlignment: "map" }).setLngLat([lon, lat]).addTo(this._map);
this._map.flyTo({ center: [lon, lat], zoom: Math.max(this._map.getZoom(), 15) });
startFollow(this._map, [lon, lat]);
} else {
this._marker.setLngLat([lon, lat]);
this._circleMarker.setLngLat([lon, lat]);
+188 -184
View File
@@ -17,17 +17,20 @@ import { LocateControl } from "/js/locate.js";
import { SearchControl } from "/js/search.js";
import { OfflineDataControl } from "/js/offline_data.js";
import { RoutePanelControl } from "/js/route.js";
import { LAYERS_ICON, WAYPOINT_ICON, SUNRISE_ICON, SUNSET_ICON, PENDING_ICON, LOCK_ICON, UNLOCK_ICON } from "/js/icons.js";
import { WAYPOINT_ICON, SUNRISE_ICON, SUNSET_ICON, PENDING_ICON, LOCK_ICON, UNLOCK_ICON } from "/js/icons.js";
import { formatCoords, formatSunInfo, sunChartHtml } from "/js/sun.js";
import { getPosition } from "/vendor/suncalc/suncalc.js";
import { notifySidePanelOpen, onlyOneSidePanelOpen, setupSidePanelModes } from "/js/panels.js";
import { addRoutePoint, setupSidePanelModes } from "/js/panels.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 OverviewMap from "/vendor/npmap-overview/overview.esm.js";
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 ZOOM = 13;
@@ -102,49 +105,18 @@ function offlineStyle() {
return style;
}
// A sidebar icon that opens a full-height side panel (like the GPX one)
// with the Online/Offline choice — modelled after OsmAnd's "Configure map"
// panel, rather than a small dropdown flyout.
// The Online/Offline choice: the first group of the On the map panel
// (the Overlays one, overlays.js), no rail item or panel of its own.
class LayerToggleControl {
constructor(onSelect) {
this._onSelect = onSelect;
this._panel = document.querySelector(".onthemap-map");
}
mount(sidebar) {
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));
mount() {
this._panel.querySelectorAll(".basemap-panel__option").forEach((button) => {
button.addEventListener("click", () => {
this._onSelect(button.dataset.style);
this._togglePanel(false);
});
button.addEventListener("click", () => this._onSelect(button.dataset.style));
});
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) {
@@ -155,84 +127,18 @@ class LayerToggleControl {
// 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
// sense to show at all when Offline was never going to work. The panel
// itself stays for its legend link.
// sense to show at all when Offline was never going to work. The legend
// link stays.
hideSources() {
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
// pitch — bearing stays untouched, so this is purely "look at it from an
// angle", not a rotate/compass control. Independent of the "Terrain
// shading" overlay toggle (overlays.js) — that adds a raster-dem hillshade/
// color-relief layer, this just moves the camera; combining both gives a
// real sense of relief but neither depends on the other.
// angle", not a rotate/compass control. Tilted, the ground is raised into
// real 3D relief (OverlaysControl.syncTerrain, overlays.js), with or
// without the "Terrain shading" overlay.
const PITCH_3D = 60;
class PitchToggleControl {
@@ -340,13 +246,7 @@ const map = new MaplibreMap({
hash: "map",
});
// A compact top-left stack — Home, zoom, zoom-level readout, measure,
// 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
// Home's bounds (rather than homePosition/zoom) so Home resets to an overview of
// 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
// above), "current view" and "the default view" are no longer the same
@@ -357,21 +257,17 @@ const SLOVAKIA_BOUNDS = [
[16.83, 47.73],
[22.57, 49.61],
];
// The Design canvas' Desktop: search in the topbar, the map's own buttons
// in one column on the right — zoom and compass, the view (north lock, 3D,
// my position), the tools (measure, note, home); the zoom level, the scale
// and the coordinates in the status bar under the map.
const searchControl = new SearchControl();
map.addControl(searchControl, "top-left");
map.addControl(new HomeButton({ bounds: SLOVAKIA_BOUNDS }), "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-left");
map.addControl(new RotationLockControl(), "top-left");
map.addControl(new ZoomLevelControl(), "top-left");
map.addControl(new NavigationControl({ visualizePitch: false }), "top-right");
map.addControl(new RotationLockControl(), "top-right");
const pitchToggle = new PitchToggleControl();
map.addControl(pitchToggle, "top-left");
map.addControl(new MeasureControl(), "top-left");
// 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.
if (isLoggedIn()) map.addControl(new NotesControl(), "top-left");
map.addControl(pitchToggle, "top-right");
// Constructed here (rather than down where it's mounted, alongside the
// other sidebar controls) so LocateControl can hold the same instance —
// its constructor only touches `map`, mount() (which needs the sidebar
@@ -383,8 +279,54 @@ const gnssControl = new GnssControl(map);
// device's separate, often less accurate location service, but only once
// the "GNSS" sidebar icon actually turns it on — not just whenever a
// receiver happens to have a fix. See locate.js.
map.addControl(new LocateControl(gnssControl), "top-left");
map.addControl(new ScaleControl({ unit: "metric" }), "bottom-left");
map.addControl(new LocateControl(gnssControl), "top-right");
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
// own overview plugin (docs/nps-resources.adoc's "overview" entry, still on
@@ -401,7 +343,7 @@ map.once("style.load", () => {
map.addControl(new OverviewMapControl({}), "top-right");
});
const coordsLabel = document.querySelector(".topbar__coords");
const coordsLabel = document.querySelector(".statusbar__coords");
const updateCoords = () => {
const { lng, lat } = map.getCenter();
coordsLabel.innerHTML = `<span class="topbar__icon">${WAYPOINT_ICON}</span><span>${formatCoords(lat, lng)}</span>`;
@@ -429,7 +371,7 @@ coordsLabel.addEventListener("click", async () => {
// barely moves between two nearby spots, not worth recomputing constantly)
// plus a periodic tick so the "Xh Ym to sunset" countdown keeps counting
// 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 { lng, lat } = map.getCenter();
@@ -467,11 +409,22 @@ updateSun();
map.on("moveend", updateSun);
setInterval(updateSun, 60000);
// Night mode (html.night, style.css) so the screen doesn't glare in the
// car: "auto" follows the sun at the map center, or forced on/off — the
// topbar button cycles the three, remembered per device.
const NIGHT_MODES = { auto: ["◐", "Night mode: automatic (after sunset)"], on: ["☾", "Night mode: on"], off: ["☀", "Night mode: off"] };
// 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
@@ -505,8 +458,12 @@ const updateNight = () => {
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);
@@ -522,19 +479,19 @@ setInterval(updateNight, 60000);
const sidebar = document.getElementById("sidebar");
// Grouped into the TODO's planned 4-module menu (Explorer / Offline hub /
// Navigation / Camper & HW) ahead of that split actually happening —
// Camper & HW has no sidebar item yet (leveling/solar/telemetry are all
// still unbuilt), so it's left out rather than shown empty.
// The rail of the Design canvas' Desktop, labelled: On the map (the map,
// overlays), the library and imports; the route; offline data; live
// (GNSS, LiveTrack); Status pinned at the bottom.
const layerToggle = new LayerToggleControl(applyStyle);
const profilePanel = new TrackProfilePanel(map);
profilePanel.mount();
sidebar.insertAdjacentHTML("beforeend", `<div class="sidebar-group-label" title="Explorer"></div>`);
const gpxPanel = new GpxPanelControl(map, profilePanel);
gpxPanel.mount(sidebar);
layerToggle.mount();
layerToggle.setActive("online");
const overlaysControl = new OverlaysControl(map);
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)),
@@ -545,26 +502,23 @@ pitchToggle.setOverlaysControl(overlaysControl);
// "hide the write-only affordance" story as NotesControl above.
if (isLoggedIn()) new PluginsControl(map).mount(sidebar);
sidebar.insertAdjacentHTML("beforeend", `<div class="sidebar-group-label" title="Offline hub"></div>`);
layerToggle.mount(sidebar);
layerToggle.setActive("online");
new RoutePanelControl(map, gnssControl, profilePanel).mount(sidebar);
sidebar.insertAdjacentHTML("beforeend", `<div class="sidebar-group-label"></div>`);
const routePanel = new RoutePanelControl(map, gnssControl, profilePanel);
routePanel.mount(sidebar);
setupDriving(map, nightButton, routePanel, gpxPanel);
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);
new LiveTrackPanelControl(map).mount(sidebar);
if (isLoggedIn()) new DebugControl().mount(sidebar);
if (isLoggedIn()) setupUpdate(document.querySelector(".topbar__update"), document.querySelector(".debug-panel__update-check"));
// A short name under each icon (CSS ::after), the title stays the tooltip.
const RAIL_LABELS = { "Import plugins": "Import", "Offline data": "Offline", LiveTrack: "Live", "Status / debug": "Status" };
sidebar.querySelectorAll(".sidebar-icon").forEach((icon) => (icon.dataset.label = RAIL_LABELS[icon.title] ?? icon.title));
setupSidePanelModes();
// The sidebar already has a "Base map" icon (opens the same panel) —
// this is a second entry point for it, grouped with Home/zoom on the map
// itself rather than off in the page's own side rail, matching NPS's
// layout. layerToggle only needs to exist (not be mounted yet) for this.
const mapLayersButton = new MapLayersButton(layerToggle);
map.addControl(mapLayersButton, "top-left");
function applyStyle(name) {
layerToggle.setActive(name);
map.setStyle(nightMap.base(name === "offline" ? offlineStyle() : onlineStyle()));
@@ -576,7 +530,8 @@ function applyStyle(name) {
// switch to), so it's removed entirely rather than left sitting there
// offering a choice that can't work.
const offlineStatus = document.querySelector(".topbar__offline-status");
fetch("/api/offline-tiles")
const ready = [];
ready.push(fetch("/api/offline-tiles")
.then((response) => response.json())
.then(({ available }) => {
if (available) {
@@ -587,61 +542,110 @@ fetch("/api/offline-tiles")
offlineStatus.hidden = false;
offlineStatus.classList.toggle("topbar__offline-status--ready", available);
offlineStatus.title = available ? "Offline map data ready" : "No offline map data on this server";
offlineStatus.textContent = available ? "Offline ready" : "Online only";
})
.catch(() => {
// Backend check failed; keep the online style and leave the switch as
// is rather than guessing — this is the same-origin request itself
// failing, not evidence offline tiles are actually unavailable.
});
}));
fetch("/api/terrain-tiles")
ready.push(fetch("/api/terrain-tiles")
.then((response) => response.json())
.then(({ available }) => {
terrainOffline = available;
overlaysControl.setHillshadeOfflineAvailable(available);
overlaysControl.setShadowOfflineAvailable(available);
})
.catch(() => {});
.catch(() => {}));
fetch("/api/hiking-trails")
ready.push(fetch("/api/hiking-trails")
.then((response) => response.json())
.then(({ countries, bboxes }) => overlaysControl.setHikingTrailsOfflineCountries(countries, bboxes))
.catch(() => {});
.catch(() => {}));
fetch("/api/kiwix")
ready.push(fetch("/api/kiwix")
.then((response) => response.json())
.then(({ available }) => overlaysControl.setWikiAvailable(available))
.catch(() => {});
.catch(() => {}));
// Alt+click, right click or a long press (touch browsers fire
// contextmenu for it) anywhere shows every rendered feature at that point — base map
// (OSM tags via OpenFreeMap/protomaps), GPX/FIT layers, radar, all of it —
// with its raw properties, inspired by NPMap4's infoboxControl (a generic
// "show me everything here" debug view, kept separate from the curated
// popups those same features already have via their own layer-specific
// click handlers, e.g. gpx.js's waypoint popups — both can fire on the same
// click, which is fine, this is a power-user/debugging affordance, not
// something replacing the normal popups). No dedicated UI for this
// deliberately — a keyboard-modified click needs no button, state, or
// cursor change of its own.
const inspect = (event) => {
// What was on before the reload / update (localStorage, per device): once
// the checks above are in (offline or online terrain, trails, wiki) and the
// base map they switched to has loaded.
Promise.allSettled(ready).then(() => {
const restore = () => {
overlaysControl.restore();
gpxPanel.restore();
};
if (map.loaded()) restore();
else map.once("idle", restore);
});
// 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);
if (features.length === 0) return;
const html = features
const rows = features
.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>`)
.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("");
new Popup({ maxWidth: "320px", className: "debug-popup" }).setLngLat(event.lngLat).setHTML(html).addTo(map);
const el = document.createElement("div");
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 && inspect(event));
map.on("click", (event) => event.originalEvent.altKey && whatsHere(event));
map.on("contextmenu", (event) => {
event.originalEvent.preventDefault();
inspect(event);
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
+33 -1
View File
@@ -8,8 +8,40 @@
// 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(parkTilesStyle(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 = {
+8
View File
@@ -342,6 +342,14 @@ export class NotesControl {
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() {
this._marker?.remove();
this._marker = null;
+78 -36
View File
@@ -8,6 +8,7 @@ import { ContourControl } from "/js/contour.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_SIZE = 0.3; // 48 * 0.3 = ~14px, sized to sit inside the marker badge below
@@ -18,6 +19,13 @@ const WIKI_ICON_ID = "wiki-icon";
const WIKI_BADGE_COLOR = "#795548";
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";
// MapLibre's own default light ({anchor:"viewport", intensity:0.5,
// position:[1.15,210,30]}) sits the sun almost overhead (polar 30°) — fine
@@ -37,7 +45,7 @@ const DEFAULT_LIGHT = { anchor: "viewport", color: "#fff", intensity: 0.5, posit
const ELEVATION_COLOR_RAMP = [
"interpolate",
["linear"],
["raster-value"],
["elevation"],
0, "#c3e8ab",
400, "#dcd08f",
900, "#c9a66b",
@@ -87,34 +95,31 @@ class HillshadeControl {
_toggle(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();
else this._removeLayer();
this.syncTerrain(this._map.getPitch() > 0);
}
// Real terrain displacement (map.setTerrain), not just the flat
// hillshade/color-relief paint above — called both when this checkbox
// changes and when the 3D pitch toggle changes (map.js's
// PitchToggleControl, via OverlaysControl.syncTerrain below), since
// showing raised terrain needs both "tilted enough to see it" and "the
// DEM source this checkbox controls is actually loaded".
// hillshade/color-relief paint above — whenever the map is tilted (the
// 3D button, map.js's PitchToggleControl, via OverlaysControl.syncTerrain
// below), like OsmAnd's 3D relief.
syncTerrain(pitched) {
// setLight/setTerrain throw if the style isn't loaded yet — called
// synchronously from map.js's setOverlaysControl during page init,
// before the first style.load; that listener re-invokes this once it
// actually is loaded, so bailing here just skips the premature call.
if (!this._map.isStyleLoaded()) return;
const terrainOn = pitched && this._active && this._map.getSource(HILLSHADE_ID);
if (terrainOn) {
this._map.setTerrain({ source: HILLSHADE_ID, exaggeration: 3 });
} else if (this._map.getTerrain()) {
this._map.setTerrain(null);
// Not isStyleLoaded(): that's false while any tile is still loading —
// always the case right after tilting — so the terrain never came on.
// Before the first style.load these throw; that listener calls again.
try {
if (pitched) {
if (!this._map.getSource(TERRAIN_ID)) this._map.addSource(TERRAIN_ID, this._demSource());
this._map.setTerrain({ source: TERRAIN_ID, exaggeration: TERRAIN_EXAGGERATION });
} else if (this._map.getTerrain()) {
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 —
// 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
@@ -135,7 +140,23 @@ class HillshadeControl {
// (docs/development.adoc), so this credits them regardless of how it
// got there — their own site lists the full per-region source
// 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",
url: `pmtiles://${window.location.origin}/tiles/terrain.pmtiles`,
@@ -150,18 +171,6 @@ class HillshadeControl {
maxzoom: 15,
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() {
@@ -180,6 +189,12 @@ class HillshadeControl {
// 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
// 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 {
constructor(map) {
this._map = map;
@@ -191,6 +206,7 @@ export class OverlaysControl {
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._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
@@ -208,7 +224,7 @@ export class OverlaysControl {
mount(sidebar) {
this._container = document.createElement("div");
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.addEventListener("click", () => this._togglePanel());
@@ -222,7 +238,7 @@ export class OverlaysControl {
["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)]]],
["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");
list.innerHTML = "";
@@ -236,6 +252,7 @@ export class OverlaysControl {
li.className = `overlays-panel__item${expandable ? " overlays-panel__item--expandable" : ""}`;
list.appendChild(li);
mount(li);
this._remember(li, `${heading}/${li.querySelector(".overlays-panel__name, label")?.textContent.trim()}`);
}
}
@@ -244,6 +261,31 @@ export class OverlaysControl {
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) {
const open = force === undefined ? this._panel.hidden : force;
this._panel.hidden = !open;
+66
View File
@@ -112,3 +112,69 @@ export function editRoute(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;
}
+43 -3
View File
@@ -1,6 +1,9 @@
import { PLUGIN_ICON } from "/js/icons.js";
import { notifyGpxStoreChanged, notifySidePanelOpen, onlyOneSidePanelOpen } from "/js/panels.js";
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
// this area" button using the current map viewport as the bbox, so there's
@@ -56,28 +59,65 @@ export class PluginsControl {
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) {
const li = document.createElement("li");
li.className = "plugins-panel__item";
li.innerHTML = `
<span class="plugins-panel__label"></span>
<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>
${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;
const button = li.querySelector(".plugins-panel__run");
const status = li.querySelector(".plugins-panel__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;
}
async _run(plugin, button, status) {
async _run(plugin, button, status, along = null) {
button.disabled = true;
status.textContent = "Running…";
try {
const bounds = this._map.getBounds();
const body = new URLSearchParams({
const body = new URLSearchParams(along || {
south: bounds.getSouth(),
west: bounds.getWest(),
north: bounds.getNorth(),
@@ -91,7 +131,7 @@ export class PluginsControl {
const data = await response.json().catch(() => ({}));
if (!response.ok) throw new Error(data.error || `run failed: ${response.status}`);
notifyGpxStoreChanged(data.path);
status.textContent = "Done";
status.textContent = `Done · ${data.count} found`;
status.classList.remove("plugins-panel__status--error");
} catch (err) {
// Plugins::RunError's message (e.g. "plugin exited with status 1")
+883 -81
View File
File diff suppressed because it is too large. Load diff
+42 -26
View File
@@ -37,7 +37,7 @@ function formatKm(km) {
return km < 10 ? `${km.toFixed(1)} km` : `${Math.round(km)} km`;
}
// A place-name/coordinate search box, matching NPS's own Park Tiles viewer.
// A place-name/coordinate search box in the topbar.
// Every result says where it was found; picking one from a layer that's
// currently switched off switches it on (see setLayerOpeners).
export class SearchControl {
@@ -53,16 +53,20 @@ export class SearchControl {
this._openers = openers;
}
onAdd(map) {
// In the topbar (the Design canvas' Desktop): the field always there,
// the sources and results drop down under it while it's in use; "/"
// anywhere focuses it.
mount(map, slot) {
this._map = map;
this._container = document.createElement("div");
this._container.className = "maplibregl-ctrl maplibregl-ctrl-group search-ctrl";
this._container.className = "search-ctrl";
this._container.innerHTML = `
<button type="button" class="search-ctrl__button" title="Search" aria-label="Search">${SEARCH_ICON}</button>
<form class="search-panel__form" role="search">
<span class="search-ctrl__icon" aria-hidden="true">${SEARCH_ICON}</span>
<input type="search" class="search-panel__input" placeholder="Search places, the library, or lat, lng" aria-label="Search">
<kbd class="search-ctrl__key" title="Press / to search">/</kbd>
</form>
<div class="search-panel" hidden>
<form class="search-panel__form">
<input type="text" class="search-panel__input" placeholder="Search, or lat, lng">
</form>
<div class="search-panel__sources">
${SOURCES.map(
(source) => `
@@ -73,12 +77,11 @@ export class SearchControl {
<ul class="search-panel__results"></ul>
</div>
`;
this._button = this._container.querySelector(".search-ctrl__button");
this._panel = this._container.querySelector(".search-panel");
this._input = this._container.querySelector(".search-panel__input");
this._resultsEl = this._container.querySelector(".search-panel__results");
this._button.addEventListener("click", () => this._toggle());
this._input.addEventListener("focus", () => (this._panel.hidden = false));
this._container.querySelector(".search-panel__form").addEventListener("submit", (event) => {
event.preventDefault();
this._search();
@@ -90,23 +93,20 @@ export class SearchControl {
if (this._input.value.trim()) this._search();
});
});
document.addEventListener("click", (event) => {
if (!this._container.contains(event.target)) this._panel.hidden = true;
});
document.addEventListener("keydown", (event) => {
if (event.key === "Escape" && this._container.contains(document.activeElement)) {
this._panel.hidden = true;
this._input.blur();
} else if (event.key === "/" && !event.target.closest("input, textarea, select, [contenteditable]")) {
event.preventDefault();
this._input.focus();
}
});
return this._container;
}
onRemove() {
this._container.remove();
}
getDefaultPosition() {
return "top-left";
}
_toggle() {
const opening = this._panel.hidden;
this._panel.hidden = !opening;
this._button.classList.toggle("active", opening);
if (opening) this._input.focus();
slot.appendChild(this._container);
}
async _search() {
@@ -120,6 +120,23 @@ export class SearchControl {
return;
}
// A pasted link (Google Maps, park4night, a page with coordinates):
// the server reads the place from it (lib/maptool/link_place.rb)
if (/^(https?:\/\/|geo:)\S+$/i.test(query)) {
this._renderResults([], true);
try {
const response = await fetch(`/api/link?${new URLSearchParams({ url: query })}`);
const place = await response.json();
if (!response.ok) throw new Error(response.status === 401 ? "log in to read links" : place.error);
let where = "From the link";
try { where = `From ${new URL(place.url || query).hostname}`; } catch { /* geo: */ }
this._renderResults([{ name: place.name || `${place.lat.toFixed(5)}, ${place.lng.toFixed(5)}`, where, lat: place.lat, lng: place.lng }]);
} catch (err) {
this._renderResults([{ status: `That link: ${err.message}` }]);
}
return;
}
// Every source answers on its own; the list re-renders (nearest first
// across all of them) as each one comes in.
const searchId = (this._searchId = (this._searchId || 0) + 1);
@@ -260,6 +277,5 @@ export class SearchControl {
this._marker = new Marker({ element: el }).setLngLat(center).addTo(this._map);
}
this._panel.hidden = true;
this._button.classList.remove("active");
}
}
+71
View File
@@ -0,0 +1,71 @@
// The countries' general speed limits (km/h) for a car / a vehicle up to
// 3.5 t and for a motorhome over 3.5 t: [motorway, expressway, outside towns,
// in towns]; null = no general limit. What a road's own sign says wins when
// it's lower (dashboard.js), these fill in what a vehicle may not exceed.
//
// Sources (read 2026-12-03; both are camping guides built on ADAC's tables,
// not the laws themselves — check before relying on a figure):
// W = womoly.app/wohnmobil-ratgeber/tempolimits-europa (Stand Oktober 2026)
// C = copilot.travel/maps/caravan-speed-limits (read up to 2026-10-31)
// CZ, HU, PL, SK only from C (a secondary source). Left out where the two
// disagree or depend on the registration: ES, SE, NO, BE, LU, and countries
// neither covers (RO, BG, GR).
// ponytail: one figure per road class; night/rain limits, Germany's 100 only for a
// registered Wohnmobil up to 7.5 t, France's 80/90 by département not modelled
export const SPEED_LIMITS = {
AT: { car: [130, 100, 100, 50], heavy: [80, 80, 70, 50], src: "W, C" },
CH: { car: [120, 100, 80, 50], heavy: [100, 100, 80, 50], src: "W, C" },
CZ: { car: [130, 110, 90, 50], heavy: [80, 80, 80, 50], src: "C" },
DE: { car: [null, 100, 100, 50], heavy: [100, 100, 80, 50], src: "W, C; 100 only registered as Wohnmobil, else 80" },
DK: { car: [130, 80, 80, 50], heavy: [80, 80, 80, 50], src: "W, C" },
FR: { car: [130, 110, 80, 50], heavy: [110, 100, 80, 50], src: "W, C" },
HR: { car: [130, 110, 90, 50], heavy: [90, 80, 80, 50], src: "W, C" },
HU: { car: [130, 110, 90, 50], heavy: [80, 70, 70, 50], src: "C" },
IT: { car: [130, 110, 90, 50], heavy: [100, 80, 80, 50], src: "W, C" },
NL: { car: [100, 100, 80, 50], heavy: [80, 80, 80, 50], src: "W, C; 130 at night on some motorways" },
PL: { car: [140, 120, 90, 50], heavy: [80, 80, 70, 50], src: "C" },
PT: { car: [120, 100, 90, 50], heavy: [100, 90, 80, 50], src: "W, C" },
SI: { car: [130, 110, 90, 50], heavy: [80, 80, 80, 50], src: "W, C" },
SK: { car: [130, 130, 90, 50], heavy: [90, 90, 90, 50], src: "C" },
};
// Motorways paid by a time-based vignette (a car up to 3.5 t); over 3.5 t
// these countries charge by distance (a toll unit) instead.
export const VIGNETTE_COUNTRIES = new Set(["AT", "BG", "CH", "CZ", "HU", "MD", "RO", "SI", "SK"]);
export const COUNTRY_NAMES = new Intl.DisplayNames(["en"], { type: "region" });
// Over 3.5 t: a car profile heavier than that.
export const isHeavy = (vehicle) => (vehicle?.type || "car") === "car" && (vehicle?.weight ?? 0) > 3.5;
// The column of the four for a Valhalla road class.
const column = (roadClass) => (roadClass === "motorway" ? 0 : roadClass === "trunk" ? 1 : 2);
// The vehicle's limit on this road: the general one for its class and road
// class (outside towns: Valhalla doesn't say where a town starts, a town's
// own 50 is the road's sign), or null where none is known.
export function vehicleLimit(code, roadClass, vehicle) {
const row = SPEED_LIMITS[code];
return row ? row[isHeavy(vehicle) ? "heavy" : "car"][column(roadClass)] : null;
}
// The lower of the road's sign (a number, "unlimited" or null) and the
// vehicle's own limit there. Only for a heavy vehicle: a car's general limit
// is what the road's sign already says, or unknown.
export function effectiveLimit(sign, code, roadClass, vehicle) {
const own = isHeavy(vehicle) ? vehicleLimit(code, roadClass, vehicle) : null;
if (own == null) return sign;
return typeof sign === "number" ? Math.min(sign, own) : own;
}
// How the motorways are paid there, and whether the profile has it:
// { how: "vignette" | "toll unit" | null, has: true | false | null, until }.
export function motorwayPayment(code, vehicle, today = new Date().toISOString().slice(0, 10)) {
const heavy = isHeavy(vehicle);
const how = VIGNETTE_COUNTRIES.has(code) ? (heavy ? "toll unit" : "vignette") : null;
if (!how) return { how: null, has: null };
const kind = heavy ? "toll" : "vignette";
const owned = (vehicle?.vignettes || []).find((v) => v.country === code && (v.kind || "vignette") === kind);
if (!owned) return { how, has: false };
return { how, has: !owned.until || owned.until >= today, until: owned.until || null };
}
+9
View File
@@ -45,11 +45,18 @@ export class TrackProfilePanel {
this._stats = this._panel.querySelector(".profile-panel__stats");
this._chartsContainer = this._panel.querySelector(".profile-panel__charts");
this._panel.querySelector(".profile-panel__close").addEventListener("click", () => this.hide());
// Docked under the map (the Design canvas' Desktop): the map gives up
// the profile's height instead of being covered by it.
new ResizeObserver(() => {
const height = this._panel.hidden ? 0 : this._panel.offsetHeight;
document.documentElement.style.setProperty("--profile-h", `${height}px`);
}).observe(this._panel);
}
show(properties) {
const profile = properties.profile;
if (!profile || profile.length === 0) return;
this.shown = properties; // whose profile this is (route.js hides its own)
this._profile = profile.map((point) => ({ ...point, speed_kmh: typeof point.speed_mps === "number" ? point.speed_mps * 3.6 : null }));
addMovingTime(this._profile);
@@ -204,7 +211,9 @@ export class TrackProfilePanel {
}
hide() {
this.shown = null;
this._panel.hidden = true;
document.documentElement.style.setProperty("--profile-h", "0px");
this._plots?.removeEventListener("pointermove", this._onPointerMove);
this._plots?.removeEventListener("pointerleave", this._onPointerLeave);
this._marker.remove();
+59
View File
@@ -0,0 +1,59 @@
// The car's server updating itself (GET/POST /api/update, SELF_UPDATE=1 in
// its .env): a topbar button shows up when main has a newer version that
// passed CI; a click installs it (bin/update-maptool.sh on the host) and the
// page reloads once the server answers with the new revision.
const CHECK_MS = 10 * 60 * 1000;
const RESTART_POLL_MS = 5000;
export function setupUpdate(button, checkNow) {
let latest = null;
let timer = null;
async function check(fresh = false) {
clearTimeout(timer);
try {
const state = await (await fetch(`/api/update${fresh ? "?fresh=1" : ""}`, { cache: "no-store" })).json();
if (!state.enabled) return;
if (checkNow) {
checkNow.hidden = false;
if (fresh) checkNow.textContent = state.available ? `Update ${state.latest} available ↑` : `Up to date (${state.current}) — check again`;
}
latest = state.latest;
button.hidden = !state.available;
button.textContent = `⟳ ${state.latest}`;
button.title = `A new version (${state.latest}, now ${state.current}) — click to update; the app restarts for about a minute`;
if (state.status?.state === "failed") button.title += `\nThe last update failed: ${state.status.message}`;
timer = setTimeout(check, CHECK_MS);
} catch {
timer = setTimeout(check, CHECK_MS);
}
}
checkNow?.addEventListener("click", () => check(true));
async function waitForRestart(revision) {
try {
const health = await (await fetch("/api/health", { cache: "no-store" })).json();
if (health.revision !== revision) return window.location.reload();
} catch {
// restarting: not answering for a while
}
setTimeout(() => waitForRestart(revision), RESTART_POLL_MS);
}
button.addEventListener("click", async () => {
if (!window.confirm(`Update to ${latest}? The app restarts — about a minute without it.`)) return;
button.disabled = true;
button.textContent = "Updating…";
const response = await fetch("/api/update", { method: "POST" });
const data = await response.json().catch(() => ({}));
if (!response.ok) {
window.alert(data.error || `Update failed (${response.status})`);
button.disabled = false;
return check();
}
const revision = (await (await fetch("/api/health")).json()).revision;
waitForRestart(revision);
});
check();
}
+3 -3
View File
@@ -1,10 +1,10 @@
/**
* MapLibre GL JS
* @license 3-Clause BSD. Full text of license: https://github.com/maplibre/maplibre-gl-js/blob/v6.19.0/LICENSE.txt
* @license 3-Clause BSD. Full text of license: https://github.com/maplibre/maplibre-gl-js/blob/v6.21.0/LICENSE.txt
*/
var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,o=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t,t.exports),e=null),t.exports),s=(e,i,o,s)=>{if(i&&typeof i==`object`||typeof i==`function`)for(var c=r(i),l=0,u=c.length,d;l<u;l++)d=c[l],!a.call(e,d)&&d!==o&&t(e,d,{get:(e=>i[e]).bind(null,d),enumerable:!(s=n(i,d))||s.enumerable});return e},c=(n,r,o)=>(o=n==null?{}:e(i(n)),s(r||!n||!n.__esModule||!a.call(n,`default`)?t(o,`default`,{value:n,enumerable:!0}):o,n));function l(e,t){this.x=e,this.y=t}l.prototype={clone(){return new l(this.x,this.y)},add(e){return this.clone()._add(e)},sub(e){return this.clone()._sub(e)},multByPoint(e){return this.clone()._multByPoint(e)},divByPoint(e){return this.clone()._divByPoint(e)},mult(e){return this.clone()._mult(e)},div(e){return this.clone()._div(e)},rotate(e){return this.clone()._rotate(e)},rotateAround(e,t){return this.clone()._rotateAround(e,t)},matMult(e){return this.clone()._matMult(e)},unit(){return this.clone()._unit()},perp(){return this.clone()._perp()},round(){return this.clone()._round()},mag(){return Math.sqrt(this.x*this.x+this.y*this.y)},equals(e){return this.x===e.x&&this.y===e.y},dist(e){return Math.sqrt(this.distSqr(e))},distSqr(e){let t=e.x-this.x,n=e.y-this.y;return t*t+n*n},angle(){return Math.atan2(this.y,this.x)},angleTo(e){return Math.atan2(this.y-e.y,this.x-e.x)},angleWith(e){return this.angleWithSep(e.x,e.y)},angleWithSep(e,t){return Math.atan2(this.x*t-this.y*e,this.x*e+this.y*t)},_matMult(e){let t=e[0]*this.x+e[1]*this.y,n=e[2]*this.x+e[3]*this.y;return this.x=t,this.y=n,this},_add(e){return this.x+=e.x,this.y+=e.y,this},_sub(e){return this.x-=e.x,this.y-=e.y,this},_mult(e){return this.x*=e,this.y*=e,this},_div(e){return this.x/=e,this.y/=e,this},_multByPoint(e){return this.x*=e.x,this.y*=e.y,this},_divByPoint(e){return this.x/=e.x,this.y/=e.y,this},_unit(){return this._div(this.mag()),this},_perp(){let e=this.y;return this.y=this.x,this.x=-e,this},_rotate(e){let t=Math.cos(e),n=Math.sin(e),r=t*this.x-n*this.y,i=n*this.x+t*this.y;return this.x=r,this.y=i,this},_rotateAround(e,t){let n=Math.cos(e),r=Math.sin(e),i=t.x+n*(this.x-t.x)-r*(this.y-t.y),a=t.y+r*(this.x-t.x)+n*(this.y-t.y);return this.x=i,this.y=a,this},_round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this},constructor:l},l.convert=function(e){if(e instanceof l)return e;if(Array.isArray(e))return new l(+e[0],+e[1]);if(e.x!==void 0&&e.y!==void 0)return new l(+e.x,+e.y);throw Error(`Expected [x, y] or {x, y} point format`)};function u(e,t,n,r){let i=3*e,a=3*(n-e)-i,o=1-i-a,s=3*t,c=3*(r-t)-s,l=1-s-c;return function(e,t=1e-6){if(e<=0)return 0;if(e>=1)return 1;let n=e;for(let r=0;r<8;r++){let r=((o*n+a)*n+i)*n-e;if(Math.abs(r)<t)return((l*n+c)*n+s)*n;let u=(3*o*n+2*a)*n+i;if(Math.abs(u)<1e-6)break;n-=r/u}let r=0,u=1;n=e;for(let s=0;s<20;s++){let s=((o*n+a)*n+i)*n;if(Math.abs(s-e)<t)break;e>s?r=n:u=n,n=(r+u)*.5}return((l*n+c)*n+s)*n}}let d;function f(){return d??=typeof OffscreenCanvas<`u`&&!!new OffscreenCanvas(1,1).getContext(`2d`)&&typeof createImageBitmap==`function`,d}let p;function m(){if(p==null&&(p=!1,f())){let e=new OffscreenCanvas(5,5).getContext(`2d`,{willReadFrequently:!0});if(e){for(let t=0;t<25;t++){let n=t*4;e.fillStyle=`rgb(${n},${n+1},${n+2})`,e.fillRect(t%5,Math.floor(t/5),1,1)}let t=e.getImageData(0,0,5,5).data;for(let e=0;e<100;e++)if(e%4!=3&&t[e]!==e){p=!0;break}}}return p||!1}var h=typeof Float32Array<`u`?Float32Array:Array;function g(e){return e[0]=1,e[1]=0,e[2]=0,e[3]=0,e[4]=0,e[5]=1,e[6]=0,e[7]=0,e[8]=0,e[9]=0,e[10]=1,e[11]=0,e[12]=0,e[13]=0,e[14]=0,e[15]=1,e}function _(e,t,n){var r=t[0],i=t[1],a=t[2],o=t[3],s=t[4],c=t[5],l=t[6],u=t[7],d=t[8],f=t[9],p=t[10],m=t[11],h=t[12],g=t[13],_=t[14],v=t[15],y=n[0],b=n[1],x=n[2],S=n[3];return e[0]=y*r+b*s+x*d+S*h,e[1]=y*i+b*c+x*f+S*g,e[2]=y*a+b*l+x*p+S*_,e[3]=y*o+b*u+x*m+S*v,y=n[4],b=n[5],x=n[6],S=n[7],e[4]=y*r+b*s+x*d+S*h,e[5]=y*i+b*c+x*f+S*g,e[6]=y*a+b*l+x*p+S*_,e[7]=y*o+b*u+x*m+S*v,y=n[8],b=n[9],x=n[10],S=n[11],e[8]=y*r+b*s+x*d+S*h,e[9]=y*i+b*c+x*f+S*g,e[10]=y*a+b*l+x*p+S*_,e[11]=y*o+b*u+x*m+S*v,y=n[12],b=n[13],x=n[14],S=n[15],e[12]=y*r+b*s+x*d+S*h,e[13]=y*i+b*c+x*f+S*g,e[14]=y*a+b*l+x*p+S*_,e[15]=y*o+b*u+x*m+S*v,e}function v(e,t,n){var r=n[0],i=n[1],a=n[2],o,s,c,l,u,d,f,p,m,h,g,_;return t===e?(e[12]=t[0]*r+t[4]*i+t[8]*a+t[12],e[13]=t[1]*r+t[5]*i+t[9]*a+t[13],e[14]=t[2]*r+t[6]*i+t[10]*a+t[14],e[15]=t[3]*r+t[7]*i+t[11]*a+t[15]):(o=t[0],s=t[1],c=t[2],l=t[3],u=t[4],d=t[5],f=t[6],p=t[7],m=t[8],h=t[9],g=t[10],_=t[11],e[0]=o,e[1]=s,e[2]=c,e[3]=l,e[4]=u,e[5]=d,e[6]=f,e[7]=p,e[8]=m,e[9]=h,e[10]=g,e[11]=_,e[12]=o*r+u*i+m*a+t[12],e[13]=s*r+d*i+h*a+t[13],e[14]=c*r+f*i+g*a+t[14],e[15]=l*r+p*i+_*a+t[15]),e}function y(e,t,n){var r=n[0],i=n[1],a=n[2];return e[0]=t[0]*r,e[1]=t[1]*r,e[2]=t[2]*r,e[3]=t[3]*r,e[4]=t[4]*i,e[5]=t[5]*i,e[6]=t[6]*i,e[7]=t[7]*i,e[8]=t[8]*a,e[9]=t[9]*a,e[10]=t[10]*a,e[11]=t[11]*a,e[12]=t[12Line truncated
var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,o=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t,t.exports),e=null),t.exports),s=(e,i,o,s)=>{if(i&&typeof i==`object`||typeof i==`function`)for(let c of r(i))!a.call(e,c)&&c!==o&&(s=n(i,c),t(e,c,{get:s&&s.get&&!s.configurable?s.get:()=>i[c],enumerable:!s||s.enumerable}));return e},c=(n,r,o)=>(o=n==null?{}:e(i(n)),s(r||!n||!n.__esModule||!a.call(n,`default`)?t(o,`default`,{value:n,enumerable:!0}):o,n));function l(e,t){this.x=e,this.y=t}l.prototype={clone(){return new l(this.x,this.y)},add(e){return this.clone()._add(e)},sub(e){return this.clone()._sub(e)},multByPoint(e){return this.clone()._multByPoint(e)},divByPoint(e){return this.clone()._divByPoint(e)},mult(e){return this.clone()._mult(e)},div(e){return this.clone()._div(e)},rotate(e){return this.clone()._rotate(e)},rotateAround(e,t){return this.clone()._rotateAround(e,t)},matMult(e){return this.clone()._matMult(e)},unit(){return this.clone()._unit()},perp(){return this.clone()._perp()},round(){return this.clone()._round()},mag(){return Math.sqrt(this.x*this.x+this.y*this.y)},equals(e){return this.x===e.x&&this.y===e.y},dist(e){return Math.sqrt(this.distSqr(e))},distSqr(e){let t=e.x-this.x,n=e.y-this.y;return t*t+n*n},angle(){return Math.atan2(this.y,this.x)},angleTo(e){return Math.atan2(this.y-e.y,this.x-e.x)},angleWith(e){return this.angleWithSep(e.x,e.y)},angleWithSep(e,t){return Math.atan2(this.x*t-this.y*e,this.x*e+this.y*t)},_matMult(e){let t=e[0]*this.x+e[1]*this.y,n=e[2]*this.x+e[3]*this.y;return this.x=t,this.y=n,this},_add(e){return this.x+=e.x,this.y+=e.y,this},_sub(e){return this.x-=e.x,this.y-=e.y,this},_mult(e){return this.x*=e,this.y*=e,this},_div(e){return this.x/=e,this.y/=e,this},_multByPoint(e){return this.x*=e.x,this.y*=e.y,this},_divByPoint(e){return this.x/=e.x,this.y/=e.y,this},_unit(){return this._div(this.mag()),this},_perp(){let e=this.y;return this.y=this.x,this.x=-e,this},_rotate(e){let t=Math.cos(e),n=Math.sin(e),r=t*this.x-n*this.y,i=n*this.x+t*this.y;return this.x=r,this.y=i,this},_rotateAround(e,t){let n=Math.cos(e),r=Math.sin(e),i=t.x+n*(this.x-t.x)-r*(this.y-t.y),a=t.y+r*(this.x-t.x)+n*(this.y-t.y);return this.x=i,this.y=a,this},_round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this},constructor:l},l.convert=function(e){if(e instanceof l)return e;if(Array.isArray(e))return new l(+e[0],+e[1]);if(e.x!==void 0&&e.y!==void 0)return new l(+e.x,+e.y);throw Error(`Expected [x, y] or {x, y} point format`)};function u(e,t,n,r){let i=3*e,a=3*(n-e)-i,o=1-i-a,s=3*t,c=3*(r-t)-s,l=1-s-c;return function(e,t=1e-6){if(e<=0)return 0;if(e>=1)return 1;let n=e;for(let r=0;r<8;r++){let r=((o*n+a)*n+i)*n-e;if(Math.abs(r)<t)return((l*n+c)*n+s)*n;let u=(3*o*n+2*a)*n+i;if(Math.abs(u)<1e-6)break;n-=r/u}let r=0,u=1;n=e;for(let s=0;s<20;s++){let s=((o*n+a)*n+i)*n;if(Math.abs(s-e)<t)break;e>s?r=n:u=n,n=(r+u)*.5}return((l*n+c)*n+s)*n}}let d;function f(){return d??=typeof OffscreenCanvas<`u`&&!!new OffscreenCanvas(1,1).getContext(`2d`)&&typeof createImageBitmap==`function`,d}let p;function m(){if(p==null&&(p=!1,f())){let e=new OffscreenCanvas(5,5).getContext(`2d`,{willReadFrequently:!0});if(e){for(let t=0;t<25;t++){let n=t*4;e.fillStyle=`rgb(${n},${n+1},${n+2})`,e.fillRect(t%5,Math.floor(t/5),1,1)}let t=e.getImageData(0,0,5,5).data;for(let e=0;e<100;e++)if(e%4!=3&&t[e]!==e){p=!0;break}}}return p||!1}var h=typeof Float32Array<`u`?Float32Array:Array;function g(e,t){return e[0]=t[0],e[1]=t[1],e[2]=t[2],e[3]=t[3],e[4]=t[4],e[5]=t[5],e[6]=t[6],e[7]=t[7],e[8]=t[8],e[9]=t[9],e[10]=t[10],e[11]=t[11],e[12]=t[12],e[13]=t[13],e[14]=t[14],e[15]=t[15],e}function _(e){return e[0]=1,e[1]=0,e[2]=0,e[3]=0,e[4]=0,e[5]=1,e[6]=0,e[7]=0,e[8]=0,e[9]=0,e[10]=1,e[11]=0,e[12]=0,e[13]=0,e[14]=0,e[15]=1,e}function v(e,t,n){var r=t[0],i=t[1],a=t[2],o=t[3],s=t[4],c=t[5],l=t[6],u=t[7],d=t[8],f=t[9],p=t[10],m=t[11],h=t[12],g=t[13],_=t[14],v=t[15],y=n[0],b=n[1],x=n[2],S=n[3];return e[0]=y*r+b*s+x*d+S*h,e[1]=y*i+b*c+x*f+S*g,e[2]=y*a+b*l+x*p+S*_,e[3]=y*o+b*u+x*m+S*v,y=n[4],b=n[5],x=n[6],S=n[7],e[4]=y*r+b*s+x*d+S*h,e[5]=y*i+b*c+x*f+S*g,e[6]=y*a+b*l+x*p+S*_,e[7]=y*o+b*u+x*m+S*v,y=n[8],b=n[9],x=n[10],S=n[11],e[8]=y*r+b*s+x*d+S*h,e[9]=y*i+b*c+x*f+S*g,e[10]=y*a+b*l+x*p+S*_,e[11]=y*o+b*u+x*m+S*v,y=n[12],b=n[13],x=n[14],S=n[15],e[12]=y*r+b*s+x*d+S*h,e[13]=y*i+b*c+x*f+S*g,e[14]=y*a+b*l+x*p+S*_,e[15]=y*o+b*u+x*m+S*v,e}function y(e,t,n){var r=n[0],i=n[1],a=n[2],o,s,c,l,u,d,f,p,m,h,g,_;return t===e?(e[12]=t[0]*r+t[4]*i+t[8]*a+t[12],e[13]=t[1]*r+t[5]*i+t[9]*a+t[13],e[14]=t[2]*r+t[6]*i+t[10]*a+t[14],e[15]=t[3]*r+t[7]*i+t[11]*a+t[15]):(o=t[0],s=t[1],c=t[2],l=t[3],u=t[4],d=t[5],f=t[6],p=t[7],m=t[8],h=t[9],g=t[10],_=t[11],e[0]=o,e[1]=s,e[2]=c,e[3]=l,e[4]=u,e[5]=d,e[6]=f,e[7]=p,e[8]=m,e[9]=h,e[10]=g,e[11]=_,e[12]=o*r+u*i+m*a+t[12],e[13]=s*r+d*i+h*a+t[13],e[14]=c*r+f*i+g*a+t[14],e[15]=l*r+p*i+_*a+t[15]),e}function b(e,t,n){vaLine truncated
/* @vite-ignore */
e);return}let t=await fetch(e,{credentials:`same-origin`});if(!t.ok)throw Error(`Failed to load ${e}: ${t.status}`);let n=await t.text();if(/^[ \t]*(import|export)\s/m.test(n)){let e=URL.createObjectURL(new Blob([n],{type:`text/javascript`}));try{await import(
/* @vite-ignore */
e)}finally{URL.revokeObjectURL(e)}}else globalThis.eval(n)}var yT=class{constructor(e){this.self=e,this.actor=new vs(e),this.layerIndexes={},this.availableImages={},this.workerSources={},this.demWorkerSources={},this.externalWorkerSourceTypes={},this.globalStates=/* @__PURE__ */ new Map,this.importedScripts=/* @__PURE__ */ new Map,this.self.registerWorkerSource=(e,t)=>{if(this.externalWorkerSourceTypes[e])throw Error(`Worker source with name "${e}" already registered.`);this.externalWorkerSourceTypes[e]=t},this.self.addProtocol=Qo,this.self.removeProtocol=$o,this.self.registerRTLTextPlugin=e=>{dg.setMethods(e)},this.self.makeRequest=os,this.self.setProjectionHandler=lT,this.actor.registerMessageHandler(`LDT`,(e,t)=>this._getDEMWorkerSource(e,t.source).loadTile(t)),this.actor.registerMessageHandler(`RDT`,async(e,t)=>{this._getDEMWorkerSource(e,t.source).removeTile(t)}),this.actor.registerMessageHandler(`GCEZ`,async(e,t)=>this._getWorkerSource(e,t.type,t.source).getClusterExpansionZoom(t)),this.actor.registerMessageHandler(`GCC`,async(e,t)=>this._getWorkerSource(e,t.type,t.source).getClusterChildren(t)),this.actor.registerMessageHandler(`GCL`,async(e,t)=>this._getWorkerSource(e,t.type,t.source).getClusterLeaves(t)),this.actor.registerMessageHandler(`LD`,(e,t)=>this._getWorkerSource(e,t.type,t.source).loadData(t)),this.actor.registerMessageHandler(`LT`,(e,t)=>this._getWorkerSource(e,t.type,t.source).loadTile(t)),this.actor.registerMessageHandler(`RT`,(e,t)=>this._getWorkerSource(e,t.type,t.source).reloadTile(t)),this.actor.registerMessageHandler(`AT`,(e,t)=>this._getWorkerSource(e,t.type,t.source).abortTile(t)),this.actor.registerMessageHandler(`RMT`,(e,t)=>this._getWorkerSource(e,t.type,t.source).removeTile(t)),this.actor.registerMessageHandler(`RS`,async(e,t)=>{if(!this.workerSources[e]?.[t.type]?.[t.source])return;let n=this.workerSources[e][t.type][t.source];delete this.workerSources[e][t.type][t.source],n.removeSource!==void 0&&n.removeSource(t)}),this.actor.registerMessageHandler(`RM`,async e=>{delete this.layerIndexes[e],delete this.availableImages[e],delete this.workerSources[e],delete this.demWorkerSources[e],this.globalStates.delete(e)}),this.actor.registerMessageHandler(`SR`,async(e,t)=>{this.referrer=t}),this.actor.registerMessageHandler(`PI`,async()=>{}),this.actor.registerMessageHandler(`SRPS`,(e,t)=>this._syncRTLPluginState(e,t)),this.actor.registerMessageHandler(`IS`,(e,t)=>this._importScript(t)),this.actor.registerMessageHandler(`SI`,(e,t)=>this._setImages(e,t)),this.actor.registerMessageHandler(`UL`,async(e,t)=>{this._getLayerIndex(e).update(t.layers,t.removedIds,this._getGlobalState(e))}),this.actor.registerMessageHandler(`UGS`,async(e,t)=>{let n=this._getGlobalState(e);for(let e in t)n[e]=t[e]}),this.actor.registerMessageHandler(`SL`,async(e,t)=>{this._getLayerIndex(e).replace(t,this._getGlobalState(e))})}async _importScript(e){let t=this.importedScripts.get(e);if(t)return t;let n=vT(e);this.importedScripts.set(e,n);try{await n}catch(t){throw this.importedScripts.delete(e),t}}_getGlobalState(e){let t=this.globalStates.get(e);return t||(t={},this.globalStates.set(e,t)),t}async _setImages(e,t){this.availableImages[e]=t;for(let n in this.workerSources[e]){let r=this.workerSources[e][n];for(let e in r)r[e].availableImages=t}}async _syncRTLPluginState(e,t){return await dg.syncState(t,e=>this._importScript(e))}_getAvailableImages(e){let t=this.availableImages[e];return t||=[],t}_getLayerIndex(e){let t=this.layerIndexes[e];return t||=this.layerIndexes[e]=new Gw,t}_getWorkerSource(e,t,n){if(this.workerSources[e]||={},this.workerSources[e][t]||={},!this.workerSources[e][t][n]){let r={sendAsync:(t,n)=>(t.targetMapId=e,this.actor.sendAsync(t,n))};switch(t){case`vector`:this.workerSources[e][t][n]=new nT(r,this._getLayerIndex(e),this._getAvailableImages(e));break;case`geojson`:this.workerSources[e][t][n]=new hT(r,this._getLayerIndex(e),this._getAvailableImages(e));break;default:this.workerSources[e][t][n]=new this.externalWorkerSourceTypes[t](r,this._getLayerIndex(e),this._getAvailableImages(e))}}return this.workerSources[e][t][n]}_getDEMWorkerSource(e,t){return this.demWorkerSources[e]||={},this.demWorkerSources[e][t]||=new rT,this.demWorkerSources[e][t]}};Oe(self)&&(self.worker=new yT(self));export{yT as default};
e)}finally{URL.revokeObjectURL(e)}}else globalThis.eval(n)}var f3=class{constructor(e){this.self=e,this.actor=new Do(e),this.layerIndexes={},this.availableImages={},this.workerSources={},this.demWorkerSources={},this.externalWorkerSourceTypes={},this.globalStates=/* @__PURE__ */ new Map,this.importedScripts=/* @__PURE__ */ new Map,this.self.registerWorkerSource=(e,t)=>{if(this.externalWorkerSourceTypes[e])throw Error(`Worker source with name "${e}" already registered.`);this.externalWorkerSourceTypes[e]=t},this.self.addProtocol=oo,this.self.removeProtocol=so,this.self.registerRTLTextPlugin=e=>{ch.setMethods(e)},this.self.makeRequest=ho,this.self.setProjectionHandler=n3,this.actor.registerMessageHandler(`LDT`,(e,t)=>this._getDEMWorkerSource(e,t.source).loadTile(t)),this.actor.registerMessageHandler(`RDT`,async(e,t)=>{this._getDEMWorkerSource(e,t.source).removeTile(t)}),this.actor.registerMessageHandler(`GCEZ`,async(e,t)=>this._getWorkerSource(e,t.type,t.source).getClusterExpansionZoom(t)),this.actor.registerMessageHandler(`GCC`,async(e,t)=>this._getWorkerSource(e,t.type,t.source).getClusterChildren(t)),this.actor.registerMessageHandler(`GCL`,async(e,t)=>this._getWorkerSource(e,t.type,t.source).getClusterLeaves(t)),this.actor.registerMessageHandler(`LD`,(e,t)=>this._getWorkerSource(e,t.type,t.source).loadData(t)),this.actor.registerMessageHandler(`LT`,(e,t)=>this._getWorkerSource(e,t.type,t.source).loadTile(t)),this.actor.registerMessageHandler(`RT`,(e,t)=>this._getWorkerSource(e,t.type,t.source).reloadTile(t)),this.actor.registerMessageHandler(`AT`,(e,t)=>this._getWorkerSource(e,t.type,t.source).abortTile(t)),this.actor.registerMessageHandler(`RMT`,(e,t)=>this._getWorkerSource(e,t.type,t.source).removeTile(t)),this.actor.registerMessageHandler(`RS`,async(e,t)=>{if(!this.workerSources[e]?.[t.type]?.[t.source])return;let n=this.workerSources[e][t.type][t.source];delete this.workerSources[e][t.type][t.source],n.removeSource!==void 0&&n.removeSource(t)}),this.actor.registerMessageHandler(`RM`,async e=>{delete this.layerIndexes[e],delete this.availableImages[e],delete this.workerSources[e],delete this.demWorkerSources[e],this.globalStates.delete(e)}),this.actor.registerMessageHandler(`SR`,async(e,t)=>{this.referrer=t}),this.actor.registerMessageHandler(`PI`,async()=>{}),this.actor.registerMessageHandler(`SRPS`,(e,t)=>this._syncRTLPluginState(e,t)),this.actor.registerMessageHandler(`IS`,(e,t)=>this._importScript(t)),this.actor.registerMessageHandler(`SI`,(e,t)=>this._setImages(e,t)),this.actor.registerMessageHandler(`UL`,async(e,t)=>{this._getLayerIndex(e).update(t.layers,t.removedIds,this._getGlobalState(e))}),this.actor.registerMessageHandler(`UGS`,async(e,t)=>{let n=this._getGlobalState(e);for(let e in t)n[e]=t[e]}),this.actor.registerMessageHandler(`SL`,async(e,t)=>{this._getLayerIndex(e).replace(t,this._getGlobalState(e))})}async _importScript(e){let t=this.importedScripts.get(e);if(t)return t;let n=d3(e);this.importedScripts.set(e,n);try{await n}catch(t){throw this.importedScripts.delete(e),t}}_getGlobalState(e){let t=this.globalStates.get(e);return t||(t={},this.globalStates.set(e,t)),t}async _setImages(e,t){this.availableImages[e]=t;for(let n in this.workerSources[e]){let r=this.workerSources[e][n];for(let e in r)r[e].availableImages=t}}async _syncRTLPluginState(e,t){return await ch.syncState(t,e=>this._importScript(e))}_getAvailableImages(e){let t=this.availableImages[e];return t||=[],t}_getLayerIndex(e){let t=this.layerIndexes[e];return t||=this.layerIndexes[e]=new I4,t}_getWorkerSource(e,t,n){if(this.workerSources[e]||={},this.workerSources[e][t]||={},!this.workerSources[e][t][n]){let r={sendAsync:(t,n)=>(t.targetMapId=e,this.actor.sendAsync(t,n))};switch(t){case`vector`:this.workerSources[e][t][n]=new q4(r,this._getLayerIndex(e),this._getAvailableImages(e));break;case`geojson`:this.workerSources[e][t][n]=new c3(r,this._getLayerIndex(e),this._getAvailableImages(e));break;default:this.workerSources[e][t][n]=new this.externalWorkerSourceTypes[t](r,this._getLayerIndex(e),this._getAvailableImages(e))}}return this.workerSources[e][t][n]}_getDEMWorkerSource(e,t){return this.demWorkerSources[e]||={},this.demWorkerSources[e][t]||=new X4,this.demWorkerSources[e][t]}};ke(self)&&(self.worker=new f3(self));export{f3 as default};
//# sourceMappingURL=maplibre-gl-worker.mjs.map
+106 -59
View File
@@ -1,8 +1,8 @@
/**
* MapLibre GL JS
* @license 3-Clause BSD. Full text of license: https://github.com/maplibre/maplibre-gl-js/blob/v6.19.0/LICENSE.txt
* @license 3-Clause BSD. Full text of license: https://github.com/maplibre/maplibre-gl-js/blob/v6.21.0/LICENSE.txt
*/
var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,o=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t,t.exports),e=null),t.exports),s=(e,i,o,s)=>{if(i&&typeof i==`object`||typeof i==`function`)for(var c=r(i),l=0,u=c.length,d;l<u;l++)d=c[l],!a.call(e,d)&&d!==o&&t(e,d,{get:(e=>i[e]).bind(null,d),enumerable:!(s=n(i,d))||s.enumerable});return e},c=(n,r,o)=>(o=n==null?{}:e(i(n)),s(r||!n||!n.__esModule||!a.call(n,`default`)?t(o,`default`,{value:n,enumerable:!0}):o,n)),l=`6.19.0`;function u(e,t){this.x=e,this.y=t}u.prototype={clone(){return new u(this.x,this.y)},add(e){return this.clone()._add(e)},sub(e){return this.clone()._sub(e)},multByPoint(e){return this.clone()._multByPoint(e)},divByPoint(e){return this.clone()._divByPoint(e)},mult(e){return this.clone()._mult(e)},div(e){return this.clone()._div(e)},rotate(e){return this.clone()._rotate(e)},rotateAround(e,t){return this.clone()._rotateAround(e,t)},matMult(e){return this.clone()._matMult(e)},unit(){return this.clone()._unit()},perp(){return this.clone()._perp()},round(){return this.clone()._round()},mag(){return Math.sqrt(this.x*this.x+this.y*this.y)},equals(e){return this.x===e.x&&this.y===e.y},dist(e){return Math.sqrt(this.distSqr(e))},distSqr(e){let t=e.x-this.x,n=e.y-this.y;return t*t+n*n},angle(){return Math.atan2(this.y,this.x)},angleTo(e){return Math.atan2(this.y-e.y,this.x-e.x)},angleWith(e){return this.angleWithSep(e.x,e.y)},angleWithSep(e,t){return Math.atan2(this.x*t-this.y*e,this.x*e+this.y*t)},_matMult(e){let t=e[0]*this.x+e[1]*this.y,n=e[2]*this.x+e[3]*this.y;return this.x=t,this.y=n,this},_add(e){return this.x+=e.x,this.y+=e.y,this},_sub(e){return this.x-=e.x,this.y-=e.y,this},_mult(e){return this.x*=e,this.y*=e,this},_div(e){return this.x/=e,this.y/=e,this},_multByPoint(e){return this.x*=e.x,this.y*=e.y,this},_divByPoint(e){return this.x/=e.x,this.y/=e.y,this},_unit(){return this._div(this.mag()),this},_perp(){let e=this.y;return this.y=this.x,this.x=-e,this},_rotate(e){let t=Math.cos(e),n=Math.sin(e),r=t*this.x-n*this.y,i=n*this.x+t*this.y;return this.x=r,this.y=i,this},_rotateAround(e,t){let n=Math.cos(e),r=Math.sin(e),i=t.x+n*(this.x-t.x)-r*(this.y-t.y),a=t.y+r*(this.x-t.x)+n*(this.y-t.y);return this.x=i,this.y=a,this},_round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this},constructor:u},u.convert=function(e){if(e instanceof u)return e;if(Array.isArray(e))return new u(+e[0],+e[1]);if(e.x!==void 0&&e.y!==void 0)return new u(+e.x,+e.y);throw Error(`Expected [x, y] or {x, y} point format`)};function d(e,t,n,r){let i=3*e,a=3*(n-e)-i,o=1-i-a,s=3*t,c=3*(r-t)-s,l=1-s-c;return function(e,t=1e-6){if(e<=0)return 0;if(e>=1)return 1;let n=e;for(let r=0;r<8;r++){let r=((o*n+a)*n+i)*n-e;if(Math.abs(r)<t)return((l*n+c)*n+s)*n;let u=(3*o*n+2*a)*n+i;if(Math.abs(u)<1e-6)break;n-=r/u}let r=0,u=1;n=e;for(let s=0;s<20;s++){let s=((o*n+a)*n+i)*n;if(Math.abs(s-e)<t)break;e>s?r=n:u=n,n=(r+u)*.5}return((l*n+c)*n+s)*n}}let f;function p(){return f??=typeof OffscreenCanvas<`u`&&!!new OffscreenCanvas(1,1).getContext(`2d`)&&typeof createImageBitmap==`function`,f}let m;function h(){if(m==null&&(m=!1,p())){let e=new OffscreenCanvas(5,5).getContext(`2d`,{willReadFrequently:!0});if(e){for(let t=0;t<25;t++){let n=t*4;e.fillStyle=`rgb(${n},${n+1},${n+2})`,e.fillRect(t%5,Math.floor(t/5),1,1)}let t=e.getImageData(0,0,5,5).data;for(let e=0;e<100;e++)if(e%4!=3&&t[e]!==e){m=!0;break}}}return m||!1}var g=typeof Float32Array<`u`?Float32Array:Array;function _(){var e=new g(4);return g!=Float32Array&&(e[1]=0,e[2]=0),e[0]=1,e[3]=1,e}function v(e,t){var n=t[0],r=t[1],i=t[2],a=t[3],o=n*a-i*r;return o?(o=1/o,e[0]=a*o,e[1]=-r*o,e[2]=-i*o,e[3]=n*o,e):null}function y(e){return e[0]*e[3]-e[2]*e[1]}function b(e,t,n){var r=t[0],i=t[1],a=t[2],o=t[3],s=Math.sin(n),c=Math.cos(n);return e[0]=r*c+a*s,e[1]=i*c+o*s,e[2]=r*-s+a*c,e[3]=i*-s+o*c,e}function x(){var e=new g(9);return g!=Float32Array&&(e[1]=0,e[2]=0,e[3]=0,e[5]=0,e[6]=0,e[7]=0),e[0]=1,e[4]=1,e[8]=1,e}function S(e){var t=e[0],n=e[1],r=e[2],i=e[3],a=e[4],o=e[5],s=e[6],c=e[7],l=e[8];return t*(l*a-o*c)+n*(-l*i+o*s)+r*(c*i-a*s)}function C(e,t){var n=Math.sin(t),r=Math.cos(t);return e[0]=r,e[1]=n,e[2]=0,e[3]=-n,e[4]=r,e[5]=0,e[6]=0,e[7]=0,e[8]=1,e}function w(e,t){var n=t[0],r=t[1],i=t[2],a=t[3],o=n+n,s=r+r,c=i+i,l=n*o,u=r*o,d=r*s,f=i*o,p=i*s,m=i*c,h=a*o,g=a*s,_=a*c;return e[0]=1-d-m,e[3]=u-_,e[6]=f+g,e[1]=u+_,e[4]=1-l-m,e[7]=p-h,e[2]=f-g,e[5]=p+h,e[8]=1-l-d,e}function T(){var e=new g(16);return g!=Float32Array&&(e[1]=0,e[2]=0,e[3]=0,e[4]=0,e[6]=0,e[7]=0,e[8]=0,e[9]=0,e[11]=0,e[12]=0,e[13]=0,e[14]=0),e[0]=1,e[5]=1,e[10]=1,e[15]=1,e}function E(e){var t=new g(16);return t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=e[3],t[4]=e[4],t[5]=e[5],t[6]=e[6],t[7]=e[7],t[8]=e[8],t[9]=e[9],t[10]=e[10],t[11]=e[11],t[12]=e[12],t[13]=e[13],t[14]=e[14],t[15]=e[15],t}function D(e,t){return e[0]=t[0],e[1]=t[1],e[2]=t[2],e[3]=t[3],e[4]=t[4],e[5]=t[5]Line truncated
var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,o=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t,t.exports),e=null),t.exports),s=(e,i,o,s)=>{if(i&&typeof i==`object`||typeof i==`function`)for(let c of r(i))!a.call(e,c)&&c!==o&&(s=n(i,c),t(e,c,{get:s&&s.get&&!s.configurable?s.get:()=>i[c],enumerable:!s||s.enumerable}));return e},c=(n,r,o)=>(o=n==null?{}:e(i(n)),s(r||!n||!n.__esModule||!a.call(n,`default`)?t(o,`default`,{value:n,enumerable:!0}):o,n)),l=`6.21.0`;function u(e,t){this.x=e,this.y=t}u.prototype={clone(){return new u(this.x,this.y)},add(e){return this.clone()._add(e)},sub(e){return this.clone()._sub(e)},multByPoint(e){return this.clone()._multByPoint(e)},divByPoint(e){return this.clone()._divByPoint(e)},mult(e){return this.clone()._mult(e)},div(e){return this.clone()._div(e)},rotate(e){return this.clone()._rotate(e)},rotateAround(e,t){return this.clone()._rotateAround(e,t)},matMult(e){return this.clone()._matMult(e)},unit(){return this.clone()._unit()},perp(){return this.clone()._perp()},round(){return this.clone()._round()},mag(){return Math.sqrt(this.x*this.x+this.y*this.y)},equals(e){return this.x===e.x&&this.y===e.y},dist(e){return Math.sqrt(this.distSqr(e))},distSqr(e){let t=e.x-this.x,n=e.y-this.y;return t*t+n*n},angle(){return Math.atan2(this.y,this.x)},angleTo(e){return Math.atan2(this.y-e.y,this.x-e.x)},angleWith(e){return this.angleWithSep(e.x,e.y)},angleWithSep(e,t){return Math.atan2(this.x*t-this.y*e,this.x*e+this.y*t)},_matMult(e){let t=e[0]*this.x+e[1]*this.y,n=e[2]*this.x+e[3]*this.y;return this.x=t,this.y=n,this},_add(e){return this.x+=e.x,this.y+=e.y,this},_sub(e){return this.x-=e.x,this.y-=e.y,this},_mult(e){return this.x*=e,this.y*=e,this},_div(e){return this.x/=e,this.y/=e,this},_multByPoint(e){return this.x*=e.x,this.y*=e.y,this},_divByPoint(e){return this.x/=e.x,this.y/=e.y,this},_unit(){return this._div(this.mag()),this},_perp(){let e=this.y;return this.y=this.x,this.x=-e,this},_rotate(e){let t=Math.cos(e),n=Math.sin(e),r=t*this.x-n*this.y,i=n*this.x+t*this.y;return this.x=r,this.y=i,this},_rotateAround(e,t){let n=Math.cos(e),r=Math.sin(e),i=t.x+n*(this.x-t.x)-r*(this.y-t.y),a=t.y+r*(this.x-t.x)+n*(this.y-t.y);return this.x=i,this.y=a,this},_round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this},constructor:u},u.convert=function(e){if(e instanceof u)return e;if(Array.isArray(e))return new u(+e[0],+e[1]);if(e.x!==void 0&&e.y!==void 0)return new u(+e.x,+e.y);throw Error(`Expected [x, y] or {x, y} point format`)};function d(e,t,n,r){let i=3*e,a=3*(n-e)-i,o=1-i-a,s=3*t,c=3*(r-t)-s,l=1-s-c;return function(e,t=1e-6){if(e<=0)return 0;if(e>=1)return 1;let n=e;for(let r=0;r<8;r++){let r=((o*n+a)*n+i)*n-e;if(Math.abs(r)<t)return((l*n+c)*n+s)*n;let u=(3*o*n+2*a)*n+i;if(Math.abs(u)<1e-6)break;n-=r/u}let r=0,u=1;n=e;for(let s=0;s<20;s++){let s=((o*n+a)*n+i)*n;if(Math.abs(s-e)<t)break;e>s?r=n:u=n,n=(r+u)*.5}return((l*n+c)*n+s)*n}}let f;function p(){return f??=typeof OffscreenCanvas<`u`&&!!new OffscreenCanvas(1,1).getContext(`2d`)&&typeof createImageBitmap==`function`,f}let m;function h(){if(m==null&&(m=!1,p())){let e=new OffscreenCanvas(5,5).getContext(`2d`,{willReadFrequently:!0});if(e){for(let t=0;t<25;t++){let n=t*4;e.fillStyle=`rgb(${n},${n+1},${n+2})`,e.fillRect(t%5,Math.floor(t/5),1,1)}let t=e.getImageData(0,0,5,5).data;for(let e=0;e<100;e++)if(e%4!=3&&t[e]!==e){m=!0;break}}}return m||!1}var g=typeof Float32Array<`u`?Float32Array:Array;function _(){var e=new g(4);return g!=Float32Array&&(e[1]=0,e[2]=0),e[0]=1,e[3]=1,e}function v(e,t){var n=t[0],r=t[1],i=t[2],a=t[3],o=n*a-i*r;return o?(o=1/o,e[0]=a*o,e[1]=-r*o,e[2]=-i*o,e[3]=n*o,e):null}function y(e){return e[0]*e[3]-e[2]*e[1]}function b(e,t,n){var r=t[0],i=t[1],a=t[2],o=t[3],s=Math.sin(n),c=Math.cos(n);return e[0]=r*c+a*s,e[1]=i*c+o*s,e[2]=r*-s+a*c,e[3]=i*-s+o*c,e}function x(){var e=new g(9);return g!=Float32Array&&(e[1]=0,e[2]=0,e[3]=0,e[5]=0,e[6]=0,e[7]=0),e[0]=1,e[4]=1,e[8]=1,e}function S(e){var t=e[0],n=e[1],r=e[2],i=e[3],a=e[4],o=e[5],s=e[6],c=e[7],l=e[8];return t*(l*a-o*c)+n*(-l*i+o*s)+r*(c*i-a*s)}function C(e,t){var n=Math.sin(t),r=Math.cos(t);return e[0]=r,e[1]=n,e[2]=0,e[3]=-n,e[4]=r,e[5]=0,e[6]=0,e[7]=0,e[8]=1,e}function w(e,t){var n=t[0],r=t[1],i=t[2],a=t[3],o=n+n,s=r+r,c=i+i,l=n*o,u=r*o,d=r*s,f=i*o,p=i*s,m=i*c,h=a*o,g=a*s,_=a*c;return e[0]=1-d-m,e[3]=u-_,e[6]=f+g,e[1]=u+_,e[4]=1-l-m,e[7]=p-h,e[2]=f-g,e[5]=p+h,e[8]=1-l-d,e}function T(){var e=new g(16);return g!=Float32Array&&(e[1]=0,e[2]=0,e[3]=0,e[4]=0,e[6]=0,e[7]=0,e[8]=0,e[9]=0,e[11]=0,e[12]=0,e[13]=0,e[14]=0),e[0]=1,e[5]=1,e[10]=1,e[15]=1,e}function E(e){var t=new g(16);return t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=e[3],t[4]=e[4],t[5]=e[5],t[6]=e[6],t[7]=e[7],t[8]=e[8],t[9]=e[9],t[10]=e[10],t[11]=e[11],t[12]=e[12],t[13]=e[13],t[14]=e[14],t[15]=e[15],t}function D(e,t){return e[0]=t[0],e[1]=t[1],e[2]=t[2],e[3]=t[3],e[4]=t[4],e[5]=t[5],e[6]=t[6Line truncated
precision mediump float;
#else
#if !defined(lowp)
@@ -15,7 +15,7 @@ precision mediump float;
#define highp
#endif
#endif
out highp vec4 fragColor;layout(std140) uniform ProjectionUBO {highp mat4 u_projection_matrix;highp mat4 u_projection_fallback_matrix;highp vec4 u_projection_tile_mercator_coords;highp vec4 u_projection_clipping_plane;highp float u_projection_transition;highp int u_projection_clip_antimeridian;};layout(std140) uniform FrameUBO {highp vec2 u_units_to_pixels;highp vec2 u_world_size;highp float u_camera_to_center_distance;highp float u_symbol_fade_change;highp float u_aspect_ratio;highp float u_device_pixel_ratio;highp vec2 u_viewport_size;highp vec2 u_pixel_extrude_scale;highp float u_pitch;};`,FA=`#ifdef GL_ES
out highp vec4 fragColor;layout(std140) uniform ProjectionUBO {highp mat4 u_projection_matrix;highp mat4 u_projection_fallback_matrix;highp vec4 u_projection_tile_mercator_coords;highp vec4 u_projection_clipping_plane;highp vec4 u_projection_tile_origin;highp vec2 u_projection_tile_origin_position;highp float u_projection_transition;highp int u_projection_clip_antimeridian;};layout(std140) uniform FrameUBO {highp vec2 u_units_to_pixels;highp vec2 u_world_size;highp float u_camera_to_center_distance;highp float u_symbol_fade_change;highp float u_aspect_ratio;highp float u_device_pixel_ratio;highp vec2 u_viewport_size;highp vec2 u_pixel_extrude_scale;highp float u_pitch;};`,t9=`#ifdef GL_ES
precision highp float;
#else
#if !defined(lowp)
@@ -63,15 +63,15 @@ return 0.0;
#endif
}const float PI=3.141592653589793;
#define PROJECTION_UBO
layout(std140) uniform ProjectionUBO {highp mat4 u_projection_matrix;highp mat4 u_projection_fallback_matrix;highp vec4 u_projection_tile_mercator_coords;highp vec4 u_projection_clipping_plane;highp float u_projection_transition;highp int u_projection_clip_antimeridian;};layout(std140) uniform FrameUBO {highp vec2 u_units_to_pixels;highp vec2 u_world_size;highp float u_camera_to_center_distance;highp float u_symbol_fade_change;highp float u_aspect_ratio;highp float u_device_pixel_ratio;highp vec2 u_viewport_size;highp vec2 u_pixel_extrude_scale;highp float u_pitch;};`,IA=`uniform vec4 u_color;uniform float u_opacity;void main() {fragColor=u_color*u_opacity;
layout(std140) uniform ProjectionUBO {highp mat4 u_projection_matrix;highp mat4 u_projection_fallback_matrix;highp vec4 u_projection_tile_mercator_coords;highp vec4 u_projection_clipping_plane;highp vec4 u_projection_tile_origin;highp vec2 u_projection_tile_origin_position;highp float u_projection_transition;highp int u_projection_clip_antimeridian;};layout(std140) uniform FrameUBO {highp vec2 u_units_to_pixels;highp vec2 u_world_size;highp float u_camera_to_center_distance;highp float u_symbol_fade_change;highp float u_aspect_ratio;highp float u_device_pixel_ratio;highp vec2 u_viewport_size;highp vec2 u_pixel_extrude_scale;highp float u_pitch;};`,n9=`uniform vec4 u_color;uniform float u_opacity;void main() {fragColor=u_color*u_opacity;
#ifdef OVERDRAW_INSPECTOR
fragColor=vec4(1.0);
#endif
}`,LA=`layout(location=0) in vec2 a_pos;void main() {gl_Position=projectTile(a_pos,a_pos);}`,RA=`uniform vec2 u_pattern_tl_a;uniform vec2 u_pattern_br_a;uniform vec2 u_pattern_tl_b;uniform vec2 u_pattern_br_b;uniform vec2 u_texsize;uniform float u_mix;uniform float u_opacity;uniform sampler2D u_image;in vec2 v_pos_a;in vec2 v_pos_b;void main() {vec2 imagecoord=mod(v_pos_a,1.0);vec2 pos=mix(u_pattern_tl_a/u_texsize,u_pattern_br_a/u_texsize,imagecoord);vec4 color1=texture(u_image,pos);vec2 imagecoord_b=mod(v_pos_b,1.0);vec2 pos2=mix(u_pattern_tl_b/u_texsize,u_pattern_br_b/u_texsize,imagecoord_b);vec4 color2=texture(u_image,pos2);fragColor=mix(color1,color2,u_mix)*u_opacity;
}`,r9=`layout(location=0) in vec2 a_pos;void main() {gl_Position=projectTile(a_pos,a_pos);}`,i9=`uniform vec2 u_pattern_tl_a;uniform vec2 u_pattern_br_a;uniform vec2 u_pattern_tl_b;uniform vec2 u_pattern_br_b;uniform vec2 u_texsize;uniform float u_mix;uniform float u_opacity;uniform sampler2D u_image;in vec2 v_pos_a;in vec2 v_pos_b;void main() {vec2 imagecoord=mod(v_pos_a,1.0);vec2 pos=mix(u_pattern_tl_a/u_texsize,u_pattern_br_a/u_texsize,imagecoord);vec4 color1=texture(u_image,pos);vec2 imagecoord_b=mod(v_pos_b,1.0);vec2 pos2=mix(u_pattern_tl_b/u_texsize,u_pattern_br_b/u_texsize,imagecoord_b);vec4 color2=texture(u_image,pos2);fragColor=mix(color1,color2,u_mix)*u_opacity;
#ifdef OVERDRAW_INSPECTOR
fragColor=vec4(1.0);
#endif
}`,zA=`uniform vec2 u_pattern_size_a;uniform vec2 u_pattern_size_b;uniform vec2 u_pixel_coord_upper;uniform vec2 u_pixel_coord_lower;uniform float u_scale_a;uniform float u_scale_b;uniform float u_tile_units_to_pixels;layout(location=0) in vec2 a_pos;out vec2 v_pos_a;out vec2 v_pos_b;void main() {gl_Position=projectTile(a_pos,a_pos);v_pos_a=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,u_scale_a*u_pattern_size_a,u_tile_units_to_pixels,a_pos);v_pos_b=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,u_scale_b*u_pattern_size_b,u_tile_units_to_pixels,a_pos);}`,BA=`in vec3 v_data;in float v_visibility;
}`,a9=`uniform vec2 u_pattern_size_a;uniform vec2 u_pattern_size_b;uniform vec2 u_pixel_coord_upper;uniform vec2 u_pixel_coord_lower;uniform float u_scale_a;uniform float u_scale_b;uniform float u_tile_units_to_pixels;layout(location=0) in vec2 a_pos;out vec2 v_pos_a;out vec2 v_pos_b;void main() {gl_Position=projectTile(a_pos,a_pos);v_pos_a=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,u_scale_a*u_pattern_size_a,u_tile_units_to_pixels,a_pos);v_pos_b=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,u_scale_b*u_pattern_size_b,u_tile_units_to_pixels,a_pos);}`,o9=`in vec3 v_data;in float v_visibility;
#pragma maplibre: define highp vec4 color
#pragma maplibre: define mediump float radius
#pragma maplibre: define lowp float blur
@@ -91,7 +91,7 @@ vec2 extrude=v_data.xy;float extrude_length=length(extrude);float antialiased_bl
#ifdef OVERDRAW_INSPECTOR
fragColor=vec4(1.0);
#endif
}`,VA=`uniform bool u_scale_with_map;uniform bool u_pitch_with_map;uniform vec2 u_extrude_scale;uniform highp float u_globe_extrude_scale;uniform vec2 u_translate;layout(location=0) in ivec2 a_pos;out vec3 v_data;out float v_visibility;
}`,s9=`uniform bool u_scale_with_map;uniform bool u_pitch_with_map;uniform vec2 u_extrude_scale;uniform highp float u_globe_extrude_scale;uniform vec2 u_translate;layout(location=0) in ivec2 a_pos;out vec3 v_data;out float v_visibility;
#pragma maplibre: define highp vec4 color
#pragma maplibre: define mediump float radius
#pragma maplibre: define lowp float blur
@@ -109,7 +109,7 @@ void main(void) {
#pragma maplibre: initialize lowp float stroke_opacity
ivec2 pos_raw=a_pos+32768;vec2 extrude=vec2(pos_raw & 7)/7.0*2.0-1.0;vec2 circle_center=vec2(pos_raw >> 3)+u_translate;float ele=get_elevation(circle_center);v_visibility=calculate_visibility(projectTileWithElevation(circle_center,ele));if (u_pitch_with_map) {
#ifdef GLOBE
vec3 center_vector=projectToSphere(circle_center);
vec3 center_vector=projectToSphereOffset(circle_center);
#endif
float angle_scale=u_globe_extrude_scale;vec2 corner_position=circle_center;if (u_scale_with_map) {angle_scale*=(radius+stroke_width);corner_position+=extrude*u_extrude_scale*(radius+stroke_width);} else {
#ifdef GLOBE
@@ -119,18 +119,19 @@ vec4 projected_center=projectTileWithElevation(circle_center,ele);
#endif
corner_position+=extrude*u_extrude_scale*(radius+stroke_width)*(projected_center.w/u_camera_to_center_distance);angle_scale*=(radius+stroke_width)*(projected_center.w/u_camera_to_center_distance);}
#ifdef GLOBE
vec2 angles=extrude*angle_scale;vec3 corner_vector=globeRotateVector(center_vector,angles);gl_Position=interpolateProjection(corner_position,corner_vector,ele);
vec2 angles=extrude*angle_scale;vec3 corner_vector=globeRotateVectorOffset(circle_center,center_vector,angles);gl_Position=interpolateProjection(corner_position,corner_vector,ele);
#else
gl_Position=projectTileWithElevation(corner_position,ele);
#endif
} else {gl_Position=projectTileWithElevation(circle_center,ele);if (gl_Position.z/gl_Position.w > 1.0) {gl_Position.xy=vec2(10000.0);}if (u_scale_with_map) {gl_Position.xy+=extrude*(radius+stroke_width)*u_extrude_scale*u_camera_to_center_distance;} else {gl_Position.xy+=extrude*(radius+stroke_width)*u_extrude_scale*gl_Position.w;}}float antialiasblur=-max(1.0/u_device_pixel_ratio/(radius+stroke_width),blur);v_data=vec3(extrude.x,extrude.y,antialiasblur);}`,HA=`void main() {fragColor=vec4(1.0);}`;const UA={prelude:WA(PA,FA),projectionMercator:WA(`
void clipAntimeridian() {}`,`float projectLineThickness(float tileY) {return 1.0;}float projectCircleRadius(float tileY) {return 1.0;}vec4 projectTile(vec2 p) {vec4 result=u_projection_matrix*vec4(p,0.0,1.0);return result;}vec4 projectTile(vec2 p,vec2 rawPos) {vec4 result=u_projection_matrix*vec4(p,0.0,1.0);if (rawPos.y <-32767.5 || rawPos.y > 32766.5) {result.z=-10000000.0;}return result;}vec4 projectTileWithElevation(vec2 posInTile,float elevation) {return u_projection_matrix*vec4(posInTile,elevation,1.0);}vec4 projectTileFor3D(vec2 posInTile,float elevation) {return projectTileWithElevation(posInTile,elevation);}`),projectionGlobe:WA(`in highp float v_projection_tile_x;void clipAntimeridian() {if (u_projection_clip_antimeridian !=0 && (v_projection_tile_x < 0.0 || v_projection_tile_x >=8192.0)) {discard;}}`,`#define GLOBE_RADIUS 6371008.8
} else {gl_Position=projectTileWithElevation(circle_center,ele);if (gl_Position.z/gl_Position.w > 1.0) {gl_Position.xy=vec2(10000.0);}if (u_scale_with_map) {gl_Position.xy+=extrude*(radius+stroke_width)*u_extrude_scale*u_camera_to_center_distance;} else {gl_Position.xy+=extrude*(radius+stroke_width)*u_extrude_scale*gl_Position.w;}}float antialiasblur=-max(1.0/u_device_pixel_ratio/(radius+stroke_width),blur);v_data=vec3(extrude.x,extrude.y,antialiasblur);}`,c9=`void main() {fragColor=vec4(1.0);}`;const l9={prelude:u9(e9,t9),projectionMercator:u9(`
void clipAntimeridian() {}`,`float projectLineThickness(float tileY) {return 1.0;}float projectCircleRadius(float tileY) {return 1.0;}vec4 projectTile(vec2 p) {vec4 result=u_projection_matrix*vec4(p,0.0,1.0);return result;}vec4 projectTile(vec2 p,vec2 rawPos) {vec4 result=u_projection_matrix*vec4(p,0.0,1.0);if (rawPos.y <-32767.5 || rawPos.y > 32766.5) {result.z=-10000000.0;}return result;}vec4 projectTileWithElevation(vec2 posInTile,float elevation) {return u_projection_matrix*vec4(posInTile,elevation,1.0);}vec4 projectTileFor3D(vec2 posInTile,float elevation) {return projectTileWithElevation(posInTile,elevation);}`),projectionGlobe:u9(`in highp float v_projection_tile_x;void clipAntimeridian() {if (u_projection_clip_antimeridian !=0 && (v_projection_tile_x < 0.0 || v_projection_tile_x >=8192.0)) {discard;}}`,`#define GLOBE_RADIUS 6371008.8
#ifndef PROJECTION_UBO
uniform highp vec4 u_projection_tile_mercator_coords;uniform highp vec4 u_projection_clipping_plane;uniform highp float u_projection_transition;uniform mat4 u_projection_fallback_matrix;
uniform highp vec4 u_projection_tile_mercator_coords;uniform highp vec4 u_projection_clipping_plane;uniform highp vec4 u_projection_tile_origin;uniform highp vec2 u_projection_tile_origin_position;uniform highp float u_projection_transition;uniform mat4 u_projection_fallback_matrix;
#endif
out highp float v_projection_tile_x;vec3 globeRotateVector(vec3 vec,vec2 angles) {vec3 axisRight=vec3(vec.z,0.0,-vec.x);vec3 axisUp=cross(axisRight,vec);axisRight=normalize(axisRight);axisUp=normalize(axisUp);vec2 t=tan(angles);return normalize(vec+axisRight*t.x+axisUp*t.y);}mat3 globeGetRotationMatrix(vec3 spherePos) {vec3 axisRight=vec3(spherePos.z,0.0,-spherePos.x);vec3 axisDown=cross(axisRight,spherePos);axisRight=normalize(axisRight);axisDown=normalize(axisDown);return mat3(axisRight,axisDown,spherePos
);}float circumferenceRatioAtTileY(float tileY) {float mercator_pos_y=u_projection_tile_mercator_coords.y+u_projection_tile_mercator_coords.w*tileY;float t=exp(PI-(mercator_pos_y*PI*2.0));return (2.0*t)/(t*t+1.0);}float projectLineThickness(float tileY) {float thickness=1.0/circumferenceRatioAtTileY(tileY);if (u_projection_transition < 0.999) {return mix(1.0,thickness,u_projection_transition);} else {return thickness;}}vec3 projectToSphere(vec2 translatedPos,vec2 rawPos) {vec2 mercator_pos=u_projection_tile_mercator_coords.xy+u_projection_tile_mercator_coords.zw*translatedPos;float spherical_x=mercator_pos.x*PI*2.0+PI;float t=exp(PI-(mercator_pos.y*PI*2.0));float t2=t*t;float denom=t2+1.0;float sin_sy=(t2-1.0)/denom;float cos_sy=(2.0*t)/denom;vec3 pos=vec3(sin(spherical_x)*cos_sy,sin_sy,cos(spherical_x)*cos_sy
);if (rawPos.y <-32767.5) {pos=vec3(0.0,1.0,0.0);}if (rawPos.y > 32766.5) {pos=vec3(0.0,-1.0,0.0);}return pos;}vec3 projectToSphere(vec2 posInTile) {return projectToSphere(posInTile,vec2(0.0,0.0));}float globeComputeClippingZ(vec3 spherePos) {return (1.0-(dot(spherePos,u_projection_clipping_plane.xyz)+u_projection_clipping_plane.w));}vec4 interpolateProjection(vec2 posInTile,vec3 spherePos,float elevation) {v_projection_tile_x=posInTile.x;vec3 elevatedPos=spherePos*(1.0+elevation/GLOBE_RADIUS);vec4 globePosition=u_projection_matrix*vec4(elevatedPos,1.0);globePosition.z=globeComputeClippingZ(elevatedPos)*globePosition.w;if (u_projection_transition > 0.999) {return globePosition;}vec4 flatPosition=u_projection_fallback_matrix*vec4(posInTile,elevation,1.0);const float z_globeness_threshold=0.2;vec4 result=globePosition;result.z=mix(0.0,globePosition.z,clamp((u_projection_transition-z_globeness_threshold)/(1.0-z_globeness_threshold),0.0,1.0));result.xyw=mix(flatPosition.xyw,globePosition.xyw,u_projection_transition);if ((posInTile.y <-32767.5) || (posInTile.y > 32766.5)) {result=globePosition;const float poles_hidden_anim_percentage=0.02;result.z=mix(globePosition.z,100.0,pow(max((1.0-u_projection_transition)/poles_hidden_anim_percentage,0.0),8.0));}return result;}vec4 interpolateProjectionFor3D(vec2 posInTile,vec3 spherePos,float elevation) {v_projection_tile_x=posInTile.x;vec3 elevatedPos=spherePos*(1.0+elevation/GLOBE_RADIUS);vec4 globePosition=u_projection_matrix*vec4(elevatedPos,1.0);if (u_projection_transition > 0.999) {return globePosition;}vec4 fallbackPosition=u_projection_fallback_matrix*vec4(posInTile,elevation,1.0);return mix(fallbackPosition,globePosition,u_projection_transition);}vec4 projectTile(vec2 posInTile) {return interpolateProjection(posInTile,projectToSphere(posInTile),0.0);}vec4 projectTile(vec2 posInTile,vec2 rawPos) {return interpolateProjection(posInTile,projectToSphere(posInTile,rawPos),0.0);}vec4 projectTileWithElevation(vec2 posInTile,float elevation) {return interpolateProjection(posInTile,projectToSphere(posInTile),elevation);}vec4 projectTileFor3D(vec2 posInTile,float elevation) {vec3 spherePos=projectToSphere(posInTile,posInTile);return interpolateProjectionFor3D(posInTile,spherePos,elevation);}`),background:WA(IA,LA),backgroundPattern:WA(RA,zA),circle:WA(BA,VA),clippingMask:WA(HA,`layout(location=0) in vec2 a_pos;void main() {gl_Position=projectTile(a_pos,a_pos);}`),heatmap:WA(`uniform highp float u_intensity;in vec2 v_extrude;
);if (rawPos.y <-32767.5) {pos=vec3(0.0,1.0,0.0);}if (rawPos.y > 32766.5) {pos=vec3(0.0,-1.0,0.0);}return pos;}vec3 projectToSphere(vec2 posInTile) {return projectToSphere(posInTile,vec2(0.0,0.0));}float globeSinSmall(float x) {float x2=x*x;return x*(1.0-x2/6.0*(1.0-x2/20.0*(1.0-x2/42.0*(1.0-x2/72.0*(1.0-x2/110.0*(1.0-x2/156.0))))));}float globeTanSmall(float x) {if (abs(x) >=0.5) {return tan(x);}float s=globeSinSmall(x);return s/sqrt(1.0-s*s);}float globeExpm1Small(float x) {if (abs(x) >=0.5) {return exp(x)-1.0;}return x*(1.0+x/2.0*(1.0+x/3.0*(1.0+x/4.0*(1.0+x/5.0*(1.0+x/6.0*(1.0+x/7.0*(1.0+x/8.0)))))));}vec3 globeTileOrigin() {if (u_projection_tile_origin.w < 0.5) {return vec3(0.0);}float t=u_projection_tile_origin.z;float denom=t*t+1.0;float cos_sy=2.0*t/denom;return vec3(u_projection_tile_origin.x*cos_sy,(t*t-1.0)/denom,u_projection_tile_origin.y*cos_sy);}vec2 globeAnglesFromTileOrigin(vec2 translatedPos) {return u_projection_tile_mercator_coords.zw*(translatedPos-u_projection_tile_origin_position)*(PI*2.0);}bool globeIsNearTileOrigin(vec2 translatedPos) {if (u_projection_tile_origin.w < 0.5) {return false;}vec2 delta=abs(globeAnglesFromTileOrigin(translatedPos));return delta.x <=PI*0.5 && delta.y <=PI*0.5;}vec3 projectToSphereOffset(vec2 translatedPos,vec2 rawPos) {if (!globeIsNearTileOrigin(translatedPos)) {return projectToSphere(translatedPos,rawPos)-globeTileOrigin();}if (rawPos.y <-32767.5) {return vec3(0.0,1.0,0.0)-globeTileOrigin();}if (rawPos.y > 32766.5) {return vec3(0.0,-1.0,0.0)-globeTileOrigin();}vec2 delta=globeAnglesFromTileOrigin(translatedPos);float sin_x0=u_projection_tile_origin.x;float cos_x0=u_projection_tile_origin.y;float t0=u_projection_tile_origin.z;float t0_2=t0*t0;float e=globeExpm1Small(-delta.y);float t=t0+t0*e;float denom=(t*t+1.0)*(t0_2+1.0);float d_sin_sy=2.0*t0_2*e*(2.0+e)/denom;float d_cos_sy=2.0*t0*e*(1.0-t*t0)/denom;float cos_sy=2.0*t0/(t0_2+1.0)+d_cos_sy;float sin_dx=globeSinSmall(delta.x);float half_sin_dx=globeSinSmall(delta.x*0.5);float cos_dx_minus_one=-2.0*half_sin_dx*half_sin_dx;float d_sin_x=sin_x0*cos_dx_minus_one+cos_x0*sin_dx;float d_cos_x=cos_x0*cos_dx_minus_one-sin_x0*sin_dx;return vec3(sin_x0*d_cos_sy+d_sin_x*cos_sy,d_sin_sy,cos_x0*d_cos_sy+d_cos_x*cos_sy
);}vec3 projectToSphereOffset(vec2 posInTile) {return projectToSphereOffset(posInTile,vec2(0.0,0.0));}vec3 globeRotateVectorOffset(vec2 posInTile,vec3 offset,vec2 angles) {if (!globeIsNearTileOrigin(posInTile)) {return globeRotateVector(projectToSphere(posInTile),angles)-globeTileOrigin();}vec3 vec=globeTileOrigin()+offset;mat3 axes=globeGetRotationMatrix(vec);vec3 d=axes[0]*globeTanSmall(angles.x)+axes[1]*globeTanSmall(angles.y);float len=sqrt(1.0+dot(d,d));return offset+(d-vec*(dot(d,d)/(1.0+len)))/len;}float globeComputeClippingZ(vec3 spherePos) {return (1.0-min(dot(spherePos,u_projection_clipping_plane.xyz)+u_projection_clipping_plane.w,0.5));}vec4 interpolateProjection(vec2 posInTile,vec3 spherePos,float elevation) {v_projection_tile_x=posInTile.x;vec3 origin=globeTileOrigin();vec3 elevatedPos=spherePos*(1.0+elevation/GLOBE_RADIUS)+origin*(elevation/GLOBE_RADIUS);vec4 globePosition=u_projection_matrix*vec4(elevatedPos,1.0);globePosition.z=globeComputeClippingZ(elevatedPos)*globePosition.w;if (u_projection_transition > 0.999) {return globePosition;}vec4 flatPosition=u_projection_fallback_matrix*vec4(posInTile,elevation,1.0);const float z_globeness_threshold=0.2;vec4 result=globePosition;result.z=mix(0.0,globePosition.z,clamp((u_projection_transition-z_globeness_threshold)/(1.0-z_globeness_threshold),0.0,1.0));result.xyw=mix(flatPosition.xyw,globePosition.xyw,u_projection_transition);if ((posInTile.y <-32767.5) || (posInTile.y > 32766.5)) {result=globePosition;const float poles_hidden_anim_percentage=0.02;result.z=mix(globePosition.z,100.0,pow(max((1.0-u_projection_transition)/poles_hidden_anim_percentage,0.0),8.0));}return result;}vec4 interpolateProjectionFor3D(vec2 posInTile,vec3 spherePos,float elevation) {v_projection_tile_x=posInTile.x;vec3 elevatedPos=spherePos*(1.0+elevation/GLOBE_RADIUS)+globeTileOrigin()*(elevation/GLOBE_RADIUS);vec4 globePosition=u_projection_matrix*vec4(elevatedPos,1.0);if (u_projection_transition > 0.999) {return globePosition;}vec4 fallbackPosition=u_projection_fallback_matrix*vec4(posInTile,elevation,1.0);return mix(fallbackPosition,globePosition,u_projection_transition);}vec4 projectTile(vec2 posInTile) {return interpolateProjection(posInTile,projectToSphereOffset(posInTile),0.0);}vec4 projectTile(vec2 posInTile,vec2 rawPos) {return interpolateProjection(posInTile,projectToSphereOffset(posInTile,rawPos),0.0);}vec4 projectTileWithElevation(vec2 posInTile,float elevation) {return interpolateProjection(posInTile,projectToSphereOffset(posInTile),elevation);}vec4 projectTileFor3D(vec2 posInTile,float elevation) {vec3 spherePos=projectToSphereOffset(posInTile,posInTile);return interpolateProjectionFor3D(posInTile,spherePos,elevation);}`),background:u9(n9,r9),backgroundPattern:u9(i9,a9),circle:u9(o9,s9),clippingMask:u9(c9,`layout(location=0) in vec2 a_pos;void main() {gl_Position=projectTile(a_pos,a_pos);}`),heatmap:u9(`uniform highp float u_intensity;in vec2 v_extrude;
#pragma maplibre: define highp float weight
#define GAUSS_COEF 0.3989422804014327
void main() {
@@ -149,15 +150,15 @@ void main(void) {
#pragma maplibre: initialize mediump float radius
ivec2 pos_raw=a_pos+32768;vec2 unscaled_extrude=vec2(pos_raw & 7)/7.0*2.0-1.0;float S=sqrt(-2.0*log(ZERO/weight/u_intensity/GAUSS_COEF))/3.0;v_extrude=S*unscaled_extrude;vec2 extrude=v_extrude*radius*u_extrude_scale;vec2 circle_center=vec2(pos_raw >> 3);
#ifdef GLOBE
vec2 angles=v_extrude*radius*u_globe_extrude_scale;vec3 center_vector=projectToSphere(circle_center);vec3 corner_vector=globeRotateVector(center_vector,angles);gl_Position=interpolateProjection(circle_center+extrude,corner_vector,0.0);
vec2 angles=v_extrude*radius*u_globe_extrude_scale;vec3 center_vector=projectToSphereOffset(circle_center);vec3 corner_vector=globeRotateVectorOffset(circle_center,center_vector,angles);gl_Position=interpolateProjection(circle_center+extrude,corner_vector,0.0);
#else
gl_Position=projectTileFor3D(circle_center+extrude,get_elevation(circle_center));
#endif
}`),heatmapTexture:WA(`uniform sampler2D u_image;uniform sampler2D u_color_ramp;uniform float u_opacity;in vec2 v_pos;void main() {float t=texture(u_image,v_pos).r;vec4 color=texture(u_color_ramp,vec2(t,0.5));fragColor=color*u_opacity;
}`),heatmapTexture:u9(`uniform sampler2D u_image;uniform sampler2D u_color_ramp;uniform float u_opacity;in vec2 v_pos;void main() {float t=texture(u_image,v_pos).r;vec4 color=texture(u_color_ramp,vec2(t,0.5));fragColor=color*u_opacity;
#ifdef OVERDRAW_INSPECTOR
fragColor=vec4(0.0);
#endif
}`,`uniform mat4 u_matrix;layout(location=0) in vec2 a_pos;out vec2 v_pos;void main() {gl_Position=u_matrix*vec4(a_pos*u_world_size,0,1);v_pos.x=a_pos.x;v_pos.y=1.0-a_pos.y;}`),collisionBox:WA(`in float v_placed;in float v_notUsed;void main() {float alpha=0.5;fragColor=vec4(1.0,0.0,0.0,1.0)*alpha;if (v_placed > 0.5) {fragColor=vec4(0.0,0.0,1.0,0.5)*alpha;}if (v_notUsed > 0.5) {fragColor*=.1;}}`,`layout(location=0) in vec2 a_anchor_pos;layout(location=1) in vec2 a_placed;layout(location=2) in vec2 a_box_real;out float v_placed;out float v_notUsed;void main() {gl_Position=projectTileWithElevation(a_anchor_pos,get_elevation(a_anchor_pos));gl_Position.xy=((a_box_real+0.5)*u_pixel_extrude_scale*2.0-1.0)*vec2(1.0,-1.0)*gl_Position.w;if (gl_Position.z/gl_Position.w < 1.1) {gl_Position.z=0.5;}v_placed=a_placed.x;v_notUsed=a_placed.y;}`),collisionCircle:WA(`in float v_radius;in vec2 v_extrude;in float v_collision;void main() {float alpha=0.5;float stroke_radius=0.9;float distance_to_center=length(v_extrude);float distance_to_edge=abs(distance_to_center-v_radius);float opacity_t=smoothstep(-stroke_radius,0.0,-distance_to_edge);vec4 color=mix(vec4(0.0,0.0,1.0,0.5),vec4(1.0,0.0,0.0,1.0),v_collision);fragColor=color*alpha*opacity_t;}`,`layout(location=0) in vec2 a_pos;layout(location=1) in float a_radius;layout(location=2) in vec2 a_flags;out float v_radius;out vec2 v_extrude;out float v_collision;void main() {float radius=a_radius;float collision=a_flags.x;float vertexIdx=a_flags.y;vec2 quadVertexOffset=vec2(mix(-1.0,1.0,float(vertexIdx >=2.0)),mix(-1.0,1.0,float(vertexIdx >=1.0 && vertexIdx <=2.0)));vec2 quadVertexExtent=quadVertexOffset*radius;float padding_factor=1.2;v_radius=radius;v_extrude=quadVertexExtent*padding_factor;v_collision=collision;gl_Position=vec4((a_pos/u_viewport_size*2.0-1.0)*vec2(1.0,-1.0),0.0,1.0)+vec4(quadVertexExtent*padding_factor/u_viewport_size*2.0,0.0,0.0);}`),colorRelief:WA(`#ifdef GL_ES
}`,`uniform mat4 u_matrix;layout(location=0) in vec2 a_pos;out vec2 v_pos;void main() {gl_Position=u_matrix*vec4(a_pos*u_world_size,0,1);v_pos.x=a_pos.x;v_pos.y=1.0-a_pos.y;}`),collisionBox:u9(`in float v_placed;in float v_notUsed;void main() {float alpha=0.5;fragColor=vec4(1.0,0.0,0.0,1.0)*alpha;if (v_placed > 0.5) {fragColor=vec4(0.0,0.0,1.0,0.5)*alpha;}if (v_notUsed > 0.5) {fragColor*=.1;}}`,`layout(location=0) in vec2 a_anchor_pos;layout(location=1) in vec2 a_placed;layout(location=2) in vec2 a_box_real;out float v_placed;out float v_notUsed;void main() {gl_Position=projectTileWithElevation(a_anchor_pos,get_elevation(a_anchor_pos));gl_Position.xy=((a_box_real+0.5)*u_pixel_extrude_scale*2.0-1.0)*vec2(1.0,-1.0)*gl_Position.w;if (gl_Position.z/gl_Position.w < 1.1) {gl_Position.z=0.5;}v_placed=a_placed.x;v_notUsed=a_placed.y;}`),collisionCircle:u9(`in float v_radius;in vec2 v_extrude;in float v_collision;void main() {float alpha=0.5;float stroke_radius=0.9;float distance_to_center=length(v_extrude);float distance_to_edge=abs(distance_to_center-v_radius);float opacity_t=smoothstep(-stroke_radius,0.0,-distance_to_edge);vec4 color=mix(vec4(0.0,0.0,1.0,0.5),vec4(1.0,0.0,0.0,1.0),v_collision);fragColor=color*alpha*opacity_t;}`,`layout(location=0) in vec2 a_pos;layout(location=1) in float a_radius;layout(location=2) in vec2 a_flags;out float v_radius;out vec2 v_extrude;out float v_collision;void main() {float radius=a_radius;float collision=a_flags.x;float vertexIdx=a_flags.y;vec2 quadVertexOffset=vec2(mix(-1.0,1.0,float(vertexIdx >=2.0)),mix(-1.0,1.0,float(vertexIdx >=1.0 && vertexIdx <=2.0)));vec2 quadVertexExtent=quadVertexOffset*radius;float padding_factor=1.2;v_radius=radius;v_extrude=quadVertexExtent*padding_factor;v_collision=collision;gl_Position=vec4((a_pos/u_viewport_size*2.0-1.0)*vec2(1.0,-1.0),0.0,1.0)+vec4(quadVertexExtent*padding_factor/u_viewport_size*2.0,0.0,0.0);}`),colorRelief:u9(`#ifdef GL_ES
precision highp float;
#endif
uniform sampler2D u_image;uniform vec4 u_unpack;uniform sampler2D u_elevation_stops;uniform sampler2D u_color_stops;uniform int u_color_ramp_size;uniform float u_opacity;in vec2 v_pos;float getElevation(vec2 coord) {vec4 data=texture(u_image,coord)*255.0;data.a=-1.0;return dot(data,u_unpack);}float getElevationStop(int stop) {vec4 data=texelFetch(u_elevation_stops,ivec2(stop,0),0)*255.0;data.a=-1.0;return dot(data,u_unpack);}void main() {float el=getElevation(v_pos);int r=(u_color_ramp_size-1);int l=0;float el_l=getElevationStop(l);float el_r=getElevationStop(r);while(r-l > 1){int m=(r+l)/2;float el_m=getElevationStop(m);if(el < el_m){r=m;el_r=el_m;}else
@@ -165,13 +166,13 @@ uniform sampler2D u_image;uniform vec4 u_unpack;uniform sampler2D u_elevation_st
#ifdef OVERDRAW_INSPECTOR
fragColor=vec4(1.0);
#endif
}`,`uniform vec2 u_dimension;layout(location=0) in vec2 a_pos;out vec2 v_pos;void main() {gl_Position=projectTile(a_pos,a_pos);highp vec2 epsilon=2.0/u_dimension;float scale=(u_dimension.x-4.0)/u_dimension.x;v_pos=(a_pos/8192.0)*scale+epsilon;if (a_pos.y <-32767.5) {v_pos.y=0.0;}if (a_pos.y > 32766.5) {v_pos.y=1.0;}}`),debug:WA(`uniform highp vec4 u_color;uniform sampler2D u_overlay;in vec2 v_uv;void main() {vec4 overlay_color=texture(u_overlay,v_uv);fragColor=mix(u_color,overlay_color,overlay_color.a);}`,`layout(location=0) in vec2 a_pos;out vec2 v_uv;uniform float u_overlay_scale;void main() {v_uv=a_pos/8192.0;gl_Position=projectTileWithElevation(a_pos*u_overlay_scale,get_elevation(a_pos));}`),depth:WA(HA,`layout(location=0) in vec2 a_pos;void main() {
}`,`uniform vec2 u_dimension;layout(location=0) in vec2 a_pos;out vec2 v_pos;void main() {gl_Position=projectTile(a_pos,a_pos);highp vec2 epsilon=2.0/u_dimension;float scale=(u_dimension.x-4.0)/u_dimension.x;v_pos=(a_pos/8192.0)*scale+epsilon;if (a_pos.y <-32767.5) {v_pos.y=0.0;}if (a_pos.y > 32766.5) {v_pos.y=1.0;}}`),debug:u9(`uniform highp vec4 u_color;uniform sampler2D u_overlay;in vec2 v_uv;void main() {vec4 overlay_color=texture(u_overlay,v_uv);fragColor=mix(u_color,overlay_color,overlay_color.a);}`,`layout(location=0) in vec2 a_pos;out vec2 v_uv;uniform float u_overlay_scale;void main() {v_uv=a_pos/8192.0;gl_Position=projectTileWithElevation(a_pos*u_overlay_scale,get_elevation(a_pos));}`),depth:u9(c9,`layout(location=0) in vec2 a_pos;void main() {
#ifdef GLOBE
gl_Position=projectTileFor3D(a_pos,0.0);
#else
gl_Position=u_projection_matrix*vec4(a_pos,0.0,1.0);
#endif
}`),fill:WA(`#pragma maplibre: define highp vec4 color
}`),fill:u9(`#pragma maplibre: define highp vec4 color
#pragma maplibre: define lowp float opacity
void main() {
#pragma maplibre: initialize highp vec4 color
@@ -186,7 +187,7 @@ fragColor=vec4(1.0);
void main() {
#pragma maplibre: initialize highp vec4 color
#pragma maplibre: initialize lowp float opacity
if (opacity < 0.01) {gl_Position=vec4(-2.0,-2.0,-2.0,1.0);return;}gl_Position=projectTile(a_pos+u_fill_translate,a_pos);}`),fillOutline:WA(`in vec2 v_pos;
if (opacity < 0.01) {gl_Position=vec4(-2.0,-2.0,-2.0,1.0);return;}gl_Position=projectTile(a_pos+u_fill_translate,a_pos);}`),fillOutline:u9(`in vec2 v_pos;
#ifdef GLOBE
in float v_depth;
#endif
@@ -215,7 +216,7 @@ if (opacity < 0.01) {gl_Position=vec4(-2.0,-2.0,-2.0,1.0);return;}gl_Position=pr
#ifdef GLOBE
v_depth=gl_Position.z/gl_Position.w;
#endif
}`),fillOutlinePattern:WA(`uniform vec2 u_texsize;uniform sampler2D u_image;uniform float u_fade;uniform bool u_sdf_pattern;in vec2 v_pos_a;in vec2 v_pos_b;in vec2 v_pos;
}`),fillOutlinePattern:u9(`uniform vec2 u_texsize;uniform sampler2D u_image;uniform float u_fade;uniform bool u_sdf_pattern;in vec2 v_pos_a;in vec2 v_pos_b;in vec2 v_pos;
#ifdef GLOBE
in float v_depth;
#endif
@@ -256,7 +257,7 @@ if (opacity < 0.01) {gl_Position=vec4(-2.0,-2.0,-2.0,1.0);return;}vec2 pattern_t
#ifdef GLOBE
v_depth=gl_Position.z/gl_Position.w;
#endif
}`),fillPattern:WA(`#ifdef GL_ES
}`),fillPattern:u9(`#ifdef GL_ES
precision highp float;
#endif
uniform vec2 u_texsize;uniform float u_fade;uniform bool u_sdf_pattern;uniform sampler2D u_image;in vec2 v_pos_a;in vec2 v_pos_b;
@@ -287,11 +288,11 @@ void main() {
#pragma maplibre: initialize mediump vec4 pattern_to
#pragma maplibre: initialize lowp float pixel_ratio_from
#pragma maplibre: initialize lowp float pixel_ratio_to
if (opacity < 0.01) {gl_Position=vec4(-2.0,-2.0,-2.0,1.0);return;}vec2 pattern_tl_a=pattern_from.xy;vec2 pattern_br_a=pattern_from.zw;vec2 pattern_tl_b=pattern_to.xy;vec2 pattern_br_b=pattern_to.zw;float tileZoomRatio=u_scale.x;float fromScale=u_scale.y;float toScale=u_scale.z;vec2 display_size_a=(pattern_br_a-pattern_tl_a)/pixel_ratio_from;vec2 display_size_b=(pattern_br_b-pattern_tl_b)/pixel_ratio_to;gl_Position=projectTile(a_pos+u_fill_translate,a_pos);v_pos_a=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,fromScale*display_size_a,tileZoomRatio,a_pos);v_pos_b=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,toScale*display_size_b,tileZoomRatio,a_pos);}`),fillExtrusion:WA(`in vec4 v_color;void main() {fragColor=v_color;
if (opacity < 0.01) {gl_Position=vec4(-2.0,-2.0,-2.0,1.0);return;}vec2 pattern_tl_a=pattern_from.xy;vec2 pattern_br_a=pattern_from.zw;vec2 pattern_tl_b=pattern_to.xy;vec2 pattern_br_b=pattern_to.zw;float tileZoomRatio=u_scale.x;float fromScale=u_scale.y;float toScale=u_scale.z;vec2 display_size_a=(pattern_br_a-pattern_tl_a)/pixel_ratio_from;vec2 display_size_b=(pattern_br_b-pattern_tl_b)/pixel_ratio_to;gl_Position=projectTile(a_pos+u_fill_translate,a_pos);v_pos_a=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,fromScale*display_size_a,tileZoomRatio,a_pos);v_pos_b=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,toScale*display_size_b,tileZoomRatio,a_pos);}`),fillExtrusion:u9(`in vec4 v_color;void main() {fragColor=v_color;
#ifdef OVERDRAW_INSPECTOR
fragColor=vec4(1.0);
#endif
}`,`uniform vec3 u_lightcolor;uniform lowp vec3 u_lightpos;uniform lowp vec3 u_lightpos_globe;uniform lowp float u_lightintensity;uniform float u_vertical_gradient;uniform lowp float u_opacity;uniform vec2 u_fill_translate;layout(location=0) in vec2 a_pos;layout(location=1) in ivec4 a_normal_ed;
}`,`uniform vec3 u_lightcolor;uniform lowp vec3 u_lightpos;uniform lowp vec3 u_lightpos_globe;uniform lowp float u_lightintensity;uniform float u_vertical_gradient;uniform vec2 u_fill_translate;layout(location=0) in vec2 a_pos;layout(location=1) in ivec4 a_normal_ed;
#ifdef TERRAIN3D
layout(location=2) in vec2 a_centroid;
#endif
@@ -299,11 +300,13 @@ out vec4 v_color;
#pragma maplibre: define highp float base
#pragma maplibre: define highp float height
#pragma maplibre: define highp vec4 color
#pragma maplibre: define highp float opacity
void main() {
#pragma maplibre: initialize highp float base
#pragma maplibre: initialize highp float height
#pragma maplibre: initialize highp vec4 color
vec3 normal=vec3(a_normal_ed.xyz);float gradient_base=max(0.0,base);float gradient_height=max(0.0,height);
#pragma maplibre: initialize highp float opacity
opacity=clamp(opacity,0.0,1.0);if (opacity <=0.0) {gl_Position=vec4(-2.0,-2.0,-2.0,1.0);return;}vec3 normal=vec3(a_normal_ed.xyz);float gradient_base=max(0.0,base);float gradient_height=max(0.0,height);
#ifdef TERRAIN3D
float height_terrain3d_offset=get_elevation(a_centroid);float base_terrain3d_offset=height_terrain3d_offset-(base > 0.0 ? 0.0 : 10.0);
#else
@@ -311,15 +314,15 @@ float height_terrain3d_offset=0.0;float base_terrain3d_offset=0.0;
#endif
base=max(0.0,base)+base_terrain3d_offset;height=max(0.0,height)+height_terrain3d_offset;float t=float(a_normal_ed.x & 1);float elevation=t > 0.0 ? height : base;vec2 posInTile=a_pos+u_fill_translate;
#ifdef GLOBE
vec3 spherePos=projectToSphere(posInTile,a_pos);gl_Position=interpolateProjectionFor3D(posInTile,spherePos,elevation);
vec3 spherePos=projectToSphereOffset(posInTile,a_pos);gl_Position=interpolateProjectionFor3D(posInTile,spherePos,elevation);
#else
gl_Position=u_projection_matrix*vec4(posInTile,elevation,1.0);
#endif
float colorvalue=color.r*0.2126+color.g*0.7152+color.b*0.0722;v_color=vec4(0.0,0.0,0.0,1.0);vec4 ambientlight=vec4(0.03,0.03,0.03,1.0);color+=ambientlight;vec3 normalForLighting=normal/16384.0;float directional=clamp(dot(normalForLighting,u_lightpos),0.0,1.0);
#ifdef GLOBE
mat3 rotMatrix=globeGetRotationMatrix(spherePos);normalForLighting=rotMatrix*normalForLighting;directional=mix(directional,clamp(dot(normalForLighting,u_lightpos_globe),0.0,1.0),u_projection_transition);
mat3 rotMatrix=globeGetRotationMatrix(globeTileOrigin()+spherePos);normalForLighting=rotMatrix*normalForLighting;directional=mix(directional,clamp(dot(normalForLighting,u_lightpos_globe),0.0,1.0),u_projection_transition);
#endif
directional=mix((1.0-u_lightintensity),max((1.0-colorvalue+u_lightintensity),1.0),directional);if (normal.z==0.0) {directional*=((1.0-u_vertical_gradient)+(u_vertical_gradient*clamp((t+gradient_base)*pow(gradient_height/150.0,0.5),mix(0.7,0.98,1.0-u_lightintensity),1.0)));}v_color.r+=clamp(color.r*directional*u_lightcolor.r,mix(0.0,0.3,1.0-u_lightcolor.r),1.0);v_color.g+=clamp(color.g*directional*u_lightcolor.g,mix(0.0,0.3,1.0-u_lightcolor.g),1.0);v_color.b+=clamp(color.b*directional*u_lightcolor.b,mix(0.0,0.3,1.0-u_lightcolor.b),1.0);v_color*=u_opacity;}`),fillExtrusionPattern:WA(`uniform vec2 u_texsize;uniform float u_fade;uniform sampler2D u_image;in vec2 v_pos_a;in vec2 v_pos_b;in vec4 v_lighting;
directional=mix((1.0-u_lightintensity),max((1.0-colorvalue+u_lightintensity),1.0),directional);if (normal.z==0.0) {directional*=((1.0-u_vertical_gradient)+(u_vertical_gradient*clamp((t+gradient_base)*pow(gradient_height/150.0,0.5),mix(0.7,0.98,1.0-u_lightintensity),1.0)));}v_color.r+=clamp(color.r*directional*u_lightcolor.r,mix(0.0,0.3,1.0-u_lightcolor.r),1.0);v_color.g+=clamp(color.g*directional*u_lightcolor.g,mix(0.0,0.3,1.0-u_lightcolor.g),1.0);v_color.b+=clamp(color.b*directional*u_lightcolor.b,mix(0.0,0.3,1.0-u_lightcolor.b),1.0);v_color*=opacity;}`),fillExtrusionPattern:u9(`uniform vec2 u_texsize;uniform float u_fade;uniform sampler2D u_image;in vec2 v_pos_a;in vec2 v_pos_b;in vec4 v_lighting;
#pragma maplibre: define lowp float base
#pragma maplibre: define lowp float height
#pragma maplibre: define lowp vec4 pattern_from
@@ -337,7 +340,7 @@ vec2 pattern_tl_a=pattern_from.xy;vec2 pattern_br_a=pattern_from.zw;vec2 pattern
#ifdef OVERDRAW_INSPECTOR
fragColor=vec4(1.0);
#endif
}`,`uniform vec2 u_pixel_coord_upper;uniform vec2 u_pixel_coord_lower;uniform float u_height_factor;uniform vec3 u_scale;uniform float u_vertical_gradient;uniform lowp float u_opacity;uniform vec2 u_fill_translate;uniform vec3 u_lightcolor;uniform lowp vec3 u_lightpos;uniform lowp vec3 u_lightpos_globe;uniform lowp float u_lightintensity;layout(location=0) in vec2 a_pos;layout(location=1) in ivec4 a_normal_ed;
}`,`uniform vec2 u_pixel_coord_upper;uniform vec2 u_pixel_coord_lower;uniform float u_height_factor;uniform vec3 u_scale;uniform float u_vertical_gradient;uniform vec2 u_fill_translate;uniform vec3 u_lightcolor;uniform lowp vec3 u_lightpos;uniform lowp vec3 u_lightpos_globe;uniform lowp float u_lightintensity;layout(location=0) in vec2 a_pos;layout(location=1) in ivec4 a_normal_ed;
#ifdef TERRAIN3D
layout(location=2) in vec2 a_centroid;
#endif
@@ -351,6 +354,7 @@ out vec2 v_pos_a;out vec2 v_pos_b;out vec4 v_lighting;
#pragma maplibre: define lowp vec4 pattern_to
#pragma maplibre: define lowp float pixel_ratio_from
#pragma maplibre: define lowp float pixel_ratio_to
#pragma maplibre: define highp float opacity
void main() {
#pragma maplibre: initialize lowp float base
#pragma maplibre: initialize lowp float height
@@ -358,7 +362,8 @@ void main() {
#pragma maplibre: initialize mediump vec4 pattern_to
#pragma maplibre: initialize lowp float pixel_ratio_from
#pragma maplibre: initialize lowp float pixel_ratio_to
vec2 pattern_tl_a=pattern_from.xy;vec2 pattern_br_a=pattern_from.zw;vec2 pattern_tl_b=pattern_to.xy;vec2 pattern_br_b=pattern_to.zw;float tileRatio=u_scale.x;float fromScale=u_scale.y;float toScale=u_scale.z;vec3 normal=vec3(a_normal_ed.xyz);float edgedistance=float(a_normal_ed.w);vec2 display_size_a=(pattern_br_a-pattern_tl_a)/pixel_ratio_from;vec2 display_size_b=(pattern_br_b-pattern_tl_b)/pixel_ratio_to;float gradient_base=max(0.0,base);float gradient_height=max(0.0,height);
#pragma maplibre: initialize highp float opacity
opacity=clamp(opacity,0.0,1.0);if (opacity <=0.0) {gl_Position=vec4(-2.0,-2.0,-2.0,1.0);return;}vec2 pattern_tl_a=pattern_from.xy;vec2 pattern_br_a=pattern_from.zw;vec2 pattern_tl_b=pattern_to.xy;vec2 pattern_br_b=pattern_to.zw;float tileRatio=u_scale.x;float fromScale=u_scale.y;float toScale=u_scale.z;vec3 normal=vec3(a_normal_ed.xyz);float edgedistance=float(a_normal_ed.w);vec2 display_size_a=(pattern_br_a-pattern_tl_a)/pixel_ratio_from;vec2 display_size_b=(pattern_br_b-pattern_tl_b)/pixel_ratio_to;float gradient_base=max(0.0,base);float gradient_height=max(0.0,height);
#ifdef TERRAIN3D
float height_terrain3d_offset=get_elevation(a_centroid);float base_terrain3d_offset=height_terrain3d_offset-(base > 0.0 ? 0.0 : 10.0);
#else
@@ -366,20 +371,20 @@ float height_terrain3d_offset=0.0;float base_terrain3d_offset=0.0;
#endif
base=max(0.0,base)+base_terrain3d_offset;height=max(0.0,height)+height_terrain3d_offset;float t=float(a_normal_ed.x & 1);float elevation=t > 0.0 ? height : base;vec2 posInTile=a_pos+u_fill_translate;
#ifdef GLOBE
vec3 spherePos=projectToSphere(posInTile,a_pos);vec3 elevatedPos=spherePos*(1.0+elevation/GLOBE_RADIUS);v_sphere_pos=elevatedPos;gl_Position=interpolateProjectionFor3D(posInTile,spherePos,elevation);
vec3 spherePos=projectToSphereOffset(posInTile,a_pos);vec3 elevatedPos=(globeTileOrigin()+spherePos)*(1.0+elevation/GLOBE_RADIUS);v_sphere_pos=elevatedPos;gl_Position=interpolateProjectionFor3D(posInTile,spherePos,elevation);
#else
gl_Position=u_projection_matrix*vec4(posInTile,elevation,1.0);
#endif
vec2 pos=a_normal_ed.x==1 && a_normal_ed.y==0 && a_normal_ed.z==16384
? a_pos
: vec2(edgedistance,elevation*u_height_factor);v_pos_a=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,fromScale*display_size_a,tileRatio,pos);v_pos_b=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,toScale*display_size_b,tileRatio,pos);v_lighting=vec4(0.0,0.0,0.0,1.0);float directional=clamp(dot(normal/16383.0,u_lightpos),0.0,1.0);directional=mix((1.0-u_lightintensity),max((0.5+u_lightintensity),1.0),directional);if (normal.z==0.0) {directional*=((1.0-u_vertical_gradient)+(u_vertical_gradient*clamp((t+gradient_base)*pow(gradient_height/150.0,0.5),mix(0.7,0.98,1.0-u_lightintensity),1.0)));}v_lighting.rgb+=clamp(directional*u_lightcolor,mix(vec3(0.0),vec3(0.3),1.0-u_lightcolor),vec3(1.0));v_lighting*=u_opacity;}`),hillshadePrepare:WA(`#ifdef GL_ES
: vec2(edgedistance,elevation*u_height_factor);v_pos_a=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,fromScale*display_size_a,tileRatio,pos);v_pos_b=get_pattern_pos(u_pixel_coord_upper,u_pixel_coord_lower,toScale*display_size_b,tileRatio,pos);v_lighting=vec4(0.0,0.0,0.0,1.0);float directional=clamp(dot(normal/16383.0,u_lightpos),0.0,1.0);directional=mix((1.0-u_lightintensity),max((0.5+u_lightintensity),1.0),directional);if (normal.z==0.0) {directional*=((1.0-u_vertical_gradient)+(u_vertical_gradient*clamp((t+gradient_base)*pow(gradient_height/150.0,0.5),mix(0.7,0.98,1.0-u_lightintensity),1.0)));}v_lighting.rgb+=clamp(directional*u_lightcolor,mix(vec3(0.0),vec3(0.3),1.0-u_lightcolor),vec3(1.0));v_lighting*=opacity;}`),hillshadePrepare:u9(`#ifdef GL_ES
precision highp float;
#endif
uniform sampler2D u_image;in vec2 v_pos;uniform vec2 u_dimension;uniform float u_zoom;uniform vec4 u_unpack;uniform float u_log2_world_width;float getElevation(ivec2 texel) {vec4 data=texelFetch(u_image,texel,0)*255.0;data.a=-1.0;return dot(data,u_unpack);}void main() {ivec2 pos=ivec2(gl_FragCoord.xy)+ivec2(1);float tileSize=u_dimension.x-4.0;float a=getElevation(pos+ivec2(-1,-1));float b=getElevation(pos+ivec2(0,-1));float c=getElevation(pos+ivec2(1,-1));float d=getElevation(pos+ivec2(-1,0));float e=getElevation(pos);float f=getElevation(pos+ivec2(1,0));float g=getElevation(pos+ivec2(-1,1));float h=getElevation(pos+ivec2(0,1));float i=getElevation(pos+ivec2(1,1));float exaggerationFactor=u_zoom < 2.0 ? 0.4 : u_zoom < 4.5 ? 0.35 : 0.3;float exaggeration=u_zoom < 15.0 ? (u_zoom-15.0)*exaggerationFactor : 0.0;vec2 deriv=vec2((c+f+f+i)-(a+d+d+g),(g+h+h+i)-(a+b+b+c))*tileSize/pow(2.0,exaggeration+(3.0+u_log2_world_width-u_zoom));fragColor=clamp(vec4(deriv.x/8.0+128.0/255.0,deriv.y/8.0+128.0/255.0,1.0,1.0),0.0,1.0);
#ifdef OVERDRAW_INSPECTOR
fragColor=vec4(1.0);
#endif
}`,`uniform mat4 u_matrix;uniform vec2 u_dimension;layout(location=0) in vec2 a_pos;layout(location=1) in vec2 a_texture_pos;out vec2 v_pos;void main() {gl_Position=u_matrix*vec4(a_pos,0,1);highp vec2 epsilon=1.0/u_dimension;float scale=(u_dimension.x-2.0)/u_dimension.x;v_pos=(a_texture_pos/8192.0)*scale+epsilon;}`),hillshade:WA(`uniform sampler2D u_image;in highp vec2 v_pos;uniform vec2 u_latrange;uniform float u_exaggeration;uniform vec4 u_accent;uniform int u_method;uniform float u_altitudes[NUM_ILLUMINATION_SOURCES];uniform float u_azimuths[NUM_ILLUMINATION_SOURCES];uniform vec4 u_shadows[NUM_ILLUMINATION_SOURCES];uniform vec4 u_highlights[NUM_ILLUMINATION_SOURCES];
}`,`uniform mat4 u_matrix;uniform vec2 u_dimension;layout(location=0) in vec2 a_pos;layout(location=1) in vec2 a_texture_pos;out vec2 v_pos;void main() {gl_Position=u_matrix*vec4(a_pos,0,1);highp vec2 epsilon=1.0/u_dimension;float scale=(u_dimension.x-2.0)/u_dimension.x;v_pos=(a_texture_pos/8192.0)*scale+epsilon;}`),hillshade:u9(`uniform sampler2D u_image;in highp vec2 v_pos;uniform vec2 u_latrange;uniform float u_exaggeration;uniform vec4 u_accent;uniform int u_method;uniform float u_altitudes[NUM_ILLUMINATION_SOURCES];uniform float u_azimuths[NUM_ILLUMINATION_SOURCES];uniform vec4 u_shadows[NUM_ILLUMINATION_SOURCES];uniform vec4 u_highlights[NUM_ILLUMINATION_SOURCES];
#define PI 3.141592653589793
#define STANDARD 0
#define COMBINED 1
@@ -392,7 +397,7 @@ float get_aspect(vec2 deriv){return deriv.x !=0.0 ? atan(deriv.y,-deriv.x) : PI/
#ifdef OVERDRAW_INSPECTOR
fragColor=vec4(1.0);
#endif
}`,`uniform mat4 u_matrix;layout(location=0) in vec2 a_pos;out vec2 v_pos;void main() {gl_Position=projectTile(a_pos,a_pos);v_pos=a_pos/8192.0;if (a_pos.y <-32767.5) {v_pos.y=0.0;}if (a_pos.y > 32766.5) {v_pos.y=1.0;}}`),line:WA(`in vec2 v_width2;in vec2 v_normal;in float v_gamma_scale;
}`,`uniform mat4 u_matrix;layout(location=0) in vec2 a_pos;out vec2 v_pos;void main() {gl_Position=projectTile(a_pos,a_pos);v_pos=a_pos/8192.0;if (a_pos.y <-32767.5) {v_pos.y=0.0;}if (a_pos.y > 32766.5) {v_pos.y=1.0;}}`),line:u9(`in vec2 v_width2;in vec2 v_normal;in float v_gamma_scale;
#ifdef GLOBE
in float v_depth;
#endif
@@ -438,7 +443,7 @@ v_gamma_scale=1.0;
#else
float extrude_length_without_perspective=length(dist);float extrude_length_with_perspective=length((projected_with_extrude.xy-projected_no_extrude.xy)/projected_with_extrude.w*u_units_to_pixels);v_gamma_scale=extrude_length_without_perspective/extrude_length_with_perspective;
#endif
v_width2=vec2(outset,inset);}`),lineGradient:WA(`uniform sampler2D u_image;in vec2 v_width2;in vec2 v_normal;in float v_gamma_scale;in highp vec2 v_uv;
v_width2=vec2(outset,inset);}`),lineGradient:u9(`uniform sampler2D u_image;in vec2 v_width2;in vec2 v_normal;in float v_gamma_scale;in highp vec2 v_uv;
#ifdef GLOBE
in float v_depth;
#endif
@@ -480,7 +485,7 @@ v_gamma_scale=1.0;
#else
float extrude_length_without_perspective=length(dist);float extrude_length_with_perspective=length((projected_with_extrude.xy-projected_no_extrude.xy)/projected_with_extrude.w*u_units_to_pixels);v_gamma_scale=extrude_length_without_perspective/extrude_length_with_perspective;
#endif
v_width2=vec2(outset,inset);}`),linePattern:WA(`#ifdef GL_ES
v_width2=vec2(outset,inset);}`),linePattern:u9(`#ifdef GL_ES
precision highp float;
#endif
uniform vec2 u_texsize;uniform float u_fade;uniform mediump vec3 u_scale;uniform sampler2D u_image;in vec2 v_normal;in vec2 v_width2;in float v_linesofar;in float v_gamma_scale;in float v_width;
@@ -544,7 +549,7 @@ v_gamma_scale=1.0;
#else
float extrude_length_without_perspective=length(dist);float extrude_length_with_perspective=length((projected_with_extrude.xy-projected_no_extrude.xy)/projected_with_extrude.w*u_units_to_pixels);v_gamma_scale=extrude_length_without_perspective/extrude_length_with_perspective;
#endif
v_linesofar=a_linesofar;v_width2=vec2(outset,inset);v_width=floorwidth;}`),lineSDF:WA(`uniform lowp float u_lineatlas_width;uniform sampler2D u_image;uniform float u_mix;in vec2 v_normal;in vec2 v_width2;in vec2 v_tex_a;in vec2 v_tex_b;in float v_gamma_scale;
v_linesofar=a_linesofar;v_width2=vec2(outset,inset);v_width=floorwidth;}`),lineSDF:u9(`uniform lowp float u_lineatlas_width;uniform sampler2D u_image;uniform float u_mix;in vec2 v_normal;in vec2 v_width2;in vec2 v_tex_a;in vec2 v_tex_b;in float v_gamma_scale;
#ifdef GLOBE
in float v_depth;
#endif
@@ -573,7 +578,7 @@ fragColor=vec4(1.0);
}`,`
#define scale 0.015873016
#define LINE_DISTANCE_SCALE 2.0
layout(location=0) in ivec2 a_pos_normal;layout(location=1) in uvec4 a_data;layout(location=2) in vec2 a_offset_normal;uniform vec2 u_translation;uniform mediump float u_ratio;uniform float u_tileratio;uniform float u_crossfade_from;uniform float u_crossfade_to;uniform float u_lineatlas_height;out vec2 v_normal;out vec2 v_width2;out vec2 v_tex_a;out vec2 v_tex_b;out float v_gamma_scale;
layout(location=0) in ivec2 a_pos_normal;layout(location=1) in uvec4 a_data;layout(location=2) in vec2 a_offset_normal;layout(location=3) in float a_offset_distance;uniform vec2 u_translation;uniform mediump float u_ratio;uniform float u_tileratio;uniform float u_crossfade_from;uniform float u_crossfade_to;uniform float u_lineatlas_height;out vec2 v_normal;out vec2 v_width2;out vec2 v_tex_a;out vec2 v_tex_b;out float v_gamma_scale;
#ifdef GLOBE
out float v_depth;
#endif
@@ -596,7 +601,7 @@ void main() {
#pragma maplibre: initialize lowp float floorwidth
#pragma maplibre: initialize mediump vec4 dasharray_from
#pragma maplibre: initialize mediump vec4 dasharray_to
if (opacity < 0.01) {gl_Position=vec4(-2.0,-2.0,-2.0,1.0);return;}float ANTIALIASING=1.0/u_device_pixel_ratio/2.0;vec2 a_extrude=vec2(ivec2(a_data.xy)-128);float a_linesofar=float((a_data.z >> 2u)+a_data.w*64u)*LINE_DISTANCE_SCALE;vec2 pos=vec2(a_pos_normal >> 1);mediump vec2 normal=vec2(a_pos_normal & 1);normal.y=normal.y*2.0-1.0;v_normal=normal;gapwidth=gapwidth/2.0;float halfwidth=width/2.0;offset=-1.0*offset;float inset=gapwidth+(gapwidth > 0.0 ? ANTIALIASING : 0.0);float outset=gapwidth+halfwidth*(gapwidth > 0.0 ? 2.0 : 1.0)+(halfwidth==0.0 ? 0.0 : ANTIALIASING);mediump vec2 dist=outset*a_extrude*scale;mediump vec2 offset2=offset*a_offset_normal*scale*normal.y;float adjustedThickness=projectLineThickness(pos.y);vec4 projected_no_extrude=projectTile(pos+offset2/u_ratio*adjustedThickness+u_translation);vec4 projected_with_extrude=projectTile(pos+offset2/u_ratio*adjustedThickness+u_translation+dist/u_ratio*adjustedThickness);gl_Position=projected_with_extrude;
if (opacity < 0.01) {gl_Position=vec4(-2.0,-2.0,-2.0,1.0);return;}float ANTIALIASING=1.0/u_device_pixel_ratio/2.0;vec2 a_extrude=vec2(ivec2(a_data.xy)-128);float a_linesofar=float((a_data.z >> 2u)+a_data.w*64u)*LINE_DISTANCE_SCALE;vec2 pos=vec2(a_pos_normal >> 1);mediump vec2 normal=vec2(a_pos_normal & 1);normal.y=normal.y*2.0-1.0;v_normal=normal;gapwidth=gapwidth/2.0;float halfwidth=width/2.0;offset=-1.0*offset;float inset=gapwidth+(gapwidth > 0.0 ? ANTIALIASING : 0.0);float outset=gapwidth+halfwidth*(gapwidth > 0.0 ? 2.0 : 1.0)+(halfwidth==0.0 ? 0.0 : ANTIALIASING);mediump vec2 dist=outset*a_extrude*scale;mediump vec2 offset2=offset*a_offset_normal*scale*normal.y;float adjustedThickness=projectLineThickness(pos.y);float linesofar=a_linesofar-offset/u_ratio*adjustedThickness*a_offset_distance;vec4 projected_no_extrude=projectTile(pos+offset2/u_ratio*adjustedThickness+u_translation);vec4 projected_with_extrude=projectTile(pos+offset2/u_ratio*adjustedThickness+u_translation+dist/u_ratio*adjustedThickness);gl_Position=projected_with_extrude;
#ifdef GLOBE
v_depth=gl_Position.z/gl_Position.w;
#endif
@@ -605,7 +610,7 @@ v_gamma_scale=1.0;
#else
float extrude_length_without_perspective=length(dist);float extrude_length_with_perspective=length((projected_with_extrude.xy-projected_no_extrude.xy)/projected_with_extrude.w*u_units_to_pixels);v_gamma_scale=extrude_length_without_perspective/extrude_length_with_perspective;
#endif
float u_patternscale_a_x=u_tileratio/dasharray_from.w/u_crossfade_from;float u_patternscale_a_y=-dasharray_from.z/2.0/u_lineatlas_height;float u_patternscale_b_x=u_tileratio/dasharray_to.w/u_crossfade_to;float u_patternscale_b_y=-dasharray_to.z/2.0/u_lineatlas_height;v_tex_a=vec2(a_linesofar*u_patternscale_a_x/floorwidth,normal.y*u_patternscale_a_y+(float(dasharray_from.y)+0.5)/u_lineatlas_height);v_tex_b=vec2(a_linesofar*u_patternscale_b_x/floorwidth,normal.y*u_patternscale_b_y+(float(dasharray_to.y)+0.5)/u_lineatlas_height);v_width2=vec2(outset,inset);}`),lineGradientSDF:WA(`uniform sampler2D u_image;uniform sampler2D u_image_dash;uniform float u_mix;uniform lowp float u_lineatlas_width;in vec2 v_normal;in vec2 v_width2;in vec2 v_tex_a;in vec2 v_tex_b;in float v_gamma_scale;in highp vec2 v_uv;
float u_patternscale_a_x=u_tileratio/dasharray_from.w/u_crossfade_from;float u_patternscale_a_y=-dasharray_from.z/2.0/u_lineatlas_height;float u_patternscale_b_x=u_tileratio/dasharray_to.w/u_crossfade_to;float u_patternscale_b_y=-dasharray_to.z/2.0/u_lineatlas_height;v_tex_a=vec2(linesofar*u_patternscale_a_x/floorwidth,normal.y*u_patternscale_a_y+(float(dasharray_from.y)+0.5)/u_lineatlas_height);v_tex_b=vec2(linesofar*u_patternscale_b_x/floorwidth,normal.y*u_patternscale_b_y+(float(dasharray_to.y)+0.5)/u_lineatlas_height);v_width2=vec2(outset,inset);}`),lineGradientSDF:u9(`uniform sampler2D u_image;uniform sampler2D u_image_dash;uniform float u_mix;uniform lowp float u_lineatlas_width;in vec2 v_normal;in vec2 v_width2;in vec2 v_tex_a;in vec2 v_tex_b;in float v_gamma_scale;in highp vec2 v_uv;
#ifdef GLOBE
in float v_depth;
#endif
@@ -632,7 +637,7 @@ fragColor=vec4(1.0);
}`,`
#define scale 0.015873016
#define LINE_DISTANCE_SCALE 2.0
layout(location=0) in ivec2 a_pos_normal;layout(location=1) in uvec4 a_data;layout(location=2) in vec2 a_offset_normal;layout(location=3) in float a_uv_x;layout(location=4) in float a_split_index;uniform vec2 u_translation;uniform mediump float u_ratio;uniform float u_image_height;uniform float u_tileratio;uniform float u_crossfade_from;uniform float u_crossfade_to;uniform float u_lineatlas_height;out vec2 v_normal;out vec2 v_width2;out float v_gamma_scale;out highp vec2 v_uv;out vec2 v_tex_a;out vec2 v_tex_b;
layout(location=0) in ivec2 a_pos_normal;layout(location=1) in uvec4 a_data;layout(location=2) in vec2 a_offset_normal;layout(location=3) in float a_uv_x;layout(location=4) in float a_split_index;layout(location=5) in float a_offset_distance;uniform vec2 u_translation;uniform mediump float u_ratio;uniform float u_image_height;uniform float u_tileratio;uniform float u_crossfade_from;uniform float u_crossfade_to;uniform float u_lineatlas_height;out vec2 v_normal;out vec2 v_width2;out float v_gamma_scale;out highp vec2 v_uv;out vec2 v_tex_a;out vec2 v_tex_b;
#ifdef GLOBE
out float v_depth;
#endif
@@ -653,7 +658,7 @@ void main() {
#pragma maplibre: initialize lowp float floorwidth
#pragma maplibre: initialize mediump vec4 dasharray_from
#pragma maplibre: initialize mediump vec4 dasharray_to
if (opacity < 0.01) {gl_Position=vec4(-2.0,-2.0,-2.0,1.0);return;}float ANTIALIASING=1.0/u_device_pixel_ratio/2.0;vec2 a_extrude=vec2(ivec2(a_data.xy)-128);float a_linesofar=float((a_data.z >> 2u)+a_data.w*64u)*LINE_DISTANCE_SCALE;float texel_height=1.0/u_image_height;float half_texel_height=0.5*texel_height;v_uv=vec2(a_uv_x,a_split_index*texel_height-half_texel_height);vec2 pos=vec2(a_pos_normal >> 1);mediump vec2 normal=vec2(a_pos_normal & 1);normal.y=normal.y*2.0-1.0;v_normal=normal;gapwidth=gapwidth/2.0;float halfwidth=width/2.0;offset=-1.0*offset;float inset=gapwidth+(gapwidth > 0.0 ? ANTIALIASING : 0.0);float outset=gapwidth+halfwidth*(gapwidth > 0.0 ? 2.0 : 1.0)+(halfwidth==0.0 ? 0.0 : ANTIALIASING);mediump vec2 dist=outset*a_extrude*scale;mediump vec2 offset2=offset*a_offset_normal*scale*normal.y;float adjustedThickness=projectLineThickness(pos.y);vec4 projected_no_extrude=projectTile(pos+offset2/u_ratio*adjustedThickness+u_translation);vec4 projected_with_extrude=projectTile(pos+offset2/u_ratio*adjustedThickness+u_translation+dist/u_ratio*adjustedThickness);gl_Position=projected_with_extrude;
if (opacity < 0.01) {gl_Position=vec4(-2.0,-2.0,-2.0,1.0);return;}float ANTIALIASING=1.0/u_device_pixel_ratio/2.0;vec2 a_extrude=vec2(ivec2(a_data.xy)-128);float a_linesofar=float((a_data.z >> 2u)+a_data.w*64u)*LINE_DISTANCE_SCALE;float texel_height=1.0/u_image_height;float half_texel_height=0.5*texel_height;v_uv=vec2(a_uv_x,a_split_index*texel_height-half_texel_height);vec2 pos=vec2(a_pos_normal >> 1);mediump vec2 normal=vec2(a_pos_normal & 1);normal.y=normal.y*2.0-1.0;v_normal=normal;gapwidth=gapwidth/2.0;float halfwidth=width/2.0;offset=-1.0*offset;float inset=gapwidth+(gapwidth > 0.0 ? ANTIALIASING : 0.0);float outset=gapwidth+halfwidth*(gapwidth > 0.0 ? 2.0 : 1.0)+(halfwidth==0.0 ? 0.0 : ANTIALIASING);mediump vec2 dist=outset*a_extrude*scale;mediump vec2 offset2=offset*a_offset_normal*scale*normal.y;float adjustedThickness=projectLineThickness(pos.y);float linesofar=a_linesofar-offset/u_ratio*adjustedThickness*a_offset_distance;vec4 projected_no_extrude=projectTile(pos+offset2/u_ratio*adjustedThickness+u_translation);vec4 projected_with_extrude=projectTile(pos+offset2/u_ratio*adjustedThickness+u_translation+dist/u_ratio*adjustedThickness);gl_Position=projected_with_extrude;
#ifdef GLOBE
v_depth=gl_Position.z/gl_Position.w;
#endif
@@ -662,25 +667,67 @@ v_gamma_scale=1.0;
#else
float extrude_length_without_perspective=length(dist);float extrude_length_with_perspective=length((projected_with_extrude.xy-projected_no_extrude.xy)/projected_with_extrude.w*u_units_to_pixels);v_gamma_scale=extrude_length_without_perspective/extrude_length_with_perspective;
#endif
float u_patternscale_a_x=u_tileratio/dasharray_from.w/u_crossfade_from;float u_patternscale_a_y=-dasharray_from.z/2.0/u_lineatlas_height;float u_patternscale_b_x=u_tileratio/dasharray_to.w/u_crossfade_to;float u_patternscale_b_y=-dasharray_to.z/2.0/u_lineatlas_height;v_tex_a=vec2(a_linesofar*u_patternscale_a_x/floorwidth,normal.y*u_patternscale_a_y+(float(dasharray_from.y)+0.5)/u_lineatlas_height);v_tex_b=vec2(a_linesofar*u_patternscale_b_x/floorwidth,normal.y*u_patternscale_b_y+(float(dasharray_to.y)+0.5)/u_lineatlas_height);v_width2=vec2(outset,inset);}`),layerComposite:WA(`uniform sampler2D u_image;uniform float u_opacity;
float u_patternscale_a_x=u_tileratio/dasharray_from.w/u_crossfade_from;float u_patternscale_a_y=-dasharray_from.z/2.0/u_lineatlas_height;float u_patternscale_b_x=u_tileratio/dasharray_to.w/u_crossfade_to;float u_patternscale_b_y=-dasharray_to.z/2.0/u_lineatlas_height;v_tex_a=vec2(linesofar*u_patternscale_a_x/floorwidth,normal.y*u_patternscale_a_y+(float(dasharray_from.y)+0.5)/u_lineatlas_height);v_tex_b=vec2(linesofar*u_patternscale_b_x/floorwidth,normal.y*u_patternscale_b_y+(float(dasharray_to.y)+0.5)/u_lineatlas_height);v_width2=vec2(outset,inset);}`),layerComposite:u9(`uniform sampler2D u_image;uniform float u_opacity;
#ifdef LAYER_BLEND
uniform sampler2D u_backdrop;uniform highp vec2 u_backdrop_offset;
#ifdef LAYER_BLEND_NONSEPARABLE
float lum(vec3 c) {return dot(c,vec3(0.3,0.59,0.11));}vec3 clipColor(vec3 c) {float l=lum(c);float n=min(min(c.r,c.g),c.b);float x=max(max(c.r,c.g),c.b);if (n < 0.0) c=l+(c-l)*l/(l-n);if (x > 1.0) c=l+(c-l)*(1.0-l)/(x-l);return c;}vec3 setLum(vec3 c,float l) {return clipColor(c+(l-lum(c)));}
float lum(vec3 c) {return dot(c,vec3(0.3,0.59,0.11));}vec3 clipColor(vec3 c) {float l=lum(c);float n=min(min(c.r,c.g),c.b);float x=max(max(c.r,c.g),c.b);if (n < 0.0) c=l+(c-l)*l/(l-n);if (x > 1.0) c=l+(c-l)*(1.0-l)/(x-l);return c;}vec3 setLum(vec3 c,float l) {return clipColor(c+(l-lum(c)));}float sat(vec3 c) {return max(max(c.r,c.g),c.b)-min(min(c.r,c.g),c.b);}vec3 setSat(vec3 c,float s) {float n=min(min(c.r,c.g),c.b);float x=max(max(c.r,c.g),c.b);return x > n ? (c-n)*s/(x-n) : vec3(0.0);}
#endif
#ifdef LAYER_BLEND_SOFT_LIGHT
vec3 softLight(vec3 cs,vec3 cb) {vec3 d=mix(sqrt(cb),((16.0*cb-12.0)*cb+4.0)*cb,step(cb,vec3(0.25)));vec3 darkened=cb-(1.0-2.0*cs)*cb*(1.0-cb);vec3 lightened=cb+(2.0*cs-1.0)*(d-cb);return mix(darkened,lightened,step(0.5,cs));}
#endif
#ifdef LAYER_BLEND_COLOR_DODGE
vec3 colorDodge(vec3 cs,vec3 cb) {return min(vec3(1.0),cb/max(1.0-cs,1e-3));}
#endif
#ifdef LAYER_BLEND_COLOR_BURN
vec3 colorBurn(vec3 cs,vec3 cb) {return 1.0-min(vec3(1.0),(1.0-cb)/max(cs,1e-3));}
#endif
vec4 composite(vec4 src,vec4 dst) {vec3 co=vec3(0.0);float invDstA=1.0-dst.a;float invSrcA=1.0-src.a;
#ifdef LAYER_BLEND_MULTIPLY
co=invDstA*src.rgb+invSrcA*dst.rgb+src.rgb*dst.rgb;
#endif
#if defined(LAYER_BLEND_OVERLAY) || defined(LAYER_BLEND_HARD_LIGHT)
#ifdef LAYER_BLEND_OVERLAY
vec3 cond=step(dst.a,2.0*dst.rgb);vec3 case1=invDstA*src.rgb+invSrcA*dst.rgb+2.0*dst.rgb*src.rgb;vec3 case2=src.rgb+dst.rgb+dst.a*src.rgb+src.a*dst.rgb-vec3(src.a*dst.a)-2.0*dst.rgb*src.rgb;co=mix(case1,case2,cond);
#endif
#ifdef LAYER_BLEND_NONSEPARABLE
vec3 cs=src.rgb/src.a;vec3 cb=dst.a > 0.0 ? dst.rgb/dst.a : vec3(0.0);
#ifdef LAYER_BLEND_COLOR
vec3 blended=setLum(cs,lum(cb));
vec3 cond=step(dst.a,2.0*dst.rgb);
#else
vec3 blended=setLum(cb,lum(cs));
vec3 cond=step(src.a,2.0*src.rgb);
#endif
vec3 case1=invDstA*src.rgb+invSrcA*dst.rgb+2.0*dst.rgb*src.rgb;vec3 case2=src.rgb+dst.rgb+dst.a*src.rgb+src.a*dst.rgb-vec3(src.a*dst.a)-2.0*dst.rgb*src.rgb;co=mix(case1,case2,cond);
#endif
#ifdef LAYER_BLEND_DIFFERENCE
co=src.rgb+dst.rgb-2.0*min(src.rgb*dst.a,dst.rgb*src.a);
#endif
#ifdef LAYER_BLEND_EXCLUSION
co=src.rgb+dst.rgb-2.0*src.rgb*dst.rgb;
#endif
#ifdef LAYER_BLEND_DARKEN
co=src.rgb+dst.rgb-max(src.rgb*dst.a,dst.rgb*src.a);
#endif
#ifdef LAYER_BLEND_LIGHTEN
co=src.rgb+dst.rgb-min(src.rgb*dst.a,dst.rgb*src.a);
#endif
#ifdef LAYER_BLEND_UNPREMULTIPLIED
vec3 cs=src.rgb/src.a;vec3 cb=dst.a > 0.0 ? dst.rgb/dst.a : vec3(0.0);vec3 blended=vec3(0.0);
#ifdef LAYER_BLEND_SOFT_LIGHT
blended=softLight(cs,cb);
#endif
#ifdef LAYER_BLEND_COLOR_DODGE
blended=colorDodge(cs,cb);
#endif
#ifdef LAYER_BLEND_COLOR_BURN
blended=colorBurn(cs,cb);
#endif
#ifdef LAYER_BLEND_HUE
blended=setLum(setSat(cs,sat(cb)),lum(cb));
#endif
#ifdef LAYER_BLEND_SATURATION
blended=setLum(setSat(cb,sat(cs)),lum(cb));
#endif
#ifdef LAYER_BLEND_COLOR
blended=setLum(cs,lum(cb));
#endif
#ifdef LAYER_BLEND_LUMINOSITY
blended=setLum(cb,lum(cs));
#endif
co=invDstA*src.rgb+invSrcA*dst.rgb+src.a*dst.a*blended;
#endif
@@ -697,7 +744,7 @@ vec4 dst=texelFetch(u_backdrop,texel-ivec2(u_backdrop_offset),0);fragColor=compo
fragColor=src;
#endif
#endif
}`,`layout(location=0) in vec2 a_pos;void main() {gl_Position=vec4(a_pos.x*2.0-1.0,1.0-a_pos.y*2.0,0.0,1.0);}`),raster:WA(`uniform float u_fade_t;uniform float u_opacity;uniform sampler2D u_image0;uniform sampler2D u_image1;in vec3 v_pos0;in vec3 v_pos1;uniform float u_brightness_low;uniform float u_brightness_high;uniform float u_saturation_factor;uniform float u_contrast_factor;uniform vec3 u_spin_weights;void main() {vec4 color0=texture(u_image0,v_pos0.xy/v_pos0.z);vec4 color1=texture(u_image1,v_pos1.xy/v_pos1.z);if (color0.a > 0.0) {color0.rgb=color0.rgb/color0.a;}if (color1.a > 0.0) {color1.rgb=color1.rgb/color1.a;}vec4 color=mix(color0,color1,u_fade_t);color.a*=u_opacity;vec3 rgb=color.rgb;rgb=vec3(dot(rgb,u_spin_weights.xyz),dot(rgb,u_spin_weights.zxy),dot(rgb,u_spin_weights.yzx));float average=(color.r+color.g+color.b)/3.0;rgb+=(average-rgb)*u_saturation_factor;rgb=(rgb-0.5)*u_contrast_factor+0.5;vec3 u_high_vec=vec3(u_brightness_low,u_brightness_low,u_brightness_low);vec3 u_low_vec=vec3(u_brightness_high,u_brightness_high,u_brightness_high);fragColor=vec4(mix(u_high_vec,u_low_vec,rgb)*color.a,color.a);
}`,`layout(location=0) in vec2 a_pos;void main() {gl_Position=vec4(a_pos.x*2.0-1.0,1.0-a_pos.y*2.0,0.0,1.0);}`),raster:u9(`uniform float u_fade_t;uniform float u_opacity;uniform sampler2D u_image0;uniform sampler2D u_image1;in vec3 v_pos0;in vec3 v_pos1;uniform float u_brightness_low;uniform float u_brightness_high;uniform float u_saturation_factor;uniform float u_contrast_factor;uniform vec3 u_spin_weights;void main() {vec4 color0=texture(u_image0,v_pos0.xy/v_pos0.z);vec4 color1=texture(u_image1,v_pos1.xy/v_pos1.z);if (color0.a > 0.0) {color0.rgb=color0.rgb/color0.a;}if (color1.a > 0.0) {color1.rgb=color1.rgb/color1.a;}vec4 color=mix(color0,color1,u_fade_t);color.a*=u_opacity;vec3 rgb=color.rgb;rgb=vec3(dot(rgb,u_spin_weights.xyz),dot(rgb,u_spin_weights.zxy),dot(rgb,u_spin_weights.yzx));float average=(color.r+color.g+color.b)/3.0;rgb+=(average-rgb)*u_saturation_factor;rgb=(rgb-0.5)*u_contrast_factor+0.5;vec3 u_high_vec=vec3(u_brightness_low,u_brightness_low,u_brightness_low);vec3 u_low_vec=vec3(u_brightness_high,u_brightness_high,u_brightness_high);fragColor=vec4(mix(u_high_vec,u_low_vec,rgb)*color.a,color.a);
#ifdef OVERDRAW_INSPECTOR
fragColor=vec4(1.0);
#endif
@@ -705,7 +752,7 @@ fragColor=vec4(1.0);
#ifdef GLOBE
if (a_pos.y <-32767.5) {texturePos.y=0.0;}if (a_pos.y > 32766.5) {texturePos.y=1.0;}
#endif
float perspectiveRatio=mix(1.0/denominator,1.0,u_image_warp.z);v_pos0=vec3(texturePos*perspectiveRatio,perspectiveRatio);vec2 parentPos=(texturePos*u_scale_parent)+u_tl_parent;v_pos1=vec3(parentPos*perspectiveRatio,perspectiveRatio);}`),symbolIcon:WA(`uniform sampler2D u_texture;in vec2 v_tex;in float v_total_opacity;void main() {fragColor=texture(u_texture,v_tex)*v_total_opacity;
float perspectiveRatio=mix(1.0/denominator,1.0,u_image_warp.z);v_pos0=vec3(texturePos*perspectiveRatio,perspectiveRatio);vec2 parentPos=(texturePos*u_scale_parent)+u_tl_parent;v_pos1=vec3(parentPos*perspectiveRatio,perspectiveRatio);}`),symbolIcon:u9(`uniform sampler2D u_texture;in vec2 v_tex;in float v_total_opacity;void main() {fragColor=texture(u_texture,v_tex)*v_total_opacity;
#ifdef OVERDRAW_INSPECTOR
fragColor=vec4(1.0);
#endif
@@ -719,7 +766,7 @@ u_camera_to_center_distance/camera_to_anchor_distance;highp float perspective_ra
#ifdef GLOBE
if(u_pitch_with_map) {float anchor_pos_tile_y=(u_coord_matrix*vec4(projected_pos.xy/projected_pos.w,z,1.0)).y;projectionScaling=mix(projectionScaling,1.0/circumferenceRatioAtTileY(anchor_pos_tile_y)*u_pitched_scale,u_projection_transition);}
#endif
vec4 finalPos=u_coord_matrix*vec4(projected_pos.xy/projected_pos.w+rotation_matrix*(a_offset/32.0*max(a_minFontScale,fontScale)+a_pxoffset/16.0)*projectionScaling,z,1.0);if(u_pitch_with_map) {finalPos=projectTileWithElevation(finalPos.xy,finalPos.z);}gl_Position=finalPos;v_tex=a_tex/u_texsize;}`),symbolSDF:WA(`#define SDF_PX 8.0
vec4 finalPos=u_coord_matrix*vec4(projected_pos.xy/projected_pos.w+rotation_matrix*(a_offset/32.0*max(a_minFontScale,fontScale)+a_pxoffset/16.0)*projectionScaling,z,1.0);if(u_pitch_with_map) {finalPos=projectTileWithElevation(finalPos.xy,finalPos.z);}gl_Position=finalPos;v_tex=a_tex/u_texsize;}`),symbolSDF:u9(`#define SDF_PX 8.0
uniform bool u_is_halo;uniform bool u_is_plain;uniform sampler2D u_texture;uniform highp float u_gamma_scale;uniform bool u_is_text;in vec2 v_data0;in vec3 v_data1;
#pragma maplibre: define highp vec4 fill_color
#pragma maplibre: define highp vec4 halo_color
@@ -752,7 +799,7 @@ u_camera_to_center_distance/camera_to_anchor_distance;highp float perspective_ra
#ifdef GLOBE
if(u_pitch_with_map) {float anchor_pos_tile_y=(u_coord_matrix*vec4(projected_pos.xy/projected_pos.w,z,1.0)).y;projectionScaling=mix(projectionScaling,1.0/circumferenceRatioAtTileY(anchor_pos_tile_y)*u_pitched_scale,u_projection_transition);}
#endif
vec4 finalPos=u_coord_matrix*vec4(projected_pos.xy/projected_pos.w+rotation_matrix*(a_offset/32.0*max(a_minFontScale,fontScale)+a_pxoffset)*projectionScaling,z,1.0);if(u_pitch_with_map) {finalPos=projectTileWithElevation(finalPos.xy,finalPos.z);}float gamma_scale=finalPos.w;gl_Position=finalPos;v_data0=a_tex/u_texsize;v_data1=vec3(gamma_scale,size,total_opacity);}`),symbolTextAndIcon:WA(`#define SDF_PX 8.0
vec4 finalPos=u_coord_matrix*vec4(projected_pos.xy/projected_pos.w+rotation_matrix*(a_offset/32.0*max(a_minFontScale,fontScale)+a_pxoffset)*projectionScaling,z,1.0);if(u_pitch_with_map) {finalPos=projectTileWithElevation(finalPos.xy,finalPos.z);}float gamma_scale=finalPos.w;gl_Position=finalPos;v_data0=a_tex/u_texsize;v_data1=vec3(gamma_scale,size,total_opacity);}`),symbolTextAndIcon:u9(`#define SDF_PX 8.0
#define SDF 1.0
#define ICON 0.0
uniform bool u_is_halo;uniform bool u_is_text;uniform sampler2D u_texture;uniform sampler2D u_texture_icon;uniform highp float u_gamma_scale;in vec4 v_data0;in vec3 v_data1;in float v_is_sdf;
@@ -791,11 +838,11 @@ u_camera_to_center_distance/camera_to_anchor_distance;highp float perspective_ra
#ifdef GLOBE
if(u_pitch_with_map && !u_is_along_line) {float anchor_pos_tile_y=(u_coord_matrix*vec4(projected_pos.xy/projected_pos.w,z,1.0)).y;projectionScaling=mix(projectionScaling,1.0/circumferenceRatioAtTileY(anchor_pos_tile_y)*u_pitched_scale,u_projection_transition);}
#endif
vec4 finalPos=u_coord_matrix*vec4(projected_pos.xy/projected_pos.w+rotation_matrix*(a_offset/32.0*fontScale)*projectionScaling,z,1.0);if(u_pitch_with_map) {finalPos=projectTileWithElevation(finalPos.xy,finalPos.z);}float gamma_scale=finalPos.w;gl_Position=finalPos;v_data0.xy=a_tex/u_texsize;v_data0.zw=a_tex/u_texsize_icon;v_data1=vec3(gamma_scale,size,total_opacity);v_is_sdf=is_sdf;}`),terrain:WA(`uniform sampler2D u_texture;uniform vec4 u_fog_color;uniform vec4 u_horizon_color;uniform float u_fog_ground_blend;uniform float u_fog_ground_blend_opacity;uniform float u_horizon_fog_blend;uniform bool u_is_globe_mode;in vec2 v_texture_pos;in float v_fog_depth;const float gamma=2.2;vec4 gammaToLinear(vec4 color) {return pow(color,vec4(gamma));}vec4 linearToGamma(vec4 color) {return pow(color,vec4(1.0/gamma));}void main() {vec4 surface_color=texture(u_texture,vec2(v_texture_pos.x,1.0-v_texture_pos.y));if (!u_is_globe_mode && u_fog_ground_blend_opacity > 0.0 && v_fog_depth > u_fog_ground_blend) {vec4 surface_color_linear=gammaToLinear(surface_color);float blend_color=smoothstep(0.0,1.0,max((v_fog_depth-u_horizon_fog_blend)/(1.0-u_horizon_fog_blend),0.0));vec4 fog_horizon_color_linear=mix(gammaToLinear(u_fog_color),gammaToLinear(u_horizon_color),blend_color);float factor_fog=max(v_fog_depth-u_fog_ground_blend,0.0)/(1.0-u_fog_ground_blend);fragColor=linearToGamma(mix(surface_color_linear,fog_horizon_color_linear,pow(factor_fog,2.0)*u_fog_ground_blend_opacity));} else {fragColor=surface_color;}}`,`layout(location=0) in vec3 a_pos3d;uniform mat4 u_fog_matrix;uniform float u_ele_delta;out vec2 v_texture_pos;out float v_fog_depth;void main() {float ele=get_elevation(a_pos3d.xy);float ele_delta=a_pos3d.z==1.0 ? u_ele_delta : 0.0;v_texture_pos=a_pos3d.xy/8192.0;gl_Position=projectTileFor3D(a_pos3d.xy,ele-ele_delta);vec4 pos=u_fog_matrix*vec4(a_pos3d.xy,ele,1.0);v_fog_depth=pos.z/pos.w*0.5+0.5;}`),terrainDepth:WA(`in float v_depth;const highp vec4 bitSh=vec4(256.*256.*256.,256.*256.,256.,1.);const highp vec4 bitMsk=vec4(0.,vec3(1./256.0));highp vec4 pack(highp float value) {highp vec4 comp=fract(value*bitSh);comp-=comp.xxyz*bitMsk;return comp;}void main() {fragColor=pack(v_depth);}`,`layout(location=0) in vec3 a_pos3d;uniform float u_ele_delta;out float v_depth;void main() {float ele=get_elevation(a_pos3d.xy);float ele_delta=a_pos3d.z==1.0 ? u_ele_delta : 0.0;gl_Position=projectTileFor3D(a_pos3d.xy,ele-ele_delta);v_depth=gl_Position.z/gl_Position.w;}`),terrainHeight:WA(`in highp float v_elevation;void main() {fragColor=vec4(v_elevation,0.0,0.0,1.0);}`,`layout(location=0) in vec3 a_pos3d;uniform vec4 u_tile_bounds;out highp float v_elevation;void main() {v_elevation=get_elevation(a_pos3d.xy);vec2 position=u_tile_bounds.xy+a_pos3d.xy/8192.0*u_tile_bounds.zw;gl_Position=vec4(position.x*2.0-1.0,1.0-position.y*2.0,0.0,1.0);}`),atmosphere:WA(`#ifdef GL_ES
vec4 finalPos=u_coord_matrix*vec4(projected_pos.xy/projected_pos.w+rotation_matrix*(a_offset/32.0*fontScale)*projectionScaling,z,1.0);if(u_pitch_with_map) {finalPos=projectTileWithElevation(finalPos.xy,finalPos.z);}float gamma_scale=finalPos.w;gl_Position=finalPos;v_data0.xy=a_tex/u_texsize;v_data0.zw=a_tex/u_texsize_icon;v_data1=vec3(gamma_scale,size,total_opacity);v_is_sdf=is_sdf;}`),terrain:u9(`uniform sampler2D u_texture;in vec2 v_texture_pos;void main() {fragColor=texture(u_texture,vec2(v_texture_pos.x,1.0-v_texture_pos.y));}`,`layout(location=0) in vec3 a_pos3d;uniform float u_ele_delta;out vec2 v_texture_pos;invariant gl_Position;void main() {float ele=get_elevation(a_pos3d.xy);float ele_delta=a_pos3d.z==1.0 ? u_ele_delta : 0.0;v_texture_pos=a_pos3d.xy/8192.0;gl_Position=projectTileFor3D(a_pos3d.xy,ele-ele_delta);}`),terrainDepth:u9(`in float v_depth;const highp vec4 bitSh=vec4(256.*256.*256.,256.*256.,256.,1.);const highp vec4 bitMsk=vec4(0.,vec3(1./256.0));highp vec4 pack(highp float value) {highp vec4 comp=fract(value*bitSh);comp-=comp.xxyz*bitMsk;return comp;}void main() {fragColor=pack(v_depth);}`,`layout(location=0) in vec3 a_pos3d;uniform float u_ele_delta;out float v_depth;void main() {float ele=get_elevation(a_pos3d.xy);float ele_delta=a_pos3d.z==1.0 ? u_ele_delta : 0.0;gl_Position=projectTileFor3D(a_pos3d.xy,ele-ele_delta);v_depth=gl_Position.z/gl_Position.w;}`),terrainHeight:u9(`in highp float v_elevation;void main() {fragColor=vec4(v_elevation,0.0,0.0,1.0);}`,`layout(location=0) in vec3 a_pos3d;uniform vec4 u_tile_bounds;out highp float v_elevation;void main() {v_elevation=get_elevation(a_pos3d.xy);vec2 position=u_tile_bounds.xy+a_pos3d.xy/8192.0*u_tile_bounds.zw;gl_Position=vec4(position.x*2.0-1.0,1.0-position.y*2.0,0.0,1.0);}`),atmosphere:u9(`#ifdef GL_ES
precision highp float;
#endif
in vec3 view_direction;uniform vec3 u_sun_pos;uniform vec3 u_globe_position;uniform float u_globe_radius;uniform float u_atmosphere_blend;/**Shader use from https:*Made some change to adapt to MapLibre Globe geometry*/const float PI=3.141592653589793;const int iSteps=5;const int jSteps=3;/*radius of the planet*/const float EARTH_RADIUS=6371e3;/*radius of the atmosphere*/const float ATMOS_RADIUS=6471e3;vec2 rsi(vec3 r0,vec3 rd,float sr) {float a=dot(rd,rd);float b=2.0*dot(rd,r0);float c=dot(r0,r0)-(sr*sr);float d=(b*b)-4.0*a*c;if (d < 0.0) return vec2(1e5,-1e5);return vec2((-b-sqrt(d))/(2.0*a),(-b+sqrt(d))/(2.0*a));}vec4 atmosphere(vec3 r,vec3 r0,vec3 pSun,float iSun,float rPlanet,float rAtmos,vec3 kRlh,float kMie,float shRlh,float shMie,float g) {pSun=normalize(pSun);r=normalize(r);vec2 p=rsi(r0,r,rAtmos);if (p.x > p.y) {return vec4(0.0,0.0,0.0,1.0);}if (p.x < 0.0) {p.x=0.0;}vec3 pos=r0+r*p.x;vec2 p2=rsi(r0,r,rPlanet);if (p2.x <=p2.y && p2.x > 0.0) {p.y=min(p.y,p2.x);}float iStepSize=(p.y-p.x)/float(iSteps);float iTime=p.x+iStepSize*0.5;vec3 totalRlh=vec3(0,0,0);vec3 totalMie=vec3(0,0,0);float iOdRlh=0.0;float iOdMie=0.0;float mu=dot(r,pSun);float mumu=mu*mu;float gg=g*g;float pRlh=3.0/(16.0*PI)*(1.0+mumu);float pMie=3.0/(8.0*PI)*((1.0-gg)*(mumu+1.0))/(pow(1.0+gg-2.0*mu*g,1.5)*(2.0+gg));for (int i=0; i < iSteps; i++) {vec3 iPos=r0+r*iTime;float iHeight=length(iPos)-rPlanet;float odStepRlh=exp(-iHeight/shRlh)*iStepSize;float odStepMie=exp(-iHeight/shMie)*iStepSize;iOdRlh+=odStepRlh;iOdMie+=odStepMie;float jStepSize=rsi(iPos,pSun,rAtmos).y/float(jSteps);float jTime=jStepSize*0.5;float jOdRlh=0.0;float jOdMie=0.0;for (int j=0; j < jSteps; j++) {vec3 jPos=iPos+pSun*jTime;float jHeight=length(jPos)-rPlanet;jOdRlh+=exp(-jHeight/shRlh)*jStepSize;jOdMie+=exp(-jHeight/shMie)*jStepSize;jTime+=jStepSize;}vec3 attn=exp(-(kMie*(iOdMie+jOdMie)+kRlh*(iOdRlh+jOdRlh)));totalRlh+=odStepRlh*attn;totalMie+=odStepMie*attn;iTime+=iStepSize;}float opacity=exp(-(length(kRlh)*length(totalRlh)+kMie*length(totalMie)));vec3 color=iSun*(pRlh*kRlh*totalRlh+pMie*kMie*totalMie);return vec4(color,opacity);}void main() {vec3 scale_camera_pos=-u_globe_position*EARTH_RADIUS/u_globe_radius;vec4 color=atmosphere(normalize(view_direction),scale_camera_pos,u_sun_pos,22.0,EARTH_RADIUS,ATMOS_RADIUS,vec3(5.5e-6,13.0e-6,22.4e-6),21e-6,8e3,1.2e3,0.758
);color.rgb=1.0-exp(-1.0*color.rgb);color=pow(color,vec4(1.0/2.2));fragColor=vec4(color.rgb,1.0-color.a)*u_atmosphere_blend;}`,`layout(location=0) in vec2 a_pos;uniform mat4 u_inv_proj_matrix;out vec3 view_direction;void main() {view_direction=(u_inv_proj_matrix*vec4(a_pos,0.0,1.0)).xyz;gl_Position=vec4(a_pos,0.0,1.0);}`),sky:WA(`uniform vec4 u_sky_color;uniform vec4 u_horizon_color;uniform vec2 u_horizon;uniform vec2 u_horizon_normal;uniform float u_sky_horizon_blend;uniform float u_sky_blend;uniform vec3 u_globe_position;uniform float u_globe_radius;uniform float u_atmosphere_blend;in vec3 v_view_direction;const float ATMOSPHERE_HEIGHT_TO_GLOBE_RADIUS=100000.0/6371000.0;void main() {float x=gl_FragCoord.x;float y=gl_FragCoord.y;float blend=(y-u_horizon.y)*u_horizon_normal.y+(x-u_horizon.x)*u_horizon_normal.x;float opacity=1.0;if (u_sky_blend > 0.0) {vec3 ray=normalize(v_view_direction);float globe_distance=length(u_globe_position);float angle_to_globe_center=acos(clamp(dot(ray,u_globe_position)/globe_distance,-1.0,1.0));float horizon_angle=asin(min(u_globe_radius/globe_distance,1.0));blend=mix(blend,((angle_to_globe_center-horizon_angle)*u_camera_to_center_distance+1.0)*u_device_pixel_ratio,u_sky_blend);float closest_approach=max(dot(ray,u_globe_position),0.0);float lowest_altitude=sqrt(max(globe_distance*globe_distance-closest_approach*closest_approach,0.0))-u_globe_radius;float atmosphere_height=u_globe_radius*ATMOSPHERE_HEIGHT_TO_GLOBE_RADIUS;float inside_atmosphere=1.0-smoothstep(atmosphere_height,10.0*atmosphere_height,globe_distance-u_globe_radius);float through_atmosphere=1.0-smoothstep(0.0,atmosphere_height,lowest_altitude);opacity=inside_atmosphere*through_atmosphere*(1.0-u_atmosphere_blend);}if (blend > 0.0) {if (blend < u_sky_horizon_blend) {fragColor=mix(u_sky_color,u_horizon_color,pow(1.0-blend/u_sky_horizon_blend,2.0));} else {fragColor=u_sky_color;}}fragColor*=mix(1.0,opacity,u_sky_blend);}`,`layout(location=0) in vec2 a_pos;uniform mat4 u_inv_proj_matrix;out vec3 v_view_direction;void main() {v_view_direction=(u_inv_proj_matrix*vec4(a_pos,0.0,1.0)).xyz;gl_Position=vec4(a_pos,1.0,1.0);}`)};function WA(e,t){let n=/#pragma maplibre: ([\w]+) ([\w]+) ([\w]+) ([\w]+)/g,r=t.match(/in ([\w]+) ([\w]+)/g),i=e.match(/uniform ([\w]+) ([\w]+)([\s]*)([\w]*)/g),a=t.match(/uniform ([\w]+) ([\w]+)([\s]*)([\w]*)/g),o=a?a.concat(i):i,s=r?r.length:0,c={};return e=e.replace(n,(e,t,n,r,i)=>(c[i]=!0,t===`define`?`
);color.rgb=1.0-exp(-1.0*color.rgb);color=pow(color,vec4(1.0/2.2));fragColor=vec4(color.rgb,1.0-color.a)*u_atmosphere_blend;}`,`layout(location=0) in vec2 a_pos;uniform mat4 u_inv_proj_matrix;out vec3 view_direction;void main() {view_direction=(u_inv_proj_matrix*vec4(a_pos,0.0,1.0)).xyz;gl_Position=vec4(a_pos,0.0,1.0);}`),sky:u9(`uniform vec4 u_sky_color;uniform vec4 u_horizon_color;uniform vec2 u_horizon;uniform vec2 u_horizon_normal;uniform float u_sky_horizon_blend;uniform float u_sky_blend;uniform vec3 u_globe_position;uniform float u_globe_radius;uniform float u_atmosphere_blend;in vec3 v_view_direction;const float ATMOSPHERE_HEIGHT_TO_GLOBE_RADIUS=100000.0/6371000.0;void main() {float x=gl_FragCoord.x;float y=gl_FragCoord.y;float blend=(y-u_horizon.y)*u_horizon_normal.y+(x-u_horizon.x)*u_horizon_normal.x;float opacity=1.0;if (u_sky_blend > 0.0) {vec3 ray=normalize(v_view_direction);float globe_distance=length(u_globe_position);float angle_to_globe_center=acos(clamp(dot(ray,u_globe_position)/globe_distance,-1.0,1.0));float horizon_angle=asin(min(u_globe_radius/globe_distance,1.0));blend=mix(blend,((angle_to_globe_center-horizon_angle)*u_camera_to_center_distance+1.0)*u_device_pixel_ratio,u_sky_blend);float closest_approach=max(dot(ray,u_globe_position),0.0);float lowest_altitude=sqrt(max(globe_distance*globe_distance-closest_approach*closest_approach,0.0))-u_globe_radius;float atmosphere_height=u_globe_radius*ATMOSPHERE_HEIGHT_TO_GLOBE_RADIUS;float inside_atmosphere=1.0-smoothstep(atmosphere_height,10.0*atmosphere_height,globe_distance-u_globe_radius);float through_atmosphere=1.0-smoothstep(0.0,atmosphere_height,lowest_altitude);opacity=inside_atmosphere*through_atmosphere*(1.0-u_atmosphere_blend);}if (blend > 0.0) {if (blend < u_sky_horizon_blend) {fragColor=mix(u_sky_color,u_horizon_color,pow(1.0-blend/u_sky_horizon_blend,2.0));} else {fragColor=u_sky_color;}}fragColor*=mix(1.0,opacity,u_sky_blend);}`,`layout(location=0) in vec2 a_pos;uniform mat4 u_inv_proj_matrix;out vec3 v_view_direction;void main() {v_view_direction=(u_inv_proj_matrix*vec4(a_pos,0.0,1.0)).xyz;gl_Position=vec4(a_pos,1.0,1.0);}`),fog:u9(`uniform vec4 u_fog_color;uniform vec4 u_horizon_color;uniform float u_fog_ground_blend;uniform float u_fog_ground_blend_opacity;uniform float u_horizon_fog_blend;in vec2 v_fog_pos;const float gamma=2.2;vec4 gammaToLinear(vec4 color) {return pow(color,vec4(gamma));}vec4 linearToGamma(vec4 color) {return pow(color,vec4(1.0/gamma));}void main() {float fog_depth=v_fog_pos.x/v_fog_pos.y*0.5+0.5;if (fog_depth <=u_fog_ground_blend) {discard;}float blend_color=u_horizon_fog_blend < 1.0 ? smoothstep(u_horizon_fog_blend,1.0,fog_depth) : 0.0;vec4 fog_horizon_color_linear=mix(gammaToLinear(u_fog_color),gammaToLinear(u_horizon_color),blend_color);float factor_fog=clamp((fog_depth-u_fog_ground_blend)/(1.0-u_fog_ground_blend),0.0,1.0);fragColor=linearToGamma(fog_horizon_color_linear)*pow(factor_fog,2.0)*u_fog_ground_blend_opacity;}`,`layout(location=0) in vec3 a_pos3d;uniform mat4 u_fog_matrix;uniform float u_ele_delta;out vec2 v_fog_pos;invariant gl_Position;void main() {float ele=get_elevation(a_pos3d.xy);float ele_delta=a_pos3d.z==1.0 ? u_ele_delta : 0.0;gl_Position=projectTileFor3D(a_pos3d.xy,ele-ele_delta);v_fog_pos=(u_fog_matrix*vec4(a_pos3d.xy,ele,1.0)).zw;}`)};function u9(e,t){let n=/#pragma maplibre: ([\w]+) ([\w]+) ([\w]+) ([\w]+)/g,r=t.match(/in ([\w]+) ([\w]+)/g),i=e.match(/uniform ([\w]+) ([\w]+)([\s]*)([\w]*)/g),a=t.match(/uniform ([\w]+) ([\w]+)([\s]*)([\w]*)/g),o=a?a.concat(i):i,s=r?r.length:0,c={};return e=e.replace(n,(e,t,n,r,i)=>(c[i]=!0,t===`define`?`
#ifndef HAS_UNIFORM_u_${i}
in ${n} ${r} ${i};
#else
@@ -844,7 +891,7 @@ uniform ${n} ${r} u_${i};
#else
${n} ${r} ${i} = u_${i};
#endif
`}),{fragmentSource:e,vertexSource:t,staticAttributes:r,staticUniforms:o}}const GA=`#define PROJECTION_MERCATOR`,KA=`mercator`;var qA=class{constructor(e=fp){this._cachedMesh=null,this._worldCoordinateHelper=e}get name(){return this._worldCoordinateHelper.name}get worldCoordinateHelper(){return this._worldCoordinateHelper}get useSubdivision(){return!1}get shaderVariantName(){return KA}get shaderDefine(){return GA}get shaderPreludeCode(){return UA.projectionMercator}get vertexShaderPreludeCode(){return UA.projectionMercator.vertexSource}get subdivisionGranularity(){return __.noSubdivision}get useGlobeControls(){return!1}get transitionState(){return 0}destroy(){}getMeshFromTileID(e,t,n,r,i){if(this._cachedMesh)return this._cachedMesh;let a=new Ed;a.emplaceBack(0,0),a.emplaceBack(N,0),a.emplaceBack(0,N),a.emplaceBack(N,N);let o=e.createVertexBuffer(a,UC.members),s=Jd.simpleSegment(0,0,4,2),c=new Ud;c.emplaceBack(1,0,2),c.emplaceBack(1,2,3);let l=e.createIndexBuffer(c);return this._cachedMesh=new HC(o,l,s),this._cachedMesh}recalculate(){}hasTransition(){return!1}};let JA;const YA=()=>JA||=new ku({type:new q(z.projection.type,`type`)}),XA=new __({fill:new g_(128,2),line:new g_(512,0),tile:new g_(128,32),stencil:new g_(128,1),circle:3});var ZA=class{constructor(){this._tileMeshCache={}}get name(){return`vertical-perspective`}get worldCoordinateHelper(){return fp}get transitionState(){return 1}get useSubdivision(){return!0}get shaderVariantName(){return`globe`}get shaderDefine(){return`#define GLOBE`}get shaderPreludeCode(){return UA.projectionGlobe}get vertexShaderPreludeCode(){return UA.projectionMercator.vertexSource}get subdivisionGranularity(){return XA}get useGlobeControls(){return!0}destroy(){}_getMeshKey(e){return`${e.granularity.toString(36)}_${e.generateBorders?`b`:``}${e.extendToNorthPole?`n`:``}${e.extendToSouthPole?`s`:``}`}getMeshFromTileID(e,t,n,r,i){let a=(i===`stencil`?XA.stencil:XA.tile).getGranularityForZoomLevel(t.z),o=t.y===0&&r,s=t.y===(1<<t.z)-1&&r;return this._getMesh(e,{granularity:a,generateBorders:n,extendToNorthPole:o,extendToSouthPole:s})}_getMesh(e,t){let n=this._getMeshKey(t);if(n in this._tileMeshCache)return this._tileMeshCache[n];let r=WC(e,t);return this._tileMeshCache[n]=r,r}recalculate(e){}hasTransition(){return!1}},QA=class extends Qn{constructor(e,t){super(),this._transitionable=new vu(YA(),`projection`,t),this.setProjection(e),this._transitioning=this._transitionable.untransitioned(),this.recalculate(new hu(0)),this._mercatorProjection=new qA,this._verticalPerspectiveProjection=new ZA}get transitionState(){let e=this.properties.get(`type`);if(typeof e==`string`&&e===`mercator`)return 0;if(typeof e==`string`&&e===`vertical-perspective`)return 1;if(e instanceof Ji){if(e.from===e.to)return e.from===`mercator`?0:1;if(e.from===`vertical-perspective`&&e.to===`mercator`)return 1-e.transition;if(e.from===`mercator`&&e.to===`vertical-perspective`)return e.transition}return 1}get useGlobeRendering(){return this.transitionState>0}get currentProjection(){return this.useGlobeRendering?this._verticalPerspectiveProjection:this._mercatorProjection}get name(){return`globe`}get worldCoordinateHelper(){return this.currentProjection.worldCoordinateHelper}get useSubdivision(){return this.currentProjection.useSubdivision}get shaderVariantName(){return this.currentProjection.shaderVariantName}get shaderDefine(){return this.currentProjection.shaderDefine}get shaderPreludeCode(){return this.currentProjection.shaderPreludeCode}get vertexShaderPreludeCode(){return this.currentProjection.vertexShaderPreludeCode}get subdivisionGranularity(){return this.currentProjection.subdivisionGranularity}get useGlobeControls(){return this.transitionState>0}destroy(){this._mercatorProjection.destroy(),this._verticalPerspectiveProjection.destroy()}getMeshFromTileID(e,t,n,r,i){return this.currentProjection.getMeshFromTileID(e,t,n,r,i)}setProjection(e){this._transitionable.setValue(`type`,e?.type||`mercator`)}updateTransitions(e){this._transitioning=this._transitionable.transitioned(e,this._transitioning)}hasTransition(){return this._transitioning.hasTransition()||this.currentProjection.hasTransition()}recalculate(e){this.properties=this._transitioning.possiblyEvaluate(e)}};function $A(e,t){if(Array.isArray(e)){let n=ej(e);return n&&I(`Projection expressions cannot use the registered projection "${n}", which only works as a plain name. Falling back to the globe projection.`),{projection:new QA({type:e},t),cameraProjection:`globe`}}let n=MC(e);if(n)return{projection:new qA(new OC(n)),cameraProjection:`mercator`};switch(e){case`mercator`:return{projection:new qA,cameraProjection:`mercator`};case`globe`:return{projection:new QA({type:[`interpolate`,[`linear`],[`zoom`],11,`vertical-perspective`,12,`mercator`]},{}),cameraProjection:`globe`};case`vertical-perspective`:return{projection:new ZA,cameraProjection:`vertical-perspective`};default:return I(`Unknown projection name: ${e}. Falling back to mercator projection.`),{pro Line truncated
`),b=v.concat(UA.prelude.vertexSource,o.vertexSource,t.vertexSource).join(`
`),x=l.createShader(l.FRAGMENT_SHADER);if(l.isContextLost()){this.failedToCreate=!0;return}l.shaderSource(x,y),l.compileShader(x),l.attachShader(this.program,x);let S=l.createShader(l.VERTEX_SHADER);if(l.isContextLost()){this.failedToCreate=!0;return}l.shaderSource(S,b),l.compileShader(S),l.attachShader(this.program,S),this.attributes={};let C={};if(this.numAttributes=f.length,l.linkProgram(this.program),!l.getProgramParameter(this.program,l.LINK_STATUS)){if(l.isContextLost()||l.getProgramParameter(this.program,l.ATTACHED_SHADERS)===0){this.failedToCreate=!0;return}throw l.getShaderParameter(x,l.COMPILE_STATUS)?l.getShaderParameter(S,l.COMPILE_STATUS)?Error(`Program failed to link: ${l.getProgramInfoLog(this.program)}`):Error(`Could not compile vertex shader: ${l.getShaderInfoLog(S)}`):Error(`Could not compile fragment shader: ${l.getShaderInfoLog(x)}`)}Gj(l,this.program);let w=SM(l,this.program);for(let e of f){if(!e)continue;let t=l.getAttribLocation(this.program,e);t>=0&&(this.attributes[e]={location:t,isInteger:w.has(e)})}l.deleteShader(S),l.deleteShader(x);for(let e of _)if(e&&!C[e]){let t=l.getUniformLocation(this.program,e);t&&(C[e]=t)}this.fixedUniforms=r(e,C),this.terrainUniforms=mM(e,C),this.binderUniforms=n?n.getUniforms(e,C):[]}draw(e,t,n,r,i,a,o,s,c,l,u,d,f,p,m,h,g,_,v){let y=e.gl;if(this.failedToCreate)return;if(e.program.set(this.program),e.terrainUniformBuffer.bind(),e.frameUniformBuffer.bind(),e.setDepthMode(n),e.setStencilMode(r),e.setColorMode(i),e.setCullFace(a),s){e.activeTexture.set(y.TEXTURE2),y.bindTexture(y.TEXTURE_2D,s.depthTexture),e.activeTexture.set(y.TEXTURE3),y.bindTexture(y.TEXTURE_2D,s.texture);for(let e in this.terrainUniforms)this.terrainUniforms[e].set(s[e]);uM(e.terrainUniformBuffer,s)}if($j(e,c),o)for(let e in this.fixedUniforms)this.fixedUniforms[e].set(o[e]);h&&h.setUniforms(e,this.binderUniforms,p,{zoom:m});let b=0;switch(t){case y.LINES:b=2;break;case y.TRIANGLES:b=3;break;case y.LINE_STRIP:b=1}for(let n of f.get())n.vaos||={},n.vaos[l]||=new pM,n.vaos[l].bind(e,this,u,h?h.getPaintVertexBuffers():[],d,n.vertexOffset,g,_,v),y.drawElements(t,n.primitiveLength*b,y.UNSIGNED_SHORT,n.primitiveOffset*b*2)}};function wM(e,t,n){let r=1/rt(n,1,t.tileZoom),i=2**n.tileID.overscaledZ,a=n.tileSize*2**t.tileZoom/i,o=a*(n.tileID.canonical.x+n.tileID.wrap*i),s=a*n.tileID.canonical.y;return{u_image:0,u_texsize:n.imageAtlasTexture.size,u_scale:[r,e.fromScale,e.toScale],u_fade:e.t,u_pixel_coord_upper:[o>>16,s>>16],u_pixel_coord_lower:[o&65535,s&65535]}}function TM(e,t,n,r,i){let a=n.getPattern(e.from.toString()),o=n.getPattern(e.to.toString()),{width:s,height:c}=n.getPixelSize(),l=2**i.tileID.overscaledZ,u=i.tileSize*2**r.tileZoom/l,d=u*(i.tileID.canonical.x+i.tileID.wrap*l),f=u*i.tileID.canonical.y;return{u_image:0,u_pattern_tl_a:a.tl,u_pattern_br_a:a.br,u_pattern_tl_b:o.tl,u_pattern_br_b:o.br,u_texsize:[s,c],u_mix:t.t,u_pattern_size_a:a.displaySize,u_pattern_size_b:o.displaySize,u_scale_a:t.fromScale,u_scale_b:t.toScale,u_tile_units_to_pixels:1/rt(i,1,r.tileZoom),u_pixel_coord_upper:[d>>16,f>>16],u_pixel_coord_lower:[d&65535,f&65535]}}const EM=(e,t)=>({u_lightpos:new cf(e,t.u_lightpos),u_lightpos_globe:new cf(e,t.u_lightpos_globe),u_lightintensity:new X(e,t.u_lightintensity),u_lightcolor:new cf(e,t.u_lightcolor),u_vertical_gradient:new X(e,t.u_vertical_gradient),u_opacity:new X(e,t.u_opacity),u_fill_translate:new sf(e,t.u_fill_translate)}),DM=(e,t)=>({u_lightpos:new cf(e,t.u_lightpos),u_lightpos_globe:new cf(e,t.u_lightpos_globe),u_lightintensity:new X(e,t.u_lightintensity),u_lightcolor:new cf(e,t.u_lightcolor),u_vertical_gradient:new X(e,t.u_vertical_gradient),u_height_factor:new X(e,t.u_height_factor),u_opacity:new X(e,t.u_opacity),u_fill_translate:new sf(e,t.u_fill_translate),u_image:new Y(e,t.u_image),u_texsize:new sf(e,t.u_texsize),u_pixel_coord_upper:new sf(e,t.u_pixel_coord_upper),u_pixel_coord_lower:new sf(e,t.u_pixel_coord_lower),u_scale:new cf(e,t.u_scale),u_fade:new X(e,t.u_fade)}),OM=(e,t,n,r,i)=>{let a=Vt(t.position),o=x();t.anchor===`viewport`&&C(o,e.bearingInRadians),Ee(a,a,o);let s=Q(e).transformLightDirection(e,a),c=t.color;return{u_lightpos:a,u_lightpos_globe:s,u_lightintensity:t.intensity,u_lightcolor:[c.r,c.g,c.b],u_vertical_gradient:+n,u_opacity:r,u_fill_translate:i}},kM=(e,t,n,r,i,a,o,s)=>F(OM(e,t,n,r,i),wM(o,e,s),{u_height_factor:-(2**a.overscaledZ)/s.tileSize/8}),AM=(e,t)=>({u_fill_translate:new sf(e,t.u_fill_translate)}),jM=(e,t)=>({u_image:new Y(e,t.u_image),u_texsize:new sf(e,t.u_texsize),u_pixel_coord_upper:new sf(e,t.u_pixel_coord_upper),u_pixel_coord_lower:new sf(e,t.u_pixel_coord_lower),u_scale:new cf(e,t.u_scale),u_fade:new X(e,t.u_fade),u_sdf_pattern:new Y(e,t.u_sdf_pattern),u_fill_translate:new sf(e,t.u_fill_translate)}),MM=(e,t)=>({u_fill_translate:new sf(e,t.u_fill_translate)}),NM=(e,t)=>({u_image:new Y(e,t.u_image),u_texsize:new sf(e,t.u_texsize),u_pixel_coord_upper:new sf(e,t.u_pixel_coord_upper),u_pixel_coord_lower:new sf(e,t.u_pixel_coord_lowe Line truncated
`}),{fragmentSource:e,vertexSource:t,staticAttributes:r,staticUniforms:o}}const d9=`#define PROJECTION_MERCATOR`,f9=`mercator`;var p9=class{constructor(e=zp){this._cachedMesh=null,this._worldCoordinateHelper=e}get name(){return this._worldCoordinateHelper.name}get worldCoordinateHelper(){return this._worldCoordinateHelper}getTransitionStateForZoom(){return 0}get useSubdivision(){return!1}get shaderVariantName(){return f9}get shaderDefine(){return d9}get shaderPreludeCode(){return l9.projectionMercator}get vertexShaderPreludeCode(){return l9.projectionMercator.vertexSource}get subdivisionGranularity(){return y_.noSubdivision}get useGlobeControls(){return!1}get transitionState(){return 0}destroy(){}getMeshFromTileID(e,t,n,r,i){if(this._cachedMesh)return this._cachedMesh;let a=new $d;a.emplaceBack(0,0),a.emplaceBack(N,0),a.emplaceBack(0,N),a.emplaceBack(N,N);let o=e.createVertexBuffer(a,i3.members),s=Cf.simpleSegment(0,0,4,2),c=new vf;c.emplaceBack(1,0,2),c.emplaceBack(1,2,3);let l=e.createIndexBuffer(c);return this._cachedMesh=new r3(o,l,s),this._cachedMesh}recalculate(){}hasTransition(){return!1}};let m9;const h9=()=>m9||=new Ou({type:new q(R.projection.type,`type`)}),g9=new y_({fill:new v_(128,2),line:new v_(512,0),tile:new v_(128,32),stencil:new v_(128,1),circle:3});var _9=class{constructor(){this._tileMeshCache={}}get name(){return`vertical-perspective`}get worldCoordinateHelper(){return zp}get transitionState(){return 1}getTransitionStateForZoom(){return 1}get useSubdivision(){return!0}get shaderVariantName(){return`globe`}get shaderDefine(){return`#define GLOBE`}get shaderPreludeCode(){return l9.projectionGlobe}get vertexShaderPreludeCode(){return l9.projectionMercator.vertexSource}get subdivisionGranularity(){return g9}get useGlobeControls(){return!0}destroy(){}_getMeshKey(e){return`${e.granularity.toString(36)}_${e.generateBorders?`b`:``}${e.extendToNorthPole?`n`:``}${e.extendToSouthPole?`s`:``}`}getMeshFromTileID(e,t,n,r,i){let a=(i===`stencil`?g9.stencil:g9.tile).getGranularityForZoomLevel(t.z),o=t.y===0&&r,s=t.y===(1<<t.z)-1&&r;return this._getMesh(e,{granularity:a,generateBorders:n,extendToNorthPole:o,extendToSouthPole:s})}_getMesh(e,t){let n=this._getMeshKey(t);if(n in this._tileMeshCache)return this._tileMeshCache[n];let r=a3(e,t);return this._tileMeshCache[n]=r,r}recalculate(e){}hasTransition(){return!1}},v9=class extends $n{constructor(e,t){super(),this._transitionable=new _u(h9(),`projection`,t),this.setProjection(e),this._transitioning=this._transitionable.untransitioned(),this.recalculate(new mu(0)),this._mercatorProjection=new p9,this._verticalPerspectiveProjection=new _9}get transitionState(){return this._getTransitionState(this.properties.get(`type`))}getTransitionStateForZoom(e){return this._getTransitionState(this._transitioning.possiblyEvaluate(new mu(e,{now:bn()})).get(`type`))}_getTransitionState(e){if(typeof e==`string`&&e===`mercator`)return 0;if(typeof e==`string`&&e===`vertical-perspective`)return 1;if(e instanceof Yi){if(e.from===e.to)return e.from===`mercator`?0:1;if(e.from===`vertical-perspective`&&e.to===`mercator`)return 1-e.transition;if(e.from===`mercator`&&e.to===`vertical-perspective`)return e.transition}return 1}get useGlobeRendering(){return this.transitionState>0}get currentProjection(){return this.useGlobeRendering?this._verticalPerspectiveProjection:this._mercatorProjection}get name(){return`globe`}get worldCoordinateHelper(){return this.currentProjection.worldCoordinateHelper}get useSubdivision(){return this.currentProjection.useSubdivision}get shaderVariantName(){return this.currentProjection.shaderVariantName}get shaderDefine(){return this.currentProjection.shaderDefine}get shaderPreludeCode(){return this.currentProjection.shaderPreludeCode}get vertexShaderPreludeCode(){return this.currentProjection.vertexShaderPreludeCode}get subdivisionGranularity(){return this.currentProjection.subdivisionGranularity}get useGlobeControls(){return this.transitionState>0}destroy(){this._mercatorProjection.destroy(),this._verticalPerspectiveProjection.destroy()}getMeshFromTileID(e,t,n,r,i){return this.currentProjection.getMeshFromTileID(e,t,n,r,i)}setProjection(e){this._transitionable.setValue(`type`,e?.type||`mercator`)}updateTransitions(e){this._transitioning=this._transitionable.transitioned(e,this._transitioning)}hasTransition(){return this._transitioning.hasTransition()||this.currentProjection.hasTransition()}recalculate(e){this.properties=this._transitioning.possiblyEvaluate(e)}};function y9(e,t){if(Array.isArray(e)){let n=b9(e);return n&&F(`Projection expressions cannot use the registered projection "${n}", which only works as a plain name. Falling back to the globe projection.`),{projection:new v9({type:e},t),cameraProjection:`globe`}}let n=q4(e);if(n)return{projection:new p9(new U4(n)),cameraProjection:`mercator`};switch(e){case`mercator`:return{projection:new p9,cameraProjection:`mercator`};case`globe`:return{projection:new v9({type:[`interpolate`,[`linear`],[`zoom`], Line truncated
`),b=v.concat(l9.prelude.vertexSource,o.vertexSource,t.vertexSource).join(`
`),x=l.createShader(l.FRAGMENT_SHADER);if(l.isContextLost()){this.failedToCreate=!0;return}l.shaderSource(x,y),l.compileShader(x),l.attachShader(this.program,x);let S=l.createShader(l.VERTEX_SHADER);if(l.isContextLost()){this.failedToCreate=!0;return}l.shaderSource(S,b),l.compileShader(S),l.attachShader(this.program,S),this.attributes={};let C={};if(this.numAttributes=f.length,l.linkProgram(this.program),!l.getProgramParameter(this.program,l.LINK_STATUS)){if(l.isContextLost()||l.getProgramParameter(this.program,l.ATTACHED_SHADERS)===0){this.failedToCreate=!0;return}throw l.getShaderParameter(x,l.COMPILE_STATUS)?l.getShaderParameter(S,l.COMPILE_STATUS)?Error(`Program failed to link: ${l.getProgramInfoLog(this.program)}`):Error(`Could not compile vertex shader: ${l.getShaderInfoLog(S)}`):Error(`Could not compile fragment shader: ${l.getShaderInfoLog(x)}`)}dS(l,this.program);let w=HS(l,this.program);for(let e of f){if(!e)continue;let t=l.getAttribLocation(this.program,e);t>=0&&(this.attributes[e]={location:t,isInteger:w.has(e)})}l.deleteShader(S),l.deleteShader(x);for(let e of _)if(e&&!C[e]){let t=l.getUniformLocation(this.program,e);t&&(C[e]=t)}this.fixedUniforms=r(e,C),this.terrainUniforms=PS(e,C),this.binderUniforms=n?n.getUniforms(e,C):[]}draw(e,t,n,r,i,a,o,s,c,l,u,d,f,p,m,h,g,_,v){let y=e.gl;if(this.failedToCreate)return;if(e.program.set(this.program),e.terrainUniformBuffer.bind(),e.frameUniformBuffer.bind(),e.setDepthMode(n),e.setStencilMode(r),e.setColorMode(i),e.setCullFace(a),s){e.activeTexture.set(y.TEXTURE2),y.bindTexture(y.TEXTURE_2D,s.depthTexture),e.activeTexture.set(y.TEXTURE3),y.bindTexture(y.TEXTURE_2D,s.texture);for(let e in this.terrainUniforms)this.terrainUniforms[e].set(s[e]);AS(e.terrainUniformBuffer,s)}if(yS(e,c),o)for(let e in this.fixedUniforms)this.fixedUniforms[e].set(o[e]);h&&h.setUniforms(e,this.binderUniforms,p,{zoom:m});let b=0;switch(t){case y.LINES:b=2;break;case y.TRIANGLES:b=3;break;case y.LINE_STRIP:b=1}for(let n of f.get())n.vaos||={},n.vaos[l]||=new NS,n.vaos[l].bind(e,this,u,h?h.getPaintVertexBuffers():[],d,n.vertexOffset,g,_,v),y.drawElements(t,n.primitiveLength*b,y.UNSIGNED_SHORT,n.primitiveOffset*b*2)}};function WS(e,t,n){let r=1/rt(n,1,t.tileZoom),i=2**n.tileID.overscaledZ,a=n.tileSize*2**t.tileZoom/i,o=a*(n.tileID.canonical.x+n.tileID.wrap*i),s=a*n.tileID.canonical.y;return{u_image:0,u_texsize:n.imageAtlasTexture.size,u_scale:[r,e.fromScale,e.toScale],u_fade:e.t,u_pixel_coord_upper:[o>>16,s>>16],u_pixel_coord_lower:[o&65535,s&65535]}}function GS(e,t,n,r,i){let a=n.getPattern(e.from.toString()),o=n.getPattern(e.to.toString()),{width:s,height:c}=n.getPixelSize(),l=2**i.tileID.overscaledZ,u=i.tileSize*2**r.tileZoom/l,d=u*(i.tileID.canonical.x+i.tileID.wrap*l),f=u*i.tileID.canonical.y;return{u_image:0,u_pattern_tl_a:a.tl,u_pattern_br_a:a.br,u_pattern_tl_b:o.tl,u_pattern_br_b:o.br,u_texsize:[s,c],u_mix:t.t,u_pattern_size_a:a.displaySize,u_pattern_size_b:o.displaySize,u_scale_a:t.fromScale,u_scale_b:t.toScale,u_tile_units_to_pixels:1/rt(i,1,r.tileZoom),u_pixel_coord_upper:[d>>16,f>>16],u_pixel_coord_lower:[d&65535,f&65535]}}const KS=(e,t)=>({u_lightpos:new Ff(e,t.u_lightpos),u_lightpos_globe:new Ff(e,t.u_lightpos_globe),u_lightintensity:new X(e,t.u_lightintensity),u_lightcolor:new Ff(e,t.u_lightcolor),u_vertical_gradient:new X(e,t.u_vertical_gradient),u_fill_translate:new Z(e,t.u_fill_translate)}),qS=(e,t)=>({u_lightpos:new Ff(e,t.u_lightpos),u_lightpos_globe:new Ff(e,t.u_lightpos_globe),u_lightintensity:new X(e,t.u_lightintensity),u_lightcolor:new Ff(e,t.u_lightcolor),u_vertical_gradient:new X(e,t.u_vertical_gradient),u_height_factor:new X(e,t.u_height_factor),u_fill_translate:new Z(e,t.u_fill_translate),u_image:new Y(e,t.u_image),u_texsize:new Z(e,t.u_texsize),u_pixel_coord_upper:new Z(e,t.u_pixel_coord_upper),u_pixel_coord_lower:new Z(e,t.u_pixel_coord_lower),u_scale:new Ff(e,t.u_scale),u_fade:new X(e,t.u_fade)}),JS=(e,t,n,r)=>{let i=Vt(t.position),a=x();t.anchor===`viewport`&&C(a,e.bearingInRadians),Ee(i,i,a);let o=$(e).transformLightDirection(e,i),s=t.color;return{u_lightpos:i,u_lightpos_globe:o,u_lightintensity:t.intensity,u_lightcolor:[s.r,s.g,s.b],u_vertical_gradient:+n,u_fill_translate:r}},YS=(e,t,n,r,i,a,o)=>({...JS(e,t,n,r),...WS(a,e,o),u_height_factor:-(2**i.overscaledZ)/o.tileSize/8}),XS=(e,t)=>({u_fill_translate:new Z(e,t.u_fill_translate)}),ZS=(e,t)=>({u_image:new Y(e,t.u_image),u_texsize:new Z(e,t.u_texsize),u_pixel_coord_upper:new Z(e,t.u_pixel_coord_upper),u_pixel_coord_lower:new Z(e,t.u_pixel_coord_lower),u_scale:new Ff(e,t.u_scale),u_fade:new X(e,t.u_fade),u_sdf_pattern:new Y(e,t.u_sdf_pattern),u_fill_translate:new Z(e,t.u_fill_translate)}),QS=(e,t)=>({u_fill_translate:new Z(e,t.u_fill_translate)}),$S=(e,t)=>({u_image:new Y(e,t.u_image),u_texsize:new Z(e,t.u_texsize),u_pixel_coord_upper:new Z(e,t.u_pixel_coord_upper),u_pixel_coord_lower:new Z(e,t.u_pixel_coord_lower),u_scale:new Ff(e,t.u_scale),u_fade:new X(e,t.u_fade),u_sdf_pattern:new Y(e,t.u_sdf_pat Line truncated
//# sourceMappingURL=maplibre-gl.mjs.map
+1
View File
@@ -3,6 +3,7 @@ export const mdiBacteriaOutline = "M9,2H7V4.1C6.29,4.25 5.73,4.54 5.32,4.91L2.7,
export const mdiBugOutline = "M20,8H17.19C16.74,7.2 16.12,6.5 15.37,6L17,4.41L15.59,3L13.42,5.17C12.96,5.06 12.5,5 12,5C11.5,5 11.05,5.06 10.59,5.17L8.41,3L7,4.41L8.62,6C7.87,6.5 7.26,7.21 6.81,8H4V10H6.09C6.03,10.33 6,10.66 6,11V12H4V14H6V15C6,15.34 6.03,15.67 6.09,16H4V18H6.81C8.47,20.87 12.14,21.84 15,20.18C15.91,19.66 16.67,18.9 17.19,18H20V16H17.91C17.97,15.67 18,15.34 18,15V14H20V12H18V11C18,10.66 17.97,10.33 17.91,10H20V8M16,15A4,4 0 0,1 12,19A4,4 0 0,1 8,15V11A4,4 0 0,1 12,7A4,4 0 0,1 16,11V15M14,10V12H10V10H14M10,14H14V16H10V14Z";
export const mdiClockOutline = "M12,20A8,8 0 0,0 20,12A8,8 0 0,0 12,4A8,8 0 0,0 4,12A8,8 0 0,0 12,20M12,2A10,10 0 0,1 22,12A10,10 0 0,1 12,22C6.47,22 2,17.5 2,12A10,10 0 0,1 12,2M12.5,7V12.25L17,14.92L16.25,16.15L11,13V7H12.5Z";
export const mdiCloudDownloadOutline = "M6.5 20Q4.22 20 2.61 18.43 1 16.85 1 14.58 1 12.63 2.17 11.1 3.35 9.57 5.25 9.15 5.68 7.35 7.38 5.73 9.07 4.1 11 4.1 11.83 4.1 12.41 4.69 13 5.28 13 6.1V12.15L14.6 10.6L16 12L12 16L8 12L9.4 10.6L11 12.15V6.1Q9.1 6.45 8.05 7.94 7 9.43 7 11H6.5Q5.05 11 4.03 12.03 3 13.05 3 14.5 3 15.95 4.03 17 5.05 18 6.5 18H18.5Q19.55 18 20.27 17.27 21 16.55 21 15.5 21 14.45 20.27 13.73 19.55 13 18.5 13H17V11Q17 9.8 16.45 8.76 15.9 7.73 15 7V4.68Q16.85 5.55 17.93 7.26 19 9 19 11 20.73 11.2 21.86 12.5 23 13.78 23 15.5 23 17.38 21.69 18.69 20.38 20 18.5 20M12 11.05Z";
export const mdiCloudSyncOutline = "M13.03 18C13.08 18.7 13.24 19.38 13.5 20H6.5C5 20 3.69 19.5 2.61 18.43C1.54 17.38 1 16.09 1 14.58C1 13.28 1.39 12.12 2.17 11.1S4 9.43 5.25 9.15C5.67 7.62 6.5 6.38 7.75 5.43S10.42 4 12 4C13.95 4 15.6 4.68 16.96 6.04C18.32 7.4 19 9.05 19 11C19.04 11 19.07 11 19.1 11C18.36 11.07 17.65 11.23 17 11.5V11C17 9.62 16.5 8.44 15.54 7.46C14.56 6.5 13.38 6 12 6S9.44 6.5 8.46 7.46C7.5 8.44 7 9.62 7 11H6.5C5.53 11 4.71 11.34 4.03 12.03C3.34 12.71 3 13.53 3 14.5S3.34 16.29 4.03 17C4.71 17.66 5.53 18 6.5 18H13.03M19 13.5V12L16.75 14.25L19 16.5V15C20.38 15 21.5 16.12 21.5 17.5C21.5 17.9 21.41 18.28 21.24 18.62L22.33 19.71C22.75 19.08 23 18.32 23 17.5C23 15.29 21.21 13.5 19 13.5M19 20C17.62 20 16.5 18.88 16.5 17.5C16.5 17.1 16.59 16.72 16.76 16.38L15.67 15.29C15.25 15.92 15 16.68 15 17.5C15 19.71 16.79 21.5 19 21.5V23L21.25 20.75L19 18.5V20Z";
export const mdiContentSaveOutline = "M17 3H5C3.89 3 3 3.9 3 5V19C3 20.1 3.89 21 5 21H19C20.1 21 21 20.1 21 19V7L17 3M19 19H5V5H16.17L19 7.83V19M12 12C10.34 12 9 13.34 9 15S10.34 18 12 18 15 16.66 15 15 13.66 12 12 12M6 6H15V10H6V6Z";
export const mdiCrosshairsGps = "M12,8A4,4 0 0,1 16,12A4,4 0 0,1 12,16A4,4 0 0,1 8,12A4,4 0 0,1 12,8M3.05,13H1V11H3.05C3.5,6.83 6.83,3.5 11,3.05V1H13V3.05C17.17,3.5 20.5,6.83 20.95,11H23V13H20.95C20.5,17.17 17.17,20.5 13,20.95V23H11V20.95C6.83,20.5 3.5,17.17 3.05,13M12,5A7,7 0 0,0 5,12A7,7 0 0,0 12,19A7,7 0 0,0 19,12A7,7 0 0,0 12,5Z";
export const mdiDeleteSweepOutline = "M15,16H19V18H15V16M15,8H22V10H15V8M15,12H21V14H15V12M11,10V18H5V10H11M13,8H3V18A2,2 0 0,0 5,20H11A2,2 0 0,0 13,18V8M14,5H11L10,4H6L5,5H2V7H14V5Z";
+170 -1
View File
@@ -137,6 +137,85 @@ class AppTest < Minitest::Test
assert_equal 401, request.get("/api/live").status
end
def test_the_sync_feed_needs_the_sync_token
# No SYNC_TOKEN in tests: closed, even with a login or an empty bearer.
assert_equal 401, request.get("/api/sync/changes").status
assert_equal 401, request.get("/api/sync/changes", "HTTP_AUTHORIZATION" => "Bearer ", **logged_in_env).status
assert_equal 401, request.get("/api/sync/source/x").status
assert_equal 401, request.post("/api/sync/apply", input: "{}").status
assert_equal 401, request.put("/api/sync/source/x", input: "x").status
assert_equal 401, request.get("/api/sync/maps", **logged_in_env).status
assert_equal 401, request.get("/api/sync/maps/file", params: { "path" => "offline.pmtiles" }).status
end
def test_connected_networks_are_the_interfaces_subnets
networks = Maptool::App.connected_networks
assert(networks.any? { |n| n.include?(IPAddr.new("127.0.0.1")) }, "loopback's 127.0.0.0/8")
refute(networks.any? { |n| n.include?(IPAddr.new("8.8.8.8")) })
end
def test_map_data_offered_to_clients_is_only_the_map_files
data = Maptool::App::DATA_DIR
files = %w[terrain.pmtiles places/SK.sqlite places/.rsync-partial/SK.sqlite routing/tiles.tar.part routing/service.sh can.json]
files.each { |f| FileUtils.mkdir_p(File.dirname(File.join(data, f))); File.write(File.join(data, f), "x") }
offered = Maptool::App.map_sync_files
assert_includes offered.keys, "terrain.pmtiles"
assert_includes offered.keys, "places/SK.sqlite"
refute(offered.keys.any? { |f| f.include?(".rsync-partial") || f.end_with?(".part") || %w[can.json routing/service.sh].include?(f) })
ensure
files.each { |f| FileUtils.rm_f(File.join(data, f)) }
end
def test_the_sync_button_is_only_a_clients
assert_equal 401, request.post("/api/sync/run").status
assert_equal 404, request.post("/api/sync/run", **logged_in_env).status
refute_includes request.get("/", **logged_in_env).body, "data-sync-client"
end
def test_can_recordings_are_listed_and_served_by_name_only
assert_equal 401, request.get("/api/can/recording").status
dir = File.join(Maptool::App::DATA_DIR, "can_rec")
FileUtils.mkdir_p(dir)
File.write(File.join(dir, "20261202-181105.mf4"), "MDF")
File.write(File.join(dir, "20261202-181105.mf4.part"), "")
body = json_body(request.get("/api/can/recording", **logged_in_env))
assert_equal [false, false, ["20261202-181105.mf4"]], [body["available"], body["running"], body["files"].map { |f| f["name"] }]
assert_equal 409, request.post("/api/can/recording", **logged_in_env).status
assert_equal "MDF", request.get("/api/can/recordings/20261202-181105.mf4", **logged_in_env).body
assert_equal 404, request.get("/api/can/recordings/20261202-181105.mf4.part", **logged_in_env).status
assert_equal 404, request.get("/api/can/recordings/..%2Fcan.json", **logged_in_env).status
ensure
FileUtils.rm_rf(dir)
end
def test_can_requires_login_and_is_off_without_a_config
assert_equal 401, request.get("/api/can").status
assert_equal 409, request.post("/api/can/actions/0", **logged_in_env).status
assert_equal({ "interfaces" => {}, "nodes" => {}, "signals" => {}, "frames" => [], "available" => false, "simulated" => false, "actions" => [], "time" => nil }, json_body(request.get("/api/can", **logged_in_env)))
end
# The keypads' bindings: the profile's until this car saves its own, checked on the way in.
def test_keypad_bindings_saved_over_the_profile
assert_equal 401, request.get("/api/keypad/bindings").status
body = json_body(request.get("/api/keypad/bindings", **logged_in_env))
refute body["saved"]
assert body["bindings"].any? { |b| b["input"] == "pad.K1" }
own = [{ "input" => "pad.K1", "output" => "relays.2", "mode" => "pulse", "pulse_s" => "2", "led" => "red", "junk" => 1 }]
body = json_body(request.put("/api/keypad/bindings", input: JSON.generate(bindings: own), **logged_in_env))
assert_equal [{ "input" => "pad.K1", "output" => "relays.2", "mode" => "pulse", "pulse_s" => 2.0, "led" => "red" }], body["bindings"]
assert_equal body["bindings"], Maptool::App.bindings
assert_equal 400, request.put("/api/keypad/bindings", input: JSON.generate(bindings: [{ "input" => "pad.K1", "mode" => "blink" }]), **logged_in_env).status
assert_equal 400, request.put("/api/keypad/bindings", input: JSON.generate(bindings: [{ "input" => "pad.K1", "led" => "pink" }]), **logged_in_env).status
assert_equal 400, request.put("/api/keypad/bindings", input: JSON.generate(bindings: [{ "input" => "pad.K2", "mode" => "positions", "output" => "relays.1" }]), **logged_in_env).status
pos = [{ "input" => "pad.K2", "mode" => "positions", "outputs" => ["relays.1", "relays.2"], "output" => "relays.1" }]
assert_equal [{ "input" => "pad.K2", "mode" => "positions", "outputs" => ["relays.1", "relays.2"] }],
json_body(request.put("/api/keypad/bindings", input: JSON.generate(bindings: pos), **logged_in_env))["bindings"]
refute json_body(request.delete("/api/keypad/bindings", **logged_in_env))["saved"]
assert Maptool::App.bindings.size > 1
ensure
FileUtils.rm_f(Maptool::App::BINDINGS_PATH)
end
# MQTT messages land in the tracker / ITS-G5 parts of /api/live.
def test_live_routes_topics_into_the_snapshot
app = Maptool::App
@@ -442,7 +521,7 @@ class AppTest < Minitest::Test
def test_plugins_lists_whatever_is_on_disk
response = request.get("/api/plugins")
assert_equal 200, response.status
assert_equal [{ "name" => "test-plugin", "label" => "Test plugin" }], json_body(response)
assert_equal [{ "name" => "test-plugin", "label" => "Test plugin", "route" => false, "settings" => [], "set" => [] }], json_body(response)
end
def test_plugins_run_imports_the_output_into_a_folder_of_its_own
@@ -459,6 +538,22 @@ class AppTest < Minitest::Test
assert_equal "Test POI", saved["features"][0]["properties"]["name"]
end
# Along the trip's route: what lies further off than the corridor dropped.
def test_plugins_run_along_the_route_keeps_the_corridor
store = Maptool::App::TRIP_STORE
saved = store.instance_variable_get(:@trip)
run = lambda do |line|
store.instance_variable_set(:@trip, saved.merge(route: { geometry: { coordinates: line } }))
json_body(request.post("/api/plugins/test-plugin/run", params: { route: "1", corridor_km: "2" }, **logged_in_env))["count"]
end
assert_equal 1, run.([[17.0, 47.99], [17.1, 47.99]]) # the POI ~1.1 km off
assert_equal 0, run.([[17.0, 47.95], [17.1, 47.95]]) # ~5.6 km off
store.instance_variable_set(:@trip, saved.merge(route: nil))
assert_equal 422, request.post("/api/plugins/test-plugin/run", params: { route: "1", corridor_km: "2" }, **logged_in_env).status
ensure
store.instance_variable_set(:@trip, saved)
end
def test_plugins_run_requires_a_bbox
response = request.post("/api/plugins/test-plugin/run", **logged_in_env)
assert_equal 400, response.status
@@ -622,6 +717,80 @@ class AppTest < Minitest::Test
assert_equal 404, response.status
end
def test_a_gnss_fix_without_a_course_gets_one_from_the_fixes_before
latest = Maptool::App::GNSS_LATEST
latest.clear
step = 10.0 / 111_320 # 10 m north each fix
Maptool::App.gnss_update({ lat: 48.0, lon: 17.0, speed: 10.0 })
assert_nil latest[:track]
Maptool::App.gnss_update({ lat: 48.0 + step, lon: 17.0 })
assert_in_delta 0.0, latest[:track], 0.1
Maptool::App.gnss_update({ lat: 48.0 + step, lon: 17.0 + step / Math.cos(48 * Math::PI / 180) })
assert_in_delta 90.0, latest[:track], 0.5
Maptool::App.gnss_update({ speed: 0.0 })
Maptool::App.gnss_update({ lat: 48.0, lon: 17.0 }) # standing still: the course stays
assert_in_delta 90.0, latest[:track], 0.5
ensure
latest.clear
end
# The recording's days and its export: a GPX with a track per day, or a .zip.
def test_trip_log_days_and_export
log = Maptool::App::TRIP_LOG
log.stop
assert_equal 200, request.post("/api/trip/log", input: JSON.generate(name: "Export test"), "CONTENT_TYPE" => "application/json", **logged_in_env).status
t0 = Time.new(2026, 12, 1, 10).to_f
10.times { |i| log.record(17.0, 48.0 + i * 0.001, 100.0, t0 + i * 60) }
10.times { |i| log.record(17.0, 48.1 + i * 0.001, 100.0, t0 + 10 * 3600 + i * 60) } # stood 10 h
log.record(17.0, 48.2, 100.0, t0 + 11 * 3600)
days = json_body(request.get("/api/trip/log/days?track=1", **logged_in_env))
assert_equal [true, 2, "auto"], [days["active"], days["days"].size, days["days"][0]["cut"]["kind"]]
assert_equal 21, days["track"].size
gpx = request.get("/api/trip/log/export?pauses=1", **logged_in_env)
assert_equal 2, gpx.body.scan("<trk>").size
assert_includes gpx.body, "Stood "
one = request.get("/api/trip/log/export?days=2", **logged_in_env).body
assert_equal 1, one.scan("<trk>").size
zip = request.get("/api/trip/log/export?per_day=1", **logged_in_env)
assert_equal "application/zip", zip.content_type
assert_equal 200, request.post("/api/trip/log/days", input: JSON.generate(join: days["track"][10][2]), "CONTENT_TYPE" => "application/json", **logged_in_env).status
assert_equal 1, json_body(request.get("/api/trip/log/days", **logged_in_env))["days"].size
ensure
log.stop
end
# A tunnel: no fix for a while, the position carried along the trip's
# route — at the average speed it was entered at, by the CAN speed when there is one.
def test_no_fix_on_the_route_is_dead_reckoned_along_it
latest = Maptool::App::GNSS_LATEST
latest.clear
store = Maptool::App::TRIP_STORE
saved = store.instance_variable_get(:@trip)
north = 1000.0 / 111_320 # 1 km north
store.instance_variable_set(:@trip, saved.merge(points: [], route: { geometry: { coordinates: [[17.0, 48.0], [17.0, 48.0 + 5 * north]] } }))
Maptool::App.gnss_update({ lat: 48.0, lon: 17.0, speed: 20.0, mode: 3 }, at: 100.0)
Maptool::App.gnss_update({ lat: 48.0, lon: 17.0, speed: 20.0 }, at: 101.0)
assert_nil Maptool::App.gnss_position(now: 102.0)[:estimated] # not yet: a fix may just be late
position = Maptool::App.gnss_position(now: 111.0) # 10 s × 20 m/s
assert position[:estimated]
assert_in_delta 48.0 + 0.2 * north, position[:lat], 1e-6
assert_in_delta 0.0, position[:track], 0.5
Maptool::App.gnss_update({ lat: 48.0, lon: 17.0, mode: 1 }, at: 105.0) # the receiver repeating its last fix
assert Maptool::App.gnss_position(now: 111.0)[:estimated]
Maptool::App.vehicle_speed_update(10.0, at: 102.0) # the car's own speed: 10 m/s
Maptool::App.vehicle_speed_update(10.0, at: 103.0)
position = Maptool::App.gnss_position(now: 104.0)
assert_in_delta 48.0 + 0.02 * north, position[:lat], 1e-6
assert_equal 10.0, position[:speed]
ensure
latest.clear
store.instance_variable_set(:@trip, saved)
end
private
def upload(filename, content, folder: "", content_type: "application/octet-stream")
+133
View File
@@ -0,0 +1,133 @@
require_relative "test_helper"
require "maptool/can"
require "maptool/can_recorder"
require "timeout"
class CanTest < Minitest::Test
Frame = Maptool::Can::Frame
def test_a_frame_round_trips_through_struct_can_frame
frame = Frame.new(0x181, "\x01\x02\x03".b, false)
bytes = frame.pack
assert_equal 16, bytes.bytesize
assert_equal frame, Frame.unpack(bytes)
extended = Frame.new(0x18FEF100, "\xFF".b, true)
assert_equal extended, Frame.unpack(extended.pack)
assert_nil Frame.unpack([0x181 | Maptool::Can::RTR_FLAG, 0, ""].pack(Maptool::Can::FRAME)), "remote request: no data"
end
def test_canopen_roles_by_cob_id
roles = [0x000, 0x080, 0x081, 0x181, 0x285, 0x20A, 0x585, 0x605, 0x77F].map { |id| Maptool::Can.canopen_role(id) }
assert_equal [[:nmt, nil], [:sync, nil], [:emcy, 1], [:tpdo1, 1], [:tpdo2, 5], [:rpdo1, 10], [:sdo_tx, 5], [:sdo_rx, 5], [:heartbeat, 127]], roles
assert_nil Maptool::Can.canopen_role(0x181, extended: true)
assert_equal [0x01, 0x00], Maptool::Can.nmt_start.data.bytes
end
def test_signals_decode_by_id_mask_type_and_scale
decoder = Maptool::Can::Decoder.new([
{ "name" => "gnss.lat", "id" => "0x181", "byte" => 0, "type" => "i32", "scale" => 1e-7 },
{ "name" => "gnss.lon", "id" => "0x181", "byte" => 4, "type" => "i32", "scale" => 1e-7 },
{ "name" => "keypad.key2", "id" => "0x195", "byte" => 0, "bit" => 1, "type" => "bit" },
{ "name" => "car.rpm", "id" => "0x18FEF100", "mask" => "0x00FFFF00", "byte" => 3, "type" => "u16", "scale" => 0.125 },
{ "name" => "temp", "id" => "0x281", "byte" => 0, "type" => "i16", "scale" => 0.1, "offset" => -40 },
])
gnss = decoder.decode(Frame.new(0x181, [491_700_000, 200_500_000].pack("l<l<"), false))
assert_in_delta 49.17, gnss["gnss.lat"], 1e-9
assert_in_delta 20.05, gnss["gnss.lon"], 1e-9
assert_equal({ "keypad.key2" => 1 }, decoder.decode(Frame.new(0x195, "\x02".b, false)))
assert_equal({ "keypad.key2" => 0 }, decoder.decode(Frame.new(0x195, "\x01".b, false)))
# Another source address (low byte) under the mask; a standard id never matches an extended signal.
assert_equal({ "car.rpm" => 800.0 }, decoder.decode(Frame.new(0x18FEF1AB, "\0\0\0#{[6400].pack('S<')}".b, true)))
assert_empty decoder.decode(Frame.new(0x0F1, "\0\0\0\0\0".b, false))
assert_in_delta(-15.0, decoder.decode(Frame.new(0x281, [250].pack("s<"), false))["temp"])
assert_empty decoder.decode(Frame.new(0x181, "\x01".b, false)), "too short for the i32s"
# esphome-canopen's Sensor16 (min..max over 0..65534, 65535 unknown) and a NaN float: no value.
alt = Maptool::Can::Decoder.new([{ "name" => "alt", "id" => "0x4A1", "type" => "u16", "scale" => 9500.0 / 65534, "offset" => -500, "invalid" => 65535 },
{ "name" => "lat", "id" => "0x3A1", "type" => "f32" }])
assert_in_delta 9000, alt.decode(Frame.new(0x4A1, [65534].pack("S<"), false))["alt"], 1e-6
assert_empty alt.decode(Frame.new(0x4A1, [65535].pack("S<"), false))
assert_empty alt.decode(Frame.new(0x3A1, [Float::NAN].pack("e"), false))
assert_raises(ArgumentError) { Maptool::Can::Decoder.new([{ "name" => "x", "id" => 1, "type" => "u64" }]) }
end
def test_the_store_keeps_signals_and_node_heartbeat_states
store = Maptool::Can::Store.new
store.record("vcan0", Frame.new(0x705, "\x05".b, false), {}, at: 1.0)
store.record("vcan0", Frame.new(0x181, "".b, false), { "gnss.lat" => 49.1 }, at: 2.0)
snapshot = store.snapshot
assert_equal({ frames: 2, last_frame_at: 2.0 }, snapshot[:interfaces]["vcan0"])
assert_equal [1.0, "operational"], snapshot[:nodes][5].values_at(:seen_at, :state)
assert_equal({ value: 49.1, at: 2.0 }, snapshot[:signals]["gnss.lat"])
store.record("vcan0", Frame.new(0x181, "".b, false), {}, at: 2.5)
store.record("vcan0", Frame.new(0x085, [0x8130, 0x11].pack("S<C"), false), {}, at: 3.0)
snapshot = store.snapshot
tpdo = snapshot[:frames].find { |f| f[:id] == 0x181 }
assert_equal [:tpdo1, 1, 2, 0.5], tpdo.values_at(:role, :node, :count, :interval)
assert_equal({ code: 0x8130, register: 0x11, at: 3.0 }, snapshot[:nodes][5][:emcy])
assert_equal [3, 4], store.snapshot(since: 2)[:log].map { |f| f[:seq] }
assert_equal [[], 4], store.snapshot(since: 99).values_at(:log, :log_seq)
assert_equal "3081" "11", store.snapshot(since: 3)[:log].first[:data]
end
def test_a_node_missing_3_heartbeats_is_silent_until_heard_again
store = Maptool::Can::Store.new
[0, 5, 10].each { |t| store.record("vcan0", Frame.new(0x702, "\x05".b, false), {}, at: t.to_f) }
_, err = capture_io { store.record("vcan0", Frame.new(0x701, "\x05".b, false), {}, at: 24.0) }
refute store.snapshot[:nodes][2][:silent]
_, err = capture_io { store.record("vcan0", Frame.new(0x701, "\x05".b, false), {}, at: 26.0) }
assert store.snapshot[:nodes][2][:silent]
assert_match(/node 2 silent/, err)
_, err = capture_io { store.record("vcan0", Frame.new(0x702, "\x05".b, false), {}, at: 30.0) }
refute store.snapshot[:nodes][2][:silent]
assert_match(/node 2 back after 20s/, err)
end
# Over a real SocketCAN interface when there is one:
# sudo ip link add dev vcan0 type vcan && sudo ip link set up vcan0
def test_frames_go_over_vcan0
skip "no vcan0" unless Socket.getifaddrs.any? { |i| i.name == "vcan0" }
store = Maptool::Can::Store.new
decoder = Maptool::Can::Decoder.new([{ "name" => "speed", "id" => "0x182", "type" => "u16", "scale" => 0.01 }])
received = Queue.new
reader = Thread.new { Maptool::Can.listen("vcan0", decoder: decoder, store: store, retry_delay: 0.1) { |values| received << values } }
sleep 0.2 until store.snapshot[:interfaces].dig("vcan0", :up)
sender = Maptool::Can.open("vcan0")
sender.write(Frame.new(0x182, [1234].pack("S<"), false).pack)
assert_in_delta 12.34, Timeout.timeout(2) { received.pop }["speed"]
ensure
reader&.kill
sender&.close
end
def test_the_recorder_runs_its_binary_until_stopped
Dir.mktmpdir do |dir|
binary = File.join(dir, "fake-recorder")
File.write(binary, "#!/bin/sh\necho \"$@\" > \"$3/args\"\ntrap 'exit 0' TERM\nwhile :; do sleep 0.1; done\n")
File.chmod(0o755, binary)
recorder = Maptool::Can::Recorder.new(File.join(dir, "rec"), %w[can0 vcan0], binary: binary, segment: 60)
recorder.start
assert recorder.running?
sleep 0.05 until File.exist?(File.join(dir, "rec", "args"))
recorder.stop
refute recorder.running?
assert_nil recorder.error
assert_equal "--segment 60 #{dir}/rec can0 vcan0\n", File.read(File.join(dir, "rec", "args"))
assert_raises(Errno::ENOENT) { Maptool::Can::Recorder.new(dir, [], binary: "/nonexistent").start }
end
end
def test_the_recorder_drops_segments_older_than_it_keeps
Dir.mktmpdir do |dir|
old, fresh = %w[20261201-100000.mf4 20261203-100000.mf4].map { |name| File.join(dir, name).tap { |p| File.write(p, "x") } }
File.utime(Time.now - 25 * 3600, Time.now - 25 * 3600, old)
File.write(File.join(dir, "notes.txt"), "kept: not a segment")
assert_equal ["20261203-100000.mf4"], Maptool::Can::Recorder.new(dir, [], keep: 24 * 3600).files.map { |f| f[:name] }
refute File.exist?(old)
assert File.exist?(fresh) && File.exist?(File.join(dir, "notes.txt"))
end
end
end
+143
View File
@@ -0,0 +1,143 @@
require_relative "test_helper"
require "tmpdir"
require "maptool/can_discovery"
class CanDiscoveryTest < Minitest::Test
Frame = Maptool::Can::Frame
# A node's SDO server over its OD ({[index, sub] => bytes}), expedited and
# segmented uploads, expedited downloads; `noise` answers first, as if for
# another SDO client.
class FakeNode
attr_reader :od
def initialize(node, od, noise: nil)
@node = node
@od = od
@queue = []
@noise = noise
end
def send(frame)
return unless frame.id == 0x600 + @node
@queue << Frame.new(0x580 + @node, @noise, false) if @noise
@noise = nil
cs = frame.data.getbyte(0)
index, sub = frame.data.byteslice(1, 3).unpack("S<C")
reply = case cs & 0xE0
when 0x40 then initiate(index, sub)
when 0x60 then segment(cs)
when 0x20 then (@od[[index, sub]] = frame.data.byteslice(4, 4 - ((cs >> 2) & 3)); [0x60, index, sub, 0].pack("CS<CL<"))
end
@queue << Frame.new(0x580 + @node, reply, false)
end
def receive(_timeout)
@queue.shift
end
private
def initiate(index, sub)
bytes = @od[[index, sub]] or return [0x80, index, sub, 0x06020000].pack("CS<CL<")
if bytes.bytesize <= 4
[0x43 | ((4 - bytes.bytesize) << 2), index, sub].pack("CS<C") + bytes.ljust(4, "\0")
else
@pending = bytes.dup
@toggle = 0
[0x41, index, sub, bytes.bytesize].pack("CS<CL<")
end
end
def segment(cs)
chunk = @pending.slice!(0, 7)
last = @pending.empty?
[((cs >> 4) & 1) << 4 | ((7 - chunk.bytesize) << 1) | (last ? 1 : 0)].pack("C") + chunk.ljust(7, "\0")
end
end
u32 = ->(v) { [v].pack("L<") }
f32 = ->(v) { [v].pack("e") }
# The GNSS node: TPDO2 0x3A1 lat/lon (entities 6, 7: sensor, REAL32),
# TPDO3 0x4A1 altitude (entity 8: sensor16, -500..9000 m) + satellites
# (entity 11: sensor8, 0..255).
GNSS_OD = {
[0x3002, 1] => u32.(0xCAFE), [0x1008, 0] => "XIAO STM32C5 2",
[0x1802, 1] => u32.(0x3A1), [0x1A02, 0] => "\x02".b, [0x1A02, 1] => u32.(0x20610120), [0x1A02, 2] => u32.(0x20710120),
[0x1803, 1] => u32.(0x4A1), [0x1A03, 0] => "\x02".b, [0x1A03, 1] => u32.(0x20810110), [0x1A03, 2] => u32.(0x20B10108),
[0x1804, 1] => u32.(0x80000000 | 0x221), # disabled
[0x2001, 6] => u32.(1), [0x2001, 7] => u32.(1), [0x2001, 8] => u32.(7), [0x2001, 11] => u32.(6),
[0x2060, 1] => "Latitude", [0x2070, 1] => "Longitude",
[0x2080, 1] => "Altitude", [0x2080, 3] => "m", [0x2080, 7] => f32.(-500.0), [0x2080, 8] => f32.(9000.0),
[0x20B0, 1] => "Satellites", [0x20B0, 7] => f32.(0.0), [0x20B0, 8] => f32.(255.0),
}.transform_values(&:b).freeze
def test_sdo_reads_expedited_and_segmented_and_skips_another_clients_answer
noise = [0x43, 0x3100, 2, 99].pack("CS<CL<") # can2mqtt's log poll answered
sdo = Maptool::Can::Sdo.new(FakeNode.new(0x21, GNSS_OD.dup, noise: noise))
assert_equal 0xCAFE, sdo.upload(0x21, 0x3002, 1).unpack1("L<")
assert_equal "XIAO STM32C5 2", sdo.upload(0x21, 0x1008, 0) # 14 bytes: 2 segments
error = assert_raises(Maptool::Can::Sdo::Abort) { sdo.upload(0x21, 0x9999, 0) }
assert_equal 0x06020000, error.code
node = FakeNode.new(0x21, {})
Maptool::Can::Sdo.new(node).download(0x21, 0x20E2, 1, "\x01")
assert_equal "\x01", node.od[[0x20E2, 1]]
end
def test_an_action_writes_its_bytes_and_rejects_bad_data
node = FakeNode.new(0x21, {})
action = Maptool::Can::Sdo::Action.parse("name" => "Level IMU", "node" => 33, "index" => "0x2022", "subindex" => 1, "data" => "01")
action.run(Maptool::Can::Sdo.new(node))
assert_equal "\x01".b, node.od[[0x2022, 1]]
assert_raises(ArgumentError) { Maptool::Can::Sdo::Action.parse("name" => "x", "node" => 1, "index" => 1, "data" => "0102030405") }
end
def test_a_node_described_decodes_its_own_tpdos
sdo = Maptool::Can::Sdo.new(FakeNode.new(0x21, GNSS_OD.dup))
description = Maptool::Can::Discovery.describe(sdo, 0x21, aliases: { "XIAO STM32C5 2.Latitude" => "gnss.lat" })
assert_equal [0xCAFE, "XIAO STM32C5 2"], description.values_at(:hash, :name)
names = description[:signals].map { |s| s["name"] }
assert_equal ["gnss.lat", "XIAO STM32C5 2.Longitude", "XIAO STM32C5 2.Altitude", "XIAO STM32C5 2.Satellites"], names
decoder = Maptool::Can::Decoder.new([])
decoder.set_node(0x21, description[:signals])
values = decoder.decode(Frame.new(0x3A1, [48.05, 17.36].pack("ee"), false))
assert_in_delta 48.05, values["gnss.lat"], 1e-5
raw = ((144.5 + 500) / 9500 * 65_534).round # the node's encoding
values = decoder.decode(Frame.new(0x4A1, [raw, 7].pack("S<C"), false))
assert_in_delta 144.5, values["XIAO STM32C5 2.Altitude"], 0.1
assert_in_delta 7.03, values["XIAO STM32C5 2.Satellites"], 0.01 # 255/254 per step, as the node encodes
assert_equal "m", decoder.units["XIAO STM32C5 2.Altitude"]
assert_empty decoder.decode(Frame.new(0x4A1, [65_535, 255].pack("S<C"), false)) # unknown
end
# A store that has heard the node, the description cached, read again only
# when the layout hash changes; a node without 0x3002 left alone.
def test_the_discoverer_caches_by_layout_hash
Dir.mktmpdir do |dir|
store = Maptool::Can::Store.new
store.record("vcan0", Frame.new(0x721, "\x05".b, false), {})
store.record("vcan0", Frame.new(0x705, "\x05".b, false), {}) # a foreign node
od = GNSS_OD.dup
node = FakeNode.new(0x21, od)
foreign = FakeNode.new(0x05, {})
both = Object.new
both.define_singleton_method(:send) { |f| node.send(f) || foreign.send(f) }
both.define_singleton_method(:receive) { |t| node.receive(t) || foreign.receive(t) }
decoder = Maptool::Can::Decoder.new([])
discoverer = Maptool::Can::Discoverer.new(store: store, decoder: decoder, cache_dir: dir, sdo: Maptool::Can::Sdo.new(both))
_, err = capture_io { discoverer.run_once(now: 0) }
assert_match(/node 33 \(XIAO STM32C5 2\): 4 signals/, err)
assert File.exist?(File.join(dir, "21.json"))
# a restart: from the cache, nothing read until it's checked again
decoder = Maptool::Can::Decoder.new([])
Maptool::Can::Discoverer.new(store: store, decoder: decoder, cache_dir: dir,
aliases: { "XIAO STM32C5 2.Altitude" => { "name" => "gnss.alt_ft", "scale" => 3.28084, "unit" => "ft" } })
raw = ((144.5 + 500) / 9500 * 65_534).round
assert_in_delta 474.1, decoder.decode(Frame.new(0x4A1, [raw, 7].pack("S<C"), false))["gnss.alt_ft"], 0.5
assert_equal "ft", decoder.units["gnss.alt_ft"]
end
end
end
+28
View File
@@ -0,0 +1,28 @@
require_relative "test_helper"
require "maptool/corridor"
class CorridorTest < Minitest::Test
C = Maptool::Corridor
# 30 km east along 48° N, as a vertex every ~0.75 km
LINE = (0..40).map { |i| [17.0 + i * 0.01, 48.0] }
def test_circles_cover_the_corridor_with_no_gap
circles = C.circles(LINE, 2.0)
assert_in_delta 2.5, circles.first[1], 1e-9
# every point 2 km off the line, all along it, inside a circle
(0..300).each do |i|
lon = 17.0 + i * 0.4 / 300
edge = [lon, 48.0 + 2.0 / C::KM_PER_DEG]
assert circles.any? { |center, r| C.km(center, edge) <= r + 1e-6 }, "gap at #{lon}"
end
assert_operator circles.size, :<=, (C.km(LINE.first, LINE.last) / 3.0).ceil + 2
end
def test_distance_to_the_line_and_thinning
assert_in_delta 1.0, C.distance_km([17.2, 48.0 + 1.0 / C::KM_PER_DEG], LINE), 1e-3
assert_in_delta C.km([16.99, 48.0], LINE.first), C.distance_km([16.99, 48.0], LINE), 1e-9 # past an end: to the end
thin = C.thin(LINE, 2.0)
assert_equal [LINE.first, LINE.last], [thin.first, thin.last]
assert thin.each_cons(2).to_a[0..-2].all? { |a, b| C.km(a, b) >= 2.0 }
end
end
+124
View File
@@ -0,0 +1,124 @@
require_relative "test_helper"
require_relative "../lib/maptool/gnss_sim"
class GnssSimTest < Minitest::Test
# A 1 km route north, 36 km/h limit for the first half, untagged after.
class FixedRoute < Maptool::GnssSim
def random_route(_position)
{ geometry: { coordinates: [[17.0, 48.0], [17.0, 48.0 + 1000.0 / 111_320]] },
properties: { speed_limits: [[0.0, 40], [0.5, nil]] } }
end
end
def test_drives_the_route_at_its_limits_and_ends_at_its_end
fixes = []
sim = FixedRoute.new("http://valhalla", sleep: ->(_s) {})
last = sim.drive([17.0, 48.0]) { |fix| fixes << fix }
assert_in_delta 36 / 3.6, fixes.first[:speed], 0.01 # 90 % of 40
assert_in_delta 45 / 3.6, fixes.last[:speed], 0.01 # 90 % of an untagged road's 50
assert_in_delta 48.0 + 1000.0 / 111_320, fixes.last[:lat], 1e-9
assert_equal [17.0, 48.0 + 1000.0 / 111_320], last
assert fixes.each_cons(2).all? { |a, b| b[:lat] >= a[:lat] } # never backwards
assert_in_delta (1000 / (36 / 3.6) / 2 + 500 / (45 / 3.6)) / Maptool::GnssSim::TICK_S, fixes.size, 3 # a fix every TICK_S
end
# A track replayed at its own pace: 100 m in 10 s (10 m/s), a stop of an
# hour cut to MAX_GAP_S, another 100 m in 20 s; ends at its end.
def test_replays_a_track_at_its_own_speed
fixes = []
step = 100.0 / 111_320
track = [[17.0, 48.0, 1000], [17.0, 48.0 + step, 1010], [17.0, 48.0 + step, 4610], [17.0, 48.0 + 2 * step, 4630]]
Maptool::GnssSim.new("http://valhalla", sleep: ->(_s) {}).replay(track) { |fix| fixes << fix }
assert_in_delta 10.0, fixes.first[:speed], 0.01
assert_in_delta 5.0, fixes.last[:speed], 0.01
assert_in_delta 48.0 + 2 * step, fixes.last[:lat], 1e-9
assert_in_delta (10 + Maptool::GnssSim::MAX_GAP_S + 20) / Maptool::GnssSim::TICK_S, fixes.size, 2
end
# Started with the trip's route: from its start along it, before any random trip.
def test_starts_along_a_given_route
fixes = Queue.new
sim = Maptool::GnssSim.new("http://valhalla", sleep: ->(_s) {}, router: ->(*) { raise Maptool::Routing::RouteError, "done" })
route = { geometry: { coordinates: [[18.0, 49.0], [18.0, 49.001]] }, properties: { speed_limits: [[0.0, 50]] } }
sim.start(route: route) { |fix| fixes << fix }
first = fixes.pop
assert_in_delta 49.0, first[:lat], 0.0001
assert_in_delta 18.0, first[:lon], 1e-9
ensure
sim&.stop
end
# Sped up: five times the ground per tick, the fixes' clock five times
# faster — the speed they report (and a recorded track's) stays real.
def test_speedup_covers_more_ground_on_a_faster_clock
times = ->(speedup) do
sim = FixedRoute.new("http://valhalla", sleep: ->(_s) {})
sim.speedup = speedup
fixes = []
sim.drive([17.0, 48.0]) { |fix| fixes << fix }
fixes
end
real, fast = times.(1), times.(5)
assert_in_delta real.size / 5.0, fast.size, 2
assert_in_delta real.last[:time] - real.first[:time], fast.last[:time] - fast.first[:time], 5 # the same simulated time
assert_equal real.first[:speed], fast.first[:speed]
sim = Maptool::GnssSim.new("http://valhalla")
sim.speedup = 7
assert_equal 1, sim.speedup # not one of SPEEDUPS
end
# A long route gets detours: a stretch replaced by the router's way through
# a point off to one side (here: straight there and back), the start and the
# end kept, the limits in order; a detour with no way keeps the route.
def test_a_route_gets_detours_off_to_the_side
asked = []
router = lambda do |_url, (a, via, b), _vehicle|
asked << via
raise Maptool::Routing::RouteError, "no way" if asked.size == 2
{ geometry: { coordinates: [a, via, b] }, properties: { speed_limits: [[0.0, 30]] } }
end
sim = Maptool::GnssSim.new("http://valhalla", random: Random.new(1), router: router)
line = [[17.0, 48.0], [17.3, 48.0]] # ~22 km east
route = sim.with_detours({ geometry: { coordinates: line }, properties: { speed_limits: [[0.0, 90]] } })
coords = route[:geometry][:coordinates]
assert_equal [line.first, line.last], [coords.first, coords.last]
assert_operator asked.size, :>=, 2
off = asked.map { |_lon, lat| (lat - 48.0).abs * 111_320 }
assert(off.all? { |m| m.between?(250, 850) }, "#{off} m off the route")
assert_includes coords, asked.first # the first detour driven through its point
refute_includes coords, asked[1] # the second had no way: the route as it was
starts = route[:properties][:speed_limits].map(&:first)
assert_equal starts.sort, starts
assert_includes route[:properties][:speed_limits].map(&:last), 30
end
# No road at the first random place: another one, inside the bbox.
class FirstPlaceAtSea < Maptool::GnssSim
attr_reader :tried
def random_route(position)
(@tried ||= []) << position
raise Maptool::Routing::RouteError, "no road" if @tried.size == 1
{ geometry: { coordinates: [position, position] }, properties: { distance_km: 5 } }
end
end
def test_a_random_start_is_inside_an_offline_country_with_a_road
sim = FirstPlaceAtSea.new("http://valhalla", random: Random.new(3))
position, route = sim.random_start([[17.0, 48.0, 18.0, 49.0]])
assert_equal 2, sim.tried.size
assert position[0].between?(17.0, 18.0) && position[1].between?(48.0, 49.0)
assert_equal position, route[:geometry][:coordinates].first
end
def test_a_route_under_a_km_is_another_try_and_none_at_all_an_error
lengths = [0.0, 0.2, 3.0]
router = ->(*) { { geometry: { coordinates: [[1, 2], [1, 3]] }, properties: { distance_km: lengths.shift } } }
sim = Maptool::GnssSim.new("http://valhalla", router: router)
assert_equal 3.0, sim.random_route([1, 2])[:properties][:distance_km]
lengths = [0.0] * 5
assert_raises(Maptool::Routing::RouteError) { sim.random_route([1, 2]) }
end
end
+28
View File
@@ -0,0 +1,28 @@
require_relative "test_helper"
require_relative "../lib/maptool/link_place"
class LinkPlaceTest < Minitest::Test
def test_coordinates_in_the_link
place = Maptool::LinkPlace.from_url("https://www.google.com/maps/place/Hallstatt/@47.5622,13.6493,15z/data=!3m1!4b1!4m6!3m5!1s0x0:0x0!8m2!3d47.5622!4d13.6493")
assert_equal({ name: "Hallstatt", lat: 47.5622, lng: 13.6493, url: place[:url] }, place)
assert_equal [48.15, 17.11], Maptool::LinkPlace.from_url("https://maps.google.com/?q=48.15,17.11").values_at(:lat, :lng)
assert_equal [48.15, 17.11], Maptool::LinkPlace.from_url("geo:48.15,17.11").values_at(:lat, :lng)
assert_nil Maptool::LinkPlace.from_url("https://park4night.com/en/place/313577")
end
def test_coordinates_in_the_page
meta = %(<title>x</title><meta property="og:title" content="Stellplatz &amp; See"><meta property="place:location:latitude" content="47.7395"><meta property="place:location:longitude" content="13.4482">)
assert_equal({ name: "Stellplatz & See", lat: 47.7395, lng: 13.4482 }, Maptool::LinkPlace.from_html(meta))
ld = %(<title> Camp </title><script type="application/ld+json">{"geo":{"latitude": 46.1, "longitude": 14.2}}</script>)
assert_equal({ name: "Camp", lat: 46.1, lng: 14.2 }, Maptool::LinkPlace.from_html(ld))
link = %(<a href="https://www.google.com/maps?daddr=45.5,13.7">go</a>)
assert_equal [45.5, 13.7], Maptool::LinkPlace.from_html(link).values_at(:lat, :lng)
assert_nil Maptool::LinkPlace.from_html("<p>nothing</p>")
end
def test_no_private_addresses
assert_raises(Maptool::LinkPlace::Error) { Maptool::LinkPlace.fetch("http://127.0.0.1/") }
assert_raises(Maptool::LinkPlace::Error) { Maptool::LinkPlace.fetch("http://192.168.1.1/") }
assert_raises(Maptool::LinkPlace::Error) { Maptool::LinkPlace.fetch("file:///etc/passwd") }
end
end
+5
View File
@@ -120,4 +120,9 @@ class OverpassPoisTest < Minitest::Test
assert_includes query, %(["amenity"="drinking_water"])
assert_includes query, %(["natural"="spring"])
end
def test_build_query_along_a_line_uses_around
query = Maptool::OverpassPois.build_query(nil, around: [5000.0, [[17.1, 48.1], [17.2, 48.15]]])
assert_includes query, %(node["amenity"="drinking_water"](around:5000,48.1,17.1,48.15,17.2);)
end
end
+21 -3
View File
@@ -18,7 +18,7 @@ class PluginsTest < Minitest::Test
end
def test_list_finds_plugins_by_their_manifest
assert_equal [{ "name" => "hello", "label" => "Hello" }], Maptool::Plugins.list(@dir)
assert_equal [{ "name" => "hello", "label" => "Hello", "route" => false, "settings" => [] }], Maptool::Plugins.list(@dir)
end
def test_list_is_empty_for_a_directory_with_no_plugins
@@ -76,7 +76,7 @@ class PluginsTest < Minitest::Test
plugins = Maptool::Plugins.list([@dir, other_dir])
assert_equal [{ "name" => "hello", "label" => "Hello" }, { "name" => "private", "label" => "Private" }], plugins
assert_equal [{ "name" => "hello", "label" => "Hello", "route" => false, "settings" => [] }, { "name" => "private", "label" => "Private", "route" => false, "settings" => [] }], plugins
ensure
FileUtils.remove_entry(other_dir)
end
@@ -88,7 +88,7 @@ class PluginsTest < Minitest::Test
plugins = Maptool::Plugins.list([@dir, other_dir])
assert_equal [{ "name" => "hello", "label" => "Hello" }], plugins
assert_equal [{ "name" => "hello", "label" => "Hello", "route" => false, "settings" => [] }], plugins
ensure
FileUtils.remove_entry(other_dir)
end
@@ -97,4 +97,22 @@ class PluginsTest < Minitest::Test
result = Maptool::Plugins.run([Dir.mktmpdir, @dir], "hello", [1, 2, 3, 4])
assert_equal({ "type" => "FeatureCollection", "features" => [] }, result)
end
# A route and settings: --route/--corridor-km and the settings as env vars,
# only the keys the plugin.json declares saved.
def test_route_args_and_saved_settings_reach_the_command
File.write(File.join(@plugin_dir, "plugin.json"), JSON.generate(label: "Hello", command: "./run.sh", route: true,
settings: [{ key: "TOKEN", label: "Token" }, { key: "bad key" }]))
File.write(File.join(@plugin_dir, "run.sh"), "#!/bin/sh\necho \"{\\\"type\\\":\\\"FeatureCollection\\\",\\\"features\\\":[],\\\"args\\\":\\\"$5 $6\\\",\\\"token\\\":\\\"$TOKEN\\\"}\"\n")
assert_equal [{ "name" => "hello", "label" => "Hello", "route" => true, "settings" => [{ "key" => "TOKEN", "label" => "Token" }] }], Maptool::Plugins.list(@dir)
path = File.join(@dir, "settings.json")
assert_equal ["TOKEN"], Maptool::Plugins.save_settings(path, @dir, "hello", { "TOKEN" => " abc ", "OTHER" => "x" })
assert_equal 0o600, File.stat(path).mode & 0o777
env = Maptool::Plugins.saved_settings(path)["hello"]
result = Maptool::Plugins.run(@dir, "hello", [1, 2, 3, 4], route: "/tmp/r.geojson", corridor_km: 5.0, env: env)
assert_equal "--route=/tmp/r.geojson --corridor-km=5.0", result["args"]
assert_equal "abc", result["token"]
assert_empty Maptool::Plugins.save_settings(path, @dir, "hello", { "TOKEN" => "" })
end
end
+46 -6
View File
@@ -113,6 +113,20 @@ class RoutingTest < Minitest::Test
assert_raises(ArgumentError) { Maptool::Routing.save_vehicles(@data, []) }
end
def test_a_car_keeps_its_fuel_euro_class_stickers_and_vignettes
Maptool::Routing.save_vehicles(@data, [{ "id" => "van", "name" => "Van", "fuel" => "diesel", "euro" => "6d", "stickers" => " DE green ",
"wheelbase" => "3.45", "track" => 1.75, "ramps" => "9, 3 6,5",
"vignettes" => [{ "country" => "sk", "until" => "2027-01-31" }, { "country" => "AT", "kind" => "toll" }] },
{ "id" => "b", "name" => "B", "type" => "bicycle", "fuel" => "diesel" }])
assert_equal({ id: "van", name: "Van", type: "car", fuel: "diesel", euro: "6d", stickers: "DE green", wheelbase: 3.45, track: 1.75, ramps: "3 6.5 9",
vignettes: [{ country: "SK", kind: "vignette", until: "2027-01-31" }, { country: "AT", kind: "toll" }] }, Maptool::Routing.vehicle(@data, "van"))
assert_equal({ id: "b", name: "B", type: "bicycle" }, Maptool::Routing.vehicle(@data, "b")) # a bike burns nothing
[{ "fuel" => "coal" }, { "euro" => "7" }, { "vignettes" => [{ "country" => "Slovakia" }] }, { "vignettes" => [{ "country" => "SK", "until" => "soon" }] },
{ "vignettes" => [{ "country" => "SK", "kind" => "sticker" }] }, { "ramps" => "3 60" }, { "track" => "5" }].each do |bad|
assert_raises(ArgumentError) { Maptool::Routing.save_vehicles(@data, [{ "id" => "x", "name" => "X", **bad }]) }
end
end
def test_the_old_single_vehicle_becomes_the_camper
File.write(File.join(@data, "vehicle.json"), JSON.generate(height: 3.3, width: 2.3, length: 7, weight: 3.5))
assert_equal 3.3, Maptool::Routing.vehicle(@data, "camper")[:height]
@@ -126,11 +140,13 @@ class RoutingTest < Minitest::Test
def test_route_picks_the_costing_by_weight_and_returns_a_line
shape = "wdg|xA{ubdQc@w@"
reply = JSON.generate(trip: { summary: { length: 1.5, time: 90 },
legs: [{ shape: shape, maneuvers: [{ instruction: "Drive north.", length: 1.5 }] }] })
legs: [{ shape: shape, summary: { length: 1.5, time: 90 }, maneuvers: [{ instruction: "Drive north.", length: 1.5, type: 2, street_names: ["Main"], verbal_pre_transition_instruction: "Drive north on Main." }] }] })
# The per-country lookup failing (400) leaves the route as it is.
request = serve_once("HTTP/1.1 200 OK\r\nContent-Length: #{reply.bytesize}\r\n\r\n#{reply}", "HTTP/1.1 400 Bad Request\r\nContent-Length: 2\r\n\r\n{}") do |url|
route = Maptool::Routing.route(url, [[9.52, 47.14], [9.53, 47.15]], Maptool::Routing::DEFAULT_VEHICLES[1])
assert_equal [2, "auto", "Drive north."], [route[:geometry][:coordinates].size, route[:properties][:costing], route[:properties][:maneuvers][0][:text]]
assert_equal({ text: "Drive north.", km: 1.5, type: 2, street: "Main", say: "Drive north on Main." }, route[:properties][:maneuvers][0])
assert_equal [[1.5], [90]], route[:properties].values_at(:legs_km, :legs_s) # each leg's km and time, for the stops
end
assert_includes request, %("costing_options":{"auto":{"height":3.0,"width":2.3}})
@@ -145,18 +161,42 @@ class RoutingTest < Minitest::Test
def test_a_route_sums_motorway_and_toll_km_per_country_and_can_avoid_tolls
route = JSON.generate(trip: { summary: { length: 3, time: 90 }, legs: [{ shape: "wdg|xA{ubdQc@w@", maneuvers: [] }] })
attributes = JSON.generate(admins: [{ country_code: "AT" }, { country_code: "SK" }],
edges: [{ length: 1.0, road_class: "motorway", toll: false, end_node: { admin_index: 0 } },
{ length: 0.5, road_class: "primary", toll: false, end_node: { admin_index: 0 } },
{ length: 1.5, road_class: "motorway", toll: true, end_node: { admin_index: 1 } }])
edges: [{ length: 1.0, road_class: "motorway", toll: false, speed_limit: 130, end_shape_index: 0, end_node: { admin_index: 0 } },
{ length: 0.5, road_class: "primary", toll: false, speed_limit: 0, end_shape_index: 1, end_node: { admin_index: 0, traffic_signal: true } },
{ length: 1.5, road_class: "motorway", toll: true, speed_limit: 130, end_shape_index: 1, end_node: { admin_index: 1 } }])
ok = ->(body) { "HTTP/1.1 200 OK\r\nContent-Length: #{body.bytesize}\r\n\r\n#{body}" }
request = serve_once(ok.(route), ok.(attributes)) do |url|
countries = Maptool::Routing.route(url, [[1, 2], [3, 4]], { id: "car" }, { "tolls" => true })[:properties][:countries]
assert_equal [{ code: "AT", km: 1.5, motorway_km: 1.0, toll_km: 0.0 }, { code: "SK", km: 1.5, motorway_km: 1.5, toll_km: 1.5 }], countries
properties = Maptool::Routing.route(url, [[1, 2], [3, 4]], { id: "car" }, { "tolls" => true })[:properties]
assert_equal [{ code: "AT", km: 1.5, motorway_km: 1.0, toll_km: 0.0 }, { code: "SK", km: 1.5, motorway_km: 1.5, toll_km: 1.5 }], properties[:countries]
assert_equal [[0.0, 130], [1.0, nil], [1.5, 130]], properties[:speed_limits]
assert_equal [[9.521034, 47.140974, 1.5]], properties[:signals]
assert_equal [[0.0, "motorway", "AT"], [1.0, "primary", "AT"], [1.5, "motorway", "SK"]], properties[:roads]
end
assert_includes request, %("costing_options":{"auto":{"use_tolls":0.0}})
assert_includes request, "/trace_attributes"
end
def test_the_road_driven_is_the_last_matched_edge
reply = JSON.generate(edges: [{ names: ["A"], road_class: "primary", speed_limit: 90 }, { names: ["B"], road_class: "motorway", speed_limit: "unlimited", surface: "paved_smooth" }])
no_route = "HTTP/1.1 400 Bad Request\r\nContent-Length: 2\r\n\r\n{}" # the signals ahead: none
request = serve_once("HTTP/1.1 200 OK\r\nContent-Length: #{reply.bytesize}\r\n\r\n#{reply}", no_route) do |url|
assert_equal({ name: "B", road_class: "motorway", speed_limit: "unlimited", surface: "paved_smooth" }, Maptool::Routing.road(url, [[17.1, 48.1], [17.2, 48.2]]))
end
assert_includes request, %("shape_match":"map_snap")
assert_raises(Maptool::Routing::RouteError) { Maptool::Routing.road("http://x", [[17.1, 48.1]]) }
end
def test_the_road_gives_the_signals_ahead_from_a_route_straight_on
http = ->(body) { "HTTP/1.1 200 OK\r\nContent-Length: #{body.bytesize}\r\n\r\n#{body}" }
road = JSON.generate(edges: [{ names: ["B"], road_class: "primary" }])
route = JSON.generate(trip: { legs: [{ shape: "wdg|xA{ubdQc@w@" }] })
along = JSON.generate(admins: [{ country_code: "SK" }], edges: [{ length: 0.4, end_shape_index: 1, end_node: { traffic_signal: true, admin_index: 0 } }])
request = serve_once(http[road], http[route], http[along]) do |url|
assert_equal [0.4], Maptool::Routing.road(url, [[17.1, 48.1], [17.1, 48.2]])[:signals].map(&:last)
end
assert_includes request, %("heading":0,"heading_tolerance":45)
end
def test_bicycle_and_foot_use_their_own_costing_without_the_country_lookup
reply = JSON.generate(trip: { summary: { length: 1.5, time: 90 }, legs: [{ shape: "wdg|xA{ubdQc@w@", maneuvers: [] }] })
request = serve_once("HTTP/1.1 200 OK\r\nContent-Length: #{reply.bytesize}\r\n\r\n#{reply}") do |url|
+7
View File
@@ -55,6 +55,13 @@ class SearchTest < Minitest::Test
assert_empty search(" ")
end
def test_blank_query_with_a_center_lists_the_library_nearest_first
results = search("", center: [48.72, 21.26])
assert_equal "Kemp Košice", results.first[:name]
assert(results.all? { |r| r[:source] == "layers" })
assert_empty search("", center: [48.72, 21.26], sources: ["hiking_trails"])
end
private
def search(text, **opts)
+83
View File
@@ -0,0 +1,83 @@
require_relative "test_helper"
require "maptool/library"
require "stringio"
# Two servers' libraries (home, car) exchanging Library#sync_changes /
# #apply_sync the way Maptool::Sync does over HTTP.
class SyncTest < Minitest::Test
def setup
@dir = Dir.mktmpdir
@home = library("home")
@car = library("car")
end
def teardown
FileUtils.remove_entry(@dir)
end
def test_changes_flow_both_ways_with_source_files_and_stop_echoing
@home.import(folder: "Rides", filename: "ride.gpx", io: File.open(fixture_path("sample.gpx")))
pull(@car, from: @home)
assert_equal ["Rides"], @car.tree["children"].map { |c| c["name"] }
track = @car.tree["children"][0]["children"].find { |c| c["path"].start_with?("item:") }
assert File.exist?(@car.original(track["path"])), "the upload's source file came along"
@car.create_folder("Car notes")
pull(@home, from: @car)
assert_equal ["Car notes", "Rides"], @home.tree["children"].map { |c| c["name"] }.sort
# Each side's echo of what it just took ties and changes nothing more.
assert_equal 0, pull(@car, from: @home)
assert_equal 0, pull(@home, from: @car)
end
def test_the_later_edit_wins_and_a_delete_carries_over
@home.create_folder("Trip")
pull(@car, from: @home)
sleep 1.1 # updated_at has second resolution
@car.rename_folder("Trip", "Trip 2026")
pull(@home, from: @car)
assert_equal ["Trip 2026"], @home.tree["children"].map { |c| c["name"] }
stale = @home.sync_changes(0)
stale["folders"].each { |f| f["updated_at"] = "2000-01-01T00:00:00Z"; f["name"] = "Old" }
@car.apply_sync(stale)
assert_equal ["Trip 2026"], @car.tree["children"].map { |c| c["name"] }, "an older version doesn't overwrite"
end
def test_pages_until_caught_up
3.times { |i| @home.create_folder("F#{i}") }
since = 0
pages = 0
loop do
changes = @home.sync_changes(since, limit: 2)
@car.apply_sync(changes)
pages += 1
since = changes["next"]
break if since >= changes["rev"]
end
assert_equal %w[F0 F1 F2], @car.tree["children"].map { |c| c["name"] }
assert_operator pages, :>, 1
end
def test_a_source_path_from_the_other_server_stays_inside_sources
row = { "id" => "x", "type" => "track", "source_path" => "../../etc/passwd", "updated_at" => "2030-01-01T00:00:00Z", "properties" => "{}", "created_at" => "2030-01-01T00:00:00Z" }
assert_raises(Maptool::Library::InvalidValue) { @car.apply_sync("items" => [row]) }
end
private
def library(name)
Maptool::Library.new(File.join(@dir, name, "library.sqlite"), gpx_store: Maptool::GpxStore.new(File.join(@dir, name, "gpx")),
sources_dir: File.join(@dir, name, "sources"))
end
# What Sync#pull does, without HTTP (since 0 is fine: idempotent).
# Returns how many rows `target` took.
def pull(target, from:)
before = target.sync_changes(0)["rev"]
missing = target.apply_sync(from.sync_changes(0))
missing.each { |item| target.store_source(item, File.binread(from.item_source(item["id"]))) }
target.sync_changes(before).values_at("folders", "items").sum(&:size)
end
end
+126
View File
@@ -0,0 +1,126 @@
require_relative "test_helper"
require "tmpdir"
require "timeout"
require_relative "../lib/maptool/trip"
class TripTest < Minitest::Test
def test_an_update_routes_bumps_the_version_and_survives_a_restart
Dir.mktmpdir do |dir|
path = File.join(dir, "trip.json")
store = Maptool::TripStore.new(path)
assert_equal 0, store.get[:version]
points = [{ lngLat: [17.1, 48.1], name: "Home" }, { lngLat: [17.2, 48.2] }]
calls = []
router = ->(locations, vehicle, avoid) { calls << [locations, vehicle, avoid]; { type: "Feature", km: 1 } }
trip = store.update(points: points, vehicle: "camper", avoid: { tolls: true }, editing: nil, &router)
assert_equal [1, { type: "Feature", km: 1 }], trip.values_at(:version, :route)
assert_equal [[[[17.1, 48.1], [17.2, 48.2]], "camper", { tolls: true }]], calls
# only a name/nav changed: no routing, the route stays
points[1] = { lngLat: [17.2, 48.2], name: "Camp", nav: true }
trip = store.update(points: points, vehicle: "camper", avoid: { tolls: true }, editing: nil, &router)
assert_equal [2, 1, "Camp"], [trip[:version], calls.size, trip[:points][1][:name]]
reloaded = Maptool::TripStore.new(path).get
assert_equal [2, { type: "Feature", km: 1 }, "Camp"], [reloaded[:version], reloaded[:route], reloaded[:points][1][:name]]
end
end
def test_the_itinerary_keeps_nights_stays_notes_and_the_start_without_routing_again
Dir.mktmpdir do |dir|
store = Maptool::TripStore.new(File.join(dir, "trip.json"))
calls = 0
router = ->(*) { calls += 1; { type: "Feature" } }
points = [{ lngLat: [17.1, 48.1] }, { lngLat: [17.2, 48.2] }]
store.update(points: points, vehicle: nil, avoid: {}, editing: nil, &router)
points[1] = { lngLat: [17.2, 48.2], night: true, stay: "90", note: " call ahead ", type: "campground", day_note: "" }
points[0] = { lngLat: [17.1, 48.1], day_note: "leave early" }
trip = store.update(points: points, vehicle: nil, avoid: {}, editing: nil, name: "Alps", start: "2026-12-12T08:00", day_start: "09:30", note: " chains ", &router)
assert_equal 1, calls # an itinerary change isn't a route change
assert_equal({ lngLat: [17.2, 48.2], name: nil, nav: false, passed: false, night: true, stay: 90, note: "call ahead", type: "campground" }.compact, trip[:points][1])
assert_equal "leave early", trip[:points][0][:day_note]
assert_equal ["Alps", "2026-12-12T08:00", "09:30", "chains"], trip.values_at(:name, :start, :day_start, :note)
assert_raises(ArgumentError) { store.update(points: [{ lngLat: [1, 2], type: "<b>" }], vehicle: nil, avoid: {}, editing: nil, &router) }
assert_raises(ArgumentError) { store.update(points: [{ lngLat: [1, 2], cost: "-1" }], vehicle: nil, avoid: {}, editing: nil, &router) }
trip = store.update(points: [{ lngLat: [1, 2], cost: "32", paid: "" }], vehicle: nil, avoid: {}, editing: nil, budget: "250", fuel_price: "1.619", &router)
assert_equal [32.0, nil, 250.0, 1.62], [trip[:points][0][:cost], trip[:points][0][:paid], trip[:budget], trip[:fuel_price]]
# a parking spot: the route goes there instead of the place
seen = nil
points[1] = points[1].merge(park: { lngLat: [17.21, 48.19], name: "P2" })
trip = store.update(points: points, vehicle: nil, avoid: {}, editing: nil) { |locations, *| seen = locations; { type: "Feature" } }
assert_equal [[17.1, 48.1], [17.21, 48.19]], seen
assert_equal({ lngLat: [17.21, 48.19], name: "P2" }, trip[:points][1][:park])
assert_raises(ArgumentError) { store.update(points: [{ lngLat: [1, 2], stay: "-5" }], vehicle: nil, avoid: {}, editing: nil, &router) }
assert_raises(ArgumentError) { store.update(points: points, vehicle: nil, avoid: {}, editing: nil, start: "tomorrow", &router) }
end
end
# A day with avoids of its own: its legs routed apart, joined into one route.
def test_a_days_own_avoids_route_it_apart
points = [{ lngLat: [0, 0] }, { lngLat: [1, 0], night: true }, { lngLat: [2, 0], avoid: { highways: true } }, { lngLat: [3, 0] }]
assert_equal [[[[0, 0], [1, 0]], { tolls: true }], [[[1, 0], [2, 0], [3, 0]], { highways: true }]], Maptool::TripStore.pieces(points, { tolls: true })
assert_equal [[[[0, 0], [1, 0], [2, 0], [3, 0]], {}]], Maptool::TripStore.pieces(points.map { |p| p.except(:avoid) }, {})
part = ->(from, to) { { type: "Feature", geometry: { coordinates: [[from, 0], [to, 0]] },
properties: { distance_km: 10.0, time_s: 600, legs_km: [10.0], legs_s: [600], maneuvers: [{ km: 10 }],
roads: [[0.0, "motorway", "AT"]], signals: [[from, 0, 5.0]], countries: [{ code: "AT", km: 10.0, motorway_km: 10.0, toll_km: 0.0 }] } } }
route = Maptool::Routing.merge([part.(0, 1), part.(1, 2)])
assert_equal [[0, 0], [1, 0], [2, 0]], route[:geometry][:coordinates]
assert_equal [20.0, 1200, [10.0, 10.0]], route[:properties].values_at(:distance_km, :time_s, :legs_km)
assert_equal [[0.0, "motorway", "AT"], [10.0, "motorway", "AT"]], route[:properties][:roads]
assert_equal [[0, 0, 5.0], [1, 0, 15.0]], route[:properties][:signals]
assert_equal [{ code: "AT", km: 20.0, motorway_km: 20.0, toll_km: 0.0 }], route[:properties][:countries]
end
# Off the route while driving for 3 fixes: routed again from the position
# to the points not reached yet (the first via passed: dropped).
def test_following_reroutes_from_the_position_off_the_route
Dir.mktmpdir do |dir|
store = Maptool::TripStore.new(File.join(dir, "trip.json"))
line = { geometry: { coordinates: [[17.0, 48.0], [17.1, 48.0], [17.2, 48.0]] }, properties: { legs_km: [7.44, 7.44] } }
points = [{ lngLat: [17.0, 48.0] }, { lngLat: [17.1, 48.0] }, { lngLat: [17.2, 48.0] }]
calls = []
router = ->(locations, _vehicle, _avoid) { calls << locations; line }
store.update(points: points, vehicle: nil, avoid: {}, editing: nil, &router)
calls.clear
store.follow([17.15, 48.0], speed: 20, now: 0, &router) # on it, past the via
3.times { |i| store.follow([17.15, 48.01], speed: 20, now: i + 1, &router) } # ~1.1 km off
Timeout.timeout(5) { sleep 0.05 until store.get[:version] == 2 }
assert_equal [[[17.15, 48.01], [17.2, 48.0]]], calls
# the start and the via reached: kept, marked passed; the detour starts here
assert_equal [[true, nil], [true, nil], [false, "My position"], [false, nil]], store.get[:points].map { |p| p.values_at(:passed, :name) }
store.follow([17.15, 48.02], speed: 20, now: 5, &router) # within REROUTE_EVERY_S: nothing
assert_equal 1, calls.size
end
end
# A passed point stays in the trip, not in the route; marking one passed
# routes again (fewer locations), only renaming it doesn't.
def test_passed_points_are_kept_but_not_routed
Dir.mktmpdir do |dir|
store = Maptool::TripStore.new(File.join(dir, "trip.json"))
calls = []
router = ->(locations, *) { calls << locations; :route }
points = [{ lngLat: [1, 1], passed: true }, { lngLat: [2, 2] }, { lngLat: [3, 3] }]
trip = store.update(points: points, vehicle: nil, avoid: {}, editing: nil, &router)
assert_equal [[[2.0, 2.0], [3.0, 3.0]]], calls
assert_equal [true, false, false], trip[:points].map { |p| p[:passed] }
points[0] = points[0].merge(name: "Missed it")
store.update(points: points, vehicle: nil, avoid: {}, editing: nil, &router)
assert_equal 1, calls.size
end
end
def test_a_routing_error_is_kept_with_the_points_and_tried_again_next_time
Dir.mktmpdir do |dir|
store = Maptool::TripStore.new(File.join(dir, "trip.json"))
points = [{ lngLat: [1, 2] }, { lngLat: [3, 4] }]
trip = store.update(points: points, vehicle: nil, avoid: {}, editing: nil) { raise Maptool::Routing::RouteError, "no route" }
assert_equal [nil, "no route", 2], [trip[:route], trip[:error], trip[:points].size]
trip = store.update(points: points, vehicle: nil, avoid: {}, editing: nil) { :routed }
assert_equal [:routed, nil], trip.values_at(:route, :error)
end
end
end
+43
View File
@@ -0,0 +1,43 @@
require_relative "test_helper"
require "maptool/trip_days"
class TripDaysTest < Minitest::Test
D = Maptool::TripDays
# A drive: a point a minute from `start` (local time), `n` of them, going north.
def drive(start, n, lat0 = 48.0)
t0 = Time.new(*start).to_f
(0...n).map { |i| [17.0, lat0 + i * 0.01, 100.0 + i, t0 + i * 60] }
end
def test_a_night_stood_cuts_a_day_and_a_night_drive_cuts_at_three
points = drive([2026, 12, 1, 18, 0], 60) + drive([2026, 12, 2, 8, 0], 30, 49.0) # stood 13 h
assert_equal [[60, "auto"]], D.cuts(points)
night = drive([2026, 12, 1, 23, 0], 300) # through the night, no stop
assert_equal [[240, "night"]], D.cuts(night) # 23:00 + 240 min = 03:00
end
def test_cuts_by_hand_and_joined
points = drive([2026, 12, 1, 10, 0], 60) + drive([2026, 12, 1, 20, 0], 10, 49.0)
hand = points[30][3] - 20 # between two points: the day starts at the next one
cuts = D.cuts(points, hand: [hand])
assert_equal [[30, "hand"], [60, "auto"]], cuts
assert_equal [[30, "hand"]], D.cuts(points, hand: [hand], joined: [points[60][3]])
days = D.days(points, cuts)
assert_equal [1, 2, 3], days.map { |d| d[:index] }
assert_equal [0, 30, 60], days.map { |d| d[:from] }
assert_equal "auto", days[1][:cut][:kind]
assert_equal 9 * 3600 + 60, days[1][:cut][:stood_s] # from 10:59 to 20:00
assert_in_delta 29 * 60, days[0][:driving_s], 1
assert_nil days.last[:cut]
end
def test_gpx_has_a_track_per_piece_with_times_and_pauses
points = drive([2026, 12, 1, 10, 0], 3) + drive([2026, 12, 1, 11, 0], 3, 48.1)
gpx = D.gpx([["Day 1", points.first(3)], ["Day 2", points.last(3)]], D.pauses(points))
assert_equal 2, gpx.scan("<trk>").size
assert_includes gpx, "<time>#{Time.at(points[0][3]).utc.iso8601}</time>"
assert_includes gpx, "Stood 58 min"
end
end
+91
View File
@@ -0,0 +1,91 @@
require_relative "test_helper"
require "tmpdir"
require "maptool/library"
require "maptool/gpx_store"
require "maptool/trip_log"
class TripLogTest < Minitest::Test
def library(dir)
Maptool::Library.new(File.join(dir, "library.sqlite"), gpx_store: Maptool::GpxStore.new(File.join(dir, "gpx")), sources_dir: File.join(dir, "sources"))
end
def names(library)
library.nodes.flat_map { |label, _key, _stamp, read| [label, *JSON.parse(read.call)["features"].map { |f| f.dig("properties", "name") }] }.compact.join(" ")
end
# Start makes the folder with the plan and its named stops; fixes 10 m
# apart become the car's track; stop builds it into the library.
def test_a_trip_records_into_its_folder
Dir.mktmpdir do |dir|
lib = library(dir)
log = Maptool::TripLog.new(File.join(dir, "trip_log"), library: lib)
plan = { geometry: { type: "LineString", coordinates: [[17.0, 48.0], [17.1, 48.0]] }, properties: { distance_km: 7.4, time_s: 600 } }
folder = log.start("Tatry", plan: plan, stops: [{ lngLat: [17.0, 48.0], name: "My position" }, { lngLat: [17.1, 48.0], name: "Camp" }], now: Time.utc(2026, 12, 1, 8))
assert_equal "Trips/2026-12-01 Tatry", folder
assert_raises(ArgumentError) { log.start("again") }
log.record(17.0, 48.0, 150, 1000)
log.record(17.00001, 48.0, 150, 1001) # < 10 m: skipped
log.record(17.001, 48.0, 151, 1002)
log.record(17.002, 48.0, 152, 1100)
assert_equal 3, log.status[:points]
assert_equal [[17.001, 48.0], [17.002, 48.0]], log.status(since: 1)[:coordinates]
assert_equal folder, log.stop
refute log.active?
all = names(lib)
%w[Camp Plan].each { |name| assert_includes all, name }
assert_includes all, "Car 2026-12-01"
refute_includes all, "My position"
assert(lib.nodes.all? { |label, *| label.include?("2026-12-01 Tatry") }) # all in the trip's folder
end
end
# A crash: the server restarts with the journal as it was — a torn last
# line included — and the trip goes on from there, into the same track.
def test_a_restart_picks_the_trip_up_from_its_journal
Dir.mktmpdir do |dir|
lib = library(dir)
log_dir = File.join(dir, "trip_log")
log = Maptool::TripLog.new(log_dir, library: lib)
log.start("Crash", now: Time.utc(2026, 12, 1, 8))
log.record(17.0, 48.0, nil, 1000)
log.record(17.001, 48.0, nil, 1010)
log.send(:sync) # as the FSYNC_EVERY_S timer does; what's after it is lost in a crash
journal = Dir[File.join(log_dir, "*.ndjson")].first
File.open(journal, "a") { |f| f.write("[17.00") } # the power cut, mid-line
again = Maptool::TripLog.new(log_dir, library: lib)
assert again.active?
assert_equal [2, "Trips/2026-12-01 Crash"], again.status.values_at(:points, :folder)
again.record(17.002, 48.0, nil, 1020)
again.stop
assert_equal 3, File.readlines(journal).count { |l| l.start_with?("[") && (JSON.parse(l) rescue nil) } # the torn line alone lost
assert_equal 1, lib.nodes.count { |label, *| label.include?("Car 2026-12-01") } # one track, not two
refute Maptool::TripLog.new(log_dir, library: lib).active? # ended stays ended
end
end
# The days' cuts by hand and the joins go into the journal — while it
# runs and after it ended — and a restart doesn't take them for a trip.
def test_cuts_and_joins_are_journaled_running_or_ended
Dir.mktmpdir do |dir|
log = Maptool::TripLog.new(File.join(dir, "trip_log"), library: library(dir))
assert_nil log.recording
log.start("Days", now: Time.utc(2026, 12, 1, 8))
log.record(17.0, 48.0, nil, 1000)
log.record(17.001, 48.0, nil, 1010)
log.mark(:cut, 1005)
rec = log.recording
assert rec[:active]
assert_equal [[1005.0], 2], [rec[:hand], rec[:points].size]
log.stop
log.mark(:join, 1010)
rec = log.recording
refute rec[:active]
assert_equal [[1005.0], [1010.0], "Trips/2026-12-01 Days"], rec.values_at(:hand, :joined, :folder)
refute Maptool::TripLog.new(File.join(dir, "trip_log"), library: library(dir)).active?
assert_raises(ArgumentError) { log.mark(:other, 1) }
end
end
end
+34
View File
@@ -0,0 +1,34 @@
require_relative "test_helper"
require "tmpdir"
require_relative "../lib/maptool/updater"
class UpdaterTest < Minitest::Test
def setup
Maptool::Updater.reset!
end
def test_latest_is_mains_commit_and_its_ci_state_cached_until_checked_again
calls = []
fetch = lambda do |url|
calls << url
url.end_with?("/branches/main") ? { "commit" => { "id" => "a" * 40 } } : { "state" => "success" }
end
assert_equal({ sha: "a" * 40, ci: "success" }, Maptool::Updater.latest("https://git", "r/m", fetch: fetch))
assert_equal ["https://git/api/v1/repos/r/m/branches/main", "https://git/api/v1/repos/r/m/commits/#{'a' * 40}/status"], calls
Maptool::Updater.latest("https://git", "r/m", fetch: fetch)
assert_equal 2, calls.size # cached
end
def test_gitea_out_of_reach_is_no_answer_not_an_error
assert_nil Maptool::Updater.latest("https://git", "r/m", fetch: ->(_) { raise SocketError })
end
def test_a_request_holds_a_full_commit_only
Dir.mktmpdir do |dir|
assert_raises(ArgumentError) { Maptool::Updater.request(dir, "abc; rm -rf /") }
Maptool::Updater.request(dir, "b" * 40)
assert_equal "b" * 40, JSON.parse(File.read(File.join(dir, "update", "request.json")))["sha"]
assert_nil Maptool::Updater.status(dir)
end
end
end
+14
View File
@@ -0,0 +1,14 @@
<%# The debug pages' switcher, on top of each (status, CAN, CAN trace, GNSS simulation). %>
<style>
.debug-nav { display: flex; flex-wrap: wrap; gap: 4px; margin: -16px -16px 12px; padding: 6px 12px; border-bottom: 1px solid color-mix(in srgb, CanvasText 15%, transparent); font-size: 0.9rem; }
.debug-nav a { padding: 6px 12px; border-radius: 6px; color: inherit; text-decoration: none; }
.debug-nav a:hover { background: color-mix(in srgb, CanvasText 8%, transparent); }
.debug-nav a[aria-current] { background: color-mix(in srgb, CanvasText 14%, transparent); font-weight: 600; }
.debug-nav .map { margin-left: auto; }
</style>
<nav class="debug-nav">
<% [["/status.html", "Server status"], ["/can.html", "CAN analyzer"], ["/trace.html", "CAN trace"], ["/keypad.html", "Keypad"], ["/sim.html", "GNSS simulation"]].each do |href, label| %>
<a href="<%= href %>"<%= ' aria-current="page"' if request.path == href %>><%= label %></a>
<% end %>
<a class="map" href="/" target="maptool">The map ↗</a>
</nav>
+168
View File
@@ -0,0 +1,168 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="color-scheme" content="light dark">
<title>CAN analyzer</title>
<link rel="icon" href="/icons/icon.svg" type="image/svg+xml">
<style>
:root { color-scheme: light dark; --muted: GrayText; --line: color-mix(in srgb, CanvasText 15%, transparent); --ok: #2e7d32; --warn: #ef6c00; --bad: #c62828; }
body { margin: 0; padding: 16px; background: Canvas; color: CanvasText; font: 15px/1.4 -apple-system, "Segoe UI", Roboto, Helvetica, Arial, sans-serif; }
header { display: flex; flex-wrap: wrap; gap: 8px 16px; align-items: baseline; margin-bottom: 12px; }
h1 { font-size: 1.2rem; margin: 0; }
h2 { font-size: 0.8rem; font-weight: 600; color: var(--muted); text-transform: uppercase; letter-spacing: 0.05em; margin: 20px 0 6px; }
#status { color: var(--muted); font-size: 0.85rem; } #status.bad { color: var(--bad); }
.scroll { overflow-x: auto; }
table { border-collapse: collapse; font-size: 0.85rem; }
th, td { padding: 6px 12px 6px 0; text-align: left; border-bottom: 1px solid var(--line); white-space: nowrap; }
th { color: var(--muted); font-weight: 500; }
.num { font-variant-numeric: tabular-nums; text-align: right; }
code { font: 0.85rem ui-monospace, SFMono-Regular, Menlo, monospace; }
.ok { color: var(--ok); } .warn { color: var(--warn); } .bad { color: var(--bad); }
.stale td { opacity: 0.5; }
input { padding: 6px 8px; font-size: 0.9rem; width: 220px; max-width: 100%; box-sizing: border-box; }
.empty { color: var(--muted); font-size: 0.85rem; }
/* side by side when there's room, the frames under the rest on a phone */
.cols { display: grid; gap: 0 32px; }
.cols > div { min-width: 0; }
/* the frames get at least 560px (their data in view), the left column
the rest up to its tables' width — each scrolls sideways if narrower */
@media (min-width: 900px) { .cols { grid-template-columns: minmax(0, max-content) minmax(560px, 1fr); } }
/* a byte that just changed, fading out over CHANGED_FOR */
/* a fixed width: the column doesn't jump when a node goes "silent" */
#nodes th:nth-child(2), #nodes td:nth-child(2) { width: 9em; min-width: 9em; }
.chg { background: color-mix(in srgb, #ffb300 calc(var(--fresh) * 70%), transparent); border-radius: 3px; }
</style>
</head>
<body>
<%= erb :_debug_nav, layout: false %>
<header>
<h1>CAN analyzer</h1>
<span id="status">loading…</span>
</header>
<div class="cols"><div>
<h2>Interfaces</h2>
<div class="scroll"><table id="interfaces"><thead><tr><th>Interface</th><th>State</th><th class="num">Frames</th><th>Last frame</th><th>Error</th></tr></thead><tbody></tbody></table></div>
<h2>Nodes</h2>
<div class="scroll"><table id="nodes"><thead><tr><th>Node</th><th>State</th><th>Last seen</th><th>Last EMCY</th><th>Sends</th><th>Actions</th></tr></thead><tbody></tbody></table></div>
<h2>Signals</h2>
<div class="scroll"><table id="signals"><thead><tr><th>Signal</th><th class="num">Value</th><th>Unit</th><th>Updated</th></tr></thead><tbody></tbody></table></div>
</div><div>
<h2>Frames <input id="filter" type="search" placeholder="Filter id, role, node…"></h2>
<div class="scroll"><table id="frames"><thead><tr><th>Interface</th><th>COB-ID</th><th>Role</th><th>Node</th><th class="num">Count</th><th class="num">Rate</th><th>Data</th><th>Last</th></tr></thead><tbody></tbody></table></div>
</div></div>
<script>
// Polls GET /api/can (lib/maptool/can.rb's Store) once a second.
const STALE_AFTER = 10; // s without a frame: greyed out
const CHANGED_FOR = 3; // s a changed byte stays highlighted
const seen = new Map(); // "iface:cob" → { bytes: [..], changedAt: [..] }
// The frame's bytes, each one that changed in the last CHANGED_FOR s
// highlighted (fading), its tooltip saying which bits and from what.
function dataHtml(f, key, now) {
const bytes = (f.data.match(/../g) || []).map((b) => parseInt(b, 16));
const before = seen.get(key);
const changedAt = bytes.map((b, i) => (before && before.bytes[i] !== undefined && before.bytes[i] !== b ? now : before?.changedAt[i] ?? 0));
const from = bytes.map((b, i) => (before && before.bytes[i] !== b ? before.bytes[i] : before?.from?.[i]));
seen.set(key, { bytes, changedAt, from });
return bytes.map((b, i) => {
const hex = b.toString(16).toUpperCase().padStart(2, "0");
const age = now - changedAt[i];
if (!changedAt[i] || age > CHANGED_FOR || from[i] === undefined) return hex;
const bits = [...Array(8).keys()].filter((bit) => ((b ^ from[i]) >> bit) & 1);
const title = `byte ${i}: ${from[i].toString(2).padStart(8, "0")} → ${b.toString(2).padStart(8, "0")} (bit ${bits.join(", ")})`;
return `<span class="chg" style="--fresh:${(1 - age / CHANGED_FOR).toFixed(2)}" title="${title}">${hex}</span>`;
}).join(" ");
}
const esc = (s) => String(s ?? "").replace(/[&<>"]/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;" })[c]);
const hex = (n, width) => "0x" + n.toString(16).toUpperCase().padStart(width, "0");
const nodeName = (n) => `${n} <code>${hex(Number(n), 2)}</code>`;
let last = null;
let clockOffset = 0; // server time minus ours, so ages don't depend on the tablet's clock
function age(at) {
if (!at) return "—";
const s = Date.now() / 1000 + clockOffset - at;
return s < 1 ? "now" : s < 60 ? `${Math.round(s)} s ago` : s < 3600 ? `${Math.round(s / 60)} min ago` : `${Math.round(s / 3600)} h ago`;
}
const stale = (at) => !at || Date.now() / 1000 + clockOffset - at > STALE_AFTER;
function fill(id, rows, empty, cols) {
document.querySelector(`#${id} tbody`).innerHTML = rows.length ? rows.join("") : `<tr><td class="empty" colspan="${cols}">${empty}</td></tr>`;
}
// can.json's "actions" beside their node: one SDO write each (POST /api/can/actions/<n>).
let notice = null; // an action's outcome, shown in the status for 10 s
const actionsHtml = (actions, node) => (actions || []).map((a, n) => a.node === node ? `<button type="button" data-action="${n}">${esc(a.name)}</button>` : "").join(" ");
document.getElementById("nodes").addEventListener("click", async (e) => {
const button = e.target.closest("button[data-action]");
if (!button || !confirm(`${button.textContent} on node ${last.actions[button.dataset.action].node}?`)) return;
button.disabled = true;
try {
const response = await fetch(`/api/can/actions/${button.dataset.action}`, { method: "POST" });
const body = await response.json().catch(() => ({}));
notice = { text: `${button.textContent}: ${response.ok ? "done" : body.error || `HTTP ${response.status}`}`, bad: !response.ok, until: Date.now() + 10000 };
} finally {
button.disabled = false;
}
});
const STATE_CLASS = { operational: "ok", "pre-operational": "warn", stopped: "bad", "boot-up": "warn" };
function render(data) {
fill("interfaces", Object.entries(data.interfaces).map(([name, i]) =>
`<tr><td>${esc(name)}</td><td class="${i.up ? "ok" : "bad"}">${i.up ? "up" : "down"}</td><td class="num">${i.frames}</td><td>${age(i.last_frame_at)}</td><td>${esc(i.error)}</td></tr>`),
data.available ? "No interface read yet." : "CAN is off: no data/can.json on this server.", 5);
const roles = {};
for (const f of data.frames) if (f.node != null) (roles[f.node] ||= new Set()).add(f.role);
fill("nodes", Object.entries(data.nodes).sort((a, b) => a[0] - b[0]).map(([id, n]) => {
const emcy = n.emcy ? `<code>${hex(n.emcy.code, 4)}</code> reg <code>${hex(n.emcy.register, 2)}</code> ${n.emcy.code === 0 ? "(reset)" : ""} · ${age(n.emcy.at)}` : "—";
return `<tr class="${stale(n.seen_at) && !n.silent ? "stale" : ""}"><td>${nodeName(id)}</td><td class="${n.silent ? "bad" : STATE_CLASS[n.state] || ""}"${n.silent ? ' title="3 heartbeats missed"' : ""}>${n.silent ? "silent" : esc(n.state || "no heartbeat")}</td><td>${age(n.seen_at)}</td><td class="${n.emcy?.code ? "bad" : ""}">${emcy}</td><td>${[...(roles[id] || [])].sort().map(esc).join(", ")}</td><td>${actionsHtml(data.actions, Number(id))}</td></tr>`;
}), "No CANopen node heard yet.", 6);
fill("signals", Object.entries(data.signals).sort().map(([name, s]) =>
`<tr class="${stale(s.at) ? "stale" : ""}"><td>${esc(name)}</td><td class="num">${typeof s.value === "number" ? +s.value.toFixed(6) : esc(s.value)}</td><td>${esc(s.unit)}</td><td>${age(s.at)}</td></tr>`),
"No signal decoded yet (signals in data/can.json).", 4);
const filter = document.getElementById("filter").value.trim().toLowerCase();
const frames = data.frames
.map((f) => ({ ...f, cob: f.extended ? hex(f.id, 8) : hex(f.id, 3) }))
.filter((f) => !filter || [f.interface, f.cob, f.role, f.node].join(" ").toLowerCase().includes(filter))
.sort((a, b) => a.interface.localeCompare(b.interface) || a.id - b.id);
const now = Date.now() / 1000;
fill("frames", frames.map((f) =>
`<tr class="${stale(f.at) ? "stale" : ""}"><td>${esc(f.interface)}</td><td><code>${f.cob}</code>${f.extended ? " ext" : ""}</td><td>${esc(f.role || "")}</td><td>${f.node ?? ""}</td><td class="num">${f.count}</td><td class="num">${f.interval ? (1 / f.interval).toFixed(f.interval > 1 ? 2 : 1) + " Hz" : ""}</td><td><code>${dataHtml(f, `${f.interface}:${f.cob}`, now)}</code></td><td>${age(f.at)}</td></tr>`),
filter ? "No frame matches." : "No frame yet.", 8);
}
async function poll() {
const status = document.getElementById("status");
try {
const response = await fetch("/api/can", { cache: "no-store" });
if (response.status === 401) { status.textContent = "Not logged in — log in on the map first."; return; }
if (!response.ok) throw new Error(`HTTP ${response.status}`);
const date = Date.parse(response.headers.get("Date"));
if (date) clockOffset = Math.abs(date / 1000 - Date.now() / 1000) > 2 ? date / 1000 - Date.now() / 1000 : 0;
render(last = await response.json());
const silent = Object.keys(last.nodes).filter((id) => last.nodes[id].silent);
const shown = notice && notice.until > Date.now() ? notice : null;
status.className = silent.length || shown?.bad ? "bad" : "";
status.textContent = (shown ? `${shown.text} · ` : "") + (silent.length ? `⚠ node ${silent.join(", ")} silent · ` : "") + (last.time ? `TIME: ${last.time.sending ? "maptool sends it" : "another node sends it"} · ` : "") + `updated ${new Date().toLocaleTimeString()}`;
} catch (e) {
status.textContent = `can't reach the server: ${e.message}`;
} finally {
setTimeout(poll, 1000);
}
}
document.getElementById("filter").addEventListener("input", () => last && render(last));
poll();
</script>
</body>
</html>
+5
View File
@@ -18,6 +18,10 @@
"/js/gpx.js": "/js/gpx.js?v=<%= ASSET_VERSION %>",
"/js/hiking_trails.js": "/js/hiking_trails.js?v=<%= ASSET_VERSION %>",
"/js/live.js": "/js/live.js?v=<%= ASSET_VERSION %>",
"/js/dashboard.js": "/js/dashboard.js?v=<%= ASSET_VERSION %>",
"/js/driving.js": "/js/driving.js?v=<%= ASSET_VERSION %>",
"/js/drive_menus.js": "/js/drive_menus.js?v=<%= ASSET_VERSION %>",
"/js/update.js": "/js/update.js?v=<%= ASSET_VERSION %>",
"/js/icons.js": "/js/icons.js?v=<%= ASSET_VERSION %>",
"/js/livetrack.js": "/js/livetrack.js?v=<%= ASSET_VERSION %>",
"/js/locate.js": "/js/locate.js?v=<%= ASSET_VERSION %>",
@@ -36,6 +40,7 @@
"/js/share_import.js": "/js/share_import.js?v=<%= ASSET_VERSION %>",
"/js/search.js": "/js/search.js?v=<%= ASSET_VERSION %>",
"/js/shadow.js": "/js/shadow.js?v=<%= ASSET_VERSION %>",
"/js/speed_limits.js": "/js/speed_limits.js?v=<%= ASSET_VERSION %>",
"/js/sun.js": "/js/sun.js?v=<%= ASSET_VERSION %>",
"/js/track_profile.js": "/js/track_profile.js?v=<%= ASSET_VERSION %>",
"/vendor/maplibre-gl/maplibre-gl.mjs": "/vendor/maplibre-gl/maplibre-gl.mjs?v=<%= ASSET_VERSION %>",
+206 -110
View File
@@ -1,13 +1,12 @@
<div id="app">
<header class="topbar">
<span class="topbar__brand" title="rev <%= revision %>">MapTool</span>
<span class="topbar__center">
<span class="topbar__coords"></span>
<span class="topbar__sun" title="Sun &amp; moon" hidden></span>
</span>
<div class="topbar__search"></div>
<span class="topbar__center"></span>
<div class="sun-chart" hidden></div>
<span class="topbar__offline-status" hidden></span>
<button type="button" class="topbar__night"></button>
<button type="button" class="topbar__update" hidden></button>
<button type="button" class="topbar__night" hidden></button> <!-- the cycle On the map's Theme row and drive mode use; no place of its own in the bar -->
<div class="topbar__auth">
<% if logged_in %>
<span><%= user %></span>
@@ -22,6 +21,14 @@
<nav id="sidebar" class="sidebar"></nav>
<div id="map"></div>
</div>
<footer class="statusbar">
<span class="statusbar__coords"></span>
<span class="statusbar__cursor"></span>
<span class="statusbar__zoom"></span>
<span class="statusbar__rev">rev <%= revision %></span>
<span class="statusbar__sun" title="Sun &amp; moon" hidden></span>
</footer>
</div>
<div id="profile-panel" class="profile-panel" hidden>
@@ -38,29 +45,9 @@
<div class="trail-panel__body"></div>
</div>
<div id="basemap-panel" class="basemap-panel" hidden>
<div class="basemap-panel__header">
<strong>Base map</strong>
<button type="button" class="basemap-panel__close" aria-label="Close">&times;</button>
</div>
<div class="basemap-panel__list basemap-panel__sources">
<button type="button" class="basemap-panel__option" data-style="online">
<span>Online</span>
<span class="basemap-panel__check">&check;</span>
</button>
<button type="button" class="basemap-panel__option" data-style="offline">
<span>Offline</span>
<span class="basemap-panel__check">&check;</span>
</button>
</div>
<div class="basemap-panel__list">
<a class="basemap-panel__link" href="/symbols.html" target="_blank">Legend &amp; symbols ↗</a>
</div>
</div>
<div id="gpx-panel" class="gpx-panel" hidden>
<div id="gpx-panel" class="gpx-panel" hidden<%= " data-sync-client" if sync_client %>>
<div class="gpx-panel__header">
<strong>Tracks &amp; Points</strong>
<strong>Library</strong>
<div class="gpx-panel__actions">
<button type="button" class="gpx-panel__action" data-action="new-folder" title="New folder" aria-label="New folder"></button>
<button type="button" class="gpx-panel__action" data-action="upload" title="Upload GPX/FIT/TCX/GeoJSON file" aria-label="Upload GPX/FIT/TCX/GeoJSON file"></button>
@@ -71,15 +58,54 @@
<input type="file" class="gpx-file-input" accept=".gpx,.fit,.tcx,.geojson,.zip" multiple hidden>
<p class="gpx-upload__status" hidden></p>
<!-- Find first (the Design canvas' Library): filled by GpxPanelControl. -->
<div class="lib-find">
<input type="search" class="lib-find__input" placeholder="Find a point, track, folder…" aria-label="Find in the library">
<div class="lib-find__kinds" role="group" aria-label="What"></div>
<div class="lib-find__bar">
<button type="button" class="lib-chip" data-find="shown" aria-pressed="false">Shown on the map</button>
<span class="lib-seg" role="group" aria-label="View">
<button type="button" data-mode="folders" aria-pressed="true">Folders</button>
<button type="button" data-mode="list" aria-pressed="false">List</button>
</span>
</div>
</div>
<div class="lib-crumb" hidden></div>
<div class="gpx-tree"></div>
<div class="gpx-legend" hidden></div>
<div class="lib-foot">
<span class="lib-foot__text"></span>
<button type="button" data-action="hide-all">Hide all</button>
</div>
</div>
<div id="overlays-panel" class="basemap-panel" hidden>
<div class="basemap-panel__header">
<strong>Overlays</strong>
<strong>On the map</strong>
<button type="button" class="basemap-panel__close" aria-label="Close">&times;</button>
</div>
<!-- On the map (the Design canvas): the map itself first — online or the
offline one (LayerToggleControl, map.js) — then the overlays. -->
<div class="onthemap-map">
<div class="overlays-panel__group">Map</div>
<div class="onthemap-row">
<span class="onthemap-row__icon" aria-hidden="true">▦</span>
<span class="onthemap-row__text"><b>Map</b><small>online or this server's offline map</small></span>
<span class="basemap-panel__sources onthemap-seg" role="group" aria-label="Map">
<button type="button" class="basemap-panel__option" data-style="online">Online</button>
<button type="button" class="basemap-panel__option" data-style="offline">Offline</button>
</span>
</div>
<div class="onthemap-row">
<span class="onthemap-row__icon" aria-hidden="true">◑</span>
<span class="onthemap-row__text"><b>Theme</b><small>day / dusk / night, auto by the sun</small></span>
<button type="button" class="onthemap-theme"></button>
</div>
<div class="onthemap-row">
<span class="onthemap-row__icon" aria-hidden="true">?</span>
<a class="onthemap-row__text basemap-panel__link" href="/symbols.html" target="_blank"><b>Legend &amp; symbols ↗</b><small>what the map's colours and symbols mean</small></a>
</div>
</div>
<!-- Each item is a live layer refetched/toggled from its own source as
the map moves, not a file to add/remove/reorder — a plain on/off
list, no upload/new-folder actions the way Tracks & Points has.
@@ -104,8 +130,12 @@
<strong>Status / debug</strong>
<button type="button" class="basemap-panel__close" aria-label="Close">&times;</button>
</div>
<!-- Filled by DebugControl (public/js/debug.js), logged-in only. -->
<div class="debug-panel__body"></div>
<div class="basemap-panel__list">
<a class="basemap-panel__link" href="/status.html" target="_blank">Server status (all endpoints) ↗</a>
<a class="basemap-panel__link" href="/can.html" target="_blank">CANopen diagnostics ↗</a>
<a class="basemap-panel__link" href="/sim.html" target="_blank">GNSS simulation ↗</a>
<button type="button" class="basemap-panel__link debug-panel__update-check" hidden>Check for an update now</button>
</div>
</div>
<div id="plugins-panel" class="basemap-panel" hidden>
@@ -120,103 +150,86 @@
</div>
</div>
<div id="route-panel" class="basemap-panel" hidden>
<div id="route-panel" class="basemap-panel route-panel" hidden>
<div class="basemap-panel__header">
<strong>Route</strong>
<!-- Icons are added by RoutePanelControl (public/js/icons.js). -->
<span class="route-panel__head-actions">
<button type="button" data-action="reverse">Reverse</button>
<button type="button" data-action="clear">Clear</button>
</span>
<button type="button" class="basemap-panel__close" aria-label="Close">&times;</button>
</div>
<!-- Filled by RoutePanelControl (public/js/route.js). -->
<!-- Filled by RoutePanelControl (public/js/route.js), laid out after the
Design canvas' Desktop artboard: the points with their legs, adding
one, the totals, the vehicle and what to avoid, the long parts folded,
saving at the bottom. -->
<div class="route-panel__body">
<p class="route-panel__hint">Click the map to add points (or "Add to route" on a search result or a library point); drag a marker to move it.</p>
<p class="route-panel__editing" hidden></p>
<!-- the itinerary (the Design canvas' Itinerary): the shared trip's name,
when it leaves; a day after a night stop starts at "Days start"; its note -->
<div class="route-panel__trip">
<input type="text" name="name" maxlength="80" placeholder="Trip name" aria-label="Trip name">
<label>Leave <input type="datetime-local" name="start"></label>
<label>Days start <input type="time" name="day_start" placeholder="09:00"></label>
<label>Fuel <input type="number" name="fuel_price" min="0" max="10" step="0.01" placeholder="–"> €/l</label>
<label>Budget <input type="number" name="budget" min="0" max="1000000" step="10" placeholder="–"> €</label>
<textarea name="note" rows="1" maxlength="2000" placeholder="The trip's note" aria-label="The trip's note"></textarea>
</div>
<!-- is the trip ready (the canvas' Plan, Check): each problem with its stop -->
<details class="route-panel__fold route-panel__check" hidden>
<summary>Check <span class="route-panel__fold-meta"></span></summary>
<ul></ul>
</details>
<!-- the money (the canvas' Plan, Costs): planned from the route and the stops vs paid -->
<details class="route-panel__fold route-panel__costs" hidden>
<summary>Costs <span class="route-panel__fold-meta"></span></summary>
<ul></ul>
</details>
<ol class="route-panel__points"></ol>
<!-- Icons are added by RoutePanelControl (public/js/icons.js). -->
<div class="route-panel__buttons">
<button type="button" data-action="position">My position</button>
<button type="button" data-action="saved-point">Saved point</button>
<div class="route-panel__add">
<button type="button" class="route-panel__chip route-panel__chip--add" data-action="search">+ Search</button>
<button type="button" class="route-panel__chip" data-action="saved-point">Saved point</button>
<button type="button" class="route-panel__chip" data-action="position">My position</button>
<span class="route-panel__hint">or click the map</span>
</div>
<div class="route-panel__saved" hidden>
<input type="search" placeholder="Search saved points" aria-label="Search saved points">
<ul></ul>
</div>
<div class="route-panel__buttons">
<button type="button" data-action="reverse">Reverse</button>
<button type="button" data-action="clear">Clear</button>
<button type="button" data-action="save" hidden>Save to library</button>
</div>
<div class="route-panel__totals" hidden></div>
<p class="route-panel__summary"></p>
<ul class="route-panel__countries" hidden></ul>
<button type="button" class="route-panel__profile" hidden>Elevation profile</button>
<details class="route-panel__directions" hidden>
<summary>Directions</summary>
<div class="route-panel__row route-panel__avoid">
<span class="route-panel__label">Avoid</span>
<label class="route-panel__chip"><input type="checkbox" name="tolls"> Tolls</label>
<label class="route-panel__chip"><input type="checkbox" name="highways"> Motorways</label>
<label class="route-panel__chip"><input type="checkbox" name="ferries"> Ferries</label>
<label class="route-panel__chip"><input type="checkbox" name="unpaved"> Unpaved</label>
</div>
<details class="route-panel__fold route-panel__directions" hidden>
<summary>Directions <span class="route-panel__fold-meta"></span></summary>
<ol></ol>
</details>
<div class="route-panel__reach">
<span>Reach in</span>
<select>
<option value="30">30 min</option>
<option value="60" selected>1 h</option>
<option value="120">2 h</option>
<option value="30,60,120">30 min · 1 h · 2 h</option>
</select>
<button type="button" data-action="reach">Show</button>
<button type="button" data-action="reach-clear" hidden>Hide</button>
</div>
<p class="route-panel__reach-status" hidden></p>
<div class="route-panel__vehicle-row">
<label>Vehicle <select class="route-panel__vehicle-select"></select></label>
<button type="button" data-action="vehicle-edit" hidden>Edit</button>
</div>
<div class="route-panel__avoid">
Avoid
<label><input type="checkbox" name="tolls"> tolls</label>
<label><input type="checkbox" name="highways"> motorways</label>
</div>
<fieldset class="route-panel__vehicle" hidden>
<label class="route-panel__vehicle-name">Name <input type="text" name="name" maxlength="40"></label>
<label>Type
<select name="type">
<option value="car">Car</option>
<option value="bicycle">Bicycle</option>
<option value="foot">On foot</option>
<details class="route-panel__fold">
<summary>Reach <span class="route-panel__fold-meta">30 min · 1 h · 2 h</span></summary>
<div class="route-panel__reach">
<span>Reach in</span>
<select>
<option value="30">30 min</option>
<option value="60" selected>1 h</option>
<option value="120">2 h</option>
<option value="30,60,120">30 min · 1 h · 2 h</option>
</select>
</label>
<!-- data-for: the types a field applies to, the rest are hidden. -->
<label data-for="car">Height <input type="number" name="height" step="0.1" min="1" max="6" placeholder="–"> m</label>
<label data-for="car">Width <input type="number" name="width" step="0.1" min="1" max="4" placeholder="–"> m</label>
<label data-for="car">Length <input type="number" name="length" step="0.5" min="2" max="25" placeholder="–"> m</label>
<label data-for="car">Weight <input type="number" name="weight" step="0.1" min="0.5" max="60" placeholder="–"> t</label>
<label data-for="bicycle">Bike
<select name="bicycle_type">
<option value="Road">Road</option>
<option value="Hybrid">Trekking</option>
<option value="Cross">Gravel</option>
<option value="Mountain">MTB</option>
</select>
</label>
<label data-for="bicycle foot">Speed <input type="number" name="speed" step="0.5" min="1" max="60" placeholder="–"> km/h</label>
<label data-for="bicycle foot">Hills
<select name="hills">
<option value="">Default</option>
<option value="0">Avoid</option>
<option value="1">Seek</option>
</select>
</label>
<label data-for="foot">Up to
<select name="sac">
<option value="">T1 hiking</option>
<option value="2">T2 mountain hiking</option>
<option value="3">T3 demanding</option>
<option value="4">T4 alpine</option>
<option value="5">T5 demanding alpine</option>
<option value="6">T6 difficult alpine</option>
</select>
</label>
<p class="route-panel__vehicle-hint" data-for="car">Empty: no limit. Over 3.5 t routes as a truck.</p>
<p class="route-panel__vehicle-hint" data-for="bicycle foot">Empty speed: the usual one for the bike or walking.</p>
<button type="button" data-action="vehicle-add">+ New vehicle</button>
<button type="button" data-action="vehicle-delete">Delete</button>
</fieldset>
<button type="button" data-action="reach">Show</button>
<button type="button" data-action="reach-clear" hidden>Hide</button>
</div>
<p class="route-panel__reach-status" hidden></p>
</details>
</div>
<div class="route-panel__footer">
<button type="button" class="route-panel__primary" data-action="save" hidden>Save to library</button>
<button type="button" class="route-panel__secondary route-panel__profile" hidden>Elevation profile</button>
</div>
</div>
@@ -231,3 +244,86 @@
"control owns its content" story as the Overlays panel. -->
<div class="offline-data-panel__body"></div>
</div>
<!-- Profiles (cars and activities): set once, rarely opened again (the
Design canvas' Vehicle). The map's bottom-left chip picks one (route.js). -->
<dialog class="profiles" aria-label="Profiles">
<div class="profiles__head"><h2>Profiles</h2><button type="button" class="profiles__close" aria-label="Close">✕</button></div>
<div class="profiles__list"><ul></ul><button type="button" data-action="vehicle-add">+ New profile</button></div>
<fieldset class="profiles__form">
<label class="route-panel__vehicle-name">Name <input type="text" name="name" maxlength="40"></label>
<label>Type
<select name="type">
<option value="car">Car</option>
<option value="bicycle">Bicycle</option>
<option value="foot">On foot</option>
</select>
</label>
<!-- data-for: the types a field applies to, the rest are hidden. -->
<label data-for="car">Height <input type="number" name="height" step="0.1" min="1" max="6" placeholder="–"> m</label>
<label data-for="car">Width <input type="number" name="width" step="0.1" min="1" max="4" placeholder="–"> m</label>
<label data-for="car">Length <input type="number" name="length" step="0.5" min="2" max="25" placeholder="–"> m</label>
<label data-for="car">Weight <input type="number" name="weight" step="0.1" min="0.5" max="60" placeholder="–"> t</label>
<label data-for="car">Wheelbase <input type="number" name="wheelbase" step="0.01" min="1" max="10" placeholder="–"> m</label>
<label data-for="car">Track <input type="number" name="track" step="0.01" min="1" max="3" placeholder="–" title="Between the wheels' centres, side to side"> m</label>
<label data-for="car">Uses <input type="number" name="consumption" step="0.1" min="1" max="100" placeholder="–" title="Per 100 km: litres (kWh for an electric car), for the trip's costs"> /100 km</label>
<label data-for="car">Ramps <input type="text" name="ramps" maxlength="30" placeholder="3 6 9" title="The levelling ramps' steps, cm"> cm</label>
<label data-for="bicycle">Bike
<select name="bicycle_type">
<option value="Road">Road</option>
<option value="Hybrid">Trekking</option>
<option value="Cross">Gravel</option>
<option value="Mountain">MTB</option>
</select>
</label>
<label data-for="bicycle foot">Speed <input type="number" name="speed" step="0.5" min="1" max="60" placeholder="–"> km/h</label>
<label data-for="bicycle foot">Hills
<select name="hills">
<option value="">Default</option>
<option value="0">Avoid</option>
<option value="1">Seek</option>
</select>
</label>
<label data-for="foot">Up to
<select name="sac">
<option value="">T1 hiking</option>
<option value="2">T2 mountain hiking</option>
<option value="3">T3 demanding</option>
<option value="4">T4 alpine</option>
<option value="5">T5 demanding alpine</option>
<option value="6">T6 difficult alpine</option>
</select>
</label>
<label data-for="car">Fuel
<select name="fuel">
<option value="">–</option>
<option value="petrol">Petrol</option>
<option value="diesel">Diesel</option>
<option value="lpg">LPG</option>
<option value="cng">CNG</option>
<option value="electric">Electric</option>
<option value="hybrid">Hybrid</option>
</select>
</label>
<label data-for="car">Euro
<select name="euro">
<option value="">–</option>
<option value="3">Euro 3</option>
<option value="4">Euro 4</option>
<option value="5">Euro 5</option>
<option value="6">Euro 6</option>
<option value="6d">Euro 6d</option>
</select>
</label>
<label data-for="car" class="profiles__wide">Stickers <input type="text" name="stickers" maxlength="80" placeholder="DE green 4 · FR Crit'Air 2"></label>
<div data-for="car" class="profiles__wide profiles__vignettes">
<span>Vignettes &amp; toll units</span>
<ul></ul>
<button type="button" data-action="vignette-add">+ Add</button>
</div>
<p class="route-panel__vehicle-hint" data-for="car">Empty: no limit. Over 3.5 t routes as a truck.</p>
<p class="route-panel__vehicle-hint" data-for="bicycle foot">Empty speed: the usual one for the bike or walking.</p>
<button type="button" data-action="vehicle-delete" class="profiles__delete">Delete this profile</button>
</fieldset>
<div class="profiles__foot">Stored on this server for every screen; changes save as you go.</div>
</dialog>
+268
View File
@@ -0,0 +1,268 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="color-scheme" content="light dark">
<title>Keypad bindings</title>
<link rel="icon" href="/icons/icon.svg" type="image/svg+xml">
<style>
:root { color-scheme: light dark; --muted: GrayText; --line: color-mix(in srgb, CanvasText 15%, transparent); --ok: #2e7d32; --bad: #c62828; --sel: #546619; }
body { margin: 0; padding: 16px; background: Canvas; color: CanvasText; font: 15px/1.4 -apple-system, "Segoe UI", Roboto, Helvetica, Arial, sans-serif; }
header { display: flex; flex-wrap: wrap; gap: 8px 16px; align-items: baseline; margin-bottom: 16px; }
h1 { font-size: 1.2rem; margin: 0; }
h2 { font-size: 0.8rem; font-weight: 600; color: var(--muted); text-transform: uppercase; letter-spacing: 0.05em; margin: 0 0 8px; }
main { display: grid; gap: 16px; grid-template-columns: repeat(auto-fit, minmax(min(420px, 100%), 1fr)); align-items: start; }
section { border: 1px solid var(--line); border-radius: 8px; padding: 12px 16px; }
.pad { display: inline-grid; gap: 10px; padding: 18px; border-radius: 20px; background: #111; margin-bottom: 12px; }
.pad button { width: 76px; height: 76px; border-radius: 14px; border: 4px solid var(--led, #333); background: #1c1c1c; color: #e8e6df; font: inherit; font-size: 12px; font-weight: 700;
display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 2px; box-shadow: 0 0 12px color-mix(in srgb, var(--led, #000) 35%, transparent); overflow: hidden; }
.pad button small { font-weight: 400; font-size: 10px; color: #9b988d; max-width: 68px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.pad .knob { border-radius: 50%; }
.pad .press { width: 76px; height: 30px; border-radius: 8px; border-width: 2px; font-size: 10px; flex-direction: row; }
.pad button[aria-pressed="true"] { outline: 3px solid #fff; outline-offset: 4px; }
.pad button.hit { background: #3a3a35; }
.knobs { display: flex; gap: 10px; }
.knobs > div { display: flex; flex-direction: column; gap: 6px; }
label, fieldset { display: flex; flex-direction: column; gap: 4px; margin: 0 0 12px; padding: 0; border: none; }
label > span, legend { font-size: 0.75rem; color: var(--muted); text-transform: uppercase; letter-spacing: 0.05em; }
select, input, button { font-size: 1rem; padding: 8px 12px; border-radius: 8px; }
.modes { display: flex; flex-wrap: wrap; gap: 6px; }
.modes button[aria-pressed="true"] { background: var(--sel); color: #fff; border-color: var(--sel); }
.row { display: grid; grid-template-columns: 1fr 1fr; gap: 0 16px; }
.actions { display: flex; flex-wrap: wrap; gap: 8px; }
.primary { background: var(--sel); color: #fff; border: 1px solid var(--sel); font-weight: 600; }
.hint { color: var(--muted); font-size: 0.85rem; }
.bad { color: var(--bad); } .on { color: var(--ok); }
a { color: inherit; }
</style>
</head>
<body>
<%= erb :_debug_nav, layout: false %>
<header>
<h1>Keypad bindings</h1>
<span id="state">loading…</span>
</header>
<main>
<section>
<h2>Keypads</h2>
<div id="pads"></div>
<p class="hint">Tap a key or knob, or press it on the keypad. The ring is the key LED's colour.</p>
</section>
<section id="editor" hidden>
<h2 id="title"></h2>
<label><span>Drives</span><select id="drives"></select></label>
<fieldset id="mode-box"><legend>Mode</legend><div class="modes" id="modes"></div>
<span class="hint" id="mode-hint"></span></fieldset>
<fieldset id="positions-box"><legend>Positions — a press steps off → 1 → 2 → … → off, a knob turns up and down</legend>
<ol id="positions" style="margin: 0; padding-left: 1.5em; display: flex; flex-direction: column; gap: 6px"></ol>
<div class="actions" style="margin-top: 6px"><button type="button" id="add-position">+ Position</button></div></fieldset>
<label id="pulse-box"><span>Pulse, s</span><input id="pulse" type="number" min="0.1" step="0.1" value="1"></label>
<label id="period-box"><span>Strobe period (on + off), s</span><input id="period" type="number" min="0.2" step="0.1" value="1"></label>
<label id="step-box"><span>Dimmer step per knob click, %</span><input id="step" type="number" min="1" max="100" step="1" value="10"></label>
<label><span>In an open menu</span><select id="menu"></select></label>
<div class="row" id="led-box">
<label><span>LED</span><select id="led"></select></label>
<label><span>LED while on</span><select id="led_on"></select></label>
</div>
<div class="actions">
<button type="button" id="remove">Remove</button>
</div>
</section>
</main>
<p class="actions" style="margin-top: 16px">
<button type="button" class="primary" id="save" disabled>Save</button>
<button type="button" id="reset">Back to the profile's</button>
<span class="hint" id="source"></span>
</p>
<script>
// The keypads' bindings (GET/PUT/DELETE /api/keypad/bindings): a key or knob
// picked, what it drives — a screen key's action or an output — how, and its LEDs.
// Edits stay here until Save; drive mode takes them when it next loads.
const $ = (id) => document.getElementById(id);
const esc = (s) => String(s ?? "").replace(/[&<>"]/g, (ch) => `&#${ch.charCodeAt(0)};`);
const LED = { red: "#e8453a", green: "#34b545", blue: "#3b82f6", yellow: "#f0a020", cyan: "#22c3d6", magenta: "#b45bd0", white: "#e8e6df" };
const KNOB_ACTIONS = ["zoom", "panX", "panY", "rows"];
const MENU = ["rows", "enter", "close"];
const MODE_HINT = { toggle: "each press switches it", on: "a press switches it on", off: "a press switches it off",
hold: "on while held — off when let go or the keypad goes silent", pulse: "on for the time below",
positions: "one output per position, the last off before the next on", strobe: "a press starts or stops it blinking",
dimmer: "a knob sets the level, a press switches it on or off; only a dimmable module dims, a relay just switches" };
const KNOB_MODES = ["positions", "dimmer"]; // what a turn does; the other modes take presses
let info = null, bindings = [], screenActions = [], selected = null, dirty = false;
const json = async (url, options) => {
const response = await fetch(url, { cache: "no-store", ...options });
const body = await response.json().catch(() => ({}));
if (!response.ok) throw new Error(body.error || `HTTP ${response.status}`);
return body;
};
const binding = (input) => bindings.find((b) => b.input === input);
const isKnob = (input) => /\.E\d+$/.test(input);
const outs = (b) => b?.outputs || (b?.output ? [b.output] : []);
const what = (b) => (!b ? "" : b.outputs ? `${b.mode}: ${b.outputs.join(", ")}` : b.output ? `${b.output}${outputLabel(b.output) ? ` ${outputLabel(b.output)}` : ""}${b.mode && b.mode !== "toggle" ? ` · ${b.mode}` : ""}` : b.action || (b.menu ? `menu: ${b.menu}` : ""));
const outputLabel = (o) => info.outputs.find((x) => x.output === o)?.label || "";
function key(input, label, cls = "") {
const b = binding(input);
const led = b?.led ? `--led: ${LED[b.led]}` : "";
return `<button type="button" class="${cls}" data-input="${esc(input)}" style="${led}" aria-pressed="${input === selected}">${esc(label)}<small>${esc(what(b) || "—")}</small></button>`;
}
function renderPads() {
$("pads").innerHTML = info.keypads.map((d) => {
const ch = d.channels;
const keys = ch.filter((c) => !/^E\d+( press)?$/.test(c));
const knobs = ch.filter((c) => /^E\d+$/.test(c));
const cols = keys.length > 6 ? Math.ceil(keys.length / 2) : Math.max(keys.length, 1);
return `<h2>${esc(d.name)}${d.protocol ? ` · ${esc(d.protocol.toUpperCase())} node 0x${d.node.toString(16).padStart(2, "0")}` : ""}</h2>` +
(keys.length ? `<div class="pad" style="grid-template-columns: repeat(${cols}, 76px)">${keys.map((c) => key(`${d.name}.${c}`, c)).join("")}</div>` : "") +
(knobs.length ? `<div class="pad knobs">${knobs.map((c) => `<div>${key(`${d.name}.${c}`, c, "knob")}${ch.includes(`${c} press`) ? key(`${d.name}.${c} press`, "⏎", "press") : ""}</div>`).join("")}</div>` : "");
}).join("") || '<p class="hint">No keypads in data/can.json ("keypads").</p>';
}
const options = (list, value, none = "— nothing —") => `<option value="">${none}</option>` + list.map(([v, l]) => `<option value="${esc(v)}"${v === value ? " selected" : ""}>${esc(l)}</option>`).join("");
function renderEditor() {
$("editor").hidden = !selected;
if (!selected) return;
const b = binding(selected) || {};
const knob = isKnob(selected);
const pkpKey = /\.K\d+$/.test(selected) && info.keypads.find((d) => selected.startsWith(`${d.name}.`))?.protocol === "pkp";
$("title").textContent = `${selected}${knob ? " · turning" : selected.endsWith(" press") ? " · pressing the knob" : ""}`;
const actions = [...(knob ? KNOB_ACTIONS : []), ...screenActions];
const first = outs(b)[0];
const drives = first ? `output:${first}` : b.action ? `action:${b.action}` : "";
$("drives").innerHTML = `<option value="">— nothing —</option>` +
`<optgroup label="Screen">${actions.map((a) => `<option value="action:${esc(a)}"${`action:${a}` === drives ? " selected" : ""}>${esc(a)}</option>`).join("")}</optgroup>` +
`<optgroup label="Output">${outputOptions(drives.slice(7))}</optgroup>`;
const isOut = !!first;
const mode = b.mode || (knob ? "dimmer" : "toggle");
$("mode-box").hidden = !isOut;
$("modes").innerHTML = info.modes.filter((m) => !knob || KNOB_MODES.includes(m)).map((m) => `<button type="button" data-mode="${m}" aria-pressed="${m === mode}">${m}</button>`).join("");
$("mode-hint").textContent = MODE_HINT[mode] || "";
$("positions-box").hidden = !isOut || mode !== "positions";
$("positions").innerHTML = (b.outputs || []).map((o, i) => `<li><span class="actions"><select data-position="${i}">${outputOptions(o)}</select>${i ? `<button type="button" data-drop="${i}" aria-label="Remove position ${i + 1}">✕</button>` : ""}</span></li>`).join("");
$("pulse-box").hidden = !isOut || mode !== "pulse";
$("pulse").value = b.pulse_s ?? 1;
$("period-box").hidden = !isOut || mode !== "strobe";
$("period").value = b.period_s ?? 1;
$("step-box").hidden = !isOut || mode !== "dimmer";
$("step").value = b.step ?? 10;
$("menu").innerHTML = options([...(knob ? ["rows"] : MENU.slice(1)).map((m) => [m, m]), ...screenActions.map((a) => [a, a])], b.menu, "— the same —");
$("led-box").hidden = !pkpKey;
const colors = info.colors.map((c) => [c, c]);
$("led").innerHTML = options(colors, b.led, "off");
$("led_on").innerHTML = options(colors, b.led_on, b.output ? "red" : "green");
}
const outputOptions = (value) => info.outputs.map((o) => `<option value="${esc(o.output)}"${o.output === value ? " selected" : ""}>${esc(o.output)}${o.label ? ` · ${esc(o.label)}` : ""}${o.dimmable ? " · dimmable" : ""}</option>`).join("");
function render() {
renderPads();
renderEditor();
$("save").disabled = !dirty;
$("source").textContent = dirty ? "unsaved changes" : info.saved ? "this car's own (data/drive/bindings.json)" : "the profile's (public/drive/road.json)";
}
// a field changed: into the selected input's binding (made, or dropped when empty)
function change(fields) {
let b = binding(selected);
if (!b) bindings.push((b = { input: selected }));
Object.assign(b, fields);
for (const k of Object.keys(b)) if (b[k] === "" || b[k] == null) delete b[k];
if (!b.action && !b.output && !b.outputs && !b.menu) bindings = bindings.filter((x) => x !== b);
dirty = true;
render();
}
$("pads").addEventListener("click", (e) => {
const el = e.target.closest("button[data-input]");
if (el) { selected = el.dataset.input; render(); }
});
$("drives").addEventListener("change", (e) => {
const [kind, value] = [e.target.value.slice(0, e.target.value.indexOf(":")), e.target.value.slice(e.target.value.indexOf(":") + 1)];
const b = binding(selected);
if (kind === "output" && b?.outputs) change({ outputs: [value, ...b.outputs.slice(1)] });
else if (kind === "output") change({ output: value, action: null, mode: isKnob(selected) ? "dimmer" : b?.mode });
else change({ action: kind === "action" ? value : null, output: null, outputs: null, mode: null, pulse_s: null, period_s: null, step: null });
});
$("modes").addEventListener("click", (e) => {
const m = e.target.closest("button[data-mode]")?.dataset.mode;
if (!m) return;
const list = outs(binding(selected));
change({ mode: m === "toggle" ? null : m, pulse_s: m === "pulse" ? binding(selected)?.pulse_s ?? 1 : null,
period_s: m === "strobe" ? binding(selected)?.period_s ?? 1 : null, step: m === "dimmer" ? binding(selected)?.step ?? 10 : null,
outputs: m === "positions" ? list : null, output: m === "positions" ? null : list[0] });
});
$("positions").addEventListener("change", (e) => {
const i = Number(e.target.dataset.position);
change({ outputs: binding(selected).outputs.map((o, k) => (k === i ? e.target.value : o)) });
});
$("positions").addEventListener("click", (e) => {
const i = e.target.dataset.drop;
if (i != null) change({ outputs: binding(selected).outputs.filter((_, k) => k !== Number(i)) });
});
$("add-position").addEventListener("click", () => {
const list = binding(selected).outputs;
const next = info.outputs.find((o) => !list.includes(o.output))?.output || list[list.length - 1];
change({ outputs: [...list, next] });
});
$("period").addEventListener("change", (e) => change({ period_s: Number(e.target.value) || 1 }));
$("step").addEventListener("change", (e) => change({ step: Number(e.target.value) || 10 }));
$("pulse").addEventListener("change", (e) => change({ pulse_s: Number(e.target.value) || 1 }));
$("menu").addEventListener("change", (e) => change({ menu: e.target.value }));
$("led").addEventListener("change", (e) => change({ led: e.target.value }));
$("led_on").addEventListener("change", (e) => change({ led_on: e.target.value }));
$("remove").addEventListener("click", () => { bindings = bindings.filter((b) => b.input !== selected); dirty = true; render(); });
$("save").addEventListener("click", async () => {
try {
Object.assign(info, await json("/api/keypad/bindings", { method: "PUT", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ bindings }) }));
bindings = structuredClone(info.bindings);
dirty = false;
$("state").innerHTML = '<span class="on">saved</span> — drive mode takes them when it next loads';
render();
} catch (e) { $("state").innerHTML = `<span class="bad">${esc(e.message)}</span>`; }
});
$("reset").addEventListener("click", async () => {
if (!confirm("Drop this car's bindings and go back to the profile's?")) return;
Object.assign(info, await json("/api/keypad/bindings", { method: "DELETE" }));
bindings = structuredClone(info.bindings);
dirty = false;
render();
});
window.addEventListener("beforeunload", (e) => { if (dirty) e.preventDefault(); });
// a key pressed on the keypad picks it (GET /api/keypad, a long poll)
async function listen() {
let since = null;
for (;;) {
try {
const response = await fetch(`/api/keypad${since == null ? "" : `?since=${since}`}`, { cache: "no-store" });
if (response.status === 404) return;
const answer = await response.json();
if (since != null) for (const e of answer.events) {
if (e.input.endsWith(" up")) continue;
selected = e.input.replace(/ [⟳⟲]$/, "");
render();
document.querySelector(`[data-input="${CSS.escape(selected)}"]`)?.classList.add("hit");
setTimeout(() => document.querySelector(".hit")?.classList.remove("hit"), 300);
}
$("state").innerHTML = answer.present.length ? `<span class="on">● ${answer.present.map((p) => esc(p.name)).join(", ")} on the bus</span>` : "no keypad on the bus";
since = answer.seq;
} catch { await new Promise((r) => setTimeout(r, 3000)); }
}
}
(async () => {
try {
const [i, profile] = await Promise.all([json("/api/keypad/bindings"), json("/drive/road.json")]);
info = i;
bindings = structuredClone(info.bindings);
screenActions = profile.cells.filter((c) => c.widget === "key").map((c) => c.action);
selected = info.keypads[0] ? `${info.keypads[0].name}.${info.keypads[0].channels[0]}` : null;
render();
listen();
} catch (e) {
$("state").innerHTML = `<span class="bad">${esc(e.message)}</span>${/401/.test(e.message) ? ' — <a href="/login">log in</a>' : ""}`;
}
})();
</script>
</body>
</html>
+134
View File
@@ -0,0 +1,134 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="color-scheme" content="light dark">
<title>GNSS simulation</title>
<link rel="icon" href="/icons/icon.svg" type="image/svg+xml">
<style>
:root { color-scheme: light dark; --muted: GrayText; --line: color-mix(in srgb, CanvasText 15%, transparent); --ok: #2e7d32; --bad: #c62828; }
body { margin: 0; padding: 16px; background: Canvas; color: CanvasText; font: 15px/1.4 -apple-system, "Segoe UI", Roboto, Helvetica, Arial, sans-serif; }
header { display: flex; flex-wrap: wrap; gap: 8px 16px; align-items: baseline; margin-bottom: 16px; }
h1 { font-size: 1.2rem; margin: 0; }
h2 { font-size: 0.8rem; font-weight: 600; color: var(--muted); text-transform: uppercase; letter-spacing: 0.05em; margin: 0 0 8px; }
#cards { display: grid; gap: 16px; grid-template-columns: repeat(auto-fill, minmax(min(360px, 100%), 1fr)); align-items: start; }
section { border: 1px solid var(--line); border-radius: 8px; padding: 12px 16px; }
button, select { font-size: 1rem; padding: 10px 14px; border-radius: 8px; }
.actions { display: flex; flex-wrap: wrap; gap: 8px; }
dl { display: grid; grid-template-columns: max-content 1fr; gap: 4px 16px; margin: 0; }
dt { color: var(--muted); } dd { margin: 0; font-variant-numeric: tabular-nums; }
.on { color: var(--ok); font-weight: 600; } .bad { color: var(--bad); }
a { color: inherit; }
</style>
</head>
<body>
<%= erb :_debug_nav, layout: false %>
<header>
<h1>GNSS simulation</h1>
<span id="state">loading…</span>
</header>
<div id="cards">
<section>
<h2>Drive</h2>
<div class="actions">
<button type="button" id="route">Drive the trip's route</button>
<button type="button" id="random">From a random place</button>
<button type="button" id="stop">Stop</button>
</div>
<div class="actions" style="margin-top: 8px">
<select id="track" aria-label="A library track"><option value="">A library track…</option></select>
<button type="button" id="replay">Replay it</button>
</div>
<p id="hint" style="color: GrayText; font-size: 0.85rem"></p>
<label>Simulated time
<select id="speedup"></select>
</label>
<p style="color: GrayText; font-size: 0.85rem">Faster time: the car moves on sooner; a recorded trip keeps the real speeds (each fix carries the simulation's clock).</p>
</section>
<section>
<h2>Position</h2>
<dl id="position"></dl>
</section>
<section>
<h2>Trip</h2>
<dl id="trip"></dl>
</section>
<section id="outputs" hidden>
<h2>Outputs</h2>
<div id="relays"></div>
<p style="color: GrayText; font-size: 0.85rem">can.json's "outputs" (simulated: no frames sent). A click switches one (and stops its strobe); the keypad's bindings with an output do too.</p>
</section>
</div>
<script>
// The simulation's controls (lib/maptool/gnss_sim.rb, /api/sim/gnss):
// the trip's route with detours, or random trips; its time sped up.
// The map (another tab) follows it with GNSS on. Polled every second.
const $ = (id) => document.getElementById(id);
const json = async (url, options) => {
const response = await fetch(url, { cache: "no-store", ...options });
const body = await response.json().catch(() => ({}));
if (!response.ok) throw new Error(body.error || `HTTP ${response.status}`);
return body;
};
const rows = (el, pairs) => (el.innerHTML = pairs.map(([k, v]) => `<dt>${k}</dt><dd>${v ?? "—"}</dd>`).join(""));
const send = (method, body) => json("/api/sim/gnss", { method, headers: { "Content-Type": "application/json" }, body: body && JSON.stringify(body) }).catch((e) => alert(e.message)).then(refresh);
$("route").addEventListener("click", () => send("POST", { trip: true }));
$("random").addEventListener("click", () => send("POST", {}));
$("stop").addEventListener("click", () => send("DELETE"));
$("replay").addEventListener("click", () => $("track").value && send("POST", { track: $("track").value }));
// the library's tracks (a recorded one replays at its own speed; one with no times can't)
json("/api/library/tree").then((tree) => {
const tracks = [];
const walk = (node, path) => node.children.forEach((c) => (c.type === "folder" ? walk(c, c.path) : c.kinds?.includes("track") && tracks.push([c.path, [path, c.name].filter(Boolean).join(" / ")])));
walk(tree, "");
const esc = (s) => s.replace(/[&<>"]/g, (ch) => `&#${ch.charCodeAt(0)};`);
$("track").innerHTML += tracks.map(([key, label]) => `<option value="${key}">${esc(label)}</option>`).join("");
}).catch(() => {});
$("speedup").addEventListener("change", () => send("PUT", { speedup: Number($("speedup").value) }));
async function refresh() {
try {
const [sim, gnss, trip, log] = await Promise.all([
json("/api/sim/gnss"), json("/api/gnss/position"), json("/api/trip"), json("/api/trip/log"),
]);
$("state").innerHTML = sim.running ? `<span class="on">● running</span>${sim.speedup > 1 ? ` · ${sim.speedup}× time` : ""}` : sim.error ? `<span class="bad">stopped: ${sim.error}</span>` : "stopped";
if (!$("speedup").options.length) $("speedup").innerHTML = sim.speedups.map((n) => `<option value="${n}">${n}×${n === 1 ? " (real)" : ""}</option>`).join("");
$("speedup").value = String(sim.speedup);
$("route").disabled = !trip.route;
$("hint").textContent = trip.route ? `The trip's route: ${trip.route.properties.distance_km.toFixed(1)} km, with a detour now and then.` : "No trip route — plan one on the map to drive it.";
rows($("position"), gnss.available ? [
["Lat, lon", `${gnss.lat.toFixed(5)}, ${gnss.lon.toFixed(5)}`], ["Speed", gnss.speed != null ? `${Math.round(gnss.speed * 3.6)} km/h` : null],
["Course", gnss.track != null ? `${Math.round(gnss.track)}°` : null], ["Fix", gnss.mode === 3 ? "3D" : gnss.mode === 2 ? "2D" : gnss.available ? "yes" : null],
] : [["Fix", "none"]]);
rows($("trip"), [
["Stops", trip.points.length ? `${trip.points.length} (${trip.points.filter((p) => p.passed).length} passed)` : "none"],
["Recording", log.active ? `<span class="on">● ${log.folder}</span>` : "no — Start the trip in the map's Trip menu"],
["Driven", log.active ? `${(log.distance_m / 1000).toFixed(1)} km, ${log.points} points` : null],
]);
} catch (e) {
$("state").innerHTML = `<span class="bad">${e.message}</span>${/401/.test(e.message) ? ' — <a href="/login">log in</a>' : ""}`;
}
}
// The relay modules (GET /api/outputs): a button per channel, lit when on.
async function relays() {
const data = await json("/api/outputs").catch(() => null);
$("outputs").hidden = !data;
if (!data) return;
const esc = (s) => String(s).replace(/[&<>"]/g, (ch) => `&#${ch.charCodeAt(0)};`);
const by = (o) => data.bindings.filter((b) => (b.outputs || [b.output]).includes(o)).map((b) => `${b.input} (${b.mode || "toggle"})`).join(", ");
$("relays").innerHTML = data.modules.map((m) => `<p>${esc(m.name)} · node ${m.node}${m.simulated ? " · simulated" : ""}</p><div class="actions">` +
m.channels.map((c) => `<button type="button" data-output="${esc(m.name)}/${c.n}" class="${c.on ? "on" : ""}" title="${esc(by(`${m.name}.${c.n}`))}">${c.on ? "●" : "○"} ${c.n}${c.label ? ` ${esc(c.label)}` : ""}${c.level != null ? ` ${Math.round(c.level)} %` : ""}${c.strobe ? " · strobe" : ""}</button>`).join("") + "</div>").join("");
}
$("relays").addEventListener("click", (e) => {
const b = e.target.closest("button[data-output]");
if (b) json(`/api/outputs/${b.dataset.output}`, { method: "POST" }).catch((err) => alert(err.message)).then(relays);
});
refresh();
relays();
setInterval(() => { refresh(); relays(); }, 1000);
</script>
</body>
</html>
+101
View File
@@ -0,0 +1,101 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="color-scheme" content="light dark">
<title>Server status</title>
<link rel="icon" href="/icons/icon.svg" type="image/svg+xml">
<style>
:root { color-scheme: light dark; --muted: GrayText; --line: color-mix(in srgb, CanvasText 15%, transparent); --ok: #2e7d32; --bad: #c62828; }
body { margin: 0; padding: 16px; background: Canvas; color: CanvasText; font: 15px/1.4 -apple-system, "Segoe UI", Roboto, Helvetica, Arial, sans-serif; }
header { display: flex; flex-wrap: wrap; gap: 8px 16px; align-items: center; margin-bottom: 12px; }
h1 { font-size: 1.2rem; margin: 0; }
#status { color: var(--muted); font-size: 0.85rem; }
input, button { padding: 6px 10px; font-size: 0.9rem; }
/* the whole width: as many columns as fit, each at least 380px */
#cards { display: grid; gap: 12px; grid-template-columns: repeat(auto-fill, minmax(min(380px, 100%), 1fr)); align-items: start; }
details { border: 1px solid var(--line); border-radius: 8px; min-width: 0; }
summary { display: flex; gap: 10px; align-items: baseline; padding: 8px 12px; cursor: pointer; }
summary code { flex: 1; font-weight: 600; overflow-wrap: anywhere; }
summary .meta { color: var(--muted); font-size: 0.8rem; white-space: nowrap; font-variant-numeric: tabular-nums; }
.dot { width: 10px; height: 10px; border-radius: 50%; flex: none; align-self: center; background: var(--ok); }
.bad .dot { background: var(--bad); }
.bad summary code { color: var(--bad); }
pre { margin: 0; padding: 8px 12px; max-height: 420px; overflow: auto; border-top: 1px solid var(--line); font: 0.8rem/1.35 ui-monospace, SFMono-Regular, Menlo, monospace; }
code { font-family: ui-monospace, SFMono-Regular, Menlo, monospace; }
</style>
</head>
<body>
<%= erb :_debug_nav, layout: false %>
<header>
<h1>Server status</h1>
<span id="status">loading…</span>
<input id="filter" type="search" placeholder="Filter endpoints or content…">
<button id="pause" type="button">Pause</button>
</header>
<div id="cards"></div>
<script>
// Every read-only status endpoint (GET, login), its JSON, refreshed every
// REFRESH_MS. Not the check-update ones (they ask the internet) nor the
// big exports (library, sync feed).
const ENDPOINTS = [
"/api/health", "/api/update", "/api/can", "/api/gnss/position", "/api/sim/gnss",
"/api/trip", "/api/trip/log", "/api/vehicles", "/api/live", "/api/livetrack/sessions",
"/api/offline-tiles", "/api/offline-tiles/build-status", "/api/offline-regions", "/api/offline-tiles/cache",
"/api/terrain-tiles", "/api/terrain-tiles/build-status", "/api/routing-tiles", "/api/routing-tiles/build-status",
"/api/build-history", "/api/hiking-trails", "/api/kiwix", "/api/plugins",
];
const REFRESH_MS = 5000;
const cards = document.getElementById("cards");
const filter = document.getElementById("filter");
const pause = document.getElementById("pause");
const status = document.getElementById("status");
const esc = (s) => s.replace(/[&<>"]/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;" })[c]);
let paused = false;
let last = [];
async function load(url) {
const started = performance.now();
try {
const response = await fetch(url, { cache: "no-store" });
const body = await response.text();
let text = body;
try { text = JSON.stringify(JSON.parse(body), null, 2); } catch { /* not JSON */ }
return { url, ok: response.ok, code: response.status, ms: performance.now() - started, text };
} catch (e) {
return { url, ok: false, code: "—", ms: performance.now() - started, text: `request failed: ${e.message}` };
}
}
function render() {
const q = filter.value.trim().toLowerCase();
const closed = new Set([...cards.querySelectorAll("details:not([open])")].map((d) => d.dataset.url));
cards.innerHTML = last.filter((r) => !q || r.url.includes(q) || r.text.toLowerCase().includes(q)).map((r) => `
<details data-url="${r.url}" class="${r.ok ? "" : "bad"}" ${closed.has(r.url) ? "" : "open"}>
<summary><span class="dot"></span><code>${r.url}</code><span class="meta">${r.code} · ${Math.round(r.ms)} ms</span></summary>
<pre>${esc(r.text)}</pre>
</details>`).join("");
const bad = last.filter((r) => !r.ok).length;
status.textContent = `${last.length} endpoints, ${bad ? `${bad} failing` : "all OK"} · ${new Date().toLocaleTimeString()}${paused ? " · paused" : ""}`;
}
async function refresh() {
if (!paused) {
last = await Promise.all(ENDPOINTS.map(load));
render();
if (last.some((r) => r.code === 401)) status.insertAdjacentHTML("beforeend", ' · some need the login — <a href="/login">log in</a>');
}
setTimeout(refresh, REFRESH_MS);
}
filter.addEventListener("input", render);
pause.addEventListener("click", () => {
paused = !paused;
pause.textContent = paused ? "Resume" : "Pause";
render();
});
refresh();
</script>
</body>
</html>
+341
View File
@@ -0,0 +1,341 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="color-scheme" content="light dark">
<title>CAN trace</title>
<link rel="icon" href="/icons/icon.svg" type="image/svg+xml">
<style>
:root { color-scheme: light dark; --muted: GrayText; --line: color-mix(in srgb, CanvasText 15%, transparent); --bad: #c62828; }
body { margin: 0; padding: 16px; background: Canvas; color: CanvasText; font: 15px/1.4 -apple-system, "Segoe UI", Roboto, Helvetica, Arial, sans-serif; }
header { display: flex; flex-wrap: wrap; gap: 8px 16px; align-items: baseline; margin-bottom: 8px; }
h1 { font-size: 1.2rem; margin: 0; }
#status { color: var(--muted); font-size: 0.85rem; } #status.bad { color: var(--bad); }
.bar { display: flex; flex-wrap: wrap; gap: 6px 12px; align-items: center; margin-bottom: 8px; font-size: 0.9rem; }
.bar label { display: inline-flex; gap: 4px; align-items: center; white-space: nowrap; }
input[type=search] { padding: 6px 8px; font-size: 0.9rem; width: 260px; max-width: 100%; box-sizing: border-box; }
select, button { padding: 6px 10px; font-size: 0.9rem; }
.types { display: flex; flex-wrap: wrap; gap: 4px; }
.types label { padding: 3px 8px; border: 1px solid var(--line); border-radius: 12px; cursor: pointer; }
.types input { margin: 0; }
#box { max-height: calc(100vh - 220px); overflow: auto; }
table { border-collapse: collapse; font-size: 0.85rem; }
th, td { padding: 3px 12px 3px 0; text-align: left; border-bottom: 1px solid var(--line); white-space: nowrap; }
thead th { position: sticky; top: 0; background: Canvas; color: var(--muted); font-weight: 500; cursor: pointer; user-select: none; }
thead th[data-dir]::after { content: " ▲"; } thead th[data-dir="-1"]::after { content: " ▼"; }
.num { font-variant-numeric: tabular-nums; text-align: right; }
code { font: 0.85rem ui-monospace, SFMono-Regular, Menlo, monospace; }
.empty { color: var(--muted); }
.legend { color: var(--muted); font-size: 0.8rem; } .legend span { margin-right: 8px; }
/* bytes colored by what they are (SDO: command, index, subindex, payload) */
.b-cmd { color: #e53935; } .b-idx { color: #1e88e5; } .b-sub { color: #64b5f6; } .b-pay { color: #00a37a; } .b-pad { color: color-mix(in srgb, CanvasText 30%, transparent); }
.bits-cs { color: #a020f0; } .bits-x { color: color-mix(in srgb, CanvasText 30%, transparent); } .bits-n { color: #5a3fc0; font-weight: 600; } .bits-es { color: #9b8fd0; }
</style>
</head>
<body>
<%= erb :_debug_nav, layout: false %>
<header>
<h1>CAN trace</h1>
<span id="status"></span>
<span id="count" class="legend"></span>
</header>
<div class="bar">
<input id="text" type="search" placeholder="Filter: ID, data, from, meaning… (a, b = either)">
<label>Interface <select id="iface"><option value="">all</option></select></label>
<label>Node <select id="node"><option value="">all</option></select></label>
<label title="Hide frames with the same data as the last one of their ID"><input id="changes" type="checkbox"> only changes</label>
<button id="record" type="button">● Start</button> <button id="clear" type="button">Clear</button>
<button id="export-log" type="button" title="candump log: can-utils (canplayer, log2asc), SavvyCAN, python-can, Wireshark">Export .log</button>
<button id="export-csv" type="button" title="The frames shown (filter, order), decoded">Export CSV</button>
</div>
<div class="bar types" id="types"></div>
<details id="server" class="bar">
<summary>Recording on the server (MF4) <span id="server-state" class="legend"></span></summary>
<p><button id="server-toggle" type="button">● Record on the server</button>
<span class="legend">every interface, a .mf4 file each 5 min — asammdf with a DBC, CSS Electronics' tools; goes on with this page closed</span></p>
<table id="server-files"><tbody></tbody></table>
</details>
<div class="legend" style="margin-bottom: 6px"><span class="b-cmd">command</span><span class="b-idx">OD index</span><span class="b-sub">subindex</span><span class="b-pay">payload</span><span class="b-pad">unused</span>
· byte 0: <span class="bits-cs">ccs/scs</span> <span class="bits-x">t</span> <span class="bits-n">n</span> <span class="bits-es">e s</span> · SDO objects named by <a href="/can/esphome.eds" download>esphome.eds</a> · click a column to sort</div>
<div id="box"><table id="trace"><thead><tr>
<th class="num" data-key="seq" data-dir="-1">#</th><th class="num" data-key="seq">Time</th><th class="num" data-key="dt">Δ ms</th><th class="num" data-key="dtId" title="Since the last frame of the same ID">Δ ID ms</th>
<th data-key="interface">Interface</th><th data-key="id">ID</th><th data-key="data">Data</th><th data-key="from">From</th><th>Byte 0</th><th data-key="note">Meaning</th>
</tr></thead><tbody></tbody></table></div>
<script>
// Every CAN frame as it came: GET /api/can?since=<seq> once a second
// (lib/maptool/can.rb's Store keeps the last 1000), each decoded by its
// CANopen role; filtered and sorted here. Records only between Start
// and Stop (no polling meanwhile).
const TRACE_MAX = 20000; // recorded at most: then it stops (export or clear)
const RENDER_MAX = 1000; // rows in the table (the filter and sort see all)
const POLL_MS = 500; // the server keeps 5000 frames: past ~10000 frames/s some get lost (counted)
const TYPES = ["NMT", "SYNC", "EMCY", "TIME", "TPDO", "RPDO", "SDO", "Heartbeat", "Other"];
const $ = (id) => document.getElementById(id);
const esc = (s) => String(s ?? "").replace(/[&<>"]/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;" })[c]);
const hex = (n, width) => "0x" + n.toString(16).toUpperCase().padStart(width, "0");
let trace = [], logSince = 0, recording = false, lost = 0, t0 = null, sortKey = "seq", sortDir = -1; // the newest on top
const lastOf = new Map(); // "iface:id" → the previous frame of that ID
const off = new Set(); // frame types hidden
function canopenRole(id, ext) { // lib/maptool/can.rb's Can.canopen_role
if (ext) return [null, null];
const node = id & 0x7f, fn = id >> 7;
if (fn === 0) return id ? [null, null] : ["nmt", null];
if (fn === 1) return node ? ["emcy", node] : ["sync", null];
if (fn === 2) return ["time", null];
if (fn >= 3 && fn <= 10) return [`${fn % 2 ? "tpdo" : "rpdo"}${Math.floor((fn - 1) / 2)}`, node];
return [{ 0xb: "sdo_tx", 0xc: "sdo_rx", 0xe: "heartbeat" }[fn] || null, node];
}
const le = (b) => b.reduceRight((v, x) => v * 256 + x, 0);
const NMT = { 0x01: "start", 0x02: "stop", 0x80: "enter pre-operational", 0x81: "reset node", 0x82: "reset communication" };
const HB = { 0x00: "boot-up", 0x04: "stopped", 0x05: "operational", 0x7f: "pre-operational" };
const ABORT = { 0x05040000: "timeout", 0x05040001: "bad command", 0x06010000: "unsupported access", 0x06010001: "write-only", 0x06010002: "read-only",
0x06020000: "no such object", 0x06070010: "length mismatch", 0x06090011: "no such subindex", 0x06090030: "value out of range",
0x08000000: "general error", 0x08000020: "can't store", 0x08000022: "device state" };
const SDO_CLIENT = ["download segment", "download init request", "upload init request", "upload segment request", "abort", "block upload", "block download"];
// Object names: esphome-canopen's EDS (public/can/esphome.eds, loaded
// below) and its entity objects (lib/maptool/can_discovery.rb).
// ponytail: one EDS for every node; per node when they carry their own (0x1021)
const OD = {};
const META = { 1: "name", 3: "unit", 7: "min", 8: "max" };
function objectName(index, sub) {
const key = index.toString(16).padStart(4, "0");
const parent = OD[key], name = OD[`${key}sub${sub}`];
if (parent || name) return name && parent && !name.startsWith(parent) ? `${parent}: ${name}` : name || parent;
if (index === 0x3002 && sub === 1) return "TPDO layout hash";
if (index === 0x2001) return `entity ${sub} type`;
const n = (index - 0x2000) >> 4;
if (index >= 0x2010 && index <= 0x2ff0 && !(index & 0xf)) return `entity ${n} ${META[sub] || `metadata ${sub}`}`;
if (index >= 0x2011 && index <= 0x2ff1 && (index & 0xf) === 1) return `entity ${n} value`;
return "";
}
fetch("/can/esphome.eds").then((r) => (r.ok ? r.text() : "")).then((text) => {
let section = null;
for (const line of text.split(/\r?\n/)) {
const head = line.match(/^\[([0-9a-f]{4}(?:sub[0-9a-f]+)?)\]/i);
if (head) section = head[1].toLowerCase().replace(/sub([0-9a-f]+)/, (_, n) => `sub${parseInt(n, 16)}`);
else if (/^\[/.test(line)) section = null;
else if (section && line.startsWith("ParameterName=")) OD[section] = line.slice(14).trim();
}
});
const SDO_SERVER = ["upload segment", "download segment response", "upload init response", "download init response", "abort", "block download", "block upload"];
// → { cls: a class per byte, from, bits (byte 0, SDO), note }
function decode(f) {
const b = (f.data.match(/../g) || []).map((x) => parseInt(x, 16));
const [role, node] = canopenRole(f.id, f.extended);
const cls = b.map(() => "b-pay");
const pad = (from) => { for (let i = from; i < b.length; i++) cls[i] = "b-pad"; };
const value = (from, to) => { const v = le(b.slice(from, to)); return `${hex(v, 2 * (to - from))} = ${v}`; };
let from = node != null ? `node ${node}` : "", bits = "", note = role || (f.extended ? "extended" : "");
if (role === "nmt") {
from = "master"; cls[0] = "b-cmd";
note = `NMT ${NMT[b[0]] || hex(b[0] ?? 0, 2)} → ${b[1] ? `node ${b[1]}` : "all nodes"}`;
} else if (role === "heartbeat") {
note = `heartbeat: ${HB[b[0] & 0x7f] || "unknown"}`;
} else if (role === "emcy" && b.length >= 3) {
cls[0] = cls[1] = "b-cmd"; cls[2] = "b-idx";
const code = b[0] | (b[1] << 8);
note = code ? `EMCY ${hex(code, 4)}, error register ${hex(b[2], 2)}` : "EMCY: errors reset";
} else if (role === "sync") {
from = "master"; note = b.length ? `SYNC, counter ${b[0]}` : "SYNC";
} else if (role?.startsWith("rpdo")) {
from = `master → ${node}`; note = role.toUpperCase();
} else if (role?.startsWith("tpdo")) {
note = role.toUpperCase();
} else if (role === "sdo_rx" || role === "sdo_tx") {
const client = role === "sdo_rx", cs = b[0] >> 5;
from = client ? `client → ${node}` : `server ${node}`;
cls.fill("b-pad"); cls[0] = "b-cmd";
const bin = b[0].toString(2).padStart(8, "0");
const segment = cs === 0; // a data segment, either way
const withIndex = client ? [1, 2, 4].includes(cs) : [2, 3, 4].includes(cs);
bits = segment
? `<span class="bits-cs">${bin.slice(0, 3)}</span><span class="bits-x">${bin[3]}</span><span class="bits-n">${bin.slice(4, 7)}</span><span class="bits-es">${bin[7]}</span>`
: `<span class="bits-cs">${bin.slice(0, 3)}</span><span class="bits-x">${bin[3]}</span><span class="bits-n">${bin.slice(4, 6)}</span><span class="bits-es">${bin.slice(6)}</span>`;
note = (client ? SDO_CLIENT : SDO_SERVER)[cs] || `command ${cs}`;
if (withIndex && b.length >= 4) {
cls[1] = cls[2] = "b-idx"; cls[3] = "b-sub";
const index = b[1] | (b[2] << 8), name = objectName(index, b[3]);
note += ` ${hex(index, 4).slice(2)}:${b[3].toString(16).toUpperCase().padStart(2, "0")}${name ? ` (${name})` : ""}`;
}
if (cs === 4 && b.length === 8) {
for (let i = 4; i < 8; i++) cls[i] = "b-pay";
const code = le(b.slice(4)); note += ` ${hex(code, 8)}${ABORT[code] ? ` (${ABORT[code]})` : ""}`;
} else if ((client && cs === 1) || (!client && cs === 2)) { // init with data or size
const n = (b[0] >> 2) & 3, e = (b[0] >> 1) & 1, s = b[0] & 1;
if (e) { const end = s ? 8 - n : 8; for (let i = 4; i < end; i++) cls[i] = "b-pay"; note += `, expedited ${end - 4} B: ${value(4, end)}`; }
else if (s) { for (let i = 4; i < 8; i++) cls[i] = "b-pay"; note += `, segmented, ${le(b.slice(4, 8))} B`; }
} else if (segment) {
const n = (b[0] >> 1) & 7, end = 8 - n;
for (let i = 1; i < end; i++) cls[i] = "b-pay";
note += `, toggle ${(b[0] >> 4) & 1}, ${end - 1} B${b[0] & 1 ? ", last" : ""}`;
}
}
return { b, cls, from, bits, note };
}
const typeOf = (role) => !role ? "Other" : role.startsWith("sdo") ? "SDO" : role === "heartbeat" ? "Heartbeat" : role.replace(/\d$/, "").toUpperCase();
// A frame from the server, its decoding and what it's sorted and filtered by.
function add(f, prev) {
const [role, node] = canopenRole(f.id, f.extended);
const key = `${f.interface}:${f.id}`, before = lastOf.get(key);
Object.assign(f, decode(f), {
type: typeOf(role), node, cob: f.extended ? hex(f.id, 8) : hex(f.id, 3),
dt: prev ? (f.at - prev.at) * 1000 : null, dtId: before ? (f.at - before.at) * 1000 : null, same: before?.data === f.data,
});
lastOf.set(key, f);
if (!$("iface").querySelector(`option[value="${CSS.escape(f.interface)}"]`)) $("iface").add(new Option(f.interface, f.interface));
if (node != null && !$("node").querySelector(`option[value="${node}"]`)) {
const options = [...$("node").options].slice(1).concat(new Option(`${node} (${hex(node, 2)})`, node));
options.sort((a, b) => a.value - b.value).forEach((o) => $("node").add(o));
}
}
let lastRows = []; // filtered and sorted, for the CSV
function render() {
const terms = $("text").value.toLowerCase().split(",").map((t) => t.trim()).filter(Boolean);
const iface = $("iface").value, node = $("node").value, changes = $("changes").checked;
const rows = trace.filter((f) =>
!off.has(f.type) && (!iface || f.interface === iface) && (!node || String(f.node) === node) && (!changes || !f.same) &&
(!terms.length || terms.some((t) => [f.cob, f.data, f.from, f.note, f.type].join(" ").toLowerCase().includes(t))));
if (sortKey === "seq") {
if (sortDir === -1) rows.reverse();
} else {
rows.sort((a, b) => {
const x = a[sortKey], y = b[sortKey];
const c = x == null ? 1 : y == null ? -1 : typeof x === "number" ? x - y : String(x).localeCompare(String(y));
return c * sortDir || a.seq - b.seq;
});
}
const ms = (v) => (v == null ? "" : v.toFixed(1));
const shown = rows.length <= RENDER_MAX ? rows : sortKey === "seq" && sortDir === 1 ? rows.slice(-RENDER_MAX) : rows.slice(0, RENDER_MAX);
$("trace").tBodies[0].innerHTML = shown.length ? shown.map((f) => {
const data = f.b.map((x, i) => `<span class="${f.cls[i]}">${x.toString(16).toUpperCase().padStart(2, "0")}</span>`).join(" ");
return `<tr><td class="num">${f.seq}</td><td class="num">${(f.at - t0).toFixed(4)}</td><td class="num">${ms(f.dt)}</td><td class="num">${ms(f.dtId)}</td><td>${esc(f.interface)}</td><td><code>${f.cob}</code>${f.extended ? " ext" : ""}</td><td><code>${data}</code></td><td>${esc(f.from)}</td><td><code>${f.bits}</code></td><td>${esc(f.note)}</td></tr>`;
}).join("") : `<tr><td class="empty" colspan="10">${trace.length ? "No frame matches." : "No frame yet."}</td></tr>`;
$("count").textContent = !trace.length ? "" : (rows.length > shown.length ? `showing ${shown.length} of ${rows.length} matching, ` : `${rows.length} matching of `) +
`${trace.length} recorded${lost ? ` · ${lost} lost (bus faster than the polling)` : ""}`;
lastRows = rows;
}
async function fetchLog(since) {
const response = await fetch(`/api/can?since=${since}`, { cache: "no-store" });
if (response.status === 401) throw new Error("not logged in — log in on the map first");
if (!response.ok) throw new Error(`HTTP ${response.status}`);
const data = await response.json();
if (!data.available) throw new Error("CAN is off: no data/can.json on this server");
return data;
}
async function poll() {
if (!recording) return;
const status = $("status");
try {
const data = await fetchLog(logSince);
if (data.log_seq < logSince) logSince = 0; // the server restarted: its frames from the start
if (data.log.length && logSince && data.log[0].seq > logSince + 1) lost += data.log[0].seq - logSince - 1;
status.className = "";
status.textContent = `● recording · ${new Date().toLocaleTimeString()}`;
if (data.log.length) {
t0 ??= data.log[0].at;
for (const f of data.log.slice(0, TRACE_MAX - trace.length)) { add(f, trace.at(-1)); trace.push(f); }
logSince = data.log.at(-1).seq;
if (trace.length >= TRACE_MAX) { stop(); status.textContent = `stopped: ${TRACE_MAX} frames recorded — export or clear`; }
render();
}
} catch (e) {
status.className = "bad";
status.textContent = `can't record: ${e.message}`;
} finally {
if (recording) setTimeout(poll, POLL_MS);
}
}
// From now on: the server's frames after its latest.
async function start() {
try {
logSince = (await fetchLog(Number.MAX_SAFE_INTEGER)).log_seq;
} catch (e) {
$("status").className = "bad";
$("status").textContent = `can't record: ${e.message}`;
return;
}
recording = true;
$("record").textContent = "■ Stop";
poll();
}
function stop() {
recording = false;
$("record").textContent = "● Start";
$("status").textContent = "stopped";
}
function download(name, text, type) {
const a = document.createElement("a");
a.href = URL.createObjectURL(new Blob([text], { type }));
a.download = name;
a.click();
setTimeout(() => URL.revokeObjectURL(a.href), 1000);
}
const fileName = (ext) => `can-trace-${new Date(trace[0].at * 1000).toISOString().slice(0, 19).replace(/[-:]/g, "").replace("T", "-")}.${ext}`;
const csvField = (v) => (/[",\n]/.test(String(v ?? "")) ? `"${String(v).replace(/"/g, '""')}"` : String(v ?? ""));
// The server's recorder (GET/POST/DELETE /api/can/recording), every 5 s.
let server = null;
const size = (b) => (b > 1e6 ? `${(b / 1e6).toFixed(1)} MB` : `${Math.ceil(b / 1e3)} kB`);
async function pollServer() {
try {
const response = await fetch("/api/can/recording", { cache: "no-store" });
if (!response.ok) throw new Error(`HTTP ${response.status}`);
server = await response.json();
$("server-state").textContent = !server.available ? "· CAN is off on this server" : server.running
? `· ● recording since ${new Date(server.started_at * 1000).toLocaleTimeString()}` : server.error ? `· ${server.error}` : "· stopped";
$("server-toggle").textContent = server.running ? "■ Stop recording on the server" : "● Record on the server";
$("server-toggle").disabled = !server.available;
$("server-files").tBodies[0].innerHTML = server.files.length ? server.files.map((f) =>
`<tr><td><a href="/api/can/recordings/${encodeURIComponent(f.name)}" download>${esc(f.name)}</a></td><td class="num">${size(f.size)}</td><td>${new Date(f.at * 1000).toLocaleString()}</td></tr>`).join("")
: `<tr><td class="empty">No recording yet.</td></tr>`;
} catch (e) {
$("server-state").textContent = `· can't reach the server: ${e.message}`;
}
}
$("server-toggle").addEventListener("click", async () => {
$("server-toggle").disabled = true;
const response = await fetch("/api/can/recording", { method: server?.running ? "DELETE" : "POST" });
if (!response.ok) $("server-state").textContent = `· ${(await response.json().catch(() => ({}))).error || `HTTP ${response.status}`}`;
else await pollServer();
$("server-toggle").disabled = false;
});
pollServer();
setInterval(pollServer, 5000);
$("record").addEventListener("click", () => (recording ? stop() : start()));
// candump -l's format: every recorded frame, in order
$("export-log").addEventListener("click", () => trace.length && download(fileName("log"),
trace.map((f) => `(${f.at.toFixed(6)}) ${f.interface} ${f.extended ? f.id.toString(16).toUpperCase().padStart(8, "0") : f.id.toString(16).toUpperCase().padStart(3, "0")}#${f.data.toUpperCase()}\n`).join(""), "text/plain"));
$("export-csv").addEventListener("click", () => trace.length && download(fileName("csv"),
[["seq", "time_s", "unix_time", "dt_ms", "dt_id_ms", "interface", "id", "extended", "dlc", "data", "type", "node", "from", "meaning"].join(",")].concat(lastRows.map((f) =>
[f.seq, (f.at - t0).toFixed(6), f.at.toFixed(6), f.dt?.toFixed(3), f.dtId?.toFixed(3), f.interface, f.cob, f.extended, f.b.length, f.b.map((x) => x.toString(16).toUpperCase().padStart(2, "0")).join(" "), f.type, f.node, f.from, f.note].map(csvField).join(","))).join("\n") + "\n", "text/csv"));
$("types").innerHTML = TYPES.map((t) => `<label><input type="checkbox" value="${t}" checked> ${t}</label>`).join("");
$("types").addEventListener("change", (e) => { e.target.checked ? off.delete(e.target.value) : off.add(e.target.value); render(); });
for (const id of ["text", "iface", "node", "changes"]) $(id).addEventListener("input", render);
$("trace").tHead.addEventListener("click", (e) => {
const th = e.target.closest("th[data-key]");
if (!th) return;
sortDir = th.dataset.key === sortKey && th.hasAttribute("data-dir") ? -sortDir : 1;
sortKey = th.dataset.key;
for (const h of $("trace").tHead.querySelectorAll("th")) h.removeAttribute("data-dir");
th.dataset.dir = sortDir;
render();
});
$("clear").addEventListener("click", () => { trace = []; t0 = null; lost = 0; lastOf.clear(); render(); });
render();
$("status").textContent = "stopped — Start records the frames from then on";
</script>
</body>
</html>