feat: OTA firmware update per device with auto config backup
- Upload .bin firmware files via web UI - Update individual devices (button per device in table) - Auto config backup before each update - Shows current version vs available firmware - Firmware file management (upload/delete) Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
parent
0d6c03049c
commit
9218d10540
1
.gitignore
vendored
1
.gitignore
vendored
@ -8,6 +8,7 @@ config.cfg
|
||||
config.dev.cfg
|
||||
*.egg-info/
|
||||
backups/
|
||||
firmware/
|
||||
dist/
|
||||
build/
|
||||
.vscode/
|
||||
|
||||
71
app.py
71
app.py
@ -39,9 +39,10 @@ async def lifespan(application: FastAPI):
|
||||
except Exception as e:
|
||||
logger.error("Graph-Client konnte nicht initialisiert werden: %s", e)
|
||||
|
||||
# Backup-Verzeichnis erstellen
|
||||
# Verzeichnisse erstellen
|
||||
os.makedirs(BACKUP_DIR, exist_ok=True)
|
||||
os.makedirs(WLED_BACKUP_DIR, exist_ok=True)
|
||||
os.makedirs(FIRMWARE_DIR, exist_ok=True)
|
||||
|
||||
# Start background polling
|
||||
interval = int(database.get_setting("poll_interval", "15"))
|
||||
@ -61,6 +62,7 @@ async def lifespan(application: FastAPI):
|
||||
|
||||
BACKUP_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "backups")
|
||||
WLED_BACKUP_DIR = os.path.join(BACKUP_DIR, "wled")
|
||||
FIRMWARE_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "firmware")
|
||||
|
||||
|
||||
def auto_backup_db():
|
||||
@ -280,8 +282,15 @@ async def devices_page(request: Request):
|
||||
).fetchone()
|
||||
conn.close()
|
||||
last_check = last_check_row["lc"] if last_check_row and last_check_row["lc"] else None
|
||||
# Firmware files
|
||||
firmwares = []
|
||||
if os.path.exists(FIRMWARE_DIR):
|
||||
for f in sorted(os.listdir(FIRMWARE_DIR), reverse=True):
|
||||
if f.endswith(".bin"):
|
||||
size = os.path.getsize(os.path.join(FIRMWARE_DIR, f)) / 1024
|
||||
firmwares.append({"name": f, "size": f"{size:.0f} KB"})
|
||||
return templates.TemplateResponse(*_ctx(request, "devices",
|
||||
devices=devices, last_check=last_check))
|
||||
devices=devices, last_check=last_check, firmwares=firmwares))
|
||||
|
||||
|
||||
@app.post("/api/devices")
|
||||
@ -705,6 +714,64 @@ async def restore_wled_backup(filename: str, device_id: int = Form(...)):
|
||||
return RedirectResponse(f"/backup?restored={'1' if success else '0'}", status_code=303)
|
||||
|
||||
|
||||
# ── Firmware Update ─────────────────────────────────────────────────────────
|
||||
|
||||
@app.post("/api/firmware/upload")
|
||||
async def upload_firmware(firmware: UploadFile = File(...)):
|
||||
"""Upload a WLED firmware .bin file."""
|
||||
if not firmware.filename.endswith(".bin"):
|
||||
return RedirectResponse("/devices?fw_error=format", status_code=303)
|
||||
path = os.path.join(FIRMWARE_DIR, firmware.filename)
|
||||
with open(path, "wb") as f:
|
||||
content = await firmware.read()
|
||||
f.write(content)
|
||||
logger.info("Firmware hochgeladen: %s (%d KB)", firmware.filename, len(content) // 1024)
|
||||
return RedirectResponse("/devices?fw_uploaded=1", status_code=303)
|
||||
|
||||
|
||||
@app.post("/api/firmware/{device_id}/update")
|
||||
async def ota_update_device(device_id: int, firmware_file: str = Form(...)):
|
||||
"""OTA update a single WLED device. Backs up config first."""
|
||||
from wled_client import get_wled_config, ota_update_wled
|
||||
|
||||
conn = database.get_db()
|
||||
dev = conn.execute("SELECT hostname, name FROM wled_devices WHERE id=?", (device_id,)).fetchone()
|
||||
conn.close()
|
||||
if not dev:
|
||||
return RedirectResponse("/devices?fw_error=notfound", status_code=303)
|
||||
|
||||
fw_path = os.path.join(FIRMWARE_DIR, firmware_file)
|
||||
if not os.path.exists(fw_path) or ".." in firmware_file:
|
||||
return RedirectResponse("/devices?fw_error=nofile", status_code=303)
|
||||
|
||||
# Auto config backup before update
|
||||
config = get_wled_config(dev["hostname"])
|
||||
if config:
|
||||
ts = datetime.now().strftime("%Y%m%d_%H%M%S")
|
||||
safe_name = dev["hostname"].replace(".", "_")
|
||||
backup_path = os.path.join(WLED_BACKUP_DIR, f"{safe_name}_{ts}_pre_update.json")
|
||||
with open(backup_path, "w") as f:
|
||||
json.dump(config, f, indent=2)
|
||||
logger.info("Pre-Update Backup: %s", backup_path)
|
||||
|
||||
# Push firmware
|
||||
success, msg = ota_update_wled(dev["hostname"], fw_path)
|
||||
logger.info("OTA Update %s: %s - %s", dev["hostname"], "OK" if success else "FEHLER", msg)
|
||||
|
||||
if success:
|
||||
return RedirectResponse(f"/devices?fw_updated={dev['hostname']}", status_code=303)
|
||||
else:
|
||||
return RedirectResponse(f"/devices?fw_error=failed", status_code=303)
|
||||
|
||||
|
||||
@app.post("/api/firmware/{filename}/delete")
|
||||
async def delete_firmware(filename: str):
|
||||
path = os.path.join(FIRMWARE_DIR, filename)
|
||||
if os.path.exists(path) and ".." not in filename:
|
||||
os.remove(path)
|
||||
return RedirectResponse("/devices", status_code=303)
|
||||
|
||||
|
||||
# ── CLI Auth Command ───────────────────────────────────────────────────────
|
||||
|
||||
def cli_auth():
|
||||
|
||||
@ -16,6 +16,29 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{% if request.query_params.get('fw_uploaded') %}
|
||||
<div class="alert alert-success alert-dismissible fade show">
|
||||
<i class="bi bi-check-circle"></i> Firmware hochgeladen.
|
||||
<button type="button" class="btn-close" data-bs-dismiss="alert"></button>
|
||||
</div>
|
||||
{% endif %}
|
||||
{% if request.query_params.get('fw_updated') %}
|
||||
<div class="alert alert-success alert-dismissible fade show">
|
||||
<i class="bi bi-check-circle"></i> Update auf <strong>{{ request.query_params.get('fw_updated') }}</strong> gestartet. Geraet startet neu.
|
||||
<button type="button" class="btn-close" data-bs-dismiss="alert"></button>
|
||||
</div>
|
||||
{% endif %}
|
||||
{% if request.query_params.get('fw_error') %}
|
||||
<div class="alert alert-danger alert-dismissible fade show">
|
||||
<i class="bi bi-x-circle"></i>
|
||||
{% if request.query_params.get('fw_error') == 'format' %}Nur .bin Dateien erlaubt.
|
||||
{% elif request.query_params.get('fw_error') == 'nofile' %}Firmware-Datei nicht gefunden.
|
||||
{% elif request.query_params.get('fw_error') == 'failed' %}Update fehlgeschlagen. Config-Backup wurde erstellt.
|
||||
{% else %}Firmware-Fehler.{% endif %}
|
||||
<button type="button" class="btn-close" data-bs-dismiss="alert"></button>
|
||||
</div>
|
||||
{% endif %}
|
||||
|
||||
<div class="row g-4">
|
||||
<div class="col-lg-8">
|
||||
<div class="card">
|
||||
@ -64,6 +87,12 @@
|
||||
<i class="bi bi-wifi"></i>
|
||||
</button>
|
||||
</form>
|
||||
{% if firmwares %}
|
||||
<button class="btn btn-sm btn-outline-warning" title="Firmware Update"
|
||||
data-bs-toggle="modal" data-bs-target="#ota-{{ device.id }}">
|
||||
<i class="bi bi-cloud-arrow-up"></i>
|
||||
</button>
|
||||
{% endif %}
|
||||
<button class="btn btn-sm btn-outline-primary" data-bs-toggle="modal"
|
||||
data-bs-target="#edit-{{ device.id }}">
|
||||
<i class="bi bi-pencil"></i>
|
||||
@ -112,6 +141,40 @@
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<!-- OTA Update Modal -->
|
||||
{% if firmwares %}
|
||||
<div class="modal fade" id="ota-{{ device.id }}" tabindex="-1">
|
||||
<div class="modal-dialog">
|
||||
<div class="modal-content">
|
||||
<form method="post" action="/api/firmware/{{ device.id }}/update">
|
||||
<div class="modal-header">
|
||||
<h5 class="modal-title">Firmware Update</h5>
|
||||
<button type="button" class="btn-close" data-bs-dismiss="modal"></button>
|
||||
</div>
|
||||
<div class="modal-body">
|
||||
<p>Update fuer <strong>{{ device.name or device.hostname }}</strong></p>
|
||||
<p><small class="text-muted">Aktuelle Version: {{ device.version or 'unbekannt' }}</small></p>
|
||||
<div class="mb-3">
|
||||
<label class="form-label">Firmware waehlen</label>
|
||||
<select name="firmware_file" class="form-select">
|
||||
{% for fw in firmwares %}
|
||||
<option value="{{ fw.name }}">{{ fw.name }} ({{ fw.size }})</option>
|
||||
{% endfor %}
|
||||
</select>
|
||||
</div>
|
||||
<div class="alert alert-info mb-0">
|
||||
<small><i class="bi bi-info-circle"></i> Die Config wird vor dem Update automatisch gesichert. Das Tuerschild startet nach dem Update neu.</small>
|
||||
</div>
|
||||
</div>
|
||||
<div class="modal-footer">
|
||||
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Abbrechen</button>
|
||||
<button type="submit" class="btn btn-warning"><i class="bi bi-cloud-arrow-up"></i> Update starten</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{% endif %}
|
||||
{% endfor %}
|
||||
|
||||
{% if not devices %}
|
||||
@ -159,6 +222,39 @@
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Firmware Upload -->
|
||||
<div class="card mt-3">
|
||||
<div class="card-header">
|
||||
<h6 class="mb-0"><i class="bi bi-cloud-arrow-up"></i> Firmware</h6>
|
||||
</div>
|
||||
<div class="card-body">
|
||||
<form method="post" action="/api/firmware/upload" enctype="multipart/form-data">
|
||||
<div class="mb-3">
|
||||
<label class="form-label">WLED Firmware (.bin)</label>
|
||||
<input type="file" name="firmware" class="form-control form-control-sm" accept=".bin" required>
|
||||
</div>
|
||||
<button type="submit" class="btn btn-outline-primary btn-sm w-100">
|
||||
<i class="bi bi-upload"></i> Hochladen
|
||||
</button>
|
||||
</form>
|
||||
{% if firmwares %}
|
||||
<hr>
|
||||
<small class="text-muted d-block mb-2">Verfuegbare Firmwares:</small>
|
||||
{% for fw in firmwares %}
|
||||
<div class="d-flex justify-content-between align-items-center mb-1">
|
||||
<small class="font-monospace">{{ fw.name }} <span class="text-muted">({{ fw.size }})</span></small>
|
||||
<form method="post" action="/api/firmware/{{ fw.name }}/delete" class="d-inline"
|
||||
onsubmit="return confirm('Firmware loeschen?')">
|
||||
<button type="submit" class="btn btn-sm btn-outline-danger py-0">
|
||||
<i class="bi bi-trash"></i>
|
||||
</button>
|
||||
</form>
|
||||
</div>
|
||||
{% endfor %}
|
||||
{% endif %}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{% endblock %}
|
||||
|
||||
@ -69,3 +69,19 @@ def restore_wled_config(hostname, config_json):
|
||||
return r.status_code == 200, f"{r.status_code} {r.reason}"
|
||||
except requests.exceptions.RequestException as e:
|
||||
return False, str(e)
|
||||
|
||||
|
||||
def ota_update_wled(hostname, firmware_path):
|
||||
"""Push firmware binary to WLED device via OTA. Returns (success, message)."""
|
||||
try:
|
||||
with open(firmware_path, "rb") as f:
|
||||
r = requests.post(
|
||||
f"http://{hostname}/update",
|
||||
files={"update": ("firmware.bin", f, "application/octet-stream")},
|
||||
timeout=120,
|
||||
)
|
||||
if r.status_code == 200:
|
||||
return True, "Update erfolgreich, Geraet startet neu"
|
||||
return False, f"{r.status_code} {r.reason}"
|
||||
except requests.exceptions.RequestException as e:
|
||||
return False, str(e)
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user