Nodes describe themselves: an SDO client (Can::Sdo) reads each esphome-canopen node's TPDOs and entities (type, name, unit, range) on its first heartbeat, cached by the TPDO layout hash, decoded with no hand-written signals — can.json keeps aliases (with unit conversion) and foreign devices; design doc (NPS planning, cockpit instruments, Unigrid band) with color tokens, the dashboard in cockpit colors; starting the simulation turns the GNSS follow on, the GNSS position an arrow by its course
CI / check (push) Successful in 23s
CI / deploy (push) Successful in 17s

This commit is contained in:
randy committed 2026-11-30 19:51:03 +01:00
1 parent ce290f2162
commit e92f01db12
12 files changed
+713 -76

No files matched your search

+34 -3
View File
@@ -171,9 +171,19 @@ already reaches the home MQTT broker (`mqtt_ext`) from ESPHome nodes in `~/espho
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
** [ ] Nodes describing themselves — no hand-written signals for our own nodes:
*** [x] esphome-canopen nodes over SDO: on a node's first heartbeat read its TPDOs
(`0x1800+n`:1 COB-ID, `0x1A00+n` mapping), each mapped entity's type (`0x2001`:N) and
metadata (`0x2000+0x10·N`: name, unit, min/max → the scale), the decoder built from that,
cached by the TPDO layout hash (`0x3002`:1, read again when it changes — after an OTA);
`can.json` keeps only aliases (a node's "Latitude" → `gnss.lat`) and foreign devices
(`lib/maptool/can_discovery.rb`, `Can::Sdo`; aliases with a unit conversion; node 0x21
reads in 2 s, its 14 signals match the hand-written scales)
*** [ ] `/can.html`: each described node's entities (name, unit, range, TPDO), from the cache
*** [ ] EDS (CiA 306) read from a node (`0x1021`) or a file, the same decoder from it — once the
ESPHome side generates EDS (proposal for mrk in home-gitops `docs/canopen-nodes.adoc`); the
car bridge's frames described the same way
*** [ ] 0x1008/0x1018 identity for any CANopen device in `/can.html`
** [x] A node that stops its heartbeat (3 missed) is flagged: one journal line when it goes
silent and when it's back (`can: node 2 silent, last heartbeat …`), red in `/can.html`
** [x] Dashboard overlay (Overlays → Live → Dashboard, `public/js/dashboard.js`): one combined
@@ -261,6 +271,27 @@ already reaches the home MQTT broker (`mqtt_ext`) from ESPHome nodes in `~/espho
* [ ] While following a planned route: the route ahead highlighted, distance to the next
maneuver from Valhalla's directions
=== Design: the park brochure and the cockpit
Planning in the NPS look, driving in the cockpit look, joined by the Unigrid black band —
`docs/design.adoc`. Action plan:
. [x] Colors: tokens on `:root` (`--band`, `--inst-*`: ok / caution / warning, magenta = what
navigation follows, cyan = set by hand); the dashboard in them — a see-through black bezel,
light values, inverted back in night mode
. [ ] The route line magenta while it's navigated (follow mode), blue while planning; the next
waypoint and maneuver magenta on the map too
. [ ] The rest of the hard-coded colors → tokens (route, warnings, panel states), one place to tune
. [ ] Panel headers as the Unigrid band: black, white title in National Park (headings weight
to vendor), the same band as the topbar
. [ ] `/can.html` in the cockpit style: dark, the node / signal states in `--inst-*`
. [ ] The navigation strip: the next maneuver big at the top (arrow, distance, street, lanes) —
with the driving mode's big-button UI
. [ ] The PDM switch panel in the cockpit style (tiles: `--inst-ok` on, muted off,
`--inst-warning` fault)
. [ ] Night: instruments dimmed (brightness) on top of the inverted UI; daylight: a full-opacity
bezel preset for sun on the screen
=== HW integration
Inspired by Garmin Tread / zūmo, but open and over CANopen — the nodes' side and the options
+8 -1
View File
@@ -12,6 +12,7 @@ require_relative "lib/maptool/google_saved"
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/gnss_sim"
require_relative "lib/maptool/trip"
require_relative "lib/maptool/updater"
@@ -431,6 +432,12 @@ module Maptool
if CAN_CONFIG && !test?
decoder = CAN_DECODER
# Our esphome-canopen nodes describe themselves over SDO (can_discovery.rb);
# can.json's "aliases" name their signals ({"XIAO STM32C5 2.Latitude": "gnss.lat"}).
if CAN_CONFIG.fetch("discover", true) && (interface = CAN_CONFIG.fetch("interfaces", []).first)
Can::Discoverer.new(store: CAN_STORE, decoder: decoder, cache_dir: File.join(DATA_DIR, "can_nodes"),
aliases: CAN_CONFIG.fetch("aliases", {}), interface: interface).start
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|
@@ -1310,7 +1317,7 @@ module Maptool
get "/api/can" do
require_login!
snapshot = CAN_STORE.snapshot
units = (CAN_CONFIG || {}).fetch("signals", []).to_h { |signal| [signal["name"], signal["unit"]] }
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?)
end
+35 -28
View File
@@ -258,39 +258,46 @@ services:
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:
Our esphome-canopen nodes describe themselves: on a node's first heartbeat
maptool reads over SDO its TPDOs (`0x1800+n`, `0x1A00+n`) and, per mapped
entity, its type, name, unit and range (`canopen_entities`' OD, its
`OBJECT_DICTIONARY.md`) and decodes them with no hand-written signals
(`lib/maptool/can_discovery.rb`); cached in `data/can_nodes/<node>.json`
by the TPDO layout hash (`0x3002`:1, checked every 10 min — read again after
an OTA that changed the layout). Signals are named `<node name>.<entity
name>` (the ESPHome name, e.g. `mcu-stm32-xiao-c5-2.Latitude`, as
`/can.html` lists them); `data/can.json` only maps the ones the app uses to
its names, with a unit conversion where needed (the node's km/h → m/s).
`"signals"` stays for devices that don't describe themselves (the car
bridge), `"discover": false` turns it off:
----
{ "interfaces": ["can0"],
"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" },
{ "name": "mag.x", "id": "0x221", "byte": 0, "type": "u16", "scale": 0.006103701895199438, "offset": -200, "invalid": 65535, "unit": "µT" },
{ "name": "mag.y", "id": "0x221", "byte": 2, "type": "u16", "scale": 0.006103701895199438, "offset": -200, "invalid": 65535, "unit": "µT" },
{ "name": "mag.z", "id": "0x221", "byte": 4, "type": "u16", "scale": 0.006103701895199438, "offset": -200, "invalid": 65535, "unit": "µT" },
{ "name": "imu.heading", "id": "0x221", "byte": 6, "type": "u16", "scale": 0.005493331705679495, "invalid": 65535, "unit": "°" } ] }
"aliases": {
"mcu-stm32-xiao-c5-2.Latitude": "gnss.lat",
"mcu-stm32-xiao-c5-2.Longitude": "gnss.lon",
"mcu-stm32-xiao-c5-2.Altitude": "gnss.alt",
"mcu-stm32-xiao-c5-2.Speed": { "name": "gnss.speed", "scale": 0.2777777777777778, "unit": "m/s" },
"mcu-stm32-xiao-c5-2.HDOP": "gnss.hdop",
"mcu-stm32-xiao-c5-2.Satellites": "gnss.satellites",
"mcu-stm32-xiao-c5-2.Pitch": "imu.pitch",
"mcu-stm32-xiao-c5-2.Roll": "imu.roll",
"mcu-stm32-xiao-c5-2.IMU Temperature": "imu.temperature",
"mcu-stm32-xiao-c5-2.Field Strength X": "mag.x",
"mcu-stm32-xiao-c5-2.Field Strength Y": "mag.y",
"mcu-stm32-xiao-c5-2.Field Strength Z": "mag.z",
"mcu-stm32-xiao-c5-2.Heading": "imu.heading" } }
----
Speed's scale also converts km/h to m/s (`300 / 65534 / 3.6`). 0x221 is
the HMC5883L (TPDO 4 → `0x200 + node`): the field ±200 µT and ESPHome's
heading 0..360° (ESPHome's plain `atan2(-x, y)` is −180..180, the node
adds 360 to the negatives — a filter on `heading:`). No tilt compensation
or hard-iron calibration yet, so only roughly right standing level. The node
goes operational by itself, so no `nmt_start`.
What node 0x21 sends (read from it, 2026-11-30): TPDO1 0x2A1 pitch, roll
(-180..180°) and the IMU's temperature, Sensor16; TPDO2 0x3A1
latitude/longitude, REAL32; TPDO3 0x4A1 altitude, speed (km/h), HDOP
(Sensor16) and satellites (Sensor8); TPDO4 0x221 the HMC5883L, the field
±200 µT and the heading 0..360° (ESPHome's plain `atan2(-x, y)` is
−180..180, the node adds 360 to the negatives — a filter on `heading:`).
No tilt compensation or hard-iron calibration yet, so only roughly right
standing level. The node goes operational by itself, so no `nmt_start`.
Sensor16/8: `value = wire * (max - min) / (2^n - 2) + min`, all ones unknown.
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
+86
View File
@@ -0,0 +1,86 @@
= Design: the park brochure and the cockpit
MapTool has two jobs with two moods, and a style for each:
* *Planning, dreaming, remembering* — the map, the library, the trip, the
search: the *NPS* look. Warm Park Tiles cartography (`map_themes.js`),
the brochures and their symbols (`docs/nps-resources.adoc`), the olive
accent.
* *Driving* — whatever the driver glances at: the dashboard, the next
maneuver, the speed limit, the switch panel, warnings: the *cockpit*
look. Avionics (PFD/MFD) and chartplotters: displays over a bus, dark
bezel, big numbers, no decoration, colors that always mean the same.
They aren't two designs bolted together: the NPS brochures are Massimo
Vignelli's *Unigrid* (1977) — a strict grid, a black band with a white
sans-serif title, lots of white space, few colors. That's the same
modernist restraint as a glass cockpit. The black band is the shared
element: the topbar (`#1a1a1a`) is the brochure's band, the instruments'
bezel is the same black.
== Colors
Defined once as custom properties on `:root` (`public/css/style.css`);
nothing outside them for these meanings.
=== Planning (NPS)
[cols="1,1,3"]
|===
|Token |Value |Use
|`--accent` |`#546619` |active items, selected options, primary buttons (NPS boundary olive)
|`--accent-bg` |`#e1e5cf` |their light background (sage)
|`--band` |`#1a1a1a` |the Unigrid black band: the topbar, panel headers, and the instruments' bezel
|===
The map's own colors are Park Tiles' (`map_themes.js`), not tokens.
=== Instruments (cockpit)
Each color has one meaning, as in avionics — so a glance is enough and
a color never decorates.
[cols="1,1,3"]
|===
|Token |Value |Means
|`--inst-bezel` |`--band` at the card's opacity |the instrument's background
|`--inst-text` |`#f2f2f2` |values
|`--inst-muted` |`#9aa0a6` |labels, scales, what's inactive
|`--inst-ok` |`#3ccf4e` |normal, engaged (a switch on, a node alive)
|`--inst-caution` |`#ffb300` |attention: past a soft limit (roll > 20°), off the route, a stale signal
|`--inst-warning` |`#ff3b30` |act now: over the speed limit, past a hard limit, a fault
|`--inst-active` |`#e040fb` |*magenta*: the active route and the next waypoint / maneuver / lane to take — the avionics convention for what navigation is following
|`--inst-selected` |`#00d5ff` |*cyan*: a value you set yourself (a speed bug, the camper's own limit, a chosen target)
|===
Road signs stay road signs: the speed limit is the white disc with the
red ring whatever the theme — it's read as a sign, not as a color.
Night: the page's night mode inverts the UI (`html.night`); the
instruments are already dark and are inverted back, only dimmed.
== Typography
* Planning UI: the system sans; *National Park* (the router-carved
signage face) only for the wordmark and, later, headings in the black
band — the brochure's title.
* Instruments: the system sans with tabular figures
(`font-variant-numeric: tabular-nums`), bold values, small uppercase
labels with letter-spacing — numbers that don't jitter as they change.
== Which surface is which
[cols="1,1"]
|===
|NPS (planning) |Cockpit (driving)
|the map and its layers, the library, the trip / itinerary, search, the
route panel, NPS maps, the offline data panel
|the dashboard (inclinometer, speed, limit, ahead), the navigation strip
(next maneuver, lanes), the switch panel (PDM), warnings, `/can.html`
|===
The route line is the bridge: blue (`#1d6fdc`) while planning, magenta
(`--inst-active`) once it's being navigated.
+24 -3
View File
@@ -79,18 +79,39 @@ module Maptool
TYPES = { "u8" => ["C", 1], "i8" => ["c", 1], "u16" => ["S<", 2], "i16" => ["s<", 2],
"u32" => ["L<", 4], "i32" => ["l<", 4], "f32" => ["e", 4] }.freeze
# Frames → { "name" => value } by the config's signals.
# Frames → { "name" => value } by the config's signals, plus each
# discovered node's (#set_node, can_discovery.rb).
class Decoder
def initialize(signals)
@signals = signals.map do |s|
@static = compile(signals)
@nodes = {}
@signals = @static
end
# A node's signals, replacing what it had (swapped in whole: the
# reader thread keeps decoding with the old list meanwhile).
def set_node(node, signals)
@nodes = @nodes.merge(node => compile(signals))
@signals = @static + @nodes.values.flatten
end
# { name => unit } of every signal that has one.
def units
@signals.each_with_object({}) { |s, units| units[s[:name]] = s[:unit] if s[:unit] }
end
def compile(signals)
signals.map do |s|
id = Integer(s.fetch("id"))
type = s.fetch("type", "u8")
raise ArgumentError, "#{s['name']}: unknown type #{type}" unless type == "bit" || TYPES.key?(type)
{ name: s.fetch("name"), id: id, mask: Integer(s.fetch("mask", "0x1FFFFFFF")), extended: id > 0x7FF,
byte: s.fetch("byte", 0), bit: s["bit"], type: type, scale: s.fetch("scale", 1), offset: s.fetch("offset", 0), invalid: s["invalid"] }
byte: s.fetch("byte", 0), bit: s["bit"], type: type, scale: s.fetch("scale", 1), offset: s.fetch("offset", 0), invalid: s["invalid"],
unit: s["unit"] }
end
end
private :compile
def decode(frame)
@signals.each_with_object({}) do |s, values|
+199
View File
@@ -0,0 +1,199 @@
require "json"
require "fileutils"
require_relative "can_sdo"
module Maptool
module Can
# Our esphome-canopen nodes describe themselves (canopen_entities' OD,
# OBJECT_DICTIONARY.md): their TPDOs (0x1800+n COB-ID, 0x1A00+n mapping)
# and, per mapped entity N, its type (0x2001:N) and metadata
# (0x2000+0x10·N: name, unit, min/max — the scale of a 1/2-byte value).
# Read once over SDO, cached by the TPDO layout hash (0x3002:1), the
# node's signals go into the Decoder — no hand-written can.json for them.
module Discovery
LAYOUT_HASH = [0x3002, 1].freeze
SCALED = { 6 => 1, 7 => 2, 9 => 1, 10 => 2 }.freeze # sensor8/16, number8/16 → bytes
FLOATS = [1, 8].freeze # sensor, number: REAL32
RAW = { 8 => "u8", 16 => "u16", 32 => "u32" }.freeze
def self.layout_hash(sdo, node)
sdo.upload(node, *LAYOUT_HASH).unpack1("L<")
end
# { node:, name:, hash:, signals: [Decoder signal config] }; raises
# Sdo::Abort when it isn't an esphome-canopen node (no 0x3002).
def self.describe(sdo, node, aliases: {})
hash = layout_hash(sdo, node)
name = optional { text(sdo.upload(node, 0x1008, 0)) }
label = name || format("node%02X", node)
entities = {}
signals = []
8.times do |n|
cob = optional { sdo.upload(node, 0x1800 + n, 1).unpack1("L<") }
next if cob.nil? || cob & 0x80000000 != 0 # not there / disabled
bit = 0
sdo.upload(node, 0x1A00 + n, 0).getbyte(0).times do |k|
entry = sdo.upload(node, 0x1A00 + n, k + 1).unpack1("L<")
index, sub, bits = entry >> 16, (entry >> 8) & 0xFF, entry & 0xFF
signal = entity_signal(sdo, node, entities, index, sub, bits)
if signal && bit % 8 == 0
full = "#{label}.#{signal.delete(:entity)}"
signals << apply_alias(signal.merge("source" => full, "id" => format("0x%03X", cob & 0x7FF), "byte" => bit / 8), aliases)
end
bit += bits
end
end
{ node: node, name: name, hash: hash, signals: signals }
end
# One TPDO entry as a signal, nil if it isn't an entity's state.
def self.entity_signal(sdo, node, entities, index, sub, bits)
return nil unless index.between?(0x2011, 0x2FF1) && (index - 0x2001) % 0x10 == 0
n = (index - 0x2001) / 0x10
entity = entities[n] ||= begin
meta = 0x2000 + 0x10 * n
{ type: sdo.upload(node, 0x2001, n).unpack1("L<") & 0xFF,
name: optional { text(sdo.upload(node, meta, 1)) } || "entity#{n}",
unit: optional { text(sdo.upload(node, meta, 3)) },
min: optional { sdo.upload(node, meta, 7).unpack1("e") },
max: optional { sdo.upload(node, meta, 8).unpack1("e") } }
end
name = sub == 1 ? entity[:name] : "#{entity[:name]} #{sub}"
base = { entity: name, "unit" => entity[:unit] }.compact
if FLOATS.include?(entity[:type]) && bits == 32
base.merge("type" => "f32")
elsif (size = SCALED[entity[:type]]) && bits == size * 8
# value = min + (max - min) * raw / (2^n - 2); 2^n - 1 = unknown
top = (1 << bits) - 1
min = entity[:min] || 0.0
max = entity[:max] || (top - 1).to_f
base.merge("type" => RAW.fetch(bits), "scale" => (max - min) / (top - 1), "offset" => min, "invalid" => top)
elsif RAW.key?(bits)
base.merge("type" => RAW.fetch(bits)) # switch, light, binary sensor…: the raw state
end
end
# The signal under its alias: a name ("gnss.lat"), or {"name", "scale",
# "unit"} when the app wants another unit (the node's km/h → m/s:
# "scale": 0.2777…). Applied to the node's own encoding, so a cached
# description takes today's aliases.
def self.apply_alias(signal, aliases)
alias_ = aliases[signal["source"]]
alias_ = { "name" => alias_ } if alias_.is_a?(String)
signal = signal.merge("name" => signal["source"]).reject { |k, _| k.start_with?("alias_") }
return signal unless alias_
k = alias_.fetch("scale", 1)
signal.merge("name" => alias_.fetch("name"), "scale" => signal.fetch("scale", 1) * k, "offset" => signal.fetch("offset", 0) * k,
"unit" => alias_.fetch("unit", signal["unit"]), "alias_scale" => k).compact
end
def self.text(bytes)
bytes.force_encoding("UTF-8").delete("\0")
end
def self.optional
yield
rescue Sdo::Abort
nil
end
private_class_method :optional, :text
end
# Describes every node heard (Store's nodes) in the background, one at
# a time: the layout hash checked again every RECHECK_S (cheap: one SDO),
# the full description read only when it changed; cached in cache_dir
# (data/can_nodes/<node>.json). Anything failing — not our kind of node,
# another SDO client in the way, the bus gone — is just tried later.
class Discoverer
POLL_S = 5
RECHECK_S = 600
RETRY_S = 30
NOT_OURS_S = 3600
def initialize(store:, decoder:, cache_dir:, aliases: {}, sdo: nil, interface: nil)
@store = store
@decoder = decoder
@cache_dir = cache_dir
@aliases = aliases
@sdo = sdo
@interface = interface
@next_at = {}
@described = {}
load_cache
end
def start
Thread.new do
loop do
run_once
rescue StandardError => e
warn "can discovery: #{e.message}"
@sdo = nil # a new socket next round
ensure
sleep POLL_S
end
end
end
def run_once(now: Time.now.to_f)
@store.snapshot[:nodes].each_key do |node|
next if @next_at.fetch(node, 0) > now
check(node, now)
end
end
private
def check(node, now)
sdo = (@sdo ||= Sdo.new(Sdo::SocketTransport.new(@interface)))
hash = Discovery.layout_hash(sdo, node)
unless @described[node]&.dig(:hash) == hash
description = Discovery.describe(sdo, node, aliases: @aliases)
save(description)
use(description)
warn "can discovery: node #{node} (#{description[:name]}): #{description[:signals].size} signals"
end
@next_at[node] = now + RECHECK_S
rescue Sdo::Abort
@next_at[node] = now + NOT_OURS_S # no 0x3002: not an esphome-canopen node
rescue Sdo::Error
@next_at[node] = now + RETRY_S
end
def use(description)
@described[description[:node]] = description
@decoder.set_node(description[:node], description[:signals])
end
def path(node)
File.join(@cache_dir, format("%02x.json", node))
end
def save(description)
FileUtils.mkdir_p(@cache_dir)
File.write(path(description[:node]), JSON.pretty_generate(description))
end
def load_cache
Dir.glob(File.join(@cache_dir, "*.json")).each do |file|
description = JSON.parse(File.read(file), symbolize_names: true)
# by today's aliases, not the ones it was cached with: back to the
# node's own scale first
description[:signals] = description[:signals].map do |s|
s = s.transform_keys(&:to_s)
k = s.delete("alias_scale") || 1
s = s.merge("scale" => s.fetch("scale", 1) / k, "offset" => s.fetch("offset", 0) / k) if k != 1
Discovery.apply_alias(s, @aliases)
end
use(description)
rescue JSON::ParserError, KeyError, NoMethodError
next
end
end
end
end
end
+105
View File
@@ -0,0 +1,105 @@
require_relative "can"
module Maptool
module Can
# A minimal SDO client (CiA 301): expedited and segmented uploads,
# expedited downloads — enough to read a node's description and write a
# command. Over a transport (#send a Frame, #receive(timeout) → Frame or
# nil): SocketTransport on its own raw socket, next to the reader thread's.
class Sdo
TIMEOUT_S = 1.0
class Error < StandardError; end
class Timeout < Error; end
class Abort < Error
attr_reader :code
def initialize(code)
@code = code
super(format("SDO abort 0x%08X", code))
end
end
class SocketTransport
def initialize(interface)
@socket = Can.open(interface)
end
def send(frame)
@socket.write(frame.pack)
end
def receive(timeout)
return nil unless IO.select([@socket], nil, nil, timeout)
Frame.unpack(@socket.recv(16))
end
def close
@socket.close
end
end
def initialize(transport, timeout: TIMEOUT_S)
@transport = transport
@timeout = timeout
end
# The object's bytes (strings come back as bytes: force_encoding them).
def upload(node, index, sub)
response = request(node, [0x40, index, sub, 0].pack("CS<CL<"), index: index, sub: sub)
cs = response.getbyte(0)
raise Error, format("unexpected SDO reply 0x%02X", cs) unless cs & 0xE0 == 0x40
if cs & 0x02 != 0 # expedited: the data's in this frame
size = cs & 0x01 != 0 ? 4 - ((cs >> 2) & 3) : 4
return response.byteslice(4, size)
end
data = "".b
toggle = 0
loop do
segment = request(node, [0x60 | (toggle << 4)].pack("C") + ("\0" * 7))
scs = segment.getbyte(0)
raise Error, "SDO segment out of order" unless scs & 0xE0 == 0x00 && (scs >> 4) & 1 == toggle
data << segment.byteslice(1, 7 - ((scs >> 1) & 7))
return data if scs & 0x01 != 0
toggle ^= 1
end
end
# An expedited download of up to 4 bytes.
def download(node, index, sub, bytes)
raise ArgumentError, "expedited: 1 to 4 bytes" unless (1..4).cover?(bytes.bytesize)
cs = 0x23 | ((4 - bytes.bytesize) << 2)
response = request(node, [cs, index, sub].pack("CS<C") + bytes.b.ljust(4, "\0"), index: index, sub: sub)
raise Error, format("unexpected SDO reply 0x%02X", response.getbyte(0)) unless response.getbyte(0) == 0x60
end
private
# Sends to 0x600+node, waits for 0x580+node. index/sub: an initiate's
# answer must be for that object — another SDO client talking to the
# same node (can2mqtt) gets its own answers too.
def request(node, data, index: nil, sub: nil)
@transport.send(Frame.new(0x600 + node, data, false))
deadline = Process.clock_gettime(Process::CLOCK_MONOTONIC) + @timeout
loop do
remaining = deadline - Process.clock_gettime(Process::CLOCK_MONOTONIC)
raise Timeout, format("no SDO answer from node 0x%02X", node) if remaining <= 0
frame = @transport.receive(remaining)
next unless frame && !frame.extended && frame.id == 0x580 + node && frame.data.bytesize == 8
next if index && frame.data.byteslice(1, 3).unpack("S<C") != [index, sub]
raise Abort, frame.data.byteslice(4, 4).unpack1("L<") if frame.data.getbyte(0) == 0x80
return frame.data
end
end
end
end
end
+49 -32
View File
@@ -3,6 +3,16 @@
:root {
--accent: #546619;
--accent-bg: #e1e5cf;
/* The Unigrid black band (topbar) — also the instruments' bezel. */
--band: #1a1a1a;
/* Instruments (the driving view), one meaning per color — docs/design.adoc. */
--inst-text: #f2f2f2;
--inst-muted: #9aa0a6;
--inst-ok: #3ccf4e;
--inst-caution: #ffb300;
--inst-warning: #ff3b30;
--inst-active: #e040fb; /* magenta: the route / waypoint / lane being followed */
--inst-selected: #00d5ff; /* cyan: a value set by hand */
}
html, body {
@@ -35,7 +45,7 @@ html, body {
align-items: center;
height: 44px;
padding: 0 16px;
background: #1a1a1a;
background: var(--band);
}
.topbar__brand {
@@ -3192,6 +3202,7 @@ html.night {
}
html.night .topbar,
html.night .dash-card,
html.night img,
html.night #map canvas,
html.night .maplibregl-marker {
@@ -3299,7 +3310,9 @@ html.night .maplibregl-marker {
display: none;
}
/* The car's dashboard over the map (public/js/dashboard.js). */
/* The car's dashboard over the map (public/js/dashboard.js), in the
cockpit style (docs/design.adoc): the black band as a see-through bezel,
light values, colors only for meaning. */
.dash-card {
position: absolute;
right: 12px;
@@ -3307,65 +3320,69 @@ html.night .maplibregl-marker {
z-index: 3;
padding: 8px;
border-radius: 12px;
background: rgb(255 255 255 / var(--dash-alpha, 0.45));
background: rgb(26 26 26 / var(--dash-alpha, 0.45));
backdrop-filter: blur(2px);
box-shadow: 0 1px 6px rgb(0 0 0 / calc(var(--dash-alpha, 0.45) * 0.5));
box-shadow: 0 1px 6px rgb(0 0 0 / calc(var(--dash-alpha, 0.45) * 0.6));
color: var(--inst-text);
text-align: center;
pointer-events: none;
/* readable over the map whatever the background */
text-shadow: 0 0 3px #fff, 0 0 3px #fff;
/* readable over a light map whatever the bezel's opacity */
text-shadow: 0 0 3px #000, 0 0 3px #000;
font-family: system-ui, sans-serif;
}
.dash-incl {
display: block;
width: 190px;
height: 190px;
font-family: system-ui, sans-serif;
}
.dash-incl text { text-anchor: middle; dominant-baseline: middle; fill: #222; }
.dash-face { fill: rgb(246 246 244 / var(--dash-alpha, 0.45)); stroke: #999; stroke-width: 2; }
.dash-incl text { paint-order: stroke; stroke: #fff; stroke-width: 3px; }
.dash-ring line { stroke: #555; stroke-width: 2; }
.dash-incl text { text-anchor: middle; dominant-baseline: middle; fill: var(--inst-text); paint-order: stroke; stroke: #000; stroke-width: 3px; }
.dash-face { fill: rgb(0 0 0 / calc(var(--dash-alpha, 0.45) * 0.5)); stroke: var(--inst-muted); stroke-width: 2; }
.dash-ring line { stroke: var(--inst-muted); stroke-width: 2; }
.dash-ring text { font-size: 14px; font-weight: 600; }
.dash-ring .dash-n { fill: #c62828; }
.dash-lubber { fill: #c62828; }
.dash-ring .dash-n { fill: var(--inst-warning); }
.dash-lubber { fill: var(--inst-active); }
.dash-heading { font-size: 15px; font-weight: 600; font-variant-numeric: tabular-nums; }
.dash-ground { stroke: #999; stroke-width: 1.5; stroke-dasharray: 3 3; }
.dash-car { fill: #37474f; }
.dash-wheel { fill: #111; }
.dash-ground { stroke: var(--inst-muted); stroke-width: 1.5; stroke-dasharray: 3 3; }
.dash-car { fill: var(--inst-text); }
.dash-wheel { fill: var(--inst-muted); }
.dash-value { font-size: 18px; font-weight: 700; font-variant-numeric: tabular-nums; }
.dash-caption { font-size: 10px; fill: #777 !important; text-transform: uppercase; letter-spacing: 0.05em; }
.dash-incl .dash-warn { fill: #ef6c00; }
.dash-incl .dash-bad { fill: #c62828; }
.dash-caption { font-size: 10px; fill: var(--inst-muted) !important; text-transform: uppercase; letter-spacing: 0.05em; }
.dash-incl .dash-warn { fill: var(--inst-caution); }
.dash-incl .dash-bad { fill: var(--inst-warning); }
.dash-speed { font-size: 14px; color: #555; }
.dash-speed span { font-size: 34px; font-weight: 700; color: #222; font-variant-numeric: tabular-nums; }
.dash-speed { font-size: 12px; color: var(--inst-muted); text-transform: uppercase; letter-spacing: 0.05em; }
.dash-speed span { font-size: 34px; font-weight: 700; color: var(--inst-text); font-variant-numeric: tabular-nums; letter-spacing: 0; }
/* Navigation on the dashboard: the speed limit sign and what's ahead. */
.dash-nav { display: flex; align-items: center; gap: 10px; margin-bottom: 6px; text-align: left; font-size: 13px; color: #333; }
.dash-nav { display: flex; align-items: center; gap: 10px; margin-bottom: 6px; text-align: left; font-size: 13px; }
/* a road sign stays a road sign: white disc, red ring, black figures */
.dash-limit {
display: inline-flex; align-items: center; justify-content: center; flex: none;
width: 56px; height: 56px; box-sizing: border-box; border: 7px solid #d32f2f; border-radius: 50%;
background: #fff; color: #111; font-size: 22px; font-weight: 700; font-variant-numeric: tabular-nums;
background: #fff; color: #111; font-size: 22px; font-weight: 700; font-variant-numeric: tabular-nums; text-shadow: none;
}
.dash-limit[hidden] { display: none; }
.dash-limit--small { width: 26px; height: 26px; border-width: 3px; font-size: 11px; vertical-align: middle; }
/* no limit (Autobahn): the white sign with the black slash */
.dash-limit--none { border: 2px solid #111; background: linear-gradient(135deg, transparent 45%, #111 45% 55%, transparent 55%), #fff; }
.dash-ahead > div { margin: 2px 0; white-space: nowrap; }
.dash-maneuver { max-width: 220px; overflow: hidden; text-overflow: ellipsis; font-weight: 600; }
.dash-maneuver { max-width: 220px; overflow: hidden; text-overflow: ellipsis; font-weight: 600; color: var(--inst-active); }
.dash-signal {
display: inline-block; width: 8px; height: 20px; vertical-align: middle; border-radius: 3px; background:
radial-gradient(circle at 50% 17%, #e53935 2.5px, transparent 3px), radial-gradient(circle at 50% 50%, #fbc02d 2.5px, transparent 3px),
radial-gradient(circle at 50% 83%, #43a047 2.5px, transparent 3px), #222;
}
.dash-lanes { display: flex; gap: 3px; }
.dash-card--over { box-shadow: 0 0 0 4px #d32f2f, 0 1px 6px rgba(0, 0, 0, 0.25); }
.dash-card--over .dash-speed span { color: #d32f2f; }
.dash-lanes svg.dash-lane { width: 26px; height: 34px; border-radius: 4px; background: #eee; }
.dash-lane__arrow { fill: none; stroke: #aaa; stroke-width: 2; stroke-linecap: round; stroke-linejoin: round; }
.dash-lane--go { background: #1d6fdc !important; }
.dash-lane--go .dash-lane__arrow { stroke: #cfe0f7; }
.dash-lane--go .dash-lane__take { stroke: #fff; stroke-width: 3; }
.dash-offroute { color: #c62828; font-weight: 600; }
.dash-card--over { box-shadow: 0 0 0 4px var(--inst-warning), 0 1px 6px rgba(0, 0, 0, 0.25); }
.dash-card--over .dash-speed span { color: var(--inst-warning); }
.dash-lanes svg.dash-lane { width: 26px; height: 34px; border-radius: 4px; background: rgb(0 0 0 / 0.45); border: 1px solid var(--inst-muted); box-sizing: border-box; }
.dash-lane__arrow { fill: none; stroke: var(--inst-muted); stroke-width: 2; stroke-linecap: round; stroke-linejoin: round; }
.dash-lane--go { border-color: var(--inst-active) !important; }
.dash-lane--go .dash-lane__arrow { stroke: var(--inst-text); }
.dash-lane--go .dash-lane__take { stroke: var(--inst-active); stroke-width: 3; }
.dash-offroute { color: var(--inst-caution); font-weight: 600; }
/* The GNSS position once it has a course: an arrow, not the dot. */
.gnss-marker--arrow { width: 26px; height: 26px; border: none; border-radius: 0; background: none; box-shadow: none; filter: drop-shadow(0 1px 2px rgb(0 0 0 / 0.5)); }
.gnss-marker--arrow svg { display: block; }
+4 -8
View File
@@ -1,5 +1,5 @@
import { isLoggedIn } from "/js/auth.js";
import { onRouteChanged, requestReroute } from "/js/panels.js";
import { onRouteChanged, requestReroute, requestGnssFollow } from "/js/panels.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
@@ -251,17 +251,17 @@ export class DashboardControl {
}
// GNSS simulation on the server (POST/DELETE /api/sim/gnss): random
// driving from a random place in the offline countries, the map jumping
// there with the first fix; on = true / false, null = just read the state.
// 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" } : {};
this._jumpToFix = on === true;
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) {
@@ -305,10 +305,6 @@ export class DashboardControl {
// Date has 1 s resolution: +1 so a fresh value isn't "stale"
return [key, s && now - s.at < STALE_S + 1 ? s.value : null];
}));
if (this._jumpToFix && this._simRunning && this._values.lat != null) {
this._jumpToFix = false;
this._map.jumpTo({ center: [this._values.lon, this._values.lat], zoom: Math.max(this._map.getZoom(), 15) });
}
this._updateCourse(this._values);
this._navigate();
this._status.textContent = this._simRunning ? "Simulated GNSS" : data.available ? "" : "CAN is off on this server";
+22 -1
View File
@@ -1,9 +1,13 @@
import { Marker } from "/vendor/maplibre-gl/maplibre-gl.mjs";
import { GNSS_ICON } from "/js/icons.js";
import { isLoggedIn } from "/js/auth.js";
import { onGnssFollow } from "/js/panels.js";
const POSITION_URL = "/api/gnss/position";
const POLL_INTERVAL_MS = 1500;
const JUMP_M = 1000; // farther than this from the marker: jump there, not glide (a new simulation)
// The position as an arrow, turned by the course once there is one.
const ARROW = `<svg viewBox="0 0 24 24" width="26" height="26"><path d="M12 2 L20 21 L12 16.5 L4 21 Z" fill="#2a9d8f" stroke="#fff" stroke-width="2" stroke-linejoin="round"/></svg>`;
// A sidebar icon that polls /api/gnss/position (the car's receiver, fed
// server-side into GNSS_LATEST in app.rb) and shows the fix as a
@@ -27,6 +31,11 @@ export function followPosition(map, lngLat, heading, speed, duration) {
});
}
// Meters between a MapLibre LngLat and [lon, lat] (equirectangular).
function distanceM({ lng, lat }, [lon2, lat2]) {
return Math.hypot((lon2 - lng) * Math.cos((lat * Math.PI) / 180), lat2 - lat) * 111320;
}
// The marker moved to lngLat the same way: a linear glide over duration ms.
function glideMarker(marker, lngLat, duration) {
cancelAnimationFrame(marker._glide);
@@ -71,6 +80,7 @@ export class GnssControl {
this._flyout = this._container.querySelector(".sidebar-flyout");
this._status = this._container.querySelector(".gnss-control__status");
this._icon.addEventListener("click", () => this._setEnabled(!this._enabled));
onGnssFollow(() => !this._enabled && !this._container.hidden && this._setEnabled(true));
// GET /api/gnss/position itself requires login too (app.rb) — hidden
// here rather than shown and failing on click, same reasoning as
@@ -128,6 +138,8 @@ export class GnssControl {
// 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.
const far = this._marker && distanceM(this._marker.getLngLat(), lngLat) > JUMP_M;
if (far) this._removeMarker();
if (!this._marker) {
const el = document.createElement("div");
el.className = "gnss-marker";
@@ -135,12 +147,21 @@ export class GnssControl {
// style's sources/layers, so — unlike the radar/GPX layers — this
// survives map.setStyle() (switching Online/Offline) with no extra
// re-add handling needed.
this._marker = new Marker({ element: el }).setLngLat(lngLat).addTo(this._map);
this._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) });
} else {
glideMarker(this._marker, lngLat, POLL_INTERVAL_MS);
followPosition(this._map, lngLat, data.track, data.speed, POLL_INTERVAL_MS);
}
// an arrow turned by the course, once there is one (a dot until then)
if (Number.isFinite(data.track)) {
const el = this._marker.getElement();
if (!el.classList.contains("gnss-marker--arrow")) {
el.classList.add("gnss-marker--arrow");
el.innerHTML = ARROW;
}
this._marker.setRotation(data.track);
}
}
_removeMarker() {
+12
View File
@@ -135,6 +135,18 @@ export function onReroute(callback) {
document.addEventListener(REROUTE_EVENT, (event) => callback(event.detail));
}
// Something that moves the GNSS position (the simulation) wants the map
// to follow it: the GNSS control turns itself on.
const GNSS_FOLLOW_EVENT = "gnss-follow";
export function requestGnssFollow() {
document.dispatchEvent(new CustomEvent(GNSS_FOLLOW_EVENT));
}
export function onGnssFollow(callback) {
document.addEventListener(GNSS_FOLLOW_EVENT, callback);
}
export function onRouteChanged(callback) {
document.addEventListener(ROUTE_CHANGED_EVENT, (event) => callback(event.detail));
return currentRoute;
+135
View File
@@ -0,0 +1,135 @@
require_relative "test_helper"
require "tmpdir"
require "maptool/can_discovery"
class CanDiscoveryTest < Minitest::Test
Frame = Maptool::Can::Frame
# A node's SDO server over its OD ({[index, sub] => bytes}), expedited and
# segmented uploads, expedited downloads; `noise` answers first, as if for
# another SDO client.
class FakeNode
attr_reader :od
def initialize(node, od, noise: nil)
@node = node
@od = od
@queue = []
@noise = noise
end
def send(frame)
return unless frame.id == 0x600 + @node
@queue << Frame.new(0x580 + @node, @noise, false) if @noise
@noise = nil
cs = frame.data.getbyte(0)
index, sub = frame.data.byteslice(1, 3).unpack("S<C")
reply = case cs & 0xE0
when 0x40 then initiate(index, sub)
when 0x60 then segment(cs)
when 0x20 then (@od[[index, sub]] = frame.data.byteslice(4, 4 - ((cs >> 2) & 3)); [0x60, index, sub, 0].pack("CS<CL<"))
end
@queue << Frame.new(0x580 + @node, reply, false)
end
def receive(_timeout)
@queue.shift
end
private
def initiate(index, sub)
bytes = @od[[index, sub]] or return [0x80, index, sub, 0x06020000].pack("CS<CL<")
if bytes.bytesize <= 4
[0x43 | ((4 - bytes.bytesize) << 2), index, sub].pack("CS<C") + bytes.ljust(4, "\0")
else
@pending = bytes.dup
@toggle = 0
[0x41, index, sub, bytes.bytesize].pack("CS<CL<")
end
end
def segment(cs)
chunk = @pending.slice!(0, 7)
last = @pending.empty?
[((cs >> 4) & 1) << 4 | ((7 - chunk.bytesize) << 1) | (last ? 1 : 0)].pack("C") + chunk.ljust(7, "\0")
end
end
u32 = ->(v) { [v].pack("L<") }
f32 = ->(v) { [v].pack("e") }
# The GNSS node: TPDO2 0x3A1 lat/lon (entities 6, 7: sensor, REAL32),
# TPDO3 0x4A1 altitude (entity 8: sensor16, -500..9000 m) + satellites
# (entity 11: sensor8, 0..255).
GNSS_OD = {
[0x3002, 1] => u32.(0xCAFE), [0x1008, 0] => "XIAO STM32C5 2",
[0x1802, 1] => u32.(0x3A1), [0x1A02, 0] => "\x02".b, [0x1A02, 1] => u32.(0x20610120), [0x1A02, 2] => u32.(0x20710120),
[0x1803, 1] => u32.(0x4A1), [0x1A03, 0] => "\x02".b, [0x1A03, 1] => u32.(0x20810110), [0x1A03, 2] => u32.(0x20B10108),
[0x1804, 1] => u32.(0x80000000 | 0x221), # disabled
[0x2001, 6] => u32.(1), [0x2001, 7] => u32.(1), [0x2001, 8] => u32.(7), [0x2001, 11] => u32.(6),
[0x2060, 1] => "Latitude", [0x2070, 1] => "Longitude",
[0x2080, 1] => "Altitude", [0x2080, 3] => "m", [0x2080, 7] => f32.(-500.0), [0x2080, 8] => f32.(9000.0),
[0x20B0, 1] => "Satellites", [0x20B0, 7] => f32.(0.0), [0x20B0, 8] => f32.(255.0),
}.transform_values(&:b).freeze
def test_sdo_reads_expedited_and_segmented_and_skips_another_clients_answer
noise = [0x43, 0x3100, 2, 99].pack("CS<CL<") # can2mqtt's log poll answered
sdo = Maptool::Can::Sdo.new(FakeNode.new(0x21, GNSS_OD.dup, noise: noise))
assert_equal 0xCAFE, sdo.upload(0x21, 0x3002, 1).unpack1("L<")
assert_equal "XIAO STM32C5 2", sdo.upload(0x21, 0x1008, 0) # 14 bytes: 2 segments
error = assert_raises(Maptool::Can::Sdo::Abort) { sdo.upload(0x21, 0x9999, 0) }
assert_equal 0x06020000, error.code
node = FakeNode.new(0x21, {})
Maptool::Can::Sdo.new(node).download(0x21, 0x20E2, 1, "\x01")
assert_equal "\x01", node.od[[0x20E2, 1]]
end
def test_a_node_described_decodes_its_own_tpdos
sdo = Maptool::Can::Sdo.new(FakeNode.new(0x21, GNSS_OD.dup))
description = Maptool::Can::Discovery.describe(sdo, 0x21, aliases: { "XIAO STM32C5 2.Latitude" => "gnss.lat" })
assert_equal [0xCAFE, "XIAO STM32C5 2"], description.values_at(:hash, :name)
names = description[:signals].map { |s| s["name"] }
assert_equal ["gnss.lat", "XIAO STM32C5 2.Longitude", "XIAO STM32C5 2.Altitude", "XIAO STM32C5 2.Satellites"], names
decoder = Maptool::Can::Decoder.new([])
decoder.set_node(0x21, description[:signals])
values = decoder.decode(Frame.new(0x3A1, [48.05, 17.36].pack("ee"), false))
assert_in_delta 48.05, values["gnss.lat"], 1e-5
raw = ((144.5 + 500) / 9500 * 65_534).round # the node's encoding
values = decoder.decode(Frame.new(0x4A1, [raw, 7].pack("S<C"), false))
assert_in_delta 144.5, values["XIAO STM32C5 2.Altitude"], 0.1
assert_in_delta 7.03, values["XIAO STM32C5 2.Satellites"], 0.01 # 255/254 per step, as the node encodes
assert_equal "m", decoder.units["XIAO STM32C5 2.Altitude"]
assert_empty decoder.decode(Frame.new(0x4A1, [65_535, 255].pack("S<C"), false)) # unknown
end
# A store that has heard the node, the description cached, read again only
# when the layout hash changes; a node without 0x3002 left alone.
def test_the_discoverer_caches_by_layout_hash
Dir.mktmpdir do |dir|
store = Maptool::Can::Store.new
store.record("vcan0", Frame.new(0x721, "\x05".b, false), {})
store.record("vcan0", Frame.new(0x705, "\x05".b, false), {}) # a foreign node
od = GNSS_OD.dup
node = FakeNode.new(0x21, od)
foreign = FakeNode.new(0x05, {})
both = Object.new
both.define_singleton_method(:send) { |f| node.send(f) || foreign.send(f) }
both.define_singleton_method(:receive) { |t| node.receive(t) || foreign.receive(t) }
decoder = Maptool::Can::Decoder.new([])
discoverer = Maptool::Can::Discoverer.new(store: store, decoder: decoder, cache_dir: dir, sdo: Maptool::Can::Sdo.new(both))
_, err = capture_io { discoverer.run_once(now: 0) }
assert_match(/node 33 \(XIAO STM32C5 2\): 4 signals/, err)
assert File.exist?(File.join(dir, "21.json"))
# a restart: from the cache, nothing read until it's checked again
decoder = Maptool::Can::Decoder.new([])
Maptool::Can::Discoverer.new(store: store, decoder: decoder, cache_dir: dir,
aliases: { "XIAO STM32C5 2.Altitude" => { "name" => "gnss.alt_ft", "scale" => 3.28084, "unit" => "ft" } })
raw = ((144.5 + 500) / 9500 * 65_534).round
assert_in_delta 474.1, decoder.decode(Frame.new(0x4A1, [raw, 7].pack("S<C"), false))["gnss.alt_ft"], 0.5
assert_equal "ft", decoder.units["gnss.alt_ft"]
end
end
end