From 82a728e0241dafd491078b79bf2bae47262f784e Mon Sep 17 00:00:00 2001 From: Roman Priesol Date: Fri, 4 Dec 2026 18:50:37 +0100 Subject: [PATCH] =?UTF-8?q?Outputs:=20positions=20(a=20key=20steps=20off?= =?UTF-8?q?=20=E2=86=92=20a=20=E2=86=92=20b=20=E2=86=92=20off,=20a=20knob?= =?UTF-8?q?=20up=20and=20down,=20the=20last=20off=20before=20the=20next=20?= =?UTF-8?q?on),=20strobe=20(a=20period)=20and=20dimmer=20(a=20knob's=20lev?= =?UTF-8?q?el=20by=20a=20step;=20a=20dimmable=20module=20gets=20a=20byte?= =?UTF-8?q?=20per=20channel,=20a=20relay=20just=20switches);=20in=20/keypa?= =?UTF-8?q?d.html=20and=20/sim.html,=20a=20key's=20LED=20on=20while=20a=20?= =?UTF-8?q?position=20is=20chosen=20or=20a=20strobe=20runs?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- TODO.adoc | 3 +- app.rb | 21 +++-- docs/deployment.adoc | 13 ++- lib/maptool/outputs.rb | 183 ++++++++++++++++++++++++++++++++++------- test/test_app.rb | 4 + views/keypad.erb | 62 +++++++++++--- views/sim.erb | 8 +- 7 files changed, 239 insertions(+), 55 deletions(-) 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 @@
Mode
+
Positions — a press steps off → 1 → 2 → … → off, a knob turns up and down +
    +
    + +
    @@ -81,7 +86,10 @@ const KNOB_ACTIONS = ["zoom", "panX", "panY", "rows"]; const MENU = ["rows", "enter", "close"]; const MODE_HINT = { toggle: "each press switches it", on: "a press switches it on", off: "a press switches it off", - hold: "on while held — off when let go or the keypad goes silent", pulse: "on for the time below" }; + hold: "on while held — off when let go or the keypad goes silent", pulse: "on for the time below", + positions: "one output per position, the last off before the next on", strobe: "a press starts or stops it blinking", + dimmer: "a knob sets the level, a press switches it on or off; only a dimmable module dims, a relay just switches" }; + const KNOB_MODES = ["positions", "dimmer"]; // what a turn does; the other modes take presses let info = null, bindings = [], screenActions = [], selected = null, dirty = false; const json = async (url, options) => { @@ -92,7 +100,8 @@ }; const binding = (input) => bindings.find((b) => b.input === input); const isKnob = (input) => /\.E\d+$/.test(input); - const what = (b) => (b ? b.output ? `${b.output}${outputLabel(b.output) ? ` ${outputLabel(b.output)}` : ""}` : b.action || (b.menu ? `menu: ${b.menu}` : "") : ""); + const outs = (b) => b?.outputs || (b?.output ? [b.output] : []); + const what = (b) => (!b ? "" : b.outputs ? `${b.mode}: ${b.outputs.join(", ")}` : b.output ? `${b.output}${outputLabel(b.output) ? ` ${outputLabel(b.output)}` : ""}${b.mode && b.mode !== "toggle" ? ` · ${b.mode}` : ""}` : b.action || (b.menu ? `menu: ${b.menu}` : "")); const outputLabel = (o) => info.outputs.find((x) => x.output === o)?.label || ""; function key(input, label, cls = "") { @@ -121,22 +130,31 @@ const pkpKey = /\.K\d+$/.test(selected) && info.keypads.find((d) => selected.startsWith(`${d.name}.`))?.protocol === "pkp"; $("title").textContent = `${selected}${knob ? " · turning" : selected.endsWith(" press") ? " · pressing the knob" : ""}`; const actions = [...(knob ? KNOB_ACTIONS : []), ...screenActions]; - const drives = b.output ? `output:${b.output}` : b.action ? `action:${b.action}` : ""; + const first = outs(b)[0]; + const drives = first ? `output:${first}` : b.action ? `action:${b.action}` : ""; $("drives").innerHTML = `` + `${actions.map((a) => ``).join("")}` + - (knob ? "" : `${info.outputs.map((o) => ``).join("")}`); - const mode = b.mode || "toggle"; - $("mode-box").hidden = !b.output; - $("modes").innerHTML = info.modes.map((m) => ``).join(""); + `${outputOptions(drives.slice(7))}`; + const isOut = !!first; + const mode = b.mode || (knob ? "dimmer" : "toggle"); + $("mode-box").hidden = !isOut; + $("modes").innerHTML = info.modes.filter((m) => !knob || KNOB_MODES.includes(m)).map((m) => ``).join(""); $("mode-hint").textContent = MODE_HINT[mode] || ""; - $("pulse-box").hidden = !b.output || mode !== "pulse"; + $("positions-box").hidden = !isOut || mode !== "positions"; + $("positions").innerHTML = (b.outputs || []).map((o, i) => `
  1. ${i ? `` : ""}
  2. `).join(""); + $("pulse-box").hidden = !isOut || mode !== "pulse"; $("pulse").value = b.pulse_s ?? 1; + $("period-box").hidden = !isOut || mode !== "strobe"; + $("period").value = b.period_s ?? 1; + $("step-box").hidden = !isOut || mode !== "dimmer"; + $("step").value = b.step ?? 10; $("menu").innerHTML = options([...(knob ? ["rows"] : MENU.slice(1)).map((m) => [m, m]), ...screenActions.map((a) => [a, a])], b.menu, "— the same —"); $("led-box").hidden = !pkpKey; const colors = info.colors.map((c) => [c, c]); $("led").innerHTML = options(colors, b.led, "off"); $("led_on").innerHTML = options(colors, b.led_on, b.output ? "red" : "green"); } + const outputOptions = (value) => info.outputs.map((o) => ``).join(""); function render() { renderPads(); renderEditor(); @@ -150,7 +168,7 @@ if (!b) bindings.push((b = { input: selected })); Object.assign(b, fields); for (const k of Object.keys(b)) if (b[k] === "" || b[k] == null) delete b[k]; - if (!b.action && !b.output && !b.menu) bindings = bindings.filter((x) => x !== b); + if (!b.action && !b.output && !b.outputs && !b.menu) bindings = bindings.filter((x) => x !== b); dirty = true; render(); } @@ -160,12 +178,34 @@ }); $("drives").addEventListener("change", (e) => { const [kind, value] = [e.target.value.slice(0, e.target.value.indexOf(":")), e.target.value.slice(e.target.value.indexOf(":") + 1)]; - change(kind === "output" ? { output: value, action: null } : { action: kind === "action" ? value : null, output: null, mode: null, pulse_s: null }); + const b = binding(selected); + if (kind === "output" && b?.outputs) change({ outputs: [value, ...b.outputs.slice(1)] }); + else if (kind === "output") change({ output: value, action: null, mode: isKnob(selected) ? "dimmer" : b?.mode }); + else change({ action: kind === "action" ? value : null, output: null, outputs: null, mode: null, pulse_s: null, period_s: null, step: null }); }); $("modes").addEventListener("click", (e) => { const m = e.target.closest("button[data-mode]")?.dataset.mode; - if (m) change({ mode: m === "toggle" ? null : m, pulse_s: m === "pulse" ? binding(selected)?.pulse_s ?? 1 : null }); + if (!m) return; + const list = outs(binding(selected)); + change({ mode: m === "toggle" ? null : m, pulse_s: m === "pulse" ? binding(selected)?.pulse_s ?? 1 : null, + period_s: m === "strobe" ? binding(selected)?.period_s ?? 1 : null, step: m === "dimmer" ? binding(selected)?.step ?? 10 : null, + outputs: m === "positions" ? list : null, output: m === "positions" ? null : list[0] }); }); + $("positions").addEventListener("change", (e) => { + const i = Number(e.target.dataset.position); + change({ outputs: binding(selected).outputs.map((o, k) => (k === i ? e.target.value : o)) }); + }); + $("positions").addEventListener("click", (e) => { + const i = e.target.dataset.drop; + if (i != null) change({ outputs: binding(selected).outputs.filter((_, k) => k !== Number(i)) }); + }); + $("add-position").addEventListener("click", () => { + const list = binding(selected).outputs; + const next = info.outputs.find((o) => !list.includes(o.output))?.output || list[list.length - 1]; + change({ outputs: [...list, next] }); + }); + $("period").addEventListener("change", (e) => change({ period_s: Number(e.target.value) || 1 })); + $("step").addEventListener("change", (e) => change({ step: Number(e.target.value) || 10 })); $("pulse").addEventListener("change", (e) => change({ pulse_s: Number(e.target.value) || 1 })); $("menu").addEventListener("change", (e) => change({ menu: e.target.value })); $("led").addEventListener("change", (e) => change({ led: e.target.value })); diff --git a/views/sim.erb b/views/sim.erb index e00fd56..a74f662 100644 --- a/views/sim.erb +++ b/views/sim.erb @@ -55,9 +55,9 @@
    @@ -118,9 +118,9 @@ $("outputs").hidden = !data; if (!data) return; const esc = (s) => String(s).replace(/[&<>"]/g, (ch) => `&#${ch.charCodeAt(0)};`); - const by = (o) => data.bindings.filter((b) => b.output === o).map((b) => `${b.input} (${b.mode || "toggle"})`).join(", "); + const by = (o) => data.bindings.filter((b) => (b.outputs || [b.output]).includes(o)).map((b) => `${b.input} (${b.mode || "toggle"})`).join(", "); $("relays").innerHTML = data.modules.map((m) => `

    ${esc(m.name)} · node ${m.node}${m.simulated ? " · simulated" : ""}

    ` + - m.channels.map((c) => ``).join("") + "
    ").join(""); + m.channels.map((c) => ``).join("") + "").join(""); } $("relays").addEventListener("click", (e) => { const b = e.target.closest("button[data-output]");