310 lines
10 KiB
JavaScript
310 lines
10 KiB
JavaScript
const grid = document.getElementById("printer-grid");
|
|
const refresh = document.getElementById("refresh");
|
|
|
|
async function loadPrinters() {
|
|
grid.innerHTML = '<p class="empty-state">Loading printers...</p>';
|
|
|
|
const response = await fetch("/api/printers", { credentials: "same-origin" });
|
|
if (response.status === 401) {
|
|
window.location.href = "/login";
|
|
return;
|
|
}
|
|
if (!response.ok) {
|
|
grid.innerHTML = '<p class="empty-state">Unable to load printers.</p>';
|
|
return;
|
|
}
|
|
|
|
const data = await response.json();
|
|
const printers = data.printers || [];
|
|
if (printers.length === 0) {
|
|
grid.innerHTML = '<p class="empty-state">No agents are connected.</p>';
|
|
return;
|
|
}
|
|
|
|
grid.innerHTML = printers.map(renderPrinter).join("");
|
|
}
|
|
|
|
function renderPrinter(printer) {
|
|
const health = printer.health || {};
|
|
const settings = printer.settings || {};
|
|
const session = window.__KA_SESSION__ || {};
|
|
const reachable = health.moonraker_reachable === true;
|
|
const state = health.moonraker_state || "unknown";
|
|
const message = health.moonraker_message || "No status message yet.";
|
|
const checked = health.checked_at_unix ? relativeTime(health.checked_at_unix) : "Waiting for heartbeat";
|
|
const uiReachable = health.ui_reachable === true;
|
|
const label = settings.display_name || printer.printer_id;
|
|
const camera = (health.cameras || []).find((item) => item.has_snapshot === true);
|
|
const mmuMaterials = formatMmuMaterialsHtml(health.print_status);
|
|
const temperatureSummary = formatTemperatureSummary(health.print_status);
|
|
const thumbnail = camera
|
|
? `<img class="printer-thumb" src="/p/${encodeURIComponent(printer.printer_id)}/camera/${encodeURIComponent(camera.name)}/snapshot?t=${Date.now()}" alt="${escapeHTML(printer.printer_id)} camera snapshot">`
|
|
: '<div class="printer-thumb printer-thumb-empty">No camera</div>';
|
|
|
|
return `
|
|
<article class="printer-card ${reachable ? "healthy" : "unhealthy"}">
|
|
${thumbnail}
|
|
<div class="printer-card-header">
|
|
<div>
|
|
<span class="status-pill ${reachable ? "ok" : "warn"}">${reachable ? "Reachable" : "Not reachable"}</span>
|
|
<h2>${escapeHTML(label)}</h2>
|
|
${label !== printer.printer_id ? `<p class="panel-subtitle">${escapeHTML(printer.printer_id)}</p>` : ""}
|
|
</div>
|
|
</div>
|
|
<dl class="printer-facts">
|
|
<div>
|
|
<dt>Agent</dt>
|
|
<dd>${printer.connected ? "Connected" : "Disconnected"}</dd>
|
|
</div>
|
|
<div>
|
|
<dt>Moonraker</dt>
|
|
<dd>${escapeHTML(state)}</dd>
|
|
</div>
|
|
<div>
|
|
<dt>Message</dt>
|
|
<dd>${escapeHTML(message)}</dd>
|
|
</div>
|
|
<div>
|
|
<dt>Last heartbeat</dt>
|
|
<dd>${escapeHTML(checked)}</dd>
|
|
</div>
|
|
${temperatureSummary ? `
|
|
<div>
|
|
<dt>Temps</dt>
|
|
<dd class="temperature-summary">${escapeHTML(temperatureSummary)}</dd>
|
|
</div>` : ""}
|
|
${mmuMaterials ? `
|
|
<div>
|
|
<dt>MMU materials</dt>
|
|
<dd class="mmu-materials-value">${mmuMaterials}</dd>
|
|
</div>` : ""}
|
|
</dl>
|
|
<div class="card-actions">
|
|
<a class="button primary" href="/printers/${encodeURIComponent(printer.printer_id)}">Open</a>
|
|
${session.is_admin ? `<a class="button secondary" href="/printers/${encodeURIComponent(printer.printer_id)}/settings">Settings</a>` : ""}
|
|
<a class="button secondary ${uiReachable ? "" : "disabled"}" href="${uiReachable ? `/printers/${encodeURIComponent(printer.printer_id)}/ui/` : "#"}" ${uiReachable ? "" : 'aria-disabled="true"'}>${uiReachable ? "Open Printer UI" : "UI unavailable"}</a>
|
|
<a class="button secondary" href="/api/printers/${encodeURIComponent(printer.printer_id)}/health">Health JSON</a>
|
|
<a class="button secondary" href="/p/${encodeURIComponent(printer.printer_id)}/moonraker/printer/info">Printer Info</a>
|
|
</div>
|
|
</article>
|
|
`;
|
|
}
|
|
|
|
function relativeTime(unixSeconds) {
|
|
const seconds = Math.max(0, Math.floor(Date.now() / 1000) - unixSeconds);
|
|
if (seconds < 5) {
|
|
return "just now";
|
|
}
|
|
if (seconds < 60) {
|
|
return `${seconds}s ago`;
|
|
}
|
|
const minutes = Math.floor(seconds / 60);
|
|
if (minutes < 60) {
|
|
return `${minutes}m ago`;
|
|
}
|
|
const hours = Math.floor(minutes / 60);
|
|
return `${hours}h ago`;
|
|
}
|
|
|
|
function escapeHTML(value) {
|
|
return String(value)
|
|
.replaceAll("&", "&")
|
|
.replaceAll("<", "<")
|
|
.replaceAll(">", ">")
|
|
.replaceAll('"', """)
|
|
.replaceAll("'", "'");
|
|
}
|
|
|
|
function formatMmuMaterialsHtml(printStatus) {
|
|
if (!printStatus || typeof printStatus !== "object") {
|
|
return "";
|
|
}
|
|
const state = collectMmuMaterialState(printStatus);
|
|
if (!state.visible) {
|
|
return "";
|
|
}
|
|
if (state.disabled) {
|
|
return `<span class="mmu-material-chip mmu-disabled"><span class="mmu-material-chip-swatch"></span><span class="mmu-material-chip-text">${escapeHTML(state.label)}: disabled</span></span>`;
|
|
}
|
|
if (state.rows.length === 0) {
|
|
return `<span class="mmu-material-chip"><span class="mmu-material-chip-swatch"></span><span class="mmu-material-chip-text">${escapeHTML(state.label)}: enabled</span></span>`;
|
|
}
|
|
return [
|
|
...state.rows.map((row) => mmuMaterialRowHtml(row)),
|
|
].join("");
|
|
}
|
|
|
|
function collectMmuMaterialState(printStatus) {
|
|
const mmu = printStatus.moonraker_status && printStatus.moonraker_status.mmu;
|
|
if (!mmu || typeof mmu !== "object" || !Object.prototype.hasOwnProperty.call(mmu, "enabled")) {
|
|
return { visible: false, disabled: false, label: "MMU", rows: [] };
|
|
}
|
|
const machine = printStatus.moonraker_status && printStatus.moonraker_status.mmu_machine;
|
|
const enabled = isTruthyMetadataValue(mmu.enabled);
|
|
const label = machine?.unit_0?.name || "MMU";
|
|
if (!enabled) {
|
|
return { visible: true, disabled: true, label, rows: [] };
|
|
}
|
|
const names = normalizeMetadataList(mmu.gate_filament_name);
|
|
const materials = normalizeMetadataList(mmu.gate_material);
|
|
const colors = normalizeMetadataList(mmu.gate_color);
|
|
const count = Math.max(names.length, materials.length, colors.length, Number(mmu.num_gates || 0));
|
|
if (count === 0) {
|
|
return { visible: true, disabled: false, label, rows: [{ label, value: "Enabled", color: "" }] };
|
|
}
|
|
return {
|
|
visible: true,
|
|
disabled: false,
|
|
label,
|
|
rows: Array.from({ length: count }, (_, index) => {
|
|
const parts = [];
|
|
let color = "";
|
|
if (names[index] && names[index] !== "Unknown") {
|
|
parts.push(String(names[index]));
|
|
}
|
|
if (materials[index] && materials[index] !== names[index]) {
|
|
parts.push(`(${String(materials[index])})`);
|
|
}
|
|
if (colors[index]) {
|
|
color = String(colors[index]).replace(/[^0-9a-fA-F]/g, "");
|
|
}
|
|
return {
|
|
label: `Gate ${index + 1}`,
|
|
value: parts.join(" ") || "Unknown material",
|
|
color,
|
|
};
|
|
}),
|
|
};
|
|
}
|
|
|
|
function normalizeMetadataList(value) {
|
|
if (Array.isArray(value)) {
|
|
return value.filter((item) => item !== null && item !== undefined && item !== "");
|
|
}
|
|
if (value === null || value === undefined || value === "") {
|
|
return [];
|
|
}
|
|
return [value];
|
|
}
|
|
|
|
function isTruthyMetadataValue(value) {
|
|
if (Array.isArray(value)) {
|
|
return value.length > 0;
|
|
}
|
|
if (typeof value === "string") {
|
|
const normalized = value.trim().toLowerCase();
|
|
return normalized === "1" || normalized === "true" || normalized === "yes";
|
|
}
|
|
return Boolean(value);
|
|
}
|
|
|
|
function mmuMaterialRowHtml(row) {
|
|
const label = escapeHTML(row.label);
|
|
const value = row.value ? escapeHTML(row.value) : "";
|
|
const color = row.color ? mmuNormalizeHexColor(row.color) : "";
|
|
const swatchStyle = color ? ` style="--mmu-swatch:${escapeHTML(color)}"` : "";
|
|
return `<span class="mmu-material-chip"${swatchStyle}><span class="mmu-material-chip-swatch"></span><span class="mmu-material-chip-text"><strong>${label}</strong>${value ? ` ${value}` : ""}</span></span>`;
|
|
}
|
|
|
|
function mmuNormalizeHexColor(value) {
|
|
const raw = String(value || "").trim().replace(/[^0-9a-fA-F]/g, "");
|
|
if (raw.length === 8) {
|
|
return `#${raw.slice(0, 6)}`;
|
|
}
|
|
if (raw.length === 6) {
|
|
return `#${raw}`;
|
|
}
|
|
if (raw.length === 3) {
|
|
return `#${raw.split("").map((ch) => ch + ch).join("")}`;
|
|
}
|
|
return "";
|
|
}
|
|
|
|
function formatTemperatureSummary(printStatus) {
|
|
const state = collectTemperatureState(printStatus);
|
|
if (!state.visible) {
|
|
return "";
|
|
}
|
|
return state.rows.map((row) => `${row.label} ${row.value}`).join(" · ");
|
|
}
|
|
|
|
function collectTemperatureState(printStatus) {
|
|
const status = printStatus && printStatus.moonraker_status;
|
|
if (!status || typeof status !== "object") {
|
|
return { visible: false, rows: [] };
|
|
}
|
|
const rows = [];
|
|
const seen = new Set();
|
|
const add = (key, label) => {
|
|
if (!Object.prototype.hasOwnProperty.call(status, key)) {
|
|
return;
|
|
}
|
|
const sensor = status[key];
|
|
if (!sensor || typeof sensor !== "object") {
|
|
return;
|
|
}
|
|
const reading = formatTemperatureReading(sensor);
|
|
if (!reading) {
|
|
return;
|
|
}
|
|
rows.push({ label, value: reading });
|
|
seen.add(key);
|
|
};
|
|
add("extruder", "Hotend");
|
|
add("heater_bed", "Bed");
|
|
add("temperature_sensor chamber", "Chamber");
|
|
Object.keys(status).sort().forEach((key) => {
|
|
if (seen.has(key) || !isTemperatureSensorKey(key)) {
|
|
return;
|
|
}
|
|
const sensor = status[key];
|
|
if (!sensor || typeof sensor !== "object") {
|
|
return;
|
|
}
|
|
const reading = formatTemperatureReading(sensor);
|
|
if (!reading) {
|
|
return;
|
|
}
|
|
rows.push({ label: prettifyTemperatureLabel(key), value: reading });
|
|
});
|
|
return { visible: rows.length > 0, rows };
|
|
}
|
|
|
|
function isTemperatureSensorKey(key) {
|
|
return typeof key === "string" && (
|
|
key.startsWith("temperature_sensor ") ||
|
|
key.startsWith("temperature_fan ") ||
|
|
key.startsWith("temperature_probe ")
|
|
);
|
|
}
|
|
|
|
function prettifyTemperatureLabel(key) {
|
|
const raw = String(key || "")
|
|
.replace(/^temperature_(sensor|fan|probe)\s+/i, "")
|
|
.replace(/_/g, " ")
|
|
.trim();
|
|
if (!raw) {
|
|
return "Sensor";
|
|
}
|
|
return raw.replace(/\b\w/g, (ch) => ch.toUpperCase());
|
|
}
|
|
|
|
function formatTemperatureReading(sensor) {
|
|
const current = Number(sensor.temperature);
|
|
if (!Number.isFinite(current)) {
|
|
return "";
|
|
}
|
|
const target = Number(sensor.target);
|
|
if (Number.isFinite(target) && target > 0) {
|
|
return `${current.toFixed(1)} / ${target.toFixed(1)}°C`;
|
|
}
|
|
return `${current.toFixed(1)}°C`;
|
|
}
|
|
|
|
refresh.addEventListener("click", loadPrinters);
|
|
const sessionReady = window.__KA_SESSION_PROMISE__ || Promise.resolve();
|
|
sessionReady.finally(() => {
|
|
loadPrinters();
|
|
setInterval(loadPrinters, 15000);
|
|
});
|