Files
maptool/views/can.erb
T

270 lines
18 KiB
ERB

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="color-scheme" content="light dark">
<title>CAN analyzer</title>
<link rel="icon" href="/icons/icon.svg" type="image/svg+xml">
<style>
:root { color-scheme: light dark; --muted: GrayText; --line: color-mix(in srgb, CanvasText 15%, transparent); --ok: #2e7d32; --warn: #ef6c00; --bad: #c62828; }
body { margin: 0; padding: 16px; background: Canvas; color: CanvasText; font: 15px/1.4 -apple-system, "Segoe UI", Roboto, Helvetica, Arial, sans-serif; }
header { display: flex; flex-wrap: wrap; gap: 8px 16px; align-items: baseline; margin-bottom: 12px; }
h1 { font-size: 1.2rem; margin: 0; }
h2 { font-size: 0.8rem; font-weight: 600; color: var(--muted); text-transform: uppercase; letter-spacing: 0.05em; margin: 20px 0 6px; }
#status { color: var(--muted); font-size: 0.85rem; } #status.bad { color: var(--bad); }
.scroll { overflow-x: auto; }
table { border-collapse: collapse; font-size: 0.85rem; }
th, td { padding: 6px 12px 6px 0; text-align: left; border-bottom: 1px solid var(--line); white-space: nowrap; }
th { color: var(--muted); font-weight: 500; }
.num { font-variant-numeric: tabular-nums; text-align: right; }
code { font: 0.85rem ui-monospace, SFMono-Regular, Menlo, monospace; }
.ok { color: var(--ok); } .warn { color: var(--warn); } .bad { color: var(--bad); }
.stale td { opacity: 0.5; }
input { padding: 6px 8px; font-size: 0.9rem; width: 220px; max-width: 100%; box-sizing: border-box; }
.empty { color: var(--muted); font-size: 0.85rem; }
/* side by side when there's room, the frames under the rest on a phone */
.cols { display: grid; gap: 0 32px; }
.cols > div { min-width: 0; }
/* the frames get at least 560px (their data in view), the left column
the rest up to its tables' width — each scrolls sideways if narrower */
@media (min-width: 900px) { .cols { grid-template-columns: minmax(0, max-content) minmax(560px, 1fr); } }
/* a byte that just changed, fading out over CHANGED_FOR */
/* a fixed width: the column doesn't jump when a node goes "silent" */
#nodes th:nth-child(2), #nodes td:nth-child(2) { width: 9em; min-width: 9em; }
/* the trace: bytes colored by what they are (SDO: command, index, subindex, payload) */
#trace-box { max-height: 70vh; overflow: auto; }
#trace td { padding-top: 3px; padding-bottom: 3px; }
#trace thead th { position: sticky; top: 0; background: Canvas; }
.b-cmd { color: #e53935; } .b-idx { color: #1e88e5; } .b-sub { color: #64b5f6; } .b-pay { color: #00a37a; } .b-pad { color: color-mix(in srgb, CanvasText 30%, transparent); }
.bits-cs { color: #a020f0; } .bits-x { color: color-mix(in srgb, CanvasText 30%, transparent); } .bits-n { color: #5a3fc0; font-weight: 600; } .bits-es { color: #9b8fd0; }
.legend { color: var(--muted); font-size: 0.8rem; font-weight: 400; text-transform: none; letter-spacing: 0; }
.legend span { margin-right: 8px; }
button { padding: 6px 10px; font-size: 0.9rem; }
.chg { background: color-mix(in srgb, #ffb300 calc(var(--fresh) * 70%), transparent); border-radius: 3px; }
</style>
</head>
<body>
<%= erb :_debug_nav, layout: false %>
<header>
<h1>CAN analyzer</h1>
<span id="status">loading…</span>
</header>
<div class="cols"><div>
<h2>Interfaces</h2>
<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>
<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>
</div><div>
<h2>Frames <input id="filter" type="search" placeholder="Filter id, role, node…"></h2>
<div class="scroll"><table id="frames"><thead><tr><th>Interface</th><th>COB-ID</th><th>Role</th><th>Node</th><th class="num">Count</th><th class="num">Rate</th><th>Data</th><th>Last</th></tr></thead><tbody></tbody></table></div>
</div></div>
<h2>Trace <button id="pause" type="button">Pause</button> <button id="clear" type="button">Clear</button>
<span class="legend"><span class="b-cmd">command</span><span class="b-idx">OD index</span><span class="b-sub">subindex</span><span class="b-pay">payload</span><span class="b-pad">unused</span>
· byte 0: <span class="bits-cs">ccs/scs</span> <span class="bits-x">t</span> <span class="bits-n">n</span> <span class="bits-es">e s</span> · the frame filter applies</span></h2>
<div id="trace-box" class="scroll"><table id="trace"><thead><tr><th class="num">#</th><th class="num">Time</th><th class="num">Δ ms</th><th>Interface</th><th>ID</th><th>Data</th><th>From</th><th>Byte 0</th><th>Meaning</th></tr></thead><tbody></tbody></table></div>
<script>
// Polls GET /api/can (lib/maptool/can.rb's Store) once a second.
const STALE_AFTER = 10; // s without a frame: greyed out
const CHANGED_FOR = 3; // s a changed byte stays highlighted
const seen = new Map(); // "iface:cob" → { bytes: [..], changedAt: [..] }
// The frame's bytes, each one that changed in the last CHANGED_FOR s
// highlighted (fading), its tooltip saying which bits and from what.
function dataHtml(f, key, now) {
const bytes = (f.data.match(/../g) || []).map((b) => parseInt(b, 16));
const before = seen.get(key);
const changedAt = bytes.map((b, i) => (before && before.bytes[i] !== undefined && before.bytes[i] !== b ? now : before?.changedAt[i] ?? 0));
const from = bytes.map((b, i) => (before && before.bytes[i] !== b ? before.bytes[i] : before?.from?.[i]));
seen.set(key, { bytes, changedAt, from });
return bytes.map((b, i) => {
const hex = b.toString(16).toUpperCase().padStart(2, "0");
const age = now - changedAt[i];
if (!changedAt[i] || age > CHANGED_FOR || from[i] === undefined) return hex;
const bits = [...Array(8).keys()].filter((bit) => ((b ^ from[i]) >> bit) & 1);
const title = `byte ${i}: ${from[i].toString(2).padStart(8, "0")} → ${b.toString(2).padStart(8, "0")} (bit ${bits.join(", ")})`;
return `<span class="chg" style="--fresh:${(1 - age / CHANGED_FOR).toFixed(2)}" title="${title}">${hex}</span>`;
}).join(" ");
}
const esc = (s) => String(s ?? "").replace(/[&<>"]/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;" })[c]);
const hex = (n, width) => "0x" + n.toString(16).toUpperCase().padStart(width, "0");
const nodeName = (n) => `${n} <code>${hex(Number(n), 2)}</code>`;
let last = null;
let clockOffset = 0; // server time minus ours, so ages don't depend on the tablet's clock
function age(at) {
if (!at) return "—";
const s = Date.now() / 1000 + clockOffset - at;
return s < 1 ? "now" : s < 60 ? `${Math.round(s)} s ago` : s < 3600 ? `${Math.round(s / 60)} min ago` : `${Math.round(s / 3600)} h ago`;
}
const stale = (at) => !at || Date.now() / 1000 + clockOffset - at > STALE_AFTER;
function fill(id, rows, empty, cols) {
document.querySelector(`#${id} tbody`).innerHTML = rows.length ? rows.join("") : `<tr><td class="empty" colspan="${cols}">${empty}</td></tr>`;
}
const STATE_CLASS = { operational: "ok", "pre-operational": "warn", stopped: "bad", "boot-up": "warn" };
function render(data) {
fill("interfaces", Object.entries(data.interfaces).map(([name, i]) =>
`<tr><td>${esc(name)}</td><td class="${i.up ? "ok" : "bad"}">${i.up ? "up" : "down"}</td><td class="num">${i.frames}</td><td>${age(i.last_frame_at)}</td><td>${esc(i.error)}</td></tr>`),
data.available ? "No interface read yet." : "CAN is off: no data/can.json on this server.", 5);
const roles = {};
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);
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>`),
"No signal decoded yet (signals in data/can.json).", 4);
const filter = document.getElementById("filter").value.trim().toLowerCase();
const frames = data.frames
.map((f) => ({ ...f, cob: f.extended ? hex(f.id, 8) : hex(f.id, 3) }))
.filter((f) => !filter || [f.interface, f.cob, f.role, f.node].join(" ").toLowerCase().includes(filter))
.sort((a, b) => a.interface.localeCompare(b.interface) || a.id - b.id);
const now = Date.now() / 1000;
fill("frames", frames.map((f) =>
`<tr class="${stale(f.at) ? "stale" : ""}"><td>${esc(f.interface)}</td><td><code>${f.cob}</code>${f.extended ? " ext" : ""}</td><td>${esc(f.role || "")}</td><td>${f.node ?? ""}</td><td class="num">${f.count}</td><td class="num">${f.interval ? (1 / f.interval).toFixed(f.interval > 1 ? 2 : 1) + " Hz" : ""}</td><td><code>${dataHtml(f, `${f.interface}:${f.cob}`, now)}</code></td><td>${age(f.at)}</td></tr>`),
filter ? "No frame matches." : "No frame yet.", 8);
}
// The trace: every frame as it came (the server keeps the last 1000),
// each decoded by its CANopen role.
const TRACE_MAX = 1000;
let trace = [], logSince = 0, paused = false, t0 = null;
function canopenRole(id, ext) { // lib/maptool/can.rb's Can.canopen_role
if (ext) return [null, null];
const node = id & 0x7f, fn = id >> 7;
if (fn === 0) return id ? [null, null] : ["nmt", null];
if (fn === 1) return node ? ["emcy", node] : ["sync", null];
if (fn === 2) return ["time", null];
if (fn >= 3 && fn <= 10) return [`${fn % 2 ? "tpdo" : "rpdo"}${Math.floor((fn - 1) / 2)}`, node];
return [{ 0xb: "sdo_tx", 0xc: "sdo_rx", 0xe: "heartbeat" }[fn] || null, node];
}
const le = (b) => b.reduceRight((v, x) => v * 256 + x, 0);
const NMT = { 0x01: "start", 0x02: "stop", 0x80: "enter pre-operational", 0x81: "reset node", 0x82: "reset communication" };
const HB = { 0x00: "boot-up", 0x04: "stopped", 0x05: "operational", 0x7f: "pre-operational" };
const ABORT = { 0x05040000: "timeout", 0x05040001: "bad command", 0x06010000: "unsupported access", 0x06010001: "write-only", 0x06010002: "read-only",
0x06020000: "no such object", 0x06070010: "length mismatch", 0x06090011: "no such subindex", 0x06090030: "value out of range",
0x08000000: "general error", 0x08000020: "can't store", 0x08000022: "device state" };
const SDO_CLIENT = ["download segment", "download init request", "upload init request", "upload segment request", "abort", "block upload", "block download"];
const SDO_SERVER = ["upload segment", "download segment response", "upload init response", "download init response", "abort", "block download", "block upload"];
// → { cls: a class per byte, from, bits (byte 0, SDO), note }
function decode(f) {
const b = (f.data.match(/../g) || []).map((x) => parseInt(x, 16));
const [role, node] = canopenRole(f.id, f.extended);
const cls = b.map(() => "b-pay");
const pad = (from) => { for (let i = from; i < b.length; i++) cls[i] = "b-pad"; };
const value = (from, to) => { const v = le(b.slice(from, to)); return `${hex(v, 2 * (to - from))} = ${v}`; };
let from = node != null ? `node ${node}` : "", bits = "", note = role || (f.extended ? "extended" : "");
if (role === "nmt") {
from = "master"; cls[0] = "b-cmd";
note = `NMT ${NMT[b[0]] || hex(b[0] ?? 0, 2)} → ${b[1] ? `node ${b[1]}` : "all nodes"}`;
} else if (role === "heartbeat") {
note = `heartbeat: ${HB[b[0] & 0x7f] || "unknown"}`;
} else if (role === "emcy" && b.length >= 3) {
cls[0] = cls[1] = "b-cmd"; cls[2] = "b-idx";
const code = b[0] | (b[1] << 8);
note = code ? `EMCY ${hex(code, 4)}, error register ${hex(b[2], 2)}` : "EMCY: errors reset";
} else if (role === "sync") {
from = "master"; note = b.length ? `SYNC, counter ${b[0]}` : "SYNC";
} else if (role?.startsWith("rpdo")) {
from = `master → ${node}`; note = role.toUpperCase();
} else if (role?.startsWith("tpdo")) {
note = role.toUpperCase();
} else if (role === "sdo_rx" || role === "sdo_tx") {
const client = role === "sdo_rx", cs = b[0] >> 5;
from = client ? `client → ${node}` : `server ${node}`;
cls.fill("b-pad"); cls[0] = "b-cmd";
const bin = b[0].toString(2).padStart(8, "0");
const segment = cs === 0; // a data segment, either way
const withIndex = client ? [1, 2, 4].includes(cs) : [2, 3, 4].includes(cs);
bits = segment
? `<span class="bits-cs">${bin.slice(0, 3)}</span><span class="bits-x">${bin[3]}</span><span class="bits-n">${bin.slice(4, 7)}</span><span class="bits-es">${bin[7]}</span>`
: `<span class="bits-cs">${bin.slice(0, 3)}</span><span class="bits-x">${bin[3]}</span><span class="bits-n">${bin.slice(4, 6)}</span><span class="bits-es">${bin.slice(6)}</span>`;
note = (client ? SDO_CLIENT : SDO_SERVER)[cs] || `command ${cs}`;
if (withIndex && b.length >= 4) {
cls[1] = cls[2] = "b-idx"; cls[3] = "b-sub";
note += ` ${hex(b[1] | (b[2] << 8), 4).slice(2)}:${b[3].toString(16).toUpperCase().padStart(2, "0")}`;
}
if (cs === 4 && b.length === 8) {
for (let i = 4; i < 8; i++) cls[i] = "b-pay";
const code = le(b.slice(4)); note += ` ${hex(code, 8)}${ABORT[code] ? ` (${ABORT[code]})` : ""}`;
} else if ((client && cs === 1) || (!client && cs === 2)) { // init with data or size
const n = (b[0] >> 2) & 3, e = (b[0] >> 1) & 1, s = b[0] & 1;
if (e) { const end = s ? 8 - n : 8; for (let i = 4; i < end; i++) cls[i] = "b-pay"; note += `, expedited ${end - 4} B: ${value(4, end)}`; }
else if (s) { for (let i = 4; i < 8; i++) cls[i] = "b-pay"; note += `, segmented, ${le(b.slice(4, 8))} B`; }
} else if (segment) {
const n = (b[0] >> 1) & 7, end = 8 - n;
for (let i = 1; i < end; i++) cls[i] = "b-pay";
note += `, toggle ${(b[0] >> 4) & 1}, ${end - 1} B${b[0] & 1 ? ", last" : ""}`;
}
}
return { b, cls, from, bits, note };
}
function renderTrace() {
const box = document.getElementById("trace-box");
const atBottom = box.scrollHeight - box.scrollTop - box.clientHeight < 24;
const filter = document.getElementById("filter").value.trim().toLowerCase();
let prev = null;
const rows = [];
for (const f of trace) {
const d = f.decoded ||= decode(f);
const cob = f.extended ? hex(f.id, 8) : hex(f.id, 3);
const dt = prev ? ((f.at - prev.at) * 1000).toFixed(1) : "";
prev = f;
if (filter && ![f.interface, cob, d.from, d.note].join(" ").toLowerCase().includes(filter)) continue;
const data = d.b.map((x, i) => `<span class="${d.cls[i]}">${x.toString(16).toUpperCase().padStart(2, "0")}</span>`).join(" ");
rows.push(`<tr><td class="num">${f.seq}</td><td class="num">${(f.at - t0).toFixed(4)}</td><td class="num">${dt}</td><td>${esc(f.interface)}</td><td><code>${cob}</code></td><td><code>${data}</code></td><td>${esc(d.from)}</td><td><code>${d.bits}</code></td><td>${esc(d.note)}</td></tr>`);
}
fill("trace", rows, trace.length ? "No frame matches." : "No frame yet.", 9);
if (atBottom) box.scrollTop = box.scrollHeight;
}
async function poll() {
const status = document.getElementById("status");
try {
const response = await fetch(paused ? "/api/can" : `/api/can?since=${logSince}`, { cache: "no-store" });
if (response.status === 401) { status.textContent = "Not logged in — log in on the map first."; return; }
if (!response.ok) throw new Error(`HTTP ${response.status}`);
const date = Date.parse(response.headers.get("Date"));
if (date) clockOffset = Math.abs(date / 1000 - Date.now() / 1000) > 2 ? date / 1000 - Date.now() / 1000 : 0;
render(last = await response.json());
if (last.log?.length) {
logSince = last.log.at(-1).seq;
t0 ??= last.log[0].at;
trace = trace.concat(last.log).slice(-TRACE_MAX);
renderTrace();
}
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()}`;
} catch (e) {
status.textContent = `can't reach the server: ${e.message}`;
} finally {
setTimeout(poll, 1000);
}
}
document.getElementById("filter").addEventListener("input", () => { if (last) render(last); renderTrace(); });
document.getElementById("pause").addEventListener("click", (e) => { paused = !paused; e.target.textContent = paused ? "Resume" : "Pause"; });
document.getElementById("clear").addEventListener("click", () => { trace = []; t0 = null; renderTrace(); });
poll();
</script>
</body>
</html>