cosmo/backend/app/api/terminal.py

255 lines
9.7 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

"""
Terminal API routes - consumed by the ESP32-S3 terminal (no user session)
"""
import logging
from datetime import datetime
from typing import NamedTuple, Optional
from fastapi import APIRouter, Depends, HTTPException, Query, Request, Response, status
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
from sqlalchemy.ext.asyncio import AsyncSession
from app.database import get_db
from app.models.db import TerminalDevice, User
from app.models.schemas.terminal import (
PairCodeRequest,
PairCodeResponse,
PairStatusResponse,
TerminalFollowsResponse,
TerminalRocketDetail,
TerminalRocketsResponse,
)
from app.services import rocket_art
from app.services import firmware_service
from app.services.auth import decode_access_token
from app.services.terminal_icon import icon_file, render_rgb565
from app.services.terminal_service import PairingError, terminal_service
logger = logging.getLogger(__name__)
router = APIRouter(prefix="/terminal", tags=["terminal"])
# auto_error=False so a missing header answers 401 instead of FastAPI's default 403
bearer_scheme = HTTPBearer(auto_error=False)
class TerminalContext(NamedTuple):
user: User
device: TerminalDevice
async def get_terminal_context(
request: Request,
credentials: Optional[HTTPAuthorizationCredentials] = Depends(bearer_scheme),
db: AsyncSession = Depends(get_db),
) -> TerminalContext:
"""Authenticate a terminal: device scoped long lived JWT + still-bound device row."""
unauthorized = HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="终端令牌无效,请重新配对",
headers={"WWW-Authenticate": "Bearer"},
)
if credentials is None:
raise unauthorized
payload = decode_access_token(credentials.credentials)
if not payload or payload.get("typ") != "terminal":
raise unauthorized
user_id = payload.get("sub")
device_id = payload.get("did")
if not user_id or not device_id:
raise unauthorized
# The device row is the revocation list: unbinding clears it and kills the token.
device = await terminal_service.get_bound_device(db, device_id)
if device is None or device.user_id != int(user_id):
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="设备已解绑,请在终端上重新获取配对码",
headers={"WWW-Authenticate": "Bearer"},
)
# The row says the device is bound, the stamp says to *this* binding: without it a
# token leaked before an unbind would come back to life as soon as someone re-binds.
session = device.bound_at.isoformat() if device.bound_at else None
if session is None or payload.get("bnd") != session:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="终端令牌已失效,请在终端上重新获取配对码",
headers={"WWW-Authenticate": "Bearer"},
)
user = await db.get(User, int(user_id))
if user is None or not user.is_active:
raise unauthorized
# 固件在每次请求的头里自报版本和板型(见 terminal/firmware/.../api.cpp)。
# 挂在鉴权这一层,所有终端接口都会顺带更新,设备列表不用等到真查升级才有值。
if await firmware_service.record_report(db, device,
request.headers.get("X-Board"),
request.headers.get("X-FW-Version")):
await db.commit()
return TerminalContext(user=user, device=device)
@router.post("/pair/code", response_model=PairCodeResponse)
async def request_pair_code(
payload: PairCodeRequest,
db: AsyncSession = Depends(get_db),
):
"""
Ask for the 6 digit code to render on the terminal screen.
Idempotent: polling this endpoint keeps returning the same code until it expires.
An already bound device gets its owner back instead of a new code.
"""
try:
data = await terminal_service.issue_pairing_code(db, payload.device_id, payload.name)
except PairingError as exc:
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(exc))
return PairCodeResponse(**data)
@router.get("/pair/status", response_model=PairStatusResponse)
async def poll_pair_status(
device_id: str = Query(..., min_length=4, max_length=50),
code: str = Query(..., min_length=6, max_length=6),
db: AsyncSession = Depends(get_db),
):
"""Poll while the code is on screen. Returns the long lived token once the user binds."""
data = await terminal_service.get_pair_status(db, device_id, code)
return PairStatusResponse(**data)
@router.get("/follows", response_model=TerminalFollowsResponse)
async def get_followed_bodies(
ctx: TerminalContext = Depends(get_terminal_context),
db: AsyncSession = Depends(get_db),
):
"""Followed bodies of the owner, newest position and nearest events, compact for a TFT."""
ctx.device.last_seen_at = datetime.utcnow()
await db.commit()
bodies = await terminal_service.build_follow_snapshot(db, ctx.user.id)
return TerminalFollowsResponse(
username=ctx.user.username,
device_id=ctx.device.id,
server_time=datetime.utcnow(),
follow_count=len(bodies),
bodies=bodies,
)
#: the terminal blits fixed size bitmaps: 40x40 in the list, 64x64 on the detail page
ICON_SIZES = (40, 64)
@router.get("/bodies/{body_id}/icon")
async def get_body_icon(
body_id: str,
size: int = Query(64, description="Edge length in pixels: 40 (list) or 64 (detail)"),
ctx: TerminalContext = Depends(get_terminal_context),
db: AsyncSession = Depends(get_db),
):
"""
The icon maintained for one body in 平台管理 -> 天体信息, as flat big endian RGB565.
The terminal has no image decoder and no alpha channel: it additive blends the bitmap
onto the framebuffer, so the answer is the finished pixel blob (size * size * 2 bytes)
rendered with the same pipeline as terminal/tools/gen_assets.py. 404 when the body has
no icon - the terminal then keeps its built in line art.
"""
if size not in ICON_SIZES:
raise HTTPException(status_code=400, detail="size must be 40 or 64")
icon = await terminal_service.get_body_icon(db, body_id)
if icon is None:
raise HTTPException(status_code=404, detail="该天体没有维护图标")
path = icon_file(icon.file_path)
if path is None:
logger.warning(f"icon row {icon.id} points at a missing file: {icon.file_path}")
raise HTTPException(status_code=404, detail="图标文件不存在")
try:
blob = render_rgb565(path, size)
except Exception as exc: # corrupt / unsupported upload
logger.error(f"Cannot render icon {icon.file_path} for {body_id}: {exc}")
raise HTTPException(status_code=502, detail="图标文件无法解码")
return Response(
content=blob,
media_type="application/octet-stream",
# the resource id is the version the terminal caches on
headers={"ETag": str(icon.id)},
)
# ----------------------------------------------------------------------
# Rockets: 平台管理 -> 火箭型号 里启用的那些,所有人都看同一份
# ----------------------------------------------------------------------
@router.get("/rockets", response_model=TerminalRocketsResponse)
async def get_rockets(
ctx: TerminalContext = Depends(get_terminal_context),
db: AsyncSession = Depends(get_db),
):
"""Enabled launch vehicles with their upcoming launch count, compact for a TFT."""
ctx.device.last_seen_at = datetime.utcnow()
await db.commit()
rockets = await terminal_service.build_rocket_snapshot(db)
return TerminalRocketsResponse(
username=ctx.user.username,
device_id=ctx.device.id,
server_time=datetime.utcnow(),
rocket_count=len(rockets),
rockets=rockets,
)
@router.get("/rockets/{code}", response_model=TerminalRocketDetail)
async def get_rocket(
code: str,
ctx: TerminalContext = Depends(get_terminal_context),
db: AsyncSession = Depends(get_db),
):
"""Spec sheet of one rocket plus its nearest launches. 404 when disabled or unknown."""
ctx.device.last_seen_at = datetime.utcnow()
await db.commit()
rocket = await terminal_service.get_rocket(db, code)
if rocket is None:
raise HTTPException(status_code=404, detail="没有这个运载型号")
return rocket
@router.get("/rockets/{code}/art")
async def get_rocket_art(
code: str,
size: int = Query(64, description="Edge length in pixels: 40 (list) or 64 (detail)"),
ctx: TerminalContext = Depends(get_terminal_context),
db: AsyncSession = Depends(get_db),
):
"""
按火箭参数画出来的霓虹线稿立面图,裸 RGB565 大端点阵(size * size * 2 字节)。
和天体图标那条流水线同一套约定(纯黑底、无 alpha、终端叠加混合),区别只是
图不用人维护:参数即图形,ETag 是参数哈希,改身高/直径/助推器才会让终端重下。
"""
if size not in ICON_SIZES:
raise HTTPException(status_code=400, detail="size must be 40 or 64")
art = await terminal_service.get_rocket_art(db, code)
if art is None:
raise HTTPException(status_code=404, detail="没有这个运载型号")
art_ver, params = art
try:
blob = rocket_art.render_rgb565(params, size)
except Exception as exc: # 参数脏数据(缺 stage_1 之类)不该把终端拖成 500 循环
logger.error(f"Cannot draw rocket {code}: {exc}")
raise HTTPException(status_code=502, detail="火箭参数无法绘制")
return Response(content=blob, media_type="application/octet-stream", headers={"ETag": str(art_ver)})