Compare commits
54
Commits
e92f01db12
..
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5998fdfe88 | ||
|
|
462303eed6 | ||
|
|
cba14300b5 | ||
|
|
f85785c61d | ||
|
|
59f64f2f97 | ||
|
|
88fa2d27a3 | ||
|
|
82a728e024 | ||
|
|
e82b2236b5 | ||
|
|
d6af65f4ef | ||
|
|
38fb06853e | ||
|
|
bf90f4cf23 | ||
|
|
87d7bd2463 | ||
|
|
5e31dfaba9 | ||
|
|
a6158f4083 | ||
|
|
ad975bcf62 | ||
|
|
f15fbef746 | ||
|
|
f981b80599 | ||
|
|
21ad6c0c21 | ||
|
|
1ee79fff66 | ||
|
|
d39e3b5edd | ||
|
|
f73badd107 | ||
|
|
285af64a65 | ||
|
|
91fa9cec41 | ||
|
|
fc8564fe3b | ||
|
|
d559f76b4a | ||
|
|
258d35a7a1 | ||
|
|
f161243c61 | ||
|
|
97d1bda09c | ||
|
|
0a5548cd8f | ||
|
|
60d7c825fc | ||
|
|
712c6bf7ad | ||
|
|
b1a5d47859 | ||
|
|
7204355510 | ||
|
|
7fdc0114e6 | ||
|
|
7901d75ff1 | ||
|
|
3325ff5d17 | ||
|
|
c101c7441f | ||
|
|
27b77790c4 | ||
|
|
bd689faa93 | ||
|
|
0c809b3e2b | ||
|
|
7d72e9eb63 | ||
|
|
809e88ab1a | ||
|
|
0eb9d05cdc | ||
|
|
9b797fd48c | ||
|
|
7fcac61c99 | ||
|
|
07a4d363ec | ||
|
|
12b4ac6725 | ||
|
|
8c999919b8 | ||
|
|
bfa70c1d17 | ||
|
|
a11a71dc89 | ||
|
|
d58f7efc41 | ||
|
|
27313b3101 | ||
|
|
e62eb90dc7 | ||
|
|
4c58c9351f |
No files matched your search
@@ -5,3 +5,4 @@ data
|
||||
.ruby-lsp
|
||||
.env
|
||||
node_modules
|
||||
can-recorder/target
|
||||
@@ -68,3 +68,6 @@
|
||||
/REVISION
|
||||
|
||||
node_modules/
|
||||
|
||||
# can-recorder's cargo build
|
||||
/can-recorder/target/
|
||||
+11
-1
@@ -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
@@ -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
|
||||
|
||||
@@ -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
|
||||
@@ -167,10 +254,28 @@ already reaches the home MQTT broker (`mqtt_ext`) from ESPHome nodes in `~/espho
|
||||
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
|
||||
@@ -183,6 +288,9 @@ already reaches the home MQTT broker (`mqtt_ext`) from ESPHome nodes in `~/espho
|
||||
*** [ ] 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`
|
||||
@@ -202,13 +310,27 @@ already reaches the home MQTT broker (`mqtt_ext`) from ESPHome nodes in `~/espho
|
||||
*** [ ] IMU every 100–200 ms (the node reads it every 5 s today) and levelling done by the
|
||||
node itself, set by an SDO write from a button in `/can.html` — design in home-gitops
|
||||
`docs/canopen-nodes.adoc` ("Nulovanie náklonu a rýchlosť IMU")
|
||||
* [x] Dead reckoning in a tunnel (`App.gnss_position`): no fix for 3 s (or `mode` < 2) on the
|
||||
trip's route — the position carried along it, `estimated: true`, a grey arrow; by the CAN
|
||||
signal `vehicle.speed` (m/s) when there is one, the average speed of the last ~20 s before
|
||||
otherwise; up to 10 min (2026-12-01). The SIM7600E's GNSS has no DR of its own
|
||||
** [ ] `vehicle.speed` off the car (OBD/CAN) into `can.json`; its scale calibrated against GNSS
|
||||
** [ ] Off the route: the gyro's yaw rate (the IMU node) or the compass, with map matching
|
||||
** [ ] Back out of the tunnel: the first fixes taken only once consistent (HDOP, the jump from
|
||||
the estimate); the trip log keeps a straight line through the tunnel for now
|
||||
* [ ] 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
|
||||
** [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
|
||||
@@ -219,26 +341,50 @@ already reaches the home MQTT broker (`mqtt_ext`) from ESPHome nodes in `~/espho
|
||||
(`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
|
||||
** [ ] Speed limits that aren't on the edge: `maxspeed:conditional` (time, wet), variable
|
||||
** [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)
|
||||
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
|
||||
*** [ ] 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
|
||||
** [ ] Turn-by-turn: the next maneuver big (arrow, distance, street), voice
|
||||
(`speechSynthesis`), the route ahead highlighted / the driven part greyed
|
||||
*** [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
|
||||
*** [ ] Lane guidance before motorway exits (lanes several maneuvers ahead), bigger on the
|
||||
driving screen
|
||||
** [ ] Traffic signals with no route: around the position (Valhalla `locate` or the offline
|
||||
PBF), and only for the direction driven (`traffic_signals:direction`)
|
||||
** [ ] 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
|
||||
** [ ] `locate()` scans the whole route each fix — a window around the last hit on long routes
|
||||
*** [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)
|
||||
@@ -247,18 +393,55 @@ already reaches the home MQTT broker (`mqtt_ext`) from ESPHome nodes in `~/espho
|
||||
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
|
||||
*** [ ] 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 (today's, `dashboard.js`)
|
||||
*** [ ] 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
|
||||
*** [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: the browser can't be cast there, only a native app — a small one with
|
||||
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. Testable without the car: the tablet runs the
|
||||
Android Auto head unit emulation (DHU)
|
||||
** [ ] 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
|
||||
@@ -267,9 +450,13 @@ already reaches the home MQTT broker (`mqtt_ext`) from ESPHome nodes in `~/espho
|
||||
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)
|
||||
*** [ ] Replay a library track (GPX/FIT with times) instead, at its own speed
|
||||
* [ ] While following a planned route: the route ahead highlighted, distance to the next
|
||||
maneuver from Valhalla's directions
|
||||
*** [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
|
||||
|
||||
@@ -279,8 +466,9 @@ Planning in the NPS look, driving in the cockpit look, joined by the Unigrid bla
|
||||
. [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
|
||||
. [ ] The route line magenta while it's navigated (follow mode), blue while planning; the next
|
||||
waypoint and maneuver magenta on the map too
|
||||
. [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
|
||||
@@ -289,26 +477,89 @@ Planning in the NPS look, driving in the cockpit look, joined by the Unigrid bla
|
||||
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)
|
||||
. [ ] Night: instruments dimmed (brightness) on top of the inverted UI; daylight: a full-opacity
|
||||
bezel preset for sun on the screen
|
||||
. [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
|
||||
|
||||
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
|
||||
|
||||
* [ ] Level gauge from IMU (ESP32/RPi) — camper tilt, wheel-chock leveling calculation
|
||||
* [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
|
||||
|
||||
@@ -319,12 +570,26 @@ 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 (a portable ~16" USB touchscreen, the co-driver's —
|
||||
@@ -347,8 +612,9 @@ 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, 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
|
||||
@@ -364,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)
|
||||
@@ -4,6 +4,7 @@ require "oauth2"
|
||||
require "securerandom"
|
||||
require "zip"
|
||||
require "stringio"
|
||||
require "tempfile"
|
||||
require_relative "lib/maptool/gpx"
|
||||
require_relative "lib/maptool/fit"
|
||||
require_relative "lib/maptool/gpx_store"
|
||||
@@ -13,8 +14,15 @@ require_relative "lib/maptool/routing"
|
||||
require_relative "lib/maptool/mqtt_client"
|
||||
require_relative "lib/maptool/can"
|
||||
require_relative "lib/maptool/can_discovery"
|
||||
require_relative "lib/maptool/can_recorder"
|
||||
require_relative "lib/maptool/keypad"
|
||||
require_relative "lib/maptool/outputs"
|
||||
require_relative "lib/maptool/can_time"
|
||||
require_relative "lib/maptool/gnss_sim"
|
||||
require_relative "lib/maptool/trip"
|
||||
require_relative "lib/maptool/trip_log"
|
||||
require_relative "lib/maptool/trip_days"
|
||||
require_relative "lib/maptool/link_place"
|
||||
require_relative "lib/maptool/updater"
|
||||
require_relative "lib/maptool/sync"
|
||||
require "ipaddr"
|
||||
@@ -23,6 +31,7 @@ require_relative "lib/maptool/livetrack_store"
|
||||
require_relative "lib/maptool/livetrack_client"
|
||||
require_relative "lib/maptool/kiwix"
|
||||
require_relative "lib/maptool/plugins"
|
||||
require_relative "lib/maptool/corridor"
|
||||
require_relative "lib/maptool/pmtiles_builder"
|
||||
require_relative "lib/maptool/search"
|
||||
|
||||
@@ -170,6 +179,7 @@ module Maptool
|
||||
# above can't. Checked after PLUGINS_DIR (see Plugins.list/run), so a
|
||||
# same-named private plugin never shadows the built-in one.
|
||||
PLUGINS_DIRS = [PLUGINS_DIR, File.join(DATA_DIR, "plugins")].freeze
|
||||
PLUGIN_SETTINGS = File.join(DATA_DIR, "plugin_settings.json")
|
||||
|
||||
# Shared secret for the Garmin LiveTrack webhook (a Google Apps Script
|
||||
# watching Gmail for LiveTrack emails, see docs/deployment.adoc) — not a
|
||||
@@ -389,27 +399,62 @@ module Maptool
|
||||
GNSS_LATEST_MUTEX = Mutex.new
|
||||
COURSE_MIN_M = 5 # fixes closer than this: too noisy for a course
|
||||
COURSE_MIN_SPEED = 1.5 # m/s: slower, the last course stays
|
||||
SPEED_AVG_S = 20.0
|
||||
VEHICLE_SPEED_FRESH_S = 2 # older: no CAN speed, the average held
|
||||
|
||||
# The car's speed off CANopen (signal vehicle.speed, m/s): the meters
|
||||
# driven since the last fix (dr_m), for dead reckoning in a tunnel.
|
||||
def self.vehicle_speed_update(speed, at: Time.now.to_f)
|
||||
GNSS_LATEST_MUTEX.synchronize do
|
||||
last, last_at = GNSS_LATEST.values_at(:vehicle_speed, :vehicle_speed_at)
|
||||
if last && GNSS_LATEST[:dr_m] && at - last_at < VEHICLE_SPEED_FRESH_S
|
||||
GNSS_LATEST[:dr_m] += last * (at - last_at)
|
||||
end
|
||||
GNSS_LATEST[:vehicle_speed] = speed.to_f
|
||||
GNSS_LATEST[:vehicle_speed_at] = at
|
||||
end
|
||||
end
|
||||
|
||||
# Where every GNSS fix lands (the node over CAN, the simulation): into
|
||||
# GNSS_LATEST, with the course over ground (track, °) worked out from
|
||||
# the fix COURSE_MIN_M back when the receiver sends none — following
|
||||
# heading-up from behind (followPosition, gnss.js) turns by it.
|
||||
def self.gnss_update(gnss, at: Time.now.to_f)
|
||||
GNSS_LATEST_MUTEX.synchronize do
|
||||
fix = GNSS_LATEST_MUTEX.synchronize do
|
||||
GNSS_LATEST.merge!(gnss)
|
||||
next unless gnss.key?(:lat) || gnss.key?(:lon)
|
||||
# a receiver that lost its fix (a tunnel) and repeats the last one
|
||||
next if GNSS_LATEST[:mode] && GNSS_LATEST[:mode].to_i < 2
|
||||
|
||||
GNSS_LATEST[:received_at] = at
|
||||
next if gnss.key?(:track)
|
||||
|
||||
position = GNSS_LATEST.values_at(:lon, :lat)
|
||||
from = GNSS_LATEST[:course_from]
|
||||
if from.nil? || (GNSS_LATEST[:speed] || 0) < COURSE_MIN_SPEED
|
||||
GNSS_LATEST[:course_from] = position
|
||||
elsif GnssSim.meters(from, position) >= COURSE_MIN_M
|
||||
GNSS_LATEST[:track] = GnssSim.bearing(from, position).round(1)
|
||||
GNSS_LATEST[:course_from] = position
|
||||
# the average speed of the last ~SPEED_AVG_S (the speed a tunnel was
|
||||
# entered at), and the car's own odometer since this fix reset
|
||||
last_at = GNSS_LATEST[:received_at]
|
||||
if gnss[:speed] && last_at && at > last_at
|
||||
k = 1 - Math.exp(-(at - last_at) / SPEED_AVG_S)
|
||||
GNSS_LATEST[:speed_avg] = (GNSS_LATEST[:speed_avg] || gnss[:speed]) * (1 - k) + gnss[:speed] * k
|
||||
end
|
||||
GNSS_LATEST[:dr_m] = 0.0
|
||||
GNSS_LATEST[:received_at] = at
|
||||
unless gnss.key?(:track)
|
||||
position = GNSS_LATEST.values_at(:lon, :lat)
|
||||
from = GNSS_LATEST[:course_from]
|
||||
if from.nil? || (GNSS_LATEST[:speed] || 0) < COURSE_MIN_SPEED
|
||||
GNSS_LATEST[:course_from] = position
|
||||
elsif GnssSim.meters(from, position) >= COURSE_MIN_M
|
||||
GNSS_LATEST[:track] = GnssSim.bearing(from, position).round(1)
|
||||
GNSS_LATEST[:course_from] = position
|
||||
end
|
||||
end
|
||||
GNSS_LATEST.dup
|
||||
end
|
||||
return unless fix && fix[:lat] && fix[:lon]
|
||||
|
||||
# a fix's own time when it has one (the simulation's clock, sped up)
|
||||
TRIP_LOG.record(fix[:lon], fix[:lat], fix[:alt], gnss[:time].is_a?(Numeric) ? gnss[:time] : at) if TRIP_LOG.active?
|
||||
# off the shared trip's route: routed again from here (TripStore#follow)
|
||||
|
||||
TRIP_STORE.follow([fix[:lon], fix[:lat]], speed: fix[:speed], hdop: fix[:hdop]) do |locations, vehicle, avoid|
|
||||
Routing.route(VALHALLA_URL, locations, Routing.vehicle(DATA_DIR, vehicle), avoid.transform_keys(&:to_s))
|
||||
end
|
||||
end
|
||||
|
||||
@@ -427,6 +472,113 @@ module Maptool
|
||||
warn "can: #{CAN_CONFIG_PATH}: #{e.message} — CAN off"
|
||||
[nil, nil]
|
||||
end
|
||||
# can.json's "actions": SDO writes /can.html offers beside their node (Can::Sdo::Action).
|
||||
CAN_ACTIONS = (CAN_CONFIG ? CAN_CONFIG.fetch("actions", []) : []).filter_map do |action|
|
||||
Can::Sdo::Action.parse(action)
|
||||
rescue StandardError => e
|
||||
warn "can: #{CAN_CONFIG_PATH}: action #{action.inspect}: #{e.message} — skipped"
|
||||
nil
|
||||
end
|
||||
# can.json's "keypads": keys and knobs as channels for the screen
|
||||
# profile's bindings (Keypad).
|
||||
KEYPAD = begin
|
||||
k = CAN_CONFIG&.dig("keypads")
|
||||
k && !k.empty? ? Keypad.new(k) : nil
|
||||
rescue StandardError => e
|
||||
warn "can: #{CAN_CONFIG_PATH}: keypads: #{e.message} — no keypads"
|
||||
nil
|
||||
end
|
||||
CAN_DECODER.set_node(:keypad, KEYPAD.signals) if KEYPAD
|
||||
|
||||
# Frames maptool puts on the bus (LEDs, outputs, TIME): one socket on
|
||||
# the first interface, opened when first needed, again after an error.
|
||||
CAN_TX_MUTEX = Mutex.new
|
||||
def self.can_send(frame)
|
||||
CAN_TX_MUTEX.synchronize do
|
||||
@can_tx ||= Can.open(CAN_CONFIG.fetch("interfaces").first)
|
||||
@can_tx.write(frame.pack)
|
||||
rescue SocketError, SystemCallError
|
||||
@can_tx&.close
|
||||
@can_tx = nil
|
||||
raise
|
||||
end
|
||||
end
|
||||
|
||||
# can.json's "outputs": relay modules driven by the profile's bindings (Outputs).
|
||||
OUTPUTS = begin
|
||||
o = CAN_CONFIG&.dig("outputs")
|
||||
o && !o.empty? ? Outputs.new(o) { |frame| App.can_send(frame) } : nil
|
||||
rescue StandardError => e
|
||||
warn "can: #{CAN_CONFIG_PATH}: outputs: #{e.message} — no outputs"
|
||||
nil
|
||||
end
|
||||
|
||||
# CANopen TIME while nobody else sends it (can.json's "time": false: never).
|
||||
CAN_TIME = CAN_CONFIG && CAN_CONFIG.fetch("time", true) && !test? ? Can::TimeProducer.new { |f| App.can_send(f) } : nil
|
||||
|
||||
# The keypads' bindings: the ones saved in /keypad.html (data/drive/
|
||||
# bindings.json, this car's), else the screen profile's defaults; read
|
||||
# again when the file changes. The browser takes them from GET /api/keypad/bindings.
|
||||
DRIVE_PROFILE_PATH = File.join(__dir__, "public", "drive", "road.json")
|
||||
BINDINGS_PATH = File.join(DATA_DIR, "drive", "bindings.json")
|
||||
def self.bindings
|
||||
path = File.exist?(BINDINGS_PATH) ? BINDINGS_PATH : DRIVE_PROFILE_PATH
|
||||
key = [path, File.mtime(path)]
|
||||
@bindings = [key, JSON.parse(File.read(path)).fetch("bindings", [])] unless @bindings&.first == key
|
||||
@bindings.last
|
||||
rescue StandardError => e
|
||||
warn "drive bindings: #{e.message}"
|
||||
[]
|
||||
end
|
||||
|
||||
BINDING_KEYS = %w[input action menu output outputs mode pulse_s period_s step led led_on].freeze
|
||||
# A saved list's check: each an input, an action / menu or an output, known modes and colours.
|
||||
def self.check_bindings(list)
|
||||
raise ArgumentError, "bindings: a list" unless list.is_a?(Array)
|
||||
|
||||
list.map do |b|
|
||||
raise ArgumentError, "a binding: an object" unless b.is_a?(Hash)
|
||||
|
||||
b = b.slice(*BINDING_KEYS).reject { |_, v| v.nil? || v == "" }
|
||||
raise ArgumentError, "a binding without an input" unless b["input"].is_a?(String) && b["input"].include?(".")
|
||||
raise ArgumentError, "#{b['input']}: unknown mode #{b['mode']}" if b["mode"] && !Outputs::MODES.include?(b["mode"])
|
||||
%w[led led_on].each { |k| raise ArgumentError, "#{b['input']}: unknown colour #{b[k]}" if b[k] && !Keypad::COLORS.key?(b[k]) }
|
||||
if b["mode"] == "positions"
|
||||
raise ArgumentError, "#{b['input']}: positions need outputs" unless b["outputs"].is_a?(Array) && b["outputs"].any? && b["outputs"].all?(String)
|
||||
|
||||
b.delete("output")
|
||||
else
|
||||
b.delete("outputs")
|
||||
end
|
||||
%w[pulse_s period_s step].each { |k| b[k] = Float(b[k]) if b[k] }
|
||||
b
|
||||
end
|
||||
end
|
||||
|
||||
def self.keypads_present
|
||||
nodes = CAN_STORE.snapshot[:nodes]
|
||||
KEYPAD ? KEYPAD.devices.select { |d| (seen = nodes.dig(d.heartbeat_node, :heartbeat_at)) && Time.now.to_f - seen < Keypad::PRESENT_S } : []
|
||||
end
|
||||
|
||||
# A keypad's key LEDs: the screen's colours (PUT /api/keypad/leds) with
|
||||
# the keys bound to outputs on top (their "led" while on, dark off),
|
||||
# sent when they change.
|
||||
KEYPAD_SCREEN_LEDS = {}
|
||||
def self.keypad_leds_frames(device)
|
||||
on = (KEYPAD_SCREEN_LEDS.dig(device.name, "on") || {}).dup
|
||||
if OUTPUTS
|
||||
bindings.each do |b|
|
||||
next unless Outputs.outputs_of(b).any? && b["input"].to_s.start_with?("#{device.name}.")
|
||||
|
||||
on[b["input"].delete_prefix("#{device.name}.")] = OUTPUTS.active?(b) ? b.fetch("led", "red") : nil
|
||||
end
|
||||
end
|
||||
KEYPAD.led_frames(device.name, on, KEYPAD_SCREEN_LEDS.dig(device.name, "blink"))
|
||||
end
|
||||
|
||||
# The bus recorded on the server into MF4 files (/trace.html, can-recorder/).
|
||||
CAN_RECORDER = Can::Recorder.new(File.join(DATA_DIR, "can_rec"), CAN_CONFIG ? CAN_CONFIG.fetch("interfaces", []) : [])
|
||||
at_exit { CAN_RECORDER.stop }
|
||||
# Simulated driving (lib/maptool/gnss_sim.rb) in place of the GNSS node.
|
||||
GNSS_SIM = GnssSim.new(VALHALLA_URL)
|
||||
|
||||
@@ -440,7 +592,10 @@ module Maptool
|
||||
end
|
||||
CAN_CONFIG.fetch("interfaces", []).each do |interface|
|
||||
Thread.new do
|
||||
Can.listen(interface, decoder: decoder, store: CAN_STORE, start_nodes: CAN_CONFIG["nmt_start"]) do |values|
|
||||
Can.listen(interface, decoder: decoder, store: CAN_STORE, start_nodes: CAN_CONFIG["nmt_start"], on_frame: ->(f) { CAN_TIME&.heard(f) }) do |values|
|
||||
App.vehicle_speed_update(values["vehicle.speed"]) if values["vehicle.speed"]
|
||||
events = KEYPAD&.update(values) || []
|
||||
events.each { |e| OUTPUTS.input(e, App.bindings) } if OUTPUTS
|
||||
gnss = values.filter_map { |name, value| [name.delete_prefix("gnss.").to_sym, value] if name.start_with?("gnss.") }.to_h
|
||||
next if gnss.empty? || GNSS_SIM.running?
|
||||
|
||||
@@ -450,6 +605,41 @@ module Maptool
|
||||
end
|
||||
end
|
||||
|
||||
# Every 100 ms: the outputs (pulses ending, their state again for the
|
||||
# modules' watchdog), a keypad gone silent letting go of what it held,
|
||||
# the keypads' LEDs when they changed; every second the TIME.
|
||||
if CAN_CONFIG && !test? && (OUTPUTS || KEYPAD || CAN_TIME)
|
||||
Thread.new do
|
||||
was_present = []
|
||||
leds_sent = {}
|
||||
time_at = 0
|
||||
loop do
|
||||
begin
|
||||
OUTPUTS&.tick
|
||||
present = App.keypads_present
|
||||
(was_present.map(&:name) - present.map(&:name)).each { |name| OUTPUTS&.keypad_lost(name) }
|
||||
leds_sent = {} if present != was_present
|
||||
was_present = present
|
||||
present.select { |d| d.protocol == "pkp" }.each do |d|
|
||||
frames = App.keypad_leds_frames(d)
|
||||
next if leds_sent[d.name] == frames.map(&:data)
|
||||
|
||||
frames.each { |f| App.can_send(f) }
|
||||
leds_sent[d.name] = frames.map(&:data)
|
||||
end
|
||||
if CAN_TIME && Time.now.to_f - time_at >= Can::TimeProducer::INTERVAL_S
|
||||
time_at = Time.now.to_f
|
||||
CAN_TIME.tick
|
||||
end
|
||||
rescue StandardError => e
|
||||
warn "can tick: #{e.message}" unless e.message == @last_tick_error
|
||||
@last_tick_error = e.message
|
||||
end
|
||||
sleep Outputs::REPEAT_S
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
# Live data off the home MQTT broker (MQTT_URL), polled by the frontend
|
||||
# from /api/live like GNSS above — the "Tracker" and "ITS-G5" overlays:
|
||||
# the LTE GNSS tracker's position and USB power (+ its trail, optionally
|
||||
@@ -488,11 +678,31 @@ module Maptool
|
||||
erb :symbols, layout: false
|
||||
end
|
||||
|
||||
# The GNSS simulation's controls (its API below, login).
|
||||
get "/sim.html" do
|
||||
erb :sim, layout: false
|
||||
end
|
||||
|
||||
# Every status endpoint on one full-screen page (they need the login).
|
||||
get "/status.html" do
|
||||
erb :status, layout: false
|
||||
end
|
||||
|
||||
# CANopen diagnostics (polls GET /api/can, which needs the login).
|
||||
get "/can.html" do
|
||||
erb :can, layout: false
|
||||
end
|
||||
|
||||
# The keypads' bindings, edited (after the Design canvas' GridBinding).
|
||||
get "/keypad.html" do
|
||||
erb :keypad, layout: false
|
||||
end
|
||||
|
||||
# Every CAN frame as it came, decoded (polls GET /api/can?since=).
|
||||
get "/trace.html" do
|
||||
erb :trace, layout: false
|
||||
end
|
||||
|
||||
# A share to the installed app normally never reaches the server: the
|
||||
# service worker (public/sw.js) takes the POST, parks the files and
|
||||
# opens the app. Only lands here if no worker is running yet — back to
|
||||
@@ -511,6 +721,7 @@ module Maptool
|
||||
require_login!
|
||||
halt json(enabled: false) unless SELF_UPDATE
|
||||
|
||||
Updater.reset! if params[:fresh] # "Check now": past the 10 min cache
|
||||
latest = Updater.latest(GITEA_URL, UPDATE_REPO)
|
||||
available = !!latest && latest[:ci] == "success" && latest[:sha] && !latest[:sha].start_with?(REVISION)
|
||||
json enabled: true, current: REVISION, latest: latest&.dig(:sha)&.slice(0, 7), ci: latest&.dig(:ci),
|
||||
@@ -721,6 +932,113 @@ module Maptool
|
||||
# {points: [{lngLat, name, nav}], vehicle, avoid, editing}, routed here.
|
||||
# Logged in only — it's this server's own itinerary.
|
||||
TRIP_STORE = TripStore.new(File.join(DATA_DIR, "trip.json"))
|
||||
# The trip recorded (lib/maptool/trip_log.rb): GET its state (?since=N:
|
||||
# the line's coordinates from N on), POST {"name"} starts it — a
|
||||
# Trips/<date> <name> folder with the planned route and its stops —
|
||||
# DELETE ends it. Every fix goes in meanwhile (App.gnss_update).
|
||||
TRIP_LOG = TripLog.new(File.join(DATA_DIR, "trip_log"), library: LIBRARY)
|
||||
|
||||
get "/api/trip/log" do
|
||||
require_login!
|
||||
json TRIP_LOG.status(since: params[:since])
|
||||
end
|
||||
|
||||
post "/api/trip/log" do
|
||||
require_login!
|
||||
name = JSON.parse(request.body.read)["name"].to_s
|
||||
trip = TRIP_STORE.get
|
||||
json folder: TRIP_LOG.start(name, plan: trip[:route], stops: trip[:points])
|
||||
rescue JSON::ParserError
|
||||
halt 400, json(error: "invalid JSON")
|
||||
rescue ArgumentError => e
|
||||
halt 409, json(error: e.message)
|
||||
end
|
||||
|
||||
delete "/api/trip/log" do
|
||||
require_login!
|
||||
json folder: TRIP_LOG.stop
|
||||
end
|
||||
|
||||
# The recording's days (lib/maptool/trip_days.rb) — the running trip's, or
|
||||
# the last one's: totals, the days with what cut them, and (?track=1) the
|
||||
# line as [lon, lat, t] for picking a piece on the map.
|
||||
get "/api/trip/log/days" do
|
||||
require_login!
|
||||
rec = TRIP_LOG.recording
|
||||
halt 404, json(error: "no trip recorded") unless rec && rec[:points].size >= 2
|
||||
|
||||
points = rec[:points]
|
||||
days = TripDays.days(points, TripDays.cuts(points, hand: rec[:hand], joined: rec[:joined]))
|
||||
body = { folder: rec[:folder], active: rec[:active], started_at: rec[:started_at],
|
||||
totals: TripDays.stats(points).merge(days: days.size, started_at: points.first[3], ended_at: points.last[3]),
|
||||
days: days.map { |d| d.merge(bbox: TripDays.bbox(points[d[:from]...d[:to]])) } }
|
||||
body[:track] = points.map { |lon, lat, _, t| [lon.round(6), lat.round(6), t] } if params[:track]
|
||||
json body
|
||||
end
|
||||
|
||||
# {"cut": t} or {"join": t} (epoch s; a cut with none: now).
|
||||
post "/api/trip/log/days" do
|
||||
require_login!
|
||||
body = JSON.parse(request.body.read)
|
||||
kind = body.key?("join") ? :join : :cut
|
||||
TRIP_LOG.mark(kind, Float(body[kind.to_s] || Time.now.to_f))
|
||||
json ok: true
|
||||
rescue JSON::ParserError, TypeError
|
||||
halt 400, json(error: "invalid JSON")
|
||||
rescue ArgumentError => e
|
||||
halt 422, json(error: e.message)
|
||||
end
|
||||
|
||||
# The recording as GPX: ?days=1,2 (those days), ?from=t&to=t (a piece),
|
||||
# neither: the whole trip — a track per day (?per_day=1: a .gpx per day in
|
||||
# a .zip), with ?stops=1 the trip's stops near the line, ?plan=1 the
|
||||
# planned route, ?pauses=1 the stands as waypoints.
|
||||
get "/api/trip/log/export" do
|
||||
require_login!
|
||||
rec = TRIP_LOG.recording
|
||||
halt 404, json(error: "no trip recorded") unless rec && rec[:points].size >= 2
|
||||
|
||||
points = rec[:points]
|
||||
days = TripDays.days(points, TripDays.cuts(points, hand: rec[:hand], joined: rec[:joined]))
|
||||
name = rec[:folder].to_s.delete_prefix("Trips/")
|
||||
label = ->(d) { "#{name} · Day #{d[:index]} · #{Time.at(d[:started_at]).strftime('%Y-%m-%d')}" }
|
||||
pieces = if params[:from] && params[:to]
|
||||
from, to = [params[:from], params[:to]].map(&:to_f).sort
|
||||
piece = points.select { |p| p[3].between?(from, to) }
|
||||
[["#{name} · #{Time.at(from).strftime('%d. %m. %H:%M')} – #{Time.at(to).strftime('%H:%M')}", piece]]
|
||||
else
|
||||
picked = params[:days].to_s.split(",").map(&:to_i)
|
||||
days.select { |d| picked.empty? || picked.include?(d[:index]) }.map { |d| [label.(d), points[d[:from]...d[:to]]] }
|
||||
end
|
||||
pieces = pieces.reject { |_, piece| piece.size < 2 }
|
||||
halt 422, json(error: "nothing to export") if pieces.empty?
|
||||
|
||||
folder = rec[:folder] ? (LIBRARY.folder_features(rec[:folder]) rescue []) : []
|
||||
extras = lambda do |piece|
|
||||
line = piece.map { |p| p.first(2) }
|
||||
out = []
|
||||
out += folder.select { |f| f.dig("properties", "kind") == "route" } if params[:plan]
|
||||
if params[:stops]
|
||||
out += folder.select { |f| f.dig("geometry", "type") == "Point" && Corridor.distance_km(f["geometry"]["coordinates"], line) <= 0.3 }
|
||||
end
|
||||
out += TripDays.pauses(piece) if params[:pauses]
|
||||
out
|
||||
end
|
||||
if params[:per_day] && pieces.size > 1
|
||||
content_type "application/zip"
|
||||
attachment "#{name}.zip"
|
||||
Zip::OutputStream.write_buffer do |zip|
|
||||
pieces.each do |title, piece|
|
||||
zip.put_next_entry("#{title.tr('/', '-')}.gpx")
|
||||
zip.write(TripDays.gpx([[title, piece]], extras.(piece)))
|
||||
end
|
||||
end.string
|
||||
else
|
||||
content_type "application/gpx+xml"
|
||||
attachment "#{pieces.size == 1 ? pieces.first.first.tr('/', '-') : name}.gpx"
|
||||
TripDays.gpx(pieces, extras.(pieces.flat_map(&:last)))
|
||||
end
|
||||
end
|
||||
|
||||
get "/api/trip" do
|
||||
require_login!
|
||||
@@ -735,7 +1053,9 @@ module Maptool
|
||||
body = JSON.parse(request.body.read, symbolize_names: true)
|
||||
halt 400, json(error: "points must be a list of {lngLat: [lon, lat]}") unless body[:points].is_a?(Array) && body[:points].all? { |p| p.is_a?(Hash) && p[:lngLat].is_a?(Array) }
|
||||
|
||||
json(TRIP_STORE.update(points: body[:points], vehicle: body[:vehicle], avoid: body[:avoid], editing: body[:editing]) do |locations, vehicle, avoid|
|
||||
json(TRIP_STORE.update(points: body[:points], vehicle: body[:vehicle], avoid: body[:avoid], editing: body[:editing],
|
||||
name: body[:name], start: body[:start], day_start: body[:day_start], note: body[:note],
|
||||
budget: body[:budget], fuel_price: body[:fuel_price]) do |locations, vehicle, avoid|
|
||||
Routing.route(VALHALLA_URL, locations, Routing.vehicle(DATA_DIR, vehicle), avoid.transform_keys(&:to_s))
|
||||
end)
|
||||
rescue JSON::ParserError
|
||||
@@ -836,6 +1156,17 @@ module Maptool
|
||||
center: center, kiwix_url: KIWIX_URL)
|
||||
end
|
||||
|
||||
# A link pasted into the search → a place (lib/maptool/link_place.rb).
|
||||
# The server fetches the page, so only for a logged-in user.
|
||||
get "/api/link" do
|
||||
require_login!
|
||||
place = LinkPlace.resolve(params[:url].to_s)
|
||||
halt 404, json(error: "no coordinates in that link or its page") unless place
|
||||
json place
|
||||
rescue LinkPlace::Error => e
|
||||
halt 422, json(error: e.message)
|
||||
end
|
||||
|
||||
# Pinged once per page load (public/js/map.js) — url is a same-origin
|
||||
# path (not kiwix-serve's own address, which the browser can't reach
|
||||
# directly behind the reverse proxy in front of this app), proxied by
|
||||
@@ -1171,32 +1502,65 @@ module Maptool
|
||||
# for the contract) — read-only, doesn't need require_login! the way
|
||||
# actually running one does below.
|
||||
get "/api/plugins" do
|
||||
json Plugins.list(PLUGINS_DIRS)
|
||||
saved = Plugins.saved_settings(PLUGIN_SETTINGS)
|
||||
json(Plugins.list(PLUGINS_DIRS).map { |p| p.merge("set" => (saved[p["name"]] || {}).keys) })
|
||||
end
|
||||
|
||||
# A plugin's settings (its plugin.json "settings": a login cookie, a key):
|
||||
# {KEY: value}, an empty value clears it. Kept in data/, never sent back.
|
||||
put "/api/plugins/:name/settings" do
|
||||
require_login!
|
||||
json set: Plugins.save_settings(PLUGIN_SETTINGS, PLUGINS_DIRS, params[:name], JSON.parse(request.body.read))
|
||||
rescue Plugins::RunError => e
|
||||
halt 404, json(error: e.message)
|
||||
rescue JSON::ParserError
|
||||
halt 400, json(error: "invalid JSON")
|
||||
end
|
||||
|
||||
# Runs one plugin for the given bbox (the current map viewport, from
|
||||
# the frontend's "Run for this area" button) and imports its GeoJSON
|
||||
# output into a folder of its own, named after the area's center and
|
||||
# the run's time — so one run's POIs stay apart from another's.
|
||||
#
|
||||
# route=1&corridor_km=N instead: along the shared trip's route, N km
|
||||
# either side (a plugin with "route": true covers just that; the points
|
||||
# further off are dropped either way), into the recorded trip's folder
|
||||
# when one is running.
|
||||
post "/api/plugins/:name/run" do
|
||||
require_login!
|
||||
bbox = %w[south west north east].map { |key| params[key].to_s }
|
||||
halt 400, json(error: "south, west, north, east are required") if bbox.any?(&:empty?)
|
||||
timestamp = Time.now.strftime("%y%m%d_%H%M")
|
||||
env = Plugins.saved_settings(PLUGIN_SETTINGS)[params[:name]] || {}
|
||||
if params[:route]
|
||||
coords = TRIP_STORE.get[:route]&.dig(:geometry, :coordinates)
|
||||
halt 422, json(error: "the trip has no route") unless coords && coords.size >= 2
|
||||
corridor = params[:corridor_km].to_f
|
||||
halt 400, json(error: "corridor_km must be 0.5 to 50") unless (0.5..50).cover?(corridor)
|
||||
|
||||
south, west, north, east = bbox.map(&:to_f)
|
||||
begin
|
||||
geojson = Plugins.run(PLUGINS_DIRS, params[:name], [south, west, north, east])
|
||||
rescue Plugins::RunError => e
|
||||
halt 502, json(error: e.message)
|
||||
geojson = Tempfile.create(["route", ".geojson"]) do |file|
|
||||
file.write(JSON.generate(type: "LineString", coordinates: coords))
|
||||
file.flush
|
||||
Plugins.run(PLUGINS_DIRS, params[:name], Corridor.bbox(coords, corridor), route: file.path, corridor_km: corridor, env: env)
|
||||
end
|
||||
geojson["features"] = geojson["features"].select do |f|
|
||||
f.dig("geometry", "type") != "Point" || Corridor.distance_km(f["geometry"]["coordinates"], coords) <= corridor
|
||||
end
|
||||
name = "#{params[:name]} along the route #{format('%g', corridor)} km #{timestamp}"
|
||||
folder = TRIP_LOG.status[:folder] || name
|
||||
else
|
||||
bbox = %w[south west north east].map { |key| params[key].to_s }
|
||||
halt 400, json(error: "south, west, north, east are required") if bbox.any?(&:empty?)
|
||||
|
||||
south, west, north, east = bbox.map(&:to_f)
|
||||
geojson = Plugins.run(PLUGINS_DIRS, params[:name], [south, west, north, east], env: env)
|
||||
center_lat = format("%.2f", (south + north) / 2)
|
||||
center_lon = format("%.2f", (west + east) / 2)
|
||||
folder = name = "#{params[:name]}_#{center_lat}_#{center_lon}_#{timestamp}"
|
||||
end
|
||||
|
||||
center_lat = format("%.2f", (south + north) / 2)
|
||||
center_lon = format("%.2f", (west + east) / 2)
|
||||
timestamp = Time.now.strftime("%y%m%d_%H%M")
|
||||
name = "#{params[:name]}_#{center_lat}_#{center_lon}_#{timestamp}"
|
||||
|
||||
keys = LIBRARY.import(folder: name, filename: "#{name}.geojson", io: StringIO.new(JSON.generate(geojson)))
|
||||
json path: keys.first, tree: LIBRARY.tree
|
||||
keys = LIBRARY.import(folder: folder, filename: "#{name}.geojson", io: StringIO.new(JSON.generate(geojson)))
|
||||
json path: keys.first, tree: LIBRARY.tree, count: geojson["features"].size
|
||||
rescue Plugins::RunError => e
|
||||
halt 502, json(error: e.message)
|
||||
end
|
||||
|
||||
# Called by the Apps Script watching Gmail for Garmin LiveTrack emails —
|
||||
@@ -1316,10 +1680,147 @@ module Maptool
|
||||
# CANopen node (heartbeat state, last seen) and each configured signal.
|
||||
get "/api/can" do
|
||||
require_login!
|
||||
snapshot = CAN_STORE.snapshot
|
||||
snapshot = CAN_STORE.snapshot(since: params[:since]&.to_i)
|
||||
units = CAN_DECODER ? CAN_DECODER.units : {}
|
||||
snapshot[:signals] = snapshot[:signals].to_h { |name, signal| [name, units[name] ? signal.merge(unit: units[name]) : signal] }
|
||||
json snapshot.merge(available: !CAN_CONFIG.nil?)
|
||||
# simulated: the GNSS simulation (/sim.html) stands in for gnss.*
|
||||
actions = CAN_ACTIONS.map { |a| { name: a.name, node: a.node } }
|
||||
# time: whether maptool sends CANopen TIME (off while another node does)
|
||||
time = CAN_TIME && { sending: !CAN_TIME.others? }
|
||||
json snapshot.merge(available: !CAN_CONFIG.nil?, simulated: GNSS_SIM.running?, actions: actions, time: time)
|
||||
end
|
||||
|
||||
# The keypads (can.json's "keypads") for drive mode: which are on the bus
|
||||
# (their heartbeat; with LEDs or not) and the events on their channels
|
||||
# after seq :since — a long poll, answered as soon as one comes (10 s at
|
||||
# most). ponytail: holds one of Puma's threads per drive-mode screen,
|
||||
# fine for the one or two in the car.
|
||||
get "/api/keypad" do
|
||||
require_login!
|
||||
halt 404, json(error: "no keypads in data/can.json") unless KEYPAD
|
||||
since = params[:since] && Integer(params[:since], exception: false)
|
||||
present = App.keypads_present
|
||||
answer = KEYPAD.events(present.empty? ? nil : since)
|
||||
json answer.merge(present: present.map { |d| { name: d.name, leds: d.protocol == "pkp" } })
|
||||
end
|
||||
|
||||
# The screen's colours for a keypad's key LEDs: { "keypad": "pad", "on":
|
||||
# { "K1": "cyan", … }, "blink": { … } } (Keypad::COLORS); the keys bound
|
||||
# to outputs come on top, the 100 ms tick sends them (App.keypad_leds_frames).
|
||||
put "/api/keypad/leds" do
|
||||
require_login!
|
||||
halt 404, json(error: "no keypads in data/can.json") unless KEYPAD
|
||||
body = JSON.parse(request.body.read)
|
||||
begin
|
||||
KEYPAD.led_frames(body["keypad"].to_s, body["on"], body["blink"]) # checks the names and colours
|
||||
rescue ArgumentError => e
|
||||
halt 400, json(error: e.message)
|
||||
end
|
||||
KEYPAD_SCREEN_LEDS[body["keypad"].to_s] = { "on" => body["on"] || {}, "blink" => body["blink"] || {} }
|
||||
json ok: true
|
||||
end
|
||||
|
||||
# The bindings and what they can bind (/keypad.html, drive mode): the
|
||||
# keypads' channels, the outputs, the colours; saved: this car's own
|
||||
# (PUT {bindings}), else the profile's (DELETE goes back to them).
|
||||
get "/api/keypad/bindings" do
|
||||
require_login!
|
||||
keypads = (KEYPAD&.devices || []).map do |d|
|
||||
keys = d.protocol == "pkp" ? (1..d.keys).map { |k| "K#{k}" } : []
|
||||
{ name: d.name, protocol: d.protocol, node: d.node, channels: (keys + d.inputs.keys).uniq }
|
||||
end
|
||||
outputs = (OUTPUTS&.snapshot || []).flat_map { |m| m[:channels].map { |c| { output: "#{m[:name]}.#{c[:n]}", label: c[:label], dimmable: m[:dimmable] } } }
|
||||
json bindings: App.bindings, saved: File.exist?(BINDINGS_PATH), keypads: keypads, outputs: outputs,
|
||||
modes: Outputs::MODES, colors: Keypad::COLORS.keys - ["off"]
|
||||
end
|
||||
|
||||
put "/api/keypad/bindings" do
|
||||
require_login!
|
||||
begin
|
||||
list = App.check_bindings(JSON.parse(request.body.read)["bindings"])
|
||||
rescue ArgumentError, JSON::ParserError => e
|
||||
halt 400, json(error: e.message)
|
||||
end
|
||||
FileUtils.mkdir_p(File.dirname(BINDINGS_PATH))
|
||||
File.write("#{BINDINGS_PATH}.tmp", JSON.pretty_generate(bindings: list))
|
||||
File.rename("#{BINDINGS_PATH}.tmp", BINDINGS_PATH)
|
||||
json bindings: App.bindings, saved: true
|
||||
end
|
||||
|
||||
delete "/api/keypad/bindings" do
|
||||
require_login!
|
||||
FileUtils.rm_f(BINDINGS_PATH)
|
||||
json bindings: App.bindings, saved: false
|
||||
end
|
||||
|
||||
# The outputs (can.json's "outputs"): each module's channels, their
|
||||
# labels and state, which bindings drive them.
|
||||
get "/api/outputs" do
|
||||
require_login!
|
||||
halt 404, json(error: "no outputs in data/can.json") unless OUTPUTS
|
||||
bound = App.bindings.select { |b| Outputs.outputs_of(b).any? }
|
||||
json modules: OUTPUTS.snapshot, bindings: bound
|
||||
end
|
||||
|
||||
# Switches an output by hand (a tile on the screen, /sim.html):
|
||||
# { "on": true | false }, or {} to toggle.
|
||||
post "/api/outputs/:module/:n" do
|
||||
require_login!
|
||||
halt 404, json(error: "no outputs in data/can.json") unless OUTPUTS
|
||||
output = "#{params[:module]}.#{params[:n]}"
|
||||
halt 404, json(error: "no output #{output}") unless OUTPUTS.find(output)
|
||||
body = request.body.read
|
||||
on = body.empty? ? nil : JSON.parse(body)["on"]
|
||||
OUTPUTS.manual(output, on.nil? ? !OUTPUTS.on?(output) : !!on)
|
||||
json on: OUTPUTS.on?(output)
|
||||
end
|
||||
|
||||
# Runs can.json's action number :n (its place in GET /api/can's actions).
|
||||
post "/api/can/actions/:n" do
|
||||
require_login!
|
||||
halt 409, json(error: "CAN is off: no data/can.json on this server") unless CAN_CONFIG
|
||||
action = CAN_ACTIONS[Integer(params[:n], exception: false) || -1] or halt 404
|
||||
transport = Can::Sdo::SocketTransport.new(CAN_CONFIG.fetch("interfaces").first)
|
||||
begin
|
||||
action.run(Can::Sdo.new(transport))
|
||||
rescue Can::Sdo::Error => e
|
||||
halt 502, json(error: e.message)
|
||||
ensure
|
||||
transport.close
|
||||
end
|
||||
json ok: true
|
||||
end
|
||||
|
||||
# Recording the bus into MF4 files on the server: GET whether it runs and
|
||||
# the files (newest first), POST starts it, DELETE stops it (the segment
|
||||
# being recorded is written); a file by GET /api/can/recordings/<name>.
|
||||
get "/api/can/recording" do
|
||||
require_login!
|
||||
json available: !CAN_CONFIG.nil?, running: CAN_RECORDER.running?, started_at: CAN_RECORDER.started_at,
|
||||
error: CAN_RECORDER.error, files: CAN_RECORDER.files
|
||||
end
|
||||
|
||||
post "/api/can/recording" do
|
||||
require_login!
|
||||
halt 409, json(error: "CAN is off: no data/can.json on this server") unless CAN_CONFIG
|
||||
begin
|
||||
CAN_RECORDER.start
|
||||
rescue SystemCallError => e
|
||||
halt 500, json(error: CAN_RECORDER.error || e.message)
|
||||
end
|
||||
json running: CAN_RECORDER.running?
|
||||
end
|
||||
|
||||
delete "/api/can/recording" do
|
||||
require_login!
|
||||
CAN_RECORDER.stop
|
||||
json running: CAN_RECORDER.running?, error: CAN_RECORDER.error
|
||||
end
|
||||
|
||||
get "/api/can/recordings/:name" do
|
||||
require_login!
|
||||
path = CAN_RECORDER.path(params[:name]) or halt 404
|
||||
send_file path, disposition: "attachment", type: "application/octet-stream"
|
||||
end
|
||||
|
||||
# The GNSS simulation: POST {"start": [lon, lat]} drives randomly from
|
||||
@@ -1327,13 +1828,37 @@ module Maptool
|
||||
# stops it, GET says whether it's on (and why it stopped).
|
||||
get "/api/sim/gnss" do
|
||||
require_login!
|
||||
json running: GNSS_SIM.running?, error: GNSS_SIM.error
|
||||
json running: GNSS_SIM.running?, error: GNSS_SIM.error, speedup: GNSS_SIM.speedup, speedups: GnssSim::SPEEDUPS
|
||||
end
|
||||
|
||||
# {"speedup": 1|2|5|10|20}: the simulation's time, faster (also while it runs).
|
||||
put "/api/sim/gnss" do
|
||||
require_login!
|
||||
GNSS_SIM.speedup = JSON.parse(request.body.read)["speedup"]
|
||||
json running: GNSS_SIM.running?, error: GNSS_SIM.error, speedup: GNSS_SIM.speedup, speedups: GnssSim::SPEEDUPS
|
||||
rescue JSON::ParserError
|
||||
halt 400, json(error: "invalid JSON")
|
||||
end
|
||||
|
||||
post "/api/sim/gnss" do
|
||||
require_login!
|
||||
lon, lat = JSON.parse(request.body.read)["start"]
|
||||
if lon.nil?
|
||||
body = JSON.parse(request.body.read)
|
||||
lon, lat = body["start"]
|
||||
# {"trip": true}: along the shared trip's route (to try the navigation)
|
||||
route = TRIP_STORE.get[:route] if body["trip"]
|
||||
halt 422, json(error: "the trip has no route") if body["trip"] && !route
|
||||
# {"track": "item:<id>"}: a library track replayed at its own speed
|
||||
if body["track"]
|
||||
begin
|
||||
line = JSON.parse(LIBRARY.geojson(body["track"].to_s))["features"].find { |f| f.dig("geometry", "type") == "LineString" }
|
||||
rescue Library::NotFound
|
||||
halt 404, json(error: "no such track")
|
||||
end
|
||||
track = line&.dig("properties", "profile")&.filter_map { |p| [p["lon"], p["lat"], p["elapsed_secs"]] if p["elapsed_secs"] }
|
||||
halt 422, json(error: "the track has no times") if track.nil? || track.size < 2
|
||||
end
|
||||
if route || track then nil
|
||||
elsif lon.nil?
|
||||
codes = (PmtilesBuilder.offline_meta(DATA_DIR) || {}).fetch("sources", []).map { |source| source["code"] }
|
||||
bboxes = codes.filter_map { |code| PmtilesBuilder.country_bbox(code) }
|
||||
halt 422, json(error: "no offline countries to start in") if bboxes.empty?
|
||||
@@ -1342,8 +1867,8 @@ module Maptool
|
||||
end
|
||||
|
||||
CAN_STORE.override_prefix = "gnss."
|
||||
GNSS_SIM.start(lon, lat, bboxes: bboxes) do |fix|
|
||||
CAN_STORE.put(fix.transform_keys { |key| "gnss.#{key}" })
|
||||
GNSS_SIM.start(lon, lat, bboxes: bboxes, route: route, track: track) do |fix|
|
||||
CAN_STORE.put(fix.except(:time).transform_keys { |key| "gnss.#{key}" })
|
||||
App.gnss_update(fix)
|
||||
end
|
||||
json running: true
|
||||
@@ -1369,13 +1894,35 @@ module Maptool
|
||||
json LIVE_STORE.update_settings(params.slice("name", "icon", "color", "logging", "trail_hours"))
|
||||
end
|
||||
|
||||
# No fix for DR_AFTER_S while driving the trip's route (a tunnel): the
|
||||
# position carried along the route, `estimated: true`, for up to
|
||||
# DR_MAX_S — by the car's speed off CAN when there is one (dr_m), the
|
||||
# average speed the tunnel was entered at otherwise. ponytail: along
|
||||
# the route only; off it the gyro's yaw rate would be needed (TODO).
|
||||
DR_AFTER_S = 3
|
||||
DR_MAX_S = 600
|
||||
|
||||
def self.gnss_position(now: Time.now.to_f)
|
||||
latest = GNSS_LATEST_MUTEX.synchronize { GNSS_LATEST.dup }
|
||||
dr_m, vehicle_at = latest.values_at(:dr_m, :vehicle_speed_at)
|
||||
fix = latest.except(:course_from, :dr_m, :vehicle_speed_at)
|
||||
age = fix[:received_at] && now - fix[:received_at]
|
||||
return { available: false } unless age
|
||||
|
||||
speed = fix[:speed_avg] || fix[:speed]
|
||||
if age >= DR_AFTER_S && age < DR_MAX_S && speed.to_f >= TripStore::MIN_SPEED &&
|
||||
(coords = TRIP_STORE.get.dig(:route, :geometry, :coordinates))
|
||||
can = vehicle_at && now - vehicle_at < VEHICLE_SPEED_FRESH_S
|
||||
meters = can ? dr_m + fix[:vehicle_speed] * (now - vehicle_at) : speed * age
|
||||
lngLat, track = TripStore.ahead(coords, [fix[:lon], fix[:lat]], meters)
|
||||
return fix.merge(lon: lngLat[0], lat: lngLat[1], track: track, speed: can ? fix[:vehicle_speed] : speed, available: true, estimated: true) if lngLat
|
||||
end
|
||||
age < GNSS_STALE_AFTER ? fix.merge(available: true) : { available: false }
|
||||
end
|
||||
|
||||
get "/api/gnss/position" do
|
||||
require_login!
|
||||
GNSS_LATEST_MUTEX.synchronize do
|
||||
received_at = GNSS_LATEST[:received_at]
|
||||
fresh = received_at && (Time.now.to_f - received_at) < GNSS_STALE_AFTER
|
||||
json(fresh ? GNSS_LATEST.except(:course_from).merge(available: true) : { available: false })
|
||||
end
|
||||
json App.gnss_position
|
||||
end
|
||||
end
|
||||
end
|
||||
+46
-15
@@ -3,12 +3,18 @@
|
||||
# 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) and restarts maptool;
|
||||
# data/update/status.json tells the app how far it got. docs/deployment.adoc.
|
||||
# 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
|
||||
|
||||
@@ -21,22 +27,47 @@ status() {
|
||||
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"
|
||||
status running "downloading ${sha:0:7}"
|
||||
tmp=$(mktemp -d)
|
||||
trap 'rm -rf "$tmp"' EXIT
|
||||
curl -fsS --retry 3 --retry-delay 5 --speed-limit 1024 --speed-time 60 -o "$tmp/src.tar.gz" "$REPO_URL/archive/$sha.tar.gz" \
|
||||
|| fail "download of ${sha:0:7} failed"
|
||||
mkdir "$tmp/build"
|
||||
tar -xzf "$tmp/src.tar.gz" -C "$tmp/build" --strip-components=1 || fail "the archive didn't unpack"
|
||||
[ -f "$tmp/build/app.rb" ] || fail "not a maptool tree"
|
||||
echo "${sha:0:7}" > "$tmp/build/REVISION"
|
||||
chown -R --reference="$ROOT" "$tmp/build"
|
||||
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 "$tmp/build" "$ROOT/build"
|
||||
status restarting "restarting with ${sha:0:7}"
|
||||
mv "$new" "$ROOT/build"
|
||||
sync
|
||||
trap - EXIT
|
||||
status restarting "restarting with $short"
|
||||
systemctl restart podman-compose@maptool.service
|
||||
status done "updated to ${sha:0:7}"
|
||||
|
||||
# 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)"
|
||||
Generated
+457
@@ -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",
|
||||
]
|
||||
@@ -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"
|
||||
@@ -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");
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
+3
-3
@@ -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:-}
|
||||
|
||||
+148
-6
@@ -193,6 +193,26 @@ Its `.env` adds:
|
||||
* `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
|
||||
@@ -201,9 +221,21 @@ mustn't restart it mid-drive. Instead it checks Gitea itself (every
|
||||
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, swaps it into `build/`
|
||||
(the previous one stays as `build.old/`), restarts maptool and reports in
|
||||
`data/update/status.json`; the page reloads on the new revision.
|
||||
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
|
||||
@@ -220,10 +252,21 @@ 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`. Back by hand:
|
||||
`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)
|
||||
@@ -299,13 +342,112 @@ 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 (Dashboard settings, `POST`/`DELETE /api/sim/gnss`) drives
|
||||
The simulation (its own diagnostics page, `/sim.html` — linked from Status / debug and the dashboard settings; `POST`/`DELETE /api/sim/gnss`; `{"trip": true}` drives the shared trip's route first — with a detour now and then, 300–800 m off to one side every 3–8 km, to try off-route and the rerouting — the page's "Drive the trip's route") drives
|
||||
random trips over the local Valhalla and stands in for the node's `gnss.*`
|
||||
meanwhile — on the car's server only for trying things out.
|
||||
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)
|
||||
|
||||
|
||||
+496
-5
@@ -56,10 +56,490 @@ a color never decorates.
|
||||
|===
|
||||
|
||||
Road signs stay road signs: the speed limit is the white disc with the
|
||||
red ring whatever the theme — it's read as a sign, not as a color.
|
||||
red ring — read as a sign, not as a color (`--sign-*`, only dimmed by
|
||||
night).
|
||||
|
||||
Night: the page's night mode inverts the UI (`html.night`); the
|
||||
instruments are already dark and are inverted back, only dimmed.
|
||||
=== 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
|
||||
|
||||
@@ -82,5 +562,16 @@ route panel, NPS maps, the offline data panel
|
||||
(next maneuver, lanes), the switch panel (PDM), warnings, `/can.html`
|
||||
|===
|
||||
|
||||
The route line is the bridge: blue (`#1d6fdc`) while planning, magenta
|
||||
(`--inst-active`) once it's being navigated.
|
||||
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).
|
||||
@@ -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
|
||||
|
||||
+16
-3
@@ -12,6 +12,8 @@ module Maptool
|
||||
# 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" },
|
||||
@@ -137,6 +139,7 @@ module Maptool
|
||||
# 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).
|
||||
@@ -148,6 +151,8 @@ module Maptool
|
||||
@nodes = {}
|
||||
@interfaces = {}
|
||||
@frames = {}
|
||||
@log = []
|
||||
@seq = 0
|
||||
end
|
||||
|
||||
def interface(name, **state)
|
||||
@@ -174,6 +179,8 @@ module Maptool
|
||||
# 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
|
||||
@@ -208,8 +215,12 @@ module Maptool
|
||||
end
|
||||
end
|
||||
|
||||
def snapshot
|
||||
@mutex.synchronize { { interfaces: @interfaces.dup, nodes: @nodes.dup, signals: @signals.dup, frames: @frames.values.map(&:dup) } }
|
||||
# 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
|
||||
|
||||
@@ -217,7 +228,8 @@ module Maptool
|
||||
# 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.
|
||||
def self.listen(interface, decoder:, store:, start_nodes: false, retry_delay: 5)
|
||||
# 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)
|
||||
@@ -230,6 +242,7 @@ module Maptool
|
||||
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?
|
||||
|
||||
@@ -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
|
||||
@@ -80,6 +80,24 @@ module Maptool
|
||||
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
|
||||
|
||||
@@ -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
|
||||
@@ -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
|
||||
+127
-6
@@ -15,6 +15,16 @@ module Maptool
|
||||
LIMIT_SHARE = 0.9 # drives a bit under the limit
|
||||
|
||||
attr_reader :error
|
||||
# Time runs this many times faster (1, 2, 5, 10…): the car covers that
|
||||
# much more ground per real tick, while each fix's `time` is the
|
||||
# simulation's own clock — a recorded trip shows the real speeds, not
|
||||
# 250 km/h. Changeable while it runs.
|
||||
SPEEDUPS = [1, 2, 5, 10, 20].freeze
|
||||
attr_reader :speedup
|
||||
|
||||
def speedup=(value)
|
||||
@speedup = SPEEDUPS.include?(value.to_i) ? value.to_i : 1
|
||||
end
|
||||
|
||||
def initialize(valhalla_url, vehicle: { id: "car" }, random: Random.new, sleep: ->(s) { Kernel.sleep(s) },
|
||||
router: Routing.method(:route))
|
||||
@@ -25,6 +35,8 @@ module Maptool
|
||||
@sleep = sleep
|
||||
@thread = nil
|
||||
@mutex = Mutex.new
|
||||
@speedup = 1
|
||||
@clock = Time.now.to_f
|
||||
end
|
||||
|
||||
def running?
|
||||
@@ -38,14 +50,24 @@ module Maptool
|
||||
|
||||
# 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; each fix to the block:
|
||||
# { lat:, lon:, speed: m/s, satellites:, hdop: }.
|
||||
def start(lon = nil, lat = nil, bboxes: nil, &on_fix)
|
||||
# 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
|
||||
position, route = bboxes ? random_start(bboxes) : [[Float(lon), Float(lat)], nil]
|
||||
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
|
||||
@@ -89,11 +111,12 @@ module Maptool
|
||||
i = 1
|
||||
while i < coords.size
|
||||
kmh = speed_kmh(limits.reverse.find { |start, _| start <= at }&.last)
|
||||
at += kmh / 3600 * TICK_S
|
||||
at += kmh / 3600 * TICK_S * @speedup
|
||||
@clock += TICK_S * @speedup
|
||||
i += 1 while i < coords.size - 1 && km[i] < at
|
||||
t = km[i] > km[i - 1] ? ((at - km[i - 1]) / (km[i] - km[i - 1])).clamp(0.0, 1.0) : 1.0
|
||||
lon, lat = coords[i - 1].zip(coords[i]).map { |a, b| a + (b - a) * t }
|
||||
on_fix&.call(lat: lat, lon: lon, speed: kmh / 3.6, satellites: 12, hdop: 0.8)
|
||||
on_fix&.call(lat: lat, lon: lon, speed: kmh / 3.6, satellites: 12, hdop: 0.8, mode: 3, time: @clock.round(1))
|
||||
break if i == coords.size - 1 && t >= 1
|
||||
|
||||
@sleep.call(TICK_S)
|
||||
@@ -101,10 +124,108 @@ module Maptool
|
||||
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
|
||||
|
||||
+6
-1
@@ -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
|
||||
|
||||
@@ -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
|
||||
@@ -539,6 +539,11 @@ module Maptool
|
||||
|
||||
# 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
|
||||
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
@@ -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?
|
||||
|
||||
+121
-10
@@ -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).
|
||||
@@ -253,25 +288,68 @@ module Maptool
|
||||
geometry: { type: "LineString", coordinates: legs.flat_map { |leg| decode_polyline(leg["shape"]) } },
|
||||
properties: { kind: "route", costing: costing, distance_km: data["trip"]["summary"]["length"],
|
||||
time_s: data["trip"]["summary"]["time"], countries: along[:countries],
|
||||
speed_limits: along[:speed_limits], signals: along[:signals],
|
||||
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
|
||||
maneuvers: legs.flat_map { |leg| leg["maneuvers"].map { |m| { text: m["instruction"], km: m["length"], lanes: m["lanes"] }.compact } } } }
|
||||
# type: Valhalla's maneuver type (the arrow), street: the road it leads onto
|
||||
maneuvers: legs.flat_map { |leg| leg["maneuvers"].map { |m| maneuver(m) } } } }
|
||||
rescue ArgumentError, TypeError
|
||||
raise RouteError, "invalid coordinates"
|
||||
end
|
||||
|
||||
# Routes of consecutive pieces (a trip's days with avoids of their own,
|
||||
# TripStore) as one: the lines joined, km along it shifted by the pieces
|
||||
# before, the countries summed.
|
||||
def self.merge(parts)
|
||||
return parts.first if parts.size <= 1
|
||||
|
||||
km = 0.0
|
||||
coords = []
|
||||
out = { distance_km: 0.0, time_s: 0.0, legs_km: [], legs_s: [], maneuvers: [], speed_limits: [], signals: [], roads: [] }
|
||||
countries = {}
|
||||
parts.each do |part|
|
||||
props = part[:properties]
|
||||
line = part[:geometry][:coordinates]
|
||||
coords.concat(coords.empty? ? line : line.drop(1))
|
||||
out[:distance_km] += props[:distance_km]
|
||||
out[:time_s] += props[:time_s]
|
||||
%i[legs_km legs_s maneuvers].each { |key| out[key].concat(props[key] || []) }
|
||||
out[:speed_limits].concat((props[:speed_limits] || []).map { |at, limit| [(at + km).round(3), limit] })
|
||||
out[:signals].concat((props[:signals] || []).map { |lon, lat, at| [lon, lat, (at + km).round(3)] })
|
||||
out[:roads].concat((props[:roads] || []).map { |at, *rest| [(at + km).round(3), *rest] })
|
||||
(props[:countries] || []).each do |row|
|
||||
sum = countries[row[:code]] ||= { code: row[:code], km: 0.0, motorway_km: 0.0, toll_km: 0.0 }
|
||||
%i[km motorway_km toll_km].each { |key| sum[key] = (sum[key] + row[key].to_f).round(1) }
|
||||
end
|
||||
km += props[:distance_km]
|
||||
end
|
||||
first = parts.first
|
||||
{ type: "Feature", geometry: { type: "LineString", coordinates: coords },
|
||||
properties: first[:properties].merge(out, distance_km: out[:distance_km].round(3), countries: countries.values) }
|
||||
end
|
||||
|
||||
def self.maneuver(m)
|
||||
{ text: m["instruction"], km: m["length"], type: m["type"], street: (m["begin_street_names"] || m["street_names"])&.first,
|
||||
exit: m["roundabout_exit_count"], lanes: m["lanes"],
|
||||
alert: m["verbal_transition_alert_instruction"], say: m["verbal_pre_transition_instruction"] }.compact
|
||||
end
|
||||
private_class_method :maneuver
|
||||
|
||||
# From Valhalla's per-edge attributes along the route:
|
||||
# countries: [{ code: "AT", km:, motorway_km:, toll_km: }, ...] in route
|
||||
# order (vignettes, tolls);
|
||||
# speed_limits: [[km from the start, km/h | "unlimited" | nil], ...], an
|
||||
# entry where the limit changes (nil: not tagged);
|
||||
# signals: [[lon, lat, km from the start], ...], the traffic signals.
|
||||
# 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"])
|
||||
@@ -289,13 +367,15 @@ module Maptool
|
||||
row[:toll_km] += edge["length"] if edge["toll"]
|
||||
limit = speed_limit(edge["speed_limit"])
|
||||
limits << [km.round(3), limit] if limits.empty? || limits.last[1] != limit
|
||||
road = [km.round(3), edge["road_class"], code]
|
||||
roads << road if roads.empty? || roads.last.drop(1) != road.drop(1)
|
||||
km += edge["length"]
|
||||
point = shape[edge["end_shape_index"].to_i] if edge.dig("end_node", "traffic_signal")
|
||||
signals << [*point, km.round(3)] if point
|
||||
end
|
||||
end
|
||||
{ countries: totals.values.each { |row| row.transform_values! { |v| v.is_a?(Float) ? v.round(1) : v } },
|
||||
speed_limits: limits, signals: signals }
|
||||
speed_limits: limits, signals: signals, roads: roads }
|
||||
rescue RouteError, Unavailable, Net::ReadTimeout, NoMethodError, TypeError
|
||||
nil
|
||||
end
|
||||
@@ -308,21 +388,50 @@ module Maptool
|
||||
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 and
|
||||
# speed limit. Map-matched, so the road actually driven, not just the
|
||||
# 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], action: "include" })
|
||||
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"
|
||||
{ name: edge["names"]&.first, road_class: edge["road_class"], speed_limit: speed_limit(edge["speed_limit"]) }
|
||||
country = data["admins"]&.dig(edge.dig("end_node", "admin_index").to_i, "country_code")
|
||||
{ name: edge["names"]&.first, road_class: edge["road_class"], speed_limit: speed_limit(edge["speed_limit"]), surface: edge["surface"], country: country,
|
||||
signals: signals_ahead(valhalla_url, points) }.compact
|
||||
rescue ArgumentError, TypeError
|
||||
raise RouteError, "invalid coordinates"
|
||||
end
|
||||
|
||||
AHEAD_KM = 1.5
|
||||
|
||||
# The traffic signals on the road ahead with no route: a route from the
|
||||
# last fix, leaving in the direction driven, to AHEAD_KM straight on;
|
||||
# [[lon, lat, km from the fix], ...], nil if that fails (it's extra).
|
||||
# ponytail: "straight on" picks the way at a junction, a signal past a
|
||||
# turn the driver then takes is missed until the next fix's lookup
|
||||
def self.signals_ahead(valhalla_url, points)
|
||||
(lon0, lat0), (lon, lat) = points.last(2).map { |p| p.map { |v| Float(v) } }
|
||||
rad = Math::PI / 180
|
||||
dx = (lon - lon0) * Math.cos(lat * rad)
|
||||
dy = lat - lat0
|
||||
return nil if dx.zero? && dy.zero?
|
||||
|
||||
heading = (Math.atan2(dx, dy) / rad) % 360
|
||||
deg = AHEAD_KM / 111.32
|
||||
to = { lon: lon + deg * Math.sin(heading * rad) / Math.cos(lat * rad), lat: lat + deg * Math.cos(heading * rad) }
|
||||
data = valhalla(valhalla_url, "/route", locations: [{ lon: lon, lat: lat, heading: heading.round, heading_tolerance: 45 }, to],
|
||||
costing: "auto", directions_type: "none")
|
||||
along_route(valhalla_url, data.dig("trip", "legs"), "auto", {})&.dig(:signals)
|
||||
rescue RouteError, Unavailable, Net::ReadTimeout, NoMethodError, TypeError, ArgumentError
|
||||
nil
|
||||
end
|
||||
private_class_method :signals_ahead
|
||||
|
||||
ISOCHRONE_MAX_MINUTES = 240 # Valhalla's own default limit
|
||||
|
||||
# How far the vehicle gets from [lon, lat] in each of `minutes`: a
|
||||
@@ -356,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
|
||||
|
||||
@@ -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|
|
||||
|
||||
+168
-10
@@ -10,6 +10,56 @@ module Maptool
|
||||
# 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
|
||||
@@ -25,28 +75,136 @@ module Maptool
|
||||
@mutex.synchronize { @trip.dup }
|
||||
end
|
||||
|
||||
# points: [{ lngLat: [lon, lat], name:, nav: }]. Routes through them 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. Last write wins.
|
||||
def update(points:, vehicle:, avoid:, editing:)
|
||||
points = points.map { |p| { lngLat: p.fetch(:lngLat).map { |v| Float(v) }, name: p[:name], nav: !!p[:nav] } }
|
||||
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
|
||||
same_route = before[:points].map { |p| p[:lngLat] } == points.map { |p| p[:lngLat] } &&
|
||||
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 points.size < 2 then [nil, nil]
|
||||
elsif routed.(points).size < 2 then [nil, nil]
|
||||
else
|
||||
begin
|
||||
[yield(points.map { |p| p[:lngLat] }, vehicle, avoid), nil]
|
||||
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,
|
||||
route: route, error: error, updated_at: Time.now.to_f }
|
||||
**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
|
||||
|
||||
@@ -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
|
||||
@@ -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
|
||||
Generated
+13
-13
@@ -9,7 +9,7 @@
|
||||
"@mdi/js": "7.4.47",
|
||||
"flag-icons": "7.6.0",
|
||||
"maplibre-contour": "0.2.0",
|
||||
"maplibre-gl": "6.20.0",
|
||||
"maplibre-gl": "6.21.0",
|
||||
"maplibre-gl-lanes": "1.7.0",
|
||||
"pmtiles": "4.5.0",
|
||||
"suncalc": "2.1.4"
|
||||
@@ -69,9 +69,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@maplibre/maplibre-gl-style-spec": {
|
||||
"version": "26.11.0",
|
||||
"resolved": "https://registry.npmjs.org/@maplibre/maplibre-gl-style-spec/-/maplibre-gl-style-spec-26.11.0.tgz",
|
||||
"integrity": "sha512-MQMBqOkmVm7fLLun2l/bwOv9bURkvyEVISo/OYleb9/nsnfjQ6gs29isysARt5FK/k9RFM4SmH4eMTUQGlv0Pw==",
|
||||
"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.20.0",
|
||||
"resolved": "https://registry.npmjs.org/maplibre-gl/-/maplibre-gl-6.20.0.tgz",
|
||||
"integrity": "sha512-7manvqXeNoN0mKRzenYDopkb3VW9j7iag45RvopkOVFZ7c+La7CBWtK8eBS5bKrI6NyxqAIxPxIG1PMcotcY1w==",
|
||||
"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": {
|
||||
@@ -195,8 +195,8 @@
|
||||
"@mapbox/unitbezier": "^1.0.0",
|
||||
"@mapbox/vector-tile": "^3.0.0",
|
||||
"@maplibre/geojson-vt": "^7.0.1",
|
||||
"@maplibre/maplibre-gl-style-spec": "^26.11.0",
|
||||
"@maplibre/mlt": "^1.3.0",
|
||||
"@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.2.0",
|
||||
"pbf": "^5.2.1",
|
||||
"potpack": "^2.1.0",
|
||||
"quickselect": "^3.0.0",
|
||||
"tinyqueue": "^3.0.0",
|
||||
|
||||
+1
-1
@@ -6,7 +6,7 @@
|
||||
"@mdi/js": "7.4.47",
|
||||
"flag-icons": "7.6.0",
|
||||
"maplibre-contour": "0.2.0",
|
||||
"maplibre-gl": "6.20.0",
|
||||
"maplibre-gl": "6.21.0",
|
||||
"maplibre-gl-lanes": "1.7.0",
|
||||
"pmtiles": "4.5.0",
|
||||
"suncalc": "2.1.4"
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
{
|
||||
"label": "Camper POIs (Overpass)",
|
||||
"command": "./run.rb"
|
||||
"command": "./run.rb",
|
||||
"route": true
|
||||
}
|
||||
@@ -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))
|
||||
@@ -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
|
||||
|
||||
+1999
-314
File diff suppressed because it is too large.
Load diff
@@ -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" }
|
||||
]
|
||||
}
|
||||
+265
-71
@@ -1,5 +1,7 @@
|
||||
import { isLoggedIn } from "/js/auth.js";
|
||||
import { onRouteChanged, requestReroute, requestGnssFollow } from "/js/panels.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
|
||||
@@ -9,10 +11,15 @@ import { onRouteChanged, requestReroute, requestGnssFollow } from "/js/panels.js
|
||||
// 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", lat: "gnss.lat", lon: "gnss.lon", hdop: "gnss.hdop" };
|
||||
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";
|
||||
@@ -30,8 +37,22 @@ 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
|
||||
const DEFAULT_WIDGETS = { inclinometer: true, speed: true, navigation: true };
|
||||
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 = () => {
|
||||
@@ -42,20 +63,41 @@ const load = () => {
|
||||
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;
|
||||
const distance = (m) => (m >= 1000 ? `${(m / 1000).toFixed(1)} km` : `${Math.round(m / 10) * 10} m`);
|
||||
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) => ({ "&": "&", "<": "<", ">": ">", '"': """ })[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.
|
||||
function laneSvg({ directions, active = 0 }) {
|
||||
export function laneSvg({ directions, active = 0 }) {
|
||||
const arrow = (bit) => {
|
||||
const bold = active & bit ? " dash-lane__take" : "";
|
||||
if (bit === LANE_REVERSE) return `<path class="dash-lane__arrow${bold}" d="M14 30 V14 A5 5 0 0 0 4 14 V20 M1 17 L4 21 L7 17"/>`;
|
||||
const a = (LANE_ANGLES[bit] * Math.PI) / 180;
|
||||
const [x, y] = [12 + 9 * Math.sin(a), 15 - 9 * Math.cos(a)];
|
||||
const head = (side) => `L${(x - 5 * Math.sin(a + side)).toFixed(1)} ${(y + 5 * Math.cos(a + side)).toFixed(1)}`;
|
||||
return `<path class="dash-lane__arrow${bold}" d="M12 30 V15 L${x.toFixed(1)} ${y.toFixed(1)} M${(x - 5 * Math.sin(a + 0.6)).toFixed(1)} ${(y + 5 * Math.cos(a + 0.6)).toFixed(1)} L${x.toFixed(1)} ${y.toFixed(1)} ${head(-0.6)}"/>`;
|
||||
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>`;
|
||||
@@ -71,16 +113,30 @@ function prepareRoute(route) {
|
||||
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, signals: route.properties.signals || [], maneuvers, viaKm };
|
||||
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].
|
||||
// ponytail: scans every segment each fix — a window around the last hit if long routes get slow.
|
||||
function locate(route, position) {
|
||||
// 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]];
|
||||
@@ -121,8 +177,19 @@ const INCLINOMETER = `
|
||||
<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;
|
||||
@@ -133,7 +200,10 @@ export class DashboardControl {
|
||||
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;
|
||||
@@ -142,6 +212,68 @@ export class DashboardControl {
|
||||
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;
|
||||
@@ -149,27 +281,49 @@ export class DashboardControl {
|
||||
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) : [0, Infinity];
|
||||
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, signals, maneuvers } = this._route;
|
||||
const current = limits.findLast(([km]) => km <= at);
|
||||
const next = limits.find(([km, limit]) => km > at && limit !== current?.[1]);
|
||||
const signal = signals.find(([, , km]) => km > at);
|
||||
const maneuver = maneuvers.find((m) => m.at > at + 0.005);
|
||||
if (off <= ON_ROUTE_M) this._lastAt = at;
|
||||
this._nav = {
|
||||
limit: current?.[1] ?? null,
|
||||
next: next && { limit: next[1], m: (next[0] - at) * 1000 },
|
||||
signal: signal && (signal[2] - at) * 1000,
|
||||
maneuver: maneuver && { text: maneuver.text, m: (maneuver.at - at) * 1000, lanes: maneuver.lanes },
|
||||
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._nav = { limit: this._road?.speed_limit ?? null, offRoute: !!this._route };
|
||||
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);
|
||||
@@ -210,10 +364,11 @@ export class DashboardControl {
|
||||
<div class="overlays-panel__details" hidden>
|
||||
<label class="live-tracker__row"><input type="checkbox" data-widget="inclinometer"> Inclinometer & 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 & ahead (route)</label>
|
||||
<label class="live-tracker__row"><input type="checkbox" data-widget="banner"> Navigation banner (next turn)</label>
|
||||
<label class="live-tracker__row">Background <input type="range" class="dash-opacity" min="0" max="1" step="0.05"></label>
|
||||
<button type="button" class="dash-sim">Simulate driving from a random place</button>
|
||||
<p class="live-panel__status dash-sim-status" hidden></p>
|
||||
<a class="dash-sim" href="/sim.html" target="_blank">GNSS simulation ↗</a>
|
||||
</div>`;
|
||||
this._toggle = li.querySelector(".overlays-panel__toggle");
|
||||
this._status = li.querySelector(".live-panel__status");
|
||||
@@ -244,31 +399,6 @@ export class DashboardControl {
|
||||
this._save();
|
||||
this._card?.style.setProperty("--dash-alpha", opacity.value);
|
||||
});
|
||||
this._simButton = li.querySelector(".dash-sim");
|
||||
this._simStatus = li.querySelector(".dash-sim-status");
|
||||
this._simButton.addEventListener("click", () => this._simulate(!this._simRunning));
|
||||
this._simulate(null);
|
||||
}
|
||||
|
||||
// GNSS simulation on the server (POST/DELETE /api/sim/gnss): random
|
||||
// driving from a random place in the offline countries, the GNSS control
|
||||
// turned on to follow it; on = true / false, null = just read the state.
|
||||
async _simulate(on) {
|
||||
const options = on === true ? { method: "POST", headers: { "Content-Type": "application/json" }, body: "{}" }
|
||||
: on === false ? { method: "DELETE" } : {};
|
||||
try {
|
||||
const response = await fetch("/api/sim/gnss", options);
|
||||
const state = await response.json();
|
||||
if (!response.ok) throw new Error(state.error || `HTTP ${response.status}`);
|
||||
this._simRunning = state.running;
|
||||
if (on === true && state.running) requestGnssFollow(); // the map follows the simulated position
|
||||
this._simStatus.hidden = !state.error;
|
||||
this._simStatus.textContent = state.error ? `Simulation stopped: ${state.error}` : "";
|
||||
} catch (e) {
|
||||
this._simStatus.hidden = false;
|
||||
this._simStatus.textContent = `Simulation: ${e.message}`;
|
||||
}
|
||||
this._simButton.textContent = this._simRunning ? "Stop the simulation" : "Simulate driving from the map center";
|
||||
}
|
||||
|
||||
_save() {
|
||||
@@ -279,22 +409,34 @@ export class DashboardControl {
|
||||
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>`;
|
||||
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…";
|
||||
this._poll();
|
||||
if (!this._timer) this._poll();
|
||||
}
|
||||
|
||||
_disable() {
|
||||
clearTimeout(this._timer);
|
||||
this._timer = null;
|
||||
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}`);
|
||||
@@ -306,6 +448,13 @@ export class DashboardControl {
|
||||
return [key, s && now - s.at < STALE_S + 1 ? s.value : null];
|
||||
}));
|
||||
this._updateCourse(this._values);
|
||||
this._simRunning = !!data.simulated; // /sim.html runs it
|
||||
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;
|
||||
@@ -315,7 +464,27 @@ export class DashboardControl {
|
||||
this._status.textContent = `Can't reach the server: ${e.message}`;
|
||||
}
|
||||
this._render();
|
||||
if (this._card) this._timer = setTimeout(() => this._poll(), POLL_MS);
|
||||
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() {
|
||||
@@ -328,8 +497,12 @@ export class DashboardControl {
|
||||
speed.style.display = widgets.speed ? "" : "none";
|
||||
const nav = this._card.querySelector(".dash-nav");
|
||||
nav.style.display = widgets.navigation ? "" : "none";
|
||||
this._card.hidden = !widgets.inclinometer && !widgets.speed && !widgets.navigation;
|
||||
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"]) {
|
||||
@@ -340,12 +513,10 @@ export class DashboardControl {
|
||||
text.textContent = value == null ? "—" : `${value > 0 ? "+" : ""}${Math.round(value)}°`;
|
||||
text.setAttribute("class", `dash-value dash-${key}-value ${severity(key, value)}`);
|
||||
}
|
||||
const moving = v.speed != null && v.speed >= MOVING_MS;
|
||||
const heading = moving ? this._course ?? v.heading : v.heading ?? this._course;
|
||||
const live = heading != null && (moving ? this._course != null : v.heading != null);
|
||||
svg.querySelector(".dash-ring").setAttribute("transform", `rotate(${heading == null ? 0 : -heading})`);
|
||||
svg.querySelector(".dash-ring").style.opacity = heading == null ? 0.3 : live ? 1 : 0.55;
|
||||
svg.querySelector(".dash-heading").textContent = heading == null ? "" : `${Math.round((heading + 360) % 360)}°`;
|
||||
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);
|
||||
}
|
||||
|
||||
@@ -363,13 +534,36 @@ export class DashboardControl {
|
||||
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) {
|
||||
if (n?.maneuver && !this._settings.widgets.banner) {
|
||||
const { text, m, lanes } = n.maneuver;
|
||||
rows.push(`<div class="dash-maneuver">${distance(m)} · ${text.replace(/[&<>]/g, (c) => ({ "&": "&", "<": "<", ">": ">" })[c])}</div>`);
|
||||
if (lanes && m <= LANES_AHEAD_M) {
|
||||
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
@@ -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
@@ -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
@@ -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");
|
||||
}
|
||||
+106
-5
@@ -20,17 +20,98 @@ const ARROW = `<svg viewBox="0 0 24 24" width="26" height="26"><path d="M12 2 L2
|
||||
// heading stays while standing still (speed in m/s, heading in degrees).
|
||||
// duration (ms): a linear glide over that long — the time until the next
|
||||
// fix, so a 1 Hz receiver moves the camera smoothly, not in 10 m jumps.
|
||||
// Moving the map by hand (drag, zoom, rotate, tilt) pauses the follow, as a
|
||||
// car navigation does — to look around, change the route — the position
|
||||
// keeps moving; "Back to the position" or FREE_LOOK_MS without touching the
|
||||
// map resumes it.
|
||||
const FREE_LOOK_MS = 15000;
|
||||
const FOLLOWING_MS = 5000; // a follow step this recently: the map is following
|
||||
const freeLook = new WeakMap(); // map -> { until, button }
|
||||
|
||||
function freeLookState(map) {
|
||||
let state = freeLook.get(map);
|
||||
if (state) return state;
|
||||
const button = document.createElement("button");
|
||||
button.type = "button";
|
||||
button.className = "follow-resume";
|
||||
button.textContent = "Back to the position";
|
||||
button.hidden = true;
|
||||
map.getContainer().appendChild(button);
|
||||
state = { until: 0, button, followedAt: 0 };
|
||||
button.addEventListener("click", () => resumeFollow(map));
|
||||
const touched = (e) => {
|
||||
// our own easeTo, or nothing being followed (GNSS off)
|
||||
if (e.originalEvent && Date.now() - state.followedAt <= FOLLOWING_MS) pauseFollow(map);
|
||||
};
|
||||
for (const type of ["dragstart", "zoomstart", "rotatestart", "pitchstart", "move"]) map.on(type, touched);
|
||||
freeLook.set(map, state);
|
||||
return state;
|
||||
}
|
||||
|
||||
// Also for a view the app moves to itself (the driving bar's route overview).
|
||||
export function pauseFollow(map) {
|
||||
const state = freeLookState(map);
|
||||
state.until = Date.now() + FREE_LOOK_MS;
|
||||
state.button.hidden = false;
|
||||
clearTimeout(state.timer);
|
||||
state.timer = setTimeout(() => (state.button.hidden = true), FREE_LOOK_MS);
|
||||
}
|
||||
|
||||
// Is the map following a position right now (a follow step lately, not
|
||||
// paused by hand)? For the driving bar's recenter button.
|
||||
export function isFollowing(map) {
|
||||
const state = freeLookState(map);
|
||||
return Date.now() - state.followedAt <= FOLLOWING_MS && Date.now() >= state.until;
|
||||
}
|
||||
|
||||
export function resumeFollow(map) {
|
||||
const state = freeLookState(map);
|
||||
state.until = 0;
|
||||
state.button.hidden = true;
|
||||
clearTimeout(state.timer);
|
||||
}
|
||||
|
||||
// The first step of a follow (or a jump after a gap): zoom in to see the
|
||||
// road ahead. easeTo, not flyTo — flyTo's swoop zooms out over the distance
|
||||
// first, the wrong way when starting to drive.
|
||||
export const FOLLOW_ZOOM = 17;
|
||||
export function startFollow(map, lngLat) {
|
||||
map.easeTo({ center: lngLat, zoom: Math.max(map.getZoom(), FOLLOW_ZOOM), duration: 1000 });
|
||||
}
|
||||
|
||||
export function followPosition(map, lngLat, heading, speed, duration) {
|
||||
const free = freeLookState(map);
|
||||
free.followedAt = Date.now();
|
||||
// following in 3D like a navigation: the overview map out of the way
|
||||
// (style.css), back once the follow stops or the view goes 2D
|
||||
document.documentElement.classList.toggle("follow-3d", map.getPitch() > 0);
|
||||
clearTimeout(free.followTimer);
|
||||
free.followTimer = setTimeout(() => document.documentElement.classList.remove("follow-3d"), FOLLOWING_MS);
|
||||
if (Date.now() < free.until) return;
|
||||
free.button.hidden = true;
|
||||
const pitched = map.getPitch() > 0;
|
||||
const moving = Number.isFinite(heading) && (speed ?? 0) >= 1;
|
||||
const zoom = moving && autoZoom(map.getZoom(), speed);
|
||||
map.easeTo({
|
||||
center: lngLat,
|
||||
padding: { top: pitched ? map.getContainer().clientHeight * 0.4 : 0 },
|
||||
...(pitched && moving && { bearing: heading }),
|
||||
...(zoom && { zoom }),
|
||||
...(duration != null && { duration, easing: (t) => t }),
|
||||
});
|
||||
}
|
||||
|
||||
// Auto-zoom like a car navigation: close in town, farther out the faster
|
||||
// (up to 20 km/h z18, 50 z17.3, 90 z16.3, 120+ z15.6). Eased toward that by at most
|
||||
// 0.15 a fix and ignored within 0.25, so speed jitter doesn't pump the map.
|
||||
// A hand zoom pauses the follow; on resuming it eases back.
|
||||
export function autoZoom(current, speed) {
|
||||
const target = Math.max(15.5, 18 - Math.max(0, speed * 3.6 - 20) * 0.024);
|
||||
const diff = target - current;
|
||||
if (Math.abs(diff) < 0.25) return null;
|
||||
return current + Math.sign(diff) * Math.min(Math.abs(diff), 0.15);
|
||||
}
|
||||
|
||||
// Meters between a MapLibre LngLat and [lon, lat] (equirectangular).
|
||||
function distanceM({ lng, lat }, [lon2, lat2]) {
|
||||
return Math.hypot((lon2 - lng) * Math.cos((lat * Math.PI) / 180), lat2 - lat) * 111320;
|
||||
@@ -129,15 +210,16 @@ export class GnssControl {
|
||||
return;
|
||||
}
|
||||
|
||||
this._status.textContent = fixLabel(data);
|
||||
// no fix, carried along the route (a tunnel: App.gnss_position)
|
||||
this._status.textContent = data.estimated ? "estimated (no fix)" : fixLabel(data);
|
||||
|
||||
const lngLat = [data.lon, data.lat];
|
||||
// Recenters on every fix while enabled — this is the app's own
|
||||
// receiver, so "GNSS on" means "follow it", the same way LocateControl
|
||||
// (public/js/locate.js) follows it when GNSS is what it's using too.
|
||||
// flyTo (with its zoom swoop) only for the first fix, since that's the
|
||||
// one jumping from wherever the map already was; easeTo for later
|
||||
// updates, a plain follow rather than repeating that swoop every poll.
|
||||
// startFollow (zooming in) only for the first fix, since that's the
|
||||
// one jumping from wherever the map already was; a plain follow for
|
||||
// later updates, zooming by the speed (autoZoom).
|
||||
const far = this._marker && distanceM(this._marker.getLngLat(), lngLat) > JUMP_M;
|
||||
if (far) this._removeMarker();
|
||||
if (!this._marker) {
|
||||
@@ -148,7 +230,7 @@ export class GnssControl {
|
||||
// survives map.setStyle() (switching Online/Offline) with no extra
|
||||
// re-add handling needed.
|
||||
this._marker = new Marker({ element: el, rotationAlignment: "map", pitchAlignment: "map" }).setLngLat(lngLat).addTo(this._map);
|
||||
this._map.flyTo({ center: lngLat, zoom: Math.max(this._map.getZoom(), 15) });
|
||||
startFollow(this._map, lngLat);
|
||||
} else {
|
||||
glideMarker(this._marker, lngLat, POLL_INTERVAL_MS);
|
||||
followPosition(this._map, lngLat, data.track, data.speed, POLL_INTERVAL_MS);
|
||||
@@ -162,9 +244,28 @@ export class GnssControl {
|
||||
}
|
||||
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;
|
||||
|
||||
+322
-167
@@ -4,9 +4,6 @@ import {
|
||||
GPX_ICON,
|
||||
NEW_FOLDER_ICON,
|
||||
UPLOAD_ICON,
|
||||
WAYPOINT_ICON,
|
||||
TRACK_ICON,
|
||||
ROUTE_ICON,
|
||||
DOWNLOAD_ICON,
|
||||
SYNC_ICON,
|
||||
MAP_MARKER_ICON,
|
||||
@@ -31,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
|
||||
@@ -118,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 & Points" aria-label="Tracks & 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());
|
||||
|
||||
@@ -161,6 +170,7 @@ export class GpxPanelControl {
|
||||
// panels.
|
||||
document.addEventListener("click", () => this._closeDownloadMenu());
|
||||
|
||||
this._setupFind();
|
||||
this._setupToolbarActions();
|
||||
this._setupRootDropTarget();
|
||||
this._setupMapDropTarget();
|
||||
@@ -183,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, {
|
||||
@@ -222,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);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -257,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) {
|
||||
@@ -346,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.
|
||||
@@ -584,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
|
||||
@@ -601,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);
|
||||
@@ -745,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
|
||||
|
||||
@@ -760,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({
|
||||
@@ -795,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({
|
||||
|
||||
+5
-6
@@ -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]);
|
||||
|
||||
+184
-181
@@ -17,10 +17,10 @@ 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";
|
||||
@@ -29,6 +29,8 @@ 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;
|
||||
@@ -103,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) {
|
||||
@@ -156,78 +127,13 @@ 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. Tilted, the ground is raised into
|
||||
@@ -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,27 +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"));
|
||||
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()));
|
||||
@@ -577,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) {
|
||||
@@ -588,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
|
||||
|
||||
+24
-6
@@ -8,19 +8,37 @@
|
||||
// map.js styles the map with it and /symbols.html draws its legend from the
|
||||
// same patched style, so the two can't drift apart.
|
||||
|
||||
// The driving view (the map tilted to 3D, as following does): route
|
||||
// numbers and minor roads' / paths' names hidden, the main roads' names
|
||||
// left — what's needed at a glance. Back as soon as the map is flat.
|
||||
// A ["pitch"] in the layers' filters (MapLibre ≥ 6.21), so they go already
|
||||
// while tilting, and come back with every style without a listener.
|
||||
const DRIVE_HIDDEN_LABELS = /^(highway-shield|road_shield|highway-name-(minor|path))/;
|
||||
const DRIVE_PITCH = 30;
|
||||
|
||||
function declutterWhenDriving(style) {
|
||||
for (const layer of style.layers) {
|
||||
if (!DRIVE_HIDDEN_LABELS.test(layer.id)) continue;
|
||||
const flat = ["<", ["pitch"], DRIVE_PITCH];
|
||||
layer.filter = layer.filter ? ["all", flat, layer.filter] : flat;
|
||||
}
|
||||
return style;
|
||||
}
|
||||
|
||||
export function patchOnlineStyle(style) {
|
||||
return insertTrackOnlyLayer(protectedAreasAndTextures(roadLabelSpacing(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. Past
|
||||
// z16 the spacing grows with the zoom: the same distance on the ground
|
||||
// (~400 m here) at every zoom.
|
||||
const ROAD_LABEL_FIXED_ZOOM = 16;
|
||||
// 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; // the style spec's default
|
||||
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;
|
||||
|
||||
@@ -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;
|
||||
|
||||
+33
-1
@@ -189,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;
|
||||
@@ -218,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());
|
||||
|
||||
@@ -246,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()}`);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -254,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;
|
||||
|
||||
@@ -123,6 +123,33 @@ export function notifyRouteChanged(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";
|
||||
|
||||
+43
-3
@@ -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")
|
||||
|
||||
+786
-83
File diff suppressed because it is too large.
Load diff
+42
-26
@@ -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");
|
||||
}
|
||||
}
|
||||
@@ -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 };
|
||||
}
|
||||
@@ -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();
|
||||
|
||||
+12
-5
@@ -5,23 +5,30 @@
|
||||
const CHECK_MS = 10 * 60 * 1000;
|
||||
const RESTART_POLL_MS = 5000;
|
||||
|
||||
export function setupUpdate(button) {
|
||||
export function setupUpdate(button, checkNow) {
|
||||
let latest = null;
|
||||
let timer = null;
|
||||
|
||||
async function check() {
|
||||
async function check(fresh = false) {
|
||||
clearTimeout(timer);
|
||||
try {
|
||||
const state = await (await fetch("/api/update", { cache: "no-store" })).json();
|
||||
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}`;
|
||||
setTimeout(check, CHECK_MS);
|
||||
timer = setTimeout(check, CHECK_MS);
|
||||
} catch {
|
||||
setTimeout(check, CHECK_MS);
|
||||
timer = setTimeout(check, CHECK_MS);
|
||||
}
|
||||
}
|
||||
checkNow?.addEventListener("click", () => check(true));
|
||||
|
||||
async function waitForRestart(revision) {
|
||||
try {
|
||||
|
||||
+3
-3
@@ -1,10 +1,10 @@
|
||||
/**
|
||||
* MapLibre GL JS
|
||||
* @license 3-Clause BSD. Full text of license: https://github.com/maplibre/maplibre-gl-js/blob/v6.20.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,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(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));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 jT=class{constructor(e){this.self=e,this.actor=new ws(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=is,this.self.removeProtocol=as,this.self.registerRTLTextPlugin=e=>{Sg.setMethods(e)},this.self.makeRequest=fs,this.self.setProjectionHandler=xT,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=AT(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 Sg.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 rT,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 mT(r,this._getLayerIndex(e),this._getAvailableImages(e));break;case`geojson`:this.workerSources[e][t][n]=new DT(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 hT,this.demWorkerSources[e][t]}};ke(self)&&(self.worker=new jT(self));export{jT 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
|
||||
+36
-36
@@ -1,8 +1,8 @@
|
||||
/**
|
||||
* MapLibre GL JS
|
||||
* @license 3-Clause BSD. Full text of license: https://github.com/maplibre/maplibre-gl-js/blob/v6.20.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.20.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 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;};`,XA=`#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 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;};`,ZA=`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
|
||||
}`,QA=`layout(location=0) in vec2 a_pos;void main() {gl_Position=projectTile(a_pos,a_pos);}`,$A=`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
|
||||
}`,ej=`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);}`,tj=`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
|
||||
}`,nj=`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
|
||||
@@ -123,15 +123,15 @@ vec2 angles=extrude*angle_scale;vec3 corner_vector=globeRotateVectorOffset(circl
|
||||
#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);}`,rj=`void main() {fragColor=vec4(1.0);}`;const ij={prelude:aj(YA,XA),projectionMercator:aj(`
|
||||
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:aj(`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 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 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:aj(ZA,QA),backgroundPattern:aj($A,ej),circle:aj(tj,nj),clippingMask:aj(rj,`layout(location=0) in vec2 a_pos;void main() {gl_Position=projectTile(a_pos,a_pos);}`),heatmap:aj(`uniform highp float u_intensity;in vec2 v_extrude;
|
||||
);}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() {
|
||||
@@ -154,11 +154,11 @@ vec2 angles=v_extrude*radius*u_globe_extrude_scale;vec3 center_vector=projectToS
|
||||
#else
|
||||
gl_Position=projectTileFor3D(circle_center+extrude,get_elevation(circle_center));
|
||||
#endif
|
||||
}`),heatmapTexture:aj(`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:aj(`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:aj(`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:aj(`#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
|
||||
@@ -166,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:aj(`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:aj(rj,`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:aj(`#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
|
||||
@@ -187,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:aj(`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
|
||||
@@ -216,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:aj(`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
|
||||
@@ -257,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:aj(`#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;
|
||||
@@ -288,7 +288,7 @@ 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:aj(`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
|
||||
@@ -322,7 +322,7 @@ float colorvalue=color.r*0.2126+color.g*0.7152+color.b*0.0722;v_color=vec4(0.0,0
|
||||
#ifdef GLOBE
|
||||
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*=opacity;}`),fillExtrusionPattern:aj(`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
|
||||
@@ -377,14 +377,14 @@ 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*=opacity;}`),hillshadePrepare:aj(`#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:aj(`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
|
||||
@@ -397,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:aj(`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
|
||||
@@ -443,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:aj(`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
|
||||
@@ -485,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:aj(`#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;
|
||||
@@ -549,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:aj(`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
|
||||
@@ -610,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(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:aj(`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
|
||||
@@ -667,7 +667,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(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:aj(`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
|
||||
@@ -744,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:aj(`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
|
||||
@@ -752,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:aj(`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
|
||||
@@ -766,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:aj(`#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
|
||||
@@ -799,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:aj(`#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;
|
||||
@@ -838,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:aj(`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:aj(`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:aj(`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:aj(`#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:aj(`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 aj(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
|
||||
@@ -891,7 +891,7 @@ uniform ${n} ${r} u_${i};
|
||||
#else
|
||||
${n} ${r} ${i} = u_${i};
|
||||
#endif
|
||||
`}),{fragmentSource:e,vertexSource:t,staticAttributes:r,staticUniforms:o}}const oj=`#define PROJECTION_MERCATOR`,sj=`mercator`;var cj=class{constructor(e=_p){this._cachedMesh=null,this._worldCoordinateHelper=e}get name(){return this._worldCoordinateHelper.name}get worldCoordinateHelper(){return this._worldCoordinateHelper}get useSubdivision(){return!1}get shaderVariantName(){return sj}get shaderDefine(){return oj}get shaderPreludeCode(){return ij.projectionMercator}get vertexShaderPreludeCode(){return ij.projectionMercator.vertexSource}get subdivisionGranularity(){return T_.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 jd;a.emplaceBack(0,0),a.emplaceBack(N,0),a.emplaceBack(0,N),a.emplaceBack(N,N);let o=e.createVertexBuffer(a,tw.members),s=ef.simpleSegment(0,0,4,2),c=new Yd;c.emplaceBack(1,0,2),c.emplaceBack(1,2,3);let l=e.createIndexBuffer(c);return this._cachedMesh=new ew(o,l,s),this._cachedMesh}recalculate(){}hasTransition(){return!1}};let lj;const uj=()=>lj||=new Pu({type:new q(R.projection.type,`type`)}),dj=new T_({fill:new w_(128,2),line:new w_(512,0),tile:new w_(128,32),stencil:new w_(128,1),circle:3});var fj=class{constructor(){this._tileMeshCache={}}get name(){return`vertical-perspective`}get worldCoordinateHelper(){return _p}get transitionState(){return 1}get useSubdivision(){return!0}get shaderVariantName(){return`globe`}get shaderDefine(){return`#define GLOBE`}get shaderPreludeCode(){return ij.projectionGlobe}get vertexShaderPreludeCode(){return ij.projectionMercator.vertexSource}get subdivisionGranularity(){return dj}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`?dj.stencil:dj.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=nw(e,t);return this._tileMeshCache[n]=r,r}recalculate(e){}hasTransition(){return!1}},pj=class extends $n{constructor(e,t){super(),this._transitionable=new Cu(uj(),`projection`,t),this.setProjection(e),this._transitioning=this._transitionable.untransitioned(),this.recalculate(new bu(0)),this._mercatorProjection=new cj,this._verticalPerspectiveProjection=new fj}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 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 mj(e,t){if(Array.isArray(e)){let n=hj(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 pj({type:e},t),cameraProjection:`globe`}}let n=WC(e);if(n)return{projection:new cj(new BC(n)),cameraProjection:`mercator`};switch(e){case`mercator`:return{projection:new cj,cameraProjection:`mercator`};case`globe`:return{projection:new pj({type:[`interpolate`,[`linear`],[`zoom`],11,`vertical-perspective`,12,`mercator`]},{}),cameraProjection:`globe`};case`vertical-perspective`:return{projection:new fj,cameraProjection:`vertical-perspective`};default:return F(`Unknown projection name: ${e}. Falling back to mercator projection.`),{pro
Line truncated
|
||||
`),b=v.concat(ij.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)}`)}oM(l,this.program);let w=LM(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=kM(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]);TM(e.terrainUniformBuffer,s)}if(mM(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 OM,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 zM(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 BM(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 VM=(e,t)=>({u_lightpos:new pf(e,t.u_lightpos),u_lightpos_globe:new pf(e,t.u_lightpos_globe),u_lightintensity:new X(e,t.u_lightintensity),u_lightcolor:new pf(e,t.u_lightcolor),u_vertical_gradient:new X(e,t.u_vertical_gradient),u_fill_translate:new Z(e,t.u_fill_translate)}),HM=(e,t)=>({u_lightpos:new pf(e,t.u_lightpos),u_lightpos_globe:new pf(e,t.u_lightpos_globe),u_lightintensity:new X(e,t.u_lightintensity),u_lightcolor:new pf(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 pf(e,t.u_scale),u_fade:new X(e,t.u_fade)}),UM=(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}},WM=(e,t,n,r,i,a,o)=>({...UM(e,t,n,r),...zM(a,e,o),u_height_factor:-(2**i.overscaledZ)/o.tileSize/8}),GM=(e,t)=>({u_fill_translate:new Z(e,t.u_fill_translate)}),KM=(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 pf(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)}),qM=(e,t)=>({u_fill_translate:new Z(e,t.u_fill_translate)}),JM=(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 pf(e,t.u_scale),u_fade:new X(e,t.u_fade),u_sdf_pattern:new Y(e,t.u_sdf_pat
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
|
||||
+114
-2
@@ -172,9 +172,48 @@ class AppTest < Minitest::Test
|
||||
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({ "interfaces" => {}, "nodes" => {}, "signals" => {}, "frames" => [], "available" => false }, json_body(request.get("/api/can", **logged_in_env)))
|
||||
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.
|
||||
@@ -482,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
|
||||
@@ -499,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
|
||||
@@ -679,6 +734,63 @@ class AppTest < Minitest::Test
|
||||
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")
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
require_relative "test_helper"
|
||||
require "maptool/can"
|
||||
require "maptool/can_recorder"
|
||||
require "timeout"
|
||||
|
||||
class CanTest < Minitest::Test
|
||||
@@ -66,6 +67,9 @@ class CanTest < Minitest::Test
|
||||
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
|
||||
@@ -98,4 +102,32 @@ class CanTest < Minitest::Test
|
||||
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
|
||||
@@ -85,6 +85,14 @@ class CanDiscoveryTest < Minitest::Test
|
||||
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" })
|
||||
|
||||
@@ -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
|
||||
@@ -22,6 +22,77 @@ class GnssSimTest < Minitest::Test
|
||||
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
|
||||
|
||||
@@ -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 & 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
|
||||
@@ -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
@@ -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
|
||||
+33
-4
@@ -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}})
|
||||
|
||||
@@ -154,20 +170,33 @@ class RoutingTest < Minitest::Test
|
||||
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" }])
|
||||
request = serve_once("HTTP/1.1 200 OK\r\nContent-Length: #{reply.bytesize}\r\n\r\n#{reply}") do |url|
|
||||
assert_equal({ name: "B", road_class: "motorway", speed_limit: "unlimited" }, Maptool::Routing.road(url, [[17.1, 48.1], [17.2, 48.2]]))
|
||||
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|
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
require_relative "test_helper"
|
||||
require "tmpdir"
|
||||
require "timeout"
|
||||
require_relative "../lib/maptool/trip"
|
||||
|
||||
class TripTest < Minitest::Test
|
||||
@@ -25,6 +26,93 @@ class TripTest < Minitest::Test
|
||||
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"))
|
||||
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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>
|
||||
+60
-8
@@ -4,7 +4,7 @@
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<meta name="color-scheme" content="light dark">
|
||||
<title>CANopen diagnostics</title>
|
||||
<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; }
|
||||
@@ -23,29 +23,63 @@
|
||||
.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>CANopen diagnostics</h1>
|
||||
<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></tr></thead><tbody></tbody></table></div>
|
||||
<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) => ({ "&": "&", "<": "<", ">": ">", '"': """ })[c]);
|
||||
const hex = (n, width) => "0x" + n.toString(16).toUpperCase().padStart(width, "0");
|
||||
const nodeName = (n) => `${n} <code>${hex(Number(n), 2)}</code>`;
|
||||
@@ -63,6 +97,22 @@
|
||||
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) {
|
||||
@@ -74,8 +124,8 @@
|
||||
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 ? "silent (heartbeat stopped)" : 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></tr>`;
|
||||
}), "No CANopen node heard yet.", 5);
|
||||
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>`),
|
||||
@@ -86,8 +136,9 @@
|
||||
.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>${(f.data.match(/../g) || []).join(" ")}</code></td><td>${age(f.at)}</td></tr>`),
|
||||
`<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);
|
||||
}
|
||||
|
||||
@@ -101,8 +152,9 @@
|
||||
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);
|
||||
status.className = silent.length ? "bad" : "";
|
||||
status.textContent = (silent.length ? `⚠ node ${silent.join(", ")} silent · ` : "") + `updated ${new Date().toLocaleTimeString()}`;
|
||||
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 {
|
||||
|
||||
@@ -19,6 +19,8 @@
|
||||
"/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 %>",
|
||||
@@ -38,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 %>",
|
||||
|
||||
+201
-109
@@ -1,14 +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 & 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__update" hidden></button>
|
||||
<button type="button" class="topbar__night"></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>
|
||||
@@ -23,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 & moon" hidden></span>
|
||||
</footer>
|
||||
</div>
|
||||
|
||||
<div id="profile-panel" class="profile-panel" hidden>
|
||||
@@ -39,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">×</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">✓</span>
|
||||
</button>
|
||||
<button type="button" class="basemap-panel__option" data-style="offline">
|
||||
<span>Offline</span>
|
||||
<span class="basemap-panel__check">✓</span>
|
||||
</button>
|
||||
</div>
|
||||
<div class="basemap-panel__list">
|
||||
<a class="basemap-panel__link" href="/symbols.html" target="_blank">Legend & symbols ↗</a>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div id="gpx-panel" class="gpx-panel" hidden<%= " data-sync-client" if sync_client %>>
|
||||
<div class="gpx-panel__header">
|
||||
<strong>Tracks & 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>
|
||||
@@ -72,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">×</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 & 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.
|
||||
@@ -106,10 +131,11 @@
|
||||
<button type="button" class="basemap-panel__close" aria-label="Close">×</button>
|
||||
</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>
|
||||
<!-- Filled by DebugControl (public/js/debug.js), logged-in only. -->
|
||||
<div class="debug-panel__body"></div>
|
||||
</div>
|
||||
|
||||
<div id="plugins-panel" class="basemap-panel" hidden>
|
||||
@@ -124,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">×</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>
|
||||
|
||||
@@ -235,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 & 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>
|
||||
@@ -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
@@ -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>
|
||||
@@ -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) => ({ "&": "&", "<": "<", ">": ">", '"': """ })[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
@@ -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) => ({ "&": "&", "<": "<", ">": ">", '"': """ })[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>
|
||||
Reference in new issue
Block a user