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
This commit is contained in:
1 parent
bf90f4cf23
commit
38fb06853e
14 files changed
+785
-24
No files matched your search
+3
-1
@@ -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?
|
||||
|
||||
@@ -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<S<"), false)
|
||||
end
|
||||
|
||||
def self.parse(data)
|
||||
ms, days = data.unpack("L<S<")
|
||||
EPOCH + days * 86_400 + (ms & 0x0FFFFFFF) / 1000.0
|
||||
end
|
||||
|
||||
def initialize(&send)
|
||||
@send = send
|
||||
@sent = []
|
||||
@others_at = nil
|
||||
end
|
||||
|
||||
# A TIME frame read off the bus: ours (just sent, the reader's socket
|
||||
# gets it too) or someone else's.
|
||||
def heard(frame, at: Time.now.to_f)
|
||||
return unless frame.id == ID && !frame.extended
|
||||
|
||||
@others_at = at unless @sent.include?(frame.data)
|
||||
end
|
||||
|
||||
def others? (at = Time.now.to_f) = !!@others_at && at - @others_at < 3 * INTERVAL_S
|
||||
|
||||
# Every INTERVAL_S: sends the time unless another producer is on or the clock isn't set.
|
||||
def tick(now = Time.now)
|
||||
return :others if others?(now.to_f)
|
||||
return :unset if now.year < MIN_YEAR
|
||||
|
||||
f = self.class.frame(now)
|
||||
@sent = (@sent + [f.data]).last(5)
|
||||
@send&.call(f)
|
||||
:sent
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
if $PROGRAM_NAME == __FILE__
|
||||
t = Time.utc(2026, 12, 4, 13, 45, 30.25)
|
||||
f = Maptool::Can::TimeProducer.frame(t)
|
||||
raise f.data.unpack1("H*") unless f.id == 0x100 && f.data.bytesize == 6
|
||||
raise Maptool::Can::TimeProducer.parse(f.data).inspect unless (Maptool::Can::TimeProducer.parse(f.data) - t).abs < 0.001
|
||||
sent = []
|
||||
p = Maptool::Can::TimeProducer.new { |x| sent << x }
|
||||
raise "send" unless p.tick(t) == :sent
|
||||
p.heard(sent.last, at: t.to_f) # our own echo
|
||||
raise "own echo" unless p.tick(t + 1) == :sent
|
||||
p.heard(Maptool::Can::TimeProducer.frame(t + 0.5), at: t.to_f + 1) # the GNSS node's
|
||||
raise "quiet" unless p.tick(t + 2) == :others
|
||||
raise "back" unless p.tick(t + 5) == :sent
|
||||
raise "unset" unless Maptool::Can::TimeProducer.new.tick(Time.utc(1970, 1, 1)) == :unset
|
||||
puts "ok"
|
||||
end
|
||||
@@ -0,0 +1,153 @@
|
||||
require_relative "can"
|
||||
|
||||
module Maptool
|
||||
# Keypads as inputs, the way PDMs do it (docs/design.adoc, "Switches and
|
||||
# the keypad: how others do it"): a device's keys and knobs become named
|
||||
# channels — "pad.K1", "pad.E3" — and the screen profile binds a channel
|
||||
# to a function ("bindings" in public/drive/road.json); nothing here knows
|
||||
# what a key does. A device is any signals off the bus; a Blink Marine PKP
|
||||
# (ours speak its protocol too, home-gitops docs/canopen-nodes.adoc) also
|
||||
# brings its keys without signals and takes LED colours back.
|
||||
#
|
||||
# can.json: "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" } },
|
||||
# { "name": "wheel", "heartbeat_node": 40, "inputs": { "K1": "wheel.Button 1" } } ]
|
||||
# name the channels' prefix
|
||||
# protocol "pkp": K1…K<keys> 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 "<knob> 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
|
||||
@@ -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
|
||||
Reference in new issue
Block a user