Compare commits

..
2 Commits
13 changed files with 25 additions and 264 deletions

No files matched your search

+1 -1
View File
@@ -13,7 +13,7 @@ Early scaffold. The web application serves a vector map (MapLibre GL
JS), with an online style and an optional offline style backed by a local
PMTiles file, an animated RainViewer radar overlay, GPX
upload/display (points and tracks, organized in folders), and a live
position marker from a local GNSS receiver via gpsd.
position marker from the car's GNSS receiver (over CAN, to come).
== Requirements
+6 -15
View File
@@ -10,7 +10,6 @@ require_relative "lib/maptool/gpx_store"
require_relative "lib/maptool/library"
require_relative "lib/maptool/google_saved"
require_relative "lib/maptool/routing"
require_relative "lib/maptool/gpsd_client"
require_relative "lib/maptool/mqtt_client"
require_relative "lib/maptool/live_store"
require_relative "lib/maptool/livetrack_store"
@@ -301,11 +300,12 @@ module Maptool
redirect "/"
end
# Live GNSS position, polled by the frontend from /api/gnss/position. A
# single background thread reads gpsd (if it's running — harmless retry
# loop if not, see GpsdClient) and keeps this updated; polling instead
# of push (SSE/WebSocket) is deliberate — gpsd itself only reports at
# ~1Hz, so there is nothing to gain from a push channel, and it avoids
# Live GNSS position, polled by the frontend from /api/gnss/position.
# No receiver feeds it for now: gpsd support was dropped, the car's
# GNSS is to come over CAN (TODO.adoc) and will fill GNSS_LATEST the
# same way. Polling instead of push (SSE/WebSocket) is deliberate — a
# receiver reports at ~1Hz, so there is nothing to gain from a push
# channel, and it avoids
# Sinatra's `stream(:keep_open)` helper, which — absent an EventMachine
# reactor (i.e. under plain threaded Puma, as here) — busy-loops calling
# its block repeatedly instead of waiting for external writes; fine for
@@ -320,15 +320,6 @@ module Maptool
GNSS_LATEST = {}
GNSS_LATEST_MUTEX = Mutex.new
Thread.new do
GpsdClient.new.each_position do |position|
GNSS_LATEST_MUTEX.synchronize do
GNSS_LATEST.replace(position)
GNSS_LATEST[:received_at] = Time.now.to_f
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
-73
View File
@@ -1,73 +0,0 @@
#!/usr/bin/env ruby
# frozen_string_literal: true
# Speaks gpsd's own JSON wire protocol (https://gpsd.io/gpsd_json.html)
# directly on gpsd's default port — GpsdClient (lib/maptool/gpsd_client.rb)
# connects to it exactly as it would to real gpsd, so no app code or config
# changes are needed. Unlike docs/development.adoc's fake-NMEA-source
# example, this doesn't need gpsd itself installed/running at all, and
# actually moves (a fixed point isn't much of a "GNSS position" to look
# at) — drives a loop around a center point at a driving-ish pace, one TPV
# report per second like a real receiver.
#
# Usage: bin/gnss_simulator.rb [lat] [lon] [radius_m] [port]
require "socket"
require "json"
$stdout.sync = true
LAT = (ARGV[0] || 48.1486).to_f
LON = (ARGV[1] || 17.1077).to_f
RADIUS_M = (ARGV[2] || 300).to_f
PORT = (ARGV[3] || 2947).to_i
LOOP_SECONDS = 120 # time to complete one full loop
EARTH_RADIUS_M = 6_371_000
def point_on_loop(center_lat, center_lon, radius_m, angle_rad)
# Flat-plane offset, not geodesic — fine at this radius (metres, not km),
# same reasoning as measure.js's own approximations at this scale.
lat_offset = (radius_m * Math.sin(angle_rad)) / EARTH_RADIUS_M
lon_offset = (radius_m * Math.cos(angle_rad)) / (EARTH_RADIUS_M * Math.cos(center_lat * Math::PI / 180))
[center_lat + lat_offset * 180 / Math::PI, center_lon + lon_offset * 180 / Math::PI]
end
server = TCPServer.new("127.0.0.1", PORT)
puts "[gnss-simulator] driving a #{RADIUS_M.to_i}m loop around #{LAT},#{LON} — listening on 127.0.0.1:#{PORT}"
loop do
socket = server.accept
puts "[gnss-simulator] client connected"
start = Time.now
begin
loop do
elapsed = Time.now - start
angle = (elapsed / LOOP_SECONDS) * 2 * Math::PI
lat, lon = point_on_loop(LAT, LON, RADIUS_M, angle)
# Bearing of travel (compass: 0 = north, clockwise). The loop runs
# counterclockwise from east (angle is a math angle), so the velocity
# points (east, north) = (-sin, cos): bearing atan2(-sin, cos) = -angle.
track = (-angle * 180 / Math::PI) % 360
speed = (2 * Math::PI * RADIUS_M) / LOOP_SECONDS # m/s, constant pace
report = {
class: "TPV",
mode: 3,
lat: lat,
lon: lon,
altHAE: 150.0,
speed: speed,
track: track,
eph: 3.0,
time: Time.now.utc.strftime("%Y-%m-%dT%H:%M:%S.%3NZ"),
}
socket.puts(JSON.generate(report))
sleep 1
end
rescue Errno::EPIPE, IOError
puts "[gnss-simulator] client disconnected"
ensure
socket.close
end
end
+1 -18
View File
@@ -91,28 +91,11 @@ services:
# files inherit the directory's label.
- /srv/backup/gdrive/my-drive/current/Takeout:/app/takeout:ro,z
# Fakes a GNSS fix (a loop around Bratislava, see
# bin/gnss_simulator.rb/docs/development.adoc) since there's no real
# receiver attached here — the "GNSS" control would otherwise just show
# "no fix" always. Remove this service (and nothing else) whenever a real
# receiver/gpsd setup replaces it. network_mode ties it to maptool's own
# network namespace rather than a bridge network, since GpsdClient
# connects to a hardcoded 127.0.0.1:2947 — same as gpsd itself normally
# being local to the machine it serves.
gnss-simulator:
image: maptool:latest
depends_on:
- maptool
restart: unless-stopped
network_mode: "service:maptool"
command: ["ruby", "bin/gnss_simulator.rb"]
# Serves an offline Wikipedia ZIM for the popup's "Nearby on Wikipedia"
# link (see docs/development.adoc for where to get one and drop it in —
# same "not part of the repo, place it under ./data locally" story as
# offline.pmtiles/terrain.pmtiles). On the default compose network (not
# network_mode: "service:maptool" — unlike gnss-simulator this doesn't
# need a hardcoded localhost port, KIWIX_URL above reaches it by this
# network_mode: "service:maptool" — KIWIX_URL above reaches it by this
# service's own name), so maptool and kiwix stay independent containers.
# Keeps restarting (harmlessly) if data/kiwix/wikipedia.zim isn't there
# yet — GET /api/kiwix just reports unavailable until it comes up.
+7 -13
View File
@@ -238,8 +238,7 @@ may not even read the same way there.
`GeolocateControl` — same button, reusing its exact CSS classes/icon
(`.maplibregl-ctrl-geolocate`) rather than a new one, so it's a visual
drop-in — but sourced differently. This app has its own GNSS receiver
(gpsd, possibly `bin/gnss_simulator.rb`'s simulated one — see
`docs/development.adoc`/`docs/deployment.adoc`), and "find my
(over CAN in the car, to come; see TODO.adoc), and "find my
location" should mean that receiver, not a device's separate (and
often less accurate, e.g. wifi-based) location service — but only
once it's actually turned on, via the sidebar's "GNSS" icon
@@ -695,23 +694,18 @@ toggling is a cheap re-render of just that strip.
== Live GNSS position
A "GNSS" map control (`public/js/gnss.js`) shows the fix from a local
GNSS receiver (a real one, plugged into the machine running the
server, or `bin/gnss_simulator.rb`'s simulated one — distinct from
GNSS receiver (the car's, over CAN, to come — distinct from
`LocateControl`'s browser-geolocation fallback, `navigator.geolocation`,
which the OS may or may not derive from such a receiver at all —
see "Finding your location" above).
`lib/maptool/gpsd_client.rb` is a small client for
https://gpsd.io[gpsd]'s JSON protocol over TCP (port 2947 by default):
it watches for TPV — "time-position-velocity", gpsd's term for a fix —
reports and yields each as a plain hash, reconnecting on any I/O error
so a receiver that isn't plugged in yet (or gpsd not running) is not
fatal. `app.rb` runs one of these in a background thread for the
whole process and keeps the latest fix in `GNSS_LATEST`, guarded by a
mutex since the HTTP threads read it concurrently.
Nothing feeds it for now: gpsd support was dropped in favor of the
car's GNSS over CAN. Whatever reads the receiver keeps the latest fix
in `app.rb`'s `GNSS_LATEST`, guarded by a mutex since the HTTP threads
read it concurrently.
`GET /api/gnss/position`, polled by the frontend every 1.5s, is a
deliberate choice over a push channel (SSE/WebSocket): gpsd itself
deliberate choice over a push channel (SSE/WebSocket): a receiver
only reports at roughly 1Hz, so a push channel buys nothing here, and
it sidesteps a real problem — Sinatra's `stream(:keep_open)` helper,
absent an EventMachine reactor (i.e. under plain threaded Puma, as
-12
View File
@@ -175,18 +175,6 @@ topics. Blank `MQTT_URL` turns it off. The URL needs a name the
container can resolve — `ha.local` (mDNS) doesn't resolve inside it,
`mqtt://ha.priesol.net:1883` does.
== GNSS simulator
`docker-compose.yaml`'s `gnss-simulator` service (`bin/gnss_simulator.rb`,
also documented for local dev in `docs/development.adoc`) runs
alongside `maptool` in production too, sharing its network namespace
(`network_mode: "service:maptool"`) so it's reachable at the
hardcoded `127.0.0.1:2947` `Maptool::GpsdClient` expects — there's no
real GNSS receiver attached to the server, so without this the "GNSS"
control would just always show "no fix". It drives a loop around
Bratislava; remove the service block (nothing else needs to change)
whenever a real receiver/gpsd setup replaces it.
== Garmin LiveTrack session webhook
`POST /api/livetrack/session` (`session_id`, `session_token`, `secret` form
-67
View File
@@ -325,73 +325,6 @@ through this app's own proxy rather than at kiwix-serve directly — it
already has a full search UI of its own, this just makes it reachable
through the same origin/reverse proxy as the rest of the app.
== GNSS position (gpsd)
The "GNSS" control needs https://gpsd.io[gpsd] running and pointed at
a receiver (`gpsd /dev/ttyUSB0`, or whatever device the receiver shows
up as). On openSUSE, `gpsd` is a package with systemd units
(`gpsd.service` / `gpsd.socket`); on other distributions, check your
package manager. No app-side configuration is needed — it just
connects to `127.0.0.1:2947`, gpsd's default port.
To test without hardware or gpsd itself installed/running, run
`bin/gnss_simulator.rb` — it speaks gpsd's own JSON wire protocol
directly on gpsd's default port (`127.0.0.1:2947`), so
`Maptool::GpsdClient` connects to it exactly as it would to real
gpsd, no app-side changes needed. Drives a loop around a center point
(Bratislava by default) at a driving-ish pace instead of sitting at a
fixed position, since a stationary "GNSS position" isn't much to look
at on the map:
[source,shell]
----
bin/gnss_simulator.rb # loop around Bratislava, 300m radius
bin/gnss_simulator.rb 48.85 2.35 500 # custom center/radius (Paris, 500m)
----
`GET /api/gnss/position` should report a fix within a couple of
seconds, moving on every poll.
To test against gpsd itself instead (e.g. to exercise the actual
NMEA-parsing path, not just gpsd's JSON output), feed it a fake NMEA
stream over TCP instead of a real serial device — gpsd accepts a
`tcp://host:port` source:
[source,shell]
----
# terminal 1: a TCP server repeating one NMEA GGA/RMC sentence pair
python3 - <<'PY' 5001
import socket, sys, time
def checksum(s):
cs = 0
for ch in s:
cs ^= ord(ch)
return f"{cs:02X}"
def sentence(body):
return f"${body}*{checksum(body)}\r\n"
port = int(sys.argv[1])
srv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
srv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
srv.bind(("127.0.0.1", port))
srv.listen(1)
conn, _ = srv.accept()
gga = "GPGGA,123519,4808.916,N,01706.462,E,1,08,0.9,140.4,M,46.9,M,,"
rmc = "GPRMC,123519,A,4808.916,N,01706.462,E,000.5,084.4,230824,003.1,W"
while True:
conn.sendall((sentence(gga) + sentence(rmc)).encode())
time.sleep(1)
PY
# terminal 2: point gpsd at it instead of a real device
gpsd -N -n tcp://127.0.0.1:5001
----
`GET /api/gnss/position` should then report the fake fix (Bratislava
Castle, in the sentences above) within a couple of seconds.
== Tests
`bundle exec rake test` runs the whole suite (`test/test_*.rb`,
+1 -1
View File
@@ -166,7 +166,7 @@ Offline routing runs https://github.com/valhalla/valhalla[Valhalla]
over the same Geofabrik extracts (ODbL). See `docs/routing-design.adoc`.
Not a frontend asset like the above, but also baked into this app's own
Docker image (not a separate container the way kiwix-serve/gpsd are —
Docker image (not a separate container the way kiwix-serve is —
see `docs/deployment.adoc`/`docs/development.adoc`): three CLI tools
`lib/maptool/pmtiles_builder.rb` shells out to for offline.pmtiles/
terrain.pmtiles regeneration.
-57
View File
@@ -1,57 +0,0 @@
require "socket"
require "json"
module Maptool
# A minimal client for gpsd's JSON protocol (https://gpsd.io/gpsd_json.html).
# Connects over TCP, asks gpsd to watch for reports, and yields a plain
# position hash for every TPV ("time-position-velocity") report — gpsd's
# term for a GNSS fix — for as long as the block keeps running.
class GpsdClient
RECONNECT_DELAY = 5 # seconds, after gpsd is unreachable or drops us
def initialize(host: "127.0.0.1", port: 2947)
@host = host
@port = port
end
# Never returns under normal operation: reconnects on any I/O error
# (gpsd not running yet, connection dropped, etc.) after a short delay,
# so a missing/disconnected receiver is not fatal to the caller.
def each_position
loop do
watch { |position| yield position }
rescue SystemCallError, EOFError, SocketError => e
warn "[gpsd] #{e.class}: #{e.message} — retrying in #{RECONNECT_DELAY}s"
sleep RECONNECT_DELAY
end
end
private
def watch
socket = TCPSocket.new(@host, @port)
socket.puts('?WATCH={"enable":true,"json":true};')
socket.each_line do |line|
report = JSON.parse(line)
next unless report["class"] == "TPV"
next unless report["lat"] && report["lon"]
yield(
lat: report["lat"],
lon: report["lon"],
# altHAE (height above ellipsoid) is gpsd's modern field; older
# gpsd versions only send "alt".
alt: report["altHAE"] || report["alt"],
speed: report["speed"],
track: report["track"],
mode: report["mode"], # 0/1 = no fix, 2 = 2D, 3 = 3D
eph: report["eph"], # estimated horizontal position error, metres
time: report["time"],
)
end
ensure
socket&.close
end
end
end
+1 -1
View File
@@ -4,7 +4,7 @@ require "securerandom"
require "uri"
module Maptool
# A minimal MQTT 3.1.1 subscriber (stdlib only, like GpsdClient): connects,
# A minimal MQTT 3.1.1 subscriber (stdlib only): connects,
# subscribes to a few topics at QoS 0 and yields every message, for as long
# as the block keeps running. Enough for reading sensor topics off the home
# broker; no publishing, no QoS 1/2 delivery guarantees, no persistent
+3 -3
View File
@@ -5,11 +5,11 @@ import { isLoggedIn } from "/js/auth.js";
const POSITION_URL = "/api/gnss/position";
const POLL_INTERVAL_MS = 1500;
// A sidebar icon that polls /api/gnss/position (backed server-side by a
// gpsd connection, see lib/maptool/gpsd_client.rb) and shows the fix as a
// A sidebar icon that polls /api/gnss/position (the car's receiver, fed
// server-side into GNSS_LATEST in app.rb) and shows the fix as a
// marker, with fix status in a flyout. Polling rather than a push channel
// is deliberate — see the comment in app.rb next to GNSS_LATEST — and fits
// gpsd's own ~1Hz report rate fine.
// a receiver's ~1Hz report rate fine.
// One follow step for a moving position (this receiver, the browser's own
// geolocation). In the 3D (pitched) view it turns heading-up like a car
// navigation, with the position in the lower part of the screen; the last
+2 -2
View File
@@ -378,8 +378,8 @@ if (isLoggedIn()) map.addControl(new NotesControl(), "top-left");
// element) can still happen later.
const gnssControl = new GnssControl(map);
// Not MapLibre's own GeolocateControl (browser Geolocation API only) —
// this app has its own GNSS receiver (gpsd, possibly a simulated one, see
// bin/gnss_simulator.rb), and "find my location" should prefer that over a
// this app has its own GNSS receiver (the car's, see app.rb's
// GNSS_LATEST), and "find my location" should prefer that over a
// 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.
+3 -1
View File
@@ -741,7 +741,9 @@ class PmtilesBuilderTest < Minitest::Test
assert_equal ["new", "old"], [File.read(dest), File.read(linked)]
serve_once("HTTP/1.1 200 OK\r\nContent-Length: 100\r\n\r\ncut") do |url|
assert_raises(StandardError) { Maptool::PmtilesBuilder.download_extract(url, dest) }
# The last attempt: a cut-off body is retried otherwise, and this
# server answers once.
assert_raises(StandardError) { Maptool::PmtilesBuilder.download_extract(url, dest, attempt: Maptool::PmtilesBuilder::DOWNLOAD_ATTEMPTS) }
end
assert_equal "new", File.read(dest)
refute File.exist?("#{dest}.part")