diff --git a/app.rb b/app.rb
index 3cdb4c2..1943d27 100644
--- a/app.rb
+++ b/app.rb
@@ -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
diff --git a/lib/maptool/can.rb b/lib/maptool/can.rb
index 08278bb..e063a16 100644
--- a/lib/maptool/can.rb
+++ b/lib/maptool/can.rb
@@ -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" },
diff --git a/lib/maptool/can_sdo.rb b/lib/maptool/can_sdo.rb
index 4a7273e..416e319 100644
--- a/lib/maptool/can_sdo.rb
+++ b/lib/maptool/can_sdo.rb
@@ -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
diff --git a/test/test_app.rb b/test/test_app.rb
index 5d9c071..3a6923f 100644
--- a/test/test_app.rb
+++ b/test/test_app.rb
@@ -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.
diff --git a/test/test_can_discovery.rb b/test/test_can_discovery.rb
index 50568bd..27b5cc7 100644
--- a/test/test_can_discovery.rb
+++ b/test/test_can_discovery.rb
@@ -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" })
diff --git a/views/can.erb b/views/can.erb
index b2afca4..b3e78b2 100644
--- a/views/can.erb
+++ b/views/can.erb
@@ -47,7 +47,7 @@
Nodes
-
+
Signals
@@ -97,6 +97,22 @@
document.querySelector(`#${id} tbody`).innerHTML = rows.length ? rows.join("") : `| ${empty} |
`;
}
+ // can.json's "actions" beside their node: one SDO write each (POST /api/can/actions/).
+ 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 ? `` : "").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 ? `${hex(n.emcy.code, 4)} reg ${hex(n.emcy.register, 2)} ${n.emcy.code === 0 ? "(reset)" : ""} · ${age(n.emcy.at)}` : "—";
- return `| ${nodeName(id)} | ${n.silent ? "silent" : esc(n.state || "no heartbeat")} | ${age(n.seen_at)} | ${emcy} | ${[...(roles[id] || [])].sort().map(esc).join(", ")} |
`;
- }), "No CANopen node heard yet.", 5);
+ return `| ${nodeName(id)} | ${n.silent ? "silent" : esc(n.state || "no heartbeat")} | ${age(n.seen_at)} | ${emcy} | ${[...(roles[id] || [])].sort().map(esc).join(", ")} | ${actionsHtml(data.actions, Number(id))} |
`;
+ }), "No CANopen node heard yet.", 6);
fill("signals", Object.entries(data.signals).sort().map(([name, s]) =>
`| ${esc(name)} | ${typeof s.value === "number" ? +s.value.toFixed(6) : esc(s.value)} | ${esc(s.unit)} | ${age(s.at)} |
`),
@@ -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 {