160 lines
5.7 KiB
Python
160 lines
5.7 KiB
Python
"""
|
|
Firmware (OTA) API routes
|
|
|
|
Two surfaces share this module because they share one table:
|
|
/terminal/firmware/check - the terminal asks which image its board should run
|
|
/admin/firmware - an admin uploads / enables / removes images
|
|
|
|
The image itself is a plain static file under /upload/firmware/, served by the
|
|
StaticFiles mount (and proxied by nginx in production).
|
|
"""
|
|
import logging
|
|
from typing import List, Optional
|
|
|
|
from fastapi import APIRouter, Depends, File, Form, HTTPException, Query, UploadFile, status
|
|
from sqlalchemy.ext.asyncio import AsyncSession
|
|
|
|
from app.api.terminal import get_terminal_context, TerminalContext
|
|
from app.database import get_db
|
|
from app.models.db import FIRMWARE_BOARDS, FirmwareVersion, User
|
|
from app.models.schemas.terminal import (
|
|
FirmwareAdminItem,
|
|
FirmwareCheckResponse,
|
|
FirmwareEnabledUpdate,
|
|
)
|
|
from app.services import firmware_service
|
|
from app.services.auth_deps import require_admin
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
router = APIRouter(prefix="/terminal", tags=["terminal-ota"])
|
|
admin_router = APIRouter(prefix="/admin/firmware", tags=["firmware-admin"])
|
|
|
|
|
|
def _to_item(row: FirmwareVersion) -> FirmwareAdminItem:
|
|
return FirmwareAdminItem(
|
|
id=row.id,
|
|
version=row.version,
|
|
board=row.board,
|
|
path=row.file_path,
|
|
size=row.file_size,
|
|
sha256=row.sha256,
|
|
notes=row.notes,
|
|
enabled=row.enabled,
|
|
created_at=row.created_at,
|
|
)
|
|
|
|
|
|
@router.get("/firmware/check", response_model=FirmwareCheckResponse)
|
|
async def check_firmware(
|
|
board: str = Query(..., max_length=40, description="BOARD_NAME compiled into the firmware"),
|
|
current: Optional[str] = Query(None, max_length=32, description="Version the terminal runs now"),
|
|
ctx: TerminalContext = Depends(get_terminal_context),
|
|
db: AsyncSession = Depends(get_db),
|
|
) -> FirmwareCheckResponse:
|
|
"""Answer one terminal's update question and record what it reports it runs."""
|
|
known = ctx.device.board
|
|
if known and known != board:
|
|
# Flashing another panel's build leaves the device black-screened with only a
|
|
# serial reflash as a way back, so a board mismatch is refused outright.
|
|
logger.warning(
|
|
"device %s reports board '%s' but is registered as '%s'; refusing to serve firmware",
|
|
ctx.device.id,
|
|
board,
|
|
known,
|
|
)
|
|
raise HTTPException(
|
|
status_code=status.HTTP_409_CONFLICT,
|
|
detail="终端上报的板型与登记记录不一致,已拒绝下发固件",
|
|
)
|
|
|
|
if await firmware_service.record_report(db, ctx.device, board, current):
|
|
await db.commit()
|
|
|
|
target = await firmware_service.enabled_release(db, board)
|
|
if target is None or not firmware_service.needs_update(target.version, current):
|
|
return FirmwareCheckResponse(has_update=False)
|
|
|
|
moving_back = bool(current) and firmware_service.parse_version(
|
|
target.version
|
|
) < firmware_service.parse_version(current)
|
|
logger.info(
|
|
"firmware %s offered to %s (running %s, %s)",
|
|
target.version,
|
|
ctx.device.id,
|
|
current or "unknown",
|
|
"rollback" if moving_back else "upgrade",
|
|
)
|
|
return FirmwareCheckResponse(
|
|
has_update=True,
|
|
version=target.version,
|
|
path=target.file_path,
|
|
size=target.file_size,
|
|
sha256=target.sha256,
|
|
notes=target.notes,
|
|
)
|
|
|
|
|
|
@admin_router.get("", response_model=List[FirmwareAdminItem])
|
|
async def list_firmware(
|
|
_: User = Depends(require_admin),
|
|
db: AsyncSession = Depends(get_db),
|
|
) -> List[FirmwareAdminItem]:
|
|
rows = await firmware_service.list_packages(db)
|
|
return [_to_item(row) for row in rows]
|
|
|
|
|
|
@admin_router.post("", response_model=FirmwareAdminItem, status_code=status.HTTP_201_CREATED)
|
|
async def upload_firmware(
|
|
file: UploadFile = File(...),
|
|
board: str = Form(...),
|
|
version: str = Form(...),
|
|
notes: Optional[str] = Form(None),
|
|
_: User = Depends(require_admin),
|
|
db: AsyncSession = Depends(get_db),
|
|
) -> FirmwareAdminItem:
|
|
"""Upload one image. Files are immutable: use a new version number for a rebuild."""
|
|
if board not in FIRMWARE_BOARDS:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_400_BAD_REQUEST,
|
|
detail=f"未知板型 {board},可选:{', '.join(FIRMWARE_BOARDS)}",
|
|
)
|
|
try:
|
|
row = await firmware_service.store_package(
|
|
db, board=board, version=version, notes=notes, source=file
|
|
)
|
|
except firmware_service.FirmwareError as exc:
|
|
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(exc))
|
|
await db.commit()
|
|
return _to_item(row)
|
|
|
|
|
|
@admin_router.patch("/{pkg_id}", response_model=FirmwareAdminItem)
|
|
async def update_firmware(
|
|
pkg_id: int,
|
|
payload: FirmwareEnabledUpdate,
|
|
_: User = Depends(require_admin),
|
|
db: AsyncSession = Depends(get_db),
|
|
) -> FirmwareAdminItem:
|
|
"""Enable or disable a package; only enabled ones are ever offered to devices."""
|
|
row = await firmware_service.get_package(db, pkg_id)
|
|
if row is None:
|
|
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="固件记录不存在")
|
|
row.enabled = payload.enabled
|
|
await db.commit()
|
|
return _to_item(row)
|
|
|
|
|
|
@admin_router.delete("/{pkg_id}", status_code=status.HTTP_204_NO_CONTENT)
|
|
async def delete_firmware(
|
|
pkg_id: int,
|
|
_: User = Depends(require_admin),
|
|
db: AsyncSession = Depends(get_db),
|
|
) -> None:
|
|
row = await firmware_service.get_package(db, pkg_id)
|
|
if row is None:
|
|
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="固件记录不存在")
|
|
firmware_service.delete_file(row)
|
|
await db.delete(row)
|
|
await db.commit()
|