AllMyPrinters
Tutti gli argomenti
IdeaFatto nella 0.24.15

Feature request: Klipper macros and relay/output pins as buttons under Controls (with a tested local sketch)

Burnie

Hi Chris,

Thanks again for the power switch (#64) and several plates (#55). One more idea for Klipper/Moonraker printers.

Setup
- Tronxy X5S, Klipper v0.13.0 + Moonraker v0.10.0, Mainsail
- Agent 0.24.11 in Docker (LAN only, no cloud accounts), Android app (latest)
- Own instance of your slicer (1.0.10), single colour

What I'd like
Buttons for the printer's own Klipper macros on the printer card, under Controls, next to fans, lights and power. Most Klipper users have macros such as LOAD_FILAMENT, UNLOAD_FILAMENT, a probe attach/dock or a bed mesh macro, and today I have to open Mainsail to run them.

What I tried locally
To check that the idea works, I patched my own copy of 0.24.11 (only on my agent, not shared anywhere). It worked: I loaded filament on the X5S from the agent web page. The changes were small, about 50 lines in each file, and are attached below in case they help. Use them or ignore them as you like.

  • Macro list (backend, mrMacros, called next to pwrEntry in the Moonraker sync):
  • Read /printer/objects/list, keep the gcode_macro … objects, and leave out names starting with _, PAUSE/RESUME/CANCEL_PRINT (they already have buttons), SET_* (they need parameters) and G-code-like names (G29, M600).
  • Read the description from /printer/objects/query?configfile=settings, ignoring Klipper's default "G-Code macro".
  • Refresh at most every 10 minutes, and keep at most 40 macros.
  • Put the result on the card entry as entry.macros = [{n, d}].
  • Running a macro (backend):
  • New printer_cmd command macro {name}, only for Moonraker printers, sends POST /printer/gcode/script.
  • Only names from the list are accepted, and never while printing or paused (printer_busy).
  • Macros like LOAD_FILAMENT run for minutes because they heat up first, so the call answers "running" after 4 s while Klipper carries on. The outcome is written to diag.
  • Interface (app.js): a "Macros" group of tiles in ampCtlBlock, after the power tiles. It shows the name and description, asks "Run X on <printer>?" before sending, and greys out the tiles while printing. The texts are plain English, without i18n keys.

Also: switch output pins that are not lights
My X5S has a relay on an output_pin named rampsrela (12 V LED strip and an extra fan), so the name is not a light name. The agent lists an output_pin under Controls only when its name matches LIGHT_RE (light, led, lamp, licht, caselight, lumi), so this relay does not show up. Today I switch it in Mainsail or Home Assistant.
Idea: show the other non-PWM output_pins as plain on/off tiles too (named from the config, or with a name chosen per printer), or let the user pick which output pins to show. Switching would be the same SET_PIN PIN=<name> VALUE=0|1 that the light tiles already send.

Ideas for a proper version
- A setting per printer to choose which macros to show, or a "hide" option per macro. After a day of tuning my X5S the list already has seven macros, including ones meant only for the slicer's start G-code (for example a PRINT_PREP that homes, levels and probes the bed), which do not need a button.
- Parameters for macros that take them, for example TEMP= for LOAD_FILAMENT, read from the macro's params usage.
- The same tiles in the Android app (my patch only covers the agent web page).

Thanks!
/Burnie
---

Local patch (0.24.11), for reference only

--- a/core/backend.js (0.24.11)
+++ b/core/backend.js
@@ -1265,6 +1265,7 @@
   L.kobra = /^kobra[-_]/i.test(pinfo.hostname || '');   // Rinkhals (GoKlipper) → Lüfter über M106 P2/P3
   entry.ctl = await mrCtl(p, L, entry.busy, st.gcode_move);
   entry.pwr = pwrEntry(p, L);   // Strom-Geräte (#64), Liste kommt aus mrCtl → mrPwrList
+  entry.macros = await mrMacros(p, L);   // LOCAL TEST (Burnie 2026-11-28): Klipper-Makros als Knöpfe in „Steuern“
   await pwrAuto(p, L, entry, L.lastState, pstate, st);   // „Nach dem Druck ausschalten“ — L.lastState ist hier noch der vorige Stand
   if (entry.pwr) entry.pwr.arm = !!(L.pwrArm && entry.pwr.main && L.pwrArm.dev === entry.pwr.main);
 
@@ -2781,6 +2782,35 @@
     diag({ a: 'pwr_auto_off', p: p.id, m: p.model || '', d: a.dev + ' ' + Math.round(Math.max(...temps)) + ' °C' });
   } catch (e) { diag({ a: 'pwr_auto_off', p: p.id, m: p.model || '', err: e.message, d: a.dev }); }
 }
