Native CAN (the van's final setup, MQTT the stopgap): SocketCAN on any number of interfaces, CANopen frame roles, heartbeat states and NMT start, signals decoded by data/can.json (id/mask, byte/bit, type, scale/offset, unit); gnss.* signals feed the GNSS control, GET /api/can; tested over vcan0
CI / check (push) Successful in 20s
CI / deploy (push) Successful in 17s

This commit is contained in:
randy committed 2026-11-27 22:48:46 +01:00
1 parent 78bdc7f6f0
commit 850a5946ad
5 files changed
+299 -5

No files matched your search

+13 -5
View File
@@ -157,9 +157,17 @@ already reaches the home MQTT broker (`mqtt_ext`) from ESPHome nodes in `~/espho
* [ ] Car CAN data (`mcu-car-can.yaml`, today over the native API to HA): add `mqtt:` like the
tracker; RPM, doors, parking brake, … in a dashboard panel
* [ ] IMU shocks along a drive as a map layer — road roughness / potholes colored by intensity
* [ ] Later in the van: CANopen (or plain CAN with own IDs) to the server, a small CAN → MQTT
bridge on the host (SocketCAN; `can0` lives in the host's network namespace), maptool stays
on MQTT
* [x] Native CAN in maptool (the van's final setup, MQTT is the stopgap): SocketCAN on any
number of interfaces (USB adapter, the board's own controller, `vcan0` for tests),
CANopen frame roles + heartbeat states, NMT start, signals decoded by `data/can.json`
(COB-ID/mask, byte/bit, type, scale/offset — `lib/maptool/can.rb`), `gnss.*` signals feed
the GNSS control, `GET /api/can`
** [ ] The container on the CAN bus: `can0` lives in the host's network namespace — either
`network_mode: host` for maptool (then kiwix/valhalla by localhost ports, not service
names) or a vxcan pair moved into the container's namespace by a host script
** [ ] The car-CAN → CANopen bridge's mapping (not decided yet) as signals in `data/can.json`;
a dashboard panel for the `car.*` signals
** [ ] The GNSS node's PDO layout (lat/lon i32 × 1e-7, speed, course, fix) as `gnss.*` signals
=== 3D navigation mode
@@ -213,8 +221,8 @@ already offline work on the road. The Pi only serves; heavy builds stay on brick
* [ ] Hardware buttons: keyboard shortcuts in the page (zoom, Navigate, night mode, …) — the
cheap way with any BLE/USB keypad that sends plain keys
* [ ] … and the full way: a CANopen keypad (Blink Marine style) on the CAN bus wired straight
to the Pi (SocketCAN `can0`) → the small CAN → MQTT bridge on the host (see "Later in the
van" above; NMT start, key bitmap from `0x180+node`, LEDs via `0x200+node`) → maptool → the
to the Pi, read by maptool's native CAN (see "Native CAN" above; NMT start, key bitmap
from `0x180+node` as `bit` signals, LEDs via `0x200+node` still to send) → the
browser over Server-Sent Events; the page's state (navigating, night) back the same way to
light the keypad's LEDs. Server needs to know which browser is "the car display" (a
per-device switch — or simply the Pi's own kiosk display)
+35
View File
@@ -11,6 +11,7 @@ require_relative "lib/maptool/library"
require_relative "lib/maptool/google_saved"
require_relative "lib/maptool/routing"
require_relative "lib/maptool/mqtt_client"
require_relative "lib/maptool/can"
require_relative "lib/maptool/live_store"
require_relative "lib/maptool/livetrack_store"
require_relative "lib/maptool/livetrack_client"
@@ -320,6 +321,30 @@ module Maptool
GNSS_LATEST = {}
GNSS_LATEST_MUTEX = Mutex.new
# Native CAN (lib/maptool/can.rb), on when data/can.json exists: one
# reader thread per interface. Signals named gnss.<field> (lat, lon,
# alt, speed in m/s, track in degrees, mode) feed GNSS_LATEST; a fix
# counts from the frame that brings lat or lon.
CAN_CONFIG_PATH = File.join(DATA_DIR, "can.json")
CAN_STORE = Can::Store.new
CAN_CONFIG = File.exist?(CAN_CONFIG_PATH) ? JSON.parse(File.read(CAN_CONFIG_PATH)) : nil
if CAN_CONFIG && !test?
decoder = Can::Decoder.new(CAN_CONFIG.fetch("signals", []))
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|
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_LATEST_MUTEX.synchronize do
GNSS_LATEST.merge!(gnss)
GNSS_LATEST[:received_at] = Time.now.to_f if gnss.key?(:lat) || gnss.key?(:lon)
end
end
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
@@ -1040,6 +1065,16 @@ module Maptool
send_file path, disposition: kind == "geotiff" ? "attachment" : "inline"
end
# What the CAN bus last said: per interface (up, frames, error), per
# CANopen node (heartbeat state, last seen) and each configured signal.
get "/api/can" do
require_login!
snapshot = CAN_STORE.snapshot
units = (CAN_CONFIG || {}).fetch("signals", []).to_h { |signal| [signal["name"], signal["unit"]] }
snapshot[:signals] = snapshot[:signals].to_h { |name, signal| [name, units[name] ? signal.merge(unit: units[name]) : signal] }
json snapshot.merge(available: !CAN_CONFIG.nil?)
end
get "/api/live" do
require_login!
json LIVE_STORE.snapshot.merge(available: !MQTT_URL.empty?)
+171
View File
@@ -0,0 +1,171 @@
require "socket"
require "json"
module Maptool
# Native CAN for the van (the final setup; MQTT is the stopgap): raw
# SocketCAN frames off one or more interfaces (a USB adapter or the
# board's own controller, vcan0 for testing — all the same to Linux),
# CANopen's frame roles, and signals decoded from frames by a config —
# what goes on the bus (the car-CAN → CANopen bridge, own nodes, the
# GNSS node) isn't fixed yet, so nothing is hardcoded but CANopen itself.
#
# Config (data/can.json; CAN is off without it):
# { "interfaces": ["can0"],
# "nmt_start": true, // NMT "start all nodes" on connect
# "signals": [
# { "name": "gnss.lat", "id": "0x181", "byte": 0, "type": "i32", "scale": 1e-7 },
# { "name": "keypad.key1", "id": "0x195", "byte": 0, "bit": 0, "type": "bit" },
# { "name": "car.rpm", "id": "0x18FEF100", "mask": "0x00FFFF00", "byte": 3,
# "type": "u16", "scale": 0.125, "unit": "rpm" } ] }
# `id` matches the frame's id under `mask` (default: all bits); an id
# above 0x7FF is an extended (29-bit) one. Types are little-endian like
# CANopen: u8 i8 u16 i16 u32 i32 f32, or bit. value = raw * scale + offset.
module Can
EFF_FLAG = 0x80000000 # extended frame
RTR_FLAG = 0x40000000
ERR_FLAG = 0x20000000
EFF_MASK = 0x1FFFFFFF
CAN_RAW = 1
FRAME = "LCx3a8" # struct can_frame: id, len, 3 bytes padding/reserved, data[8]
Frame = Struct.new(:id, :data, :extended) do
def self.unpack(bytes)
raw, len, data = bytes.unpack(FRAME)
return nil if raw & (ERR_FLAG | RTR_FLAG) != 0
new(raw & EFF_MASK, data.byteslice(0, [len, 8].min), raw & EFF_FLAG != 0)
end
def pack
[id | (extended ? EFF_FLAG : 0), data.bytesize, data.b.ljust(8, "\0")].pack(FRAME)
end
end
# A raw CAN socket bound to `interface` (struct sockaddr_can: family,
# padding, ifindex, 16 bytes of protocol-specific address).
def self.open(interface)
ifindex = Socket.getifaddrs.find { |i| i.name == interface }&.ifindex or raise SocketError, "no CAN interface #{interface}"
socket = Socket.new(Socket::AF_CAN, Socket::SOCK_RAW, CAN_RAW)
socket.bind([Socket::AF_CAN, ifindex].pack("Sx2lx16"))
socket
end
# CANopen's predefined connection set: what a COB-ID is.
def self.canopen_role(id, extended: false)
return nil if extended
node = id & 0x7F
case id >> 7
when 0x0 then id.zero? ? [:nmt, nil] : nil
when 0x1 then node.zero? ? [:sync, nil] : [:emcy, node]
when 0x2 then [:time, nil]
when 0x3, 0x5, 0x7, 0x9 then [:"tpdo#{((id >> 7) - 1) / 2}", node]
when 0x4, 0x6, 0x8, 0xA then [:"rpdo#{((id >> 7) - 2) / 2}", node]
when 0xB then [:sdo_tx, node]
when 0xC then [:sdo_rx, node]
when 0xE then [:heartbeat, node]
end
end
HEARTBEAT_STATES = { 0x00 => "boot-up", 0x04 => "stopped", 0x05 => "operational", 0x7F => "pre-operational" }.freeze
# NMT "start remote node" (node 0: all of them).
def self.nmt_start(node = 0)
Frame.new(0, [0x01, node].pack("CC"), false)
end
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.
class Decoder
def initialize(signals)
@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) }
end
end
def decode(frame)
@signals.each_with_object({}) do |s, values|
next unless s[:extended] == frame.extended && (frame.id & s[:mask]) == (s[:id] & s[:mask])
raw = if s[:type] == "bit"
byte = frame.data.getbyte(s[:byte])
byte && (byte >> s[:bit].to_i) & 1
else
format, size = TYPES.fetch(s[:type])
chunk = frame.data.byteslice(s[:byte], size)
chunk.unpack1(format) if chunk&.bytesize == size
end
values[s[:name]] = s[:type] == "bit" ? raw : raw * s[:scale] + s[:offset] unless raw.nil?
end
end
end
# The latest of everything heard, for GET /api/can.
class Store
def initialize
@mutex = Mutex.new
@signals = {}
@nodes = {}
@interfaces = {}
end
def interface(name, **state)
@mutex.synchronize { (@interfaces[name] ||= { frames: 0 }).merge!(state) }
end
def record(interface, frame, values, at: Time.now.to_f)
@mutex.synchronize do
entry = (@interfaces[interface] ||= { frames: 0 })
entry[:frames] += 1
entry[:last_frame_at] = at
role, node = Can.canopen_role(frame.id, extended: frame.extended)
if node
n = (@nodes[node] ||= {})
n[:seen_at] = at
n[:state] = HEARTBEAT_STATES.fetch(frame.data.getbyte(0) & 0x7F, "unknown") if role == :heartbeat && frame.data.bytesize >= 1
end
values.each { |name, value| @signals[name] = { value: value, at: at } }
end
end
def snapshot
@mutex.synchronize { { interfaces: @interfaces.dup, nodes: @nodes.dup, signals: @signals.dup } }
end
end
# Reads `interface` forever, reconnecting (warned once per outage, not
# every retry): an adapter unplugged or not up yet isn't fatal.
def self.listen(interface, decoder:, store:, start_nodes: false, retry_delay: 5)
down = false
loop do
socket = open(interface)
store.interface(interface, up: true, error: nil)
warn "can: #{interface} up" if down
down = false
socket.write(nmt_start.pack) if start_nodes
loop do
bytes = socket.read(16) or raise IOError, "#{interface} closed"
frame = Frame.unpack(bytes)
next unless frame
values = decoder.decode(frame)
store.record(interface, frame, values)
yield(values) if block_given? && !values.empty?
end
rescue SocketError, SystemCallError, IOError => e
store.interface(interface, up: false, error: e.message)
warn "can: #{interface}: #{e.message} — retrying every #{retry_delay}s" unless down
down = true
socket&.close
sleep retry_delay
end
end
end
end
+5
View File
@@ -137,6 +137,11 @@ class AppTest < Minitest::Test
assert_equal 401, request.get("/api/live").status
end
def test_can_requires_login_and_is_off_without_a_config
assert_equal 401, request.get("/api/can").status
assert_equal({ "interfaces" => {}, "nodes" => {}, "signals" => {}, "available" => false }, json_body(request.get("/api/can", **logged_in_env)))
end
# MQTT messages land in the tracker / ITS-G5 parts of /api/live.
def test_live_routes_topics_into_the_snapshot
app = Maptool::App
+75
View File
@@ -0,0 +1,75 @@
require_relative "test_helper"
require "maptool/can"
require "timeout"
class CanTest < Minitest::Test
Frame = Maptool::Can::Frame
def test_a_frame_round_trips_through_struct_can_frame
frame = Frame.new(0x181, "\x01\x02\x03".b, false)
bytes = frame.pack
assert_equal 16, bytes.bytesize
assert_equal frame, Frame.unpack(bytes)
extended = Frame.new(0x18FEF100, "\xFF".b, true)
assert_equal extended, Frame.unpack(extended.pack)
assert_nil Frame.unpack([0x181 | Maptool::Can::RTR_FLAG, 0, ""].pack(Maptool::Can::FRAME)), "remote request: no data"
end
def test_canopen_roles_by_cob_id
roles = [0x000, 0x080, 0x081, 0x181, 0x285, 0x20A, 0x585, 0x605, 0x77F].map { |id| Maptool::Can.canopen_role(id) }
assert_equal [[:nmt, nil], [:sync, nil], [:emcy, 1], [:tpdo1, 1], [:tpdo2, 5], [:rpdo1, 10], [:sdo_tx, 5], [:sdo_rx, 5], [:heartbeat, 127]], roles
assert_nil Maptool::Can.canopen_role(0x181, extended: true)
assert_equal [0x01, 0x00], Maptool::Can.nmt_start.data.bytes
end
def test_signals_decode_by_id_mask_type_and_scale
decoder = Maptool::Can::Decoder.new([
{ "name" => "gnss.lat", "id" => "0x181", "byte" => 0, "type" => "i32", "scale" => 1e-7 },
{ "name" => "gnss.lon", "id" => "0x181", "byte" => 4, "type" => "i32", "scale" => 1e-7 },
{ "name" => "keypad.key2", "id" => "0x195", "byte" => 0, "bit" => 1, "type" => "bit" },
{ "name" => "car.rpm", "id" => "0x18FEF100", "mask" => "0x00FFFF00", "byte" => 3, "type" => "u16", "scale" => 0.125 },
{ "name" => "temp", "id" => "0x281", "byte" => 0, "type" => "i16", "scale" => 0.1, "offset" => -40 },
])
gnss = decoder.decode(Frame.new(0x181, [491_700_000, 200_500_000].pack("l<l<"), false))
assert_in_delta 49.17, gnss["gnss.lat"], 1e-9
assert_in_delta 20.05, gnss["gnss.lon"], 1e-9
assert_equal({ "keypad.key2" => 1 }, decoder.decode(Frame.new(0x195, "\x02".b, false)))
assert_equal({ "keypad.key2" => 0 }, decoder.decode(Frame.new(0x195, "\x01".b, false)))
# Another source address (low byte) under the mask; a standard id never matches an extended signal.
assert_equal({ "car.rpm" => 800.0 }, decoder.decode(Frame.new(0x18FEF1AB, "\0\0\0#{[6400].pack('S<')}".b, true)))
assert_empty decoder.decode(Frame.new(0x0F1, "\0\0\0\0\0".b, false))
assert_in_delta(-15.0, decoder.decode(Frame.new(0x281, [250].pack("s<"), false))["temp"])
assert_empty decoder.decode(Frame.new(0x181, "\x01".b, false)), "too short for the i32s"
assert_raises(ArgumentError) { Maptool::Can::Decoder.new([{ "name" => "x", "id" => 1, "type" => "u64" }]) }
end
def test_the_store_keeps_signals_and_node_heartbeat_states
store = Maptool::Can::Store.new
store.record("vcan0", Frame.new(0x705, "\x05".b, false), {}, at: 1.0)
store.record("vcan0", Frame.new(0x181, "".b, false), { "gnss.lat" => 49.1 }, at: 2.0)
snapshot = store.snapshot
assert_equal({ frames: 2, last_frame_at: 2.0 }, snapshot[:interfaces]["vcan0"])
assert_equal({ seen_at: 1.0, state: "operational" }, snapshot[:nodes][5])
assert_equal({ value: 49.1, at: 2.0 }, snapshot[:signals]["gnss.lat"])
end
# Over a real SocketCAN interface when there is one:
# sudo ip link add dev vcan0 type vcan && sudo ip link set up vcan0
def test_frames_go_over_vcan0
skip "no vcan0" unless Socket.getifaddrs.any? { |i| i.name == "vcan0" }
store = Maptool::Can::Store.new
decoder = Maptool::Can::Decoder.new([{ "name" => "speed", "id" => "0x182", "type" => "u16", "scale" => 0.01 }])
received = Queue.new
reader = Thread.new { Maptool::Can.listen("vcan0", decoder: decoder, store: store, retry_delay: 0.1) { |values| received << values } }
sleep 0.2 until store.snapshot[:interfaces].dig("vcan0", :up)
sender = Maptool::Can.open("vcan0")
sender.write(Frame.new(0x182, [1234].pack("S<"), false).pack)
assert_in_delta 12.34, Timeout.timeout(2) { received.pop }["speed"]
ensure
reader&.kill
sender&.close
end
end