/* Lab English adapter for Ironoxx Snapmaker U1 Card 2.0.0. Source: https://github.com/Ironoxx/ha-snapmaker-u1-card/tree/v2.0.0 MIT License Copyright (c) 2026 Ironoxx Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /* snapmaker-u1-card: generated by 'npm run build' from frontend/src. Do not edit. */ (() => { // frontend/src/const.js var DOMAIN = "snapmaker_u1_card"; var CARD_VERSION = "2.0.0"; var BLANK = "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7"; var SUFFIX = ["", "1", "2", "3"]; var SECTIONS = [ "stage", "layer", "job", "queue", "files", "toolheads", "climate", "mesh", "motion", "console", "system", "maintenance", "charts", "stats", "history", "timelapse" ]; var OFFLINE_SECTIONS = ["queue", "files", "charts", "history", "timelapse", "maintenance"]; var TABS = [ { id: "overview", icon: "mdi:printer-3d", label: "Übersicht", sections: ["stage", "layer", "job", "toolheads"] }, { id: "control", icon: "mdi:tune-variant", label: "Steuerung", sections: ["climate", "mesh", "motion", "console"] }, { id: "files", icon: "mdi:file-document-multiple-outline", label: "Dateien", sections: ["queue", "files"] }, { id: "history", icon: "mdi:history", label: "Verlauf", sections: ["charts", "history", "stats"] }, { id: "timelapse", icon: "mdi:filmstrip", label: "Zeitraffer", sections: ["timelapse"] }, { id: "system", icon: "mdi:chip", label: "System", sections: ["maintenance", "system"] } ]; var TABLET_SIDE = ["stage", "job", "toolheads"]; var TAB_STORE = "u1-fusion-showcase-ironoxx.tab"; var RESULT = { complete: ["Fertig", "ok"], cancelled: ["Abgebrochen", "warn"], error: ["Fehler", "error"], unknown: ["Unbekannt", ""] }; var LAYER_PALETTE = ["#e53935", "#1e88e5", "#43a047", "#fdd835", "#8e24aa", "#fb8c00", "#00acc1", "#6d4c41"]; var MAINT_LABELS = { plate: "Druckplatte reinigen", nozzle: "Düsen und Abstreifer reinigen", rails: "Linearführungen reinigen und schmieren", belts: "Riemen prüfen", filter: "Luftfilter wechseln", tool_changer: "Werkzeugwechsler (Firmware)", carbon_rods: "X-Carbonstangen reinigen", lead_screws: "Z-Spindeln und Muttern schmieren", coupling: "Stahlstifte und Kugeln der Kopfaufnahme", pogo: "Pogo-Kontakte der Köpfe reinigen" }; var METRICS = [ ["prints", "Drucke"], ["hours", "Stunden"], ["filament_g", "Filament"], ["cost", "Kosten"] ]; // frontend/src/i18n.js var LANG = "en"; var LOCALE = "en-GB"; function setLang() {} function tr(text, vars) { let out = LANG === "de" ? text : EN[text] !== void 0 ? EN[text] : text; if (vars) for (const [k, v] of Object.entries(vars)) out = out.split(`{${k}}`).join(String(v)); return out; } var EN = { "aus": "off", "Kammerheizung": "Chamber heater", "Gerät": "Device", "Kammer": "Chamber", "Heizleistung": "Heater power", "Kammer-Solltemperatur": "Chamber target", "Der Slicer setzt die Kammer mit M141/M191. Nie unbeaufsichtigt heizen, Hauptplatine braucht zusätzliche Kühlung (Hinweis von paxx12).": "The slicer sets the chamber with M141/M191. Never heat unattended, the mainboard needs extra cooling (paxx12's advice).", "Kamera wechseln": "Switch camera", "Den Verbrauch bucht Moonraker (Spoolman im Drucker aktiv) – die Integration bucht nicht zusätzlich ab.": "Moonraker books the usage (Spoolman active on the printer) – the integration does not book it again.", "Gewogen": "Weighed", "mit Spule": "with spool", "nur Filament": "filament only", "Mit Leerspule gewogen ({g} g werden abgezogen)": "Weighed with the empty spool ({g} g are subtracted)", "Leerspulengewicht fehlt in Spoolman – nur das Filament wiegen.": "Empty spool weight missing in Spoolman – weigh the filament only.", "Spule #{id}: {g} g Filament": "Spool #{id}: {g} g filament", "SpoolLink im Drucker: die Wahl geht an den Drucker (SET_SPOOL_ID), er übernimmt das Filament der Spule.": "SpoolLink on the printer: the choice goes to the printer (SET_SPOOL_ID), which loads the spool's filament.", "monatlich": "monthly", "alle {n} Monate": "every {n} months", "noch {d} Tage": "{d} days left", "Gezählt in Druckstunden und Monaten (Monatswerte nach Snapmakers U1-Wartungsanleitung). Intervalle in den Optionen der Integration.": "Counted in print hours and months (month values from Snapmaker's U1 maintenance guide). Intervals in the integration options.", "X-Carbonstangen reinigen": "Clean the X carbon rods", "Z-Spindeln und Muttern schmieren": "Grease the Z lead screws and nuts", "Stahlstifte und Kugeln der Kopfaufnahme": "Steel pins and balls of the head coupling", "Pogo-Kontakte der Köpfe reinigen": "Clean the pogo contacts of the heads", "Linearführungen reinigen und schmieren": "Clean and lubricate the linear shafts", "Riemen prüfen": "Check the belts", "Düse passt nicht: Datei {a} mm, Kopf {b} mm": "Nozzle mismatch: file {a} mm, head {b} mm", "Düse {d} mm": "Nozzle {d} mm", "Material, Hersteller und Farbe der gewählten Spule werden in den Kopf übernommen.": "Material, vendor and colour of the chosen spool are loaded into the head.", "Profil {p}": "Profile {p}", "Höchster minus tiefster Messpunkt": "Highest minus lowest probed point", "Spanne (mm)": "Spread (mm)", "Tiefster (mm)": "Lowest (mm)", "Höchster (mm)": "Highest (mm)", "Messpunkte": "Probe points", "Kein Höhenprofil geladen. Es entsteht bei einem Druckstart mit Bettnivellierung.": "No bed mesh loaded. It is created when a print starts with bed leveling.", "Höhenprofil des Druckbetts": "Height map of the build plate", "vorne": "front", "tiefer": "lower", "höher": "higher", "Leerlauf": "Idle", "Kammer kühlen": "Cooling chamber", "Kammer vorheizen": "Preheating chamber", "Heiße Kammer": "Hot chamber", "Modus": "Mode", "Kammer-Soll": "Chamber target", "Umluft (U/min)": "Circulation (rpm)", "Filter-Laufzeit": "Filter runtime", "Betriebsstunden des Umluftlüfters (Filter)": "Operating hours of the circulation fan (filter)", "Abluftlüfter": "Exhaust fan", "Umluftlüfter": "Circulation fan", "Während eines Drucks regelt die Firmware die Lüfter je nach Material selbst nach.": "During a print the firmware adjusts the fans itself depending on the material.", "G-Code-Konsole": "G-code console", "Während des Drucks nur Feineinstellungen: Temperaturen, Lüfter, Geschwindigkeit, Flussrate, Z-Versatz, Licht, Top Cover und Abfragen.": "During a print only tuning: temperatures, fans, speed, flow, Z offset, light, top cover and queries.", "z. B. M105": "e.g. M105", "Senden": "Send", "Befehl eingeben, Antwort des Druckers erscheint hier.": "Enter a command; the printer’s answer appears here.", "Läuft …": "Running …", "Auf dem Schlitten": "On the carriage", "Im Dock": "In the dock", "Status unbekannt": "State unknown", "Kopfwechsel": "Head change", "Ablegen": "Park", "Aufnehmen": "Pick up", "Fährt bei Bedarf vorher X/Y an.": "Homes X/Y first if needed.", "{head} abgelegt": "{head} parked", "{head} aufgenommen": "{head} picked up", "Flussrate": "Flow", "Details und Filament bearbeiten": "Details and edit filament", "Druckkopf": "Print head", "Hersteller": "Vendor", "Spulengewicht": "Spool weight", "Länge": "Length", "Durchmesser": "Diameter", "Düsentemperatur": "Nozzle temperature", "Erste Schicht / weitere": "First layer / other layers", "Trocknen": "Drying", "Hergestellt": "Manufactured", "unbekannt": "unknown", "Daten der Spule (RFID)": "Spool data (RFID)", "Filament von Hand setzen": "Set filament by hand", "Während eines Drucks nicht möglich.": "Not possible during a print.", "Der Drucker ist ausgeschaltet.": "The printer is switched off.", "Unterart": "Sub type", "z. B. Silk, Matte, HF": "e.g. Silk, Matte, HF", "Farbe": "Colour", "RFID-Daten der Snapmaker-Spule überschreiben": "Overwrite the RFID data of the Snapmaker spool", "Übernehmen": "Apply", "Filament für {head} gesetzt": "Filament set for {head}", "Filament automatisch nachfüllen": "Auto-replenish filament", "Läuft eine Spule leer, druckt ein Kopf mit gleichem Material weiter.": "When a spool runs out, a head with the same material continues.", "Nachfüllen ohne Farbprüfung": "Replenish ignoring colour", "Auch ein Kopf mit anderer Farbe darf übernehmen.": "A head with a different colour may also take over.", "Verhedderungs-Erkennung": "Filament entangle detection", "Pausiert, wenn sich das Filament verhakt.": "Pauses when the filament gets tangled.", "Licht aus nach dem Druck": "Light off after print", "Empfindlichkeit": "Sensitivity", "Niedrig": "Low", "Mittel": "Medium", "Hoch": "High", "Druckereinstellungen": "Printer settings", "Rahmen in der Farbe des Zustands": "Frame in the state colour", "Druckt, pausiert, Fehler, fertig – in den Farben deines Home-Assistant-Designs": "Printing, paused, error, done – in the colours of your Home Assistant theme", "Snapmaker U1: Kamera, geladene Filamente, Druckstart mit Filamentzuordnung, Diagnose.": "Snapmaker U1: camera, loaded filaments, print start with filament mapping, diagnostics.", "Kompakt: Status, Fortschritt, Filamente und Netzschalter – ohne Kamera.": "Compact: status, progress, filaments and power switch, no camera.", "{h} übernimmt": "{h} takes over", "leer in ~{m} min": "empty in ~{m} min", "Alle": "All", "Suchen ({n} Dateien)": "Search ({n} files)", "Sortierung": "Sort", "Ältere Dateien": "Older files", "Temperaturverlauf": "Temperature history", "letzte 20 min": "last 20 min", "Noch keine Daten.": "No data yet.", "Drucker nicht erreichbar.": "Printer not reachable.", "Lädt …": "Loading …", "jetzt": "now", "Bett": "Bed", "Firmware": "Firmware", "Selbsttest": "Self-test", "verfügbar": "available", "aktuell": "up to date", "Prüfe …": "Checking …", "Keine Antwort": "No response", "Ergebnisfoto": "Result photo", "Nach Material": "By material", "Material": "Material", "Verbrauch": "Usage", "Erfolg": "Success", "Meistgenutzte Farben": "Most used colours", "Neuer Name oder Pfad (Unterordner mit /):": "New name or path (subfolders with /):", "„{n}“ vom Drucker löschen?": "Delete “{n}” from the printer?", "Umbenennen / verschieben": "Rename / move", "Datei löschen": "Delete file", "Neueste": "Newest", "Druckzeit": "Print time", "Vergrößern": "Zoom in", "Verkleinern": "Zoom out", "Vollbild": "Full screen", "Load Average über 1 Minute: im Mittel laufende oder wartende Prozesse. Liegt der Wert unter der Zahl der Kerne, ist der Drucker nicht ausgelastet.": "Load average over 1 minute: processes running or waiting on average. Below the number of cores the printer is not saturated.", "Systemlast (Ø 1 min)": "System load (1 min avg)", "{p} % von {n} Kernen": "{p} % of {n} cores", "Solltemperatur während des Drucks auf {v} °C ändern?": "Change target temperature to {v} °C while printing?", "Regler entsperren ({n} s)": "Unlock controls ({n} s)", "Regler entsperren": "Unlock controls", "Sperre für Regler": "Control lock", "Aus": "Off", "Bis zum erneuten Sperren": "Until locked again", "Leer = 1 min. Gesperrt sind Temperatur- und Lüfterregler, Schnellwahl, Heizungsschalter und Referenzfahrt; das Schloss öffnet sie bis zur gewählten Zeit nach der letzten Bedienung.": "Empty = 1 min. Locks temperature and fan sliders, presets, heater switches and homing; the padlock unlocks them until the chosen time after the last use.", "Regler sperren": "Lock controls", "Gesperrt": "Locked", "Entsperrt": "Unlocked", "Regler nicht sperren": "Don't lock controls", "Kopf {n}": "Head {n}", "Dauer": "Duration", "Schicht {n} / {t}": "Layer {n} / {t}", "Schichtansicht wird vorbereitet …": "Preparing layer view …", "Schichtansicht nicht verfügbar: {e}": "Layer view unavailable: {e}", "keine Bahnen": "no paths", "Filament {n}": "Filament {n}", "gedruckt": "printed", "folgt": "to do", "Am häufigsten": "Most printed", "Auf dem Drucker bleiben die {n} neuesten.": "The {n} newest stay on the printer.", "Datei hochladen": "Upload file", "Der Drucker druckt gerade. Du kannst den Auftrag in die Warteschlange stellen.": "The printer is printing. You can add the job to the queue.", "Der Drucker druckt. Antippen, um einen Auftrag in die Warteschlange zu stellen.": "The printer is printing. Tap a file to add it to the queue.", "Der Drucker hält vor Schicht {l} an (z. B. für Magnete). Fortsetzen am Display oder in der Karte.": "The printer pauses before layer {l} (e.g. for magnets). Resume on the display or in the card.", "Diagramm": "Chart", "Diagramme": "Charts", "Die Datei hat nur {n} Schichten.": "The file only has {n} layers.", "Drucke": "Prints", "Druckplatte reinigen": "Clean build plate", "Düsen und Abstreifer reinigen": "Clean nozzles and wiper", "Entfernen": "Remove", "Erfolgsquote": "Success rate", "Erledigt": "Done", "Gesichert in Medien": "Backed up to media", "Hochgeladen: {name}": "Uploaded: {name}", "In die Warteschlange gestellt: {name}": "Added to queue: {name}", "Jetzt sichern": "Back up now", "Kosten": "Cost", "Gemessen bei Drucken seit Installation der Integration.": "Measured for prints since the integration was installed.", "Ältere Drucke mit Filamentpreis geschätzt, ohne Strom.": "Older prints estimated from filament price, without power.", "Letzte 12 Monate": "Last 12 months", "Luftfilter wechseln": "Replace air filter", "Löschen auf dem Drucker wird von der Firmware nicht unterstützt.": "The firmware does not support deleting on the printer.", "Nach oben": "Move up", "Noch nichts gesichert.": "Nothing backed up yet.", "Nochmal drucken": "Print again", "Nur .gcode- und .3mf-Dateien.": "Only .gcode and .3mf files.", "Nächster: {name}": "Next: {name}", "Pause vor Schicht": "Pause before layer", "Pause vor {l}": "Pause before {l}", "Schichten als ganze Zahlen ab 1 angeben, z. B. 12, 40.": "Enter layers as whole numbers from 1, e.g. 12, 40.", "Sicherung läuft …": "Backup running …", "Starten": "Start", "Startet nicht von selbst: nach dem Druck das Bett räumen und hier starten.": "Does not start by itself: clear the bed after the print and start it here.", "Strom": "Energy", "Geschätzt": "Estimated", "MCU-Last und -Wachzeit sind wie in Mainsail berechnet; einstellige Werte sind normal, kritisch wird die Last erst gegen 100 %.": "MCU load and awake time are calculated as in Mainsail; single-digit values are normal, load only becomes critical towards 100 %.", "Last: längste Aufgabe des Controllers (Mittel + 3 σ) im Verhältnis zu 2,5 ms. Ab etwa 100 % meldet Klipper 'Timer too close'. Wach: Anteil der Zeit, in der der Controller rechnet statt zu schlafen. Einstellige Werte sind normal.": "Load: longest controller task (mean + 3 σ) relative to 2.5 ms. Around 100 % Klipper reports 'Timer too close'. Awake: share of time the controller is working instead of sleeping. Single-digit values are normal.", "Belegter Arbeitsspeicher des Druckerrechners (ohne Puffer und Cache).": "Memory in use on the printer's computer (excluding buffers and cache).", "Live-Verbindung": "Live connection", "verbunden": "connected", "seit": "since", "getrennt · Abfrage alle {n} s": "disconnected · polling every {n} s", "noch keine": "none yet", "{n} Dateien": "{n} files", "{n} Datei": "{n} file", "Drucker-Konfiguration gesichert": "Printer configuration backed up", "Leer = automatisch (Seitenverhältnis des Bildes)": "Empty = automatic (image aspect ratio)", "Stunden": "Hours", "Verbindung abgebrochen": "Connection lost", "Wartung": "Maintenance", "Wechsel": "changes", "Werkzeugwechsler (Firmware)": "Tool changer (firmware)", "Zuletzt gesichert: {d}": "Last backup: {d}", "fällig": "due", "noch {h} h": "{h} h left", "z. B. 12, 40": "e.g. 12, 40", "{name} starten? Druckbett ist leer und der Drucker frei?": "Start {name}? Is the bed clear and the printer free?", "{n} Aufträge": "{n} jobs", "{n} Drucke": "{n} prints", "{n} fällig": "{n} due", "„{x}“ als erledigt markieren?": "Mark “{x}” as done?", "Reiter": "Tabs", "Untereinander": "Stacked", "Kamera": "Camera", "Druckauftrag": "Print job", "Bett & Innenraum": "Bed & chamber", "System & Diagnose": "System & diagnostics", "Name": "Name", "Marke": "Brand", "Darstellung": "Layout", "Bereiche ausblenden": "Hide sections", "Leer = Reiter": "Empty = tabs", "Leer = Livestream": "Empty = live stream", "Kamera-Entität": "Camera entity", "Kameramodus": "Camera mode", "Livestream": "Live stream", "Einzelbilder": "Still images", "Fortschritt auf dem Kamerabild ausblenden": "Hide progress on the camera image", "Skalierung": "Scaling", "Einpassen": "Fit", "Füllen": "Fill", "Strecken": "Stretch", "Bildhöhe (px)": "Image height (px)", "Bildrate (s)": "Frame interval (s)", "„Bild veraltet“ ab (s)": "“Image stale” after (s)", "Statisches Bild statt Kamera": "Static image instead of camera", "Erweitert": "Advanced", "Moonraker-Präfix": "Moonraker prefix", "WLAN-Tracker": "Wi-Fi tracker", "Angezeigte Dateien": "Files shown", "Leer = automatisch erkannt": "Empty = detected automatically", "Nur bei mehreren Druckern nötig": "Only needed with several printers", "Zeigt einen Verbindungs-Chip in der Kopfzeile": "Shows a connection chip in the header", "Kopfnamen und Temperatur-Presets im YAML-Editor": "Head names and temperature presets in the YAML editor", "Beim Antippen öffnen": "Open on tap", "Filamente ausblenden": "Hide filaments", "z. B. /dashboard-drucker/0 – leer = Statusdialog": "e.g. /dashboard-printer/0 – empty = status dialog", "Übersicht": "Overview", "Steuerung": "Control", "Verlauf": "History", "Aktiver Kopf": "Active head", "Ansicht": "View", "(Stand vor dem Ausschalten)": "(as of before switching off)", "Abbrechen": "Cancel", "Abgebrochen": "Cancelled", "Alle Achsen": "All axes", "An": "On", "Arbeitsspeicher": "Memory", "Automatisch": "Automatic", "Bauteillüfter": "Part fan", "Bereit": "Ready", "Bett & Innenraum": "Bed & chamber", "Bett-Heizung": "Bed heater", "Bett-Solltemperatur": "Bed target", "Bettnivellierung": "Bed leveling", "Bewegung": "Motion", "Bild veraltet": "Image stale", "Bisher": "Elapsed", "Bitte warten": "Please wait", "Das dauert etwa 1–2 Minuten.": "This takes about 1–2 minutes.", "Dateien": "Files", "Der Drucker antwortet nicht. Trotzdem ausschalten?": "The printer is not responding. Switch off anyway?", "Der Drucker druckt gerade. Druck erst beenden oder abbrechen.": "The printer is printing. Finish or cancel the print first.", "Der Drucker ist aus oder nicht erreichbar. Zeitraffer lassen sich erst nach dem Einschalten abspielen.": "The printer is off or unreachable. Timelapses can be played once it is switched on.", "Der Drucker ist aus. Bitte erst einschalten.": "The printer is off. Please switch it on first.", "Der Drucker ist aus. Er wird eingeschaltet und startet den Druck, sobald er bereit ist (ca. 1–2 min).": "The printer is off. It will be switched on and start the print once ready (about 1–2 min).", "Der Drucker meldet einen Fehler": "The printer reports an error", "Der Strom wird abgeschaltet, sobald er heruntergefahren ist.": "Power will be cut once it has shut down.", "Die Datei enthält keine Filamentangaben. Der Drucker nutzt seine Standardzuordnung (Filament 1 → Kopf 1 …).": "The file has no filament information. The printer uses its default mapping (filament 1 → head 1 …).", "Die Integration Snapmaker U1 Card ist nicht eingerichtet.": "The Snapmaker U1 Card integration is not set up.", "Der Drucker antwortet nicht im Netzwerk.": "The printer does not respond on the network.", "Druck": "Print", "Druck gestartet: {name}": "Print started: {name}", "Druck gestoppt": "Print stopped", "Druck starten": "Start print", "Druck wirklich abbrechen?": "Really cancel the print?", "Druckbett": "Bed", "Druckbett ist leer und der Drucker frei": "The bed is clear and the printer is free", "Drucke gesamt": "Total prints", "Drucken": "Print", "Drucker fährt herunter": "Printer shutting down", "Drucker herunterfahren und ausschalten?": "Shut down and switch off the printer?", "Drucker ist aus": "Printer is off", "Drucker nicht erreichbar": "Printer unreachable", "Drucker startet": "Printer starting", "Drucker startet …": "Printer starting …", "Druckhistorie": "Print history", "Druckköpfe": "Toolheads", "Druckraum": "Build chamber", "Druckt": "Printing", "Druckzeit gesamt": "Total print time", "Einschalten": "Switch on", "Einschalten & drucken": "Switch on & print", "Einstellungen → Geräte & Dienste → Integration hinzufügen → „Snapmaker U1 Card“.": "Settings → Devices & services → Add integration → “Snapmaker U1 Card”.", "Fehler": "Error", "Fertig": "Done", "Fertig um": "Done at", "Filament": "Filament", "Filament gesamt": "Total filament", "Filamentzuordnung": "Filament mapping", "Flusskalibrierung": "Flow calibration", "Fortsetzen": "Resume", "Fährt herunter …": "Shutting down …", "Geladen": "Loaded", "Geschw.": "Speed", "Geschwindigkeit": "Speed", "Getrennt": "Disconnected", "Heiz. {v}": "Heat {v}", "Heizung an": "Heater on", "Heizung aus": "Heater off", "Herunterfahren und ausschalten": "Shut down and switch off", "Herunterladen": "Download", "Höhe": "Height", "Idle-Status": "Idle state", "Innenraum": "Chamber", "Innenraumlüfter": "Chamber fan", "Keine Druckdateien auf dem Drucker.": "No print files on the printer.", "Keine Spule": "No spool", "Keine Zeitraffer auf dem Drucker. Aufnahme im Druckdialog unter „Zeitraffer“ einschalten.": "No timelapses on the printer. Enable recording under “Timelapse” in the print dialog.", "Keine aktiven Spulen in Spoolman.": "No active spools in Spoolman.", "Kosten aktueller Druck": "Cost current print", "Kosten letzter Druck": "Cost last print", "Laufender Druck": "Current print", "Leer": "Empty", "Letzter Druck": "Last print", "Licht": "Light", "Längster Druck": "Longest print", "Lüfter {v}": "Fan {v}", "MCU Host (Last / Wach)": "MCU host (load / awake)", "Material weicht ab: Datei {a}, Slot {b}": "Material differs: file {a}, slot {b}", "Meldung": "Message", "Netzschalter nicht erreichbar": "Power switch unavailable", "Netzteil-Lüfter": "PSU fan", "Neu laden": "Reload", "Noch keine Drucke erfasst. Die Historie füllt sich ab dem nächsten Druck.": "No prints recorded yet. The history fills up from the next print.", "Not-Halt": "Emergency stop", "Not-Halt auslösen?": "Trigger emergency stop?", "Klipper stoppt sofort, Heizungen und Motoren gehen aus. Danach ist ein Neustart der Firmware nötig.": "Klipper stops immediately, heaters and motors switch off. A firmware restart is needed afterwards.", "Not-Halt 1 s gedrückt halten. Klipper stoppt sofort, danach ist ein Neustart der Firmware nötig.": "Hold the emergency stop for 1 s. Klipper stops immediately, a firmware restart is needed afterwards.", "Der laufende Druck lässt sich danach nicht fortsetzen.": "The running print cannot be resumed afterwards.", "Die Integration ist auf {v}, im Browser läuft noch die Karte {c}. Seite neu laden; hilft das nicht, den Browser-Cache leeren (Companion App: Einstellungen → Companion App → Fehlerbehebung → Frontend-Cache zurücksetzen).": "The integration is on {v}, the browser still runs card {c}. Reload the page; if that does not help, clear the browser cache (Companion app: Settings → Companion app → Troubleshooting → Reset frontend cache).", "Die Karte ist auf {c}, die Integration noch auf {v}. Home Assistant neu starten, damit das Update vollständig aktiv wird.": "The card is on {c}, the integration still on {v}. Restart Home Assistant to finish the update.", "Veraltete Karte im Browser-Cache": "Outdated card in the browser cache", "Neustart von Home Assistant nötig": "Home Assistant restart required", "Neu laden": "Reload", "G-Code herunterladen": "Download G-code", "Download fehlgeschlagen": "Download failed", "Benachrichtigungen": "Notifications", "Fortschritt aufs Handy": "Progress on the phone", "Fortschrittsbalken und Countdown in der Benachrichtigungsleiste. Heute {n} von {b} Updates.": "Progress bar and countdown in the notification shade. Today {n} of {b} updates.", "Kein Android-Handy unter den Benachrichtigungszielen der Integration.": "No Android phone among the integration's notification targets.", "Objekte – antippen zum Ausschließen": "Objects – tap to exclude", "Objekte ({n})": "Objects ({n})", "Weniger": "Less", "Ausschließen ({n})": "Exclude ({n})", "Ausgeschlossen": "Excluded", "Letztes Objekt": "Last object", "Ausschließen": "Exclude", "„{n}“ ausschließen?": "Exclude “{n}”?", "Das Objekt wird ab sofort nicht mehr gedruckt, der Rest läuft weiter. Das lässt sich nicht rückgängig machen.": "The object will no longer be printed, the rest continues. This cannot be undone.", "Teil vergrößert": "Zoomed to the part", "Schichtansicht": "Layer view", "Leer = Teil vergrößert. Umschalten geht auch direkt in der Schichtansicht.": "Empty = zoomed to the part. You can also switch directly in the layer view.", "Draufsicht": "Top view", "Eigenes Hintergrundbild": "Own background image", "Bildbereich in mm (x0, y0, x1, y1)": "Image area in mm (x0, y0, x1, y1)", "Deckkraft": "Opacity", "Raster über dem Bild": "Grid over the image", "z. B. /local/u1_oben.png (Datei unter config/www). Ersetzt Platte und Köpfe in der Draufsicht.": "e.g. /local/u1_top.png (file in config/www). Replaces plate and heads in the top view.", "Welche Druckerkoordinaten das Bild abdeckt. Leer = genau die Platte 0, 0, 270, 270. Für ein Foto des ganzen Druckers z. B. -40, -30, 310, 360.": "Printer coordinates the image covers. Empty = exactly the plate 0, 0, 270, 270. For a photo of the whole printer e.g. -40, -30, 310, 360.", "Keine Kamera erkannt. Der Selbsttest im System-Reiter zeigt, was die Integration gefunden hat.": "No camera detected. The self test in the System tab shows what the integration found.", "Leer = automatisch (die Kamera-Entität der Integration erkennt Livestream oder Standbilder selbst)": "Empty = automatic (the integration's camera entity detects live stream or still images itself)", "Leer = Kamera der Integration (erkennt Stock- und angepasste Firmware), sonst die der Moonraker-Integration": "Empty = the integration's camera (detects stock and modified firmware), else the Moonraker integration's", "Teil vergrößern": "Zoom to the part", "Ganzes Druckbett": "Whole build plate", "Druck abbrechen": "Cancel print", "Weiterdrucken": "Keep printing", "Anzeigen, mit Rückfrage": "Show, with confirmation", "Gesichert: 1 s gedrückt halten": "Guarded: hold for 1 s", "Ausblenden": "Hide", "Tablet / Monitor": "Tablet / monitor", "Kamera bei stehendem Bild wecken": "Wake the camera when the image stops", "Direktstream vom Drucker": "Direct stream from the printer", "Adresse des Direktstreams": "Direct stream URL", "Aus (immer über Home Assistant)": "Off (always through Home Assistant)", "Leer = automatisch: im Heimnetz direkt vom Drucker (weniger Verzögerung), bei https oder unterwegs über Home Assistant": "Empty = automatic: directly from the printer at home (less delay), through Home Assistant on https or away from home", "Leer = http:///webcam/?action=stream": "Empty = http:///webcam/?action=stream", "Leer = Reiter. Tablet / Monitor: Kamera, Druckauftrag und Druckköpfe links, Reiter rechts (ab ca. 900 px Breite)": "Empty = tabs. Tablet / monitor: camera, job and print heads on the left, tabs on the right (from about 900 px width)", "Leer = anzeigen. Der Not-Halt-Button in Home Assistant bleibt in jedem Fall erhalten.": "Empty = show. The emergency stop button entity in Home Assistant is always kept.", "Leer = an. Bleibt das Bild stehen, schickt die Karte camera.start_monitor an den Drucker (nur solange sie sichtbar ist).": "Empty = on. If the image stops, the card sends camera.start_monitor to the printer (only while it is visible).", "Not-Halt stoppt Klipper sofort. Ein Neustart der Firmware ist danach nötig.": "Emergency stop halts Klipper immediately. A firmware restart is needed afterwards.", "Offline": "Offline", "Optionen": "Options", "Pause": "Pause", "Pausiert": "Paused", "Pausiere …": "Pausing …", "Spule aus Spoolman, vom Drucker per SpoolLink übernommen": "Spool from Spoolman, taken over by the printer via SpoolLink", "3D-Waben": "3D honeycomb", "Adaptiv kubisch": "Adaptive cubic", "Außenwand {v}": "Outer wall {v}", "Baum (automatisch)": "Tree (auto)", "Baum (manuell)": "Tree (manual)", "Blitz": "Lightning", "Bügeln": "Ironing", "Die Datei enthält keine Slicer-Einstellungen.": "The file contains no slicer settings.", "Dreiecke": "Triangles", "Druckplatte": "Build plate", "Düse {n} · Bett {b}": "Nozzle {n} · bed {b}", "Einstellungen werden gelesen …": "Reading settings …", "Geradlinig": "Rectilinear", "Gitter": "Grid", "In Klammern: erste Schicht.": "In brackets: first layer.", "Infill": "Infill", "Infill {v}": "Infill {v}", "Kubisch": "Cubic", "Linien": "Line", "Mausohren": "Mouse ears", "Naht": "Seam", "Normal (automatisch)": "Normal (auto)", "Normal (manuell)": "Normal (manual)", "Profil": "Profile", "Rand (Brim)": "Brim", "Reinigungsturm": "Prime tower", "Schichthöhe": "Layer height", "Slicer-Einstellungen": "Slicer settings", "Stützen": "Supports", "Temperaturen": "Temperatures", "Waben": "Honeycomb", "Wände": "Walls", "alle festen Schichten": "all solid layers", "an": "on", "ausgerichtet": "aligned", "automatisch": "automatic", "außen": "outer", "außen und innen": "outer and inner", "erste {v}": "first {v}", "hinten": "back", "innen": "inner", "nur vom Bett": "from the bed only", "nächste": "nearest", "oben {n}": "top {n}", "obere Flächen": "top surfaces", "oberste Fläche": "topmost surface", "unten {n}": "bottom {n}", "zufällig": "random", "{n} Wände": "{n} walls", "Akzentfarbe": "Accent colour", "WebRTC (paxx12-Firmware)": "WebRTC (paxx12 firmware)", "Zoom zurücksetzen nach (s)": "Reset zoom after (s)", "Leer = 60 s ohne Bedienung, 0 = nie. Beim Verlassen der Seite oder Wegscrollen geht der Zoom immer zurück.": "Empty = 60 s without interaction, 0 = never. Leaving the page or scrolling away always resets the zoom.", "Leer = automatisch: WebRTC, wenn der Drucker es anbietet (weniger Verzögerung und Datenlast). Klappt keine direkte Verbindung (unterwegs ohne VPN), bleibt MJPEG.": "Empty = automatic: WebRTC when the printer offers it (less delay and data). If no direct connection works (away without VPN), MJPEG stays.", "Aus (MJPEG)": "Off (MJPEG)", "Leer = Hauptfarbe deines Home-Assistant-Designs. Färbt Knöpfe, Regler und Hervorhebungen der Karte.": "Empty = your Home Assistant theme's primary colour. Colours the card's buttons, sliders and highlights.", "Wieder #{id} {name}?": "Use #{id} {name} again?", "Diese Spule steckte vor dem Entladen in diesem Kopf": "This spool was in this head before unloading", "Andere Spule wählen": "Choose another spool", "Setze fort …": "Resuming …", "Breche ab …": "Cancelling …", "Der Drucker hat die Pause noch nicht bestätigt.": "The printer has not confirmed the pause yet.", "Der Drucker hat das Fortsetzen noch nicht bestätigt.": "The printer has not confirmed the resume yet.", "Der Drucker hat den Abbruch noch nicht bestätigt.": "The printer has not confirmed the cancel yet.", "Position X": "Position X", "Position Y": "Position Y", "Position Z": "Position Z", "Prozent": "percent", "Referenzfahrt ist während des Drucks gesperrt.": "Homing is locked while printing.", "Restzeit": "Remaining", "Schicht": "Layer", "Schließen": "Close", "Seit Wartung (max.)": "Since maintenance (max.)", "Slicer-Rest": "Slicer remaining", "Slot ist leer": "Slot is empty", "Slot {n}": "Slot {n}", "Snapmaker-Spule, per RFID erkannt": "Snapmaker spool, detected via RFID", "Soll": "Target", "Spoolman nicht erreichbar": "Spoolman unreachable", "Spoolman-Spule #{id} (automatisch) – zum Ändern tippen": "Spoolman spool #{id} (automatic) – tap to change", "Spoolman-Spule #{id} (manuell gewählt) – zum Ändern tippen": "Spoolman spool #{id} (chosen manually) – tap to change", "Spule #{id} hat noch {rest} g, gebraucht werden ca. {need} g": "Spool #{id} has {rest} g left, about {need} g needed", "Spule für {head}": "Spool for {head}", "Leer = automatisch: Ist keine direkte Verbindung zum Drucker möglich (z. B. Nabu Casa), spielt Home Assistant den RTSP-Stream ab – flüssiger und viel weniger Daten als MJPEG. Nur mit RTSP (paxx12).": "Empty = automatic: when there is no direct connection to the printer (e.g. Nabu Casa), Home Assistant plays the RTSP stream – smoother and far less data than MJPEG. Only with RTSP (paxx12).", "Unterwegs: RTSP über Home Assistant": "Away: RTSP through Home Assistant", "CPU": "CPU", "Temperatur des Rechners im Drucker (Moonraker).": "Temperature of the printer's computer (Moonraker).", "CPU-Temperatur": "CPU temperature", "Einblenden": "Show", "Einstellungen": "Settings", "Änderungen verwerfen?": "Discard changes?", "Lade Einstellungen …": "Loading settings …", "Entität nicht gefunden": "Entity not found", "nicht verfügbar": "unavailable", "Auto-Aus": "Auto-off", "Auto-Ein": "Auto-on", "kein Netzschalter": "no power switch", "1 Ziel": "1 target", "{n} Ziele": "{n} targets", "Spoolman: 1 Material": "Spoolman: 1 material", "Weitere anzeigen ({n})": "Show more ({n})", "keine Benachrichtigungen": "no notifications", "Spoolman: {n} Materialien": "Spoolman: {n} materials", "keine Preise": "no prices", "keine": "none", "Spoolman: {p} €/kg – hat Vorrang": "Spoolman: {p} €/kg – takes precedence", "keine verfügbar": "none available", "Mon.": "mo.", "Monate": "Months", "geändert": "changed", "Verwerfen": "Discard", "Speichern": "Save", "Gilt für die Integration (alle Dashboards). Nach dem Speichern lädt sie kurz neu.": "Applies to the integration (all dashboards). It reloads briefly after saving.", "Einstellungen gespeichert – die Integration lädt neu.": "Settings saved – the integration reloads.", "Keine Änderung.": "No change.", "Neue Spule anlegen": "Create new spool", "in Spoolman, mit dem Filament dieses Kopfs vorausgefüllt": "in Spoolman, prefilled with this head's filament", "Neue Spule für {head}": "New spool for {head}", "Hersteller und Filament werden in Spoolman wiederverwendet oder angelegt.": "Vendor and filament are reused in Spoolman or created.", "z. B. PLA Matte Schwarz": "e.g. PLA Matte Black", "Nettogewicht (g)": "Net weight (g)", "Leerspule (g)": "Empty spool (g)", "Preis": "Price", "optional": "optional", "Zurück": "Back", "Anlegen und zuordnen": "Create and assign", "Spule #{id} angelegt und {head} zugeordnet": "Spool #{id} created and assigned to {head}", "Spule wählen": "Choose spool", "Startet …": "Starting …", "Statistik": "Statistics", "Stepper X": "Stepper X", "Stepper Y": "Stepper Y", "Strom aktueller Druck": "Energy current print", "Strom letzter Druck": "Energy last print", "Strom {e} · Filament {f}": "Energy {e} · filament {f}", "System & Diagnose": "System & diagnostics", "Systemlast": "System load", "Temperaturen werden gehalten": "Temperatures are held", "Unbekannt": "Unknown", "Verbunden": "Connected", "Video nicht abrufbar": "Video unavailable", "Vorschau": "Preview", "Warteschlange": "Queue", "Wechsel aktueller Druck": "Changes current print", "Wechsel je Kopf": "Changes per head", "Wechsel letzter Druck": "Changes last print", "Werkzeugwechsel gesamt": "Total tool changes", "Wird gestartet …": "Starting …", "Während eines laufenden Drucks ausgeblendet.": "Hidden while a print is running.", "Zeitraffer": "Timelapse", "Zuletzt": "Last", "Zum Drucken einfach eine Datei wählen, er schaltet sich selbst ein.": "Just pick a file to print; it switches itself on.", "abgebrochen": "cancelled", "fertig": "done", "kein Filament erkannt": "no filament detected", "leer": "empty", "nach Material, Farbe und Hersteller": "by material, colour and vendor", "nichts abbuchen": "nothing is deducted", "steckt in {head}": "in {head}", "{n} Schichten": "{n} layers", "{n} Wechsel": "{n} changes", "{n} neueste": "{n} newest" }; // frontend/src/accent.js function parseColor(value) { if (Array.isArray(value) && value.length === 3 && value.every((v) => Number.isFinite(Number(v)))) { return value.map((v) => Math.max(0, Math.min(255, Math.round(Number(v))))); } const m = /^#?([0-9a-f]{3}|[0-9a-f]{6})$/i.exec(String(value || "").trim()); if (!m) return null; const hex = m[1].length === 3 ? m[1].replace(/./g, (c) => c + c) : m[1]; return [0, 2, 4].map((i) => parseInt(hex.slice(i, i + 2), 16)); } var lum = ([r, g, b]) => { const ch = (c) => { c /= 255; return c <= 0.03928 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4; }; return 0.2126 * ch(r) + 0.7152 * ch(g) + 0.0722 * ch(b); }; function accentVars(value) { const rgb = parseColor(value); if (!rgb) return {}; const col = `rgb(${rgb.join(", ")})`; const dark = lum(rgb) > 0.4; return { "--u1-primary": col, "--u1-on-primary": dark ? "#111318" : "#ffffff", "--u1-primary-container": `color-mix(in srgb, ${col} 32%, var(--u1-surface))`, "--u1-on-primary-container": "var(--u1-on)" }; } function applyAccent(el, value) { const vars = accentVars(value); for (const k of ["--u1-primary", "--u1-on-primary", "--u1-primary-container", "--u1-on-primary-container"]) { if (vars[k]) el.style.setProperty(k, vars[k]); else el.style.removeProperty(k); } } // frontend/src/editor.js var SECTION_LABELS = { stage: "Kamera", job: "Druckauftrag", files: "Dateien", toolheads: "Druckköpfe", climate: "Bett & Innenraum", mesh: "Bettnivellierung", motion: "Bewegung", console: "G-Code-Konsole", system: "System & Diagnose", stats: "Statistik", history: "Druckhistorie", timelapse: "Zeitraffer", queue: "Warteschlange", charts: "Diagramme", maintenance: "Wartung", layer: "Schichtansicht" }; var FORM_LABELS = { printer_name: "Name", printer_brand: "Marke", layout: "Darstellung", hide: "Bereiche ausblenden", camera: "Kamera-Entität", camera_mode: "Kameramodus", hide_overlay: "Fortschritt auf dem Kamerabild ausblenden", state_accent: "Rahmen in der Farbe des Zustands", accent_color: "Akzentfarbe", camera_fit: "Skalierung", camera_height: "Bildhöhe (px)", refresh: "Bildrate (s)", stale_after: "„Bild veraltet“ ab (s)", printer_image: "Statisches Bild statt Kamera", prefix: "Moonraker-Präfix", network_tracker: "WLAN-Tracker", files_limit: "Angezeigte Dateien", navigation_path: "Beim Antippen öffnen", hide_filaments: "Filamente ausblenden", unlock_controls: "Regler nicht sperren", controls_lock: "Sperre für Regler", emergency_stop: "Not-Halt", layer_view: "Schichtansicht", bed_image: "Eigenes Hintergrundbild", bed_image_area: "Bildbereich in mm (x0, y0, x1, y1)", bed_image_opacity: "Deckkraft", bed_grid: "Raster über dem Bild", camera_wake: "Kamera bei stehendem Bild wecken", camera_direct: "Direktstream vom Drucker", camera_direct_url: "Adresse des Direktstreams", camera_webrtc: "WebRTC (paxx12-Firmware)", camera_ha_stream: "Unterwegs: RTSP über Home Assistant", camera_zoom_reset: "Zoom zurücksetzen nach (s)" }; var FORM_HELPERS = { camera: "Leer = Kamera der Integration (erkennt Stock- und angepasste Firmware), sonst die der Moonraker-Integration", prefix: "Nur bei mehreren Druckern nötig", network_tracker: "Zeigt einen Verbindungs-Chip in der Kopfzeile", hide: "Kopfnamen und Temperatur-Presets im YAML-Editor", layout: "Leer = Reiter. Tablet / Monitor: Kamera, Druckauftrag und Druckköpfe links, Reiter rechts (ab ca. 900 px Breite)", bed_image: "z. B. /local/u1_oben.png (Datei unter config/www). Ersetzt Platte und Köpfe in der Draufsicht.", bed_image_area: "Welche Druckerkoordinaten das Bild abdeckt. Leer = genau die Platte 0, 0, 270, 270. Für ein Foto des ganzen Druckers z. B. -40, -30, 310, 360.", layer_view: "Leer = Teil vergrößert. Umschalten geht auch direkt in der Schichtansicht.", emergency_stop: "Leer = anzeigen. Der Not-Halt-Button in Home Assistant bleibt in jedem Fall erhalten.", camera_direct: "Leer = automatisch: im Heimnetz direkt vom Drucker (weniger Verzögerung), bei https oder unterwegs über Home Assistant", camera_direct_url: "Leer = http:///webcam/?action=stream", camera_webrtc: "Leer = automatisch: WebRTC, wenn der Drucker es anbietet (weniger Verzögerung und Datenlast). Klappt keine direkte Verbindung (unterwegs ohne VPN), bleibt MJPEG.", camera_ha_stream: "Leer = automatisch: Ist keine direkte Verbindung zum Drucker möglich (z. B. Nabu Casa), spielt Home Assistant den RTSP-Stream ab – flüssiger und viel weniger Daten als MJPEG. Nur mit RTSP (paxx12).", camera_zoom_reset: "Leer = 60 s ohne Bedienung, 0 = nie. Beim Verlassen der Seite oder Wegscrollen geht der Zoom immer zurück.", camera_wake: "Leer = an. Bleibt das Bild stehen, schickt die Karte camera.start_monitor an den Drucker (nur solange sie sichtbar ist).", camera_mode: "Leer = automatisch (die Kamera-Entität der Integration erkennt Livestream oder Standbilder selbst)", controls_lock: "Leer = 1 min. Gesperrt sind Temperatur- und Lüfterregler, Schnellwahl, Heizungsschalter und Referenzfahrt; das Schloss öffnet sie bis zur gewählten Zeit nach der letzten Bedienung.", camera_height: "Leer = automatisch (Seitenverhältnis des Bildes)", state_accent: "Druckt, pausiert, Fehler, fertig – in den Farben deines Home-Assistant-Designs", accent_color: "Leer = Hauptfarbe deines Home-Assistant-Designs. Färbt Knöpfe, Regler und Hervorhebungen der Karte.", navigation_path: "z. B. /dashboard-drucker/0 – leer = Statusdialog" }; function configForm(mini) { try { const ha = document.querySelector("home-assistant"); if (ha && ha.hass) setLang(ha.hass); } catch (e) { } const opts = (list) => list.map(([value, label]) => ({ value, label: tr(label) })); const name = [ { name: "printer_name", selector: { text: {} } }, { name: "printer_brand", selector: { text: {} } } ]; const advanced = { type: "expandable", name: "advanced", flatten: true, title: tr("Erweitert"), icon: "mdi:cog-outline", schema: [ { name: "prefix", selector: { text: {} } }, ...mini ? [] : [ { name: "network_tracker", selector: { entity: { domain: "device_tracker" } } }, { name: "files_limit", selector: { number: { min: 1, max: 100, mode: "box" } } } ] ] }; const schema = mini ? [ { name: "printer_name", selector: { text: {} } }, { name: "accent_color", selector: { color_rgb: {} } }, { name: "hide_filaments", selector: { boolean: {} } }, { name: "navigation_path", selector: { text: {} } }, advanced ] : [ { type: "grid", name: "", schema: name }, { name: "layout", selector: { select: { mode: "dropdown", options: opts([["tabs", "Reiter"], ["scroll", "Untereinander"], ["tablet", "Tablet / Monitor"]]) } } }, { name: "hide", selector: { select: { multiple: true, mode: "list", options: SECTIONS.map((sec) => ({ value: sec, label: tr(SECTION_LABELS[sec]) })) } } }, { name: "state_accent", selector: { boolean: {} } }, { name: "accent_color", selector: { color_rgb: {} } }, { name: "layer_view", selector: { select: { mode: "dropdown", options: opts([["part", "Teil vergrößert"], ["bed", "Ganzes Druckbett"]]) } } }, { name: "emergency_stop", selector: { select: { mode: "dropdown", options: opts([ ["show", "Anzeigen, mit Rückfrage"], ["hold", "Gesichert: 1 s gedrückt halten"], ["hide", "Ausblenden"] ]) } } }, { name: "controls_lock", selector: { select: { mode: "dropdown", options: opts([ ["off", "Aus"], ["30", "30 s"], ["60", "1 min"], ["120", "2 min"], ["300", "5 min"], ["manual", "Bis zum erneuten Sperren"] ]) } } }, { type: "expandable", name: "bed_group", flatten: true, title: tr("Draufsicht"), icon: "mdi:grid", schema: [ { name: "bed_image", selector: { text: {} } }, { name: "bed_image_area", selector: { text: {} } }, { type: "grid", name: "", schema: [ { name: "bed_image_opacity", selector: { number: { min: 0.1, max: 1, step: 0.05, mode: "box" } } }, { name: "bed_grid", selector: { boolean: {} } } ] } ] }, { type: "expandable", name: "camera_group", flatten: true, title: tr("Kamera"), icon: "mdi:cctv", schema: [ { name: "camera", selector: { entity: { domain: "camera" } } }, { type: "grid", name: "", schema: [ { name: "camera_mode", selector: { select: { mode: "dropdown", options: opts([["auto", "Automatisch"], ["stream", "Livestream"], ["still", "Einzelbilder"]]) } } }, { name: "camera_fit", selector: { select: { mode: "dropdown", options: opts([["contain", "Einpassen"], ["cover", "Füllen"], ["fill", "Strecken"]]) } } }, { name: "camera_height", selector: { number: { min: 120, max: 900, step: 10, mode: "box" } } }, { name: "refresh", selector: { number: { min: 1, max: 60, mode: "box" } } }, { name: "stale_after", selector: { number: { min: 10, max: 3600, mode: "box" } } }, { name: "camera_zoom_reset", selector: { number: { min: 0, max: 3600, mode: "box" } } } ] }, { name: "hide_overlay", selector: { boolean: {} } }, { name: "camera_wake", selector: { boolean: {} } }, { name: "camera_direct", selector: { select: { mode: "dropdown", options: opts([["auto", "Automatisch"], ["off", "Aus (immer über Home Assistant)"]]) } } }, { name: "camera_direct_url", selector: { text: {} } }, { name: "camera_webrtc", selector: { select: { mode: "dropdown", options: opts([["auto", "Automatisch"], ["off", "Aus (MJPEG)"]]) } } }, { name: "camera_ha_stream", selector: { select: { mode: "dropdown", options: opts([["auto", "Automatisch"], ["off", "Aus (MJPEG)"]]) } } }, { name: "printer_image", selector: { text: {} } } ] }, advanced ]; return { schema, computeLabel: (s) => FORM_LABELS[s.name] ? tr(FORM_LABELS[s.name]) : void 0, computeHelper: (s) => FORM_HELPERS[s.name] ? tr(FORM_HELPERS[s.name]) : void 0 }; } // frontend/src/format.js var fmtEuro = (v) => v === null || v === void 0 || Number.isNaN(v) ? "—" : `${Number(v).toLocaleString(LOCALE, { minimumFractionDigits: 2, maximumFractionDigits: 2 })} €`; var THUMB_TONES = /* @__PURE__ */ new Map(); var THUMB_BOXES = ".file-thumb, .dlg-thumb, .hist-thumb, .thumb"; function thumbTone(img) { const key = img.currentSrc || img.src; if (THUMB_TONES.has(key)) return THUMB_TONES.get(key); let tone = ""; try { const c = document.createElement("canvas"); c.width = c.height = 32; const ctx = c.getContext("2d", { willReadFrequently: true }); if (!ctx) return ""; ctx.drawImage(img, 0, 0, 32, 32); const px = ctx.getImageData(0, 0, 32, 32).data; let sum = 0, n = 0, opaque = 0; for (let i = 0; i < px.length; i += 4) { const a = px[i + 3] / 255; if (a < 0.5) continue; opaque++; sum += (0.2126 * px[i] + 0.7152 * px[i + 1] + 0.0722 * px[i + 2]) / 255; n++; } if (n && opaque < px.length / 4 * 0.97) { const lum2 = sum / n; tone = lum2 < 0.3 ? "dark" : lum2 > 0.8 ? "light" : ""; } } catch (e) { tone = ""; } THUMB_TONES.set(key, tone); return tone; } function toneThumb(img) { if (!img || img.tagName !== "IMG") return; const box = img.closest(THUMB_BOXES); if (!box) return; const tone = thumbTone(img); if (tone) box.dataset.toneBg = tone; else delete box.dataset.toneBg; } var fmtDate = (iso) => { if (!iso) return "—"; const dt = new Date(iso); if (Number.isNaN(dt.getTime())) return "—"; return dt.toLocaleString(LOCALE, { day: "2-digit", month: "2-digit", hour: "2-digit", minute: "2-digit" }); }; var archiveName = (file) => String(file).replace(/\.\w+$/, "").replace(/_\d{14}$/, "").replace(/_/g, " "); var clamp = (v, lo, hi) => Math.min(Math.max(v, lo), hi); function fmtMin(min) { if (min === null || min === void 0 || min <= 0) return "—"; const h = Math.floor(min / 60); const m = Math.round(min % 60); return h > 0 ? `${h} h ${m} min` : `${m} min`; } function fmtClock(iso) { if (!iso) return "—"; const d = new Date(iso); if (Number.isNaN(d.getTime())) return "—"; const today = /* @__PURE__ */ new Date(); const sameDay = d.toDateString() === today.toDateString(); const t = d.toLocaleTimeString(LOCALE, { hour: "2-digit", minute: "2-digit" }); return sameDay ? t : `${d.toLocaleDateString(LOCALE, { weekday: "short" })} ${t}`; } function fixed(v, dec = 0) { return Number(v).toLocaleString(LOCALE, { minimumFractionDigits: dec, maximumFractionDigits: dec, useGrouping: false }); } function num(v, dec = 0, unit = "") { if (v === null || v === void 0 || Number.isNaN(v)) return "—"; return `${fixed(v, dec)}${unit ? " " + unit : ""}`; } var fmtInt = (v) => v === null || v === void 0 || Number.isNaN(v) ? "—" : Math.round(v).toLocaleString(LOCALE); var esc = (s) => String(s === null || s === void 0 ? "" : s).replace(/&/g, "&").replace(//g, ">").replace(/"/g, """); // frontend/src/card/state.js var StateMixin = (Base) => class extends Base { /** * State of an entity. Since 2.0 the integration reads the printer values itself * and hands them over in one sensor (``values``/``attrs``, keyed like the * Moonraker integration's entities): ``._`` is answered * from there first, the Moonraker integration is only the fallback. */ _st(id) { const h = this._hass; if (!h) return void 0; const m = id && this._machine(); if (m) { const dot = id.indexOf("."); if (dot > 0 && id.startsWith(m.pre, dot)) { const key = id.slice(dot + m.pre.length); if (Object.prototype.hasOwnProperty.call(m.values, key)) { let e = m.cache.get(id); if (!e) { const real = h.states[id]; e = { entity_id: id, state: String(m.values[key]), attributes: { ...real && real.attributes, ...m.attrs[key] || {} } }; m.cache.set(id, e); } return e; } } } return h.states[id]; } /** The integration's machine values (null without them, e.g. printer offline). */ _machine() { const id = this._ents && this._ents.machine; const st = id && this._hass.states[id]; const a = st && st.attributes; if (!a || !a.values || typeof a.values !== "object") return null; if (!this._mach || this._mach.src !== st || this._mach.prefix !== this._ents.prefix) { this._mach = { src: st, prefix: this._ents.prefix, pre: `.${this._ents.prefix}_`, values: a.values, attrs: a.attrs || {}, entry: a.entry_id, cache: /* @__PURE__ */ new Map() }; } return this._mach; } /** Controls through the integration (2.0) instead of the Moonraker integration's entities. */ _ownControl() { const sv = this._hass && this._hass.services && this._hass.services.snapmaker_u1_card; return !!(sv && sv.machine_command && this._machine()); } _machineCommand(action, target, value) { const data = { action }; if (target !== void 0) data.target = target; if (value !== void 0) data.value = value; const entry = this._machine() && this._machine().entry; if (entry) data.config_entry_id = entry; return this._hass.callService("snapmaker_u1_card", "machine_command", data); } _s(id, fb = null) { const e = this._st(id); if (!e || ["unknown", "unavailable", ""].includes(e.state)) return fb; return e.state; } /** Duration entity in minutes, converted from its unit_of_measurement (fallback: ``unit``). */ _minutes(id, unit, fb = null) { const v = this._n(id, null); if (v === null) return fb; const st = this._st(id); const u = String(st && st.attributes && st.attributes.unit_of_measurement || unit).toLowerCase(); const f = { d: 1440, h: 60, min: 1, s: 1 / 60, ms: 1 / 6e4 }[u]; return v * (f === void 0 ? { h: 60, min: 1, s: 1 / 60 }[unit] || 1 : f); } _n(id, fb = null) { const v = this._s(id, null); if (v === null) return fb; const f = parseFloat(v); return Number.isNaN(f) ? fb : f; } _p(n) { return `${this._ents ? this._ents.prefix : "snapmaker_u1"}_${n}`; } /** Spoolman data from the integration; null if not configured. */ _spoolman() { const st = this._ents && this._ents.filaments && this._st(this._ents.filaments); const sm = st && st.attributes && st.attributes.spoolman; return sm && typeof sm === "object" ? sm : null; } _slotSpool(idx) { const sm = this._spoolman(); return sm && sm.slots ? sm.slots[String(idx)] || null : null; } /** Four slots from the integration, otherwise null. */ _slots() { const st = this._ents && this._ents.filaments && this._st(this._ents.filaments); const s = st && st.attributes && st.attributes.slots; return Array.isArray(s) && s.length ? s : null; } /** Loaded bed mesh from the integration's sensor; null without one. */ _meshData() { const st = this._ents && this._ents.bedMesh && this._st(this._ents.bedMesh); const a = st && st.attributes; if (!a || !Array.isArray(a.matrix) || !a.matrix.length || ["unknown", "unavailable"].includes(st.state)) return null; return { ...a, range: parseFloat(st.state) }; } /** Top cover state; null if none is plugged in (entity missing or unavailable). */ _coverData() { const st = this._ents && this._ents.topCover && this._st(this._ents.topCover); if (!st || ["unknown", "unavailable"].includes(st.state)) return null; return { mode: st.state, ...st.attributes }; } /** Chamber heater (Panda Breath / DragonBreath); null without one. */ _chamberData() { const st = this._ents && this._ents.chamber && this._st(this._ents.chamber); if (!st || st.state === "unavailable") return null; const temp = parseFloat(st.state); return { ...st.attributes, temperature: Number.isNaN(temp) ? null : temp }; } _collect() { if (!this._hass) return; const P = (n) => this._p(n); const klipper = this._s(`sensor.${P("printer_state")}`, null); const slots = this._slots(); const heads = SUFFIX.map((sfx, i) => { const meta = this._cfg.toolheads && this._cfg.toolheads[i] || {}; const slot = slots ? slots[i] : null; const material = slot ? slot.loaded ? [slot.type, slot.sub_type].filter(Boolean).join(" ") || tr("Unbekannt") : tr("Leer") : meta.material || "—"; const color = slot ? slot.loaded && slot.color ? slot.color : "var(--u1-outline)" : meta.color || "var(--u1-outline)"; return { idx: i, sfx, name: meta.name || tr("Kopf {n}", { n: i + 1 }), material, color, colors: slot && slot.loaded && slot.colors && slot.colors.length ? slot.colors : [color], vendor: slot && slot.loaded ? slot.vendor : null, official: !!(slot && slot.official && slot.loaded), live: !!slot, temp: this._n(`sensor.${P(`extruder${sfx}_temperature`)}`), target: this._n(`number.${P(`extruder${sfx}_target`)}`, 0), power: this._n(`sensor.${P(`extruder${sfx}_power`)}`, 0), fan: this._n(`sensor.${P(`e${i}_nozzle_fan`)}`, 0), loaded: slot ? !!slot.loaded : this._s(`binary_sensor.${P(`e${i}_filament`)}`) === "on", heater: this._s(`switch.${P(`output_pin_e${i}_heat_sw`)}`), mcuLoad: this._n(`sensor.${P(`mcu_e${i}_load`)}`), mcuAwake: this._n(`sensor.${P(`mcu_e${i}_awake`)}`), targetEntity: `number.${P(`extruder${sfx}_target`)}` }; }); const fst = this._ents && this._ents.filaments && this._st(this._ents.filaments); const fw = fst && fst.attributes && Number.isInteger(fst.attributes.active_head) ? fst.attributes.active_head : null; const live = this._liveHead && Date.now() - this._liveHead.at < 15e3 ? this._liveHead.idx : null; let active = live !== null ? live : fw !== null ? fw : -1; if (active < 0) { let best = 0; heads.forEach((h, i) => { if (h.target > best) { best = h.target; active = i; } }); } heads.forEach((h, i) => { h.active = i === active; }); const hot = active >= 0 ? heads[active] : heads[0]; const liveState = fst && fst.attributes && fst.attributes.live ? fst.attributes.print_state : null; const state = liveState || this._s(`sensor.${P("current_print_state")}`, "standby"); this._d = { online: klipper !== null, klipper, state, printing: state === "printing", paused: state === "paused", active: state === "printing" || state === "paused", idleTimeout: this._s(`sensor.${P("idle_timeout_state")}`, "—"), queueState: this._s(`sensor.${P("queue_state")}`, "—"), jobsQueued: (this._attr("queue", "jobs") || []).length, message: this._s(`sensor.${P("current_print_message")}`) || this._s(`sensor.${P("printer_message")}`, ""), display: this._s(`sensor.${P("current_display_message")}`, ""), filename: (this._s(`sensor.${P("filename")}`, "") || "").replace(/\.(gcode|3mf)$/i, ""), progress: this._n(`sensor.${P("progress")}`, 0), // Durations in minutes (fmtMin). The unit comes from the entity: users can // change the display unit, and the own sensor (min) differs from Moonraker's (h). elapsed: this._minutes(`sensor.${P("print_duration")}`, "min", 0), // Remaining/finish time: own sensors (file time profile), else the Moonraker integration remaining: (() => { const v = this._ents.remaining && this._minutes(this._ents.remaining, "min"); return v !== null && v !== void 0 ? v : this._minutes(`sensor.${P("print_time_left")}`, "h", 0); })(), projected: this._minutes(`sensor.${P("print_projected_total_duration")}`, "h", 0), slicerLeft: this._minutes(`sensor.${P("slicer_print_time_left_estimate")}`, "h", 0), slicerTotal: this._minutes(`sensor.${P("slicer_print_duration_estimate")}`, "h", 0), eta: this._ents.finish && this._s(this._ents.finish) || this._s(`sensor.${P("print_eta")}`), filamentUsed: this._n(`sensor.${P("filament_used")}`, 0), layer: this._n(`sensor.${P("current_layer")}`, 0), totalLayers: this._n(`sensor.${P("total_layer")}`, 0), objectHeight: this._n(`sensor.${P("object_height")}`), printSpeed: this._n(`sensor.${P("print_speed")}`, 0), // Machine controls of the integration (flow, bed mesh, top cover, head park states) flow: this._ents.flow ? this._n(this._ents.flow) : null, mesh: this._meshData(), cover: this._coverData(), chamber: this._chamberData(), headStates: fst && fst.attributes && Array.isArray(fst.attributes.head_states) ? fst.attributes.head_states : [], hot, heads, bed: this._n(`sensor.${P("bed_temperature")}`, 0), bedTarget: this._n(`number.${P("bed_target")}`, 0), bedPower: this._n(`sensor.${P("bed_power")}`, 0), cavity: this._n(`sensor.${P("cavity_temp")}`), cavityFan: this._n(`sensor.${P("cavity_fan")}`, 0), powerFan: this._n(`sensor.${P("power_fan")}`, 0), posX: this._n(`sensor.${P("toolhead_position_x")}`), posY: this._n(`sensor.${P("toolhead_position_y")}`), posZ: this._n(`sensor.${P("toolhead_position_z")}`), stepX: this._n(`sensor.${P("stepper_x_temp")}`), stepY: this._n(`sensor.${P("stepper_y_temp")}`), speedFactor: this._n(`number.${P("speed_factor")}`, 100), partFan: this._n(`number.${P("fan_speed")}`, 0), cavityFanSet: this._n(`number.${P("cavity_fan_speed")}`, 0), mcuLoad: this._n(`sensor.${P("mcu_load")}`), mcuAwake: this._n(`sensor.${P("mcu_awake")}`), memory: this._n(`sensor.${P("memory_used")}`), cpuTemp: this._n(`sensor.${P("cpu_temp")}`), sysLoad: this._n(`sensor.${P("system_load")}`), totalsJobs: this._n(`sensor.${P("totals_jobs")}`, 0), totalsTime: this._s(`sensor.${P("totals_print_time")}`, "—"), longest: this._s(`sensor.${P("longest_print")}`, "—"), totalsFilament: this._n(`sensor.${P("totals_filament_used")}`, 0), light: this._s(`light.${this._p("led_cavity_led")}`) === "on", lightReal: this._s(`light.${this._p("led_cavity_led")}`) === "on", lightBri: (this._st(`light.${this._p("led_cavity_led")}`) || {}).attributes?.brightness ?? 0, network: this._cfg.network_tracker ? this._s(this._cfg.network_tracker) : null, files: this._files(), tc: this._toolChanges(), power: this._power(), usage: this._usage(), history: this._historyList(), timelapses: this._timelapseList(), queue: this._attr("queue", "jobs"), stats: this._statsData(), maint: this._attr("maintenance", "items"), backup: (() => { const st = this._ents && this._ents.maintenance && this._st(this._ents.maintenance); return st && st.attributes && st.attributes.config_backup || null; })(), errors: this._attr("errors", "errors") || [] }; } /** List attribute of one of our sensors; null if the sensor does not exist. */ _attr(key, name) { const st = this._ents && this._ents[key] && this._st(this._ents[key]); const v = st && st.attributes && st.attributes[name]; return Array.isArray(v) ? v : null; } _statsData() { const st = this._ents && this._ents.statistics && this._st(this._ents.statistics); const a = st && st.attributes; if (!a || !Array.isArray(a.months) || !a.months.length) return null; return { months: a.months, totals: a.totals || {}, top: a.top_files || [], hours: parseFloat(st.state), materials: a.materials || [], colors: a.colors || [] }; } _errText(e) { const key = LANG === "de" ? "de" : "en"; let t = e.text && e.text[key] || e.message || ""; if (!e.known && e.message) t = `${t}: ${e.message}`; return t; } /** The integration's power switch (options) incl. power draw. */ _power() { const id = this._ents && this._ents.power; const st = id && this._st(id); if (!st) return null; const a = st.attributes || {}; return { entity: id, on: st.state === "on", available: st.state !== "unavailable" && st.state !== "unknown", shuttingDown: !!a.shutting_down, poweringOn: !!a.powering_on, autoOn: !!a.auto_on, autoOffPending: !!a.auto_off_pending, watts: a.power_sensor ? this._n(a.power_sensor) : null, hasEnergy: !!a.energy_sensor }; } /** Consumption and cost of the running or last print. */ _usage() { const e = this._ents || {}; const en = e.energyPrint && this._st(e.energyPrint); const co = e.costPrint && this._st(e.costPrint); if (!en && !co) return null; const val = (st) => st && !Number.isNaN(parseFloat(st.state)) ? parseFloat(st.state) : null; const a = (en || co).attributes || {}; return { energy: val(en), cost: val(co), inProgress: !!a.in_progress, result: a.result || null, hasEnergy: !!en, hasCost: !!co, currency: co && co.attributes.unit_of_measurement || "€" }; } _historyList() { const st = this._ents && this._ents.history && this._st(this._ents.history); const list = st && st.attributes && st.attributes.prints; return Array.isArray(list) ? list : null; } _timelapseList() { const st = this._ents && this._ents.timelapses && this._st(this._ents.timelapses); const a = st && st.attributes; if (!a || !Array.isArray(a.videos)) return null; return { videos: a.videos, url: a.url, playable: a.playable !== false, archive: a.archive || null }; } /** Tool changes from the integration's sensors; null without firmware counters. */ _toolChanges() { const e = this._ents || {}; const tot = e.toolChanges && this._st(e.toolChanges); if (!tot || !/^\d+$/.test(tot.state)) return null; const pr = e.toolChangesPrint && this._st(e.toolChangesPrint); const pa = pr && pr.attributes || {}; const heads = Array.isArray(tot.attributes.heads) ? tot.attributes.heads : []; const threshold = tot.attributes.maintenance_threshold || null; const since = heads.length ? Math.max(...heads.map((h) => h.since_maintenance || 0)) : null; return { total: Number(tot.state), heads, threshold, since, print: pr && /^\d+$/.test(pr.state) ? Number(pr.state) : null, inProgress: !!pa.in_progress, file: pa.file || null, result: pa.result || null }; } /** The file list comes from a sensor attribute, not from a fetch, * so this part also stays on the HA connection. */ _files() { const st = this._ents && this._ents.files && this._st(this._ents.files); const raw = st && st.attributes && st.attributes.files; if (!Array.isArray(raw)) return null; return raw.filter((f) => f && f.path).slice(0, this._cfg.files_limit || 12); } }; // frontend/src/card/controls.js var OWN_BUTTONS = { pause_print: ["pause"], resume_print: ["resume"], cancel_print: ["cancel"], emergency_stop: ["emergency_stop"], home_all_axes: ["home", "all"], home_x_axis: ["home", "x"], home_y_axis: ["home", "y"], home_z_axis: ["home", "z"] }; var ControlsMixin = (Base) => class extends Base { _press(name) { const own = this._ownControl() && OWN_BUTTONS[name]; if (own) this._machineCommand(...own); else this._hass.callService("button", "press", { entity_id: `button.${this._p(name)}` }); } /** Key of a machine value for an entity id of the printer (``number._bed_target`` → ``bed_target``). */ _machineKey(entity) { const m = this._ownControl() && this._machine(); if (!m) return null; const dot = entity.indexOf("."); const key = dot > 0 && entity.startsWith(m.pre, dot) ? entity.slice(dot + m.pre.length) : null; return key && Object.prototype.hasOwnProperty.call(m.values, key) ? key : null; } _setNumber(entity, value) { if (this._d && this._d.active && /_target$/.test(entity) && !confirm(tr("Solltemperatur während des Drucks auf {v} °C ändern?", { v: Number(value) }))) { this._busy.delete(entity); this._patch(); return; } const key = this._machineKey(entity); if (key) this._machineCommand("set", key, Number(value)); else this._hass.callService("number", "set_value", { entity_id: entity, value: Number(value) }); } // ── Pending commands ────────────────────────────────────────────────────── // Pause parks the head first and the Moonraker integration polls: without // feedback a tap looks ignored. A pending command shows at once that it was // sent ("Pausiere …", light already toggled) until the printer confirms it. /** key: "pause" | "resume" | "cancel" | "light" | "t:"; done(d) = confirmed. */ _pend(key, done, ms = 3e4, extra = {}) { if (!this._pending) this._pending = /* @__PURE__ */ new Map(); this._pending.set(key, { done, until: Date.now() + ms, ...extra }); this._pendTimer(); this._rerender(); } /** One timer for the earliest expiry; none while nothing waits. */ _pendTimer() { clearTimeout(this._pendT); this._pendT = null; if (!this._pending || !this._pending.size) return; const next = Math.min(...[...this._pending.values()].map((p) => p.until)); this._pendT = setTimeout(() => { this._pendT = null; const before = this._lastPendKey; if (this._settlePending()) { if (this._pendingKey() !== before) this._rerender(); else { this._applyPending(); this._patch(); } } this._pendTimer(); }, Math.max(0, next - Date.now()) + 50); } _isPending(key) { const p = this._pending && this._pending.get(key); return !!p && p.until > Date.now(); } /** Drop confirmed and expired commands; true = something changed. */ _settlePending() { if (!this._pending || !this._pending.size || !this._d) return false; const now = Date.now(); let changed = false; for (const [key, p] of this._pending) { let ok = false; try { ok = p.done(this._d); } catch (e) { ok = true; } if (ok || p.until <= now) { this._pending.delete(key); changed = true; if (!ok && p.timeout) this._toast(p.timeout); } } if (changed && !this._pending.size) this._pendTimer(); return changed; } /** Optimistic values while a command is on its way (light). */ _applyPending() { const d = this._d; if (!d) return; const l = this._pending && this._pending.get("light"); d.light = l && l.until > Date.now() ? l.want : d.lightReal; } _rerender() { this._renderKey = null; if (this._d) this._render(); } _pendingKey() { this._lastPendKey = this._pending ? [...this._pending.keys()].filter((k) => k !== "light" && !k.startsWith("t:")).join(",") : ""; return this._lastPendKey; } _spin() { return ``; } /** Pause / resume / cancel / light as buttons, with a waiting state. */ _stageActions() { const d = this._d; const busy = (key, cls, icon, label, wait) => this._isPending(key) ? `` : ``; const out = []; const cancelling = this._isPending("cancel"); if (d.printing && !cancelling) out.push(busy("pause", "filled", "mdi:pause", tr("Pause"), tr("Pausiere …"))); if (d.paused && !cancelling) out.push(busy("resume", "filled", "mdi:play", tr("Fortsetzen"), tr("Setze fort …"))); if (d.active) out.push(busy("cancel", "outline", "mdi:stop", tr("Abbrechen"), tr("Breche ab …"))); out.push(``); return out.join(""); } _pausePrint() { this._press("pause_print"); this._pend( "pause", (d) => d.paused || !d.active, 9e4, { timeout: tr("Der Drucker hat die Pause noch nicht bestätigt.") } ); } _resumePrint() { this._press("resume_print"); this._pend( "resume", (d) => d.printing || !d.active, 9e4, { timeout: tr("Der Drucker hat das Fortsetzen noch nicht bestätigt.") } ); } _cancelPrint() { this._press("cancel_print"); this._pend( "cancel", (d) => !d.active, 12e4, { timeout: tr("Der Drucker hat den Abbruch noch nicht bestätigt.") } ); } _toggleLight() { const want = !this._d.light; const light = `light.${this._p("led_cavity_led")}`; if (this._machineKey(light)) this._machineCommand("switch", "led_cavity_led", want); else this._hass.callService("light", "toggle", { entity_id: light }); if (!this._pending) this._pending = /* @__PURE__ */ new Map(); this._pending.set("light", { done: (d) => d.lightReal === want, until: Date.now() + 15e3, want }); this._pendTimer(); this._applyPending(); this._patch(); } /** Switch toggles (heater, filter): spinner until the entity has changed. */ _toggleEntity(id, btn) { const before = this._s(id); const key = this._machineKey(id); if (key && /^(output_pin|led)_/.test(key)) this._machineCommand("switch", key, before !== "on"); else this._hass.callService(id.split(".")[0], "toggle", { entity_id: id }); if (!this._pending) this._pending = /* @__PURE__ */ new Map(); this._pending.set(`t:${id}`, { done: () => this._s(id) !== before, until: Date.now() + 15e3 }); this._pendTimer(); if (btn) btn.classList.add("pending"); } /** Take the head's previous spool again (one tap, after reloading the filament). */ async _restoreSpool(idx, spoolId) { this._pend(`r:${idx}`, () => { const sm = this._spoolman(); return !sm || !(sm.restore || {})[String(idx)]; }, 2e4); try { await this._hass.callService(DOMAIN, "set_spool", { slot: idx + 1, spool_id: spoolId, ...this._entryData() }, void 0, false); } catch (err) { if (this._pending) this._pending.delete(`r:${idx}`); this._rerender(); alert(err && (err.message || err.error) || String(err)); } } // ── Control lock ──────────────────────────────────────────────────────── // On a phone it is easy to brush a slider while scrolling. So sliders, // presets, heater switches and homing are locked until the padlock is // tapped; they lock again 60 s after the last interaction. /** * controls_lock: "off" | seconds ("30", "60", "120", "300") | "manual" * (stays open until locked again). Legacy: unlock_controls: true = "off". */ _lockMode() { if (this._cfg.unlock_controls) return "off"; const v = this._cfg.controls_lock; if (v === void 0 || v === null || v === "") return 60; if (v === false || v === "off") return "off"; if (v === "manual") return "manual"; const n = parseInt(v, 10); return n > 0 ? n : 60; } _unlockMs() { const m = this._lockMode(); return m === "manual" ? Infinity : m * 1e3; } _unlockTitle() { const m = this._lockMode(); return m === "manual" ? tr("Regler entsperren") : tr("Regler entsperren ({n} s)", { n: m }); } _locked() { return this._lockMode() !== "off" && !(this._unlockUntil > Date.now()); } _lockBtn() { if (this._lockMode() === "off") return ""; const locked = this._locked(); return ``; } _toggleLock() { this._unlockUntil = this._locked() ? Date.now() + this._unlockMs() : 0; this._applyLock(); } _touchLock() { if (!this._locked()) this._unlockUntil = Date.now() + this._unlockMs(); } _applyLock() { const r = this.shadowRoot && this.shadowRoot.getElementById("u1card"); if (!r) return; const locked = this._locked(); r.querySelectorAll("[data-lockable]").forEach((el) => { el.classList.toggle("locked", locked); const ctrls = el.matches("button, input") ? [el] : el.querySelectorAll("button, input"); ctrls.forEach((c) => { c.disabled = locked; }); }); r.querySelectorAll("[data-su1-lock]").forEach((b) => { b.setAttribute("aria-pressed", String(!locked)); b.title = locked ? this._unlockTitle() : tr("Regler sperren"); b.innerHTML = `${locked ? tr("Gesperrt") : tr("Entsperrt")}`; }); } _more(entityId) { if (this._hass && !this._hass.states[entityId]) return; this.dispatchEvent(new CustomEvent("hass-more-info", { detail: { entityId }, bubbles: true, composed: true })); } // ── Building blocks ────────────────────────────────────────────────────── _statusTone() { const d = this._d; if (!d.online) return "off"; if (d.state === "error") return "error"; if (d.paused) return "warn"; if (d.printing) return "active"; if (d.state === "complete") return "ok"; return "idle"; } _statusLabel() { const d = this._d; if (!d.online) return tr("Offline"); if (this._isPending("cancel")) return tr("Breche ab …"); if (this._isPending("pause")) return tr("Pausiere …"); if (this._isPending("resume")) return tr("Setze fort …"); return { printing: tr("Druckt"), standby: tr("Bereit"), complete: tr("Fertig"), cancelled: tr("Abgebrochen"), paused: tr("Pausiert"), error: tr("Fehler") }[d.state] || d.state; } _spoolSvg(color, active, colors = null) { const list = colors && colors.length > 1 ? colors : [color]; const C = 2 * Math.PI * 17; const seg = C / list.length; const ring = list.map((c, k) => ``).join(""); return ``; } _slider(opts) { const { entity, label, min, max, step, value, unit, presets, dec } = opts; const st = this._st(entity); if (!st) return ""; const mn = min ?? st.attributes.min ?? 0; const mx = max ?? st.attributes.max ?? 100; const sp = step ?? st.attributes.step ?? 1; const chips = (presets || []).map( (p) => `` ).join(""); return `
${esc(label)} ${num(value, dec ?? 0, unit)}
${chips ? `
${chips}
` : ""}
`; } _stat(k, v, cls = "", hint = "") { const t = hint ? ` title="${esc(hint)}"` : ` title="${esc(k)}"`; return `
${esc(k)}
${v}
`; } _row(k, v, entity, title) { const attr = (entity ? ` data-more="${entity}" style="cursor:pointer"` : "") + (title ? ` title="${esc(title)}"` : ""); return `
${esc(k)}${v}
`; } _loadText() { const d = this._d; if (d.sysLoad === null || d.sysLoad === void 0) return "—"; const fst = this._ents && this._ents.filaments && this._st(this._ents.filaments); const cores = fst && fst.attributes && fst.attributes.cpu_count; return cores ? `${num(d.sysLoad, 2)} · ${tr("{p} % von {n} Kernen", { p: Math.round(d.sysLoad / cores * 100), n: cores })}` : num(d.sysLoad, 2); } _toast(message) { this.dispatchEvent(new CustomEvent("hass-notification", { detail: { message }, bubbles: true, composed: true })); } /** Call an integration service; errors are shown instead of swallowed. */ async _call(service, data) { try { await this._hass.callService(DOMAIN, service, { ...data, ...this._entryData() }, void 0, false); return true; } catch (err) { alert(err && (err.message || err.error) || String(err)); return false; } } _reprint(idx) { const h = (this._d.history || [])[idx]; if (!h) return; this._openPrint(h.source || h.file, { mapping: h.mapping, options: h.options, pause_layers: h.pause_layers }); } }; // frontend/src/color.js function hexRgb(c) { const m = /^#?([0-9a-f]{6})/i.exec(c || ""); if (!m) return null; const n = parseInt(m[1], 16); return [n >> 16 & 255, n >> 8 & 255, n & 255]; } function colorDistance(a, b) { const x = hexRgb(a), y = hexRgb(b); if (!x || !y) return 765; const rm = (x[0] + y[0]) / 2; const dr = x[0] - y[0], dg = x[1] - y[1], db = x[2] - y[2]; return Math.sqrt((2 + rm / 256) * dr * dr + 4 * dg * dg + (2 + (255 - rm) / 256) * db * db); } function onColor(c) { const x = hexRgb(c); if (!x) return "#fff"; const lum2 = (0.299 * x[0] + 0.587 * x[1] + 0.114 * x[2]) / 255; return lum2 > 0.6 ? "#1b1b1f" : "#fff"; } function suggestMapping(filaments, slots) { const loaded = slots.filter((s) => s.loaded); const taken = /* @__PURE__ */ new Set(); const map = {}; filaments.filter((f) => f.used).forEach((f) => { if (!loaded.length) { map[f.index] = f.index % 4; return; } const same = (s) => !!(f.type && s.type && f.type.toUpperCase() === s.type.toUpperCase()); const score = (s) => [same(s) ? 0 : 1, colorDistance(f.color, s.color), taken.has(s.index) ? 1 : 0]; let best = loaded[0], bs = score(best); for (const s of loaded.slice(1)) { const sc = score(s); if (sc[0] < bs[0] || sc[0] === bs[0] && (sc[1] < bs[1] || sc[1] === bs[1] && sc[2] < bs[2])) { best = s; bs = sc; } } map[f.index] = best.index; taken.add(best.index); }); return map; } // frontend/src/card/overview.js var OverviewMixin = (Base) => class extends Base { _sectionStage() { const d = this._d; const fit = ["cover", "contain", "fill"].includes(this._cfg.camera_fit) ? this._cfg.camera_fit : "contain"; const h = parseInt(this._cfg.camera_height, 10) || 0; const still = this._cfg.printer_image; const frameStyle = h ? `min-height:${h}px;height:${h}px` : `aspect-ratio:${this._camAspect || "16 / 9"};max-height:${parseInt(this._cfg.camera_max_height, 10) || 520}px`; const own = !still && this._ents.ownCamera && this._st(this._ents.ownCamera); if (own && own.attributes.mode === "none") return this._noCamera(); const img = still ? `Snapmaker U1` : `${tr(`; const thumbEnt = this._st(this._ents.thumbnail); const hud = this._cfg.camera_overlay !== false && d.active && !d.paused && d.state !== "error" ? this._hud() : ""; const thumb = thumbEnt && thumbEnt.attributes.entity_picture && d.filename ? `
${tr(${esc(d.filename)}
` : ""; let overlay = ""; let dim = "0"; if (d.paused) { dim = "1"; overlay = `
${tr("Pausiert")}
${tr("Temperaturen werden gehalten")}
`; } else if (d.state === "error") { dim = "1"; overlay = `
${tr("Druck gestoppt")}
${esc(d.errors[0] && this._errText(d.errors[0]) || d.message || tr("Der Drucker meldet einen Fehler"))}
`; } const tone = this._statusTone(); const sub = !d.active && (d.display || d.message) ? `${esc(d.display || d.message)}` : ""; const pill = `
${this._statusLabel()}${sub}
`; const actions = [this._stageActions()]; return `
${img}
${tr("Bild veraltet")}
${document.fullscreenEnabled || document.webkitFullscreenEnabled ? `` : ""} ${this._hasCamera2() ? `` : ""}
${pill} ${thumb} ${overlay} ${hud}
${actions.join("")}
`; } _noCamera() { const actions = [this._stageActions()]; return `
${tr("Keine Kamera erkannt. Der Selbsttest im System-Reiter zeigt, was die Integration gefunden hat.")}
${actions.join("")}
`; } /** Progress directly on the camera image (running print). */ _hud() { const d = this._d; const h = d.heads.find((x) => x.active); const head = h ? ` ${esc(h.name)} · ${esc(h.material)}` : ""; return `
${d.progress.toFixed(0)}% ${d.layer} / ${d.totalLayers} ${fmtMin(d.remaining)} ${fmtClock(d.eta)} ${head}
`; } _sectionJob() { const d = this._d; const pct = d.progress; const tone = d.state === "error" ? "error" : d.paused ? "warn" : ""; const w = (k, v) => `${v}`; if (!d.active) return this._sectionLastPrint(); const grid = d.active ? [ this._stat(tr("Schicht"), w("layer", `${d.layer} / ${d.totalLayers}`)), this._stat(tr("Restzeit"), w("remain", fmtMin(d.remaining)), "sm"), this._stat(tr("Fertig um"), w("eta", fmtClock(d.eta)), "sm"), this._stat(tr("Bisher"), w("elapsed", fmtMin(d.elapsed)), "sm"), this._stat(tr("Filament"), w("fil", num(d.filamentUsed, 1, "m"))), this._stat(tr("Höhe"), w("height", num(d.objectHeight, 1, "mm"))), this._stat(tr("Geschw."), w("pspeed", num(d.printSpeed, 0, "mm/s")), "sm"), this._stat(tr("Slicer-Rest"), w("sremain", fmtMin(d.slicerLeft)), "sm") ] : [ this._stat(tr("Drucke gesamt"), w("tjobs2", num(d.totalsJobs, 0))), this._stat(tr("Warteschlange"), w("queued", num(d.jobsQueued, 0))), this._stat(tr("Zuletzt"), w("elapsed", fmtMin(d.elapsed)), "sm"), this._stat(tr("Filament"), w("fil", num(d.filamentUsed, 1, "m"))) ]; return `
${d.active ? tr("Laufender Druck") : tr("Letzter Druck")}
${esc(d.filename || "—")}
${fixed(pct, 1)} ${tr("Prozent")}
${grid.join("")}
`; } /** Without a running print: last print from the history instead of empty zeros. */ _sectionLastPrint() { const d = this._d; const h = (d.history || [])[0]; const q = (d.queue || []).length; if (!h) { return `
${tr("Letzter Druck")}
${tr("Noch keine Drucke erfasst. Die Historie füllt sich ab dem nächsten Druck.")}
${this._stat(tr("Drucke gesamt"), num(d.totalsJobs || d.stats && d.stats.totals.prints || 0, 0))} ${this._stat(tr("Warteschlange"), fmtInt(q))}
`; } const [rawLabel, tone] = RESULT[h.result] || [h.result || "—", ""]; const tiles = [ [tr("Dauer"), h.duration ? fmtMin(h.duration / 60) : "—"], [tr("Filament"), h.filament_g !== void 0 && h.filament_g !== null ? `${Math.round(h.filament_g)} g` : "—"], h.energy !== void 0 && h.energy !== null ? [tr("Strom"), num(h.energy, 2, "kWh")] : null, h.total_cost !== void 0 && h.total_cost !== null ? [tr("Kosten"), fmtEuro(h.total_cost)] : null, [tr("Drucke gesamt"), num(d.totalsJobs || d.stats && d.stats.totals.prints || 0, 0)], [tr("Warteschlange"), fmtInt(q)] ].filter(Boolean).map(([k, v]) => this._stat(k, v, "sm")).join(""); const thumb = h.thumb ? `` : ``; return `
${tr("Letzter Druck")} ${esc(tr(rawLabel))}
${thumb}
${esc(h.name || h.file || "—")}
${esc(fmtDate(h.ended))}${h.error ? ` · ${esc(h.error)}` : ""}
${tiles}
`; } _sectionHeads() { const d = this._d; const cards = d.heads.map((h) => { const heaterBtn = h.heater !== null ? `` : ""; return `
${this._spoolSvg(h.color, h.active, h.colors)}
${esc(h.name)}${this._headBadge(h)}
${esc(h.material)}
${h.vendor ? `
${esc(h.vendor)}
` : ""}
${this._spoolLine(h)}
${h.loaded ? tr("Geladen") : tr("Leer")}
${num(h.temp, 0, "°C")}${h.target > 0 ? ` → ${h.target.toFixed(0)} °C` : ""}
${tr("Lüfter {v}", { v: num(h.fan, 0, "%") })} ${tr("Heiz. {v}", { v: num(h.power, 0, "%") })}
${this._slider({ entity: h.targetEntity, label: tr("Soll"), value: h.target, unit: "°C", presets: this._cfg.nozzle_presets })} ${heaterBtn}
`; }).join(""); return `
${tr("Druckköpfe")} ${this._lockBtn()}
${cards}
`; } /** "RFID" for a read tag; SpoolLink marks Spoolman spools as official without a tag. */ _headBadge(h) { if (!h.official) return ""; const slot = (this._slots() || [])[h.idx] || {}; const sm = this._spoolman(); const tag = slot.rfid && slot.rfid.tag; if (!tag && sm && sm.spoollink && this._slotSpool(h.idx)) { return ` Spoolman`; } return ` RFID`; } /** The head's spool from Spoolman (only with Spoolman configured). */ _spoolLine(h) { const sm = this._spoolman(); if (!sm) return ""; const sp = this._slotSpool(h.idx); if (!h.loaded && !sp) return ""; const back = !sp && sm.online && sm.restore && sm.restore[String(h.idx)]; if (back) { const busy = this._isPending(`r:${h.idx}`); return `
`; } if (!sp) { return ``; } const rest = sp.remaining_weight; const pct = rest != null && sp.initial_weight ? clamp(rest / sp.initial_weight * 100, 0, 100) : null; const low = rest != null && rest < (sm.low || 0); return ``; } /** Spool runs out during the print (integration: time profile x Spoolman remainder). */ _runoutText(idx) { const fst = this._ents && this._ents.filaments && this._st(this._ents.filaments); const r = fst && fst.attributes && fst.attributes.runout && fst.attributes.runout[String(idx)]; if (!r) return ""; const heads = this._d ? this._d.heads : []; const take = r.takeover !== null && r.takeover !== void 0 ? ` · ${tr("{h} übernimmt", { h: (heads[r.takeover] || {}).name || tr("Kopf {n}", { n: r.takeover + 1 }) })}` : ""; return `${tr("leer in ~{m} min", { m: r.minutes })}${esc(take)}`; } /** Form in the picker dialog: create a spool in Spoolman, prefilled from the head's filament. */ _newSpoolForm(dlg, idx) { const slot = (this._slots() || [])[idx] || {}; const head = this._d && this._d.heads[idx] || { name: `E${idx}` }; const rfid = slot.rfid || {}; const color = /^#[0-9a-f]{6}$/i.test(slot.color || "") ? slot.color : "#ffffff"; const vendor = slot.vendor && slot.vendor !== "Generic" ? slot.vendor : rfid.manufacturer || rfid.vendor || "Generic"; const material = (slot.type || "PLA").toUpperCase(); const name = [material, slot.sub_type].filter(Boolean).join(" "); dlg.innerHTML = `
${esc(tr("Neue Spule für {head}", { head: head.name }))}
${tr("Hersteller und Filament werden in Spoolman wiederverwendet oder angelegt.")}
`; dlg.querySelector("[data-close]").addEventListener("click", () => dlg.close()); dlg.querySelector("[data-back]").addEventListener("click", () => this._openSpoolPicker(idx)); const form = dlg.querySelector("[data-newspoolform]"); form.addEventListener("submit", async (e) => { e.preventDefault(); const f = new FormData(form); const opt = (k) => String(f.get(k) || "").trim() === "" ? {} : { [k]: Number(f.get(k)) }; const data = { slot: idx + 1, vendor: String(f.get("vendor") || "").trim() || "Generic", material: String(f.get("material") || "").trim(), name: String(f.get("name") || "").trim() || void 0, color: f.get("color"), weight: Number(f.get("weight")), ...opt("spool_weight"), ...opt("price"), ...this._entryData() }; if (!data.name) delete data.name; const btn = form.querySelector("button[type=submit]"); btn.disabled = true; try { const res = await this._hass.callService(DOMAIN, "create_spool", data, void 0, false, true); const id = res && res.response && res.response.spool_id; dlg.close(); this._toast(tr("Spule #{id} angelegt und {head} zugeordnet", { id: id ?? "?", head: head.name })); } catch (err) { btn.disabled = false; const el = form.querySelector(".dlg-error"); el.hidden = false; el.textContent = err && err.message || String(err); } }); } _openSpoolPicker(idx) { const sm = this._spoolman(); if (!sm) return; const slot = (this._slots() || [])[idx] || {}; const cur = this._slotSpool(idx); const head = this._d && this._d.heads[idx] || { name: `E${idx}` }; const host = this.shadowRoot.getElementById("u1dlg"); let dlg = host.querySelector("dialog.u1spool"); if (!dlg) { host.insertAdjacentHTML("beforeend", ``); dlg = host.querySelector("dialog.u1spool"); dlg.addEventListener("click", (e) => { if (e.target === dlg) dlg.close(); }); } const type = (slot.type || "").toUpperCase(); const list = (sm.spools || []).slice().sort((a, b) => ((a.material || "").toUpperCase() === type ? 0 : 1) - ((b.material || "").toUpperCase() === type ? 0 : 1) || colorDistance(slot.color, a.color) - colorDistance(slot.color, b.color) || (a.name || "").localeCompare(b.name || "")); const used = Object.entries(sm.slots || {}).filter(([k, v]) => v && Number(k) !== idx).map(([k, v]) => [v.id, Number(k)]); const usedBy = new Map(used); const item = (sp) => { const other = usedBy.get(sp.id); return ``; }; dlg.innerHTML = `
${esc(tr("Spule für {head}", { head: head.name }))}
${esc([slot.type, slot.sub_type, slot.vendor].filter(Boolean).join(" ") || tr("kein Filament erkannt"))}
${sm.spoollink ? `
${tr("SpoolLink im Drucker: die Wahl geht an den Drucker (SET_SPOOL_ID), er übernimmt das Filament der Spule.")}
` : slot.official ? "" : `
${tr("Material, Hersteller und Farbe der gewählten Spule werden in den Kopf übernommen.")}
`} ${sm.online ? "" : `
${tr("Spoolman nicht erreichbar")}${sm.error ? `: ${esc(sm.error)}` : ""}
`}
${sm.spoollink ? "" : ``} ${list.map(item).join("") || `
${tr("Keine aktiven Spulen in Spoolman.")}
`}
`; dlg.querySelector("[data-close]").addEventListener("click", () => dlg.close()); const nb = dlg.querySelector("[data-newspool]"); if (nb) nb.addEventListener("click", () => this._newSpoolForm(dlg, idx)); dlg.querySelectorAll("[data-pick]").forEach((b) => b.addEventListener("click", async () => { const v = b.dataset.pick; const data = { slot: idx + 1, ...this._entryData() }; if (v !== "auto") data.spool_id = Number(v); try { await this._hass.callService(DOMAIN, "set_spool", data, void 0, false); dlg.close(); } catch (err) { const e = dlg.querySelector(".dlg-error"); e.hidden = false; e.textContent = err && err.message || String(err); } })); if (!dlg.open) { if (typeof dlg.showModal === "function") dlg.showModal(); else dlg.setAttribute("open", ""); } } }; // frontend/src/card/files.js var FilesMixin = (Base) => class extends Base { _sectionFiles() { const d = this._d; const head = (extra = "") => `
${tr("Dateien")}${extra}
`; if (!d.files) { return `
${head()}
${tr("Die Integration Snapmaker U1 Card ist nicht eingerichtet.")} ${tr("Einstellungen → Geräte & Dienste → Integration hinzufügen → „Snapmaker U1 Card“.")}
`; } const off = !d.online; const upload = ` `; const refresh = ``; const up = this._uploadLine(); if (!d.files.length) { return `
${head(refresh + upload)}${up}
${tr("Keine Druckdateien auf dem Drucker.")}
`; } const cards = d.files.map((f) => { const folder = f.path.includes("/") ? f.path.slice(0, f.path.lastIndexOf("/")) : ""; const meta = []; if (f.time) meta.push(fmtMin(f.time / 60)); if (f.weight) meta.push(`${Math.round(f.weight)} g`); else if (f.filament) meta.push(`${f.filament} m`); const thumb = f.thumb ? `` : ``; const dots = (f.filaments || []).filter((x) => x.used).slice(0, 8).map((x) => ``).join(""); return ` `; }).join(""); return `
${head(`${tr("{n} neueste", { n: d.files.length })}${refresh.replace('style="margin-left:auto"', "")}${upload}`)} ${up} ${d.active ? `
${tr("Der Drucker druckt. Antippen, um einen Auftrag in die Warteschlange zu stellen.")}
` : ""} ${this._fileTools()}
${cards}
`; } /** Search, sort, folders. Filters the tiles in the DOM without a rebuild (focus stays). */ _fileTools() { const all = this._allFiles(); const folders = [...new Set(all.map((f) => f.path.includes("/") ? f.path.split("/")[0] : "").filter(Boolean))].sort(); const fs = this._fstate || (this._fstate = { q: "", sort: "new", folder: "" }); const chips = folders.length ? `
${folders.map((f) => ``).join("")}
` : ""; return `
${chips}`; } _allFiles() { const st = this._ents && this._ents.files && this._st(this._ents.files); const a = st && st.attributes && st.attributes.all; return Array.isArray(a) ? a : []; } _filterFiles() { const r = this.shadowRoot && this.shadowRoot.getElementById("u1card"); const grid = r && r.querySelector(".files"); if (!grid) return; const fs = this._fstate || { q: "", sort: "new", folder: "" }; const q = fs.q.trim().toLowerCase(); const tiles = [...grid.querySelectorAll("button.file")]; const inFolder = (folder) => !fs.folder || folder === fs.folder || folder.startsWith(fs.folder + "/"); tiles.forEach((b) => { b.hidden = !(inFolder(b.dataset.folder || "") && (!q || b.dataset.fname.includes(q))); }); const key = { new: (b) => -Number(b.dataset.fmod), name: (b) => b.dataset.fname, time: (b) => Number(b.dataset.ftime) }[fs.sort]; tiles.sort((a, b) => key(a) < key(b) ? -1 : key(a) > key(b) ? 1 : 0).forEach((b) => grid.appendChild(b)); const more = r.querySelector("[data-fmore]"); if (!more) return; const shown = new Set(tiles.map((b) => b.dataset.print)); const hits = q || fs.folder ? this._allFiles().filter((f) => !shown.has(f.path) && inFolder(f.path.includes("/") ? f.path.slice(0, f.path.lastIndexOf("/")) : "") && (!q || f.path.toLowerCase().includes(q))).slice(0, 20) : []; more.innerHTML = hits.length ? `
${tr("Ältere Dateien")}
` + hits.map((f) => ``).join("") : ""; more.querySelectorAll("[data-fopen]").forEach((b) => b.addEventListener("click", () => this._openOlder(b.dataset.fopen))); } async _openOlder(path) { try { const res = await this._hass.callService(DOMAIN, "file_details", { path, ...this._entryData() }, void 0, false, true); const file = res && res.response && res.response.file; if (!file) return; (this._extraFiles || (this._extraFiles = {}))[path] = file; this._openPrint(path); } catch (err) { alert(err && (err.message || err.error) || String(err)); } } _sectionQueue() { const jobs = this._d.queue; if (!jobs || !jobs.length) return ""; const d = this._d; const slots = this._slots() || []; const canStart = !d.active && (d.online || !!(d.power && d.power.autoOn)); const items = jobs.map((j, i) => { const dots = Object.values(j.mapping || {}).map((sl) => { const slot = slots[Number(sl)]; return ``; }).join(""); const opts = [ j.timelapse ? `` : "", j.bed_leveling ? `` : "", Array.isArray(j.pause_layers) && j.pause_layers.length ? `${tr("Pause vor {l}", { l: j.pause_layers.join(", ") })}` : "" ].join(""); return `
${i + 1} ${j.thumb ? `` : ``}
${esc(j.name || j.file)}
${dots ? `${dots}` : ""}${opts}
${i === 0 ? `` : ` `}
`; }).join(""); return `
${tr("Warteschlange")} ${tr("{n} Aufträge", { n: jobs.length })}
${d.active ? `
${tr("Startet nicht von selbst: nach dem Druck das Bett räumen und hier starten.")}
` : ""}
${items}
`; } async _queueAction(action, jobId, pos) { if (action === "remove") return this._call("queue_remove", { job_id: jobId }); if (action === "move") return this._call("queue_move", { job_id: jobId, position: pos }); if (action === "start") { const job = (this._d.queue || []).find((j) => j.id === jobId); const name = job && (job.name || job.file) || ""; if (!confirm(tr("{name} starten? Druckbett ist leer und der Drucker frei?", { name }))) return; if (await this._call("queue_start", { job_id: jobId })) this._toast(tr("Druck gestartet: {name}", { name })); } } // ── Upload ────────────────────────────────────────────────────────────── _uploadLine() { const u = this._up; if (!u) return ""; if (u.error) { return `
${esc(u.name)}: ${esc(u.error)}
`; } return `
${esc(u.name)}
${u.done ? tr("fertig") : `${u.pct} %`}
`; } _upload(file) { const entry = this._entryData().config_entry_id; if (!entry || !this._hass) return; if (!/\.(gcode|3mf)$/i.test(file.name)) { alert(tr("Nur .gcode- und .3mf-Dateien.")); return; } this._up = { name: file.name, pct: 0, done: false, error: null }; this._renderKey = null; this._render(); const rerender = () => { this._renderKey = null; this._render(); }; const send = (token) => { const xhr = new XMLHttpRequest(); xhr.open("POST", `/api/${DOMAIN}/upload/${entry}`); xhr.setRequestHeader("Authorization", `Bearer ${token}`); xhr.upload.onprogress = (e) => { if (!e.lengthComputable || !this._up) return; this._up.pct = Math.min(99, Math.round(e.loaded / e.total * 100)); const root = this.shadowRoot.getElementById("u1card"); const bar = root && root.querySelector('[data-su1="uplbar"]'); const pct = root && root.querySelector('[data-su1="uplpct"]'); if (bar) bar.style.width = `${this._up.pct}%`; if (pct) pct.textContent = `${this._up.pct} %`; }; xhr.onload = () => { let body = {}; try { body = JSON.parse(xhr.responseText || "{}"); } catch (e) { } if (xhr.status >= 200 && xhr.status < 300) { this._up = { name: file.name, pct: 100, done: true, error: null }; this._afterUpload = { path: body.file, until: Date.now() + 3e4 }; this._toast(tr("Hochgeladen: {name}", { name: file.name })); setTimeout(() => { if (this._up && this._up.done) { this._up = null; rerender(); } }, 4e3); } else { this._up = { name: file.name, pct: 0, done: false, error: body.message || `HTTP ${xhr.status}` }; } rerender(); this._checkAfterUpload(); }; xhr.onerror = () => { this._up = { name: file.name, pct: 0, done: false, error: tr("Verbindung abgebrochen") }; rerender(); }; const form = new FormData(); form.append("file", file, file.name); xhr.send(form); }; const auth = this._hass.auth; const go = () => send(auth && auth.data ? auth.data.access_token : ""); if (auth && auth.expired && typeof auth.refreshAccessToken === "function") auth.refreshAccessToken().then(go, go); else go(); } /** After the upload, open the print dialog as soon as the file is listed. */ _checkAfterUpload() { const a = this._afterUpload; if (!a || this._dlg) return; if (Date.now() > a.until) { this._afterUpload = null; return; } if ((this._d.files || []).some((f) => f.path === a.path)) { this._afterUpload = null; this._openPrint(a.path); } } }; // frontend/src/card/control-tab.js var TEMP_HIDDEN = "u1-fusion-showcase-ironoxx.temp-hidden"; var KNOWN_SERIES = ["extruder", "extruder1", "extruder2", "extruder3", "heater_bed", "cavity", "stepper_x", "stepper_y", "cpu"]; var EXTRA_COLORS = ["#fdd835", "#d81b60", "#5e35b1", "#00897b", "#c0ca33"]; var ControlTabMixin = (Base) => class extends Base { _sectionClimate() { const d = this._d; return `
${tr("Bett & Innenraum")} ${this._lockBtn()}
${this._stat(tr("Druckbett"), `${num(d.bed, 0, "°C")}`)} ${this._stat(tr("Innenraum"), `${num(d.cavity, 0, "°C")}`)} ${this._stat(tr("Bett-Heizung"), `${num(d.bedPower, 0, "%")}`)} ${this._stat(tr("Netzteil-Lüfter"), `${num(d.powerFan, 0, "%")}`)}
${this._slider({ entity: `number.${this._p("bed_target")}`, label: tr("Bett-Solltemperatur"), value: d.bedTarget, unit: "°C", presets: this._cfg.bed_presets })} ${this._slider({ entity: `number.${this._p("fan_speed")}`, label: tr("Bauteillüfter"), value: d.partFan, unit: "%", presets: [0, 50, 100] })} ${this._slider({ entity: `number.${this._p("cavity_fan_speed")}`, label: tr("Innenraumlüfter"), value: d.cavityFanSet, unit: "%", presets: [0, 50, 100] })}
${this._coverPanel()} ${this._chamberPanel()}
${tr("Temperaturverlauf")} ${tr("letzte 20 min")}
${this._tempSvg()}
`; } /** History from Moonraker's temperature_store (via the integration), every 10 s, only when visible. */ async _tickTemps() { const r = this.shadowRoot && this.shadowRoot.getElementById("u1card"); const box = r && r.querySelector("[data-tchart]"); if (!box || document.hidden || !this._onScreen) return; const pane = box.closest("[data-pane]"); if (pane && pane.hidden) return; const entry = this._entryData().config_entry_id; if (!entry || this._tBusy) return; this._tBusy = true; try { this._temps = await this._fetchJson(`/api/${DOMAIN}/temps/${entry}`); box.innerHTML = this._tempSvg(); } catch (e) { } finally { this._tBusy = false; } } /** Lines hidden by a tap on the legend (per browser). */ _tempHidden() { if (!this._tHidden) { try { this._tHidden = new Set(JSON.parse(window.localStorage.getItem(TEMP_HIDDEN) || "[]")); } catch (e) { this._tHidden = /* @__PURE__ */ new Set(); } } return this._tHidden; } _toggleTempSeries(key) { const h = this._tempHidden(); if (h.has(key)) h.delete(key); else h.add(key); try { window.localStorage.setItem(TEMP_HIDDEN, JSON.stringify([...h])); } catch (e) { } const box = this.shadowRoot && this.shadowRoot.querySelector("[data-tchart]"); if (box) box.innerHTML = this._tempSvg(); } _tempSvg() { const t = this._temps; if (!t) return `
${tr("Lädt …")}
`; if (t.offline) return `
${tr("Drucker nicht erreichbar.")}
`; const series = t.series || null; if (!series || !Object.keys(series).length) return `
${tr("Noch keine Daten.")}
`; const heads = this._d ? this._d.heads : []; const hidden = this._tempHidden(); const isNum = (v) => typeof v === "number" && Number.isFinite(v); const defs = [ ...["extruder", "extruder1", "extruder2", "extruder3"].map((k, i) => ({ key: k, color: ["#e53935", "#1e88e5", "#43a047", "#fb8c00"][i], label: heads[i] && heads[i].name || tr("Kopf {n}", { n: i + 1 }), heater: true })), { key: "heater_bed", color: "#8e24aa", label: tr("Bett"), heater: true, always: true }, { key: "cavity", color: "#00acc1", label: tr("Innenraum") }, { key: "stepper_x", color: "#8d6e63", label: tr("Stepper X") }, { key: "stepper_y", color: "#9e9e9e", label: tr("Stepper Y") }, { key: "cpu", color: "#78909c", label: tr("CPU") }, // further sensors of the printer config (mods): own colours, name from Klipper ...Object.keys(series).filter((k) => !KNOWN_SERIES.includes(k)).map((k, i) => ({ key: k, color: EXTRA_COLORS[i % EXTRA_COLORS.length], label: k.replace(/_/g, " ") })) ].filter((s) => { const d = series[s.key]; if (!d || !(d.temperatures || []).some(isNum)) return false; return !s.heater || s.always || d.temperatures.some((v) => v > 45) || (d.targets || []).some((v) => v > 0); }); if (!defs.length) return `
${tr("Noch keine Daten.")}
`; const shown = defs.filter((s) => !hidden.has(s.key)); const W = 300, H = 120, PAD = 22; let max = 60, n = 0; defs.forEach((s) => { n = Math.max(n, series[s.key].temperatures.length); }); shown.forEach((s) => { [...series[s.key].temperatures, ...series[s.key].targets || []].forEach((v) => { if (isNum(v) && v > max) max = v; }); }); max = Math.ceil((max + 10) / 50) * 50; if (n < 2) return `
${tr("Noch keine Daten.")}
`; const x = (i) => PAD + i / (n - 1) * (W - PAD - 4); const y = (v) => H - 14 - v / max * (H - 22); const line = (vals, color, dash, width) => { const off = n - vals.length; const runs = []; let cur = []; vals.forEach((v, i) => { if (isNum(v)) cur.push(`${x(i + off).toFixed(1)},${y(v).toFixed(1)}`); else if (cur.length) { runs.push(cur); cur = []; } }); if (cur.length) runs.push(cur); return runs.filter((r) => r.length > 1).map((r) => ``).join(""); }; const grid = [0, max / 2, max].map((v) => `${Math.round(v)}`).join(""); const mins = Math.round(n * (t.step || 5) / 60); const xlab = `−${mins} min${tr("jetzt")}`; const paths = shown.map((s) => { const d = series[s.key]; return (s.heater ? line(d.targets || [], s.color, "3 3", 0.8) : "") + line(d.temperatures, s.color, "", s.heater ? 1.6 : 1.2); }).join(""); const legend = defs.map((s) => { const vals = series[s.key].temperatures.filter(isNum); const off = hidden.has(s.key); return ``; }).join(""); return `${grid}${paths}${xlab}
${legend}
`; } async _fetchJson(url) { const h = this._hass; const res = typeof h.fetchWithAuth === "function" ? await h.fetchWithAuth(url) : await fetch(url, { headers: { Authorization: `Bearer ${h.auth && h.auth.data ? h.auth.data.access_token : ""}` } }); if (!res.ok) throw new Error(`HTTP ${res.status}`); return res.json(); } _sectionMotion() { const d = this._d; const homing = d.active ? `
${tr("Referenzfahrt ist während des Drucks gesperrt.")}
` : `
`; return `
${tr("Bewegung")} ${this._lockBtn()}
${this._stat(tr("Position X"), `${num(d.posX, 1)}`)} ${this._stat(tr("Position Y"), `${num(d.posY, 1)}`)} ${this._stat(tr("Position Z"), `${num(d.posZ, 2)}`)}
${this._slider({ entity: `number.${this._p("speed_factor")}`, label: tr("Geschwindigkeit"), value: d.speedFactor, unit: "%", presets: [50, 100, 150] })} ${this._ents.flow && d.flow !== null ? this._slider({ entity: this._ents.flow, label: tr("Flussrate"), value: d.flow, unit: "%", presets: [95, 100, 105] }) : ""} ${homing}
`; } }; // frontend/src/card/system.js var SystemMixin = (Base) => class extends Base { _sectionSystem() { const d = this._d; const mcuTip = tr("Last: längste Aufgabe des Controllers (Mittel + 3 σ) im Verhältnis zu 2,5 ms. Ab etwa 100 % meldet Klipper 'Timer too close'. Wach: Anteil der Zeit, in der der Controller rechnet statt zu schlafen. Einstellige Werte sind normal."); const heads = d.heads.map( (h) => this._row( `MCU ${h.name}`, `${num(h.mcuLoad, 2, "%")} / ${num(h.mcuAwake, 2, "%")}`, null, mcuTip ) ).join(""); return `
${tr("System & Diagnose")}
${this._ents.firmware ? this._row(tr("Firmware"), `${this._fwText()}`, this._ents.firmware) : ""} ${this._ents.live ? this._row(tr("Live-Verbindung"), `${this._liveText()}`, this._ents.live) : ""} ${this._row("Klipper", `${esc(d.klipper || "—")}`, `sensor.${this._p("printer_state")}`)} ${this._row(tr("Meldung"), `${esc(d.message || "—")}`)} ${this._row(tr("Idle-Status"), `${esc(d.idleTimeout)}`)} ${this._row(tr("MCU Host (Last / Wach)"), `${num(d.mcuLoad, 2, "%")} / ${num(d.mcuAwake, 2, "%")}`, null, mcuTip)} ${heads} ${d.cpuTemp !== null ? this._row(tr("CPU-Temperatur"), `${num(d.cpuTemp, 1, "°C")}`, null, tr("Temperatur des Rechners im Drucker (Moonraker).")) : ""} ${this._row(tr("Arbeitsspeicher"), `${num(d.memory, 1, "%")}`, null, tr("Belegter Arbeitsspeicher des Druckerrechners (ohne Puffer und Cache)."))}
${tr("Systemlast (Ø 1 min)")}${this._loadText()}
${d.stepX !== null ? this._row(tr("Stepper X"), `${num(d.stepX, 1, "°C")}`) : ""} ${d.stepY !== null ? this._row(tr("Stepper Y"), `${num(d.stepY, 1, "°C")}`) : ""} ${this._printerSettingsHtml()} ${this._liveNotifyHtml()}
${this._settingsButtonHtml()}
${this._selfTestHtml()}
${tr("MCU-Last und -Wachzeit sind wie in Mainsail berechnet; einstellige Werte sind normal, kritisch wird die Last erst gegen 100 %.")}
`; } /** Firmware preferences (stored on the printer); only those the firmware reports. */ _printerSettingsHtml() { const p = this._prefs(); const items = [ ["auto_replenish", tr("Filament automatisch nachfüllen"), tr("Läuft eine Spule leer, druckt ein Kopf mit gleichem Material weiter.")], ["replenish_ignore_color", tr("Nachfüllen ohne Farbprüfung"), tr("Auch ein Kopf mit anderer Farbe darf übernehmen.")], ["entangle_detect", tr("Verhedderungs-Erkennung"), tr("Pausiert, wenn sich das Filament verhakt.")], ["end_led_off", tr("Licht aus nach dem Druck"), ""] ].filter(([k]) => p[k] !== null && p[k] !== void 0); if (!items.length) return ""; const off = !this._d.online; const rows = items.map(([k, label, hint]) => `
${label}
`).join(""); const sen = p.entangle_detect && p.entangle_sensitivity ? `
${tr("Empfindlichkeit")} ${[["low", tr("Niedrig")], ["medium", tr("Mittel")], ["high", tr("Hoch")]].map(([v, l]) => ``).join("")}
` : ""; return `
${tr("Druckereinstellungen")}
${rows}${sen}`; } /** Switch for the ongoing progress notification (integration, Android phones). */ _liveNotifyHtml() { const st = this._st(this._ents && this._ents.liveNotify); if (!st) return ""; const on = st.state === "on"; const a = st.attributes || {}; const targets = (a.targets || []).length; const hint = targets ? tr("Fortschrittsbalken und Countdown in der Benachrichtigungsleiste. Heute {n} von {b} Updates.", { n: a.sent_today || 0, b: a.budget || 0 }) : tr("Kein Android-Handy unter den Benachrichtigungszielen der Integration."); return `
${tr("Benachrichtigungen")}
${tr("Fortschritt aufs Handy")}${esc(hint)}
`; } _fwText() { const st = this._st(this._ents && this._ents.firmware); if (!st || st.state === "unavailable" || st.state === "unknown") return "—"; const a = st.attributes || {}; if (st.state === "on" && a.latest_version) { return `${esc(a.installed_version || "?")} → ${esc(a.latest_version)} ${tr("verfügbar")}`; } return `${esc(a.installed_version || "?")} · ${tr("aktuell")}`; } _selfTestHtml() { const t = this._selftest; if (!t) return ""; if (t.busy) return `
${tr("Prüfe …")}
`; if (t.error) return `
${esc(t.error)}
`; const icon = (ok) => ok === true ? `✓` : ok === false ? `✗` : `!`; return (t.checks || []).map((c) => `
${icon(c.ok)}${esc(c.detail)}
`).join(""); } async _runSelfTest() { const box = () => this.shadowRoot.querySelector("[data-selftest]"); this._selftest = { busy: true }; if (box()) box().innerHTML = this._selfTestHtml(); try { const res = await this._hass.callService(DOMAIN, "self_test", { ...this._entryData(), language: LANG }, void 0, false, true); this._selftest = res && res.response || { error: tr("Keine Antwort") }; } catch (err) { this._selftest = { error: err && (err.message || err.error) || String(err) }; } if (box()) box().innerHTML = this._selfTestHtml(); } /** Live subscription to Moonraker: connected since ... or disconnected (polling every x s). */ _liveText() { const st = this._st(this._ents && this._ents.live); if (!st || st.state === "unavailable" || st.state === "unknown") return "—"; const a = st.attributes || {}; if (st.state === "on") { return `● ${tr("verbunden")}${a.connected_since ? ` · ${tr("seit")} ${esc(fmtDate(a.connected_since))}` : ""}`; } const sec = a.poll_interval_s ? Math.round(a.poll_interval_s) : 10; return `● ${tr("getrennt · Abfrage alle {n} s", { n: sec })}`; } _sectionStats() { const d = this._d; return `
${tr("Statistik")}
${this._row(tr("Drucke gesamt"), `${num(d.totalsJobs, 0)}`)} ${this._row(tr("Druckzeit gesamt"), `${esc(d.totalsTime)}`)} ${this._row(tr("Längster Druck"), `${esc(d.longest)}`)} ${this._row(tr("Filament gesamt"), `${num(d.totalsFilament, 1, "m")}`)} ${d.usage ? this._usageRows() : ""} ${d.tc ? this._toolChangeRows() : ""}
`; } _usageRows() { const u = this._d.usage; const e = this._ents; return [ u.hasEnergy ? this._row(u.inProgress ? tr("Strom aktueller Druck") : tr("Strom letzter Druck"), `${num(u.energy, 2, "kWh")}`, e.energyPrint) : "", u.hasCost ? this._row(u.inProgress ? tr("Kosten aktueller Druck") : tr("Kosten letzter Druck"), `${fmtEuro(u.cost)}`, e.costPrint) : "" ].join(""); } _sectionMaintenance() { const items = this._d.maint; if (!items || !items.length) return ""; const rows = items.map((m) => { const pct = Math.min(100, m.progress || 0); const tone = m.due ? "error" : pct >= 80 ? "warn" : ""; const hours = m.interval_h ? m.used_h === null || m.used_h === void 0 ? "—" : `${num(m.used_h, 0)} / ${m.interval_h} h` : ""; const months = m.interval_m ? tr(m.interval_m === 1 ? "monatlich" : "alle {n} Monate", { n: m.interval_m }) : ""; const used = m.firmware ? `${fmtInt(m.used)} / ${fmtInt(m.interval)} ${tr("Wechsel")}` : [hours, months].filter(Boolean).join(" · ") || "—"; const leftH = m.interval_h && m.remaining_h !== null && m.remaining_h !== void 0 ? m.remaining_h : null; const leftD = m.interval_m && m.remaining_d !== null && m.remaining_d !== void 0 ? m.remaining_d : null; const byDays = m.by ? m.by === "months" : leftD !== null && leftH === null; const left = m.firmware ? "" : m.due ? tr("fällig") : byDays && leftD !== null ? tr("noch {d} Tage", { d: Math.max(0, Math.round(leftD)) }) : leftH !== null ? tr("noch {h} h", { h: Math.round(leftH) }) : leftD !== null ? tr("noch {d} Tage", { d: Math.max(0, Math.round(leftD)) }) : ""; return `
${esc(tr(MAINT_LABELS[m.key] || m.key))} ${esc(used)}${left ? ` · ${esc(left)}` : ""} ${m.firmware ? "" : ``}
`; }).join(""); const due = items.filter((m) => m.due).length; return `
${tr("Wartung")} ${due ? `${tr("{n} fällig", { n: due })}` : ""}
${rows}
${tr("Gezählt in Druckstunden und Monaten (Monatswerte nach Snapmakers U1-Wartungsanleitung). Intervalle in den Optionen der Integration.")}
${this._backupLine()}
`; } /** Config backup: last snapshot and a "back up now" button. */ _backupLine() { const b = this._d.backup; if (!b || !b.enabled) return ""; const when = b.saved_at ? fmtDate(b.saved_at) : tr("noch keine"); const info = [when, b.files ? tr(b.files === 1 ? "{n} Datei" : "{n} Dateien", { n: b.files }) : "", b.status === "error" ? tr("Fehler") : ""].filter(Boolean).join(" · "); return `
${tr("Drucker-Konfiguration gesichert")} ${esc(info)}
`; } _togglePower() { const p = this._d && this._d.power; if (!p || !p.available || p.shuttingDown || p.poweringOn) return; if (p.on) { if (this._d.active) { alert(tr("Der Drucker druckt gerade. Druck erst beenden oder abbrechen.")); return; } if (!confirm(tr("Drucker herunterfahren und ausschalten?"))) return; this._hass.callService(DOMAIN, "power_off", this._entryData(), void 0, false).catch((err) => { const msg = err && err.message || String(err); if (!this._d.online && /druckt gerade/.test(msg) && confirm(`${msg} ${tr("Der Drucker antwortet nicht. Trotzdem ausschalten?")}`)) { this._hass.callService(DOMAIN, "power_off", { ...this._entryData(), force: true }); } else { alert(msg); } }); } else { this._hass.callService(DOMAIN, "power_on", this._entryData()); } } _toolChangeRows() { const tc = this._d.tc; const e = this._ents; return [ this._row(tr("Werkzeugwechsel gesamt"), `${fmtInt(tc.total)}`, e.toolChanges), this._row( tc.inProgress ? tr("Wechsel aktueller Druck") : tr("Wechsel letzter Druck"), `${this._tcPrintText(tc)}`, e.toolChangesPrint ), tc.heads.length ? this._row(tr("Wechsel je Kopf"), `${this._tcHeadsText(tc)}`, e.toolChanges) : "", tc.threshold && tc.since !== null ? this._row(tr("Seit Wartung (max.)"), `${this._tcMaintText(tc)}`, e.toolChanges) : "" ].join(""); } _tcPrintText(tc) { if (tc.print === null) return "—"; const res = { complete: tr("fertig"), cancelled: tr("abgebrochen"), error: tr("Fehler") }[tc.result]; return `${fmtInt(tc.print)}${!tc.inProgress && res ? ` (${res})` : ""}`; } _tcHeadsText(tc) { const own = (this._cfg.toolheads || []).map((t) => t && t.name); return tc.heads.map((h) => `${esc(own[h.index] || String(h.index + 1))}: ${fmtInt(h.switches)}`).join(" · "); } _tcMaintText(tc) { const warn = tc.since >= tc.threshold * 0.9; const txt = `${fmtInt(tc.since)} / ${fmtInt(tc.threshold)}`; return warn ? `${txt}` : txt; } }; // frontend/src/card/history.js var HistoryMixin = (Base) => class extends Base { _sectionHistory() { const list = this._d.history; if (!list) return ""; const files = new Set((this._d.files || []).map((f) => f.path)); const rows = list.length ? list.map((h, idx) => { const [rawLabel, tone] = RESULT[h.result] || [h.result || "—", ""]; const label = tr(rawLabel); const facts = [ h.duration ? fmtMin(h.duration / 60) : null, h.filament_g !== void 0 && h.filament_g !== null ? `${Math.round(h.filament_g)} g` : null, h.energy !== void 0 && h.energy !== null ? num(h.energy, 2, "kWh") : null, h.switches > 1 ? tr("{n} Wechsel", { n: fmtInt(h.switches) }) : null, Array.isArray(h.pause_layers) && h.pause_layers.length ? tr("Pause vor {l}", { l: h.pause_layers.join(", ") }) : null, h.error || null, // Spoolman per spool: remaining before -> after, else the booked amount (⏳ = not booked yet) Array.isArray(h.spools) && h.spools.length ? h.spools.map((sp) => { const g = (v) => `${Math.round(v)} g`; const pending = sp.booked === false ? " ⏳" : ""; if (typeof sp.before === "number" && typeof sp.after === "number") return `#${sp.spool_id} ${g(sp.before)} → ${g(sp.after)}${pending}`; return `#${sp.spool_id} −${String(sp.grams).replace(".", ",")} g${pending}`; }).join(", ") : null ].filter(Boolean); const thumb = h.thumb ? `` : ``; return `
${thumb} ${h.photo ? `${tr(` : ""}
${esc(h.name || h.file || tr("Druck"))}
${esc(fmtDate(h.ended))} · ${facts.map(esc).join(" · ") || "—"}
${files.has(h.source || h.file) ? `` : ""} ${esc(label)} ${h.total_cost !== void 0 && h.total_cost !== null ? `${fmtEuro(h.total_cost)}` : ""}
`; }).join("") : `
${tr("Noch keine Drucke erfasst. Die Historie füllt sich ab dem nächsten Druck.")}
`; const sum = list.reduce((acc, h) => { if (h.total_cost !== void 0 && h.total_cost !== null) acc.cost += h.total_cost; if (h.energy) acc.energy += h.energy; return acc; }, { cost: 0, energy: 0 }); const summary = list.length ? `${tr("{n} Drucke", { n: list.length })}${sum.energy ? ` · ${num(sum.energy, 1, "kWh")}` : ""}${sum.cost ? ` · ${fmtEuro(sum.cost)}` : ""}` : ""; return `
${tr("Druckhistorie")}${summary}
${rows}
`; } _sectionCharts() { const st = this._d.stats; if (!st) return ""; const metric = this._metric || "prints"; const monthName = (m) => { const [y, mo] = m.split("-").map(Number); return new Date(y, mo - 1, 1).toLocaleDateString(LOCALE, { month: "short" }); }; const val = (b) => metric === "prints" ? b.prints + b.failed : Number(b[metric]) || 0; const max = Math.max(1e-9, ...st.months.map(val)); const fmt = (b) => { if (metric === "prints") return `${b.prints} ${tr("fertig")}, ${b.failed} ${tr("abgebrochen")}`; if (metric === "hours") return num(b.hours, 1, "h"); if (metric === "filament_g") return b.filament_g >= 1e3 ? num(b.filament_g / 1e3, 2, "kg") : num(b.filament_g, 0, "g"); return b.cost === null ? "—" : fmtEuro(b.cost); }; const bars = st.months.map((b) => { const total = val(b); const h = total / max * 100; const okPart = metric === "prints" && total ? b.prints / total * 100 : 100; return `
${metric === "prints" && b.failed ? `` : ""}
${esc(monthName(b.month))}
`; }).join(""); const t = st.totals; const cost = st.months.some((b) => b.cost !== null); const chips = METRICS.filter(([k]) => k !== "cost" || cost).map(([k, label]) => ``).join(""); const rate = t.success_rate === null || t.success_rate === void 0 ? "—" : `${String(t.success_rate).replace(".", LANG === "de" ? "," : ".")} %`; const tiles = [ [tr("Drucke"), fmtInt(t.prints)], [tr("Erfolgsquote"), rate], [tr("Druckstunden"), num(t.hours_total ?? t.hours, 0, "h")], [tr("Filament"), num(t.filament_kg, 2, "kg")], t.energy !== null && t.energy !== void 0 ? [tr("Strom"), num(t.energy, 1, "kWh"), tr("Gemessen bei Drucken seit Installation der Integration.")] : null, t.cost !== null && t.cost !== void 0 ? [ tr("Kosten"), (t.cost_estimated ? "≈ " : "") + fmtEuro(t.cost), t.cost_estimated ? tr("Ältere Drucke mit Filamentpreis geschätzt, ohne Strom.") : "" ] : null ].filter(Boolean).map(([k, v, hint]) => this._stat(k, v, "sm", hint)).join(""); const top = (st.top || []).slice(0, 3).map((f) => `${esc(String(f.file).split("/").pop().replace(/\.(gcode|3mf)$/i, ""))} ×${f.count}`).join(""); return `
${tr("Letzte 12 Monate")} ${chips}
${metric === "prints" ? `
${tr("fertig")}${tr("abgebrochen")}
` : ""}
${tiles}
${top ? `
${tr("Am häufigsten")}: ${top}
` : ""} ${this._materialsHtml(st)}
`; } /** Consumption per material and colour from Moonraker's print history. */ _materialsHtml(st) { const mats = st && st.materials || []; if (!mats.length) return ""; const rows = mats.map((m) => `${esc(m.type)}${m.prints} ${m.grams >= 1e3 ? num(m.grams / 1e3, 2, "kg") : num(m.grams, 0, "g")} ${m.cost !== null && m.cost !== void 0 ? fmtEuro(m.cost) : "—"} ${m.success_rate !== null && m.success_rate !== void 0 ? num(m.success_rate, 0, "%") : "—"}`).join(""); const colors = (st && st.colors || []).map((c) => `${esc(c.type)} ${num(c.grams, 0, "g")}`).join(""); return `
${tr("Nach Material")}
${rows}
${tr("Material")}${tr("Drucke")}${tr("Verbrauch")}${tr("Kosten")}${tr("Erfolg")}
${colors ? `
${tr("Meistgenutzte Farben")}
${colors}
` : ""}
`; } }; // frontend/src/card/timelapse.js var TimelapseMixin = (Base) => class extends Base { _sectionTimelapse() { const tl = this._d.timelapses; if (!tl) return ""; const tiles = tl.videos.length ? tl.videos.slice(0, this._cfg.timelapse_limit || 8).map((v, i) => ` `).join("") : `
${tr("Keine Zeitraffer auf dem Drucker. Aufnahme im Druckdialog unter „Zeitraffer“ einschalten.")}
`; return `
${tr("Zeitraffer")} ${tl.videos.length ? `${tl.videos.length}` : ""}
${tiles}
${this._archiveBlock(tl.archive)}
`; } _archiveBlock(a) { if (!a) return ""; const status = [ a.busy ? tr("Sicherung läuft …") : a.last_backup ? tr("Zuletzt gesichert: {d}", { d: fmtDate(new Date(a.last_backup * 1e3).toISOString()) }) : tr("Noch nichts gesichert."), a.keep > 0 ? a.cleanup === "not_supported" ? tr("Löschen auf dem Drucker wird von der Firmware nicht unterstützt.") : tr("Auf dem Drucker bleiben die {n} neuesten.", { n: a.keep }) : null ].filter(Boolean).join(" · "); const tiles = (a.videos || []).slice(0, this._cfg.timelapse_limit || 8).map((v, i) => ` `).join(""); return `
${tr("Gesichert in Medien")} (${a.count})
${esc(status)}
${(a.errors || []).length ? `
${a.errors.map(esc).join("
")}
` : ""} ${tiles ? `
${tiles}
` : ""}`; } /** Play a backed-up video via HA's media source (signed URL). */ async _openArchive(index) { const a = this._d.timelapses && this._d.timelapses.archive; const v = a && a.videos[index]; if (!v) return; this._showVideo( archiveName(v.file), fmtDate(new Date(v.modified * 1e3).toISOString()), v.file, async () => { const res = await this._hass.callWS({ type: "media_source/resolve_media", media_content_id: v.media_id, expires: 3600 }); return { url: res.url, poster: v.poster_url || "" }; } ); } // Signed URL for the video proxy: