Keypad bindings in the UI (/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, what it drives (a screen action or an output), the output's mode, what it does in an open menu, its LEDs; saved per car in data/drive/bindings.json over the profile's (GET/PUT/DELETE /api/keypad/bindings, checked on the way in), drive mode takes them when it loads
This commit is contained in:
1 parent
d6af65f4ef
commit
e82b2236b5
7 files changed
+325
-8
No files matched your search
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
.debug-nav .map { margin-left: auto; }
|
||||
</style>
|
||||
<nav class="debug-nav">
|
||||
<% [["/status.html", "Server status"], ["/can.html", "CAN analyzer"], ["/trace.html", "CAN trace"], ["/sim.html", "GNSS simulation"]].each do |href, label| %>
|
||||
<% [["/status.html", "Server status"], ["/can.html", "CAN analyzer"], ["/trace.html", "CAN trace"], ["/keypad.html", "Keypad"], ["/sim.html", "GNSS simulation"]].each do |href, label| %>
|
||||
<a href="<%= href %>"<%= ' aria-current="page"' if request.path == href %>><%= label %></a>
|
||||
<% end %>
|
||||
<a class="map" href="/" target="maptool">The map ↗</a>
|
||||
|
||||
@@ -0,0 +1,228 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<meta name="color-scheme" content="light dark">
|
||||
<title>Keypad bindings</title>
|
||||
<link rel="icon" href="/icons/icon.svg" type="image/svg+xml">
|
||||
<style>
|
||||
:root { color-scheme: light dark; --muted: GrayText; --line: color-mix(in srgb, CanvasText 15%, transparent); --ok: #2e7d32; --bad: #c62828; --sel: #546619; }
|
||||
body { margin: 0; padding: 16px; background: Canvas; color: CanvasText; font: 15px/1.4 -apple-system, "Segoe UI", Roboto, Helvetica, Arial, sans-serif; }
|
||||
header { display: flex; flex-wrap: wrap; gap: 8px 16px; align-items: baseline; margin-bottom: 16px; }
|
||||
h1 { font-size: 1.2rem; margin: 0; }
|
||||
h2 { font-size: 0.8rem; font-weight: 600; color: var(--muted); text-transform: uppercase; letter-spacing: 0.05em; margin: 0 0 8px; }
|
||||
main { display: grid; gap: 16px; grid-template-columns: repeat(auto-fit, minmax(min(420px, 100%), 1fr)); align-items: start; }
|
||||
section { border: 1px solid var(--line); border-radius: 8px; padding: 12px 16px; }
|
||||
.pad { display: inline-grid; gap: 10px; padding: 18px; border-radius: 20px; background: #111; margin-bottom: 12px; }
|
||||
.pad button { width: 76px; height: 76px; border-radius: 14px; border: 4px solid var(--led, #333); background: #1c1c1c; color: #e8e6df; font: inherit; font-size: 12px; font-weight: 700;
|
||||
display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 2px; box-shadow: 0 0 12px color-mix(in srgb, var(--led, #000) 35%, transparent); overflow: hidden; }
|
||||
.pad button small { font-weight: 400; font-size: 10px; color: #9b988d; max-width: 68px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.pad .knob { border-radius: 50%; }
|
||||
.pad .press { width: 76px; height: 30px; border-radius: 8px; border-width: 2px; font-size: 10px; flex-direction: row; }
|
||||
.pad button[aria-pressed="true"] { outline: 3px solid #fff; outline-offset: 4px; }
|
||||
.pad button.hit { background: #3a3a35; }
|
||||
.knobs { display: flex; gap: 10px; }
|
||||
.knobs > div { display: flex; flex-direction: column; gap: 6px; }
|
||||
label, fieldset { display: flex; flex-direction: column; gap: 4px; margin: 0 0 12px; padding: 0; border: none; }
|
||||
label > span, legend { font-size: 0.75rem; color: var(--muted); text-transform: uppercase; letter-spacing: 0.05em; }
|
||||
select, input, button { font-size: 1rem; padding: 8px 12px; border-radius: 8px; }
|
||||
.modes { display: flex; flex-wrap: wrap; gap: 6px; }
|
||||
.modes button[aria-pressed="true"] { background: var(--sel); color: #fff; border-color: var(--sel); }
|
||||
.row { display: grid; grid-template-columns: 1fr 1fr; gap: 0 16px; }
|
||||
.actions { display: flex; flex-wrap: wrap; gap: 8px; }
|
||||
.primary { background: var(--sel); color: #fff; border: 1px solid var(--sel); font-weight: 600; }
|
||||
.hint { color: var(--muted); font-size: 0.85rem; }
|
||||
.bad { color: var(--bad); } .on { color: var(--ok); }
|
||||
a { color: inherit; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<%= erb :_debug_nav, layout: false %>
|
||||
<header>
|
||||
<h1>Keypad bindings</h1>
|
||||
<span id="state">loading…</span>
|
||||
</header>
|
||||
<main>
|
||||
<section>
|
||||
<h2>Keypads</h2>
|
||||
<div id="pads"></div>
|
||||
<p class="hint">Tap a key or knob, or press it on the keypad. The ring is the key LED's colour.</p>
|
||||
</section>
|
||||
<section id="editor" hidden>
|
||||
<h2 id="title"></h2>
|
||||
<label><span>Drives</span><select id="drives"></select></label>
|
||||
<fieldset id="mode-box"><legend>Mode</legend><div class="modes" id="modes"></div>
|
||||
<span class="hint" id="mode-hint"></span></fieldset>
|
||||
<label id="pulse-box"><span>Pulse, s</span><input id="pulse" type="number" min="0.1" step="0.1" value="1"></label>
|
||||
<label><span>In an open menu</span><select id="menu"></select></label>
|
||||
<div class="row" id="led-box">
|
||||
<label><span>LED</span><select id="led"></select></label>
|
||||
<label><span>LED while on</span><select id="led_on"></select></label>
|
||||
</div>
|
||||
<div class="actions">
|
||||
<button type="button" id="remove">Remove</button>
|
||||
</div>
|
||||
</section>
|
||||
</main>
|
||||
<p class="actions" style="margin-top: 16px">
|
||||
<button type="button" class="primary" id="save" disabled>Save</button>
|
||||
<button type="button" id="reset">Back to the profile's</button>
|
||||
<span class="hint" id="source"></span>
|
||||
</p>
|
||||
|
||||
<script>
|
||||
// The keypads' bindings (GET/PUT/DELETE /api/keypad/bindings): a key or knob
|
||||
// picked, what it drives — a screen key's action or an output — how, and its LEDs.
|
||||
// Edits stay here until Save; drive mode takes them when it next loads.
|
||||
const $ = (id) => document.getElementById(id);
|
||||
const esc = (s) => String(s ?? "").replace(/[&<>"]/g, (ch) => `&#${ch.charCodeAt(0)};`);
|
||||
const LED = { red: "#e8453a", green: "#34b545", blue: "#3b82f6", yellow: "#f0a020", cyan: "#22c3d6", magenta: "#b45bd0", white: "#e8e6df" };
|
||||
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" };
|
||||
let info = null, bindings = [], screenActions = [], selected = null, dirty = false;
|
||||
|
||||
const json = async (url, options) => {
|
||||
const response = await fetch(url, { cache: "no-store", ...options });
|
||||
const body = await response.json().catch(() => ({}));
|
||||
if (!response.ok) throw new Error(body.error || `HTTP ${response.status}`);
|
||||
return body;
|
||||
};
|
||||
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 outputLabel = (o) => info.outputs.find((x) => x.output === o)?.label || "";
|
||||
|
||||
function key(input, label, cls = "") {
|
||||
const b = binding(input);
|
||||
const led = b?.led ? `--led: ${LED[b.led]}` : "";
|
||||
return `<button type="button" class="${cls}" data-input="${esc(input)}" style="${led}" aria-pressed="${input === selected}">${esc(label)}<small>${esc(what(b) || "—")}</small></button>`;
|
||||
}
|
||||
function renderPads() {
|
||||
$("pads").innerHTML = info.keypads.map((d) => {
|
||||
const ch = d.channels;
|
||||
const keys = ch.filter((c) => !/^E\d+( press)?$/.test(c));
|
||||
const knobs = ch.filter((c) => /^E\d+$/.test(c));
|
||||
const cols = keys.length > 6 ? Math.ceil(keys.length / 2) : Math.max(keys.length, 1);
|
||||
return `<h2>${esc(d.name)}${d.protocol ? ` · ${esc(d.protocol.toUpperCase())} node 0x${d.node.toString(16).padStart(2, "0")}` : ""}</h2>` +
|
||||
(keys.length ? `<div class="pad" style="grid-template-columns: repeat(${cols}, 76px)">${keys.map((c) => key(`${d.name}.${c}`, c)).join("")}</div>` : "") +
|
||||
(knobs.length ? `<div class="pad knobs">${knobs.map((c) => `<div>${key(`${d.name}.${c}`, c, "knob")}${ch.includes(`${c} press`) ? key(`${d.name}.${c} press`, "⏎", "press") : ""}</div>`).join("")}</div>` : "");
|
||||
}).join("") || '<p class="hint">No keypads in data/can.json ("keypads").</p>';
|
||||
}
|
||||
const options = (list, value, none = "— nothing —") => `<option value="">${none}</option>` + list.map(([v, l]) => `<option value="${esc(v)}"${v === value ? " selected" : ""}>${esc(l)}</option>`).join("");
|
||||
|
||||
function renderEditor() {
|
||||
$("editor").hidden = !selected;
|
||||
if (!selected) return;
|
||||
const b = binding(selected) || {};
|
||||
const knob = isKnob(selected);
|
||||
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}` : "";
|
||||
$("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>` +
|
||||
(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>`);
|
||||
const mode = b.mode || "toggle";
|
||||
$("mode-box").hidden = !b.output;
|
||||
$("modes").innerHTML = info.modes.map((m) => `<button type="button" data-mode="${m}" aria-pressed="${m === mode}">${m}</button>`).join("");
|
||||
$("mode-hint").textContent = MODE_HINT[mode] || "";
|
||||
$("pulse-box").hidden = !b.output || mode !== "pulse";
|
||||
$("pulse").value = b.pulse_s ?? 1;
|
||||
$("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");
|
||||
}
|
||||
function render() {
|
||||
renderPads();
|
||||
renderEditor();
|
||||
$("save").disabled = !dirty;
|
||||
$("source").textContent = dirty ? "unsaved changes" : info.saved ? "this car's own (data/drive/bindings.json)" : "the profile's (public/drive/road.json)";
|
||||
}
|
||||
|
||||
// a field changed: into the selected input's binding (made, or dropped when empty)
|
||||
function change(fields) {
|
||||
let b = binding(selected);
|
||||
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);
|
||||
dirty = true;
|
||||
render();
|
||||
}
|
||||
$("pads").addEventListener("click", (e) => {
|
||||
const el = e.target.closest("button[data-input]");
|
||||
if (el) { selected = el.dataset.input; render(); }
|
||||
});
|
||||
$("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 });
|
||||
});
|
||||
$("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 });
|
||||
});
|
||||
$("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 }));
|
||||
$("led_on").addEventListener("change", (e) => change({ led_on: e.target.value }));
|
||||
$("remove").addEventListener("click", () => { bindings = bindings.filter((b) => b.input !== selected); dirty = true; render(); });
|
||||
$("save").addEventListener("click", async () => {
|
||||
try {
|
||||
Object.assign(info, await json("/api/keypad/bindings", { method: "PUT", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ bindings }) }));
|
||||
bindings = structuredClone(info.bindings);
|
||||
dirty = false;
|
||||
$("state").innerHTML = '<span class="on">saved</span> — drive mode takes them when it next loads';
|
||||
render();
|
||||
} catch (e) { $("state").innerHTML = `<span class="bad">${esc(e.message)}</span>`; }
|
||||
});
|
||||
$("reset").addEventListener("click", async () => {
|
||||
if (!confirm("Drop this car's bindings and go back to the profile's?")) return;
|
||||
Object.assign(info, await json("/api/keypad/bindings", { method: "DELETE" }));
|
||||
bindings = structuredClone(info.bindings);
|
||||
dirty = false;
|
||||
render();
|
||||
});
|
||||
window.addEventListener("beforeunload", (e) => { if (dirty) e.preventDefault(); });
|
||||
|
||||
// a key pressed on the keypad picks it (GET /api/keypad, a long poll)
|
||||
async function listen() {
|
||||
let since = null;
|
||||
for (;;) {
|
||||
try {
|
||||
const response = await fetch(`/api/keypad${since == null ? "" : `?since=${since}`}`, { cache: "no-store" });
|
||||
if (response.status === 404) return;
|
||||
const answer = await response.json();
|
||||
if (since != null) for (const e of answer.events) {
|
||||
if (e.input.endsWith(" up")) continue;
|
||||
selected = e.input.replace(/ [⟳⟲]$/, "");
|
||||
render();
|
||||
document.querySelector(`[data-input="${CSS.escape(selected)}"]`)?.classList.add("hit");
|
||||
setTimeout(() => document.querySelector(".hit")?.classList.remove("hit"), 300);
|
||||
}
|
||||
$("state").innerHTML = answer.present.length ? `<span class="on">● ${answer.present.map((p) => esc(p.name)).join(", ")} on the bus</span>` : "no keypad on the bus";
|
||||
since = answer.seq;
|
||||
} catch { await new Promise((r) => setTimeout(r, 3000)); }
|
||||
}
|
||||
}
|
||||
|
||||
(async () => {
|
||||
try {
|
||||
const [i, profile] = await Promise.all([json("/api/keypad/bindings"), json("/drive/road.json")]);
|
||||
info = i;
|
||||
bindings = structuredClone(info.bindings);
|
||||
screenActions = profile.cells.filter((c) => c.widget === "key").map((c) => c.action);
|
||||
selected = info.keypads[0] ? `${info.keypads[0].name}.${info.keypads[0].channels[0]}` : null;
|
||||
render();
|
||||
listen();
|
||||
} catch (e) {
|
||||
$("state").innerHTML = `<span class="bad">${esc(e.message)}</span>${/401/.test(e.message) ? ' — <a href="/login">log in</a>' : ""}`;
|
||||
}
|
||||
})();
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
Reference in new issue
Block a user