Files

342 lines
22 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 trace</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); --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: 8px; }
h1 { font-size: 1.2rem; margin: 0; }
#status { color: var(--muted); font-size: 0.85rem; } #status.bad { color: var(--bad); }
.bar { display: flex; flex-wrap: wrap; gap: 6px 12px; align-items: center; margin-bottom: 8px; font-size: 0.9rem; }
.bar label { display: inline-flex; gap: 4px; align-items: center; white-space: nowrap; }
input[type=search] { padding: 6px 8px; font-size: 0.9rem; width: 260px; max-width: 100%; box-sizing: border-box; }
select, button { padding: 6px 10px; font-size: 0.9rem; }
.types { display: flex; flex-wrap: wrap; gap: 4px; }
.types label { padding: 3px 8px; border: 1px solid var(--line); border-radius: 12px; cursor: pointer; }
.types input { margin: 0; }
#box { max-height: calc(100vh - 220px); overflow: auto; }
table { border-collapse: collapse; font-size: 0.85rem; }
th, td { padding: 3px 12px 3px 0; text-align: left; border-bottom: 1px solid var(--line); white-space: nowrap; }
thead th { position: sticky; top: 0; background: Canvas; color: var(--muted); font-weight: 500; cursor: pointer; user-select: none; }
thead th[data-dir]::after { content: " ▲"; } thead th[data-dir="-1"]::after { content: " ▼"; }
.num { font-variant-numeric: tabular-nums; text-align: right; }
code { font: 0.85rem ui-monospace, SFMono-Regular, Menlo, monospace; }
.empty { color: var(--muted); }
.legend { color: var(--muted); font-size: 0.8rem; } .legend span { margin-right: 8px; }
/* bytes colored by what they are (SDO: command, index, subindex, payload) */
.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; }
</style>
</head>
<body>
<%= erb :_debug_nav, layout: false %>
<header>
<h1>CAN trace</h1>
<span id="status"></span>
<span id="count" class="legend"></span>
</header>
<div class="bar">
<input id="text" type="search" placeholder="Filter: ID, data, from, meaning… (a, b = either)">
<label>Interface <select id="iface"><option value="">all</option></select></label>
<label>Node <select id="node"><option value="">all</option></select></label>
<label title="Hide frames with the same data as the last one of their ID"><input id="changes" type="checkbox"> only changes</label>
<button id="record" type="button">● Start</button> <button id="clear" type="button">Clear</button>
<button id="export-log" type="button" title="candump log: can-utils (canplayer, log2asc), SavvyCAN, python-can, Wireshark">Export .log</button>
<button id="export-csv" type="button" title="The frames shown (filter, order), decoded">Export CSV</button>
</div>
<div class="bar types" id="types"></div>
<details id="server" class="bar">
<summary>Recording on the server (MF4) <span id="server-state" class="legend"></span></summary>
<p><button id="server-toggle" type="button">● Record on the server</button>
<span class="legend">every interface, a .mf4 file each 5 min — asammdf with a DBC, CSS Electronics' tools; goes on with this page closed</span></p>
<table id="server-files"><tbody></tbody></table>
</details>
<div class="legend" style="margin-bottom: 6px"><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> · SDO objects named by <a href="/can/esphome.eds" download>esphome.eds</a> · click a column to sort</div>
<div id="box"><table id="trace"><thead><tr>
<th class="num" data-key="seq" data-dir="-1">#</th><th class="num" data-key="seq">Time</th><th class="num" data-key="dt">Δ ms</th><th class="num" data-key="dtId" title="Since the last frame of the same ID">Δ ID ms</th>
<th data-key="interface">Interface</th><th data-key="id">ID</th><th data-key="data">Data</th><th data-key="from">From</th><th>Byte 0</th><th data-key="note">Meaning</th>
</tr></thead><tbody></tbody></table></div>
<script>
// Every CAN frame as it came: GET /api/can?since=<seq> once a second
// (lib/maptool/can.rb's Store keeps the last 1000), each decoded by its
// CANopen role; filtered and sorted here. Records only between Start
// and Stop (no polling meanwhile).
const TRACE_MAX = 20000; // recorded at most: then it stops (export or clear)
const RENDER_MAX = 1000; // rows in the table (the filter and sort see all)
const POLL_MS = 500; // the server keeps 5000 frames: past ~10000 frames/s some get lost (counted)
const TYPES = ["NMT", "SYNC", "EMCY", "TIME", "TPDO", "RPDO", "SDO", "Heartbeat", "Other"];
const $ = (id) => document.getElementById(id);
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");
let trace = [], logSince = 0, recording = false, lost = 0, t0 = null, sortKey = "seq", sortDir = -1; // the newest on top
const lastOf = new Map(); // "iface:id" → the previous frame of that ID
const off = new Set(); // frame types hidden
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"];
// Object names: esphome-canopen's EDS (public/can/esphome.eds, loaded
// below) and its entity objects (lib/maptool/can_discovery.rb).
// ponytail: one EDS for every node; per node when they carry their own (0x1021)
const OD = {};
const META = { 1: "name", 3: "unit", 7: "min", 8: "max" };
function objectName(index, sub) {
const key = index.toString(16).padStart(4, "0");
const parent = OD[key], name = OD[`${key}sub${sub}`];
if (parent || name) return name && parent && !name.startsWith(parent) ? `${parent}: ${name}` : name || parent;
if (index === 0x3002 && sub === 1) return "TPDO layout hash";
if (index === 0x2001) return `entity ${sub} type`;
const n = (index - 0x2000) >> 4;
if (index >= 0x2010 && index <= 0x2ff0 && !(index & 0xf)) return `entity ${n} ${META[sub] || `metadata ${sub}`}`;
if (index >= 0x2011 && index <= 0x2ff1 && (index & 0xf) === 1) return `entity ${n} value`;
return "";
}
fetch("/can/esphome.eds").then((r) => (r.ok ? r.text() : "")).then((text) => {
let section = null;
for (const line of text.split(/\r?\n/)) {
const head = line.match(/^\[([0-9a-f]{4}(?:sub[0-9a-f]+)?)\]/i);
if (head) section = head[1].toLowerCase().replace(/sub([0-9a-f]+)/, (_, n) => `sub${parseInt(n, 16)}`);
else if (/^\[/.test(line)) section = null;
else if (section && line.startsWith("ParameterName=")) OD[section] = line.slice(14).trim();
}
});
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";
const index = b[1] | (b[2] << 8), name = objectName(index, b[3]);
note += ` ${hex(index, 4).slice(2)}:${b[3].toString(16).toUpperCase().padStart(2, "0")}${name ? ` (${name})` : ""}`;
}
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 };
}
const typeOf = (role) => !role ? "Other" : role.startsWith("sdo") ? "SDO" : role === "heartbeat" ? "Heartbeat" : role.replace(/\d$/, "").toUpperCase();
// A frame from the server, its decoding and what it's sorted and filtered by.
function add(f, prev) {
const [role, node] = canopenRole(f.id, f.extended);
const key = `${f.interface}:${f.id}`, before = lastOf.get(key);
Object.assign(f, decode(f), {
type: typeOf(role), node, cob: f.extended ? hex(f.id, 8) : hex(f.id, 3),
dt: prev ? (f.at - prev.at) * 1000 : null, dtId: before ? (f.at - before.at) * 1000 : null, same: before?.data === f.data,
});
lastOf.set(key, f);
if (!$("iface").querySelector(`option[value="${CSS.escape(f.interface)}"]`)) $("iface").add(new Option(f.interface, f.interface));
if (node != null && !$("node").querySelector(`option[value="${node}"]`)) {
const options = [...$("node").options].slice(1).concat(new Option(`${node} (${hex(node, 2)})`, node));
options.sort((a, b) => a.value - b.value).forEach((o) => $("node").add(o));
}
}
let lastRows = []; // filtered and sorted, for the CSV
function render() {
const terms = $("text").value.toLowerCase().split(",").map((t) => t.trim()).filter(Boolean);
const iface = $("iface").value, node = $("node").value, changes = $("changes").checked;
const rows = trace.filter((f) =>
!off.has(f.type) && (!iface || f.interface === iface) && (!node || String(f.node) === node) && (!changes || !f.same) &&
(!terms.length || terms.some((t) => [f.cob, f.data, f.from, f.note, f.type].join(" ").toLowerCase().includes(t))));
if (sortKey === "seq") {
if (sortDir === -1) rows.reverse();
} else {
rows.sort((a, b) => {
const x = a[sortKey], y = b[sortKey];
const c = x == null ? 1 : y == null ? -1 : typeof x === "number" ? x - y : String(x).localeCompare(String(y));
return c * sortDir || a.seq - b.seq;
});
}
const ms = (v) => (v == null ? "" : v.toFixed(1));
const shown = rows.length <= RENDER_MAX ? rows : sortKey === "seq" && sortDir === 1 ? rows.slice(-RENDER_MAX) : rows.slice(0, RENDER_MAX);
$("trace").tBodies[0].innerHTML = shown.length ? shown.map((f) => {
const data = f.b.map((x, i) => `<span class="${f.cls[i]}">${x.toString(16).toUpperCase().padStart(2, "0")}</span>`).join(" ");
return `<tr><td class="num">${f.seq}</td><td class="num">${(f.at - t0).toFixed(4)}</td><td class="num">${ms(f.dt)}</td><td class="num">${ms(f.dtId)}</td><td>${esc(f.interface)}</td><td><code>${f.cob}</code>${f.extended ? " ext" : ""}</td><td><code>${data}</code></td><td>${esc(f.from)}</td><td><code>${f.bits}</code></td><td>${esc(f.note)}</td></tr>`;
}).join("") : `<tr><td class="empty" colspan="10">${trace.length ? "No frame matches." : "No frame yet."}</td></tr>`;
$("count").textContent = !trace.length ? "" : (rows.length > shown.length ? `showing ${shown.length} of ${rows.length} matching, ` : `${rows.length} matching of `) +
`${trace.length} recorded${lost ? ` · ${lost} lost (bus faster than the polling)` : ""}`;
lastRows = rows;
}
async function fetchLog(since) {
const response = await fetch(`/api/can?since=${since}`, { cache: "no-store" });
if (response.status === 401) throw new Error("not logged in — log in on the map first");
if (!response.ok) throw new Error(`HTTP ${response.status}`);
const data = await response.json();
if (!data.available) throw new Error("CAN is off: no data/can.json on this server");
return data;
}
async function poll() {
if (!recording) return;
const status = $("status");
try {
const data = await fetchLog(logSince);
if (data.log_seq < logSince) logSince = 0; // the server restarted: its frames from the start
if (data.log.length && logSince && data.log[0].seq > logSince + 1) lost += data.log[0].seq - logSince - 1;
status.className = "";
status.textContent = `● recording · ${new Date().toLocaleTimeString()}`;
if (data.log.length) {
t0 ??= data.log[0].at;
for (const f of data.log.slice(0, TRACE_MAX - trace.length)) { add(f, trace.at(-1)); trace.push(f); }
logSince = data.log.at(-1).seq;
if (trace.length >= TRACE_MAX) { stop(); status.textContent = `stopped: ${TRACE_MAX} frames recorded — export or clear`; }
render();
}
} catch (e) {
status.className = "bad";
status.textContent = `can't record: ${e.message}`;
} finally {
if (recording) setTimeout(poll, POLL_MS);
}
}
// From now on: the server's frames after its latest.
async function start() {
try {
logSince = (await fetchLog(Number.MAX_SAFE_INTEGER)).log_seq;
} catch (e) {
$("status").className = "bad";
$("status").textContent = `can't record: ${e.message}`;
return;
}
recording = true;
$("record").textContent = "■ Stop";
poll();
}
function stop() {
recording = false;
$("record").textContent = "● Start";
$("status").textContent = "stopped";
}
function download(name, text, type) {
const a = document.createElement("a");
a.href = URL.createObjectURL(new Blob([text], { type }));
a.download = name;
a.click();
setTimeout(() => URL.revokeObjectURL(a.href), 1000);
}
const fileName = (ext) => `can-trace-${new Date(trace[0].at * 1000).toISOString().slice(0, 19).replace(/[-:]/g, "").replace("T", "-")}.${ext}`;
const csvField = (v) => (/[",\n]/.test(String(v ?? "")) ? `"${String(v).replace(/"/g, '""')}"` : String(v ?? ""));
// The server's recorder (GET/POST/DELETE /api/can/recording), every 5 s.
let server = null;
const size = (b) => (b > 1e6 ? `${(b / 1e6).toFixed(1)} MB` : `${Math.ceil(b / 1e3)} kB`);
async function pollServer() {
try {
const response = await fetch("/api/can/recording", { cache: "no-store" });
if (!response.ok) throw new Error(`HTTP ${response.status}`);
server = await response.json();
$("server-state").textContent = !server.available ? "· CAN is off on this server" : server.running
? `· ● recording since ${new Date(server.started_at * 1000).toLocaleTimeString()}` : server.error ? `· ${server.error}` : "· stopped";
$("server-toggle").textContent = server.running ? "■ Stop recording on the server" : "● Record on the server";
$("server-toggle").disabled = !server.available;
$("server-files").tBodies[0].innerHTML = server.files.length ? server.files.map((f) =>
`<tr><td><a href="/api/can/recordings/${encodeURIComponent(f.name)}" download>${esc(f.name)}</a></td><td class="num">${size(f.size)}</td><td>${new Date(f.at * 1000).toLocaleString()}</td></tr>`).join("")
: `<tr><td class="empty">No recording yet.</td></tr>`;
} catch (e) {
$("server-state").textContent = `· can't reach the server: ${e.message}`;
}
}
$("server-toggle").addEventListener("click", async () => {
$("server-toggle").disabled = true;
const response = await fetch("/api/can/recording", { method: server?.running ? "DELETE" : "POST" });
if (!response.ok) $("server-state").textContent = `· ${(await response.json().catch(() => ({}))).error || `HTTP ${response.status}`}`;
else await pollServer();
$("server-toggle").disabled = false;
});
pollServer();
setInterval(pollServer, 5000);
$("record").addEventListener("click", () => (recording ? stop() : start()));
// candump -l's format: every recorded frame, in order
$("export-log").addEventListener("click", () => trace.length && download(fileName("log"),
trace.map((f) => `(${f.at.toFixed(6)}) ${f.interface} ${f.extended ? f.id.toString(16).toUpperCase().padStart(8, "0") : f.id.toString(16).toUpperCase().padStart(3, "0")}#${f.data.toUpperCase()}\n`).join(""), "text/plain"));
$("export-csv").addEventListener("click", () => trace.length && download(fileName("csv"),
[["seq", "time_s", "unix_time", "dt_ms", "dt_id_ms", "interface", "id", "extended", "dlc", "data", "type", "node", "from", "meaning"].join(",")].concat(lastRows.map((f) =>
[f.seq, (f.at - t0).toFixed(6), f.at.toFixed(6), f.dt?.toFixed(3), f.dtId?.toFixed(3), f.interface, f.cob, f.extended, f.b.length, f.b.map((x) => x.toString(16).toUpperCase().padStart(2, "0")).join(" "), f.type, f.node, f.from, f.note].map(csvField).join(","))).join("\n") + "\n", "text/csv"));
$("types").innerHTML = TYPES.map((t) => `<label><input type="checkbox" value="${t}" checked> ${t}</label>`).join("");
$("types").addEventListener("change", (e) => { e.target.checked ? off.delete(e.target.value) : off.add(e.target.value); render(); });
for (const id of ["text", "iface", "node", "changes"]) $(id).addEventListener("input", render);
$("trace").tHead.addEventListener("click", (e) => {
const th = e.target.closest("th[data-key]");
if (!th) return;
sortDir = th.dataset.key === sortKey && th.hasAttribute("data-dir") ? -sortDir : 1;
sortKey = th.dataset.key;
for (const h of $("trace").tHead.querySelectorAll("th")) h.removeAttribute("data-dir");
th.dataset.dir = sortDir;
render();
});
$("clear").addEventListener("click", () => { trace = []; t0 = null; lost = 0; lastOf.clear(); render(); });
render();
$("status").textContent = "stopped — Start records the frames from then on";
</script>
</body>
</html>