+// ── LOCAL TEST (Burnie 2026-11-28, nicht veröffentlicht): Klipper-Makros als Knöpfe ─────────────────────────────
+// Liste: gcode_macro-Objekte ohne _-Präfix, ohne Druck-Steuerung (PAUSE/RESUME/CANCEL_PRINT haben eigene Knöpfe) und ohne SET_*
+// (brauchen Parameter); Beschreibung aus configfile.settings. Höchstens alle 10 min neu, Ausführen nur Namen aus der Liste, nie im Druck.
+const MAC_SKIP = /^(PAUSE|RESUME|CANCEL_PRINT|SET_.*|M\d+|G\d+)$/i;
+async function mrMacros(p, L) {
+  if (!L.macros || Date.now() - (L.macrosAt || 0) > 600000) {
+    try {
+      const objs = (await mrGet(p, '/printer/objects/list', 3000)).objects || [];
+      const names = objs.filter(o => /^gcode_macro [A-Za-z0-9_]+$/.test(o)).map(o => o.slice(12)).filter(n => !n.startsWith('_') && !MAC_SKIP.test(n));
+      let set = {};
+      try { set = (((await mrGet(p, '/printer/objects/query?configfile=settings', 6000)).status || {}).configfile || {}).settings || {}; } catch (e) {}
+      L.macros = names.slice(0, 40).map(n => { const d = String(((set['gcode_macro ' + n.toLowerCase()] || {}).description) || ''); return { n, d: d === 'G-Code macro' ? '' : d.slice(0, 120) }; });
+      L.macrosAt = Date.now();
+    } catch (e) { L.macros = L.macros || []; }
+  }
+  return L.macros;
+}
+/** printer_cmd macro {name}: läuft oft Minuten (Aufheizen) → nach 4 s „läuft“ zurückmelden, Klipper arbeitet weiter. */
+async function mrMacroRun(p, inp) {
+  const L = live[p.id] || fail('cmd'), n = String(inp.name || '');
+  if (!(L.macros || []).some(m => m.n === n)) fail('cmd');
+  const ps = await mrGet(p, '/printer/objects/query?print_stats', 3000).then(r => ((r.status || {}).print_stats || {}).state, () => null);
+  if (ps === 'printing' || ps === 'paused') fail('printer_busy');
+  const run = mrPost(p, '/printer/gcode/script', { script: n }, 1800000);
+  run.then(() => diag({ a: 'macro', p: p.id, m: p.model || '', err: '', d: n }), e => diag({ a: 'macro', p: p.id, m: p.model || '', err: String(e.message || e).slice(0, 40), d: n + ' ' + String(e.msg || '').slice(0, 80) }));
+  const r = await Promise.race([run.then(() => 'done'), new Promise(res => setTimeout(() => res('running'), 4000))]);
+  return { ok: true, running: r === 'running' };
+}
+
 /** Schalten aus der Oberfläche (printer_cmd power {id, on}). Aus nie während eines Drucks, wenn es das Gerät des Druckers ist (oder keins feststeht). */
 async function mrPwrSet(p, inp) {
   const L = live[p.id] || (live[p.id] = { meta: {}, thumbs: {}, histAt: 0 });
@@ -5635,7 +5665,8 @@
     }
     if (inp.cmd === 'fan' || inp.cmd === 'light' || inp.cmd === 'speed') return ctlSet(p, inp);   // Lüfter und Licht (12.11.2026), Geschwindigkeit (21.11.2026)
     if (inp.cmd === 'unload') { if (kindOf(p) !== 'moonraker') fail('cmd'); return u1Unload(p, inp); }   // Snapmaker U1: Filament je Kopf entladen (27.11.2026)
