Nodes describe themselves: an SDO client (Can::Sdo) reads each esphome-canopen node's TPDOs and entities (type, name, unit, range) on its first heartbeat, cached by the TPDO layout hash, decoded with no hand-written signals — can.json keeps aliases (with unit conversion) and foreign devices; design doc (NPS planning, cockpit instruments, Unigrid band) with color tokens, the dashboard in cockpit colors; starting the simulation turns the GNSS follow on, the GNSS position an arrow by its course
This commit is contained in:
1 parent
ce290f2162
commit
e92f01db12
12 files changed
+713
-76
No files matched your search
+24
-3
@@ -79,18 +79,39 @@ module Maptool
|
||||
TYPES = { "u8" => ["C", 1], "i8" => ["c", 1], "u16" => ["S<", 2], "i16" => ["s<", 2],
|
||||
"u32" => ["L<", 4], "i32" => ["l<", 4], "f32" => ["e", 4] }.freeze
|
||||
|
||||
# Frames → { "name" => value } by the config's signals.
|
||||
# Frames → { "name" => value } by the config's signals, plus each
|
||||
# discovered node's (#set_node, can_discovery.rb).
|
||||
class Decoder
|
||||
def initialize(signals)
|
||||
@signals = signals.map do |s|
|
||||
@static = compile(signals)
|
||||
@nodes = {}
|
||||
@signals = @static
|
||||
end
|
||||
|
||||
# A node's signals, replacing what it had (swapped in whole: the
|
||||
# reader thread keeps decoding with the old list meanwhile).
|
||||
def set_node(node, signals)
|
||||
@nodes = @nodes.merge(node => compile(signals))
|
||||
@signals = @static + @nodes.values.flatten
|
||||
end
|
||||
|
||||
# { name => unit } of every signal that has one.
|
||||
def units
|
||||
@signals.each_with_object({}) { |s, units| units[s[:name]] = s[:unit] if s[:unit] }
|
||||
end
|
||||
|
||||
def compile(signals)
|
||||
signals.map do |s|
|
||||
id = Integer(s.fetch("id"))
|
||||
type = s.fetch("type", "u8")
|
||||
raise ArgumentError, "#{s['name']}: unknown type #{type}" unless type == "bit" || TYPES.key?(type)
|
||||
|
||||
{ name: s.fetch("name"), id: id, mask: Integer(s.fetch("mask", "0x1FFFFFFF")), extended: id > 0x7FF,
|
||||
byte: s.fetch("byte", 0), bit: s["bit"], type: type, scale: s.fetch("scale", 1), offset: s.fetch("offset", 0), invalid: s["invalid"] }
|
||||
byte: s.fetch("byte", 0), bit: s["bit"], type: type, scale: s.fetch("scale", 1), offset: s.fetch("offset", 0), invalid: s["invalid"],
|
||||
unit: s["unit"] }
|
||||
end
|
||||
end
|
||||
private :compile
|
||||
|
||||
def decode(frame)
|
||||
@signals.each_with_object({}) do |s, values|
|
||||
|
||||
@@ -0,0 +1,199 @@
|
||||
require "json"
|
||||
require "fileutils"
|
||||
require_relative "can_sdo"
|
||||
|
||||
module Maptool
|
||||
module Can
|
||||
# Our esphome-canopen nodes describe themselves (canopen_entities' OD,
|
||||
# OBJECT_DICTIONARY.md): their TPDOs (0x1800+n COB-ID, 0x1A00+n mapping)
|
||||
# and, per mapped entity N, its type (0x2001:N) and metadata
|
||||
# (0x2000+0x10·N: name, unit, min/max — the scale of a 1/2-byte value).
|
||||
# Read once over SDO, cached by the TPDO layout hash (0x3002:1), the
|
||||
# node's signals go into the Decoder — no hand-written can.json for them.
|
||||
module Discovery
|
||||
LAYOUT_HASH = [0x3002, 1].freeze
|
||||
SCALED = { 6 => 1, 7 => 2, 9 => 1, 10 => 2 }.freeze # sensor8/16, number8/16 → bytes
|
||||
FLOATS = [1, 8].freeze # sensor, number: REAL32
|
||||
RAW = { 8 => "u8", 16 => "u16", 32 => "u32" }.freeze
|
||||
|
||||
def self.layout_hash(sdo, node)
|
||||
sdo.upload(node, *LAYOUT_HASH).unpack1("L<")
|
||||
end
|
||||
|
||||
# { node:, name:, hash:, signals: [Decoder signal config] }; raises
|
||||
# Sdo::Abort when it isn't an esphome-canopen node (no 0x3002).
|
||||
def self.describe(sdo, node, aliases: {})
|
||||
hash = layout_hash(sdo, node)
|
||||
name = optional { text(sdo.upload(node, 0x1008, 0)) }
|
||||
label = name || format("node%02X", node)
|
||||
entities = {}
|
||||
signals = []
|
||||
8.times do |n|
|
||||
cob = optional { sdo.upload(node, 0x1800 + n, 1).unpack1("L<") }
|
||||
next if cob.nil? || cob & 0x80000000 != 0 # not there / disabled
|
||||
|
||||
bit = 0
|
||||
sdo.upload(node, 0x1A00 + n, 0).getbyte(0).times do |k|
|
||||
entry = sdo.upload(node, 0x1A00 + n, k + 1).unpack1("L<")
|
||||
index, sub, bits = entry >> 16, (entry >> 8) & 0xFF, entry & 0xFF
|
||||
signal = entity_signal(sdo, node, entities, index, sub, bits)
|
||||
if signal && bit % 8 == 0
|
||||
full = "#{label}.#{signal.delete(:entity)}"
|
||||
signals << apply_alias(signal.merge("source" => full, "id" => format("0x%03X", cob & 0x7FF), "byte" => bit / 8), aliases)
|
||||
end
|
||||
bit += bits
|
||||
end
|
||||
end
|
||||
{ node: node, name: name, hash: hash, signals: signals }
|
||||
end
|
||||
|
||||
# One TPDO entry as a signal, nil if it isn't an entity's state.
|
||||
def self.entity_signal(sdo, node, entities, index, sub, bits)
|
||||
return nil unless index.between?(0x2011, 0x2FF1) && (index - 0x2001) % 0x10 == 0
|
||||
|
||||
n = (index - 0x2001) / 0x10
|
||||
entity = entities[n] ||= begin
|
||||
meta = 0x2000 + 0x10 * n
|
||||
{ type: sdo.upload(node, 0x2001, n).unpack1("L<") & 0xFF,
|
||||
name: optional { text(sdo.upload(node, meta, 1)) } || "entity#{n}",
|
||||
unit: optional { text(sdo.upload(node, meta, 3)) },
|
||||
min: optional { sdo.upload(node, meta, 7).unpack1("e") },
|
||||
max: optional { sdo.upload(node, meta, 8).unpack1("e") } }
|
||||
end
|
||||
name = sub == 1 ? entity[:name] : "#{entity[:name]} #{sub}"
|
||||
base = { entity: name, "unit" => entity[:unit] }.compact
|
||||
if FLOATS.include?(entity[:type]) && bits == 32
|
||||
base.merge("type" => "f32")
|
||||
elsif (size = SCALED[entity[:type]]) && bits == size * 8
|
||||
# value = min + (max - min) * raw / (2^n - 2); 2^n - 1 = unknown
|
||||
top = (1 << bits) - 1
|
||||
min = entity[:min] || 0.0
|
||||
max = entity[:max] || (top - 1).to_f
|
||||
base.merge("type" => RAW.fetch(bits), "scale" => (max - min) / (top - 1), "offset" => min, "invalid" => top)
|
||||
elsif RAW.key?(bits)
|
||||
base.merge("type" => RAW.fetch(bits)) # switch, light, binary sensor…: the raw state
|
||||
end
|
||||
end
|
||||
|
||||
# The signal under its alias: a name ("gnss.lat"), or {"name", "scale",
|
||||
# "unit"} when the app wants another unit (the node's km/h → m/s:
|
||||
# "scale": 0.2777…). Applied to the node's own encoding, so a cached
|
||||
# description takes today's aliases.
|
||||
def self.apply_alias(signal, aliases)
|
||||
alias_ = aliases[signal["source"]]
|
||||
alias_ = { "name" => alias_ } if alias_.is_a?(String)
|
||||
signal = signal.merge("name" => signal["source"]).reject { |k, _| k.start_with?("alias_") }
|
||||
return signal unless alias_
|
||||
|
||||
k = alias_.fetch("scale", 1)
|
||||
signal.merge("name" => alias_.fetch("name"), "scale" => signal.fetch("scale", 1) * k, "offset" => signal.fetch("offset", 0) * k,
|
||||
"unit" => alias_.fetch("unit", signal["unit"]), "alias_scale" => k).compact
|
||||
end
|
||||
|
||||
def self.text(bytes)
|
||||
bytes.force_encoding("UTF-8").delete("\0")
|
||||
end
|
||||
|
||||
def self.optional
|
||||
yield
|
||||
rescue Sdo::Abort
|
||||
nil
|
||||
end
|
||||
private_class_method :optional, :text
|
||||
end
|
||||
|
||||
# Describes every node heard (Store's nodes) in the background, one at
|
||||
# a time: the layout hash checked again every RECHECK_S (cheap: one SDO),
|
||||
# the full description read only when it changed; cached in cache_dir
|
||||
# (data/can_nodes/<node>.json). Anything failing — not our kind of node,
|
||||
# another SDO client in the way, the bus gone — is just tried later.
|
||||
class Discoverer
|
||||
POLL_S = 5
|
||||
RECHECK_S = 600
|
||||
RETRY_S = 30
|
||||
NOT_OURS_S = 3600
|
||||
|
||||
def initialize(store:, decoder:, cache_dir:, aliases: {}, sdo: nil, interface: nil)
|
||||
@store = store
|
||||
@decoder = decoder
|
||||
@cache_dir = cache_dir
|
||||
@aliases = aliases
|
||||
@sdo = sdo
|
||||
@interface = interface
|
||||
@next_at = {}
|
||||
@described = {}
|
||||
load_cache
|
||||
end
|
||||
|
||||
def start
|
||||
Thread.new do
|
||||
loop do
|
||||
run_once
|
||||
rescue StandardError => e
|
||||
warn "can discovery: #{e.message}"
|
||||
@sdo = nil # a new socket next round
|
||||
ensure
|
||||
sleep POLL_S
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
def run_once(now: Time.now.to_f)
|
||||
@store.snapshot[:nodes].each_key do |node|
|
||||
next if @next_at.fetch(node, 0) > now
|
||||
|
||||
check(node, now)
|
||||
end
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def check(node, now)
|
||||
sdo = (@sdo ||= Sdo.new(Sdo::SocketTransport.new(@interface)))
|
||||
hash = Discovery.layout_hash(sdo, node)
|
||||
unless @described[node]&.dig(:hash) == hash
|
||||
description = Discovery.describe(sdo, node, aliases: @aliases)
|
||||
save(description)
|
||||
use(description)
|
||||
warn "can discovery: node #{node} (#{description[:name]}): #{description[:signals].size} signals"
|
||||
end
|
||||
@next_at[node] = now + RECHECK_S
|
||||
rescue Sdo::Abort
|
||||
@next_at[node] = now + NOT_OURS_S # no 0x3002: not an esphome-canopen node
|
||||
rescue Sdo::Error
|
||||
@next_at[node] = now + RETRY_S
|
||||
end
|
||||
|
||||
def use(description)
|
||||
@described[description[:node]] = description
|
||||
@decoder.set_node(description[:node], description[:signals])
|
||||
end
|
||||
|
||||
def path(node)
|
||||
File.join(@cache_dir, format("%02x.json", node))
|
||||
end
|
||||
|
||||
def save(description)
|
||||
FileUtils.mkdir_p(@cache_dir)
|
||||
File.write(path(description[:node]), JSON.pretty_generate(description))
|
||||
end
|
||||
|
||||
def load_cache
|
||||
Dir.glob(File.join(@cache_dir, "*.json")).each do |file|
|
||||
description = JSON.parse(File.read(file), symbolize_names: true)
|
||||
# by today's aliases, not the ones it was cached with: back to the
|
||||
# node's own scale first
|
||||
description[:signals] = description[:signals].map do |s|
|
||||
s = s.transform_keys(&:to_s)
|
||||
k = s.delete("alias_scale") || 1
|
||||
s = s.merge("scale" => s.fetch("scale", 1) / k, "offset" => s.fetch("offset", 0) / k) if k != 1
|
||||
Discovery.apply_alias(s, @aliases)
|
||||
end
|
||||
use(description)
|
||||
rescue JSON::ParserError, KeyError, NoMethodError
|
||||
next
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,105 @@
|
||||
require_relative "can"
|
||||
|
||||
module Maptool
|
||||
module Can
|
||||
# A minimal SDO client (CiA 301): expedited and segmented uploads,
|
||||
# expedited downloads — enough to read a node's description and write a
|
||||
# command. Over a transport (#send a Frame, #receive(timeout) → Frame or
|
||||
# nil): SocketTransport on its own raw socket, next to the reader thread's.
|
||||
class Sdo
|
||||
TIMEOUT_S = 1.0
|
||||
|
||||
class Error < StandardError; end
|
||||
class Timeout < Error; end
|
||||
|
||||
class Abort < Error
|
||||
attr_reader :code
|
||||
|
||||
def initialize(code)
|
||||
@code = code
|
||||
super(format("SDO abort 0x%08X", code))
|
||||
end
|
||||
end
|
||||
|
||||
class SocketTransport
|
||||
def initialize(interface)
|
||||
@socket = Can.open(interface)
|
||||
end
|
||||
|
||||
def send(frame)
|
||||
@socket.write(frame.pack)
|
||||
end
|
||||
|
||||
def receive(timeout)
|
||||
return nil unless IO.select([@socket], nil, nil, timeout)
|
||||
|
||||
Frame.unpack(@socket.recv(16))
|
||||
end
|
||||
|
||||
def close
|
||||
@socket.close
|
||||
end
|
||||
end
|
||||
|
||||
def initialize(transport, timeout: TIMEOUT_S)
|
||||
@transport = transport
|
||||
@timeout = timeout
|
||||
end
|
||||
|
||||
# The object's bytes (strings come back as bytes: force_encoding them).
|
||||
def upload(node, index, sub)
|
||||
response = request(node, [0x40, index, sub, 0].pack("CS<CL<"), index: index, sub: sub)
|
||||
cs = response.getbyte(0)
|
||||
raise Error, format("unexpected SDO reply 0x%02X", cs) unless cs & 0xE0 == 0x40
|
||||
|
||||
if cs & 0x02 != 0 # expedited: the data's in this frame
|
||||
size = cs & 0x01 != 0 ? 4 - ((cs >> 2) & 3) : 4
|
||||
return response.byteslice(4, size)
|
||||
end
|
||||
|
||||
data = "".b
|
||||
toggle = 0
|
||||
loop do
|
||||
segment = request(node, [0x60 | (toggle << 4)].pack("C") + ("\0" * 7))
|
||||
scs = segment.getbyte(0)
|
||||
raise Error, "SDO segment out of order" unless scs & 0xE0 == 0x00 && (scs >> 4) & 1 == toggle
|
||||
|
||||
data << segment.byteslice(1, 7 - ((scs >> 1) & 7))
|
||||
return data if scs & 0x01 != 0
|
||||
|
||||
toggle ^= 1
|
||||
end
|
||||
end
|
||||
|
||||
# An expedited download of up to 4 bytes.
|
||||
def download(node, index, sub, bytes)
|
||||
raise ArgumentError, "expedited: 1 to 4 bytes" unless (1..4).cover?(bytes.bytesize)
|
||||
|
||||
cs = 0x23 | ((4 - bytes.bytesize) << 2)
|
||||
response = request(node, [cs, index, sub].pack("CS<C") + bytes.b.ljust(4, "\0"), index: index, sub: sub)
|
||||
raise Error, format("unexpected SDO reply 0x%02X", response.getbyte(0)) unless response.getbyte(0) == 0x60
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
# Sends to 0x600+node, waits for 0x580+node. index/sub: an initiate's
|
||||
# answer must be for that object — another SDO client talking to the
|
||||
# same node (can2mqtt) gets its own answers too.
|
||||
def request(node, data, index: nil, sub: nil)
|
||||
@transport.send(Frame.new(0x600 + node, data, false))
|
||||
deadline = Process.clock_gettime(Process::CLOCK_MONOTONIC) + @timeout
|
||||
loop do
|
||||
remaining = deadline - Process.clock_gettime(Process::CLOCK_MONOTONIC)
|
||||
raise Timeout, format("no SDO answer from node 0x%02X", node) if remaining <= 0
|
||||
|
||||
frame = @transport.receive(remaining)
|
||||
next unless frame && !frame.extended && frame.id == 0x580 + node && frame.data.bytesize == 8
|
||||
next if index && frame.data.byteslice(1, 3).unpack("S<C") != [index, sub]
|
||||
raise Abort, frame.data.byteslice(4, 4).unpack1("L<") if frame.data.getbyte(0) == 0x80
|
||||
|
||||
return frame.data
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
Reference in new issue
Block a user