Files
GivouandClaude Opus 5.5 fe13f261f7 Add BetterDSPControl: web UI, desktop app and Pi writer for t.racks DSP 204/408
- 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>
2026-11-01 20:24:33 +01:00

171 lines
6.6 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""Raw SD card writing on Windows (needs administrator rights).
Safety: only removable USB/SD/MMC disks that are neither the boot nor the system disk are offered.
The first MiB (partition table) is written last, so Windows does not mount half-written
partitions in the middle of the job - the same trick Raspberry Pi Imager uses.
"""
import ctypes
import hashlib
import json
import lzma
import subprocess
import sys
import time
from pathlib import Path
CHUNK = 4 << 20 # write size (multiple of the sector size)
HEAD = 1 << 20 # held back and written last
MAX_SIZE = 512 << 30 # larger "removable" disks are most likely not an SD card
NO_WINDOW = 0x08000000 if sys.platform == "win32" else 0
def is_admin() -> bool:
try:
return bool(ctypes.windll.shell32.IsUserAnAdmin())
except (AttributeError, OSError):
return False
def relaunch_as_admin() -> bool:
"""Restart this program elevated (UAC prompt). True if the elevated copy was started."""
argv = sys.argv[1:] if getattr(sys, "frozen", False) else sys.argv # script: python <script> ...
args = " ".join(f'"{a}"' for a in argv)
return ctypes.windll.shell32.ShellExecuteW(None, "runas", sys.executable, args, None, 1) > 32
def powershell(script: str, timeout=60) -> str:
r = subprocess.run(["powershell", "-NoProfile", "-NonInteractive", "-Command", script],
capture_output=True, text=True, timeout=timeout, creationflags=NO_WINDOW)
if r.returncode:
raise RuntimeError(r.stderr.strip() or r.stdout.strip() or "PowerShell-Fehler")
return r.stdout
def list_disks() -> list[dict]:
out = powershell(
"@(Get-Disk | Where-Object { $_.BusType -in 'USB','SD','MMC' -and -not $_.IsBoot -and -not $_.IsSystem "
"-and $_.Size -gt 0 } | Select-Object Number,FriendlyName,Size,BusType) | ConvertTo-Json -Compress")
out = out.strip()
disks = json.loads(out) if out else []
if isinstance(disks, dict):
disks = [disks]
for d in disks:
d["Letters"] = drive_letters(d["Number"])
return [d for d in disks if 0 < d["Size"] <= MAX_SIZE]
def drive_letters(number: int) -> list[str]:
try:
out = powershell(f"@(Get-Partition -DiskNumber {int(number)} -ErrorAction SilentlyContinue | "
"Where-Object DriveLetter | ForEach-Object {{ [string]$_.DriveLetter }}) -join ','")
return [x for x in out.strip().split(",") if x]
except RuntimeError:
return []
def describe(d: dict) -> str:
letters = f" [{', '.join(l + ':' for l in d['Letters'])}]" if d.get("Letters") else ""
return f"Datenträger {d['Number']}: {d['FriendlyName']} – {d['Size'] / 1e9:.1f} GB ({d['BusType']}){letters}"
def diskpart(lines: list[str]):
r = subprocess.run(["diskpart"], input="\n".join(lines) + "\nexit\n", capture_output=True, text=True,
timeout=120, creationflags=NO_WINDOW)
if r.returncode:
raise RuntimeError("diskpart: " + (r.stdout.strip().splitlines() or ["Fehler"])[-1])
def write_image(number: int, xz_path: Path, total: int, progress, verify=True, target: Path | None = None):
"""Decompress xz_path straight onto the disk; total = image size for the progress bar.
progress(phase, done, total). `target` writes into a plain file instead (testing without a card)."""
if target is None:
diskpart([f"select disk {int(number)}", "clean"]) # drops partitions, Windows unmounts them
time.sleep(1)
dev = rf"\\.\PhysicalDrive{int(number)}"
else:
dev = str(target)
open(dev, "wb").close()
h = hashlib.sha256()
head = b""
written = 0
with lzma.open(xz_path) as src, open(dev, "r+b", buffering=0) as out:
buf = bytearray()
while True:
data = src.read(CHUNK)
if data:
h.update(data)
if len(head) < HEAD:
take = HEAD - len(head)
head += data[:take]
data = data[take:]
if len(head) == HEAD:
out.seek(HEAD)
buf += data
while len(buf) >= CHUNK or (not data and buf):
piece = bytes(buf[:CHUNK])
del buf[:CHUNK]
if len(piece) % 512:
piece += b"\0" * (512 - len(piece) % 512)
out.write(piece)
written += len(piece)
progress("write", written + len(head), total)
if not data:
break
out.seek(0)
out.write(head + b"\0" * (-len(head) % 512))
out.flush()
size = written + len(head)
if verify:
progress("verify", 0, size)
v = hashlib.sha256()
with open(dev, "rb", buffering=0) as f:
left = size
while left > 0:
n = min(CHUNK, left)
block = f.read(n + (-n % 512))[:n]
if not block:
break
v.update(block)
left -= len(block)
progress("verify", size - left, size)
if v.digest() != h.digest():
raise RuntimeError("Überprüfung fehlgeschlagen – die SD-Karte ist evtl. defekt oder gefälscht")
def mount_boot_partition(number: int, timeout=40) -> Path:
"""Make Windows pick up the new partition table and return the boot partition's drive root."""
try:
diskpart([f"select disk {int(number)}", "rescan"])
except RuntimeError:
pass
deadline = time.time() + timeout
assigned = False
while time.time() < deadline:
try:
letter = powershell(f"(Get-Partition -DiskNumber {int(number)} -PartitionNumber 1 "
"-ErrorAction Stop).DriveLetter").strip()
except RuntimeError:
letter = ""
if letter and letter != "\0":
root = Path(f"{letter}:\\")
if (root / "cmdline.txt").exists():
return root
elif not assigned and time.time() > deadline - timeout + 6:
try:
powershell(f"Add-PartitionAccessPath -DiskNumber {int(number)} -PartitionNumber 1 -AssignDriveLetter")
assigned = True
except RuntimeError:
pass
time.sleep(1)
raise RuntimeError("Bootpartition wurde von Windows nicht eingebunden – Karte neu einstecken und erneut versuchen")
def eject(root: Path):
"""Ask Windows to safely remove the card (best effort)."""
try:
powershell(f"(New-Object -ComObject Shell.Application).Namespace(17).ParseName('{str(root)[:2]}')"
".InvokeVerb('Eject')", timeout=20)
except (RuntimeError, subprocess.TimeoutExpired):
pass