200 lines
7.6 KiB
Ruby
200 lines
7.6 KiB
Ruby
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
|