-    if (inp.cmd === 'power') { if (kindOf(p) !== 'moonraker') fail('cmd'); return mrPwrSet(p, inp); }   // Moonraker-Stromschalter (27.11.2026, #64)
+    if (inp.cmd === 'power') { if (kindOf(p) !== 'moonraker') fail('cmd'); return mrPwrSet(p, inp); }
+    if (inp.cmd === 'macro') { if (kindOf(p) !== 'moonraker') fail('cmd'); return mrMacroRun(p, inp); }   // LOCAL TEST 2026-11-28   // Moonraker-Stromschalter (27.11.2026, #64)
     if (!['pause', 'resume', 'stop'].includes(inp.cmd)) fail('cmd');
     if (kindOf(p) === 'sdcp') await sdSend(p, { pause: 129, stop: 130, resume: 131 }[inp.cmd]);
     else if (kindOf(p) === 'cc2') await ccSend(p, { pause: 1021, stop: 1022, resume: 1023 }[inp.cmd]);   // Antwort kommt erst nach dem Ablauf
--- a/www/js/app.js (0.24.11)
+++ b/www/js/app.js
@@ -7062,7 +7062,7 @@
 };
 window.ampCtlBlock = (prov, p) => {
   const c = p.ctl || { fans: [], lights: [] }, pw = (p.pwr && p.pwr.devs) || [];
-  if (!p.online || p.locked || (!(c.fans || []).length && !(c.lights || []).length && !c.speed && !pw.length)) return '';
+  if (!p.online || p.locked || (!(c.fans || []).length && !(c.lights || []).length && !c.speed && !pw.length && !(p.macros || []).length)) return '';
   const pid = esc(p.id);
   const fans = (c.fans || []).map(f => {
     const run = f.pct > 0;
@@ -7072,7 +7072,7 @@
   const lights = (c.lights || []).map(l => `<button type="button" class="amp-ct lt${l.on ? ' on' : ''}" role="switch" aria-checked="${l.on ? 'true' : 'false'}" data-amplight="${esc(l.id)}" data-on="${l.on ? 1 : 0}" data-pid="${pid}" aria-label="${esc(ampCtlName(l, true))}">
       <span class="amp-ct-t"><b>${esc(ampCtlName(l, true))}</b><small>${esc(l.on == null ? '–' : t(l.on ? 'amp_ctl_on' : 'amp_ctl_off'))}</small></span><span class="amp-ct-i amp-bulb">${I_BULB}</span></button>`);
   const tiles = fans.concat(lights);
-  return `<div class="amp-ctl">${ampSpdBlock(p, pid)}${tiles.length ? `<div class="amp-ctl-h">${esc(t('amp_ctl_h'))}</div><div class="amp-ct-g">${tiles.join('')}</div>` : ''}${ampPwrTiles(p, pid)}</div>`;
+  return `<div class="amp-ctl">${ampSpdBlock(p, pid)}${tiles.length ? `<div class="amp-ctl-h">${esc(t('amp_ctl_h'))}</div><div class="amp-ct-g">${tiles.join('')}</div>` : ''}${ampPwrTiles(p, pid)}${ampMacTiles(p, pid)}</div>`;
 };
 const ampCtlOf = (pid, kind, id) => { for (const cn of (pv.data && pv.data.connections) || []) for (const p of cn.printers || []) if (String(p.id) === String(pid)) return (((p.ctl || {})[kind]) || []).find(x => String(x.id) === String(id)) || null; return null; };
 const ampCtlErr = (e, cmd) => toast(String((e && e.message) || '').split('\n')[0] === 'print_only' ? t(cmd === 'speed' ? 'amp_spd_print_only' : 'amp_ctl_print_only') : t('amp_ctl_err'));
@@ -7125,6 +7125,28 @@
   }
 });
 
