- Python stdlib server with SSE live updates, PIN login, remote access - Vanilla JS web UI (English/German): mixer, channel, routing, links, limiter calculator - Preset file export/import with undo, settings backup, lock for the desktop app - Network (TCP 9761) and USB HID transport (Windows, macOS, Linux) - Desktop app via pywebview, Raspberry Pi SD card writer, simulator and protocol tests - README with import guide for Claude Code, CLAUDE.md, protocol documentation Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
263 lines
12 KiB
Python
263 lines
12 KiB
Python
"""DSP Control Pi Writer: prepares a bootable SD card with Raspberry Pi OS Lite + DSP Control.
|
||
|
||
After the first boot (2-5 minutes) the WebUI is at http://<hostname>.local - no monitor,
|
||
keyboard or internet needed on the Pi.
|
||
|
||
Build: pyinstaller packaging/pi-writer.spec
|
||
"""
|
||
|
||
import json
|
||
import os
|
||
import queue
|
||
import sys
|
||
import threading
|
||
import tkinter as tk
|
||
import traceback
|
||
from pathlib import Path
|
||
from tkinter import messagebox, ttk
|
||
|
||
import pi_image
|
||
import win_disk
|
||
|
||
APP = "DSP Control Pi Writer"
|
||
ROOT = Path(getattr(sys, "_MEIPASS", Path(__file__).resolve().parent)) # bundled app files
|
||
SETTINGS = Path(os.environ.get("APPDATA") or Path.home()) / "DSP Control" / "pi-writer.json"
|
||
CACHE = Path(os.environ.get("LOCALAPPDATA") or Path.home()) / "DSP Control" / "pi-images"
|
||
REMEMBER = ("model", "hostname", "ssid", "country", "user", "ssh", "dsp204", "dsp408", "verify")
|
||
|
||
|
||
class Writer(tk.Tk):
|
||
def __init__(self):
|
||
super().__init__()
|
||
self.title(APP)
|
||
self.minsize(560, 640)
|
||
self.events: queue.Queue = queue.Queue()
|
||
self.busy = False
|
||
self.disks: list[dict] = []
|
||
saved = self.load_settings()
|
||
|
||
self.v = {
|
||
"model": tk.StringVar(value=saved.get("model", pi_image.MODELS[1][0])),
|
||
"disk": tk.StringVar(),
|
||
"hostname": tk.StringVar(value=saved.get("hostname", "dsp-control")),
|
||
"ssid": tk.StringVar(value=saved.get("ssid", "")),
|
||
"wifi_password": tk.StringVar(),
|
||
"country": tk.StringVar(value=saved.get("country", "AT")),
|
||
"user": tk.StringVar(value=saved.get("user", "dsp")),
|
||
"password": tk.StringVar(),
|
||
"ssh": tk.BooleanVar(value=saved.get("ssh", True)),
|
||
"pin": tk.StringVar(value="1234"),
|
||
"dsp204": tk.StringVar(value=saved.get("dsp204", "")),
|
||
"dsp408": tk.StringVar(value=saved.get("dsp408", "")),
|
||
"verify": tk.BooleanVar(value=saved.get("verify", True)),
|
||
}
|
||
self.build()
|
||
self.after(100, self.poll)
|
||
self.after(200, self.refresh_disks)
|
||
|
||
# ------------------------------------------------------------ layout
|
||
|
||
def build(self):
|
||
pad = {"padx": 12, "pady": 4}
|
||
root = ttk.Frame(self, padding=(8, 8))
|
||
root.pack(fill="both", expand=True)
|
||
root.columnconfigure(0, weight=1)
|
||
|
||
ttk.Label(root, text="Raspberry Pi für DSP Control", font=("Segoe UI", 14, "bold")).grid(sticky="w", **pad)
|
||
ttk.Label(root, text="Schreibt Raspberry Pi OS Lite mit vorinstallierter DSP-Control-WebUI auf eine SD-Karte.",
|
||
foreground="#555").grid(sticky="w", padx=12)
|
||
|
||
def section(title):
|
||
f = ttk.LabelFrame(root, text=title, padding=(10, 6))
|
||
f.grid(sticky="ew", padx=12, pady=6)
|
||
f.columnconfigure(0, minsize=110)
|
||
f.columnconfigure(1, weight=1)
|
||
return f
|
||
|
||
def row(f, r, label, widget, hint=None):
|
||
ttk.Label(f, text=label).grid(row=r, column=0, sticky="w", pady=3, padx=(0, 10))
|
||
widget.grid(row=r, column=1, sticky="ew", pady=3)
|
||
if hint:
|
||
ttk.Label(f, text=hint, foreground="#777").grid(row=r, column=2, sticky="w", padx=(8, 0))
|
||
|
||
f = section("1 · Gerät")
|
||
models = [f"{n} ({d})" for n, d, _ in pi_image.MODELS]
|
||
cur = next((m for m in models if m.startswith(self.v["model"].get())), models[1])
|
||
self.model_box = ttk.Combobox(f, values=models, state="readonly")
|
||
self.model_box.set(cur)
|
||
row(f, 0, "Raspberry Pi", self.model_box)
|
||
disk_row = ttk.Frame(f)
|
||
disk_row.columnconfigure(0, weight=1)
|
||
self.disk_box = ttk.Combobox(disk_row, textvariable=self.v["disk"], state="readonly")
|
||
self.disk_box.grid(row=0, column=0, sticky="ew")
|
||
ttk.Button(disk_row, text="↻", width=3, command=self.refresh_disks).grid(row=0, column=1, padx=(6, 0))
|
||
row(f, 1, "SD-Karte", disk_row)
|
||
|
||
f = section("2 · Netzwerk")
|
||
row(f, 0, "Hostname", ttk.Entry(f, textvariable=self.v["hostname"]), ".local")
|
||
row(f, 1, "WLAN-Name", ttk.Entry(f, textvariable=self.v["ssid"]), "leer = nur LAN-Kabel")
|
||
row(f, 2, "WLAN-Passwort", ttk.Entry(f, textvariable=self.v["wifi_password"], show="•"))
|
||
row(f, 3, "Land", ttk.Entry(f, textvariable=self.v["country"], width=6), "z. B. AT, DE, CH")
|
||
|
||
f = section("3 · Zugang")
|
||
row(f, 0, "Benutzer", ttk.Entry(f, textvariable=self.v["user"]), "für SSH / Wartung")
|
||
row(f, 1, "Passwort", ttk.Entry(f, textvariable=self.v["password"], show="•"))
|
||
ttk.Checkbutton(f, text="SSH aktivieren", variable=self.v["ssh"]).grid(row=2, column=1, sticky="w", pady=3)
|
||
row(f, 3, "WebUI-PIN", ttk.Entry(f, textvariable=self.v["pin"], width=8), "4 Ziffern, später änderbar")
|
||
|
||
f = section("4 · DSPs (optional, später in der WebUI änderbar)")
|
||
row(f, 0, "IP DSP 204", ttk.Entry(f, textvariable=self.v["dsp204"]), "z. B. 192.168.1.101")
|
||
row(f, 1, "IP DSP 408", ttk.Entry(f, textvariable=self.v["dsp408"]))
|
||
|
||
bottom = ttk.Frame(root)
|
||
bottom.grid(sticky="ew", padx=12, pady=(8, 4))
|
||
bottom.columnconfigure(0, weight=1)
|
||
ttk.Checkbutton(bottom, text="Nach dem Schreiben überprüfen", variable=self.v["verify"]).grid(row=0, column=0, sticky="w")
|
||
self.go = ttk.Button(bottom, text="SD-Karte schreiben", command=self.start)
|
||
self.go.grid(row=0, column=1, sticky="e")
|
||
self.bar = ttk.Progressbar(root, maximum=1000)
|
||
self.bar.grid(sticky="ew", padx=12, pady=(6, 2))
|
||
self.status = ttk.Label(root, text="Bereit.", foreground="#333")
|
||
self.status.grid(sticky="w", padx=12, pady=(0, 8))
|
||
|
||
# ------------------------------------------------------------ settings
|
||
|
||
def load_settings(self) -> dict:
|
||
try:
|
||
return json.loads(SETTINGS.read_text(encoding="utf-8"))
|
||
except (OSError, ValueError):
|
||
return {}
|
||
|
||
def save_settings(self, cfg: dict):
|
||
try:
|
||
SETTINGS.parent.mkdir(parents=True, exist_ok=True)
|
||
SETTINGS.write_text(json.dumps({k: cfg[k] for k in REMEMBER if k in cfg}, indent=2), encoding="utf-8")
|
||
except OSError:
|
||
pass
|
||
|
||
# ------------------------------------------------------------ disks
|
||
|
||
def refresh_disks(self):
|
||
if self.busy:
|
||
return
|
||
self.status.config(text="Suche SD-Karten…")
|
||
threading.Thread(target=self._list_disks, daemon=True).start()
|
||
|
||
def _list_disks(self):
|
||
try:
|
||
self.events.put(("disks", win_disk.list_disks()))
|
||
except Exception as e: # noqa: BLE001
|
||
self.events.put(("disks_err", str(e)))
|
||
|
||
# ------------------------------------------------------------ run
|
||
|
||
def collect(self) -> dict:
|
||
cfg = {k: (v.get().strip() if isinstance(v, tk.StringVar) and k not in ("password", "wifi_password") else v.get())
|
||
for k, v in self.v.items()}
|
||
cfg["hostname"] = cfg["hostname"].lower()
|
||
cfg["user"] = cfg["user"].lower()
|
||
idx = self.model_box.current()
|
||
cfg["model"], _, cfg["bits"] = pi_image.MODELS[max(0, idx)]
|
||
return cfg
|
||
|
||
def start(self):
|
||
if self.busy:
|
||
return
|
||
cfg = self.collect()
|
||
errs = pi_image.validate(cfg)
|
||
disk = next((d for d in self.disks if win_disk.describe(d) == cfg["disk"]), None)
|
||
if not disk:
|
||
errs.insert(0, "Bitte eine SD-Karte wählen")
|
||
if errs:
|
||
messagebox.showerror(APP, "\n".join(errs))
|
||
return
|
||
if not messagebox.askyesno(APP, f"ALLE Daten auf\n\n{win_disk.describe(disk)}\n\nwerden gelöscht. Fortfahren?",
|
||
icon="warning"):
|
||
return
|
||
self.save_settings(cfg)
|
||
self.busy = True
|
||
self.go.config(state="disabled")
|
||
threading.Thread(target=self.job, args=(cfg, disk), daemon=True).start()
|
||
|
||
def job(self, cfg: dict, disk: dict):
|
||
ev = self.events.put
|
||
try:
|
||
ev(("status", "Lade Raspberry-Pi-OS-Liste…", None))
|
||
img = pi_image.find_image(pi_image.fetch_os_list(), cfg["bits"])
|
||
ev(("status", f"{img['name']} vom {img.get('release_date', '?')}", None))
|
||
path = pi_image.download(img, CACHE, lambda d, t: ev(("progress", f"Download {d / 1e6:.0f} / {t / 1e6:.0f} MB", d, t)))
|
||
phases = {"write": "Schreibe", "verify": "Überprüfe"}
|
||
win_disk.write_image(disk["Number"], path, int(img.get("extract_size") or 0),
|
||
lambda ph, d, t: ev(("progress", f"{phases[ph]} {d / 1e9:.2f} / {t / 1e9:.2f} GB", d, t)),
|
||
verify=cfg["verify"])
|
||
ev(("status", "Richte DSP Control ein…", None))
|
||
boot = win_disk.mount_boot_partition(disk["Number"])
|
||
pi_image.write_boot_files(boot, cfg, ROOT)
|
||
win_disk.eject(boot)
|
||
ev(("done", cfg))
|
||
except Exception as e: # noqa: BLE001 - every failure is shown to the user
|
||
traceback.print_exc()
|
||
ev(("error", str(e)))
|
||
|
||
def poll(self):
|
||
try:
|
||
while True:
|
||
kind, *a = self.events.get_nowait()
|
||
if kind == "disks":
|
||
self.disks = a[0]
|
||
names = [win_disk.describe(d) for d in self.disks]
|
||
self.disk_box.config(values=names)
|
||
if self.v["disk"].get() not in names:
|
||
self.v["disk"].set(names[0] if len(names) == 1 else "")
|
||
self.status.config(text=f"{len(names)} SD-Karte(n) gefunden." if names
|
||
else "Keine SD-Karte gefunden – einstecken und ↻ drücken.")
|
||
elif kind == "disks_err":
|
||
self.status.config(text="Fehler beim Suchen: " + a[0])
|
||
elif kind == "status":
|
||
self.status.config(text=a[0])
|
||
self.bar.config(mode="indeterminate")
|
||
self.bar.start(15)
|
||
elif kind == "progress":
|
||
text, done, total = a
|
||
self.bar.stop()
|
||
self.bar.config(mode="determinate", value=1000 * done / total if total else 0)
|
||
self.status.config(text=text)
|
||
elif kind in ("done", "error"):
|
||
self.busy = False
|
||
self.go.config(state="normal")
|
||
self.bar.stop()
|
||
self.bar.config(mode="determinate", value=1000 if kind == "done" else 0)
|
||
if kind == "done":
|
||
cfg = a[0]
|
||
self.status.config(text="Fertig.")
|
||
messagebox.showinfo(APP, "Fertig! Die SD-Karte kann entnommen werden.\n\n"
|
||
"Karte in den Raspberry Pi stecken, Netzwerk (LAN oder WLAN) und Strom anschließen. "
|
||
"Der erste Start dauert 2–5 Minuten.\n\n"
|
||
f"Dann im Browser öffnen: http://{cfg['hostname']}.local\n"
|
||
f"PIN: {cfg['pin']}")
|
||
else:
|
||
self.status.config(text="Fehler: " + a[0])
|
||
messagebox.showerror(APP, a[0])
|
||
self.refresh_disks()
|
||
except queue.Empty:
|
||
pass
|
||
self.after(100, self.poll)
|
||
|
||
|
||
def main():
|
||
if sys.platform == "win32" and not win_disk.is_admin():
|
||
if win_disk.relaunch_as_admin():
|
||
return
|
||
messagebox.showerror(APP, "Zum Beschreiben von SD-Karten werden Administratorrechte benötigt.")
|
||
return
|
||
try:
|
||
import ctypes
|
||
ctypes.windll.shcore.SetProcessDpiAwareness(1) # sharp text on high-DPI screens
|
||
except (AttributeError, OSError):
|
||
pass
|
||
Writer().mainloop()
|
||
|
||
|
||
if __name__ == "__main__":
|
||
main()
|