Compare commits
6 Commits
nightly-0.
...
master
| Author | SHA1 | Date | |
|---|---|---|---|
| 5e87f1f94f | |||
| 6c9363c718 | |||
| 86adde0a45 | |||
|
|
c4f321c9b0 | ||
| 1f1d60d571 | |||
|
|
9f76d28622 |
@@ -1,3 +1,2 @@
|
||||
## Changes in this build
|
||||
|
||||
- Feat: the GCode browser now has a second tab showing files stored directly on the printer's own internal storage (e.g. from prints started via Anycubic Slicer Next, bypassing the bridge) — list, multi-select, and delete them right from the Bridge UI instead of needing the printer's own display.
|
||||
|
||||
17
README.de.md
17
README.de.md
@@ -23,7 +23,7 @@ Feedback willkommen.</sub>
|
||||
|
||||
[](https://gitea.it-drui.de/viewit/KX-Bridge-Release/releases)
|
||||
|
||||
[](https://www.youtube.com/watch?v=1Ql4wfH27fM)
|
||||
[](https://www.youtube.com/watch?v=E3sDigSeSdM)
|
||||
|
||||
<sub>Gefällt dir KX-Bridge? Ein Kaffee auf <a href="https://ko-fi.com/viewitde">Ko-fi</a> hält das Projekt am Leben. ☕</sub>
|
||||
|
||||
@@ -41,12 +41,16 @@ Feedback willkommen.</sub>
|
||||
| 🖨️ | **Druckersteuerung** — Start, Pause, Resume, Abbruch, Temperaturen, Druckgeschwindigkeit |
|
||||
| 📊 | **Live-Status** — Temperatur, Fortschritt, Layer, Restzeit, Kamera-Stream |
|
||||
| 🎨 | **AMS / Multicolor** — Slots mit **Profil-Picker pro Slot** (eigene Marke aus OrcaSlicer-Profilen pro Slot zuweisen); Bridge schreibt Material und Farbe ans Drucker-Display zurück |
|
||||
| 🏷️ | **Custom-RFID-Tag-Matching** — mit Drittanbieter-Tools (z.B. der „ACE RFID"-App) beschriebene Spulen werden automatisch nach Marke + Material gegen deine importierten OrcaSlicer-Profile gematcht, statt auf ein generisches Profil zurückzufallen |
|
||||
| 📦 | **Eigene OrcaSlicer-Profile importieren** — ZIP aus `~/.config/OrcaSlicer/user/<id>/filament/` in die Bridge ziehen; tauchen im Slot-Dropdown unter ★ Eigene Profile auf |
|
||||
| 🧵 | **Spoolman-Integration** — Spulen einzelnen AMS-Slots zuweisen, Filament-Verbrauch wird automatisch beim Drucken erfasst und synchronisiert |
|
||||
| 🔗 | **Multi-ACE-Unterstützung** — mehrere aneinandergekettete ACE-Einheiten, auch bei Druckern ohne Toolhead-Buffer |
|
||||
| 📷 | **Obico-Integration (experimentell)** — Time-Lapse und WebRTC-Livestream gegen einen selbst gehosteten [Obico-Server](https://github.com/TheSpaghettiDetective/obico-server) via moonraker-obico |
|
||||
| 📐 | **H.264-Direkt-Stream + Z-Höhe** — sparsamer Kamera-Pfad für Obico, aktuelle Z aus der Layer-Höhe abgeleitet (Mm-Progress-Widget) |
|
||||
| 🗂️ | **GCode-Browser** — hochgeladene Dateien mit Thumbnail, Druckhistorie, Suche & Filter |
|
||||
| 📐 | **H.264-Direkt-Stream + Z-Höhe** — sparsamer Kamera-Pfad für Obico, aktuelle Z aus der Layer-Höhe abgeleitet (Mm-Progress-Widget); erholt sich automatisch nach einem Drucker-Reboot mit rotiertem Stream-Token, kein manueller Reset nötig |
|
||||
| 🗂️ | **GCode-Browser** — zwei Tabs: hochgeladene Dateien (mit Thumbnail, Druckhistorie, Suche & Filter, Mehrfachauswahl + Sammel-Löschen) und Dateien direkt auf dem Drucker-Speicher (mit echten Thumbnails, Mehrfachauswahl + Löschen) |
|
||||
| 🧩 | **Multi-Printer** — mehrere Drucker in **einer** Bridge-Instanz, Umschalten per Dropdown |
|
||||
| ➕ | **Drucker hinzufügen per Klick** — nur die IP eingeben, Zugangsdaten werden automatisch importiert |
|
||||
| 🖱️ | **Frei anpassbares Dashboard** — Kacheln per Drag & Drop verschieben und in der Größe anpassen, als Preset speichern |
|
||||
| 🔁 | **Robuster MQTT-Reconnect** — Bridge überlebt nächtlichen Drucker-Reboot ohne manuellen Neustart |
|
||||
| 🌐 | **Mehrsprachiges UI** — DE / EN / ES / FR / IT / 中文, Browser-Sprache automatisch erkannt |
|
||||
| 🔄 | **Self-Update** — neue Versionen direkt im Browser installieren |
|
||||
@@ -68,6 +72,11 @@ LAN-Modus am Kobra X aktivieren:
|
||||
docker compose up -d
|
||||
```
|
||||
|
||||
> Zusätzlich Spoolman und einen kompletten selbst gehosteten Obico-Setup
|
||||
> (Spaghetti-Erkennung, Live-Stream) neben der Bridge? [`docker-compose-KX.yml`](docker-compose-KX.yml)
|
||||
> bündelt KX-Bridge + Spoolman + Obico (Web/ML/Tasks/Redis) + moonraker-obico
|
||||
> in einem Netzwerk — Setup-Schritte in den Kommentaren am Dateianfang.
|
||||
|
||||
**Linux-Binary (kein Docker):**
|
||||
```bash
|
||||
chmod +x kx-bridge && ./kx-bridge
|
||||
@@ -110,7 +119,7 @@ Drucker → Verbindungstyp **Moonraker** → Host: `http://BRIDGE-IP:7125`
|
||||
|
||||
## 📺 Video-Tutorial
|
||||
|
||||
[](https://www.youtube.com/watch?v=1Ql4wfH27fM)
|
||||
[](https://www.youtube.com/watch?v=E3sDigSeSdM)
|
||||
|
||||
---
|
||||
|
||||
|
||||
17
README.es.md
17
README.es.md
@@ -22,7 +22,7 @@ ninguna está oficialmente probada ni soportada. Se agradece el feedback.</sub>
|
||||
|
||||
[](https://gitea.it-drui.de/viewit/KX-Bridge-Release/releases)
|
||||
|
||||
[](https://www.youtube.com/watch?v=1Ql4wfH27fM)
|
||||
[](https://www.youtube.com/watch?v=E3sDigSeSdM)
|
||||
|
||||
<sub>¿Te gusta KX-Bridge? Un café en <a href="https://ko-fi.com/viewitde">Ko-fi</a> mantiene el proyecto vivo. ☕</sub>
|
||||
|
||||
@@ -42,12 +42,16 @@ ninguna está oficialmente probada ni soportada. Se agradece el feedback.</sub>
|
||||
| 🖨️ | **Control de impresora** — iniciar, pausar, reanudar, cancelar, temperaturas, velocidad de impresión |
|
||||
| 📊 | **Estado en tiempo real** — temperatura, progreso, capas, tiempo restante, transmisión de cámara |
|
||||
| 🎨 | **AMS / multicolor** — ranuras con **selector de perfil por ranura** (asigna tu propia marca de los perfiles de OrcaSlicer a cada ranura); el puente escribe material y color al display de la impresora |
|
||||
| 🏷️ | **Coincidencia de etiquetas RFID personalizadas** — las bobinas etiquetadas con herramientas de terceros (p. ej. la app "ACE RFID") se emparejan automáticamente por marca + material con tus perfiles de OrcaSlicer importados, en lugar de caer en un perfil genérico |
|
||||
| 📦 | **Importa tus propios perfiles de OrcaSlicer** — arrastra un ZIP de `~/.config/OrcaSlicer/user/<id>/filament/` al puente; aparecen en el desplegable de la ranura bajo ★ Perfiles propios |
|
||||
| 🧵 | **Integración con Spoolman** — asigna bobinas a las ranuras del AMS, el consumo de filamento se registra y sincroniza automáticamente al imprimir |
|
||||
| 🔗 | **Soporte multi-ACE** — múltiples unidades ACE encadenadas, incluso en impresoras sin buffer en el cabezal |
|
||||
| 📷 | **Integración con Obico (experimental)** — Time-Lapse y stream en vivo WebRTC contra un [servidor Obico](https://github.com/TheSpaghettiDetective/obico-server) autoalojado vía moonraker-obico |
|
||||
| 📐 | **Stream H.264 directo + altura Z** — ruta de cámara de bajo consumo de CPU para Obico, Z actual derivada de la altura de capa (widget de progreso) |
|
||||
| 🗂️ | **Explorador de GCode** — archivos subidos con vistas previas, historial de impresión, búsqueda y filtros |
|
||||
| 📐 | **Stream H.264 directo + altura Z** — ruta de cámara de bajo consumo de CPU para Obico, Z actual derivada de la altura de capa (widget de progreso); se recupera automáticamente tras un reinicio de la impresora que rota el token del stream, sin necesidad de reinicio manual |
|
||||
| 🗂️ | **Explorador de GCode** — dos pestañas: archivos subidos (con vistas previas, historial de impresión, búsqueda y filtros, selección múltiple + borrado masivo) y archivos almacenados directamente en la memoria de la impresora (con vistas previas reales, selección múltiple + borrado) |
|
||||
| 🧩 | **Multi-impresora** — múltiples impresoras en **una** instancia del puente, cambia mediante un menú desplegable |
|
||||
| ➕ | **Añade una impresora con un clic** — solo introduce la IP, las credenciales se importan automáticamente |
|
||||
| 🖱️ | **Panel de control libre** — arrastra y redimensiona las tarjetas del panel a tu gusto, guárdalo como preset |
|
||||
| 🔁 | **Reconexión MQTT robusta** — el puente sobrevive a reinicios nocturnos de la impresora sin reinicio manual |
|
||||
| 🌐 | **Interfaz multilingüe** — DE / EN / ES / FR / IT / 中文, detecta automáticamente el idioma del navegador |
|
||||
| 🔄 | **Actualización automática** — instala nuevas versiones directamente desde el navegador |
|
||||
@@ -69,6 +73,11 @@ Activa el modo LAN en la Kobra X:
|
||||
docker compose up -d
|
||||
```
|
||||
|
||||
> ¿Quieres Spoolman y un setup completo de Obico autoalojado (detección de
|
||||
> espagueti, stream en vivo) junto al puente? [`docker-compose-KX.yml`](docker-compose-KX.yml)
|
||||
> combina KX-Bridge + Spoolman + Obico (web/ML/tasks/redis) + moonraker-obico
|
||||
> en una sola red — consulta los comentarios al inicio del archivo para los pasos de configuración.
|
||||
|
||||
**Binario Linux (sin Docker):**
|
||||
```bash
|
||||
chmod +x kx-bridge && ./kx-bridge
|
||||
@@ -111,7 +120,7 @@ Impresora → Tipo de conexión **Moonraker** → Host: `http://IP-DEL-PUENTE:71
|
||||
|
||||
## 📺 Vídeo tutorial
|
||||
|
||||
[](https://www.youtube.com/watch?v=1Ql4wfH27fM)
|
||||
[](https://www.youtube.com/watch?v=E3sDigSeSdM)
|
||||
|
||||
---
|
||||
|
||||
|
||||
17
README.md
17
README.md
@@ -22,7 +22,7 @@ officially tested or supported. Feedback welcome.</sub>
|
||||
|
||||
[](https://gitea.it-drui.de/viewit/KX-Bridge-Release/releases)
|
||||
|
||||
[](https://www.youtube.com/watch?v=1Ql4wfH27fM)
|
||||
[](https://www.youtube.com/watch?v=E3sDigSeSdM)
|
||||
|
||||
<sub>Like KX-Bridge? A coffee on <a href="https://ko-fi.com/viewitde">Ko-fi</a> keeps the project alive. ☕</sub>
|
||||
|
||||
@@ -42,12 +42,16 @@ officially tested or supported. Feedback welcome.</sub>
|
||||
| 🖨️ | **Printer control** — start, pause, resume, cancel, temperatures, print speed |
|
||||
| 📊 | **Live status** — temperature, progress, layers, remaining time, camera stream |
|
||||
| 🎨 | **AMS / multicolor** — slots with per-slot **profile picker** (assign your own brand from OrcaSlicer profiles per slot); bridge writes material & colour back to the printer display |
|
||||
| 🏷️ | **Custom RFID tag matching** — spools tagged with third-party tools (e.g. the "ACE RFID" app) auto-match vendor + material against your imported OrcaSlicer profiles instead of falling back to a generic default |
|
||||
| 📦 | **Import your own OrcaSlicer profiles** — drag a ZIP from `~/.config/OrcaSlicer/user/<id>/filament/` into the bridge; they show up in the slot dropdown under ★ Own profiles |
|
||||
| 🧵 | **Spoolman integration** — assign spools to AMS slots, filament usage tracked and synced automatically as you print |
|
||||
| 🔗 | **Multi-ACE support** — multiple daisy-chained ACE units, including printers without a toolhead buffer |
|
||||
| 📷 | **Obico integration (experimental)** — Time-Lapse and WebRTC live stream against a self-hosted [Obico server](https://github.com/TheSpaghettiDetective/obico-server) via moonraker-obico |
|
||||
| 📐 | **Direct H.264 stream + Z-height** — low-CPU camera path for Obico, current Z derived from layer-height for the print-progress widget |
|
||||
| 🗂️ | **GCode browser** — uploaded files with thumbnails, print history, search & filter |
|
||||
| 📐 | **Direct H.264 stream + Z-height** — low-CPU camera path for Obico, current Z derived from layer-height for the print-progress widget; auto-recovers after a printer reboot rotates its stream token, no manual reset needed |
|
||||
| 🗂️ | **GCode browser** — two tabs: files you've uploaded (with thumbnails, print history, search & filter, multi-select + bulk delete) and files stored directly on the printer's own storage (with real thumbnails, multi-select + delete) |
|
||||
| 🧩 | **Multi-printer** — multiple printers in **one** bridge instance, switch via dropdown |
|
||||
| ➕ | **Add a printer with one click** — just enter the IP, credentials are imported automatically |
|
||||
| 🖱️ | **Free-form dashboard** — drag & resize the dashboard tiles into your own layout, save it as a preset |
|
||||
| 🔁 | **Robust MQTT reconnect** — bridge survives overnight printer reboots without manual restart |
|
||||
| 🌐 | **Multi-language UI** — DE / EN / ES / FR / IT / 中文, auto-detect browser locale |
|
||||
| 🔄 | **Self-update** — install new versions directly in the browser |
|
||||
@@ -69,6 +73,11 @@ Enable LAN mode on the Kobra X:
|
||||
docker compose up -d
|
||||
```
|
||||
|
||||
> Want Spoolman and a full self-hosted Obico setup (spaghetti detection, live stream)
|
||||
> alongside the bridge? [`docker-compose-KX.yml`](docker-compose-KX.yml) bundles
|
||||
> KX-Bridge + Spoolman + Obico (web/ML/tasks/redis) + moonraker-obico behind one
|
||||
> network — see the file's header comments for setup steps.
|
||||
|
||||
**Linux binary (no Docker):**
|
||||
```bash
|
||||
chmod +x kx-bridge && ./kx-bridge
|
||||
@@ -111,7 +120,7 @@ Printer → Connection type **Moonraker** → Host: `http://BRIDGE-IP:7125`
|
||||
|
||||
## 📺 Video Tutorial
|
||||
|
||||
[](https://www.youtube.com/watch?v=1Ql4wfH27fM)
|
||||
[](https://www.youtube.com/watch?v=E3sDigSeSdM)
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
# KobraX Full Stack — KX-Bridge + Obico Self-Hosted + Spoolman
|
||||
#
|
||||
# Für Portainer: Stack → Add Stack → Upload → diese Datei wählen
|
||||
# For Portainer: Stack → Add Stack → Upload → select this file
|
||||
#
|
||||
# Voraussetzung: Obico-Images einmalig in Gitea-Registry pushen:
|
||||
# Prerequisite: push the Obico images to the Gitea registry once:
|
||||
# docker tag obico-server-web:latest gitea.it-drui.de/viewit/obico-web:latest
|
||||
# docker tag obico-server-ml_api:latest gitea.it-drui.de/viewit/obico-ml:latest
|
||||
# docker tag obico-server-tasks:latest gitea.it-drui.de/viewit/obico-tasks:latest
|
||||
@@ -10,14 +10,14 @@
|
||||
# docker push gitea.it-drui.de/viewit/obico-ml:latest
|
||||
# docker push gitea.it-drui.de/viewit/obico-tasks:latest
|
||||
#
|
||||
# Persistente Daten: /mnt/dockerdata/KobraXStack/<service>/
|
||||
# Persistent data: /mnt/dockerdata/KobraXStack/<service>/
|
||||
#
|
||||
# Ports:
|
||||
# 7125 — KX-Bridge (Moonraker-API)
|
||||
# 3334 — Obico (Web-UI)
|
||||
# 7912 — Spoolman (Web-UI)
|
||||
# 7125 — KX-Bridge (Moonraker API)
|
||||
# 3334 — Obico (Web UI)
|
||||
# 7912 — Spoolman (Web UI)
|
||||
#
|
||||
# Obico Admin-Account nach dem ersten Start:
|
||||
# Obico admin account after first start:
|
||||
# docker exec obico-web python manage.py createsuperuser
|
||||
|
||||
x-obico-base: &obico-base
|
||||
@@ -162,12 +162,12 @@ services:
|
||||
max-size: "10m"
|
||||
max-file: "3"
|
||||
|
||||
# ── moonraker-obico Plugin ──────────────────────────────────
|
||||
# Verbindet KX-Bridge mit dem Obico-Server (Spaghetti-Detektion, Remote-UI)
|
||||
# Voraussetzung: /mnt/dockerdata/KobraXStack/moonraker-obico/moonraker-obico.cfg
|
||||
# muss existieren und einen gültigen auth_token enthalten.
|
||||
# ── moonraker-obico plugin ──────────────────────────────────
|
||||
# Connects KX-Bridge to the Obico server (spaghetti detection, remote UI)
|
||||
# Prerequisite: /mnt/dockerdata/KobraXStack/moonraker-obico/moonraker-obico.cfg
|
||||
# must exist and contain a valid auth_token.
|
||||
#
|
||||
# Token holen (nach erstem obico-web Start):
|
||||
# Getting a token (after the first obico-web start):
|
||||
# docker exec obico-web python manage.py shell -c "
|
||||
# from app.models import OneTimeVerificationCode, User
|
||||
# from django.utils import timezone; from datetime import timedelta; import random
|
||||
@@ -175,7 +175,7 @@ services:
|
||||
# c = OneTimeVerificationCode.objects.create(user=u, code='%06d' % random.randint(100000,999999), expired_at=timezone.now()+timedelta(hours=2))
|
||||
# print('CODE:', c.code)"
|
||||
# curl -X POST 'http://localhost:3334/api/v1/octo/verify/?code=<CODE>'
|
||||
# → printer.auth_token aus der Antwort in die cfg eintragen
|
||||
# → enter printer.auth_token from the response into the cfg
|
||||
moonraker-obico:
|
||||
image: gitea.it-drui.de/viewit/moonraker-obico:latest
|
||||
container_name: moonraker-obico
|
||||
@@ -195,7 +195,7 @@ networks:
|
||||
kobrax-stack:
|
||||
driver: bridge
|
||||
|
||||
# Verzeichnisse müssen auf dem Host existieren:
|
||||
# Directories must exist on the host:
|
||||
# mkdir -p /mnt/dockerdata/KobraXStack/kx-bridge/config \
|
||||
# /mnt/dockerdata/KobraXStack/kx-bridge/data \
|
||||
# /mnt/dockerdata/KobraXStack/spoolman \
|
||||
@@ -203,8 +203,8 @@ networks:
|
||||
# /mnt/dockerdata/KobraXStack/obico/frontend \
|
||||
# /mnt/dockerdata/KobraXStack/obico/redis \
|
||||
# /mnt/dockerdata/KobraXStack/moonraker-obico/logs
|
||||
# Spoolman benötigt UID/GID 1000:
|
||||
# Spoolman requires UID/GID 1000:
|
||||
# sudo chown -R 1000:1000 /mnt/dockerdata/KobraXStack/spoolman
|
||||
#
|
||||
# moonraker-obico Config anlegen (auth_token nach Obico-Setup eintragen):
|
||||
# Create the moonraker-obico config (enter auth_token after Obico setup):
|
||||
# cp /path/to/moonraker-obico.cfg.example /mnt/dockerdata/KobraXStack/moonraker-obico/moonraker-obico.cfg
|
||||
|
||||
@@ -1058,6 +1058,10 @@ class KobraXBridge:
|
||||
# as the existing fileDetails fire-and-forget pattern. Format:
|
||||
# {action: {"event": threading.Event(), "result": dict|None}}.
|
||||
self._file_action_waiters: dict[str, dict] = {}
|
||||
# Thumbnail cache for files on the printer's own storage (filename ->
|
||||
# base64 PNG string, "" if the file has no embedded thumbnail).
|
||||
# In-memory only - not persisted, cleared on restart.
|
||||
self._printer_thumbnail_cache: dict[str, str] = {}
|
||||
self._store = store if store is not None else GCodeStore(args.data_dir)
|
||||
self._serve_dir_path: str = self._store._gcode_dir
|
||||
self._current_job_id: str = ""
|
||||
@@ -2870,6 +2874,40 @@ class KobraXBridge:
|
||||
return self._json_cors({"error": "delete failed", "detail": result}, status=502)
|
||||
return self._json_cors({"result": "ok"})
|
||||
|
||||
async def handle_kx_printer_file_thumbnail(self, request):
|
||||
"""GET /kx/printer-files/{filename}/thumbnail - fetches the embedded
|
||||
GCode thumbnail for a file on the printer's own storage, via
|
||||
file/fileDetails. The printer extracts and base64-encodes the
|
||||
"; thumbnail begin"-block from the GCode header on demand and
|
||||
returns it inline in data.file_details.thumbnail - no separate
|
||||
download/presigned-URL step needed (verified live against a real
|
||||
Kobra X). Cached in-memory per filename since a file's thumbnail
|
||||
never changes while it exists on the printer, and re-querying on
|
||||
every render/scroll would mean one MQTT roundtrip per visible card."""
|
||||
filename = request.match_info.get("filename", "")
|
||||
if not filename:
|
||||
return self._json_cors({"error": "no filename given"}, status=400)
|
||||
cached = self._printer_thumbnail_cache.get(filename)
|
||||
if cached is not None:
|
||||
return self._json_cors({"result": {"thumbnail": cached}})
|
||||
loop = asyncio.get_event_loop()
|
||||
def _fetch():
|
||||
return self._wait_for_file_action(
|
||||
"fileDetails",
|
||||
lambda: self.client.publish(
|
||||
"file", "fileDetails",
|
||||
{"root": "local", "filename": filename},
|
||||
timeout=0,
|
||||
),
|
||||
timeout=8.0,
|
||||
)
|
||||
result = await loop.run_in_executor(None, _fetch)
|
||||
if not result or result.get("code") != 200:
|
||||
return self._json_cors({"error": "printer unreachable or query failed"}, status=502)
|
||||
thumb = ((result.get("data") or {}).get("file_details") or {}).get("thumbnail") or ""
|
||||
self._printer_thumbnail_cache[filename] = thumb
|
||||
return self._json_cors({"result": {"thumbnail": thumb}})
|
||||
|
||||
async def handle_kx_file_download(self, request):
|
||||
file_id = request.match_info["file_id"]
|
||||
f = self._store.get_file(file_id)
|
||||
@@ -5829,6 +5867,7 @@ def build_app(bridge: KobraXBridge) -> web.Application:
|
||||
r.add_post("/kx/files/{file_id}/verify", bridge.handle_kx_file_verify)
|
||||
r.add_get("/kx/printer-files", bridge.handle_kx_printer_files)
|
||||
r.add_post("/kx/printer-files/delete", bridge.handle_kx_printer_file_delete)
|
||||
r.add_get("/kx/printer-files/{filename}/thumbnail", bridge.handle_kx_printer_file_thumbnail)
|
||||
r.add_get("/kx/filament/slots", bridge.handle_kx_filament_slots)
|
||||
r.add_get("/kx/filament/profiles", bridge.handle_kx_filament_profiles)
|
||||
r.add_post("/kx/filament/slots/{idx}/profile", bridge.handle_kx_filament_slot_profile)
|
||||
|
||||
@@ -54,6 +54,40 @@ DELETEBATCH_FAILED = {
|
||||
"data": None,
|
||||
}
|
||||
|
||||
FILEDETAILS_SUCCESS = {
|
||||
"action": "fileDetails",
|
||||
"code": 200,
|
||||
"state": "done",
|
||||
"data": {
|
||||
"file_details": {
|
||||
"thumbnail": "iVBORw0KGgoAAAANSUhEUgAAAAEAAAAB",
|
||||
"png_image": "",
|
||||
"svg_image": "",
|
||||
"objects_skip_parts": [],
|
||||
},
|
||||
"filename": "a.gcode",
|
||||
"root": "local",
|
||||
},
|
||||
}
|
||||
|
||||
FILEDETAILS_NO_THUMBNAIL = {
|
||||
"action": "fileDetails",
|
||||
"code": 200,
|
||||
"state": "done",
|
||||
"data": {
|
||||
"file_details": {"thumbnail": "", "png_image": "", "svg_image": "", "objects_skip_parts": []},
|
||||
"filename": "a.gcode",
|
||||
"root": "local",
|
||||
},
|
||||
}
|
||||
|
||||
FILEDETAILS_FAILED = {
|
||||
"action": "fileDetails",
|
||||
"code": 10112,
|
||||
"state": "failed",
|
||||
"data": None,
|
||||
}
|
||||
|
||||
|
||||
def _deliver_async(bridge, payload, delay=0.05):
|
||||
"""Simulates the MQTT reader thread delivering a file/report a moment
|
||||
@@ -142,3 +176,58 @@ async def test_printer_file_delete_returns_502_on_printer_rejection(client):
|
||||
bridge.client.publish.side_effect = lambda *a, **kw: (_deliver_async(bridge, DELETEBATCH_FAILED), None)[1]
|
||||
resp = await c.post("/kx/printer-files/delete", json={"filenames": ["a.gcode"]})
|
||||
assert resp.status == 502
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_printer_file_thumbnail_success(client):
|
||||
c, bridge = client
|
||||
bridge.client.publish.side_effect = lambda *a, **kw: (_deliver_async(bridge, FILEDETAILS_SUCCESS), None)[1]
|
||||
resp = await c.get("/kx/printer-files/a.gcode/thumbnail")
|
||||
assert resp.status == 200
|
||||
data = await resp.json()
|
||||
assert data["result"]["thumbnail"] == "iVBORw0KGgoAAAANSUhEUgAAAAEAAAAB"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_printer_file_thumbnail_uses_correct_mqtt_payload(client):
|
||||
c, bridge = client
|
||||
bridge.client.publish.side_effect = lambda *a, **kw: (_deliver_async(bridge, FILEDETAILS_SUCCESS), None)[1]
|
||||
await c.get("/kx/printer-files/a.gcode/thumbnail")
|
||||
args, kwargs = bridge.client.publish.call_args
|
||||
assert args[0] == "file"
|
||||
assert args[1] == "fileDetails"
|
||||
assert args[2] == {"root": "local", "filename": "a.gcode"}
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_printer_file_thumbnail_empty_when_no_thumbnail_embedded(client):
|
||||
c, bridge = client
|
||||
bridge.client.publish.side_effect = lambda *a, **kw: (_deliver_async(bridge, FILEDETAILS_NO_THUMBNAIL), None)[1]
|
||||
resp = await c.get("/kx/printer-files/a.gcode/thumbnail")
|
||||
assert resp.status == 200
|
||||
data = await resp.json()
|
||||
assert data["result"]["thumbnail"] == ""
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_printer_file_thumbnail_returns_502_on_printer_failure(client):
|
||||
c, bridge = client
|
||||
bridge.client.publish.side_effect = lambda *a, **kw: (_deliver_async(bridge, FILEDETAILS_FAILED), None)[1]
|
||||
resp = await c.get("/kx/printer-files/a.gcode/thumbnail")
|
||||
assert resp.status == 502
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_printer_file_thumbnail_is_cached_after_first_fetch(client):
|
||||
"""Second request for the same filename must not call publish() again."""
|
||||
c, bridge = client
|
||||
bridge.client.publish.side_effect = lambda *a, **kw: (_deliver_async(bridge, FILEDETAILS_SUCCESS), None)[1]
|
||||
resp1 = await c.get("/kx/printer-files/a.gcode/thumbnail")
|
||||
assert resp1.status == 200
|
||||
call_count_after_first = bridge.client.publish.call_count
|
||||
|
||||
resp2 = await c.get("/kx/printer-files/a.gcode/thumbnail")
|
||||
assert resp2.status == 200
|
||||
data2 = await resp2.json()
|
||||
assert data2["result"]["thumbnail"] == "iVBORw0KGgoAAAANSUhEUgAAAAEAAAAB"
|
||||
assert bridge.client.publish.call_count == call_count_after_first # no new MQTT call
|
||||
|
||||
@@ -3045,7 +3045,7 @@ function renderPrinterFiles(){
|
||||
return;
|
||||
}
|
||||
empty.style.display='none';
|
||||
grid.innerHTML=printerFiles.map(function(f){
|
||||
grid.innerHTML=printerFiles.map(function(f,idx){
|
||||
var name=f.filename.length>28?f.filename.slice(0,25)+'…':f.filename;
|
||||
var sizeKb=f.size?(f.size/1024).toFixed(0)+' KB':'–';
|
||||
var date=f.timestamp?new Date(f.timestamp).toISOString().replace('T',' ').slice(0,16):'';
|
||||
@@ -3059,9 +3059,14 @@ function renderPrinterFiles(){
|
||||
'style="width:16px;height:16px;margin:0"></span>';
|
||||
var cardClick=_printerFilesSelectMode?'onclick="printerFileToggleSelect(\''+f.filename.replace(/'/g,"\\'")+'\')" style="cursor:pointer;position:relative;background:var(--raised);border-radius:8px;'+selectBorder+';display:flex;flex-direction:column"':
|
||||
'style="position:relative;background:var(--raised);border-radius:8px;'+selectBorder+';display:flex;flex-direction:column"';
|
||||
var thumbId='pft-'+idx;
|
||||
var cachedThumb=_printerThumbCache[f.filename];
|
||||
var thumbHtml=cachedThumb
|
||||
? '<img id="'+thumbId+'" src="data:image/png;base64,'+cachedThumb+'" style="width:100%;height:60px;object-fit:contain;border-radius:6px;background:var(--raised);margin-bottom:8px">'
|
||||
: '<div id="'+thumbId+'" data-filename="'+encodeURIComponent(f.filename)+'" style="width:100%;height:60px;background:var(--raised);border-radius:6px;display:flex;align-items:center;justify-content:center;margin-bottom:8px;font-size:28px">🖨</div>';
|
||||
return '<div '+cardClick+'>'+
|
||||
checkbox+
|
||||
'<div style="width:100%;height:60px;background:var(--raised);border-radius:6px;display:flex;align-items:center;justify-content:center;margin-bottom:8px;font-size:28px">🖨</div>'+
|
||||
thumbHtml+
|
||||
'<div title="'+f.filename+'" style="font-size:12px;font-weight:600;margin-bottom:4px;color:var(--txt)">'+name+'</div>'+
|
||||
'<div style="font-size:11px;color:var(--txt2);margin-bottom:2px">💾 '+sizeKb+'</div>'+
|
||||
'<div style="font-size:11px;color:var(--txt2);margin-bottom:8px">📅 '+date+'</div>'+
|
||||
@@ -3072,6 +3077,46 @@ function renderPrinterFiles(){
|
||||
'</div>';
|
||||
}).join('');
|
||||
_printerFilesUpdateSelectBar();
|
||||
_loadVisiblePrinterThumbnails();
|
||||
}
|
||||
|
||||
// Thumbnails are fetched lazily, one at a time, only for cards not already
|
||||
// cached - fetching all of them upfront would mean one MQTT roundtrip per
|
||||
// file (145+ files is common), overwhelming the single MQTT connection.
|
||||
var _printerThumbCache={}; // filename -> base64 PNG string ("" = no thumbnail)
|
||||
var _printerThumbQueue=[];
|
||||
var _printerThumbLoading=false;
|
||||
|
||||
function _loadVisiblePrinterThumbnails(){
|
||||
var placeholders=document.querySelectorAll('#printer-store-grid [data-filename]');
|
||||
_printerThumbQueue=Array.prototype.slice.call(placeholders);
|
||||
_pumpPrinterThumbQueue();
|
||||
}
|
||||
|
||||
function _pumpPrinterThumbQueue(){
|
||||
if(_printerThumbLoading||!_printerThumbQueue.length)return;
|
||||
var el=_printerThumbQueue.shift();
|
||||
if(!el||!el.isConnected){_pumpPrinterThumbQueue();return;}
|
||||
var encodedName=el.getAttribute('data-filename');
|
||||
_printerThumbLoading=true;
|
||||
fetch(_apiUrl('/kx/printer-files/'+encodedName+'/thumbnail'))
|
||||
.then(function(r){return r.json()})
|
||||
.then(function(d){
|
||||
var thumb=(d.result&&d.result.thumbnail)||'';
|
||||
_printerThumbCache[decodeURIComponent(encodedName)]=thumb;
|
||||
if(thumb&&el.isConnected){
|
||||
var img=document.createElement('img');
|
||||
img.src='data:image/png;base64,'+thumb;
|
||||
img.style.cssText='width:100%;height:60px;object-fit:contain;border-radius:6px;background:var(--raised);margin-bottom:8px';
|
||||
img.id=el.id;
|
||||
el.replaceWith(img);
|
||||
}
|
||||
})
|
||||
.catch(function(){/* keep the placeholder icon on failure */})
|
||||
.finally(function(){
|
||||
_printerThumbLoading=false;
|
||||
_pumpPrinterThumbQueue();
|
||||
});
|
||||
}
|
||||
|
||||
function _printerFilesUpdateSelectBar(){
|
||||
|
||||
Reference in New Issue
Block a user