Outputs: positions (a key steps off → a → b → off, a knob up and down, the last off before the next on), strobe (a period) and dimmer (a knob's level by a step; a dimmable module gets a byte per channel, a relay just switches); in /keypad.html and /sim.html, a key's LED on while a position is chosen or a strobe runs
CI / check (push) Successful in 23s
CI / deploy (push) Successful in 17s

This commit is contained in:
randy committed 2026-12-04 18:50:37 +01:00
1 parent e82b2236b5
commit 82a728e024
7 files changed
+239 -55

No files matched your search

+2 -1
View File
@@ -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] 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] 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 *** [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 ** [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) *** [ ] 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 ** [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
+14 -7
View File
@@ -531,7 +531,7 @@ module Maptool
[] []
end 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. # A saved list's check: each an input, an action / menu or an output, known modes and colours.
def self.check_bindings(list) def self.check_bindings(list)
raise ArgumentError, "bindings: a list" unless list.is_a?(Array) 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, "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"]) 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]) } %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 b
end end
end end
@@ -561,9 +568,9 @@ module Maptool
on = (KEYPAD_SCREEN_LEDS.dig(device.name, "on") || {}).dup on = (KEYPAD_SCREEN_LEDS.dig(device.name, "on") || {}).dup
if OUTPUTS if OUTPUTS
bindings.each do |b| 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
end end
KEYPAD.led_frames(device.name, on, KEYPAD_SCREEN_LEDS.dig(device.name, "blink")) 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}" } : [] 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 } { name: d.name, protocol: d.protocol, node: d.node, channels: (keys + d.inputs.keys).uniq }
end 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, json bindings: App.bindings, saved: File.exist?(BINDINGS_PATH), keypads: keypads, outputs: outputs,
modes: Outputs::MODES, colors: Keypad::COLORS.keys - ["off"] modes: Outputs::MODES, colors: Keypad::COLORS.keys - ["off"]
end end
@@ -1751,7 +1758,7 @@ module Maptool
get "/api/outputs" do get "/api/outputs" do
require_login! require_login!
halt 404, json(error: "no outputs in data/can.json") unless OUTPUTS 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 json modules: OUTPUTS.snapshot, bindings: bound
end end
@@ -1764,7 +1771,7 @@ module Maptool
halt 404, json(error: "no output #{output}") unless OUTPUTS.find(output) halt 404, json(error: "no output #{output}") unless OUTPUTS.find(output)
body = request.body.read body = request.body.read
on = body.empty? ? nil : JSON.parse(body)["on"] 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) json on: OUTPUTS.on?(output)
end end
+10 -3
View File
@@ -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": `{ "input": "pad.E2 press", "output": "relays.1", "mode": "hold", "led":
"red" }` — `mode`: `toggle` (default), `on`, `off`, `hold` (on while held; "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 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 `pulse_s`, 1 s by default), `positions` (`"outputs": [a, b, …]`: a press
by default) while it's on, whatever the screen says. The module's 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 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 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 after 2 s without a frame. `"simulated": true` sends nothing, the state
only lives in the server — `/sim.html` shows the relays and switches only lives in the server — `/sim.html` shows the relays and switches
+154 -29
View File
@@ -6,36 +6,50 @@ module Maptool
# the bindings that drive them from a keypad's channels (docs/design.adoc, # 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 and the keypad"): maptool is the controller, the module only
# switches. The bindings are the screen profile's (public/drive/road.json) # 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" } # { "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 # Modes (after Garmin PowerSwitch, OnDeck, MaxxECU — docs/design.adoc):
# let go or the keypad goes silent), pulse (on for "pulse_s", 1 s by default). # 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, # 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 # 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 # 0x200+node, a bit per channel (byte 0: 1–8, byte 1: 9–16) — a dimmable
# state in every frame, sent on a change and every REPEAT_S — the module # one a byte per channel instead (0–255, up to 8) — the whole state in
# turns everything off after 2 s without one. "simulated": no frames, # every frame, sent on a change and every REPEAT_S; the module turns
# the state is just kept here (/sim.html shows it). # everything off after 2 s without one. "simulated": no frames, the state
# is just kept here (/sim.html shows it).
class Outputs class Outputs
REPEAT_S = 0.1 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 attr_reader :modules
# send: a block that puts a Frame on the bus (not called for simulated modules) # send: a block that puts a Frame on the bus (not called for simulated modules)
def initialize(configs, &send) def initialize(configs, &send)
@modules = configs.map do |c| @modules = configs.map do |c|
Module.new(name: c.fetch("name"), node: Integer(c.fetch("node", 0)), channels: c.fetch("channels", 8), n = c.fetch("channels", 8)
simulated: c.fetch("simulated", false), labels: c.fetch("labels", {}), state: Array.new(c.fetch("channels", 8), false)) 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 end
@send = send @send = send
@mutex = Mutex.new @mutex = Mutex.new
@pulses = {} @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 end
def find(output) def find(output)
@@ -50,9 +64,15 @@ module Maptool
m ? @mutex.synchronize { m.state[i] } : nil m ? @mutex.synchronize { m.state[i] } : nil
end end
def level(output)
m, i = find(output)
m ? @mutex.synchronize { m.level[i] } : nil
end
def set(output, value) def set(output, value)
m, i = find(output) m, i = find(output)
raise ArgumentError, "no output #{output}" unless m raise ArgumentError, "no output #{output}" unless m
changed = @mutex.synchronize do changed = @mutex.synchronize do
next false if m.state[i] == value next false if m.state[i] == value
@@ -64,16 +84,46 @@ module Maptool
changed changed
end end
# A keypad event ("pad.K6", "pad.K6 up") through the bindings that have an output. # By hand (/sim.html, a screen tile): a strobe stops.
def input(event, bindings, at: Time.now.to_f) def manual(output, value)
up = event.end_with?(" up") @mutex.synchronize { @strobes.delete(output) }
channel = event.delete_suffix(" up") set(output, value)
bindings.each do |b| end
next unless b["output"] && b["input"] == channel && find(b["output"]) # a profile's output this car hasn't: skipped
output = b["output"] # The binding's outputs: "outputs" (positions) or "output".
case b.fetch("mode", "toggle") def self.outputs_of(binding) = Array(binding["outputs"] || binding["output"])
when "toggle" then set(output, !on?(output)) unless up
# 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 "on" then set(output, true) unless up
when "off" then set(output, false) unless up when "off" then set(output, false) unless up
when "hold" when "hold"
@@ -84,6 +134,12 @@ module Maptool
set(output, true) set(output, true)
@mutex.synchronize { @pulses[output] = at + b.fetch("pulse_s", 1).to_f } @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 end
end end
@@ -96,26 +152,57 @@ module Maptool
end end
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) 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) } ended.each { |o| set(o, false) }
strobes.each { |o, (since, period)| set(o, ((at - since) / (period / 2)).floor.even?) }
@modules.each { |m| transmit(m) } @modules.each { |m| transmit(m) }
end end
def frame(m) def frame(m)
bits = m.state.each_with_index.sum { |on, i| on ? 1 << i : 0 } data = if m.dimmable
Can::Frame.new(0x200 + m.node, [bits].pack("Q<").byteslice(0, (m.channels + 7) / 8), false) 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 end
def snapshot def snapshot
@mutex.synchronize do @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
end end
private 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) def transmit(m)
return if m.simulated || !@send return if m.simulated || !@send
@@ -128,7 +215,7 @@ end
if $PROGRAM_NAME == __FILE__ if $PROGRAM_NAME == __FILE__
sent = [] 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" }, 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 }] { "input" => "pad.K7", "output" => "relays.3", "mode" => "pulse", "pulse_s" => 2 }]
out.input("pad.K1", b) out.input("pad.K1", b)
@@ -143,6 +230,44 @@ if $PROGRAM_NAME == __FILE__
out.tick(at: 102.1) out.tick(at: 102.1)
raise "pulse" if out.on?("relays.3") raise "pulse" if out.on?("relays.3")
out.input("pad.K1", [{ "input" => "pad.K1", "output" => "winch.1" }]) # no such module: nothing, no error 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" puts "ok"
end end
+4
View File
@@ -206,6 +206,10 @@ class AppTest < Minitest::Test
assert_equal body["bindings"], Maptool::App.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", "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.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"] refute json_body(request.delete("/api/keypad/bindings", **logged_in_env))["saved"]
assert Maptool::App.bindings.size > 1 assert Maptool::App.bindings.size > 1
ensure ensure
+51 -11
View File
@@ -54,7 +54,12 @@
<label><span>Drives</span><select id="drives"></select></label> <label><span>Drives</span><select id="drives"></select></label>
<fieldset id="mode-box"><legend>Mode</legend><div class="modes" id="modes"></div> <fieldset id="mode-box"><legend>Mode</legend><div class="modes" id="modes"></div>
<span class="hint" id="mode-hint"></span></fieldset> <span class="hint" id="mode-hint"></span></fieldset>
<fieldset id="positions-box"><legend>Positions — a press steps off → 1 → 2 → … → off, a knob turns up and down</legend>
<ol id="positions" style="margin: 0; padding-left: 1.5em; display: flex; flex-direction: column; gap: 6px"></ol>
<div class="actions" style="margin-top: 6px"><button type="button" id="add-position">+ Position</button></div></fieldset>
<label id="pulse-box"><span>Pulse, s</span><input id="pulse" type="number" min="0.1" step="0.1" value="1"></label> <label id="pulse-box"><span>Pulse, s</span><input id="pulse" type="number" min="0.1" step="0.1" value="1"></label>
<label id="period-box"><span>Strobe period (on + off), s</span><input id="period" type="number" min="0.2" step="0.1" value="1"></label>
<label id="step-box"><span>Dimmer step per knob click, %</span><input id="step" type="number" min="1" max="100" step="1" value="10"></label>
<label><span>In an open menu</span><select id="menu"></select></label> <label><span>In an open menu</span><select id="menu"></select></label>
<div class="row" id="led-box"> <div class="row" id="led-box">
<label><span>LED</span><select id="led"></select></label> <label><span>LED</span><select id="led"></select></label>
@@ -81,7 +86,10 @@
const KNOB_ACTIONS = ["zoom", "panX", "panY", "rows"]; const KNOB_ACTIONS = ["zoom", "panX", "panY", "rows"];
const MENU = ["rows", "enter", "close"]; 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", 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; let info = null, bindings = [], screenActions = [], selected = null, dirty = false;
const json = async (url, options) => { const json = async (url, options) => {
@@ -92,7 +100,8 @@
}; };
const binding = (input) => bindings.find((b) => b.input === input); const binding = (input) => bindings.find((b) => b.input === input);
const isKnob = (input) => /\.E\d+$/.test(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 || ""; const outputLabel = (o) => info.outputs.find((x) => x.output === o)?.label || "";
function key(input, label, cls = "") { 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"; 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" : ""}`; $("title").textContent = `${selected}${knob ? " · turning" : selected.endsWith(" press") ? " · pressing the knob" : ""}`;
const actions = [...(knob ? KNOB_ACTIONS : []), ...screenActions]; 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 = `<option value="">— nothing —</option>` + $("drives").innerHTML = `<option value="">— nothing —</option>` +
`<optgroup label="Screen">${actions.map((a) => `<option value="action:${esc(a)}"${`action:${a}` === drives ? " selected" : ""}>${esc(a)}</option>`).join("")}</optgroup>` + `<optgroup label="Screen">${actions.map((a) => `<option value="action:${esc(a)}"${`action:${a}` === drives ? " selected" : ""}>${esc(a)}</option>`).join("")}</optgroup>` +
(knob ? "" : `<optgroup label="Output">${info.outputs.map((o) => `<option value="output:${esc(o.output)}"${`output:${o.output}` === drives ? " selected" : ""}>${esc(o.output)}${o.label ? ` · ${esc(o.label)}` : ""}</option>`).join("")}</optgroup>`); `<optgroup label="Output">${outputOptions(drives.slice(7))}</optgroup>`;
const mode = b.mode || "toggle"; const isOut = !!first;
$("mode-box").hidden = !b.output; const mode = b.mode || (knob ? "dimmer" : "toggle");
$("modes").innerHTML = info.modes.map((m) => `<button type="button" data-mode="${m}" aria-pressed="${m === mode}">${m}</button>`).join(""); $("mode-box").hidden = !isOut;
$("modes").innerHTML = info.modes.filter((m) => !knob || KNOB_MODES.includes(m)).map((m) => `<button type="button" data-mode="${m}" aria-pressed="${m === mode}">${m}</button>`).join("");
$("mode-hint").textContent = MODE_HINT[mode] || ""; $("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) => `<li><span class="actions"><select data-position="${i}">${outputOptions(o)}</select>${i ? `<button type="button" data-drop="${i}" aria-label="Remove position ${i + 1}">✕</button>` : ""}</span></li>`).join("");
$("pulse-box").hidden = !isOut || mode !== "pulse";
$("pulse").value = b.pulse_s ?? 1; $("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 —"); $("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; $("led-box").hidden = !pkpKey;
const colors = info.colors.map((c) => [c, c]); const colors = info.colors.map((c) => [c, c]);
$("led").innerHTML = options(colors, b.led, "off"); $("led").innerHTML = options(colors, b.led, "off");
$("led_on").innerHTML = options(colors, b.led_on, b.output ? "red" : "green"); $("led_on").innerHTML = options(colors, b.led_on, b.output ? "red" : "green");
} }
const outputOptions = (value) => info.outputs.map((o) => `<option value="${esc(o.output)}"${o.output === value ? " selected" : ""}>${esc(o.output)}${o.label ? ` · ${esc(o.label)}` : ""}${o.dimmable ? " · dimmable" : ""}</option>`).join("");
function render() { function render() {
renderPads(); renderPads();
renderEditor(); renderEditor();
@@ -150,7 +168,7 @@
if (!b) bindings.push((b = { input: selected })); if (!b) bindings.push((b = { input: selected }));
Object.assign(b, fields); Object.assign(b, fields);
for (const k of Object.keys(b)) if (b[k] === "" || b[k] == null) delete b[k]; 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; dirty = true;
render(); render();
} }
@@ -160,12 +178,34 @@
}); });
$("drives").addEventListener("change", (e) => { $("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)]; 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) => { $("modes").addEventListener("click", (e) => {
const m = e.target.closest("button[data-mode]")?.dataset.mode; 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 })); $("pulse").addEventListener("change", (e) => change({ pulse_s: Number(e.target.value) || 1 }));
$("menu").addEventListener("change", (e) => change({ menu: e.target.value })); $("menu").addEventListener("change", (e) => change({ menu: e.target.value }));
$("led").addEventListener("change", (e) => change({ led: e.target.value })); $("led").addEventListener("change", (e) => change({ led: e.target.value }));
+4 -4
View File
@@ -55,9 +55,9 @@
<dl id="trip"></dl> <dl id="trip"></dl>
</section> </section>
<section id="outputs" hidden> <section id="outputs" hidden>
<h2>Relays</h2> <h2>Outputs</h2>
<div id="relays"></div> <div id="relays"></div>
<p style="color: GrayText; font-size: 0.85rem">can.json's "outputs" (simulated: no frames sent). A click switches one; the keypad's bindings with an "output" do too.</p> <p style="color: GrayText; font-size: 0.85rem">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.</p>
</section> </section>
</div> </div>
@@ -118,9 +118,9 @@
$("outputs").hidden = !data; $("outputs").hidden = !data;
if (!data) return; if (!data) return;
const esc = (s) => String(s).replace(/[&<>"]/g, (ch) => `&#${ch.charCodeAt(0)};`); 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) => `<p>${esc(m.name)} · node ${m.node}${m.simulated ? " · simulated" : ""}</p><div class="actions">` + $("relays").innerHTML = data.modules.map((m) => `<p>${esc(m.name)} · node ${m.node}${m.simulated ? " · simulated" : ""}</p><div class="actions">` +
m.channels.map((c) => `<button type="button" data-output="${esc(m.name)}/${c.n}" class="${c.on ? "on" : ""}" title="${esc(by(`${m.name}.${c.n}`))}">${c.on ? "●" : "○"} ${c.n}${c.label ? ` ${esc(c.label)}` : ""}</button>`).join("") + "</div>").join(""); m.channels.map((c) => `<button type="button" data-output="${esc(m.name)}/${c.n}" class="${c.on ? "on" : ""}" title="${esc(by(`${m.name}.${c.n}`))}">${c.on ? "●" : "○"} ${c.n}${c.label ? ` ${esc(c.label)}` : ""}${c.level != null ? ` ${Math.round(c.level)} %` : ""}${c.strobe ? " · strobe" : ""}</button>`).join("") + "</div>").join("");
} }
$("relays").addEventListener("click", (e) => { $("relays").addEventListener("click", (e) => {
const b = e.target.closest("button[data-output]"); const b = e.target.closest("button[data-output]");