diff --git a/TODO.adoc b/TODO.adoc index 744affb..e0f336f 100644 --- a/TODO.adoc +++ b/TODO.adoc @@ -472,7 +472,8 @@ are in home-gitops `docs/canopen-nodes.adoc` ("Inšpirácia: Garmin Tread / zūm ** [x] Drive mode keys from the keyboard (profile `key`, labels in the corners, ↑ ↓ / Enter / Space / + / Esc in a menu) ** [x] Keypads as channels and bindings, the PDMs' way (2026-12-04, `lib/maptool/keypad.rb`): can.json's `"keypads"` (a PKP by its protocol, or any signals as `inputs`) give channels `pad.K1`, `pad.E3`, `pad.E3 press`; the screen profile's `"bindings"` give each an action (a screen key, zoom, pan, rows), another in an open menu, its LED colour and the colour while on. A keypad's heartbeat labels the screen keys with its channels (back after 5 s without it), a line under them in the LED colour. Not tried on the real node yet *** [x] Outputs (2026-12-04, `lib/maptool/outputs.rb`): can.json's relay modules (simulated for now, no current measured), a binding's `output` with Toggle / On / Off / Hold / Pulse, Hold off when the keypad goes silent, the state re-sent every 100 ms (the module's 2 s watchdog), the key LED while on; `/sim.html` switches them by hand. Not tried on a real module -*** [ ] Positions (a key stepping through states), interlocks and conditions (speed, ignition), switch tiles on the screen (docs/design.adoc, the canvas' GridSwitches / GridBinding) +*** [x] Positions, strobe and dimmer (2026-12-04): a key steps through outputs (a knob up and down), blinking with a period, a knob's level by a step (a dimmable module: a byte per channel); in /keypad.html and /sim.html. Nothing real behind them yet +*** [ ] Interlocks and conditions (speed, ignition), long press, 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) ** [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 diff --git a/app.rb b/app.rb index 95b7206..32197a7 100644 --- a/app.rb +++ b/app.rb @@ -531,7 +531,7 @@ module Maptool [] end - BINDING_KEYS = %w[input action menu output mode pulse_s led led_on].freeze + BINDING_KEYS = %w[input action menu output outputs mode pulse_s period_s step 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) @@ -543,7 +543,14 @@ module Maptool 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"] + if b["mode"] == "positions" + raise ArgumentError, "#{b['input']}: positions need outputs" unless b["outputs"].is_a?(Array) && b["outputs"].any? && b["outputs"].all?(String) + + b.delete("output") + else + b.delete("outputs") + end + %w[pulse_s period_s step].each { |k| b[k] = Float(b[k]) if b[k] } b end end @@ -561,9 +568,9 @@ module Maptool on = (KEYPAD_SCREEN_LEDS.dig(device.name, "on") || {}).dup if OUTPUTS bindings.each do |b| - next unless b["output"] && b["input"].to_s.start_with?("#{device.name}.") + next unless Outputs.outputs_of(b).any? && b["input"].to_s.start_with?("#{device.name}.") - on[b["input"].delete_prefix("#{device.name}.")] = OUTPUTS.on?(b["output"]) ? b.fetch("led", "red") : nil + on[b["input"].delete_prefix("#{device.name}.")] = OUTPUTS.active?(b) ? b.fetch("led", "red") : nil end end KEYPAD.led_frames(device.name, on, KEYPAD_SCREEN_LEDS.dig(device.name, "blink")) @@ -1722,7 +1729,7 @@ module Maptool 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] } } } + outputs = (OUTPUTS&.snapshot || []).flat_map { |m| m[:channels].map { |c| { output: "#{m[:name]}.#{c[:n]}", label: c[:label], dimmable: m[:dimmable] } } } json bindings: App.bindings, saved: File.exist?(BINDINGS_PATH), keypads: keypads, outputs: outputs, modes: Outputs::MODES, colors: Keypad::COLORS.keys - ["off"] end @@ -1751,7 +1758,7 @@ module Maptool get "/api/outputs" do require_login! halt 404, json(error: "no outputs in data/can.json") unless OUTPUTS - bound = App.bindings.select { |b| b["output"] } + bound = App.bindings.select { |b| Outputs.outputs_of(b).any? } json modules: OUTPUTS.snapshot, bindings: bound end @@ -1764,7 +1771,7 @@ module Maptool halt 404, json(error: "no output #{output}") unless OUTPUTS.find(output) body = request.body.read on = body.empty? ? nil : JSON.parse(body)["on"] - OUTPUTS.set(output, on.nil? ? !OUTPUTS.on?(output) : !!on) + OUTPUTS.manual(output, on.nil? ? !OUTPUTS.on?(output) : !!on) json on: OUTPUTS.on?(output) end diff --git a/docs/deployment.adoc b/docs/deployment.adoc index b0aad2e..ea19baa 100644 --- a/docs/deployment.adoc +++ b/docs/deployment.adoc @@ -415,10 +415,17 @@ controller, nothing measured (no current, no feedback). A binding with an `{ "input": "pad.E2 press", "output": "relays.1", "mode": "hold", "led": "red" }` — `mode`: `toggle` (default), `on`, `off`, `hold` (on while held; off when let go or when the keypad's heartbeat is gone), `pulse` (on for -`pulse_s`, 1 s by default). A PKP key bound to an output shows `led` (red -by default) while it's on, whatever the screen says. The module's +`pulse_s`, 1 s by default), `positions` (`"outputs": [a, b, …]`: a press +steps off → a → b → … → off, a knob turns up and down, one on at a time, +the last off before the next on), `strobe` (a press starts / stops it +blinking, `period_s` a whole on + off, 1 s), `dimmer` (a knob sets the +level by `step` %, 10; a press switches it on / off — only a module with +`"dimmable": true` dims, a relay just switches). A PKP key bound to an +output shows `led` (red by default) while it's on (a position chosen, a +strobe running), whatever the screen says. The module's protocol is ours (after LD's native CAN control): RPDO1 `0x200+node`, a -bit per channel (byte 0 channels 1–8, byte 1 9–16), the whole state sent +bit per channel (byte 0 channels 1–8, byte 1 9–16) — a dimmable one a +byte per channel, 0–255, 8 channels at most — the whole state sent on every change and every 100 ms; the module is to switch everything off after 2 s without a frame. `"simulated": true` sends nothing, the state only lives in the server — `/sim.html` shows the relays and switches diff --git a/lib/maptool/outputs.rb b/lib/maptool/outputs.rb index 31b63db..ca14d51 100644 --- a/lib/maptool/outputs.rb +++ b/lib/maptool/outputs.rb @@ -6,36 +6,50 @@ module Maptool # the bindings that drive them from a keypad's channels (docs/design.adoc, # "Switches and the keypad"): maptool is the controller, the module only # switches. The bindings are the screen profile's (public/drive/road.json) - # with an "output" in place of an "action": + # or this car's (data/drive/bindings.json) with an "output" in place of an "action": # { "input": "pad.K6", "output": "relays.2", "mode": "hold", "led": "red" } - # Modes: toggle, on, off, hold (on while the key is held — off when it's - # let go or the keypad goes silent), pulse (on for "pulse_s", 1 s by default). + # Modes (after Garmin PowerSwitch, OnDeck, MaxxECU — docs/design.adoc): + # toggle, on, off + # hold on while the key is held — off when it's let go or the keypad goes silent + # pulse on for "pulse_s" (1 s) + # positions "outputs": [a, b, …] — a press steps off → a → b → … → off, a knob + # turns up and down; one on at a time, the last off before the next on + # strobe a press starts / stops it blinking, "period_s" (1 s) a whole on + off + # dimmer a knob sets the level by "step" % (10), a press switches it on / off; + # only a "dimmable" module dims, a relay is on above 0 # # can.json: "outputs": [ { "name": "relays", "node": 48, "channels": 8, "simulated": true, - # "labels": { "1": "Lights", "2": "Winch in" } } ] + # "labels": { "1": "Lights", "2": "Winch in" } }, + # { "name": "dim", "node": 49, "channels": 4, "dimmable": true, "simulated": true } ] # A module's protocol, ours (after LD's native CAN control): RPDO1 - # 0x200+node, a bit per channel (byte 0: 1–8, byte 1: 9–16), the whole - # state in every frame, sent on a change and every REPEAT_S — the module - # turns everything off after 2 s without one. "simulated": no frames, - # the state is just kept here (/sim.html shows it). + # 0x200+node, a bit per channel (byte 0: 1–8, byte 1: 9–16) — a dimmable + # one a byte per channel instead (0–255, up to 8) — the whole state in + # every frame, sent on a change and every REPEAT_S; the module turns + # everything off after 2 s without one. "simulated": no frames, the state + # is just kept here (/sim.html shows it). class Outputs REPEAT_S = 0.1 - MODES = %w[toggle on off hold pulse].freeze + MODES = %w[toggle on off hold pulse positions strobe dimmer].freeze - Module = Struct.new(:name, :node, :channels, :simulated, :labels, :state, keyword_init: true) + Module = Struct.new(:name, :node, :channels, :simulated, :dimmable, :labels, :state, :level, keyword_init: true) attr_reader :modules # send: a block that puts a Frame on the bus (not called for simulated modules) def initialize(configs, &send) @modules = configs.map do |c| - Module.new(name: c.fetch("name"), node: Integer(c.fetch("node", 0)), channels: c.fetch("channels", 8), - simulated: c.fetch("simulated", false), labels: c.fetch("labels", {}), state: Array.new(c.fetch("channels", 8), false)) + n = c.fetch("channels", 8) + raise ArgumentError, "#{c['name']}: a dimmable module has 8 channels at most" if c["dimmable"] && n > 8 + + Module.new(name: c.fetch("name"), node: Integer(c.fetch("node", 0)), channels: n, simulated: c.fetch("simulated", false), + dimmable: c.fetch("dimmable", false), labels: c.fetch("labels", {}), state: Array.new(n, false), level: Array.new(n, 100)) end @send = send @mutex = Mutex.new @pulses = {} - @held = {} # channel (the key) → outputs it holds on + @held = {} # channel (the key) → outputs it holds on + @positions = {} # channel → its position, 0 = all off + @strobes = {} # output → [since, period] end def find(output) @@ -50,9 +64,15 @@ module Maptool m ? @mutex.synchronize { m.state[i] } : nil end + def level(output) + m, i = find(output) + m ? @mutex.synchronize { m.level[i] } : nil + end + def set(output, value) m, i = find(output) raise ArgumentError, "no output #{output}" unless m + changed = @mutex.synchronize do next false if m.state[i] == value @@ -64,16 +84,46 @@ module Maptool changed end - # A keypad event ("pad.K6", "pad.K6 up") through the bindings that have an output. - def input(event, bindings, at: Time.now.to_f) - up = event.end_with?(" up") - channel = event.delete_suffix(" up") - bindings.each do |b| - next unless b["output"] && b["input"] == channel && find(b["output"]) # a profile's output this car hasn't: skipped + # By hand (/sim.html, a screen tile): a strobe stops. + def manual(output, value) + @mutex.synchronize { @strobes.delete(output) } + set(output, value) + end - output = b["output"] - case b.fetch("mode", "toggle") - when "toggle" then set(output, !on?(output)) unless up + # The binding's outputs: "outputs" (positions) or "output". + def self.outputs_of(binding) = Array(binding["outputs"] || binding["output"]) + + # Whether a binding's function is on (its key's LED): a position chosen, a strobe running, else its output on. + def active?(binding) + outs = self.class.outputs_of(binding) + case binding["mode"] + when "positions" then @mutex.synchronize { @positions.fetch(binding["input"], 0) }.positive? + when "strobe" then @mutex.synchronize { @strobes.key?(outs.first) } + else !!on?(outs.first) + end + end + + # A keypad event ("pad.K6", "pad.K6 up", "pad.E4 ⟳") through the bindings that have an output. + def input(event, bindings, at: Time.now.to_f) + turn = event[/ ([⟳⟲])\z/, 1] + up = event.end_with?(" up") + channel = event.sub(/ (up|⟳|⟲)\z/, "") + bindings.each do |b| + outs = self.class.outputs_of(b) + # a profile's output this car hasn't: skipped + next unless b["input"] == channel && outs.any? && outs.all? { |o| find(o) } + + output = outs.first + mode = b.fetch("mode", "toggle") + if turn + step = turn == "⟳" ? 1 : -1 + if mode == "positions" then position(channel, outs, @mutex.synchronize { @positions.fetch(channel, 0) } + step) + elsif mode == "dimmer" then dim(output, step * b.fetch("step", 10).to_f) + end + next + end + case mode + when "toggle", "dimmer" then switch(output, !on?(output)) unless up when "on" then set(output, true) unless up when "off" then set(output, false) unless up when "hold" @@ -84,6 +134,12 @@ module Maptool set(output, true) @mutex.synchronize { @pulses[output] = at + b.fetch("pulse_s", 1).to_f } + when "positions" then position(channel, outs, (@mutex.synchronize { @positions.fetch(channel, 0) } + 1) % (outs.size + 1)) unless up + when "strobe" + next if up + + started = @mutex.synchronize { @strobes.delete(output) ? false : (@strobes[output] = [at, b.fetch("period_s", 1).to_f]) && true } + set(output, started) # started: on now; stopped: off end end end @@ -96,26 +152,57 @@ module Maptool end end - # Every REPEAT_S: pulses ending, the state sent again (the module's watchdog). + # Every REPEAT_S: pulses ending, strobes blinking, the state sent again (the module's watchdog). def tick(at: Time.now.to_f) - ended = @mutex.synchronize { @pulses.select { |_, till| till <= at }.keys } + ended, strobes = @mutex.synchronize { [@pulses.select { |_, till| till <= at }.keys, @strobes.dup] } ended.each { |o| set(o, false) } + strobes.each { |o, (since, period)| set(o, ((at - since) / (period / 2)).floor.even?) } @modules.each { |m| transmit(m) } end def frame(m) - bits = m.state.each_with_index.sum { |on, i| on ? 1 << i : 0 } - Can::Frame.new(0x200 + m.node, [bits].pack("Q<").byteslice(0, (m.channels + 7) / 8), false) + data = if m.dimmable + m.state.each_with_index.map { |on, i| on ? (m.level[i] * 255 / 100.0).round : 0 }.pack("C*") + else + [m.state.each_with_index.sum { |on, i| on ? 1 << i : 0 }].pack("Q<").byteslice(0, (m.channels + 7) / 8) + end + Can::Frame.new(0x200 + m.node, data, false) end def snapshot @mutex.synchronize do - @modules.map { |m| { name: m.name, node: m.node, simulated: m.simulated, channels: (1..m.channels).map { |n| { n: n, label: m.labels[n.to_s], on: m.state[n - 1] } } } } + @modules.map do |m| + { name: m.name, node: m.node, simulated: m.simulated, dimmable: m.dimmable, + channels: (1..m.channels).map do |n| + { n: n, label: m.labels[n.to_s], on: m.state[n - 1], level: m.dimmable ? m.level[n - 1] : nil, strobe: @strobes.key?("#{m.name}.#{n}") }.compact + end } + end end end private + # on with its level above 0 (a dimmer switched on at 0 comes back at 100) + def switch(output, value) + m, i = find(output) + @mutex.synchronize { m.level[i] = 100 if value && m.level[i].zero? } + set(output, value) + end + + def dim(output, delta) + m, i = find(output) + level = @mutex.synchronize { m.level[i] = (m.level[i] + delta).clamp(0, 100) } + transmit(m) unless set(output, level.positive?) + end + + # The channel's position n (clamped to 0..outputs): the others off first, then its own on. + def position(channel, outs, n) + n = n.clamp(0, outs.size) + @mutex.synchronize { @positions[channel] = n } + outs.each_with_index { |o, i| set(o, false) unless i == n - 1 } + set(outs[n - 1], true) if n.positive? + end + def transmit(m) return if m.simulated || !@send @@ -128,7 +215,7 @@ end if $PROGRAM_NAME == __FILE__ sent = [] - out = Maptool::Outputs.new([{ "name" => "relays", "node" => 48 }]) { |f| sent << f } + out = Maptool::Outputs.new([{ "name" => "relays", "node" => 48 }, { "name" => "dim", "node" => 49, "channels" => 2, "dimmable" => true }]) { |f| sent << f } b = [{ "input" => "pad.K1", "output" => "relays.1" }, { "input" => "pad.K6", "output" => "relays.2", "mode" => "hold" }, { "input" => "pad.K7", "output" => "relays.3", "mode" => "pulse", "pulse_s" => 2 }] out.input("pad.K1", b) @@ -143,6 +230,44 @@ if $PROGRAM_NAME == __FILE__ out.tick(at: 102.1) raise "pulse" if out.on?("relays.3") out.input("pad.K1", [{ "input" => "pad.K1", "output" => "winch.1" }]) # no such module: nothing, no error - raise sent.last.inspect unless sent.last.id == 0x230 && sent.last.data == "\x01".b + relay_frame = sent.reverse.find { |f| f.id == 0x230 } + raise relay_frame.inspect unless relay_frame.data == "\x01".b + + # positions: off → 4 → 5 → off by presses; a knob up and down, clamped + pos = [{ "input" => "pad.K2", "outputs" => ["relays.4", "relays.5"], "mode" => "positions" }, + { "input" => "pad.E4", "outputs" => ["relays.4", "relays.5"], "mode" => "positions" }] + states = -> { [out.on?("relays.4"), out.on?("relays.5")] } + out.input("pad.K2", pos) + raise "pos 1" unless states.call == [true, false] && out.active?(pos[0]) + out.input("pad.K2", pos) + raise "pos 2" unless states.call == [false, true] + out.input("pad.K2", pos) + raise "pos 0" unless states.call == [false, false] && !out.active?(pos[0]) + 3.times { out.input("pad.E4 ⟳", pos) } + raise "knob clamp" unless states.call == [false, true] + out.input("pad.E4 ⟲", pos) + raise "knob down" unless states.call == [true, false] + + # strobe: blinks at half the period, a press stops it off + st = [{ "input" => "pad.K3", "output" => "relays.6", "mode" => "strobe", "period_s" => 1 }] + out.input("pad.K3", st, at: 200) + out.tick(at: 200.6) + raise "strobe off phase" if out.on?("relays.6") + out.tick(at: 201.1) + raise "strobe on phase" unless out.on?("relays.6") && out.active?(st[0]) + out.input("pad.K3", st, at: 201.2) + out.tick(at: 201.6) + raise "strobe stopped" if out.on?("relays.6") || out.active?(st[0]) + + # dimmer: a knob down to 0 is off, up is on again; a dimmable module sends bytes + dm = [{ "input" => "pad.E5", "output" => "dim.1", "mode" => "dimmer", "step" => 50 }, { "input" => "pad.E5 press", "output" => "dim.1", "mode" => "dimmer" }] + out.input("pad.E5 press", dm) + raise "dimmer on" unless out.on?("dim.1") && out.level("dim.1") == 100 + out.input("pad.E5 ⟲", dm) + raise sent.last.data.bytes.inspect unless sent.last.id == 0x231 && sent.last.data.bytes == [128, 0] + out.input("pad.E5 ⟲", dm) + raise "dimmer 0 off" if out.on?("dim.1") + out.input("pad.E5 ⟳", dm) + raise "dimmer up" unless out.on?("dim.1") && out.level("dim.1") == 50 puts "ok" end diff --git a/test/test_app.rb b/test/test_app.rb index db06bb4..33a855f 100644 --- a/test/test_app.rb +++ b/test/test_app.rb @@ -206,6 +206,10 @@ class AppTest < Minitest::Test 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 + assert_equal 400, request.put("/api/keypad/bindings", input: JSON.generate(bindings: [{ "input" => "pad.K2", "mode" => "positions", "output" => "relays.1" }]), **logged_in_env).status + pos = [{ "input" => "pad.K2", "mode" => "positions", "outputs" => ["relays.1", "relays.2"], "output" => "relays.1" }] + assert_equal [{ "input" => "pad.K2", "mode" => "positions", "outputs" => ["relays.1", "relays.2"] }], + json_body(request.put("/api/keypad/bindings", input: JSON.generate(bindings: pos), **logged_in_env))["bindings"] refute json_body(request.delete("/api/keypad/bindings", **logged_in_env))["saved"] assert Maptool::App.bindings.size > 1 ensure diff --git a/views/keypad.erb b/views/keypad.erb index 2d781f1..7ed0164 100644 --- a/views/keypad.erb +++ b/views/keypad.erb @@ -54,7 +54,12 @@
+ + +can.json's "outputs" (simulated: no frames sent). A click switches one; the keypad's bindings with an "output" do too.
+can.json's "outputs" (simulated: no frames sent). A click switches one (and stops its strobe); the keypad's bindings with an output do too.
${esc(m.name)} · node ${m.node}${m.simulated ? " · simulated" : ""}