diff --git a/TODO.adoc b/TODO.adoc index 7734d38..1f307a4 100644 --- a/TODO.adoc +++ b/TODO.adoc @@ -470,7 +470,11 @@ are in home-gitops `docs/canopen-nodes.adoc` ("Inšpirácia: Garmin Tread / zūm trip), mark a place, switch views (navigation / overview / dashboard), mute / volume, the trip's next stop, night mode; a long press for a second action, the keypad's LEDs showing state ** [x] Drive mode keys from the keyboard (profile `key`, labels in the corners, ↑ ↓ / Enter / Space / + / Esc in a menu) -** [ ] The keypad's keys and encoder (as ↑ ↓) from the bus into the same keys; its heartbeat switches the labels to `keypad`, gone 5 s back +** [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] 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 * [ ] 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 diff --git a/app.rb b/app.rb index 4dbcc33..72de240 100644 --- a/app.rb +++ b/app.rb @@ -15,6 +15,9 @@ require_relative "lib/maptool/mqtt_client" require_relative "lib/maptool/can" require_relative "lib/maptool/can_discovery" require_relative "lib/maptool/can_recorder" +require_relative "lib/maptool/keypad" +require_relative "lib/maptool/outputs" +require_relative "lib/maptool/can_time" require_relative "lib/maptool/gnss_sim" require_relative "lib/maptool/trip" require_relative "lib/maptool/trip_log" @@ -476,6 +479,76 @@ module Maptool warn "can: #{CAN_CONFIG_PATH}: action #{action.inspect}: #{e.message} — skipped" nil end + # can.json's "keypads": keys and knobs as channels for the screen + # profile's bindings (Keypad). + KEYPAD = begin + k = CAN_CONFIG&.dig("keypads") + k && !k.empty? ? Keypad.new(k) : nil + rescue StandardError => e + warn "can: #{CAN_CONFIG_PATH}: keypads: #{e.message} — no keypads" + nil + end + CAN_DECODER.set_node(:keypad, KEYPAD.signals) if KEYPAD + + # Frames maptool puts on the bus (LEDs, outputs, TIME): one socket on + # the first interface, opened when first needed, again after an error. + CAN_TX_MUTEX = Mutex.new + def self.can_send(frame) + CAN_TX_MUTEX.synchronize do + @can_tx ||= Can.open(CAN_CONFIG.fetch("interfaces").first) + @can_tx.write(frame.pack) + rescue SocketError, SystemCallError + @can_tx&.close + @can_tx = nil + raise + end + end + + # can.json's "outputs": relay modules driven by the profile's bindings (Outputs). + OUTPUTS = begin + o = CAN_CONFIG&.dig("outputs") + o && !o.empty? ? Outputs.new(o) { |frame| App.can_send(frame) } : nil + rescue StandardError => e + warn "can: #{CAN_CONFIG_PATH}: outputs: #{e.message} — no outputs" + nil + end + + # 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. + DRIVE_PROFILE_PATH = File.join(__dir__, "public", "drive", "road.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 + @bindings.last + rescue StandardError => e + warn "drive profile: #{e.message}" + [] + 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 } : [] + end + + # A keypad's key LEDs: the screen's colours (PUT /api/keypad/leds) with + # the keys bound to outputs on top (their "led" while on, dark off), + # sent when they change. + KEYPAD_SCREEN_LEDS = {} + def self.keypad_leds_frames(device) + 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}.") + + on[b["input"].delete_prefix("#{device.name}.")] = OUTPUTS.on?(b["output"]) ? b.fetch("led", "red") : nil + end + end + KEYPAD.led_frames(device.name, on, KEYPAD_SCREEN_LEDS.dig(device.name, "blink")) + end + # The bus recorded on the server into MF4 files (/trace.html, can-recorder/). CAN_RECORDER = Can::Recorder.new(File.join(DATA_DIR, "can_rec"), CAN_CONFIG ? CAN_CONFIG.fetch("interfaces", []) : []) at_exit { CAN_RECORDER.stop } @@ -492,8 +565,10 @@ module Maptool end CAN_CONFIG.fetch("interfaces", []).each do |interface| Thread.new do - Can.listen(interface, decoder: decoder, store: CAN_STORE, start_nodes: CAN_CONFIG["nmt_start"]) do |values| + Can.listen(interface, decoder: decoder, store: CAN_STORE, start_nodes: CAN_CONFIG["nmt_start"], on_frame: ->(f) { CAN_TIME&.heard(f) }) do |values| App.vehicle_speed_update(values["vehicle.speed"]) if values["vehicle.speed"] + events = KEYPAD&.update(values) || [] + events.each { |e| OUTPUTS.input(e, App.bindings) } if OUTPUTS gnss = values.filter_map { |name, value| [name.delete_prefix("gnss.").to_sym, value] if name.start_with?("gnss.") }.to_h next if gnss.empty? || GNSS_SIM.running? @@ -503,6 +578,41 @@ module Maptool end end + # Every 100 ms: the outputs (pulses ending, their state again for the + # modules' watchdog), a keypad gone silent letting go of what it held, + # the keypads' LEDs when they changed; every second the TIME. + if CAN_CONFIG && !test? && (OUTPUTS || KEYPAD || CAN_TIME) + Thread.new do + was_present = [] + leds_sent = {} + time_at = 0 + loop do + begin + OUTPUTS&.tick + present = App.keypads_present + (was_present.map(&:name) - present.map(&:name)).each { |name| OUTPUTS&.keypad_lost(name) } + leds_sent = {} if present != was_present + was_present = present + present.select { |d| d.protocol == "pkp" }.each do |d| + frames = App.keypad_leds_frames(d) + next if leds_sent[d.name] == frames.map(&:data) + + frames.each { |f| App.can_send(f) } + leds_sent[d.name] = frames.map(&:data) + end + if CAN_TIME && Time.now.to_f - time_at >= Can::TimeProducer::INTERVAL_S + time_at = Time.now.to_f + CAN_TIME.tick + end + rescue StandardError => e + warn "can tick: #{e.message}" unless e.message == @last_tick_error + @last_tick_error = e.message + end + sleep Outputs::REPEAT_S + end + end + end + # Live data off the home MQTT broker (MQTT_URL), polled by the frontend # from /api/live like GNSS above — the "Tracker" and "ITS-G5" overlays: # the LTE GNSS tracker's position and USB power (+ its trail, optionally @@ -1543,7 +1653,61 @@ module Maptool snapshot[:signals] = snapshot[:signals].to_h { |name, signal| [name, units[name] ? signal.merge(unit: units[name]) : signal] } # simulated: the GNSS simulation (/sim.html) stands in for gnss.* actions = CAN_ACTIONS.map { |a| { name: a.name, node: a.node } } - json snapshot.merge(available: !CAN_CONFIG.nil?, simulated: GNSS_SIM.running?, actions: actions) + # time: whether maptool sends CANopen TIME (off while another node does) + time = CAN_TIME && { sending: !CAN_TIME.others? } + json snapshot.merge(available: !CAN_CONFIG.nil?, simulated: GNSS_SIM.running?, actions: actions, time: time) + end + + # The keypads (can.json's "keypads") for drive mode: which are on the bus + # (their heartbeat; with LEDs or not) and the events on their channels + # after seq :since — a long poll, answered as soon as one comes (10 s at + # most). ponytail: holds one of Puma's threads per drive-mode screen, + # fine for the one or two in the car. + get "/api/keypad" do + require_login! + halt 404, json(error: "no keypads in data/can.json") unless KEYPAD + since = params[:since] && Integer(params[:since], exception: false) + present = App.keypads_present + answer = KEYPAD.events(present.empty? ? nil : since) + json answer.merge(present: present.map { |d| { name: d.name, leds: d.protocol == "pkp" } }) + end + + # The screen's colours for a keypad's key LEDs: { "keypad": "pad", "on": + # { "K1": "cyan", … }, "blink": { … } } (Keypad::COLORS); the keys bound + # to outputs come on top, the 100 ms tick sends them (App.keypad_leds_frames). + put "/api/keypad/leds" do + require_login! + halt 404, json(error: "no keypads in data/can.json") unless KEYPAD + body = JSON.parse(request.body.read) + begin + KEYPAD.led_frames(body["keypad"].to_s, body["on"], body["blink"]) # checks the names and colours + rescue ArgumentError => e + halt 400, json(error: e.message) + end + KEYPAD_SCREEN_LEDS[body["keypad"].to_s] = { "on" => body["on"] || {}, "blink" => body["blink"] || {} } + json ok: true + end + + # The outputs (can.json's "outputs"): each module's channels, their + # labels and state, which bindings drive them. + 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"] } + json modules: OUTPUTS.snapshot, bindings: bound + end + + # Switches an output by hand (a tile on the screen, /sim.html): + # { "on": true | false }, or {} to toggle. + post "/api/outputs/:module/:n" do + require_login! + halt 404, json(error: "no outputs in data/can.json") unless OUTPUTS + output = "#{params[:module]}.#{params[:n]}" + 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) + json on: OUTPUTS.on?(output) end # Runs can.json's action number :n (its place in GET /api/can's actions). diff --git a/docs/deployment.adoc b/docs/deployment.adoc index dfd6cd1..8b2c17f 100644 --- a/docs/deployment.adoc +++ b/docs/deployment.adoc @@ -353,6 +353,73 @@ No tilt compensation or hard-iron calibration yet, so only roughly right standing level. The node goes operational by itself, so no `nmt_start`. Sensor16/8: `value = wire * (max - min) / (2^n - 2) + min`, all ones unknown. +Keypads for drive mode (`lib/maptool/keypad.rb`), the way PDMs do it: a +device's keys and knobs become named channels, and the screen profile's +`"bindings"` say what each one does (`public/drive/road.json`) — nothing +in the server knows what a key is for. + +---- +"keypads": [ + { "name": "pad", "protocol": "pkp", "node": 20, "keys": 8, "heartbeat_node": 32, + "inputs": { "E1": "XIAO STM32C5.Encoder 1", "E1 press": "XIAO STM32C5.Encoder Button 1", + "E2": "XIAO STM32C5.Encoder 2", "E3": "XIAO STM32C5.Encoder 3", + "E3 press": "XIAO STM32C5.Encoder Button 3" } } ] +---- + +`name` prefixes its channels (`pad.K1`, `pad.E3`, `pad.E3 press`). +`"protocol": "pkp"` — a Blink Marine PKP CANopen keypad, or ours speaking +its protocol (home-gitops `docs/canopen-nodes.adoc`): K1… come from its +TPDO1 (`0x180+node`, a bit each, `keys` of them) with no signals, and its +key LEDs take colours. Without it a keypad is just `inputs`: channel → any +signal, can.json's own or a discovered node's (as `/can.html` names them); +a channel starting with E is a knob (a free-turning counter mod 256 — set +its bit in the 8Encoder's "Encoder Relative Modes", entity 7, e.g. by an +`actions` SDO write), anything else a key. `heartbeat_node`: whose +heartbeat says it's there (a real PKP has it off; ours is the XIAO's own +node 0x20, the one with the knobs) — default `node`. The PKP waits for +NMT Start: `"nmt_start": true`. + +A binding in the profile: `{ "input": "pad.K5", "action": "menu", "menu": +"close", "led": "cyan", "led_on": "green" }` — `action` a screen key's +(`trip`, `zoomIn`, `follow`, …) or a knob's (`zoom`, `panX`, `panY`, +`rows`), `menu` what it does while a menu is open (`rows`, `enter`, +`close`, or any action), `led` the key LED's colour (red green blue yellow +cyan magenta white), `led_on` while its screen key is on. `GET +/api/keypad?since=` is a long poll of the channels' events, `PUT +/api/keypad/leds` (`{"keypad": "pad", "on": {"K1": "cyan"}, "blink": {}}`) +sets a PKP's key LEDs. + +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: + +---- +"outputs": [ { "name": "relays", "node": 48, "channels": 8, "simulated": true, + "labels": { "1": "Lights", "2": "Winch in" } } ] +---- + +`{ "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 +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 +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 +them by hand. `GET /api/outputs`, `POST /api/outputs//` (`{"on": +true}`, empty toggles). An output in the profile that this car's can.json +hasn't is skipped. + +CANopen TIME (`lib/maptool/can_time.rb`): maptool sends the TIME object +(`0x100`, CiA 301 TIME_OF_DAY, UTC: ms after midnight + days since +1984-01-01) once a second, but only while no other node does — once the +GNSS node sends it (esphome-canopen has no TIME yet), maptool stays quiet +until it's been silent 3 s. Nothing goes out while the Pi's clock is +unset (before 2025). `"time": false` in can.json turns it off; `/can.html` +shows who's sending it. + The node sends no course: `App.gnss_update` (where every fix lands, the node's and the GNSS simulation's) works it out from the fix ≥ 5 m back while moving ≥ 1.5 m/s and keeps the last one standing still, so diff --git a/docs/design.adoc b/docs/design.adoc index d54e71a..6530d73 100644 --- a/docs/design.adoc +++ b/docs/design.adoc @@ -316,9 +316,13 @@ the menus' own buttons carry theirs (1 2 3, H). In an open menu ↑ ↓ move the row (the keypad's encoder sends the same arrows), Enter its first button, Space its eye, + adds it, ⌫ up a folder, Esc closes. Every bound button shows its key in the corner, from the first key -pressed on. Still to do: the keypad's keys from the bus, its heartbeat -switching the labels to the keypad by itself, and the switch (auto / -keyboard / keypad) and the mapping in our diagnostics. +pressed on. Keypads are channels (`pad.K1`, `pad.E3`) and the +profile's `"bindings"` say what each does (below, a binding), so any +keypad fits; a keypad's heartbeat switches the labels to its channels by +itself, a line under each screen key in its LED colour (menus cyan, the +map white, the view amber, green while on). +Still to do: the switch (auto / keyboard / keypad) and the mapping in our +diagnostics. *Terrain* (artboard GridTerrain): the inclinometer only off-road — on the road its cells show the elevation ahead. A 7 × 8 panel like a menu, diff --git a/lib/maptool/can.rb b/lib/maptool/can.rb index e063a16..137c47c 100644 --- a/lib/maptool/can.rb +++ b/lib/maptool/can.rb @@ -228,7 +228,8 @@ module Maptool # every retry): an adapter unplugged, not up yet or the bus gone down # isn't fatal, nor is anything else going wrong in here — the thread # never dies, it waits and starts over. - def self.listen(interface, decoder:, store:, start_nodes: false, retry_delay: 5) + # on_frame: called with every frame (CANopen TIME heard, can_time.rb). + def self.listen(interface, decoder:, store:, start_nodes: false, retry_delay: 5, on_frame: nil) down = false loop do socket = open(interface) @@ -241,6 +242,7 @@ module Maptool frame = Frame.unpack(bytes) next unless frame + on_frame&.call(frame) values = decoder.decode(frame) store.record(interface, frame, values) yield(values) if block_given? && !values.empty? diff --git a/lib/maptool/can_time.rb b/lib/maptool/can_time.rb new file mode 100644 index 0000000..d982098 --- /dev/null +++ b/lib/maptool/can_time.rb @@ -0,0 +1,75 @@ +require_relative "can" + +module Maptool + module Can + # CANopen TIME (CiA 301, COB-ID 0x100): the nodes' clock off the bus. + # maptool sends it only while nobody else does — the GNSS node, once + # esphome-canopen has TIME, gives the real one off the satellites; heard + # from it, maptool stays quiet until it's gone for 3 intervals. + class TimeProducer + ID = 0x100 + EPOCH = Time.utc(1984, 1, 1) + INTERVAL_S = 1 + # ponytail: a clock before this is taken for unset (a Pi without its + # RTC or NTP yet) and nothing is sent; chrony's sync state if that's wrong + MIN_YEAR = 2025 + + # TIME_OF_DAY: ms after midnight (28 bits, u32 LE), days since 1984-01-01 (u16 LE), UTC. + def self.frame(time) + t = time.utc + midnight = Time.utc(t.year, t.month, t.day) + ms = ((t - midnight) * 1000).floor + Frame.new(ID, [ms & 0x0FFFFFFF, ((midnight - EPOCH) / 86_400).round].pack("L from its TPDO1 (0x180+node, a bit each), LEDs by RPDO + # heartbeat_node whose heartbeat says it's there (a real PKP has it off) — default node + # inputs channel → any signal (can.json's or a discovered node's, as /can.html + # names them): a key (0 → 1 is a press), a knob (a free-turning + # counter mod 256, a step per change) when its name starts with E, + # its button " press" + class Keypad + COLORS = { "off" => 0, "red" => 1, "green" => 2, "blue" => 4, "yellow" => 3, "cyan" => 6, "magenta" => 5, "white" => 7 }.freeze + PRESENT_S = 6 # heartbeat seen this recently (5 s interval): there + LOG_SIZE = 200 + + # One device: its channels by signal name, its LEDs if it has them. + Device = Struct.new(:name, :protocol, :node, :keys, :heartbeat_node, :inputs) do + def self.parse(config) + protocol = config["protocol"] + raise ArgumentError, "unknown protocol #{protocol}" unless [nil, "pkp"].include?(protocol) + + node = config["node"] && Integer(config["node"]) + raise ArgumentError, "a pkp keypad needs its node" if protocol == "pkp" && !node + + new(config.fetch("name"), protocol, node, config.fetch("keys", 8), config["heartbeat_node"] ? Integer(config["heartbeat_node"]) : node, + config.fetch("inputs", {})) + end + + # The PKP's keys as decoder signals (Decoder#set_node). + def signals + return [] unless protocol == "pkp" + + (1..keys).map { |k| { "name" => "#{name}.K#{k}", "id" => format("0x%03X", 0x180 + node), "byte" => (k - 1) / 8, "bit" => (k - 1) % 8, "type" => "bit" } } + end + + # signal name → channel + def channels + @channels ||= signals.to_h { |s| [s["name"], s["name"]] }.merge(inputs.to_h { |channel, signal| [signal, "#{name}.#{channel}"] }) + end + end + + attr_reader :devices + + def initialize(configs) + @devices = configs.map { |c| Device.parse(c) } + @by_signal = @devices.flat_map { |d| d.channels.to_a }.to_h + @mutex = Mutex.new + @changed = ConditionVariable.new + @log = [] + @seq = 0 + @last = {} + end + + def signals = @devices.flat_map(&:signals) + + def device(name) = @devices.find { |d| d.name == name } + + # Decoded values → events on channels (returned too): a key or a knob's + # button pressed (0 → 1) and let go ("… up"), a knob turned (a step + # each, "⟳" or "⟲", wrapping at 256). + def update(values) + events = [] + values.each do |signal, value| + next unless (channel = @by_signal[signal]) + + previous = @last[channel] + @last[channel] = value + if channel.split(".").last.match?(/\AE\d+\z/) + next if previous.nil? # a knob's first value: where it is, no turn + + delta = ((value.to_i - previous.to_i + 128) % 256) - 128 + events.concat(["#{channel} #{delta.positive? ? '⟳' : '⟲'}"] * delta.abs) + elsif value.to_i == 1 && previous.to_i != 1 + events << channel + elsif value.to_i != 1 && previous.to_i == 1 + events << "#{channel} up" # let go (the outputs' Hold) + end + end + return events if events.empty? + + @mutex.synchronize do + events.each { |input| @log << { seq: @seq += 1, input: input } } + @log.shift(@log.size - LOG_SIZE) if @log.size > LOG_SIZE + @changed.broadcast + end + events + end + + # The events after seq `since`, waiting up to `wait` s for one (a long + # poll); since nil: none, just the last seq to start from. + def events(since, wait: 10) + @mutex.synchronize do + if since + deadline = Time.now + wait + while @seq <= since && (left = deadline - Time.now).positive? + @changed.wait(@mutex, left) + end + end + { seq: @seq, events: since ? @log.select { |e| e[:seq] > since } : [] } + end + end + + # A PKP's two LED frames (RPDO 0x200+node on, 0x300+node blink: bytes + # R, G, B, a bit per key) from { "K1" => "cyan", … } (nil, absent: off); + # on and blink both set alternate between the two colours. + def led_frames(name, on, blink = {}) + d = device(name) + raise ArgumentError, "no keypad #{name}" unless d + raise ArgumentError, "#{name} has no LEDs" unless d.protocol == "pkp" + + [[0x200, on], [0x300, blink]].map do |base, colors| + masks = [0, 0, 0] + (colors || {}).each do |channel, color| + k = channel[/\AK(\d+)\z/, 1]&.to_i + next unless k&.between?(1, d.keys) + + rgb = COLORS.fetch(color.to_s.empty? ? "off" : color.to_s) { raise ArgumentError, "unknown colour #{color}" } + 3.times { |c| masks[c] |= 1 << (k - 1) if rgb[c] == 1 } + end + bytes = (d.keys + 7) / 8 + Can::Frame.new(base + d.node, masks.flat_map { |m| [m].pack("Q<").bytes.first(bytes) }.pack("C*"), false) + end + end + end +end + +if $PROGRAM_NAME == __FILE__ + pads = Maptool::Keypad.new([{ "name" => "pad", "protocol" => "pkp", "node" => 0x14, "inputs" => { "E3" => "x.Encoder 3", "E3 press" => "x.Button 3" } }]) + pads.update("pad.K1" => 1) + pads.update("pad.K1" => 1) # held: no second press + pads.update("x.Encoder 3" => 250) + pads.update("x.Encoder 3" => 2) # +8 across the wrap + pads.update("x.Button 3" => 1) + pads.update("pad.K1" => 0) + inputs = pads.events(0)[:events].map { |e| e[:input] } + raise inputs.inspect unless inputs == ["pad.K1"] + ["pad.E3 ⟳"] * 8 + ["pad.E3 press", "pad.K1 up"] + on, blink = pads.led_frames("pad", { "K1" => "cyan", "K2" => "white", "K3" => "yellow" }, { "K2" => "red" }) + raise on.data.unpack("C*").inspect unless on.id == 0x214 && on.data.unpack("C*") == [0b110, 0b111, 0b011] + raise blink.data.unpack("C*").inspect unless blink.id == 0x314 && blink.data.unpack("C*") == [0b10, 0, 0] + puts "ok" +end diff --git a/lib/maptool/outputs.rb b/lib/maptool/outputs.rb new file mode 100644 index 0000000..31b63db --- /dev/null +++ b/lib/maptool/outputs.rb @@ -0,0 +1,148 @@ +require "json" +require_relative "can" + +module Maptool + # Outputs on the bus — relay modules for now, no current measured — and + # 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": + # { "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). + # + # can.json: "outputs": [ { "name": "relays", "node": 48, "channels": 8, "simulated": true, + # "labels": { "1": "Lights", "2": "Winch in" } } ] + # 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). + class Outputs + REPEAT_S = 0.1 + MODES = %w[toggle on off hold pulse].freeze + + Module = Struct.new(:name, :node, :channels, :simulated, :labels, :state, 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)) + end + @send = send + @mutex = Mutex.new + @pulses = {} + @held = {} # channel (the key) → outputs it holds on + end + + def find(output) + name, ch = output.to_s.split(".", 2) + m = @modules.find { |x| x.name == name } + i = Integer(ch, exception: false) + [m, i - 1] if m && i&.between?(1, m.channels) + end + + def on?(output) + m, i = find(output) + m ? @mutex.synchronize { m.state[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 + + m.state[i] = value + @pulses.delete(output) unless value + true + end + transmit(m) if changed + 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 + + output = b["output"] + case b.fetch("mode", "toggle") + when "toggle" then set(output, !on?(output)) unless up + when "on" then set(output, true) unless up + when "off" then set(output, false) unless up + when "hold" + set(output, !up) + up ? @held.delete(channel) : (@held[channel] ||= []) << output + when "pulse" + next if up + + set(output, true) + @mutex.synchronize { @pulses[output] = at + b.fetch("pulse_s", 1).to_f } + end + end + end + + # A keypad gone silent: what it held goes off (the fail-safe). + def keypad_lost(device) + @held.select { |channel, _| channel.start_with?("#{device}.") }.each do |channel, outputs| + outputs.each { |o| set(o, false) } + @held.delete(channel) + end + end + + # Every REPEAT_S: pulses ending, 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.each { |o| set(o, false) } + @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) + 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] } } } } + end + end + + private + + def transmit(m) + return if m.simulated || !@send + + @send.call(frame(m)) + rescue StandardError => e + warn "outputs: #{m.name}: #{e.message}" + end + end +end + +if $PROGRAM_NAME == __FILE__ + sent = [] + out = Maptool::Outputs.new([{ "name" => "relays", "node" => 48 }]) { |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) + raise "toggle" unless out.on?("relays.1") + out.input("pad.K6", b) + raise "hold" unless out.on?("relays.2") + out.keypad_lost("pad") + raise "fail-safe" if out.on?("relays.2") + out.input("pad.K7", b, at: 100) + out.tick(at: 101) + raise "pulse early" unless out.on?("relays.3") + 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 + puts "ok" +end diff --git a/public/css/style.css b/public/css/style.css index c821e06..1ce468d 100644 --- a/public/css/style.css +++ b/public/css/style.css @@ -4947,6 +4947,15 @@ html.driving #app, border-radius: var(--drive-radius); } html.driving .app-body { border-radius: calc(var(--drive-radius) + 2px); overflow: hidden; } + +/* The CAN keypad on the bus (html.drive-keypad, driving.js): the corner + labels its keys (none = touch only), a line under the key in its LED colour */ +html.driving.drive-keypad [data-key]::after { content: attr(data-keypad); } +html.driving.drive-keypad [data-key]:not([data-keypad])::after { display: none; } +html.driving.drive-keypad [data-led] { box-shadow: inset 0 calc(-4px * var(--s, 1)) 0 var(--led); } +[data-led="cyan"] { --led: #22c3d6; } +[data-led="white"] { --led: #e8e6df; } +[data-led="yellow"] { --led: #f0a020; } .drive-rec__cutrow { flex: none; height: calc(var(--cell, 80px) / 2); display: flex; align-items: center; gap: 10px; padding-left: 28px; background: var(--band); color: var(--drive-muted); font-size: calc(14px * var(--s, 1)); } .drive-rec__cutrow span:nth-child(2) { flex: 1; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } .drive-panel .drive-rec__cutrow button { height: 100%; padding: 0 16px; background: none; border-left: 1px solid var(--drive-line); font-size: calc(14px * var(--s, 1)); font-weight: 700; } diff --git a/public/drive/road.json b/public/drive/road.json index 23e7688..16f283a 100644 --- a/public/drive/road.json +++ b/public/drive/road.json @@ -21,16 +21,32 @@ { "area": "5 / 14 / 6 / 17", "widget": "field", "value": "toEnd" }, { "area": "6 / 14 / 9 / 17", "widget": "elevation", "km": 10 }, { "area": "9 / 14 / 10 / 17", "widget": "compass" }, - { "area": "10 / 1 / 11 / 3", "widget": "key", "action": "trip", "key": "F1", "keypad": "K1" }, - { "area": "10 / 3 / 11 / 5", "widget": "key", "action": "points", "key": "F2", "keypad": "K2" }, - { "area": "10 / 5 / 11 / 7", "widget": "key", "action": "layers", "key": "F3", "keypad": "K3" }, - { "area": "10 / 7 / 11 / 9", "widget": "key", "action": "search", "key": "/", "keypad": "K4" }, - { "area": "10 / 9 / 11 / 11", "widget": "key", "action": "menu", "key": "F5", "keypad": "K5" }, - { "area": "10 / 11 / 11 / 12", "widget": "key", "action": "zoomOut", "key": "-", "keypad": "E3 ⟲" }, - { "area": "10 / 12 / 11 / 13", "widget": "key", "action": "zoomIn", "key": "+", "keypad": "E3 ⟳" }, - { "area": "10 / 13 / 11 / 14", "widget": "key", "action": "pitch", "key": "3", "keypad": "K6" }, - { "area": "10 / 14 / 11 / 15", "widget": "key", "action": "follow", "key": "f", "keypad": "E3 ⏎" }, - { "area": "10 / 15 / 11 / 16", "widget": "key", "action": "terrain", "key": "t", "keypad": "K7" }, - { "area": "10 / 16 / 11 / 17", "widget": "key", "action": "palette", "key": "n", "keypad": "K8" } + { "area": "10 / 1 / 11 / 3", "widget": "key", "action": "trip", "key": "F1" }, + { "area": "10 / 3 / 11 / 5", "widget": "key", "action": "points", "key": "F2" }, + { "area": "10 / 5 / 11 / 7", "widget": "key", "action": "layers", "key": "F3" }, + { "area": "10 / 7 / 11 / 9", "widget": "key", "action": "search", "key": "/" }, + { "area": "10 / 9 / 11 / 11", "widget": "key", "action": "menu", "key": "F5" }, + { "area": "10 / 11 / 11 / 12", "widget": "key", "action": "zoomOut", "key": "-" }, + { "area": "10 / 12 / 11 / 13", "widget": "key", "action": "zoomIn", "key": "+" }, + { "area": "10 / 13 / 11 / 14", "widget": "key", "action": "pitch", "key": "3" }, + { "area": "10 / 14 / 11 / 15", "widget": "key", "action": "follow", "key": "f" }, + { "area": "10 / 15 / 11 / 16", "widget": "key", "action": "terrain", "key": "t" }, + { "area": "10 / 16 / 11 / 17", "widget": "key", "action": "palette", "key": "n" } + ], + "bindings": [ + { "input": "pad.K1", "action": "trip", "led": "cyan" }, + { "input": "pad.K2", "action": "points", "led": "cyan" }, + { "input": "pad.K3", "action": "layers", "led": "cyan" }, + { "input": "pad.K4", "action": "search", "led": "cyan" }, + { "input": "pad.K5", "action": "menu", "menu": "close", "led": "cyan" }, + { "input": "pad.K6", "action": "pitch", "led": "white" }, + { "input": "pad.K7", "action": "terrain", "led": "yellow" }, + { "input": "pad.K8", "action": "palette", "led": "yellow" }, + { "input": "pad.E1", "action": "panX", "menu": "rows" }, + { "input": "pad.E1 press", "menu": "enter" }, + { "input": "pad.E2", "action": "panY" }, + { "input": "pad.E2 press", "output": "relays.1" }, + { "input": "pad.E3", "action": "zoom" }, + { "input": "pad.E3 press", "action": "follow" } ] } diff --git a/public/js/driving.js b/public/js/driving.js index ce6f160..ab01d81 100644 --- a/public/js/driving.js +++ b/public/js/driving.js @@ -41,6 +41,9 @@ const KEYS = { palette: ["", "", "Day, dusk, night"], }; const NOT_YET = new Set(); +// A knob's function → the screen keys it stands for (their labels: ⟳ ⟲) +const KNOB_KEYS = { zoom: ["zoomIn", "zoomOut"] }; +const KEYPAD_ABSENT_MS = 5000; // no keypad on the bus: asked again after this // The Terrain view switches itself on off-road (docs/design.adoc, Screen // profiles): an unpaved surface (/api/road, off a route) or roll / pitch past // TILT_DEG for TILT_S; back to the road view after PAVED_BACK_M on paved road. @@ -421,7 +424,7 @@ export function setupDriving(map, nightButton, routePanel, gpxPanel) { el.disabled = NOT_YET.has(cell.action) || !keyAction[cell.action]; el.addEventListener("click", () => keyAction[cell.action]?.()); if (cell.action === "zoomIn" || cell.action === "zoomOut") el.classList.add("drive-key--big"); - if (cell.key) bindKey(el, cell.key); // "keypad" too, for when the keypad is on the bus + if (cell.key) bindKey(el, cell.key); } else { el = document.createElement("div"); } @@ -596,6 +599,7 @@ export function setupDriving(map, nightButton, routePanel, gpxPanel) { else if (cell.widget === "compass") renderCompass(el); else if (cell.widget === "key") renderKey(el, cell); } + sendLeds(); } map.on("pitchend", render); setInterval(render, RENDER_MS); @@ -627,6 +631,7 @@ export function setupDriving(map, nightButton, routePanel, gpxPanel) { app.append(el); cells.push({ cell, el }); } + labelKeys(); // a keypad heard before the profile came render(); map.resize(); }); @@ -651,8 +656,7 @@ export function setupDriving(map, nightButton, routePanel, gpxPanel) { // (the keypad's encoder will send the same arrows), Enter its first button, // Space its eye, + adds it, ⌫ up a folder, Esc closes. The labels in the // corners show from the first key pressed on, so a touch-only screen stays clean. - // ponytail: keyboard only; the keypad's keys and its heartbeat switching the - // labels to "keypad" wait for the keypad on the bus (and the diagnostics' mapping) + // (The keypads' channels: the profile's bindings, further down.) const KEYS_SEEN = "maptool.driveKeys"; let row = 0; try { if (localStorage.getItem(KEYS_SEEN)) document.documentElement.classList.add("drive-keys"); } catch { /* nothing kept */ } @@ -704,6 +708,101 @@ export function setupDriving(map, nightButton, routePanel, gpxPanel) { if (!done) done = press(bound(openPanel) || bound(app)); if (done) e.preventDefault(); // F1, F5, / are the browser's otherwise }); + + // Keypads (can.json's "keypads", GET /api/keypad, a long poll) and the + // profile's "bindings" (docs/design.adoc, Switches and the keypad): a + // channel ("pad.K1", "pad.E3" — a key, a knob, its "press") → an action, + // another one while a menu is open ("menu"). A screen key's action clicks + // it; knobs turn: zoom, panX / panY, rows (the menu's ↑ ↓); enter, close. + // A keypad's heartbeat on the bus labels the screen keys with its + // channels (none = touch only) and the line under them in the binding's + // LED colour; its key LEDs follow them, "led_on" (green) while on. + // ponytail: screen functions only — outputs (relays), the modes (hold, + // pulse, positions…) and the mapping UI (the canvas' GridBinding) to come. + const bindings = () => profile?.bindings || []; + let present = []; + let ledsSent = {}; + const keyEl = (action) => cells.find((c) => c.cell.widget === "key" && c.cell.action === action)?.el; + const shortName = (input) => input.slice(input.indexOf(".") + 1).replace(/ press$/, " ⏎"); + function labelKeys() { + for (const { cell, el } of cells) { + if (cell.widget !== "key") continue; + delete el.dataset.keypad; + delete el.dataset.led; + } + for (const b of bindings()) { + if (!present.some((d) => b.input.startsWith(`${d.name}.`)) || !b.action) continue; + const knob = KNOB_KEYS[b.action]; + for (const [i, action] of (knob || [b.action]).entries()) { + const el = keyEl(action); + if (!el) continue; + el.dataset.keypad = shortName(b.input) + (knob ? (i ? " ⟲" : " ⟳") : ""); + if (b.led) el.dataset.led = b.led; + } + } + } + function sendLeds() { + for (const d of present.filter((p) => p.leds)) { + const on = {}; + for (const b of bindings()) { + const k = b.input.startsWith(`${d.name}.`) && /^K\d+$/.exec(b.input.slice(d.name.length + 1))?.[0]; + const el = k && b.led && keyEl(b.action); + if (el) on[k] = el.disabled ? null : el.getAttribute("aria-pressed") === "true" ? b.led_on || "green" : b.led; + } + const body = JSON.stringify({ keypad: d.name, on }); + if (body === ledsSent[d.name]) continue; + ledsSent[d.name] = body; + fetch("/api/keypad/leds", { method: "PUT", headers: { "Content-Type": "application/json" }, body }).catch(() => { ledsSent[d.name] = ""; }); + } + } + const navKey = (key) => document.dispatchEvent(new KeyboardEvent("keydown", { key })); + const PAN_PX = 80; + const knobAction = { + zoom: (dir) => keyEl(dir > 0 ? "zoomIn" : "zoomOut")?.click(), + panX: (dir) => map.panBy([dir * PAN_PX, 0], { duration: 100 }), + panY: (dir) => map.panBy([0, dir * PAN_PX], { duration: 100 }), + rows: (dir) => navKey(dir > 0 ? "ArrowDown" : "ArrowUp"), + enter: () => navKey("Enter"), + close: () => navKey("Escape"), + }; + const onInput = (event) => { + if (!document.documentElement.classList.contains("driving")) return; + const [, channel, turn] = /^(.*?)(?: (⟳|⟲))?$/.exec(event); + const b = bindings().find((x) => x.input === channel); + const action = (openPanel && b?.menu) || b?.action; + if (!action) return; + if (knobAction[action]) return knobAction[action](turn === "⟲" ? -1 : 1); + const el = keyEl(action); + if (el && visible(el)) el.click(); + }; + (async function keypadLoop() { + let since = null; + for (;;) { + let answer = null; + try { + const response = await fetch(`/api/keypad${since == null ? "" : `?since=${since}`}`, { cache: "no-store" }); + if (response.status === 404) return; // no keypads configured on this server + if (response.ok) answer = await response.json(); + } catch { /* the server restarting, offline for a moment */ } + const now = answer?.present || []; + if (JSON.stringify(now) !== JSON.stringify(present)) { + present = now; + document.documentElement.classList.toggle("drive-keypad", present.length > 0); + if (present.length) document.documentElement.classList.add("drive-keys"); + ledsSent = {}; + labelKeys(); + sendLeds(); + } + if (!present.length) { + since = null; + await new Promise((r) => setTimeout(r, KEYPAD_ABSENT_MS)); + continue; + } + if (since != null) for (const e of answer.events) onInput(e.input); + since = answer.seq; + } + })(); + let saved = null; try { saved = localStorage.getItem(KEY); } catch { /* nothing kept */ } set(saved === "on"); diff --git a/test/test_app.rb b/test/test_app.rb index 5285fc8..ea1e25d 100644 --- a/test/test_app.rb +++ b/test/test_app.rb @@ -191,7 +191,7 @@ class AppTest < Minitest::Test def test_can_requires_login_and_is_off_without_a_config assert_equal 401, request.get("/api/can").status assert_equal 409, request.post("/api/can/actions/0", **logged_in_env).status - assert_equal({ "interfaces" => {}, "nodes" => {}, "signals" => {}, "frames" => [], "available" => false, "simulated" => false, "actions" => [] }, json_body(request.get("/api/can", **logged_in_env))) + assert_equal({ "interfaces" => {}, "nodes" => {}, "signals" => {}, "frames" => [], "available" => false, "simulated" => false, "actions" => [], "time" => nil }, json_body(request.get("/api/can", **logged_in_env))) end # MQTT messages land in the tracker / ITS-G5 parts of /api/live. diff --git a/views/can.erb b/views/can.erb index b3e78b2..d1f19f5 100644 --- a/views/can.erb +++ b/views/can.erb @@ -154,7 +154,7 @@ const silent = Object.keys(last.nodes).filter((id) => last.nodes[id].silent); const shown = notice && notice.until > Date.now() ? notice : null; status.className = silent.length || shown?.bad ? "bad" : ""; - status.textContent = (shown ? `${shown.text} · ` : "") + (silent.length ? `⚠ node ${silent.join(", ")} silent · ` : "") + `updated ${new Date().toLocaleTimeString()}`; + status.textContent = (shown ? `${shown.text} · ` : "") + (silent.length ? `⚠ node ${silent.join(", ")} silent · ` : "") + (last.time ? `TIME: ${last.time.sending ? "maptool sends it" : "another node sends it"} · ` : "") + `updated ${new Date().toLocaleTimeString()}`; } catch (e) { status.textContent = `can't reach the server: ${e.message}`; } finally { diff --git a/views/sim.erb b/views/sim.erb index dd7bfbc..e00fd56 100644 --- a/views/sim.erb +++ b/views/sim.erb @@ -54,6 +54,11 @@

Trip

+