CAN actions: can.json's "actions" ({name, node, index, subindex, data: 1–4 bytes hex}) are SDO expedited downloads, a button beside their node on /can.html (confirm first, the result in the status line) — POST /api/can/actions/:n (login, 409 with no config, 404 unknown, 502 on an SDO error), GET /api/can lists them; first one: Level IMU on node 0x21 (0x2022:1 ← 01)
This commit is contained in:
1 parent
0a5548cd8f
commit
97d1bda09c
6 files changed
+77
-7
No files matched your search
@@ -464,6 +464,13 @@ module Maptool
|
||||
warn "can: #{CAN_CONFIG_PATH}: #{e.message} — CAN off"
|
||||
[nil, nil]
|
||||
end
|
||||
# can.json's "actions": SDO writes /can.html offers beside their node (Can::Sdo::Action).
|
||||
CAN_ACTIONS = (CAN_CONFIG ? CAN_CONFIG.fetch("actions", []) : []).filter_map do |action|
|
||||
Can::Sdo::Action.parse(action)
|
||||
rescue StandardError => e
|
||||
warn "can: #{CAN_CONFIG_PATH}: action #{action.inspect}: #{e.message} — skipped"
|
||||
nil
|
||||
end
|
||||
# The bus recorded on the server into MF4 files (/trace.html, can-recorder/).
|
||||
CAN_RECORDER = Can::Recorder.new(File.join(DATA_DIR, "can_rec"), CAN_CONFIG ? CAN_CONFIG.fetch("interfaces", []) : [])
|
||||
at_exit { CAN_RECORDER.stop }
|
||||
@@ -1403,7 +1410,24 @@ module Maptool
|
||||
units = CAN_DECODER ? CAN_DECODER.units : {}
|
||||
snapshot[:signals] = snapshot[:signals].to_h { |name, signal| [name, units[name] ? signal.merge(unit: units[name]) : signal] }
|
||||
# simulated: the GNSS simulation (/sim.html) stands in for gnss.*
|
||||
json snapshot.merge(available: !CAN_CONFIG.nil?, simulated: GNSS_SIM.running?)
|
||||
actions = CAN_ACTIONS.map { |a| { name: a.name, node: a.node } }
|
||||
json snapshot.merge(available: !CAN_CONFIG.nil?, simulated: GNSS_SIM.running?, actions: actions)
|
||||
end
|
||||
|
||||
# Runs can.json's action number :n (its place in GET /api/can's actions).
|
||||
post "/api/can/actions/:n" do
|
||||
require_login!
|
||||
halt 409, json(error: "CAN is off: no data/can.json on this server") unless CAN_CONFIG
|
||||
action = CAN_ACTIONS[Integer(params[:n], exception: false) || -1] or halt 404
|
||||
transport = Can::Sdo::SocketTransport.new(CAN_CONFIG.fetch("interfaces").first)
|
||||
begin
|
||||
action.run(Can::Sdo.new(transport))
|
||||
rescue Can::Sdo::Error => e
|
||||
halt 502, json(error: e.message)
|
||||
ensure
|
||||
transport.close
|
||||
end
|
||||
json ok: true
|
||||
end
|
||||
|
||||
# Recording the bus into MF4 files on the server: GET whether it runs and
|
||||
|
||||
@@ -12,6 +12,8 @@ module Maptool
|
||||
# Config (data/can.json; CAN is off without it):
|
||||
# { "interfaces": ["can0"],
|
||||
# "nmt_start": true, // NMT "start all nodes" on connect
|
||||
# "actions": [ // SDO writes, buttons beside the node in /can.html
|
||||
# { "name": "Level IMU", "node": 33, "index": "0x2022", "subindex": 1, "data": "01" } ],
|
||||
# "signals": [
|
||||
# { "name": "gnss.lat", "id": "0x181", "byte": 0, "type": "i32", "scale": 1e-7 },
|
||||
# { "name": "keypad.key1", "id": "0x195", "byte": 0, "bit": 0, "type": "bit" },
|
||||
|
||||
@@ -80,6 +80,24 @@ module Maptool
|
||||
raise Error, format("unexpected SDO reply 0x%02X", response.getbyte(0)) unless response.getbyte(0) == 0x60
|
||||
end
|
||||
|
||||
# A command from can.json's "actions", written by an expedited download
|
||||
# — /can.html's buttons beside a node, e.g. levelling its IMU:
|
||||
# { "name": "Level IMU", "node": 33, "index": "0x2022", "subindex": 1, "data": "01" }
|
||||
# `data`: the bytes in hex, little-endian like the OD (1 to 4 bytes).
|
||||
Action = Struct.new(:name, :node, :index, :sub, :bytes) do
|
||||
def self.parse(config)
|
||||
int = ->(v) { Integer(v) } # "0x2022" or 8226
|
||||
bytes = [config.fetch("data")].pack("H*")
|
||||
raise ArgumentError, "#{config["name"]}: data must be 1 to 4 bytes in hex" unless (1..4).cover?(bytes.bytesize)
|
||||
|
||||
new(config.fetch("name"), int.(config.fetch("node")), int.(config.fetch("index")), int.(config.fetch("subindex", 0)), bytes)
|
||||
end
|
||||
|
||||
def run(sdo)
|
||||
sdo.download(node, index, sub, bytes)
|
||||
end
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
# Sends to 0x600+node, waits for 0x580+node. index/sub: an initiate's
|
||||
|
||||
+2
-1
@@ -190,7 +190,8 @@ class AppTest < Minitest::Test
|
||||
|
||||
def test_can_requires_login_and_is_off_without_a_config
|
||||
assert_equal 401, request.get("/api/can").status
|
||||
assert_equal({ "interfaces" => {}, "nodes" => {}, "signals" => {}, "frames" => [], "available" => false, "simulated" => false }, json_body(request.get("/api/can", **logged_in_env)))
|
||||
assert_equal 409, request.post("/api/can/actions/0", **logged_in_env).status
|
||||
assert_equal({ "interfaces" => {}, "nodes" => {}, "signals" => {}, "frames" => [], "available" => false, "simulated" => false, "actions" => [] }, json_body(request.get("/api/can", **logged_in_env)))
|
||||
end
|
||||
|
||||
# MQTT messages land in the tracker / ITS-G5 parts of /api/live.
|
||||
|
||||
@@ -85,6 +85,14 @@ class CanDiscoveryTest < Minitest::Test
|
||||
assert_equal "\x01", node.od[[0x20E2, 1]]
|
||||
end
|
||||
|
||||
def test_an_action_writes_its_bytes_and_rejects_bad_data
|
||||
node = FakeNode.new(0x21, {})
|
||||
action = Maptool::Can::Sdo::Action.parse("name" => "Level IMU", "node" => 33, "index" => "0x2022", "subindex" => 1, "data" => "01")
|
||||
action.run(Maptool::Can::Sdo.new(node))
|
||||
assert_equal "\x01".b, node.od[[0x2022, 1]]
|
||||
assert_raises(ArgumentError) { Maptool::Can::Sdo::Action.parse("name" => "x", "node" => 1, "index" => 1, "data" => "0102030405") }
|
||||
end
|
||||
|
||||
def test_a_node_described_decodes_its_own_tpdos
|
||||
sdo = Maptool::Can::Sdo.new(FakeNode.new(0x21, GNSS_OD.dup))
|
||||
description = Maptool::Can::Discovery.describe(sdo, 0x21, aliases: { "XIAO STM32C5 2.Latitude" => "gnss.lat" })
|
||||
|
||||
+22
-5
@@ -47,7 +47,7 @@
|
||||
<div class="scroll"><table id="interfaces"><thead><tr><th>Interface</th><th>State</th><th class="num">Frames</th><th>Last frame</th><th>Error</th></tr></thead><tbody></tbody></table></div>
|
||||
|
||||
<h2>Nodes</h2>
|
||||
<div class="scroll"><table id="nodes"><thead><tr><th>Node</th><th>State</th><th>Last seen</th><th>Last EMCY</th><th>Sends</th></tr></thead><tbody></tbody></table></div>
|
||||
<div class="scroll"><table id="nodes"><thead><tr><th>Node</th><th>State</th><th>Last seen</th><th>Last EMCY</th><th>Sends</th><th>Actions</th></tr></thead><tbody></tbody></table></div>
|
||||
|
||||
<h2>Signals</h2>
|
||||
<div class="scroll"><table id="signals"><thead><tr><th>Signal</th><th class="num">Value</th><th>Unit</th><th>Updated</th></tr></thead><tbody></tbody></table></div>
|
||||
@@ -97,6 +97,22 @@
|
||||
document.querySelector(`#${id} tbody`).innerHTML = rows.length ? rows.join("") : `<tr><td class="empty" colspan="${cols}">${empty}</td></tr>`;
|
||||
}
|
||||
|
||||
// can.json's "actions" beside their node: one SDO write each (POST /api/can/actions/<n>).
|
||||
let notice = null; // an action's outcome, shown in the status for 10 s
|
||||
const actionsHtml = (actions, node) => (actions || []).map((a, n) => a.node === node ? `<button type="button" data-action="${n}">${esc(a.name)}</button>` : "").join(" ");
|
||||
document.getElementById("nodes").addEventListener("click", async (e) => {
|
||||
const button = e.target.closest("button[data-action]");
|
||||
if (!button || !confirm(`${button.textContent} on node ${last.actions[button.dataset.action].node}?`)) return;
|
||||
button.disabled = true;
|
||||
try {
|
||||
const response = await fetch(`/api/can/actions/${button.dataset.action}`, { method: "POST" });
|
||||
const body = await response.json().catch(() => ({}));
|
||||
notice = { text: `${button.textContent}: ${response.ok ? "done" : body.error || `HTTP ${response.status}`}`, bad: !response.ok, until: Date.now() + 10000 };
|
||||
} finally {
|
||||
button.disabled = false;
|
||||
}
|
||||
});
|
||||
|
||||
const STATE_CLASS = { operational: "ok", "pre-operational": "warn", stopped: "bad", "boot-up": "warn" };
|
||||
|
||||
function render(data) {
|
||||
@@ -108,8 +124,8 @@
|
||||
for (const f of data.frames) if (f.node != null) (roles[f.node] ||= new Set()).add(f.role);
|
||||
fill("nodes", Object.entries(data.nodes).sort((a, b) => a[0] - b[0]).map(([id, n]) => {
|
||||
const emcy = n.emcy ? `<code>${hex(n.emcy.code, 4)}</code> reg <code>${hex(n.emcy.register, 2)}</code> ${n.emcy.code === 0 ? "(reset)" : ""} · ${age(n.emcy.at)}` : "—";
|
||||
return `<tr class="${stale(n.seen_at) && !n.silent ? "stale" : ""}"><td>${nodeName(id)}</td><td class="${n.silent ? "bad" : STATE_CLASS[n.state] || ""}"${n.silent ? ' title="3 heartbeats missed"' : ""}>${n.silent ? "silent" : esc(n.state || "no heartbeat")}</td><td>${age(n.seen_at)}</td><td class="${n.emcy?.code ? "bad" : ""}">${emcy}</td><td>${[...(roles[id] || [])].sort().map(esc).join(", ")}</td></tr>`;
|
||||
}), "No CANopen node heard yet.", 5);
|
||||
return `<tr class="${stale(n.seen_at) && !n.silent ? "stale" : ""}"><td>${nodeName(id)}</td><td class="${n.silent ? "bad" : STATE_CLASS[n.state] || ""}"${n.silent ? ' title="3 heartbeats missed"' : ""}>${n.silent ? "silent" : esc(n.state || "no heartbeat")}</td><td>${age(n.seen_at)}</td><td class="${n.emcy?.code ? "bad" : ""}">${emcy}</td><td>${[...(roles[id] || [])].sort().map(esc).join(", ")}</td><td>${actionsHtml(data.actions, Number(id))}</td></tr>`;
|
||||
}), "No CANopen node heard yet.", 6);
|
||||
|
||||
fill("signals", Object.entries(data.signals).sort().map(([name, s]) =>
|
||||
`<tr class="${stale(s.at) ? "stale" : ""}"><td>${esc(name)}</td><td class="num">${typeof s.value === "number" ? +s.value.toFixed(6) : esc(s.value)}</td><td>${esc(s.unit)}</td><td>${age(s.at)}</td></tr>`),
|
||||
@@ -136,8 +152,9 @@
|
||||
if (date) clockOffset = Math.abs(date / 1000 - Date.now() / 1000) > 2 ? date / 1000 - Date.now() / 1000 : 0;
|
||||
render(last = await response.json());
|
||||
const silent = Object.keys(last.nodes).filter((id) => last.nodes[id].silent);
|
||||
status.className = silent.length ? "bad" : "";
|
||||
status.textContent = (silent.length ? `⚠ node ${silent.join(", ")} silent · ` : "") + `updated ${new Date().toLocaleTimeString()}`;
|
||||
const shown = notice && notice.until > Date.now() ? notice : null;
|
||||
status.className = silent.length || shown?.bad ? "bad" : "";
|
||||
status.textContent = (shown ? `${shown.text} · ` : "") + (silent.length ? `⚠ node ${silent.join(", ")} silent · ` : "") + `updated ${new Date().toLocaleTimeString()}`;
|
||||
} catch (e) {
|
||||
status.textContent = `can't reach the server: ${e.message}`;
|
||||
} finally {
|
||||
|
||||
Reference in new issue
Block a user