Files
maptool/views/can.erb
T
2026-11-30 20:42:04 +01:00

151 lines
9.6 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>CANopen diagnostics</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; }
.chg { background: color-mix(in srgb, #ffb300 calc(var(--fresh) * 70%), transparent); border-radius: 3px; }
</style>
</head>
<body>
<header>
<h1>CANopen diagnostics</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>
<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);
}
async function poll() {
const status = document.getElementById("status");
try {
const response = await fetch("/api/can", { 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());
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", () => last && render(last));
poll();
</script>
</body>
</html>