diff --git a/TODO.adoc b/TODO.adoc index 1f307a4..744affb 100644 --- a/TODO.adoc +++ b/TODO.adoc @@ -475,7 +475,8 @@ are in home-gitops `docs/canopen-nodes.adoc` ("Inšpirácia: Garmin Tread / zūm *** [ ] Positions (a key stepping through states), interlocks and conditions (speed, ignition), switch tiles on the screen (docs/design.adoc, the canvas' GridSwitches / GridBinding) ** [x] CANopen TIME from maptool while no node sends it (2026-12-04, `lib/maptool/can_time.rb`); the GNSS node takes over once esphome-canopen has TIME *** [ ] A knob's hold (the eye), the focused row's badges in keypad mode, the knobs' LEDs (8Encoder colours over SDO) -** [ ] The switch (auto / keyboard / keypad) and the key mapping in our diagnostics +** [x] The key mapping in our diagnostics (2026-12-04, `/keypad.html`, the canvas' GridBinding): pick a key or knob (or press it), what it drives, mode, menu, LEDs; saved per car in `data/drive/bindings.json`. Not yet: interlocks, conditions, long press; drive mode picks a change up only on reload +** [ ] The switch (auto / keyboard / keypad) in our diagnostics * [ ] A virtual switch panel for the PDM node (like Garmin's PowerSwitch: tiles with icon, label, state and current, groups) + rules: by speed, sun/time of day, geofence (the trip's camp), ignition and battery voltage diff --git a/app.rb b/app.rb index 72de240..95b7206 100644 --- a/app.rb +++ b/app.rb @@ -516,18 +516,38 @@ module Maptool # CANopen TIME while nobody else sends it (can.json's "time": false: never). CAN_TIME = CAN_CONFIG && CAN_CONFIG.fetch("time", true) && !test? ? Can::TimeProducer.new { |f| App.can_send(f) } : nil - # The screen profile's bindings, for the outputs (the browser has them - # for the screen's functions); read again when the file changes. + # The keypads' bindings: the ones saved in /keypad.html (data/drive/ + # bindings.json, this car's), else the screen profile's defaults; read + # again when the file changes. The browser takes them from GET /api/keypad/bindings. DRIVE_PROFILE_PATH = File.join(__dir__, "public", "drive", "road.json") + BINDINGS_PATH = File.join(DATA_DIR, "drive", "bindings.json") def self.bindings - mtime = File.mtime(DRIVE_PROFILE_PATH) - @bindings = [mtime, JSON.parse(File.read(DRIVE_PROFILE_PATH)).fetch("bindings", [])] unless @bindings&.first == mtime + path = File.exist?(BINDINGS_PATH) ? BINDINGS_PATH : DRIVE_PROFILE_PATH + key = [path, File.mtime(path)] + @bindings = [key, JSON.parse(File.read(path)).fetch("bindings", [])] unless @bindings&.first == key @bindings.last rescue StandardError => e - warn "drive profile: #{e.message}" + warn "drive bindings: #{e.message}" [] end + BINDING_KEYS = %w[input action menu output mode pulse_s led led_on].freeze + # A saved list's check: each an input, an action / menu or an output, known modes and colours. + def self.check_bindings(list) + raise ArgumentError, "bindings: a list" unless list.is_a?(Array) + + list.map do |b| + raise ArgumentError, "a binding: an object" unless b.is_a?(Hash) + + b = b.slice(*BINDING_KEYS).reject { |_, v| v.nil? || v == "" } + raise ArgumentError, "a binding without an input" unless b["input"].is_a?(String) && b["input"].include?(".") + raise ArgumentError, "#{b['input']}: unknown mode #{b['mode']}" if b["mode"] && !Outputs::MODES.include?(b["mode"]) + %w[led led_on].each { |k| raise ArgumentError, "#{b['input']}: unknown colour #{b[k]}" if b[k] && !Keypad::COLORS.key?(b[k]) } + b["pulse_s"] = Float(b["pulse_s"]) if b["pulse_s"] + b + end + end + def self.keypads_present nodes = CAN_STORE.snapshot[:nodes] KEYPAD ? KEYPAD.devices.select { |d| (seen = nodes.dig(d.heartbeat_node, :heartbeat_at)) && Time.now.to_f - seen < Keypad::PRESENT_S } : [] @@ -666,6 +686,11 @@ module Maptool erb :can, layout: false end + # The keypads' bindings, edited (after the Design canvas' GridBinding). + get "/keypad.html" do + erb :keypad, layout: false + end + # Every CAN frame as it came, decoded (polls GET /api/can?since=). get "/trace.html" do erb :trace, layout: false @@ -1688,6 +1713,39 @@ module Maptool json ok: true end + # The bindings and what they can bind (/keypad.html, drive mode): the + # keypads' channels, the outputs, the colours; saved: this car's own + # (PUT {bindings}), else the profile's (DELETE goes back to them). + get "/api/keypad/bindings" do + require_login! + keypads = (KEYPAD&.devices || []).map do |d| + keys = d.protocol == "pkp" ? (1..d.keys).map { |k| "K#{k}" } : [] + { name: d.name, protocol: d.protocol, node: d.node, channels: (keys + d.inputs.keys).uniq } + end + outputs = (OUTPUTS&.snapshot || []).flat_map { |m| m[:channels].map { |c| { output: "#{m[:name]}.#{c[:n]}", label: c[:label] } } } + json bindings: App.bindings, saved: File.exist?(BINDINGS_PATH), keypads: keypads, outputs: outputs, + modes: Outputs::MODES, colors: Keypad::COLORS.keys - ["off"] + end + + put "/api/keypad/bindings" do + require_login! + begin + list = App.check_bindings(JSON.parse(request.body.read)["bindings"]) + rescue ArgumentError, JSON::ParserError => e + halt 400, json(error: e.message) + end + FileUtils.mkdir_p(File.dirname(BINDINGS_PATH)) + File.write("#{BINDINGS_PATH}.tmp", JSON.pretty_generate(bindings: list)) + File.rename("#{BINDINGS_PATH}.tmp", BINDINGS_PATH) + json bindings: App.bindings, saved: true + end + + delete "/api/keypad/bindings" do + require_login! + FileUtils.rm_f(BINDINGS_PATH) + json bindings: App.bindings, saved: false + end + # The outputs (can.json's "outputs"): each module's channels, their # labels and state, which bindings drive them. get "/api/outputs" do diff --git a/docs/deployment.adoc b/docs/deployment.adoc index a684ad6..b0aad2e 100644 --- a/docs/deployment.adoc +++ b/docs/deployment.adoc @@ -394,6 +394,15 @@ cyan magenta white), `led_on` while its screen key is on. `GET /api/keypad/leds` (`{"keypad": "pad", "on": {"K1": "cyan"}, "blink": {}}`) sets a PKP's key LEDs. +The bindings are edited in `/keypad.html` (after the Design canvas' +GridBinding): the keypads drawn as can.json has them, a key or knob picked +by a tap or by pressing it on the keypad, then what it drives (a screen +key's action or an output), the output's mode, what it does in an open +menu, its LEDs. Saved, they're this car's own, `data/drive/bindings.json` +(`GET`/`PUT`/`DELETE /api/keypad/bindings`), and win over the profile's; +"Back to the profile's" deletes the file. Drive mode takes them when it +loads. + Outputs (`lib/maptool/outputs.rb`): relay modules on the bus, maptool the controller, nothing measured (no current, no feedback). A binding with an `output` in place of an `action` drives one channel: diff --git a/public/js/driving.js b/public/js/driving.js index ab01d81..b9933c2 100644 --- a/public/js/driving.js +++ b/public/js/driving.js @@ -604,7 +604,10 @@ export function setupDriving(map, nightButton, routePanel, gpxPanel) { map.on("pitchend", render); setInterval(render, RENDER_MS); - fetch(PROFILE_URL, { cache: "no-cache" }).then((r) => r.json()).then((p) => { + // the keypads' bindings: this car's own (saved in /keypad.html) over the profile's + const savedBindings = fetch("/api/keypad/bindings", { cache: "no-store" }).then((r) => (r.ok ? r.json() : null)).catch(() => null); + fetch(PROFILE_URL, { cache: "no-cache" }).then((r) => r.json()).then(async (p) => { + p.bindings = (await savedBindings)?.bindings || p.bindings; profile = p; // Cells of p.cell px at most; on a bigger screen only the map's columns // and rows (beside an open menu) stretch, the rest stays cell-sized. diff --git a/test/test_app.rb b/test/test_app.rb index ea1e25d..db06bb4 100644 --- a/test/test_app.rb +++ b/test/test_app.rb @@ -194,6 +194,24 @@ class AppTest < Minitest::Test assert_equal({ "interfaces" => {}, "nodes" => {}, "signals" => {}, "frames" => [], "available" => false, "simulated" => false, "actions" => [], "time" => nil }, json_body(request.get("/api/can", **logged_in_env))) end + # The keypads' bindings: the profile's until this car saves its own, checked on the way in. + def test_keypad_bindings_saved_over_the_profile + assert_equal 401, request.get("/api/keypad/bindings").status + body = json_body(request.get("/api/keypad/bindings", **logged_in_env)) + refute body["saved"] + assert body["bindings"].any? { |b| b["input"] == "pad.K1" } + own = [{ "input" => "pad.K1", "output" => "relays.2", "mode" => "pulse", "pulse_s" => "2", "led" => "red", "junk" => 1 }] + body = json_body(request.put("/api/keypad/bindings", input: JSON.generate(bindings: own), **logged_in_env)) + assert_equal [{ "input" => "pad.K1", "output" => "relays.2", "mode" => "pulse", "pulse_s" => 2.0, "led" => "red" }], body["bindings"] + assert_equal body["bindings"], Maptool::App.bindings + assert_equal 400, request.put("/api/keypad/bindings", input: JSON.generate(bindings: [{ "input" => "pad.K1", "mode" => "blink" }]), **logged_in_env).status + assert_equal 400, request.put("/api/keypad/bindings", input: JSON.generate(bindings: [{ "input" => "pad.K1", "led" => "pink" }]), **logged_in_env).status + refute json_body(request.delete("/api/keypad/bindings", **logged_in_env))["saved"] + assert Maptool::App.bindings.size > 1 + ensure + FileUtils.rm_f(Maptool::App::BINDINGS_PATH) + end + # MQTT messages land in the tracker / ITS-G5 parts of /api/live. def test_live_routes_topics_into_the_snapshot app = Maptool::App diff --git a/views/_debug_nav.erb b/views/_debug_nav.erb index 96b9ca4..e26d015 100644 --- a/views/_debug_nav.erb +++ b/views/_debug_nav.erb @@ -7,7 +7,7 @@ .debug-nav .map { margin-left: auto; }