diff --git a/TODO.adoc b/TODO.adoc index 21cc0cf..3cb5059 100644 --- a/TODO.adoc +++ b/TODO.adoc @@ -17,6 +17,10 @@ independence from connectivity. * [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 +** [ ] Along the planned route (2026-12-01): Park4Night and overpass-pois fetch the whole + viewport/bbox today — a second mode for a corridor around the route (a few km either side): + the plugin contract gains the route (a polyline / buffered boxes, not one big bbox), the + results into the trip's folder ** [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 `` 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) @@ -113,6 +117,14 @@ plan from — the server does the heavy lifting. The UI is built for a mouse tod 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/): 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`). Still to do: the pictogram, the + planned route dashed behind, a walk from another device shown with it, visited points ** [ ] 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 ** [ ] The menu while driving: showing routes and points, editing the trip — all of it on the diff --git a/app.rb b/app.rb index bb78db1..b4009d4 100644 --- a/app.rb +++ b/app.rb @@ -15,6 +15,7 @@ require_relative "lib/maptool/can" require_relative "lib/maptool/can_discovery" require_relative "lib/maptool/gnss_sim" require_relative "lib/maptool/trip" +require_relative "lib/maptool/trip_log" require_relative "lib/maptool/updater" require_relative "lib/maptool/sync" require "ipaddr" @@ -414,6 +415,7 @@ module Maptool end return unless fix && fix[:lat] && fix[:lon] + TRIP_LOG.record(fix[:lon], fix[:lat], fix[:alt], 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| @@ -735,6 +737,32 @@ 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/ 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.json"), 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 get "/api/trip" do require_login! diff --git a/lib/maptool/trip_log.rb b/lib/maptool/trip_log.rb new file mode 100644 index 0000000..90cd207 --- /dev/null +++ b/lib/maptool/trip_log.rb @@ -0,0 +1,124 @@ +require "json" +require "time" +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/ . 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, written into the library every FLUSH_EVERY_S (a power cut + # loses that much at most) and at the end. A walk away from the car comes + # from another device's track put into the same folder (a FIT, LiveTrack). + class TripLog + MIN_STEP_M = 10 + FLUSH_EVERY_S = 60 + ROOT = "Trips".freeze + + def initialize(path, library:) + @path = path + @library = library + @mutex = Mutex.new + @state = begin + JSON.parse(File.read(path), symbolize_names: true) + rescue Errno::ENOENT, JSON::ParserError + {} + end + @flushed_at = 0 + end + + def active? + @mutex.synchronize { !!@state[:folder] } + 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 = @state[:points] || [] + result = { active: !!@state[:folder], folder: @state[:folder], started_at: @state[:started_at], points: points.size, + distance_m: TrackStats.compute(points.map { |p| p.first(3) })["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 (#{@state[:folder]})" if @state[:folder] + + 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? + @state = { folder: folder, started_at: now.to_i, points: [], item: nil } + save + 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 @state[:folder] + + last = @state[:points].last + return if last && GnssSim.meters(last, [lon, lat]) < MIN_STEP_M + + @state[:points] << [lon, lat, alt, at.to_f.round(1)] + flush if at.to_f - @flushed_at >= FLUSH_EVERY_S + end + end + + # Ends it: the track written a last time. Returns the folder. + def stop + @mutex.synchronize do + folder = @state[:folder] or return nil + flush + @state = {} + save + folder + end + end + + private + + # The car's track into the library (made on the first flush, replaced + # after), the state file with it. + def flush + points = @state[:points] + 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(@state[: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 @state[:item] + @library.update_feature(@state[:item], @state[:item].delete_prefix("item:"), feature) + else + @state[:item] = @library.import_features([feature], folder: @state[:folder]).find { |key| key.start_with?("item:") } + end + end + @flushed_at = points.last ? points.last[3] : 0 + save + end + + def save + File.write("#{@path}.tmp", JSON.generate(@state)) + File.rename("#{@path}.tmp", @path) + end + end +end diff --git a/public/css/style.css b/public/css/style.css index 0a9bac2..2d7ffdd 100644 --- a/public/css/style.css +++ b/public/css/style.css @@ -30,6 +30,7 @@ --inst-active: #a21caf; /* magenta: the route / waypoint / lane being followed */ --inst-selected: #00799a; /* cyan: a value set by hand */ --route-planned: #1d6fdc; + --route-driven: #c2410c; /* the recorded trip log: really driven */ --route-active: var(--inst-active); /* road signs: still the sign (white disc, red ring), dimmed by night */ --sign-bg: #ffffff; @@ -57,6 +58,7 @@ --inst-active: #cc45e0; --inst-selected: #12bedf; --route-planned: #3f86e0; + --route-driven: #ea7a3c; /* the recorded trip log: really driven */ --sign-bg: #e4e1d6; --sign-ring: #c42b26; } @@ -87,6 +89,7 @@ --sign-bg: #6b675e; --sign-ring: #8a231b; --sign-fg: #0c0c0b; + --route-driven: #9a5a32; } /* The palette follows the night mode (map.js sets data-palette); the @@ -3683,3 +3686,18 @@ html.follow-3d .maplibregl-ctrl-overview-map { display: none; } .drive-trip__stops .drive-bar__stop-done { width: 68px; font-size: 24px; border-left: 1px solid var(--ui-line); color: var(--ui-muted); } .drive-trip__stops .drive-bar__stop-done.active { color: var(--inst-ok); font-weight: 700; } .route-marker--passed { opacity: 0.45; } +.drive-trip__log { display: flex; align-items: center; gap: 12px; padding: 10px 12px; border-bottom: 1px solid var(--ui-line); } +.drive-trip__log[hidden] { display: none; } +.drive-trip__log button { + min-height: 60px; + padding: 0 18px; + border: 2px solid var(--route-driven); + border-radius: 10px; + background: none; + color: var(--ui-fg); + font-size: 18px; + font-weight: 700; + cursor: pointer; +} +.drive-trip__log button.drive-trip__log--on { background: var(--route-driven); color: #fff; } +.drive-trip__log-state { flex: 1; color: var(--route-driven); font-weight: 600; font-size: 15px; } diff --git a/public/js/driving.js b/public/js/driving.js index 62dd5d8..80a9ec6 100644 --- a/public/js/driving.js +++ b/public/js/driving.js @@ -2,6 +2,7 @@ import { LngLatBounds } 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"; // Driving mode: the few things needed on the road as big buttons, the // planning sidebar and panels out of the way. After the research in @@ -13,6 +14,8 @@ const KEY = "drivingMode"; const PITCH_3D = 60; // as map.js's 3D toggle const CHECK_MS = 1000; // how often the recenter button looks whether the map follows 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 escapeHtml = (text) => String(text).replace(/[&<>"]/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """ })[c]); @@ -66,6 +69,7 @@ export function setupDriving(map, nightButton, routePanel) { tripPanel.className = "drive-trip"; tripPanel.hidden = true; tripPanel.innerHTML = `
Trip
+
    @@ -169,6 +173,61 @@ export function setupDriving(map, nightButton, routePanel) { }); tripPanel.querySelector('[data-action="start"]').addEventListener("click", () => routePanel?.startHere()); routePanel?.onStopsChanged(renderTrip); + + // 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-state"); + 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 (record it)"; + logButton.classList.toggle("drive-trip__log--on", !!log?.active); + logState.textContent = log?.active ? `● ${log.folder.replace(/^Trips\//, "")} · ${(log.distance_m / 1000).toFixed(1)} km` : ""; + }; + logButton.addEventListener("click", async () => { + if (log?.active) { + if (!window.confirm(`End the trip "${log.folder}"? Its track stays in the library.`)) return; + await fetch("/api/trip/log", { method: "DELETE" }); + } else { + 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 tripPanel.querySelector(".drive-trip__log").hidden = true; window.addEventListener("resize", placeCrosshair); map.getContainer().append(bar, recenter, tripPanel, crosshair); diff --git a/test/test_trip_log.rb b/test/test_trip_log.rb new file mode 100644 index 0000000..cf64cbe --- /dev/null +++ b/test/test_trip_log.rb @@ -0,0 +1,37 @@ +require_relative "test_helper" +require "tmpdir" +require "maptool/library" +require "maptool/gpx_store" +require "maptool/trip_log" + +class TripLogTest < Minitest::Test + # Start makes the folder with the plan and its named stops; fixes 10 m + # apart become the car's track (written on the first flush, replaced + # after); stop closes it. + def test_a_trip_records_into_its_folder + Dir.mktmpdir do |dir| + library = Maptool::Library.new(File.join(dir, "library.sqlite"), gpx_store: Maptool::GpxStore.new(File.join(dir, "gpx")), sources_dir: File.join(dir, "sources")) + log = Maptool::TripLog.new(File.join(dir, "trip_log.json"), library: library) + 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) # a minute on: flushed + 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? + + names = library.nodes.flat_map { |label, _key, _stamp, read| [label, *JSON.parse(read.call)["features"].map { |f| f.dig("properties", "name") }] }.compact + assert(library.nodes.all? { |label, *| label.include?("2026-12-01 Tatry") }) # all in the trip's folder + assert_includes names.join(" "), "Camp" + assert_includes names.join(" "), "Car 2026-12-01" + assert_includes names.join(" "), "Plan" + refute_includes names.join(" "), "My position" + end + end +end diff --git a/views/status.erb b/views/status.erb index 826f9ac..5563a78 100644 --- a/views/status.erb +++ b/views/status.erb @@ -42,7 +42,7 @@ // big exports (library, sync feed). const ENDPOINTS = [ "/api/health", "/api/update", "/api/can", "/api/gnss/position", "/api/sim/gnss", - "/api/trip", "/api/vehicles", "/api/live", "/api/livetrack/sessions", + "/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",