+// ── LOCAL TEST (Burnie 2026-11-28, nicht veröffentlicht): Klipper-Makros als Knöpfe (backend entry.macros [{n, d}]) ──
+const I_PLAY = '<svg viewBox="0 0 24 24" aria-hidden="true" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M7 4l13 8-13 8z"/></svg>';
+function ampMacTiles(p, pid) {
+  const ms = p.macros || []; if (!ms.length) return '';
+  const ro = !!p.busy;
+  const tiles = ms.map(m => `<button type="button" class="amp-ct${ro ? ' ro' : ''}" data-ampmac="${esc(m.n)}" data-pid="${pid}" title="${esc(m.d || m.n)}" aria-label="${esc(m.n)}">
+      <span class="amp-ct-t"><b>${esc(m.n.replace(/_/g, ' '))}</b><small>${esc(m.d || 'Macro')}</small></span><span class="amp-ct-i">${I_PLAY}</span></button>`);
+  return `<div class="amp-ctl-h">Macros</div><div class="amp-ct-g">${tiles.join('')}</div>`;
+}
+document.addEventListener('click', async e => {
+  const b = e.target.closest && e.target.closest('[data-ampmac]');
+  if (!b) return;
+  e.preventDefault(); e.stopPropagation();
+  const p = ampPrOf(b.dataset.pid), n = b.dataset.ampmac;
+  if (p && p.busy) { toast('Not while printing.'); return; }
+  if (!confirm('Run ' + n + ' on ' + ((p && p.name) || 'the printer') + '?')) return;
+  pv.busy = true;
+  try { const r = await api('printer_cmd', { printer: b.dataset.pid, cmd: 'macro', name: n }); toast(r && r.running ? n + ' is running …' : n + ' done.'); }
+  catch (er) { toast(String((er && er.message) || '').split('\n')[0] === 'printer_busy' ? 'Not while printing.' : n + ' failed.'); }
+  finally { pv.busy = false; }
+}, true);
+
 // ── Moonraker-Stromschalter (27.11.2026, Community #64 Burnie: Drucker an einer Steckdose, die Moonraker schaltet) ─────────────
 // backend.js entry.pwr {devs [{id, on, locked}], main, chosen, off_after, cool, wait_s, wake, off, arm}. Kacheln unter „Steuern“ (online),
 // Hinweis „Ausgeschaltet“ + „Einschalten“ in der Karte (offline), Dialog im ⋯ (Gerät des Druckers, „Nach dem Druck ausschalten“).
Lo voglio anche io0

2 risposte

Chris Team

Hi Burnie, wow, thank you! This is one of the best feature requests I've had, and the patch with the list of things you ran into helps a lot.

I'm going to build it. I'll go with your "choose per printer" idea: nothing is shown by default, and you pick which macros appear under Controls. Some printers, like the Snapmaker U1, come with lots of internal macros that shouldn't end up as buttons. The same picker will work for your other on/off output pins, so your relay rampsrela can show up there too.

Macros will ask before running and stay locked while printing, like in your patch. Output pins will be locked during a print by default, and you'll be able to allow it per pin, so your LED strip can stay switchable. Parameters such as TEMP= will come in a later step.

It will start in the agent, and the Android and iPhone apps follow with the next bundle. I'd be glad if you could test it on your X5S. Thanks again! Chris

Burnie

Hi Chris,

Thank you so much, that was fast! I updated the agent to 0.24.16 the same evening, and the implementation looks great. It's actually nicer than my patch.

Tested on the X5S (Klipper v0.13.0, Moonraker, agent in Docker on the LAN):

  • Picker: the "Macros and switches" dialog listed all my macros with their descriptions. Internal _ macros and PRINT_START/PAUSE etc. were left out, just as you described. "Uses parameters, runs with the macro's defaults" is a very clear hint.
  • Relay: my relay rampsrela (12 V LED strip + electronics fan) shows up as an on/off tile, "LED och fläkt". Toggling it works instantly.
  • Macros: I ran UNLOAD and then LOAD filament from the tiles. Both asked for confirmation first, showed "running", and finished correctly.
  • Macros as presets: because the app runs macros with their defaults, I now use small wrapper macros with fixed values: LOAD_PLA / UNLOAD_PLA (210 °C) and LOAD_PETG / UNLOAD_PETG (230 °C). It works perfectly and gives one tile per material. That might be a handy tip for other Klipper users until parameters arrive.
  • Layout: the tiles sit nicely under Controls together with "Fans and light" and "Power". It looks clean.

A small confession: I had help from a digital friend (an AI assistant running locally in my homelab) for the first patch and the tests. It only ever touched my own local install. I hope that's okay for local testing like this.

Thanks again for listening and building it so quickly!

Burnie

Accedi per rispondere

Segnala contenuto