From e92f01db121a9cbf9ad3ead6444f05e65874dba1 Mon Sep 17 00:00:00 2001 From: Roman Priesol Date: Mon, 30 Nov 2026 19:51:03 +0100 Subject: [PATCH] =?UTF-8?q?Nodes=20describe=20themselves:=20an=20SDO=20cli?= =?UTF-8?q?ent=20(Can::Sdo)=20reads=20each=20esphome-canopen=20node's=20TP?= =?UTF-8?q?DOs=20and=20entities=20(type,=20name,=20unit,=20range)=20on=20i?= =?UTF-8?q?ts=20first=20heartbeat,=20cached=20by=20the=20TPDO=20layout=20h?= =?UTF-8?q?ash,=20decoded=20with=20no=20hand-written=20signals=20=E2=80=94?= =?UTF-8?q?=20can.json=20keeps=20aliases=20(with=20unit=20conversion)=20an?= =?UTF-8?q?d=20foreign=20devices;=20design=20doc=20(NPS=20planning,=20cock?= =?UTF-8?q?pit=20instruments,=20Unigrid=20band)=20with=20color=20tokens,?= =?UTF-8?q?=20the=20dashboard=20in=20cockpit=20colors;=20starting=20the=20?= =?UTF-8?q?simulation=20turns=20the=20GNSS=20follow=20on,=20the=20GNSS=20p?= =?UTF-8?q?osition=20an=20arrow=20by=20its=20course?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- TODO.adoc | 37 ++++++- app.rb | 9 +- docs/deployment.adoc | 63 ++++++----- docs/design.adoc | 86 +++++++++++++++ lib/maptool/can.rb | 27 ++++- lib/maptool/can_discovery.rb | 199 +++++++++++++++++++++++++++++++++++ lib/maptool/can_sdo.rb | 105 ++++++++++++++++++ public/css/style.css | 81 ++++++++------ public/js/dashboard.js | 12 +-- public/js/gnss.js | 23 +++- public/js/panels.js | 12 +++ test/test_can_discovery.rb | 135 ++++++++++++++++++++++++ 12 files changed, 713 insertions(+), 76 deletions(-) create mode 100644 docs/design.adoc create mode 100644 lib/maptool/can_discovery.rb create mode 100644 lib/maptool/can_sdo.rb create mode 100644 test/test_can_discovery.rb diff --git a/TODO.adoc b/TODO.adoc index 2d10f96..3f32191 100644 --- a/TODO.adoc +++ b/TODO.adoc @@ -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 diff --git a/app.rb b/app.rb index 06618b1..18c665a 100644 --- a/app.rb +++ b/app.rb @@ -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 diff --git a/docs/deployment.adoc b/docs/deployment.adoc index 978aa49..1618450 100644 --- a/docs/deployment.adoc +++ b/docs/deployment.adoc @@ -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/.json` +by the TPDO layout hash (`0x3002`:1, checked every 10 min — read again after +an OTA that changed the layout). Signals are named `.` (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 diff --git a/docs/design.adoc b/docs/design.adoc new file mode 100644 index 0000000..fc8a6a3 --- /dev/null +++ b/docs/design.adoc @@ -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. diff --git a/lib/maptool/can.rb b/lib/maptool/can.rb index 78aa078..4a0954a 100644 --- a/lib/maptool/can.rb +++ b/lib/maptool/can.rb @@ -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| diff --git a/lib/maptool/can_discovery.rb b/lib/maptool/can_discovery.rb new file mode 100644 index 0000000..a36cd87 --- /dev/null +++ b/lib/maptool/can_discovery.rb @@ -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/.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 diff --git a/lib/maptool/can_sdo.rb b/lib/maptool/can_sdo.rb new file mode 100644 index 0000000..4a7273e --- /dev/null +++ b/lib/maptool/can_sdo.rb @@ -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> 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 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; } diff --git a/public/js/dashboard.js b/public/js/dashboard.js index f5928b1..aca429e 100644 --- a/public/js/dashboard.js +++ b/public/js/dashboard.js @@ -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"; diff --git a/public/js/gnss.js b/public/js/gnss.js index 4ac168d..46657f9 100644 --- a/public/js/gnss.js +++ b/public/js/gnss.js @@ -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 = ``; // 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() { diff --git a/public/js/panels.js b/public/js/panels.js index dcdf5da..b562d2d 100644 --- a/public/js/panels.js +++ b/public/js/panels.js @@ -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; diff --git a/test/test_can_discovery.rb b/test/test_can_discovery.rb new file mode 100644 index 0000000..50568bd --- /dev/null +++ b/test/test_can_discovery.rb @@ -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> 2) & 3)); [0x60, index, sub, 0].pack("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 "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 { "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