274 lines
11 KiB
Ruby
274 lines
11 KiB
Ruby
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)
|
||
# or this car's (data/drive/bindings.json) with an "output" in place of an "action":
|
||
# { "input": "pad.K6", "output": "relays.2", "mode": "hold", "led": "red" }
|
||
# Modes (after Garmin PowerSwitch, OnDeck, MaxxECU — docs/design.adoc):
|
||
# toggle, on, off
|
||
# hold on while the key is held — off when it's let go or the keypad goes silent
|
||
# pulse on for "pulse_s" (1 s)
|
||
# positions "outputs": [a, b, …] — a press steps off → a → b → … → off, a knob
|
||
# turns up and down; one on at a time, the last off before the next on
|
||
# strobe a press starts / stops it blinking, "period_s" (1 s) a whole on + off
|
||
# dimmer a knob sets the level by "step" % (10), a press switches it on / off;
|
||
# only a "dimmable" module dims, a relay is on above 0
|
||
#
|
||
# can.json: "outputs": [ { "name": "relays", "node": 48, "channels": 8, "simulated": true,
|
||
# "labels": { "1": "Lights", "2": "Winch in" } },
|
||
# { "name": "dim", "node": 49, "channels": 4, "dimmable": true, "simulated": true } ]
|
||
# A module's protocol, ours (after LD's native CAN control): RPDO1
|
||
# 0x200+node, a bit per channel (byte 0: 1–8, byte 1: 9–16) — a dimmable
|
||
# one a byte per channel instead (0–255, up to 8) — 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 positions strobe dimmer].freeze
|
||
|
||
Module = Struct.new(:name, :node, :channels, :simulated, :dimmable, :labels, :state, :level, 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|
|
||
n = c.fetch("channels", 8)
|
||
raise ArgumentError, "#{c['name']}: a dimmable module has 8 channels at most" if c["dimmable"] && n > 8
|
||
|
||
Module.new(name: c.fetch("name"), node: Integer(c.fetch("node", 0)), channels: n, simulated: c.fetch("simulated", false),
|
||
dimmable: c.fetch("dimmable", false), labels: c.fetch("labels", {}), state: Array.new(n, false), level: Array.new(n, 100))
|
||
end
|
||
@send = send
|
||
@mutex = Mutex.new
|
||
@pulses = {}
|
||
@held = {} # channel (the key) → outputs it holds on
|
||
@positions = {} # channel → its position, 0 = all off
|
||
@strobes = {} # output → [since, period]
|
||
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 level(output)
|
||
m, i = find(output)
|
||
m ? @mutex.synchronize { m.level[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
|
||
|
||
# By hand (/sim.html, a screen tile): a strobe stops.
|
||
def manual(output, value)
|
||
@mutex.synchronize { @strobes.delete(output) }
|
||
set(output, value)
|
||
end
|
||
|
||
# The binding's outputs: "outputs" (positions) or "output".
|
||
def self.outputs_of(binding) = Array(binding["outputs"] || binding["output"])
|
||
|
||
# Whether a binding's function is on (its key's LED): a position chosen, a strobe running, else its output on.
|
||
def active?(binding)
|
||
outs = self.class.outputs_of(binding)
|
||
case binding["mode"]
|
||
when "positions" then @mutex.synchronize { @positions.fetch(binding["input"], 0) }.positive?
|
||
when "strobe" then @mutex.synchronize { @strobes.key?(outs.first) }
|
||
else !!on?(outs.first)
|
||
end
|
||
end
|
||
|
||
# A keypad event ("pad.K6", "pad.K6 up", "pad.E4 ⟳") through the bindings that have an output.
|
||
def input(event, bindings, at: Time.now.to_f)
|
||
turn = event[/ ([⟳⟲])\z/, 1]
|
||
up = event.end_with?(" up")
|
||
channel = event.sub(/ (up|⟳|⟲)\z/, "")
|
||
bindings.each do |b|
|
||
outs = self.class.outputs_of(b)
|
||
# a profile's output this car hasn't: skipped
|
||
next unless b["input"] == channel && outs.any? && outs.all? { |o| find(o) }
|
||
|
||
output = outs.first
|
||
mode = b.fetch("mode", "toggle")
|
||
if turn
|
||
step = turn == "⟳" ? 1 : -1
|
||
if mode == "positions" then position(channel, outs, @mutex.synchronize { @positions.fetch(channel, 0) } + step)
|
||
elsif mode == "dimmer" then dim(output, step * b.fetch("step", 10).to_f)
|
||
end
|
||
next
|
||
end
|
||
case mode
|
||
when "toggle", "dimmer" then switch(output, !on?(output)) unless up
|
||
when "on" then set(output, true) unless up
|
||
when "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 }
|
||
when "positions" then position(channel, outs, (@mutex.synchronize { @positions.fetch(channel, 0) } + 1) % (outs.size + 1)) unless up
|
||
when "strobe"
|
||
next if up
|
||
|
||
started = @mutex.synchronize { @strobes.delete(output) ? false : (@strobes[output] = [at, b.fetch("period_s", 1).to_f]) && true }
|
||
set(output, started) # started: on now; stopped: off
|
||
end
|
||
end
|
||
end
|
||
|
||
# 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, strobes blinking, the state sent again (the module's watchdog).
|
||
def tick(at: Time.now.to_f)
|
||
ended, strobes = @mutex.synchronize { [@pulses.select { |_, till| till <= at }.keys, @strobes.dup] }
|
||
ended.each { |o| set(o, false) }
|
||
strobes.each { |o, (since, period)| set(o, ((at - since) / (period / 2)).floor.even?) }
|
||
@modules.each { |m| transmit(m) }
|
||
end
|
||
|
||
def frame(m)
|
||
data = if m.dimmable
|
||
m.state.each_with_index.map { |on, i| on ? (m.level[i] * 255 / 100.0).round : 0 }.pack("C*")
|
||
else
|
||
[m.state.each_with_index.sum { |on, i| on ? 1 << i : 0 }].pack("Q<").byteslice(0, (m.channels + 7) / 8)
|
||
end
|
||
Can::Frame.new(0x200 + m.node, data, false)
|
||
end
|
||
|
||
def snapshot
|
||
@mutex.synchronize do
|
||
@modules.map do |m|
|
||
{ name: m.name, node: m.node, simulated: m.simulated, dimmable: m.dimmable,
|
||
channels: (1..m.channels).map do |n|
|
||
{ n: n, label: m.labels[n.to_s], on: m.state[n - 1], level: m.dimmable ? m.level[n - 1] : nil, strobe: @strobes.key?("#{m.name}.#{n}") }.compact
|
||
end }
|
||
end
|
||
end
|
||
end
|
||
|
||
private
|
||
|
||
# on with its level above 0 (a dimmer switched on at 0 comes back at 100)
|
||
def switch(output, value)
|
||
m, i = find(output)
|
||
@mutex.synchronize { m.level[i] = 100 if value && m.level[i].zero? }
|
||
set(output, value)
|
||
end
|
||
|
||
def dim(output, delta)
|
||
m, i = find(output)
|
||
level = @mutex.synchronize { m.level[i] = (m.level[i] + delta).clamp(0, 100) }
|
||
transmit(m) unless set(output, level.positive?)
|
||
end
|
||
|
||
# The channel's position n (clamped to 0..outputs): the others off first, then its own on.
|
||
def position(channel, outs, n)
|
||
n = n.clamp(0, outs.size)
|
||
@mutex.synchronize { @positions[channel] = n }
|
||
outs.each_with_index { |o, i| set(o, false) unless i == n - 1 }
|
||
set(outs[n - 1], true) if n.positive?
|
||
end
|
||
|
||
def transmit(m)
|
||
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 }, { "name" => "dim", "node" => 49, "channels" => 2, "dimmable" => true }]) { |f| sent << f }
|
||
b = [{ "input" => "pad.K1", "output" => "relays.1" }, { "input" => "pad.K6", "output" => "relays.2", "mode" => "hold" },
|
||
{ "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
|
||
relay_frame = sent.reverse.find { |f| f.id == 0x230 }
|
||
raise relay_frame.inspect unless relay_frame.data == "\x01".b
|
||
|
||
# positions: off → 4 → 5 → off by presses; a knob up and down, clamped
|
||
pos = [{ "input" => "pad.K2", "outputs" => ["relays.4", "relays.5"], "mode" => "positions" },
|
||
{ "input" => "pad.E4", "outputs" => ["relays.4", "relays.5"], "mode" => "positions" }]
|
||
states = -> { [out.on?("relays.4"), out.on?("relays.5")] }
|
||
out.input("pad.K2", pos)
|
||
raise "pos 1" unless states.call == [true, false] && out.active?(pos[0])
|
||
out.input("pad.K2", pos)
|
||
raise "pos 2" unless states.call == [false, true]
|
||
out.input("pad.K2", pos)
|
||
raise "pos 0" unless states.call == [false, false] && !out.active?(pos[0])
|
||
3.times { out.input("pad.E4 ⟳", pos) }
|
||
raise "knob clamp" unless states.call == [false, true]
|
||
out.input("pad.E4 ⟲", pos)
|
||
raise "knob down" unless states.call == [true, false]
|
||
|
||
# strobe: blinks at half the period, a press stops it off
|
||
st = [{ "input" => "pad.K3", "output" => "relays.6", "mode" => "strobe", "period_s" => 1 }]
|
||
out.input("pad.K3", st, at: 200)
|
||
out.tick(at: 200.6)
|
||
raise "strobe off phase" if out.on?("relays.6")
|
||
out.tick(at: 201.1)
|
||
raise "strobe on phase" unless out.on?("relays.6") && out.active?(st[0])
|
||
out.input("pad.K3", st, at: 201.2)
|
||
out.tick(at: 201.6)
|
||
raise "strobe stopped" if out.on?("relays.6") || out.active?(st[0])
|
||
|
||
# dimmer: a knob down to 0 is off, up is on again; a dimmable module sends bytes
|
||
dm = [{ "input" => "pad.E5", "output" => "dim.1", "mode" => "dimmer", "step" => 50 }, { "input" => "pad.E5 press", "output" => "dim.1", "mode" => "dimmer" }]
|
||
out.input("pad.E5 press", dm)
|
||
raise "dimmer on" unless out.on?("dim.1") && out.level("dim.1") == 100
|
||
out.input("pad.E5 ⟲", dm)
|
||
raise sent.last.data.bytes.inspect unless sent.last.id == 0x231 && sent.last.data.bytes == [128, 0]
|
||
out.input("pad.E5 ⟲", dm)
|
||
raise "dimmer 0 off" if out.on?("dim.1")
|
||
out.input("pad.E5 ⟳", dm)
|
||
raise "dimmer up" unless out.on?("dim.1") && out.level("dim.1") == 50
|
||
puts "ok"
|
||
end
|