Keypads as channels and bindings, the PDMs' way (lib/maptool/keypad.rb): can.json's keypads (a Blink Marine PKP by its protocol, or any signals as inputs) give channels pad.K1, pad.E3, pad.E3 press; the drive profile's bindings give each a screen action, a knob action (zoom, pan, rows), another in an open menu and its LED colour, sent back to the PKP. Outputs (lib/maptool/outputs.rb): relay modules (simulated, 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; /sim.html switches them by hand. CANopen TIME from maptool while no other node sends it (lib/maptool/can_time.rb), shown in /can.html
CI / check (push) Successful in 23s
CI / deploy (push) Successful in 17s

This commit is contained in:
randy committed 2026-12-04 16:14:39 +01:00
1 parent bf90f4cf23
commit 38fb06853e
14 files changed
+785 -24

No files matched your search

+166 -2
View File
@@ -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).