CANopen diagnostics and map data over HTTPS: /can.html (interfaces, nodes with heartbeat state and last EMCY, decoded signals, every COB-ID with role, count, rate and last data); signals can mark an invalid raw value (esphome-canopen's unknown) and NaN gives no value; the CAN reader never dies and a broken can.json only turns CAN off; the GNSS node mcu-stm32-xiao-c5-2 (0x21) and host networking for the car's server in docs; bin/pull-maps.sh pulls map data from GET /api/sync/maps(/file) with SYNC_TOKEN instead of rsync over SSH, resuming cut-off downloads
CI / check (push) Successful in 42s
CI / deploy (push) Successful in 18s

This commit is contained in:
randy committed 2026-11-29 12:47:23 +01:00
1 parent a3e5fefaf1
commit 6a0d6194fe
9 files changed
+365 -43

No files matched your search

+14 -2
View File
@@ -167,7 +167,18 @@ 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 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`; ** [ ] The car-CAN → CANopen bridge's mapping (not decided yet) as signals in `data/can.json`;
a dashboard panel for the `car.*` signals a dashboard panel for the `car.*` signals
** [ ] The GNSS node's PDO layout (lat/lon i32 × 1e-7, speed, course, fix) as `gnss.*` signals ** [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)
** [ ] Discover our esphome-canopen nodes over SDO (0x1008 name, 0x2001 entity types,
0x2000+0x10·N names/units/min/max, 0x1A00+n TPDO mapping): their entities decoded with no
`can.json`; 0x1008/0x1018 identity for any CANopen device
** [ ] A configurable dashboard overlay over the map (like dashcams burn it in): widgets picked
and placed per screen, each bound to a signal — speed, turn signals, brake, … — and one
combined inclinometer (Pajero style, but one instrument, not three): compass heading, pitch
and roll, all from the GNSS node (pitch/roll already in its TPDO1; the HMC5883L compass
still to add to its firmware); GNSS course as the heading until then
=== 3D navigation mode === 3D navigation mode
@@ -199,7 +210,8 @@ already offline work on the road. The Pi only serves; heavy builds stay on brick
without login (e.g. `TRUSTED_NETWORKS` CIDR list), or a local fallback account without login (e.g. `TRUSTED_NETWORKS` CIDR list), or a local fallback account
* [ ] HTTPS on the LAN (the secure session cookie, the PWA and the service worker need it): * [ ] 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 the same hostname resolved to the Pi by the car router's DNS, Let's Encrypt cert via DNS-01
* [ ] A touch display on the Pi itself (USB touchscreen, Chromium in kiosk mode on * [ ] A touch display on the Pi itself (a portable ~16" USB touchscreen, the co-driver's —
the navigator plans on it while driving; Chromium in kiosk mode on
`http://localhost`) as the car display — solves a lot at once: localhost is a secure `http://localhost`) as the car display — solves a lot at once: localhost is a secure
context (no certificate needed for the PWA/service worker) and can skip login, it doesn't context (no certificate needed for the PWA/service worker) and can skip login, it doesn't
depend on the car's Wi-Fi, buttons plug straight into the Pi (a USB/BLE keypad is just a depend on the car's Wi-Fi, buttons plug straight into the Pi (a USB/BLE keypad is just a
+44 -2
View File
@@ -221,6 +221,22 @@ module Maptool
SYNC_SERVER_URL = ENV.fetch("SYNC_SERVER_URL", "") SYNC_SERVER_URL = ENV.fetch("SYNC_SERVER_URL", "")
SYNC_CLIENT = SYNC_TOKEN.empty? || SYNC_SERVER_URL.empty? ? nil : Sync.new(server: SYNC_SERVER_URL, token: SYNC_TOKEN, library: LIBRARY, state_path: File.join(DATA_DIR, "sync_state.json")) SYNC_CLIENT = SYNC_TOKEN.empty? || SYNC_SERVER_URL.empty? ? nil : Sync.new(server: SYNC_SERVER_URL, token: SYNC_TOKEN, library: LIBRARY, state_path: File.join(DATA_DIR, "sync_state.json"))
SYNC_MUTEX = Mutex.new SYNC_MUTEX = Mutex.new
# Map data the server hands its clients (GET /api/sync/maps, pulled by
# bin/pull-maps.sh — one way, the server builds it): these files and
# everything under these directories of DATA_DIR.
MAP_SYNC_FILES = %w[offline.pmtiles offline.pmtiles.meta.json terrain.pmtiles terrain.pmtiles.meta.json offline_regions.json].freeze
MAP_SYNC_DIRS = %w[routing places hiking_trails kiwix nps].freeze
# { "relative/path" => absolute path } of the map data there is now;
# hidden and temporary files (.rsync-partial, *.part, *.tmp) left out,
# and routing/service.sh (each server copies its own in at boot).
def self.map_sync_files
paths = MAP_SYNC_FILES.map { |f| File.join(DATA_DIR, f) } +
MAP_SYNC_DIRS.flat_map { |d| Dir.glob(File.join(DATA_DIR, d, "**", "*")) }
paths.select { |p| File.file?(p) }
.to_h { |p| [p.delete_prefix("#{DATA_DIR}/"), p] }
.reject { |rel, _| rel.split("/").any? { |part| part.start_with?(".") } || rel.match?(/\.(part|tmp)\z|[\t\n]/) || rel == "routing/service.sh" }
end
helpers do helpers do
def logged_in? def logged_in?
@@ -358,9 +374,16 @@ module Maptool
# counts from the frame that brings lat or lon. # counts from the frame that brings lat or lon.
CAN_CONFIG_PATH = File.join(DATA_DIR, "can.json") CAN_CONFIG_PATH = File.join(DATA_DIR, "can.json")
CAN_STORE = Can::Store.new CAN_STORE = Can::Store.new
CAN_CONFIG = File.exist?(CAN_CONFIG_PATH) ? JSON.parse(File.read(CAN_CONFIG_PATH)) : nil # A broken can.json turns CAN off (logged) instead of the whole server.
CAN_CONFIG, CAN_DECODER = begin
config = JSON.parse(File.read(CAN_CONFIG_PATH)) if File.exist?(CAN_CONFIG_PATH)
[config, config && Can::Decoder.new(config.fetch("signals", []))]
rescue StandardError => e
warn "can: #{CAN_CONFIG_PATH}: #{e.message} — CAN off"
[nil, nil]
end
if CAN_CONFIG && !test? if CAN_CONFIG && !test?
decoder = Can::Decoder.new(CAN_CONFIG.fetch("signals", [])) decoder = CAN_DECODER
CAN_CONFIG.fetch("interfaces", []).each do |interface| CAN_CONFIG.fetch("interfaces", []).each do |interface|
Thread.new do 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"]) do |values|
@@ -414,6 +437,11 @@ module Maptool
erb :symbols, layout: false erb :symbols, layout: false
end end
# CANopen diagnostics (polls GET /api/can, which needs the login).
get "/can.html" do
erb :can, layout: false
end
# A share to the installed app normally never reaches the server: the # A share to the installed app normally never reaches the server: the
# service worker (public/sw.js) takes the POST, parks the files and # 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 # opens the app. Only lands here if no worker is running yet — back to
@@ -866,6 +894,20 @@ module Maptool
halt 400, json(error: "bad source path") halt 400, json(error: "bad source path")
end end
# Map data for bin/pull-maps.sh: one "size<TAB>mtime<TAB>path" line per
# file, then each file by its path (Range requests resume a cut-off one).
get "/api/sync/maps" do
require_sync_token!
content_type :text
App.map_sync_files.sort.map { |rel, path| [File.size(path), File.mtime(path).to_i, rel].join("\t") }.join("\n") + "\n"
end
get "/api/sync/maps/file" do
require_sync_token!
path = App.map_sync_files[params[:path].to_s] or halt 404
send_file path
end
# The Sync button (a client only): pull, then push, now. # The Sync button (a client only): pull, then push, now.
post "/api/sync/run" do post "/api/sync/run" do
require_login! require_login!
+74 -23
View File
@@ -1,37 +1,88 @@
#!/bin/bash #!/bin/bash
# Map data, one way: the home server (brick) builds it, the car's server # Map data, one way: the main server (brick) builds it, the car's server
# pulls it — only while at home (brick reachable), never over LTE. The # pulls it over HTTPS from the same public URL and SYNC_TOKEN as the
# library goes both ways on its own (lib/maptool/sync.rb), not here. # library sync (no SSH/VPN): GET /api/sync/maps lists the files, each one
# comes from /api/sync/maps/file, a cut-off download resumes. The library
# goes both ways on its own (lib/maptool/sync.rb), not here.
# #
# Run by maptool-pull-maps.timer on the car's server (docs/deployment.adoc). # Run by maptool-pull-maps.timer on the car's server (docs/deployment.adoc).
# The key it uses is limited on brick to read-only rsync of the data dir: # Big files (GBs), so by default only at home: when HOME_HOST answers.
# command="python3 /usr/share/doc/packages/rsync/support/rrsync -ro /srv/podman/maptool/data",restrict ssh-ed25519 … # HOME_HOST= (empty) pulls anywhere, LTE included.
# so paths below are relative to brick's data/.
set -euo pipefail set -euo pipefail
SOURCE=${MAP_SOURCE:-randy@10.17.240.2} ENV_FILE=${MAP_ENV:-/srv/podman/maptool/.env}
DATA=${MAP_DATA:-/srv/podman/maptool/data} DATA=${MAP_DATA:-/srv/podman/maptool/data}
FILES="offline.pmtiles offline.pmtiles.meta.json terrain.pmtiles terrain.pmtiles.meta.json offline_regions.json" HOME_HOST=${HOME_HOST-10.17.240.2}
DIRS="routing places hiking_trails kiwix nps"
host=${SOURCE#*@} env_value() { grep -m1 "^$1=" "$ENV_FILE" | cut -d= -f2- | sed 's/^["'\'']//; s/["'\'']$//'; }
if ! timeout 5 bash -c "</dev/tcp/$host/22" 2>/dev/null; then server=$(env_value SYNC_SERVER_URL)
echo "pull-maps: $host not reachable (not at home), skipping" token=$(env_value SYNC_TOKEN)
if [ -z "$server" ] || [ -z "$token" ]; then
echo "pull-maps: no SYNC_SERVER_URL/SYNC_TOKEN in $ENV_FILE" >&2
exit 1
fi
server=${server%/}
if [ -n "$HOME_HOST" ] && ! timeout 5 bash -c "</dev/tcp/$HOME_HOST/22" 2>/dev/null; then
echo "pull-maps: $HOME_HOST not reachable (not at home), skipping"
exit 0 exit 0
fi fi
changes=$(mktemp) # The token in a header file, not on the command line (ps shows that).
trap 'rm -f "$changes"' EXIT auth=$(mktemp)
# Into a temp file, renamed when complete (rsync's default): the app and trap 'rm -f "$auth"' EXIT
# Valhalla keep reading the old copy until restarted. printf 'Authorization: Bearer %s\n' "$token" > "$auth"
for f in $FILES; do
rsync -a --partial-dir=.rsync-partial --out-format='%n' "$SOURCE:$f" "$DATA/$f" >> "$changes" 2>/dev/null || true manifest=$(curl -fsS --retry 3 -H "@$auth" "$server/api/sync/maps")
done
for d in $DIRS; do updated=0
rsync -a --delete-delay --partial-dir=.rsync-partial --out-format='%n' "$SOURCE:$d/" "$DATA/$d/" >> "$changes" failed=0
declare -A wanted=()
while IFS=$'\t' read -r size mtime path; do
[ -n "$path" ] || continue
case "$path" in /* | *..*) echo "pull-maps: skipping odd path $path" >&2; continue ;; esac
wanted[$path]=1
local_file="$DATA/$path"
[ -f "$local_file" ] && [ "$(stat -c '%s %Y' "$local_file")" = "$size $mtime" ] && continue
mkdir -p "$(dirname "$local_file")"
part="$local_file.part"
# A partial download of another version of the file starts over.
[ "$(cat "$part.version" 2>/dev/null)" = "$size $mtime" ] || rm -f "$part"
echo "$size $mtime" > "$part.version"
echo "pull-maps: $path ($((size / 1048576)) MB)"
# Into a temp file, renamed when complete: the app and Valhalla keep
# reading the old copy until restarted.
if [ "$(stat -c %s "$part" 2>/dev/null || echo -1)" != "$size" ]; then
curl -fsS --retry 10 --retry-all-errors --retry-delay 5 -C - -o "$part" -H "@$auth" \
--get --data-urlencode "path=$path" "$server/api/sync/maps/file" || true
fi
if [ "$(stat -c %s "$part" 2>/dev/null || echo -1)" = "$size" ]; then
touch -d "@$mtime" "$part"
mv "$part" "$local_file"
rm -f "$part.version"
updated=$((updated + 1))
else
echo "pull-maps: $path incomplete, continuing next run" >&2
failed=$((failed + 1))
fi
done <<< "$manifest"
# What the server no longer has, in the directories it sends.
for dir in $(cut -f3 <<< "$manifest" | grep / | cut -d/ -f1 | sort -u); do
while IFS= read -r -d '' file; do
rel=${file#"$DATA/"}
case "$rel" in *.part | *.part.version | routing/service.sh) continue ;; esac
if [ -z "${wanted[$rel]:-}" ]; then
echo "pull-maps: removing $rel"
rm -f "$file"
updated=$((updated + 1))
fi
done < <(find "$DATA/$dir" -type f -not -path '*/.*' -print0)
done done
if grep -qv '/$' "$changes"; then if [ "$updated" -gt 0 ]; then
echo "pull-maps: $(grep -cv '/$' "$changes") files updated, restarting maptool" echo "pull-maps: $updated files changed, restarting maptool"
sudo systemctl restart podman-compose@maptool.service sudo systemctl restart podman-compose@maptool.service
fi fi
[ "$failed" -eq 0 ]
+56 -8
View File
@@ -202,17 +202,65 @@ server's `GET /api/sync/changes`, `GET`/`PUT /api/sync/source/:id`,
`data/sync_state.json`. Over the public URL, so no VPN is needed for it. `data/sync_state.json`. Over the public URL, so no VPN is needed for it.
On brick the CI deploy writes `SYNC_TOKEN` (a Gitea secret) into `.env`. On brick the CI deploy writes `SYNC_TOKEN` (a Gitea secret) into `.env`.
=== CAN (GNSS node)
SocketCAN interfaces live in the host's network namespace, so on the car's
server maptool runs with host networking: a `docker-compose.override.yaml`
next to the compose symlink (podman-compose picks it up), with kiwix and
Valhalla published on loopback since their service names no longer resolve
from maptool:
----
services:
maptool:
network_mode: host
environment:
KIWIX_URL: "http://127.0.0.1:8080"
VALHALLA_URL: "http://127.0.0.1:8002"
kiwix:
ports: ["127.0.0.1:8080:8080"]
valhalla:
ports: ["127.0.0.1:8002:8002"]
----
`data/can.json` (`lib/maptool/can.rb`) decodes the GNSS node
`mcu-stm32-xiao-c5-2` (CANopen node 0x21, esphome-canopen's
`canopen_entities`; layout in its `OBJECT_DICTIONARY.md`): TPDO2 (0x3A1)
carries latitude/longitude as REAL32, TPDO3 (0x4A1) altitude, speed (km/h)
and HDOP as Sensor16 over their `min_value..max_value` (`value = wire *
(max - min) / 65534 + min`, 65535 unknown) and satellites as Sensor8; TPDO1 (0x2A1) the on-board IMU's pitch, roll
(-180..180°) and temperature, Sensor16 too. The compass (HMC5883L on the
same node) isn't in the firmware yet:
----
{ "interfaces": ["can0"],
"signals": [
{ "name": "gnss.lat", "id": "0x3A1", "byte": 0, "type": "f32" },
{ "name": "gnss.lon", "id": "0x3A1", "byte": 4, "type": "f32" },
{ "name": "gnss.alt", "id": "0x4A1", "byte": 0, "type": "u16", "scale": 0.14496292001098665, "offset": -500, "invalid": 65535, "unit": "m" },
{ "name": "gnss.speed", "id": "0x4A1", "byte": 2, "type": "u16", "scale": 0.001271604561499883, "invalid": 65535, "unit": "m/s" },
{ "name": "gnss.hdop", "id": "0x4A1", "byte": 4, "type": "u16", "scale": 0.0007629627368999298, "invalid": 65535 },
{ "name": "gnss.satellites", "id": "0x4A1", "byte": 6, "type": "u8", "scale": 1.0039370078740157, "invalid": 255 },
{ "name": "imu.pitch", "id": "0x2A1", "byte": 0, "type": "u16", "scale": 0.005493331705679495, "offset": -180, "invalid": 65535, "unit": "°" },
{ "name": "imu.roll", "id": "0x2A1", "byte": 2, "type": "u16", "scale": 0.005493331705679495, "offset": -180, "invalid": 65535, "unit": "°" },
{ "name": "imu.temperature", "id": "0x2A1", "byte": 4, "type": "u16", "scale": 0.0025177770317697684, "offset": -40, "invalid": 65535, "unit": "°C" } ] }
----
Speed's scale also converts km/h to m/s (`300 / 65534 / 3.6`). The node
goes operational by itself, so no `nmt_start`.
=== Map data (one way) === Map data (one way)
`bin/pull-maps.sh`, run by `maptool-pull-maps.timer` (10 min after boot, `bin/pull-maps.sh`, run by `maptool-pull-maps.timer` (10 min after boot,
then every 6 h) as `randy`: rsyncs the pmtiles, routing, places, hiking then every 6 h) as `randy`: pulls the pmtiles, routing, places, hiking
trails, the ZIM and the NPS maps from brick while brick is reachable, and trails, the ZIM and the NPS maps from brick over HTTPS — the same public
restarts maptool when something changed. Its key is limited on brick URL and `SYNC_TOKEN` as the library sync (read from `.env`), so no SSH or
(`~randy/.ssh/authorized_keys`) to a read-only rsync of the data dir: VPN. brick lists them (`GET /api/sync/maps`: size, mtime, path; the list
of files is app.rb's `MAP_SYNC_FILES`/`MAP_SYNC_DIRS`) and serves each
---- (`GET /api/sync/maps/file?path=`); a cut-off download resumes (Range) on
command="python3 /usr/share/doc/packages/rsync/support/rrsync -ro /srv/podman/maptool/data",restrict ssh-ed25519 AAAA… rpi-dev maptool map sync the next try or run, files gone on brick are removed, maptool restarts
---- when something changed. They're GBs, so only at home by default (brick's
LAN address `HOME_HOST` answers); `HOME_HOST=` pulls anywhere.
== Garmin LiveTrack session webhook == Garmin LiveTrack session webhook
+32 -7
View File
@@ -19,7 +19,9 @@ module Maptool
# "type": "u16", "scale": 0.125, "unit": "rpm" } ] } # "type": "u16", "scale": 0.125, "unit": "rpm" } ] }
# `id` matches the frame's id under `mask` (default: all bits); an id # `id` matches the frame's id under `mask` (default: all bits); an id
# above 0x7FF is an extended (29-bit) one. Types are little-endian like # above 0x7FF is an extended (29-bit) one. Types are little-endian like
# CANopen: u8 i8 u16 i16 u32 i32 f32, or bit. value = raw * scale + offset. # CANopen: u8 i8 u16 i16 u32 i32 f32, or bit. value = raw * scale + offset;
# a raw `invalid` (e.g. 65535, esphome-canopen's "unknown") or a NaN float
# gives no value.
module Can module Can
EFF_FLAG = 0x80000000 # extended frame EFF_FLAG = 0x80000000 # extended frame
RTR_FLAG = 0x40000000 RTR_FLAG = 0x40000000
@@ -86,7 +88,7 @@ module Maptool
raise ArgumentError, "#{s['name']}: unknown type #{type}" unless type == "bit" || TYPES.key?(type) raise ArgumentError, "#{s['name']}: unknown type #{type}" unless type == "bit" || TYPES.key?(type)
{ name: s.fetch("name"), id: id, mask: Integer(s.fetch("mask", "0x1FFFFFFF")), extended: id > 0x7FF, { name: s.fetch("name"), id: id, mask: Integer(s.fetch("mask", "0x1FFFFFFF")), extended: id > 0x7FF,
byte: s.fetch("byte", 0), bit: s["bit"], type: type, scale: s.fetch("scale", 1), offset: s.fetch("offset", 0) } byte: s.fetch("byte", 0), bit: s["bit"], type: type, scale: s.fetch("scale", 1), offset: s.fetch("offset", 0), invalid: s["invalid"] }
end end
end end
@@ -102,18 +104,25 @@ module Maptool
chunk = frame.data.byteslice(s[:byte], size) chunk = frame.data.byteslice(s[:byte], size)
chunk.unpack1(format) if chunk&.bytesize == size chunk.unpack1(format) if chunk&.bytesize == size
end end
values[s[:name]] = s[:type] == "bit" ? raw : raw * s[:scale] + s[:offset] unless raw.nil? next if raw.nil? || raw == s[:invalid] || (raw.is_a?(Float) && raw.nan?)
values[s[:name]] = s[:type] == "bit" ? raw : raw * s[:scale] + s[:offset]
end end
end end
end end
# The latest of everything heard, for GET /api/can. # The latest of everything heard, for GET /api/can (and the /can.html
# diagnostics): interfaces, CANopen nodes (heartbeat state, last EMCY),
# every frame id seen (count, rate, last data) and the decoded signals.
class Store class Store
MAX_FRAME_IDS = 2048 # ponytail: stops counting new ids past this, enough for a bus
def initialize def initialize
@mutex = Mutex.new @mutex = Mutex.new
@signals = {} @signals = {}
@nodes = {} @nodes = {}
@interfaces = {} @interfaces = {}
@frames = {}
end end
def interface(name, **state) def interface(name, **state)
@@ -130,18 +139,34 @@ module Maptool
n = (@nodes[node] ||= {}) n = (@nodes[node] ||= {})
n[:seen_at] = at n[:seen_at] = at
n[:state] = HEARTBEAT_STATES.fetch(frame.data.getbyte(0) & 0x7F, "unknown") if role == :heartbeat && frame.data.bytesize >= 1 n[:state] = HEARTBEAT_STATES.fetch(frame.data.getbyte(0) & 0x7F, "unknown") if role == :heartbeat && frame.data.bytesize >= 1
# EMCY: error code (0 = errors reset), error register, 5 bytes vendor-specific
n[:emcy] = { code: frame.data.unpack1("S<"), register: frame.data.getbyte(2), at: at } if role == :emcy && frame.data.bytesize >= 3
end
key = "#{interface}:#{frame.extended ? format('%08X', frame.id) : format('%03X', frame.id)}"
f = @frames[key]
if f.nil? && @frames.size < MAX_FRAME_IDS
f = @frames[key] = { interface: interface, id: frame.id, extended: frame.extended, role: role, node: node, count: 0 }
end
if f
if f[:at] # smoothed time between frames, for the rate
gap = at - f[:at]
f[:interval] = f[:interval] ? f[:interval] * 0.8 + gap * 0.2 : gap
end
f.merge!(count: f[:count] + 1, data: frame.data.unpack1("H*"), at: at)
end end
values.each { |name, value| @signals[name] = { value: value, at: at } } values.each { |name, value| @signals[name] = { value: value, at: at } }
end end
end end
def snapshot def snapshot
@mutex.synchronize { { interfaces: @interfaces.dup, nodes: @nodes.dup, signals: @signals.dup } } @mutex.synchronize { { interfaces: @interfaces.dup, nodes: @nodes.dup, signals: @signals.dup, frames: @frames.values.map(&:dup) } }
end end
end end
# Reads `interface` forever, reconnecting (warned once per outage, not # Reads `interface` forever, reconnecting (warned once per outage, not
# every retry): an adapter unplugged or not up yet isn't fatal. # 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) def self.listen(interface, decoder:, store:, start_nodes: false, retry_delay: 5)
down = false down = false
loop do loop do
@@ -159,7 +184,7 @@ module Maptool
store.record(interface, frame, values) store.record(interface, frame, values)
yield(values) if block_given? && !values.empty? yield(values) if block_given? && !values.empty?
end end
rescue SocketError, SystemCallError, IOError => e rescue StandardError => e
store.interface(interface, up: false, error: e.message) store.interface(interface, up: false, error: e.message)
warn "can: #{interface}: #{e.message} — retrying every #{retry_delay}s" unless down warn "can: #{interface}: #{e.message} — retrying every #{retry_delay}s" unless down
down = true down = true
+15 -1
View File
@@ -144,6 +144,20 @@ class AppTest < Minitest::Test
assert_equal 401, request.get("/api/sync/source/x").status assert_equal 401, request.get("/api/sync/source/x").status
assert_equal 401, request.post("/api/sync/apply", input: "{}").status assert_equal 401, request.post("/api/sync/apply", input: "{}").status
assert_equal 401, request.put("/api/sync/source/x", input: "x").status assert_equal 401, request.put("/api/sync/source/x", input: "x").status
assert_equal 401, request.get("/api/sync/maps", **logged_in_env).status
assert_equal 401, request.get("/api/sync/maps/file", params: { "path" => "offline.pmtiles" }).status
end
def test_map_data_offered_to_clients_is_only_the_map_files
data = Maptool::App::DATA_DIR
files = %w[terrain.pmtiles places/SK.sqlite places/.rsync-partial/SK.sqlite routing/tiles.tar.part routing/service.sh can.json]
files.each { |f| FileUtils.mkdir_p(File.dirname(File.join(data, f))); File.write(File.join(data, f), "x") }
offered = Maptool::App.map_sync_files
assert_includes offered.keys, "terrain.pmtiles"
assert_includes offered.keys, "places/SK.sqlite"
refute(offered.keys.any? { |f| f.include?(".rsync-partial") || f.end_with?(".part") || %w[can.json routing/service.sh].include?(f) })
ensure
files.each { |f| FileUtils.rm_f(File.join(data, f)) }
end end
def test_the_sync_button_is_only_a_clients def test_the_sync_button_is_only_a_clients
@@ -154,7 +168,7 @@ class AppTest < Minitest::Test
def test_can_requires_login_and_is_off_without_a_config def test_can_requires_login_and_is_off_without_a_config
assert_equal 401, request.get("/api/can").status assert_equal 401, request.get("/api/can").status
assert_equal({ "interfaces" => {}, "nodes" => {}, "signals" => {}, "available" => false }, json_body(request.get("/api/can", **logged_in_env))) assert_equal({ "interfaces" => {}, "nodes" => {}, "signals" => {}, "frames" => [], "available" => false }, json_body(request.get("/api/can", **logged_in_env)))
end end
# MQTT messages land in the tracker / ITS-G5 parts of /api/live. # MQTT messages land in the tracker / ITS-G5 parts of /api/live.
+13
View File
@@ -42,6 +42,12 @@ class CanTest < Minitest::Test
assert_empty decoder.decode(Frame.new(0x0F1, "\0\0\0\0\0".b, false)) assert_empty decoder.decode(Frame.new(0x0F1, "\0\0\0\0\0".b, false))
assert_in_delta(-15.0, decoder.decode(Frame.new(0x281, [250].pack("s<"), false))["temp"]) assert_in_delta(-15.0, decoder.decode(Frame.new(0x281, [250].pack("s<"), false))["temp"])
assert_empty decoder.decode(Frame.new(0x181, "\x01".b, false)), "too short for the i32s" assert_empty decoder.decode(Frame.new(0x181, "\x01".b, false)), "too short for the i32s"
# esphome-canopen's Sensor16 (min..max over 0..65534, 65535 unknown) and a NaN float: no value.
alt = Maptool::Can::Decoder.new([{ "name" => "alt", "id" => "0x4A1", "type" => "u16", "scale" => 9500.0 / 65534, "offset" => -500, "invalid" => 65535 },
{ "name" => "lat", "id" => "0x3A1", "type" => "f32" }])
assert_in_delta 9000, alt.decode(Frame.new(0x4A1, [65534].pack("S<"), false))["alt"], 1e-6
assert_empty alt.decode(Frame.new(0x4A1, [65535].pack("S<"), false))
assert_empty alt.decode(Frame.new(0x3A1, [Float::NAN].pack("e"), false))
assert_raises(ArgumentError) { Maptool::Can::Decoder.new([{ "name" => "x", "id" => 1, "type" => "u64" }]) } assert_raises(ArgumentError) { Maptool::Can::Decoder.new([{ "name" => "x", "id" => 1, "type" => "u64" }]) }
end end
@@ -53,6 +59,13 @@ class CanTest < Minitest::Test
assert_equal({ frames: 2, last_frame_at: 2.0 }, snapshot[:interfaces]["vcan0"]) assert_equal({ frames: 2, last_frame_at: 2.0 }, snapshot[:interfaces]["vcan0"])
assert_equal({ seen_at: 1.0, state: "operational" }, snapshot[:nodes][5]) assert_equal({ seen_at: 1.0, state: "operational" }, snapshot[:nodes][5])
assert_equal({ value: 49.1, at: 2.0 }, snapshot[:signals]["gnss.lat"]) assert_equal({ value: 49.1, at: 2.0 }, snapshot[:signals]["gnss.lat"])
store.record("vcan0", Frame.new(0x181, "".b, false), {}, at: 2.5)
store.record("vcan0", Frame.new(0x085, [0x8130, 0x11].pack("S<C"), false), {}, at: 3.0)
snapshot = store.snapshot
tpdo = snapshot[:frames].find { |f| f[:id] == 0x181 }
assert_equal [:tpdo1, 1, 2, 0.5], tpdo.values_at(:role, :node, :count, :interval)
assert_equal({ code: 0x8130, register: 0x11, at: 3.0 }, snapshot[:nodes][5][:emcy])
end end
# Over a real SocketCAN interface when there is one: # Over a real SocketCAN interface when there is one:
+114
View File
@@ -0,0 +1,114 @@
<!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>CANopen diagnostics</title>
<link rel="icon" href="/icons/icon.svg" type="image/svg+xml">
<style>
:root { color-scheme: light dark; --muted: GrayText; --line: color-mix(in srgb, CanvasText 15%, transparent); --ok: #2e7d32; --warn: #ef6c00; --bad: #c62828; }
body { margin: 0; padding: 16px; background: Canvas; color: CanvasText; font: 15px/1.4 -apple-system, "Segoe UI", Roboto, Helvetica, Arial, sans-serif; }
header { display: flex; flex-wrap: wrap; gap: 8px 16px; align-items: baseline; margin-bottom: 12px; }
h1 { font-size: 1.2rem; margin: 0; }
h2 { font-size: 0.8rem; font-weight: 600; color: var(--muted); text-transform: uppercase; letter-spacing: 0.05em; margin: 20px 0 6px; }
#status { color: var(--muted); font-size: 0.85rem; }
.scroll { overflow-x: auto; }
table { border-collapse: collapse; font-size: 0.85rem; min-width: 100%; }
th, td { padding: 6px 12px 6px 0; text-align: left; border-bottom: 1px solid var(--line); white-space: nowrap; }
th { color: var(--muted); font-weight: 500; }
td.num { font-variant-numeric: tabular-nums; text-align: right; }
code { font: 0.85rem ui-monospace, SFMono-Regular, Menlo, monospace; }
.ok { color: var(--ok); } .warn { color: var(--warn); } .bad { color: var(--bad); }
.stale td { opacity: 0.5; }
input { padding: 6px 8px; font-size: 0.9rem; width: 220px; max-width: 100%; box-sizing: border-box; }
.empty { color: var(--muted); font-size: 0.85rem; }
</style>
</head>
<body>
<header>
<h1>CANopen diagnostics</h1>
<span id="status">loading…</span>
</header>
<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>
<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>
<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>
<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 esc = (s) => String(s ?? "").replace(/[&<>"]/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;" })[c]);
const hex = (n, width) => "0x" + n.toString(16).toUpperCase().padStart(width, "0");
const nodeName = (n) => `${n} <code>${hex(Number(n), 2)}</code>`;
let last = null;
let clockOffset = 0; // server time minus ours, so ages don't depend on the tablet's clock
function age(at) {
if (!at) return "—";
const s = Date.now() / 1000 + clockOffset - at;
return s < 1 ? "now" : s < 60 ? `${Math.round(s)} s ago` : s < 3600 ? `${Math.round(s / 60)} min ago` : `${Math.round(s / 3600)} h ago`;
}
const stale = (at) => !at || Date.now() / 1000 + clockOffset - at > STALE_AFTER;
function fill(id, rows, empty, cols) {
document.querySelector(`#${id} tbody`).innerHTML = rows.length ? rows.join("") : `<tr><td class="empty" colspan="${cols}">${empty}</td></tr>`;
}
const STATE_CLASS = { operational: "ok", "pre-operational": "warn", stopped: "bad", "boot-up": "warn" };
function render(data) {
fill("interfaces", Object.entries(data.interfaces).map(([name, i]) =>
`<tr><td>${esc(name)}</td><td class="${i.up ? "ok" : "bad"}">${i.up ? "up" : "down"}</td><td class="num">${i.frames}</td><td>${age(i.last_frame_at)}</td><td>${esc(i.error)}</td></tr>`),
data.available ? "No interface read yet." : "CAN is off: no data/can.json on this server.", 5);
const roles = {};
for (const f of data.frames) if (f.node != null) (roles[f.node] ||= new Set()).add(f.role);
fill("nodes", Object.entries(data.nodes).sort((a, b) => a[0] - b[0]).map(([id, n]) => {
const emcy = n.emcy ? `<code>${hex(n.emcy.code, 4)}</code> reg <code>${hex(n.emcy.register, 2)}</code> ${n.emcy.code === 0 ? "(reset)" : ""} · ${age(n.emcy.at)}` : "—";
return `<tr class="${stale(n.seen_at) ? "stale" : ""}"><td>${nodeName(id)}</td><td class="${STATE_CLASS[n.state] || ""}">${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);
fill("signals", Object.entries(data.signals).sort().map(([name, s]) =>
`<tr class="${stale(s.at) ? "stale" : ""}"><td>${esc(name)}</td><td class="num">${typeof s.value === "number" ? +s.value.toFixed(6) : esc(s.value)}</td><td>${esc(s.unit)}</td><td>${age(s.at)}</td></tr>`),
"No signal decoded yet (signals in data/can.json).", 4);
const filter = document.getElementById("filter").value.trim().toLowerCase();
const frames = data.frames
.map((f) => ({ ...f, cob: f.extended ? hex(f.id, 8) : hex(f.id, 3) }))
.filter((f) => !filter || [f.interface, f.cob, f.role, f.node].join(" ").toLowerCase().includes(filter))
.sort((a, b) => a.interface.localeCompare(b.interface) || a.id - b.id);
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>`),
filter ? "No frame matches." : "No frame yet.", 8);
}
async function poll() {
const status = document.getElementById("status");
try {
const response = await fetch("/api/can", { cache: "no-store" });
if (response.status === 401) { status.textContent = "Not logged in — log in on the map first."; return; }
if (!response.ok) throw new Error(`HTTP ${response.status}`);
const date = Date.parse(response.headers.get("Date"));
if (date) clockOffset = Math.abs(date / 1000 - Date.now() / 1000) > 2 ? date / 1000 - Date.now() / 1000 : 0;
render(last = await response.json());
status.textContent = `updated ${new Date().toLocaleTimeString()}`;
} catch (e) {
status.textContent = `can't reach the server: ${e.message}`;
} finally {
setTimeout(poll, 1000);
}
}
document.getElementById("filter").addEventListener("input", () => last && render(last));
poll();
</script>
</body>
</html>
+3
View File
@@ -104,6 +104,9 @@
<strong>Status / debug</strong> <strong>Status / debug</strong>
<button type="button" class="basemap-panel__close" aria-label="Close">&times;</button> <button type="button" class="basemap-panel__close" aria-label="Close">&times;</button>
</div> </div>
<div class="basemap-panel__list">
<a class="basemap-panel__link" href="/can.html" target="_blank">CANopen diagnostics ↗</a>
</div>
<!-- Filled by DebugControl (public/js/debug.js), logged-in only. --> <!-- Filled by DebugControl (public/js/debug.js), logged-in only. -->
<div class="debug-panel__body"></div> <div class="debug-panel__body"></div>
</div> </div>