添加了对esp32的支持

main
mula.liu 2026-10-07 21:02:00 +08:00
parent 25dfbd9a56
commit 654ab18a1f
87 changed files with 16335 additions and 292 deletions

BIN
.DS_Store vendored

Binary file not shown.

View File

@ -19,7 +19,7 @@ REDIS_MAX_CONNECTIONS=50
# Application Configuration
# ======================
# JWT Secret Key (IMPORTANT: Change this in production!)
JWT_SECRET_KEY=your-production-secret-key-change-this-to-random-string
JWT_SECRET_KEY=cosmo
# CORS - Support both internal IP access and external domain
# Format: comma-separated list of origins

View File

@ -0,0 +1,102 @@
"""
Device management API routes - logged in web user binds / lists / unbinds terminals
"""
import logging
from datetime import datetime, timedelta
from fastapi import APIRouter, Depends, HTTPException, status
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 DeviceBindRequest, DeviceResponse
from app.services.auth_deps import get_current_user
from app.services.redis_cache import redis_cache
from app.services.terminal_service import PairingError, terminal_service
logger = logging.getLogger(__name__)
router = APIRouter(prefix="/devices", tags=["devices"])
# A 6 digit code has 10^6 variants, so failed redemption attempts are capped per user.
BIND_WINDOW_SECONDS = 600
BIND_MAX_ATTEMPTS = 10
# 终端每 5 分钟拉一次订阅数据,在线判定窗口必须比它长,否则设备永远显示离线
ONLINE_WINDOW_SECONDS = 360
def _to_response(device: TerminalDevice) -> DeviceResponse:
online = bool(
device.last_seen_at
and datetime.utcnow() - device.last_seen_at < timedelta(seconds=ONLINE_WINDOW_SECONDS)
)
return DeviceResponse(
id=device.id,
name=device.name,
status=device.status,
bound_at=device.bound_at,
last_seen_at=device.last_seen_at,
online=online,
)
async def _ensure_bind_allowed(user_id: int) -> None:
"""Redis backed attempt counter, skipped when Redis is unavailable."""
client = redis_cache.client
if client is None:
return
key = f"terminal:bind_attempts:{user_id}"
attempts = await client.incr(key)
if attempts == 1:
await client.expire(key, BIND_WINDOW_SECONDS)
if attempts > BIND_MAX_ATTEMPTS:
raise HTTPException(
status_code=status.HTTP_429_TOO_MANY_REQUESTS,
detail=f"绑定尝试过多,请 {BIND_WINDOW_SECONDS // 60} 分钟后再试",
)
async def _reset_bind_attempts(user_id: int) -> None:
client = redis_cache.client
if client is not None:
await client.delete(f"terminal:bind_attempts:{user_id}")
@router.post("/bind", response_model=DeviceResponse)
async def bind_terminal(
payload: DeviceBindRequest,
current_user: User = Depends(get_current_user),
db: AsyncSession = Depends(get_db),
):
"""Bind a terminal by the 6 digit code displayed on its screen."""
await _ensure_bind_allowed(current_user.id)
try:
device = await terminal_service.bind_device(db, current_user.id, payload.code)
except PairingError as exc:
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(exc))
await _reset_bind_attempts(current_user.id)
return _to_response(device)
@router.get("", response_model=list[DeviceResponse])
async def list_terminals(
current_user: User = Depends(get_current_user),
db: AsyncSession = Depends(get_db),
):
"""Terminals bound to the current user."""
devices = await terminal_service.list_devices(db, current_user.id)
return [_to_response(device) for device in devices]
@router.delete("/{device_id}", status_code=status.HTTP_204_NO_CONTENT)
async def unbind_terminal(
device_id: str,
current_user: User = Depends(get_current_user),
db: AsyncSession = Depends(get_db),
):
"""Release a terminal. Its long lived token stops working immediately."""
removed = await terminal_service.unbind_device(db, current_user.id, device_id)
if not removed:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND, detail="未找到该设备或设备不属于当前账号"
)

View File

@ -31,6 +31,8 @@ async def follow_body(
try:
follow = await social_service.follow_body(current_user.id, body_id, db)
return follow
except HTTPException:
raise
except ValueError as e:
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(e))
except Exception as e:
@ -49,6 +51,8 @@ async def unfollow_body(
if not unfollowed:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Not following this body")
return None
except HTTPException:
raise
except Exception as e:
logger.error(f"Error unfollowing body {body_id} by user {current_user.id}: {e}")
raise HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail="Failed to unfollow body")

View File

@ -0,0 +1,174 @@
"""
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, 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,
)
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(
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
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)},
)

View File

@ -60,6 +60,10 @@ class Settings(BaseSettings):
redis_password: str = ""
redis_max_connections: int = 50
# Terminal (ESP32) device pairing settings
terminal_pair_code_ttl_seconds: int = 60 * 10 # pairing code validity
terminal_token_expire_days: int = 365 # long lived terminal token lifetime
# File upload settings
upload_dir: str = "upload"
max_upload_size: int = 10485760 # 10MB

View File

@ -35,6 +35,8 @@ from app.api.scheduled_job import router as scheduled_job_router
from app.api.social import router as social_router # Import social_router
from app.api.event import router as event_router # Import event_router
from app.api.rocket import router as rocket_router
from app.api.terminal import router as terminal_router
from app.api.device import router as device_router
from app.services.redis_cache import redis_cache
from app.services.cache_preheat import preheat_all_caches
from app.services.scheduler_service import scheduler_service
@ -190,6 +192,10 @@ app.include_router(social_router, prefix=settings.api_prefix)
app.include_router(event_router, prefix=settings.api_prefix) # Added event_router
app.include_router(rocket_router, prefix=settings.api_prefix)
# ESP32 terminal: pairing + device management
app.include_router(terminal_router, prefix=settings.api_prefix)
app.include_router(device_router, prefix=settings.api_prefix)
# Mount static files for uploaded resources
upload_dir = Path(__file__).parent.parent / "upload"
upload_dir.mkdir(exist_ok=True)

View File

@ -16,6 +16,7 @@ from .task import Task
from .user_follow import UserFollow
from .celestial_event import CelestialEvent
from .rocket import RocketConfig
from .terminal_device import TerminalDevice
__all__ = [
"CelestialBody",
@ -35,4 +36,5 @@ __all__ = [
"UserFollow",
"CelestialEvent",
"RocketConfig",
"TerminalDevice",
]

View File

@ -0,0 +1,60 @@
"""
TerminalDevice ORM model - ESP32 terminals paired with a user account
"""
from sqlalchemy import Column, String, Integer, TIMESTAMP, ForeignKey, Index, CheckConstraint
from sqlalchemy.sql import func
from sqlalchemy.orm import relationship
from app.database import Base
class TerminalDevice(Base):
"""
A physical terminal (ESP32-S3) that can be bound to exactly one user.
Pairing state machine:
pending - a 6 digit code was issued and can be redeemed by one user
bound - a user owns it, the code is expired and can no longer bind
"""
__tablename__ = "terminal_devices"
id = Column(String(50), primary_key=True, comment="Device id reported by the terminal")
name = Column(String(100), nullable=True, comment="Device name shown to the user")
user_id = Column(
Integer,
ForeignKey("users.id", ondelete="CASCADE"),
nullable=True,
comment="Owner, NULL when unbound",
)
status = Column(
String(20),
nullable=False,
default="pending",
comment="pending | bound",
)
pairing_code = Column(
String(6),
nullable=True,
unique=True,
comment="Last 6 digit pairing code (kept for audit after binding)",
)
code_expires_at = Column(TIMESTAMP, nullable=True, comment="Pairing code expiry (UTC)")
token_delivered_at = Column(
TIMESTAMP,
nullable=True,
comment="When the long lived terminal token was handed to the device",
)
bound_at = Column(TIMESTAMP, nullable=True)
last_seen_at = Column(TIMESTAMP, nullable=True, comment="Last poll from the device (UTC)")
created_at = Column(TIMESTAMP, server_default=func.now())
updated_at = Column(TIMESTAMP, server_default=func.now(), onupdate=func.now())
user = relationship("User")
__table_args__ = (
CheckConstraint("status IN ('pending', 'bound')", name="chk_terminal_device_status"),
Index("idx_terminal_devices_user", "user_id"),
)
def __repr__(self):
return f"<TerminalDevice(id='{self.id}', status='{self.status}', user_id={self.user_id})>"

View File

@ -0,0 +1,100 @@
"""
Pydantic schemas for ESP32 terminal pairing and terminal data delivery
"""
from datetime import datetime
from typing import List, Optional
from pydantic import BaseModel, Field
# --- Pairing (terminal -> backend, no auth) ---
class PairCodeRequest(BaseModel):
device_id: str = Field(
...,
pattern=r"^[A-Za-z0-9:_-]{4,50}$",
description="Stable device id reported by the terminal (e.g. ESP32-S3 MAC)",
)
name: Optional[str] = Field(None, max_length=100, description="Device display name")
class PairCodeResponse(BaseModel):
status: str = Field(..., description="pending = show the code, bound = already paired")
device_id: str
name: Optional[str] = None
code: Optional[str] = Field(None, description="6 digit code to render on the screen")
expires_in: Optional[int] = Field(None, description="Seconds the code stays redeemable")
username: Optional[str] = Field(None, description="Owner, only set when already bound")
class PairStatusResponse(BaseModel):
status: str = Field(
...,
description="pending | bound | expired | invalid_code | unknown | unbound",
)
username: Optional[str] = None
access_token: Optional[str] = Field(
None, description="Long lived terminal token, delivered once after binding"
)
expires_at: Optional[datetime] = None
expires_in: Optional[int] = Field(None, description="Seconds left for the pending code")
poll_interval: int = Field(2, description="Seconds the terminal should wait before polling again")
message: Optional[str] = None
# --- Device management (web -> backend, user auth) ---
class DeviceBindRequest(BaseModel):
code: str = Field(..., pattern=r"^[0-9]{6}$", description="6 digit code shown on the terminal")
class DeviceResponse(BaseModel):
id: str
name: Optional[str] = None
status: str
bound_at: Optional[datetime] = None
last_seen_at: Optional[datetime] = Field(None, description="Last time the device called the API")
online: bool = Field(False, description="Device polled within the last 6 minutes")
# --- Data snapshot (terminal -> backend, terminal token) ---
class TerminalPosition(BaseModel):
time: datetime = Field(..., description="Epoch of the stored position (UTC)")
x: float = Field(..., description="Heliocentric X in AU")
y: float
z: float
vx: Optional[float] = Field(None, description="km/s, NULL when not computed")
vy: Optional[float] = None
vz: Optional[float] = None
distance_au: float = Field(..., description="Distance from the sun in AU")
speed_km_s: Optional[float] = None
source: str
class TerminalEvent(BaseModel):
id: int
title: str
event_type: str
event_time: datetime
description: Optional[str] = None
is_upcoming: bool
class TerminalBody(BaseModel):
id: str
name: str
name_zh: Optional[str] = None
type: str
description: Optional[str] = None
is_active: Optional[bool] = None
icon_ver: Optional[int] = Field(
None,
description="Icon resource maintained in admin; 0/None = no icon, terminal keeps its built-in one",
)
position: Optional[TerminalPosition] = None
events: List[TerminalEvent] = []
class TerminalFollowsResponse(BaseModel):
username: str
device_id: str
server_time: datetime
follow_count: int
bodies: List[TerminalBody]

View File

@ -11,6 +11,7 @@ from sqlalchemy.orm import selectinload
from app.database import get_db
from app.models.db import User, Role
from app.services.auth import decode_access_token
from app.services.token_service import token_service
# HTTP Bearer token scheme
@ -38,6 +39,22 @@ async def get_current_user(
headers={"WWW-Authenticate": "Bearer"},
)
# Terminal tokens are long lived and device scoped: they must not unlock web/admin APIs.
if payload.get("typ") == "terminal":
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="Terminal token is not allowed for this endpoint",
)
# Logout blacklists the token; without this read the blacklist is decorative and a
# logged-out token keeps working until its natural expiry.
if await token_service.is_revoked(token):
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Token revoked",
headers={"WWW-Authenticate": "Bearer"},
)
# Get user ID from token
user_id: Optional[int] = payload.get("sub")
if user_id is None:

View File

@ -23,7 +23,7 @@ class SocialService:
# --- User Follows ---
async def follow_body(self, user_id: int, body_id: str, db: AsyncSession) -> UserFollow:
async def follow_body(self, user_id: int, body_id: str, db: AsyncSession) -> dict:
"""User follows a celestial body"""
# Check if already following
existing_follow = await self.get_follow(user_id, body_id, db)
@ -31,8 +31,9 @@ class SocialService:
raise ValueError("Already following this body")
# Check if body exists
body = await db.execute(select(CelestialBody).where(CelestialBody.id == body_id))
if not body.scalar_one_or_none():
body_result = await db.execute(select(CelestialBody).where(CelestialBody.id == body_id))
body = body_result.scalar_one_or_none()
if not body:
raise ValueError("Celestial body not found")
follow = UserFollow(user_id=user_id, body_id=body_id)
@ -40,7 +41,17 @@ class SocialService:
await db.commit()
await db.refresh(follow)
logger.info(f"User {user_id} followed body {body_id}")
return follow
# Response model needs the body details, same shape as get_user_follows_with_time
return {
"user_id": follow.user_id,
"body_id": follow.body_id,
"created_at": follow.created_at,
"id": body.id,
"name": body.name,
"name_zh": body.name_zh,
"type": body.type,
"is_active": body.is_active,
}
async def unfollow_body(self, user_id: int, body_id: str, db: AsyncSession) -> bool:
"""User unfollows a celestial body"""

View File

@ -0,0 +1,52 @@
"""把后台维护的天体图标渲染成 ESP32 直接可贴的 RGB565 裸点阵。
终端不解码图片、也不做 alpha:固件用"叠加混合"把不带 alpha 的 RGB565 贴到帧缓冲上,
黑色加上去等于没画,霓虹线稿自动发光。这和 terminal/tools/gen_assets.py 的内置图标
是同一套约定,所以这里必须和它保持同一条流水线:
亮度 bbox 裁切 -> 补方 -> LANCZOS 缩放 -> 黑底门限 -> RGB565(大端)。
改这里记得同步改 gen_assets.py 的 icon_pixels()。
"""
from array import array
from pathlib import Path
from typing import Optional
from PIL import Image
#: 与 backend/app/main.py 挂载 /upload 的目录一致(相对 backend/ 上传的 file_path 落在这里)
UPLOAD_ROOT = (Path(__file__).resolve().parent.parent.parent / "upload").resolve()
BBOX_LUMA = 40 # 亮度高于它的算"有墨",用来裁掉四周留白
BLACK_FLOOR = 10 # 亮度不高于它的直接归零,叠加混合时不落地
def icon_file(file_path: str) -> Optional[Path]:
"""resources.file_path(形如 icon/xxx.jpeg)-> 磁盘绝对路径,越界或不存在返回 None"""
root = UPLOAD_ROOT
candidate = (root / file_path).resolve()
if root not in candidate.parents or not candidate.is_file():
return None
return candidate
def render_rgb565(path: Path, size: int) -> bytes:
"""任意位图 -> size x size 的 RGB565 大端裸数据(size*size*2 字节)"""
with Image.open(path) as src:
ink = src.convert("L").point(lambda v: 255 if v > BBOX_LUMA else 0)
im = src.convert("RGB")
bbox = ink.getbbox()
if bbox:
im = im.crop(bbox)
w, h = im.size
side = max(w, h)
square = Image.new("RGB", (side, side), (0, 0, 0))
square.paste(im, ((side - w) // 2, (side - h) // 2))
square = square.resize((size, size), Image.LANCZOS)
out = array("H")
for r, g, b in square.getdata():
if (r * 299 + g * 587 + b * 114) // 1000 <= BLACK_FLOOR:
out.append(0)
else:
out.append(((r >> 3) << 11) | ((g >> 2) << 5) | (b >> 3))
out.byteswap() # 帧缓冲按大端存放
return out.tobytes()

View File

@ -0,0 +1,465 @@
"""
Terminal service - pairing codes, device binding and terminal data snapshots
Pairing flow (device code flow, RFC 8628 style):
1. terminal -> POST /terminal/pair/code : get a 6 digit code, show it on the TFT
2. user -> POST /devices/bind : redeem the code while logged in on the web
3. terminal -> GET /terminal/pair/status : polls until it receives a long lived token
4. terminal -> GET /terminal/follows : authenticated data pull
Binding is one atomic UPDATE, so concurrent redemption attempts can never both succeed:
the first one flips the row to 'bound' and every other attempt stops matching the WHERE
clause and gets rowcount = 0.
"""
import logging
import math
import secrets
from datetime import datetime, timedelta
from typing import List, Optional
from sqlalchemy import func, select, update
from sqlalchemy.dialects.postgresql import insert as pg_insert
from sqlalchemy.ext.asyncio import AsyncSession
from app.config import settings
from app.models.db import CelestialBody, Position, Resource, TerminalDevice, User, UserFollow
from app.models.db.celestial_event import CelestialEvent
from app.services.auth import create_access_token
logger = logging.getLogger(__name__)
STATUS_PENDING = "pending"
STATUS_BOUND = "bound"
class PairingError(Exception):
"""Pairing or binding was rejected. The message is safe to show to clients."""
class TerminalService:
"""Pairing, binding and the compact data snapshot served to terminals."""
# ------------------------------------------------------------------
# Pairing (device side, no auth)
# ------------------------------------------------------------------
async def issue_pairing_code(
self, db: AsyncSession, device_id: str, name: Optional[str] = None
) -> dict:
"""Issue (or refresh) the 6 digit pairing code of an unbound device."""
now = datetime.utcnow()
ttl = settings.terminal_pair_code_ttl_seconds
device = await self.get_device(db, device_id)
if device is not None:
if device.status == STATUS_BOUND:
# A bound terminal cannot re-pair on its own, the owner must unbind it first.
return await self._pairing_response(db, device)
# Keep a live code so a flaky terminal can retry without invalidating what
# is already on its screen while the user is typing it.
if device.pairing_code and device.code_expires_at and device.code_expires_at > now:
device.last_seen_at = now
await db.commit()
return await self._pairing_response(db, device)
code = await self._generate_code(db)
values = {
"id": device_id,
"name": name,
"status": STATUS_PENDING,
"user_id": None,
"pairing_code": code,
"code_expires_at": now + timedelta(seconds=ttl),
"token_delivered_at": None,
"bound_at": None,
"last_seen_at": now,
"created_at": now,
"updated_at": now,
}
stmt = pg_insert(TerminalDevice).values(**values)
stmt = stmt.on_conflict_do_update(
index_elements=[TerminalDevice.id],
set_={
"name": func.coalesce(stmt.excluded.name, TerminalDevice.name),
"status": STATUS_PENDING,
"user_id": None,
"pairing_code": code,
"code_expires_at": values["code_expires_at"],
"token_delivered_at": None,
"bound_at": None,
"last_seen_at": now,
"updated_at": now,
},
# Never overwrite a device that got bound while we were generating a code.
where=TerminalDevice.status != STATUS_BOUND,
)
await db.execute(stmt)
await db.commit()
# The upsert bypassed the ORM identity map, drop cached values before re-reading.
db.expire_all()
device = await self.get_device(db, device_id)
logger.info("Pairing code issued for terminal %s", device_id)
return await self._pairing_response(db, device)
async def get_pair_status(
self, db: AsyncSession, device_id: str, code: Optional[str] = None
) -> dict:
"""Handle one device poll. Hands out the long lived token exactly once."""
now = datetime.utcnow()
device = await self.get_device(db, device_id)
if device is None:
return {"status": "unknown", "message": "设备尚未申请配对码"}
if not code or code != device.pairing_code:
return {"status": "invalid_code"}
device.last_seen_at = now
if device.status == STATUS_BOUND:
user = await db.get(User, device.user_id) if device.user_id else None
if user is None:
await db.commit()
return {"status": "unbound"}
response = {"status": STATUS_BOUND, "username": user.username}
if device.token_delivered_at is None:
device.token_delivered_at = now
lifetime = timedelta(days=settings.terminal_token_expire_days)
response["access_token"] = self._create_terminal_token(device, user)
response["expires_at"] = now + lifetime
logger.info(
"Terminal token issued for device %s (user %s)", device_id, user.username
)
await db.commit()
return response
if device.code_expires_at is None or device.code_expires_at <= now:
await db.commit()
return {"status": "expired"}
await db.commit()
return {
"status": STATUS_PENDING,
"expires_in": max(0, int((device.code_expires_at - now).total_seconds())),
}
# ------------------------------------------------------------------
# Binding (user side, authenticated)
# ------------------------------------------------------------------
async def bind_device(self, db: AsyncSession, user_id: int, code: str) -> TerminalDevice:
"""Redeem a pairing code for the given user. Raises PairingError when rejected."""
now = datetime.utcnow()
# One atomic statement: exactly one concurrent caller can match this WHERE clause.
result = await db.execute(
update(TerminalDevice)
.where(
TerminalDevice.pairing_code == code,
TerminalDevice.status == STATUS_PENDING,
TerminalDevice.user_id.is_(None),
TerminalDevice.code_expires_at > now,
)
.values(
user_id=user_id,
status=STATUS_BOUND,
bound_at=now,
# Expire the code in the same statement so it can never bind twice.
code_expires_at=now,
token_delivered_at=None,
updated_at=now,
)
)
await db.commit()
if result.rowcount != 1:
raise PairingError("配对码无效、已过期或已被其他账号绑定")
device = (
await db.execute(
select(TerminalDevice).where(
TerminalDevice.pairing_code == code,
TerminalDevice.user_id == user_id,
TerminalDevice.status == STATUS_BOUND,
)
)
).scalar_one()
logger.info("Terminal %s bound to user %s", device.id, user_id)
return device
async def list_devices(self, db: AsyncSession, user_id: int) -> List[TerminalDevice]:
"""Devices bound to a user, most recently bound first."""
result = await db.execute(
select(TerminalDevice)
.where(TerminalDevice.user_id == user_id)
.order_by(TerminalDevice.bound_at.desc().nullslast())
)
return list(result.scalars().all())
async def unbind_device(self, db: AsyncSession, user_id: int, device_id: str) -> bool:
"""Release a device. Any token issued for it stops working immediately."""
now = datetime.utcnow()
result = await db.execute(
update(TerminalDevice)
.where(TerminalDevice.id == device_id, TerminalDevice.user_id == user_id)
.values(
user_id=None,
status=STATUS_PENDING,
pairing_code=None,
code_expires_at=None,
token_delivered_at=None,
bound_at=None,
updated_at=now,
)
)
await db.commit()
if result.rowcount > 0:
logger.info("Terminal %s unbound from user %s", device_id, user_id)
return True
return False
async def get_bound_device(self, db: AsyncSession, device_id: str) -> Optional[TerminalDevice]:
"""Device row only when it is still bound, used to validate terminal tokens."""
result = await db.execute(
select(TerminalDevice).where(
TerminalDevice.id == device_id,
TerminalDevice.status == STATUS_BOUND,
)
)
return result.scalar_one_or_none()
# ------------------------------------------------------------------
# Data snapshot for the terminal
# ------------------------------------------------------------------
async def build_follow_snapshot(self, db: AsyncSession, user_id: int) -> List[dict]:
"""Followed bodies with their newest known position and nearest events."""
follows = (
await db.execute(
select(CelestialBody)
.join(UserFollow, UserFollow.body_id == CelestialBody.id)
.where(UserFollow.user_id == user_id)
.order_by(UserFollow.created_at)
)
).scalars().all()
if not follows:
return []
body_ids = [body.id for body in follows]
positions = await self._latest_positions(db, body_ids)
events = await self._events_for(db, body_ids)
icons = await self._icons_for(db, body_ids)
snapshot = []
for body in follows:
events_for_body = events.get(body.id, [])
snapshot.append(
{
"id": body.id,
"name": body.name,
"name_zh": body.name_zh,
"type": body.type,
"description": body.description,
"is_active": body.is_active,
"position": positions.get(body.id),
"events": self._pick_events(events_for_body),
# the terminal caches the icon bitmap, so it only needs to know
# when the maintained icon changed (the resource id is that version)
"icon_ver": icons[body.id].id if body.id in icons else None,
}
)
return snapshot
#: positions.vx/vy/vz is only filled for stars, so for planets and spacecraft the
#: velocity is derived from the two newest samples when they are close in time.
_AU_IN_KM = 149_597_870.7
_MAX_VELOCITY_GAP_SECONDS = 7 * 86400
async def _latest_positions(self, db: AsyncSession, body_ids: List[str]) -> dict:
"""Newest stored position per body, keyed by body id."""
sample_no = (
func.row_number()
.over(partition_by=Position.body_id, order_by=Position.time.desc())
.label("sample_no")
)
samples = (
select(
Position.body_id,
Position.time,
Position.x,
Position.y,
Position.z,
Position.vx,
Position.vy,
Position.vz,
Position.source,
sample_no,
)
.where(Position.body_id.in_(body_ids))
.subquery()
)
result = await db.execute(
select(samples)
.where(samples.c.sample_no <= 2)
.order_by(samples.c.body_id, samples.c.sample_no)
)
latest: dict[str, list] = {}
for row in result:
latest.setdefault(row.body_id, []).append(row)
positions = {}
for body_id, rows in latest.items():
row = rows[0]
vx, vy, vz = row.vx, row.vy, row.vz
if vx is None and len(rows) > 1:
vx, vy, vz = self._derived_velocity(rows[0], rows[1])
velocity = (vx, vy, vz)
speed = (
round(math.sqrt(sum(v * v for v in velocity)), 3)
if all(v is not None for v in velocity)
else None
)
positions[body_id] = {
"time": row.time,
"x": row.x,
"y": row.y,
"z": row.z,
"vx": vx,
"vy": vy,
"vz": vz,
"distance_au": round(math.sqrt(row.x**2 + row.y**2 + row.z**2), 4),
"speed_km_s": speed,
"source": row.source,
}
return positions
@classmethod
def _derived_velocity(cls, latest, previous) -> tuple:
"""d(position)/dt in km/s from two samples. None when the gap is too wide to trust."""
gap = (latest.time - previous.time).total_seconds()
if not 0 < gap <= cls._MAX_VELOCITY_GAP_SECONDS:
return (None, None, None)
scale = cls._AU_IN_KM / gap
return (
round((latest.x - previous.x) * scale, 3),
round((latest.y - previous.y) * scale, 3),
round((latest.z - previous.z) * scale, 3),
)
async def get_body_icon(self, db: AsyncSession, body_id: str) -> Optional[Resource]:
"""The icon the admin maintains for one body, or None when it has none."""
return (await self._icons_for(db, [body_id])).get(body_id)
#: "icon" resources are uploaded from 平台管理 -> 天体信息 -> 资源配置.
#: Replacing an icon uploads a new row, so the newest one is the live icon and
#: its id doubles as the cache busting version the terminal compares against.
async def _icons_for(self, db: AsyncSession, body_ids: List[str]) -> dict:
"""Newest icon resource per body id, keyed by body id."""
if not body_ids:
return {}
result = await db.execute(
select(Resource)
.where(Resource.body_id.in_(body_ids), Resource.resource_type == "icon")
.order_by(Resource.body_id, Resource.created_at.desc(), Resource.id.desc())
.distinct(Resource.body_id)
)
return {row.body_id: row for row in result.scalars().all()}
async def _events_for(self, db: AsyncSession, body_ids: List[str]) -> dict:
"""All stored events of the given bodies, grouped by body id."""
result = await db.execute(
select(CelestialEvent)
.where(CelestialEvent.body_id.in_(body_ids))
.order_by(CelestialEvent.event_time)
)
grouped: dict[str, list] = {}
for event in result.scalars().all():
grouped.setdefault(event.body_id, []).append(event)
return grouped
@staticmethod
def _pick_events(events: List[CelestialEvent], limit: int = 3) -> List[dict]:
"""Upcoming events first, then the most recent past ones."""
now = datetime.utcnow()
upcoming = sorted((e for e in events if e.event_time >= now), key=lambda e: e.event_time)
past = sorted((e for e in events if e.event_time < now), key=lambda e: e.event_time, reverse=True)
picked = [(e, True) for e in upcoming[:limit]] + [(e, False) for e in past[:limit]]
return [
{
"id": event.id,
"title": event.title,
"event_type": event.event_type,
"event_time": event.event_time,
"description": event.description,
"is_upcoming": upcoming_flag,
}
for event, upcoming_flag in picked
]
# ------------------------------------------------------------------
# Helpers
# ------------------------------------------------------------------
async def get_device(self, db: AsyncSession, device_id: str) -> Optional[TerminalDevice]:
result = await db.execute(select(TerminalDevice).where(TerminalDevice.id == device_id))
return result.scalar_one_or_none()
async def _pairing_response(self, db: AsyncSession, device: TerminalDevice) -> dict:
"""Build the response of POST /terminal/pair/code from the stored row."""
now = datetime.utcnow()
if device.status == STATUS_BOUND:
user = await db.get(User, device.user_id) if device.user_id else None
return {
"status": STATUS_BOUND,
"device_id": device.id,
"name": device.name,
"code": None,
"expires_in": None,
"username": user.username if user else None,
}
remaining = (
max(0, int((device.code_expires_at - now).total_seconds()))
if device.code_expires_at
else None
)
return {
"status": STATUS_PENDING,
"device_id": device.id,
"name": device.name,
"code": device.pairing_code,
"expires_in": remaining,
"username": None,
}
async def _generate_code(self, db: AsyncSession) -> str:
"""Cryptographically random 6 digit code that is not in use right now."""
for _ in range(5):
code = f"{secrets.randbelow(1_000_000):06d}"
clash = (
await db.execute(
select(TerminalDevice.id).where(TerminalDevice.pairing_code == code).limit(1)
)
).scalar_one_or_none()
if clash is None:
return code
raise PairingError("配对码生成失败,请稍后重试")
@staticmethod
def _create_terminal_token(device: TerminalDevice, user: User) -> str:
"""Long lived JWT for a terminal, scoped to one user and one device."""
return create_access_token(
data={
"sub": str(user.id),
"username": user.username,
"typ": "terminal",
"did": device.id,
# Binding session stamp: unbind clears bound_at and every re-bind stamps a
# new one, so a token minted for an earlier binding stays dead for good.
"bnd": device.bound_at.isoformat(),
},
expires_delta=timedelta(days=settings.terminal_token_expire_days),
)
terminal_service = TerminalService()

View File

@ -39,6 +39,10 @@ class TokenService:
ttl_seconds=ttl_seconds
)
# Same-second re-login re-issues a byte-identical JWT (the payload is only
# sub/username/exp), so clear any earlier logout of that exact string first.
await redis_cache.delete(f"{self.blacklist_prefix}{token}")
# Track user's active tokens (for multi-device support)
user_tokens_key = f"{self.user_tokens_prefix}{user_id}"
# Add token to user's token set
@ -67,6 +71,16 @@ class TokenService:
return json.loads(data)
return None
async def is_revoked(self, token: str) -> bool:
"""
True when the token has been revoked and has not aged out of the blacklist yet.
Fails open by design: redis_cache.exists() answers False when Redis is down, so a
cache outage degrades to plain stateless JWT validation instead of locking out
every logged-in user.
"""
return await redis_cache.exists(f"{self.blacklist_prefix}{token}")
async def revoke_token(self, token: str) -> None:
"""
Revoke a token (logout)

Binary file not shown.

After

Width:  |  Height:  |  Size: 139 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 28 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 135 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 194 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 26 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 16 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 21 KiB

View File

@ -139,7 +139,9 @@ function App() {
);
const handleBodySelect = (body: CelestialBody | null) => {
setSelectedBody(body);
// 每次点击都视为一次新的聚焦事件:复制对象,保证重复点击同一个天体时
// selectedBody 的引用发生变化,信息面板与相机聚焦动画才会重新触发。
setSelectedBody(body ? { ...body } : null);
};
// Screenshot handler with auth check
@ -263,6 +265,7 @@ function App() {
resetTrigger={resetTrigger}
toast={toast}
onViewDetails={handleViewDetails}
user={user}
/>
{/* Timeline Controller */}

View File

@ -22,6 +22,7 @@ const Tasks = lazy(() => import('./pages/admin/Tasks').then((module) => ({ defau
const ScheduledJobs = lazy(() => import('./pages/admin/ScheduledJobs').then((module) => ({ default: module.ScheduledJobs })));
const UserProfile = lazy(() => import('./pages/admin/UserProfile').then((module) => ({ default: module.UserProfile })));
const MyCelestialBodies = lazy(() => import('./pages/admin/MyCelestialBodies').then((module) => ({ default: module.MyCelestialBodies })));
const MyDevices = lazy(() => import('./pages/admin/MyDevices').then((module) => ({ default: module.MyDevices })));
const Rockets = lazy(() => import('./pages/admin/Rockets').then((module) => ({ default: module.Rockets })));
function RouteFallback() {
@ -75,6 +76,7 @@ export function Router() {
>
<Route path="profile" element={<UserProfile />} />
<Route path="follow" element={<MyCelestialBodies />} />
<Route path="devices" element={<MyDevices />} />
{/* 修改密码已合并到个人资料页,旧链接重定向过去 */}
<Route path="change-password" element={<Navigate to="/user/profile" replace />} />
</Route>

View File

@ -67,7 +67,8 @@ export function CameraController({
}, [resetTrigger, camera, defaultPosition, controlsRef]); // Only run when resetTrigger changes
// Handle focus target changes
// Trigger only on the SELECTED body changing (by id), not on every new bodies array.
// Trigger only on the selection changing, not on every new bodies array.
// `focusTarget` gets a new object on every selection (even re-selecting the same body).
useEffect(() => {
const bodies = allBodiesRef.current;
if (focusTarget) {
@ -114,7 +115,7 @@ export function CameraController({
}
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [focusTarget?.id, camera, controlsRef, typeConfigs]);
}, [focusTarget, camera, controlsRef, typeConfigs]);
useFrame((_, delta) => {
const orbitControls = controlsRef.current;

View File

@ -0,0 +1,208 @@
import { useCallback, useEffect, useState } from 'react';
import { X, Cpu, RefreshCw, Trash2, MonitorSmartphone } from 'lucide-react';
import {
bindTerminalDevice,
fetchMyDevices,
unbindTerminalDevice,
type TerminalDevice,
} from '../utils/api';
import { useToast } from '../contexts/ToastContext';
interface DeviceBindingModalProps {
isOpen: boolean;
onClose: () => void;
}
function formatTime(value: string | null): string {
if (!value) return '--';
// 后端返回 UTC 时间但不带时区标记,补上 Z 才能正确转成本地时间
const date = new Date(value.endsWith('Z') ? value : `${value}Z`);
if (Number.isNaN(date.getTime())) return '--';
return date.toLocaleString();
}
function errorMessage(err: unknown, fallback: string): string {
const detail = (err as { response?: { data?: { detail?: unknown } } })?.response?.data?.detail;
if (typeof detail === 'string') return detail;
if (Array.isArray(detail) && detail.length > 0) return JSON.stringify(detail);
return fallback;
}
export function DeviceBindingModal({ isOpen, onClose }: DeviceBindingModalProps) {
const [code, setCode] = useState('');
const [devices, setDevices] = useState<TerminalDevice[]>([]);
const [loading, setLoading] = useState(false);
const [binding, setBinding] = useState(false);
const [error, setError] = useState<string | null>(null);
const [pendingUnbind, setPendingUnbind] = useState<string | null>(null);
const toast = useToast();
const loadDevices = useCallback(async () => {
setLoading(true);
try {
setDevices(await fetchMyDevices());
} catch (err) {
toast.error(errorMessage(err, '设备列表加载失败'));
} finally {
setLoading(false);
}
}, [toast]);
useEffect(() => {
if (isOpen) {
setCode('');
setError(null);
setPendingUnbind(null);
void loadDevices();
}
}, [isOpen, loadDevices]);
if (!isOpen) return null;
const handleBind = async (e: React.FormEvent) => {
e.preventDefault();
if (code.length !== 6) {
setError('请输入终端上显示的 6 位配对码');
return;
}
setBinding(true);
setError(null);
try {
const device = await bindTerminalDevice(code);
toast.success(`设备已绑定:${device.name || device.id}`);
setCode('');
await loadDevices();
} catch (err) {
setError(errorMessage(err, '绑定失败,请检查配对码是否正确'));
} finally {
setBinding(false);
}
};
const handleUnbind = async (deviceId: string) => {
try {
await unbindTerminalDevice(deviceId);
toast.success('设备已解绑,其终端令牌立即失效');
setPendingUnbind(null);
await loadDevices();
} catch (err) {
toast.error(errorMessage(err, '解绑失败'));
}
};
return (
<div className="fixed inset-0 z-[60] flex items-center justify-center p-4" onClick={onClose}>
<div className="absolute inset-0 bg-black/60 backdrop-blur-sm" />
<div
className="relative bg-black/40 backdrop-blur-md border border-[#238636] rounded-2xl w-full max-w-lg shadow-2xl shadow-[#238636]/20 overflow-hidden animate-in fade-in zoom-in-95 duration-200"
onClick={(e) => e.stopPropagation()}
>
<div className="relative p-6 pb-4 border-b border-white/10">
<button
onClick={onClose}
className="absolute top-4 right-4 text-gray-400 hover:text-white transition-colors"
>
<X size={20} />
</button>
<h2 className="text-xl font-bold text-white text-center flex items-center justify-center gap-2">
<MonitorSmartphone size={20} className="text-[#2ea043]" />
绑定终端设备
</h2>
<p className="text-gray-400 text-xs text-center mt-1">
输入 ESP32 终端屏幕上显示的 6 位配对码,绑定后终端自动同步你关注的天体
</p>
</div>
<form onSubmit={handleBind} className="p-6 pt-5 border-b border-white/10">
<div className="flex gap-3">
<input
value={code}
onChange={(e) => setCode(e.target.value.replace(/\D/g, '').slice(0, 6))}
placeholder="000000"
inputMode="numeric"
autoComplete="off"
className="flex-1 bg-black/50 border border-gray-700 rounded-lg px-4 py-3 text-white text-2xl tracking-[0.5em] text-center font-mono focus:outline-none focus:border-[#238636] transition-colors"
/>
<button
type="submit"
disabled={binding || code.length !== 6}
className="px-5 rounded-lg bg-[#238636] hover:bg-[#2ea043] disabled:opacity-40 disabled:cursor-not-allowed text-white font-medium transition-colors"
>
{binding ? '绑定中...' : '绑定'}
</button>
</div>
{error && <p className="mt-3 text-sm text-red-400">{error}</p>}
</form>
<div className="p-6 pt-4 max-h-[40vh] overflow-y-auto">
<div className="flex items-center justify-between mb-3">
<span className="text-sm text-gray-300">我的设备({devices.length})</span>
<button
onClick={() => void loadDevices()}
className="text-xs text-gray-400 hover:text-white flex items-center gap-1 transition-colors"
>
<RefreshCw size={13} className={loading ? 'animate-spin' : ''} />
刷新
</button>
</div>
{devices.length === 0 && !loading && (
<div className="text-center text-gray-500 text-sm py-6 border border-dashed border-white/10 rounded-lg">
<Cpu size={22} className="mx-auto mb-2 opacity-60" />
还没有绑定终端。在终端的配对页面获取 6 位配对码后输入即可。
</div>
)}
<ul className="space-y-2">
{devices.map((device) => (
<li
key={device.id}
className="flex items-center gap-3 bg-white/5 border border-white/10 rounded-lg px-3 py-2.5"
>
<span
className={`w-2 h-2 rounded-full flex-shrink-0 ${
device.online ? 'bg-green-400 shadow-[0_0_8px_rgba(74,222,128,0.8)]' : 'bg-gray-600'
}`}
/>
<div className="flex-1 min-w-0">
<p className="text-sm text-white truncate">
{device.name || '未命名终端'}
<span className="ml-2 text-[10px] text-gray-500 font-mono">{device.id}</span>
</p>
<p className="text-[11px] text-gray-500">
绑定于 {formatTime(device.bound_at)} · 最后同步 {formatTime(device.last_seen_at)}
</p>
</div>
{pendingUnbind === device.id ? (
<div className="flex gap-1">
<button
onClick={() => void handleUnbind(device.id)}
className="px-2 py-1 text-xs rounded bg-red-600/80 hover:bg-red-600 text-white transition-colors"
>
确认解绑
</button>
<button
onClick={() => setPendingUnbind(null)}
className="px-2 py-1 text-xs rounded bg-white/10 hover:bg-white/20 text-gray-200 transition-colors"
>
取消
</button>
</div>
) : (
<button
onClick={() => setPendingUnbind(device.id)}
className="p-2 text-gray-500 hover:text-red-400 transition-colors"
title="解绑设备"
>
<Trash2 size={15} />
</button>
)}
</li>
))}
</ul>
</div>
</div>
</div>
);
}

View File

@ -1,24 +1,66 @@
import { X, Ruler, Activity, Radar, Eye } from 'lucide-react';
import { useState } from 'react';
import { X, Ruler, Activity, Radar, Eye, Star } from 'lucide-react';
import { useState, useEffect } from 'react';
import { request } from '../utils/request';
import type { CelestialBody } from '../types';
import { TerminalModal } from './TerminalModal';
import type { ToastContextValue } from '../contexts/ToastContext'; // Import ToastContextValue type
import type { AuthUser } from '../utils/auth';
interface FocusInfoProps {
body: CelestialBody | null;
onClose: () => void;
toast: ToastContextValue; // Add toast prop
onViewDetails?: (body: CelestialBody) => void; // Add onViewDetails prop
user?: AuthUser | null; // 登录用户才能关注天体
}
export function FocusInfo({ body, onClose, toast, onViewDetails }: FocusInfoProps) {
export function FocusInfo({ body, onClose, toast, onViewDetails, user }: FocusInfoProps) {
const [showTerminal, setShowTerminal] = useState(false);
const [terminalData, setTerminalData] = useState('');
const [loading, setLoading] = useState(false);
const [followState, setFollowState] = useState<{ bodyId: string; following: boolean } | null>(null);
const [followBusy, setFollowBusy] = useState(false);
const bodyId = body?.id;
// 切换聚焦天体时刷新关注状态(未登录不请求)
useEffect(() => {
if (!user || !bodyId) return;
let active = true;
request.get<{ is_following: boolean }>(`/social/follows/check/${bodyId}`)
.then(({ data }) => {
if (active) setFollowState({ bodyId, following: !!data.is_following });
})
.catch((err) => {
console.error('Failed to check follow state:', err);
});
return () => { active = false; };
}, [user, bodyId]);
if (!body) return null;
const isFollowing = followState?.bodyId === body.id && followState.following;
const toggleFollow = async () => {
setFollowBusy(true);
const name = body.name_zh || body.name;
try {
if (isFollowing) {
await request.delete(`/social/follow/${body.id}`);
setFollowState({ bodyId: body.id, following: false });
toast.success(`已取消关注 ${name}`);
} else {
await request.post(`/social/follow/${body.id}`);
setFollowState({ bodyId: body.id, following: true });
toast.success(`已关注 ${name}`);
}
} catch (err) {
console.error(err);
toast.error(isFollowing ? '取消关注失败' : '关注失败');
} finally {
setFollowBusy(false);
}
};
// Calculate distance if position is available
const pos = body.positions[0];
const distance = pos ? Math.sqrt(pos.x ** 2 + pos.y ** 2 + pos.z ** 2).toFixed(2) : '---';
@ -126,6 +168,25 @@ export function FocusInfo({ body, onClose, toast, onViewDetails }: FocusInfoProp
</button>
</div>
{/* Follow / Unfollow (logged-in users only) */}
{user && (
<button
onClick={(e) => {
e.stopPropagation();
void toggleFollow();
}}
disabled={followBusy}
className={`w-full mb-2 px-3 py-2 rounded-lg border transition-all flex items-center justify-center gap-2 text-[10px] font-mono uppercase tracking-widest disabled:opacity-50 ${
isFollowing
? 'bg-yellow-500/10 text-yellow-300 border-yellow-500/40 hover:bg-red-500/10 hover:text-red-300 hover:border-red-500/40'
: 'bg-[#238636]/15 text-[#4ade80] border-[#238636]/40 hover:bg-[#238636]/30'
}`}
>
<Star size={14} fill={isFollowing ? 'currentColor' : 'none'} />
<span>{followBusy ? '同步中...' : isFollowing ? '取消关注' : '关注天体'}</span>
</button>
)}
{/* Conditional Probe Status Card (if isProbe is true, this goes in a new row) */}
{isProbe && (
<div className="grid grid-cols-1 mb-2">

View File

@ -20,6 +20,7 @@ import { AsteroidBelts } from './AsteroidBelts';
import { calculateRenderPosition } from '../utils/renderPosition';
import type { CelestialBody as CelestialBodyType, Position } from '../types';
import type { ToastContextValue } from '../contexts/ToastContext'; // Import ToastContextValue
import type { AuthUser } from '../utils/auth';
import { useSystemSetting } from '../hooks/useSystemSetting';
interface SceneProps {
@ -31,9 +32,10 @@ interface SceneProps {
resetTrigger?: number;
toast: ToastContextValue; // Add toast prop
onViewDetails?: (body: CelestialBodyType) => void; // Add prop
user?: AuthUser | null;
}
export function Scene({ bodies, selectedBody, trajectoryPositions = [], showOrbits = true, onBodySelect, resetTrigger = 0, toast, onViewDetails }: SceneProps) {
export function Scene({ bodies, selectedBody, trajectoryPositions = [], showOrbits = true, onBodySelect, resetTrigger = 0, toast, onViewDetails, user }: SceneProps) {
const [typeConfigs] = useSystemSetting('celestial_type_configs', null);
const [rawCameraPos] = useSystemSetting('default_camera_position', [10, 8, 10]);
const [rendererGeneration, setRendererGeneration] = useState(0);
@ -237,6 +239,7 @@ export function Scene({ bodies, selectedBody, trajectoryPositions = [], showOrbi
onClose={() => setShowInfoPanel(false)}
toast={toast}
onViewDetails={onViewDetails}
user={user}
/>
</Html>
)}

View File

@ -1,6 +1,8 @@
import { useState } from 'react';
import { User, LogOut, LayoutDashboard, LogIn } from 'lucide-react';
import { useCallback, useEffect, useState } from 'react';
import { User, LogOut, LayoutDashboard, LogIn, MonitorSmartphone } from 'lucide-react';
import type { AuthUser } from '../utils/auth';
import { fetchMyDevices, type TerminalDevice } from '../utils/api';
import { DeviceBindingModal } from './DeviceBindingModal';
interface UserAuthProps {
user: AuthUser | null | undefined;
@ -11,6 +13,23 @@ interface UserAuthProps {
export function UserAuth({ user, onOpenAuth, onLogout, onNavigateToAdmin }: UserAuthProps) {
const [showUserMenu, setShowUserMenu] = useState(false);
const [showDeviceBinding, setShowDeviceBinding] = useState(false);
const [devices, setDevices] = useState<TerminalDevice[] | null>(null);
// 菜单里直接显示绑定情况(也是解绑入口),每次展开菜单时向后端取一次
const loadDevices = useCallback(() => {
fetchMyDevices().then(setDevices).catch(() => setDevices(null));
}, []);
useEffect(() => {
if (showUserMenu) loadDevices();
}, [showUserMenu, loadDevices]);
const deviceSummary = devices === null
? '加载中...'
: devices.length === 0
? '尚未绑定终端'
: `已绑定 ${devices.length} 台 / ${devices.filter((d) => d.online).length} 台在线`;
if (!user) {
return (
@ -75,6 +94,20 @@ export function UserAuth({ user, onOpenAuth, onLogout, onNavigateToAdmin }: User
</div>
<div className="p-1">
<button
onClick={() => {
setShowDeviceBinding(true);
setShowUserMenu(false);
}}
className="w-full text-left px-3 py-2.5 text-sm text-gray-200 hover:bg-white/10 hover:text-white transition-colors rounded-lg"
>
<span className="flex items-center gap-3">
<MonitorSmartphone size={16} className="text-green-400" />
绑定终端设备
</span>
<span className="block pl-7 text-[10px] text-gray-500">{deviceSummary}</span>
</button>
<button
onClick={() => {
onNavigateToAdmin();
@ -101,6 +134,14 @@ export function UserAuth({ user, onOpenAuth, onLogout, onNavigateToAdmin }: User
</div>
</div>
)}
<DeviceBindingModal
isOpen={showDeviceBinding}
onClose={() => {
setShowDeviceBinding(false);
loadDevices();
}}
/>
</div>
);
}

View File

@ -0,0 +1,14 @@
/**
* 管理后台统一窗体(编辑 / 详情)
*
* 除统一垂直居中与「内容超高时窗体内部滚动」外,不改变 antd Modal 的任何行为:
* 窗体整体高度受视口约束,标题栏与底部按钮常驻,长表单的保存按钮不会被顶出屏幕。
* 具体高度与滚动样式在 admin.css 的「编辑窗体」一节,按 adm-modal 这个
* wrapper 类名作用于 antd 的 container / body 语义节点。
*/
import { Modal } from 'antd';
import type { ModalProps } from 'antd';
export function AdminModal(props: ModalProps) {
return <Modal centered {...props} classNames={{ wrapper: 'adm-modal' }} />;
}

View File

@ -40,6 +40,28 @@ export function AdminPage({ title, description, icon, meta, actions, children }:
);
}
/**
* 页面 Header 右侧的统计胶囊:各页面统一用它展示计数类信息。
*/
export function HeaderStat({
label,
value,
tone,
}: {
label: string;
value: ReactNode;
tone?: 'primary';
}) {
const { t } = useAdminPrefs();
return (
<span className={`adm-page-stat${tone ? ` adm-page-stat--${tone}` : ''}`}>
{t(label)}
<strong>{value}</strong>
</span>
);
}
/**
* 统计卡片:控制台等页面统一使用。
*/

View File

@ -1,4 +1,4 @@
import { createContext, useContext, useState, useCallback, useRef } from 'react';
import { createContext, useContext, useMemo, useState, useCallback, useRef } from 'react';
import type { ReactNode } from 'react';
import { X, CheckCircle, AlertCircle, AlertTriangle, Info } from 'lucide-react';
@ -91,8 +91,15 @@ export function ToastProvider({ children }: { children: React.ReactNode }) {
const warning = useCallback((msg: ReactNode, d = 3000, onClose?: () => void) => showToast(msg, 'warning', d, onClose), [showToast]);
const info = useCallback((msg: ReactNode, d?: number, onClose?: () => void) => showToast(msg, 'info', d, onClose), [showToast]);
// 稳定 context 引用:否则每次 Provider 重渲染都会生成新的 toast 对象,
// 让所有把 toast 写进依赖数组的页面在任意一次提示后重新拉取数据。
const value = useMemo<ToastContextValue>(
() => ({ showToast, success, error, warning, info, removeToast }),
[showToast, success, error, warning, info, removeToast],
);
return (
<ToastContext.Provider value={{ showToast, success, error, warning, info, removeToast }}>
<ToastContext.Provider value={value}>
{children}
{/* Toast Container - Top Right */}

View File

@ -74,7 +74,6 @@
display: none;
}
.sx-profile,
.sx-vehicle,
.sx-data {
background: var(--panel);
@ -405,22 +404,55 @@
text-align: center;
}
/* ---------- mission profile timeline ---------- */
/* ---------- mission timeline(时钟下方的任务剖面) ---------- */
.sx-profile-list {
padding: 7px 13px 9px;
.sx-timeline {
margin-top: 2px;
width: 100%;
max-width: 660px;
display: flex;
align-items: flex-start;
gap: 9px;
}
.sx-profile-row {
.sx-timeline-track {
position: relative;
height: 23px;
display: grid;
grid-template-columns: 13px 62px minmax(0, 1fr) 62px;
align-items: center;
gap: 6px;
flex: 1 1 auto;
height: 52px;
}
.sx-profile-row i {
/* 进度线:填充宽度就是已完成里程碑占比,右端停在最近一个节点之后 */
.sx-timeline-line {
position: absolute;
left: 0;
right: 0;
top: 18px;
height: 3px;
overflow: hidden;
border-radius: 2px;
background: #232829;
}
.sx-timeline-line i {
display: block;
height: 100%;
background: linear-gradient(90deg, var(--green-dim), var(--green-bright));
box-shadow: 0 0 8px rgba(53, 208, 127, 0.7);
transition: width 300ms linear;
}
/* 节点是零尺寸锚点:圆点压在进度线上,代号在上方、中文名与时间戳在下方 */
.sx-timeline-node {
position: absolute;
top: 19.5px;
width: 0;
height: 0;
}
.sx-timeline-node em {
position: absolute;
left: -3.5px;
top: -3.5px;
width: 7px;
height: 7px;
border: 1.5px solid #4a5250;
@ -428,50 +460,76 @@
background: #141718;
}
.sx-profile-row b {
.sx-timeline-node b {
position: absolute;
left: 0;
bottom: 8px;
transform: translateX(-50%);
color: #6d7573;
font-size: 9px;
font-size: 8px;
font-weight: 750;
letter-spacing: 0.06em;
white-space: nowrap;
font-variant-numeric: tabular-nums;
}
.sx-profile-row span {
overflow: hidden;
.sx-timeline-node > span {
position: absolute;
left: 0;
top: 8px;
transform: translateX(-50%);
color: #565e5c;
font-size: 9.5px;
text-overflow: ellipsis;
font-size: 9px;
white-space: nowrap;
}
.sx-profile-row time {
.sx-timeline-node time {
position: absolute;
left: 0;
top: 20px;
transform: translateX(-50%);
color: #4c5452;
font-size: 9.5px;
font-variant-numeric: tabular-nums;
text-align: right;
font-size: 8.5px;
white-space: nowrap;
font-family: var(--mono);
font-variant-numeric: tabular-nums;
}
.sx-profile-row.reached i {
.sx-timeline-node.reached em {
border-color: #9be8c0;
background: var(--green);
box-shadow: 0 0 6px rgba(53, 208, 127, 0.55);
}
.sx-profile-row.reached b { color: #c9f2dc; }
.sx-profile-row.reached span { color: #8fb6a3; }
.sx-profile-row.reached time { color: var(--green-bright); }
.sx-timeline-node.reached b { color: #c9f2dc; }
.sx-timeline-node.reached > span { color: #8fb6a3; }
.sx-timeline-node.reached time { color: var(--green-bright); }
.sx-profile-row.next i {
.sx-timeline-node.next em {
border-color: #ffe2a0;
background: var(--amber);
box-shadow: 0 0 6px rgba(245, 196, 81, 0.6);
animation: sxPulse 1s ease-in-out infinite;
}
.sx-profile-row.next b { color: #f4d391; }
.sx-profile-row.next span { color: #e9d7ae; }
.sx-profile-row.next time { color: #d9c99a; }
.sx-timeline-node.next b { color: #f4d391; }
.sx-timeline-node.next > span { color: #e9d7ae; }
.sx-timeline-node.next time { color: #d9c99a; }
.sx-timeline-node > span,
.sx-timeline-node time {
transition: color 200ms linear;
}
.sx-timeline-pct {
flex: 0 0 34px;
padding-top: 13px;
color: var(--green-bright);
font-size: 10px;
font-family: var(--mono);
font-variant-numeric: tabular-nums;
text-align: right;
}
/* ---------- vehicle stack diagram ---------- */
@ -994,40 +1052,6 @@
letter-spacing: 0.14em;
}
.sx-progress {
margin-top: 5px;
width: 100%;
max-width: 420px;
display: flex;
align-items: center;
gap: 9px;
}
.sx-progress-track {
flex: 1 1 auto;
height: 3px;
overflow: hidden;
border-radius: 2px;
background: #232829;
}
.sx-progress-track i {
display: block;
height: 100%;
background: linear-gradient(90deg, var(--green-dim), var(--green-bright));
box-shadow: 0 0 8px rgba(53, 208, 127, 0.7);
transition: width 300ms linear;
}
.sx-progress > span {
flex: 0 0 34px;
color: var(--green-bright);
font-size: 10px;
font-family: var(--mono);
font-variant-numeric: tabular-nums;
text-align: right;
}
.sx-bottom-right {
flex: 0 0 auto;
display: flex;
@ -1245,6 +1269,10 @@
.sx-select:not(.sx-select--speed) { width: 240px; }
.sx-left { display: none; }
.sx-bottom-right .sx-engine-gauge { display: none; }
.sx-timeline-track { height: 32px; }
.sx-timeline-node > span,
.sx-timeline-node time { display: none; }
}
@media (max-width: 760px) {
@ -1309,7 +1337,9 @@
.sx-clock { font-size: 26px; }
.sx-realtime { font-size: 7px; letter-spacing: 0.08em; }
.sx-progress { max-width: 220px; }
.sx-timeline { max-width: 220px; }
.sx-timeline-track { height: 12px; }
.sx-timeline-node b { display: none; }
.sx-bottom-right { gap: 9px; }
.sx-attitude-gauge { display: none; }
@ -1325,8 +1355,8 @@
@media (max-height: 720px) {
.sx-left,
.sx-right { top: 68px; }
.sx-profile-list { padding-top: 4px; padding-bottom: 6px; }
.sx-profile-row { height: 20px; }
.sx-timeline-track { height: 40px; }
.sx-timeline-node time { display: none; }
.sx-vehicle-body { padding-top: 7px; padding-bottom: 8px; }
.sx-data { padding-bottom: 9px; }
.sx-data-row { min-height: 26px; }

View File

@ -243,39 +243,50 @@ function VehiclePanel({ rocket, mode, stage1FuelPct, stage2FuelPct }: { rocket:
}
/* ------------------------------------------------------------------ */
/* Mission profile timeline (SpaceX webcast style) */
/* Mission timeline: the mission clock progress bar IS the mission */
/* profile — every phase sits on the bar at its own node, so the */
/* progress readout and the phase list can never drift apart. */
/* ------------------------------------------------------------------ */
function MissionProfile({
function MissionTimeline({
events,
next,
running,
milestones,
progress,
}: {
events: FlightEvent[];
next?: { id: string; code: string; label: string };
running: boolean;
milestones: Array<{ id: string; code: string; label: string }>;
progress: number;
}) {
const eventTime = (id: string) => events.find((event) => event.id === id)?.time ?? null;
return (
<div className="sx-profile">
<div className="sx-panel-title"><span>MISSION PROFILE</span><b>任务剖面</b></div>
<div className="sx-profile-list">
{milestones.map((m) => {
<div className="sx-timeline">
<div className="sx-timeline-track">
<div className="sx-timeline-line"><i style={{ width: `${progress}%` }} /></div>
{milestones.map((m, index) => {
const time = eventTime(m.id);
const reached = time !== null;
const isNext = next?.id === m.id && running;
const at = `${((index + 0.5) / milestones.length) * 100}%`;
return (
<div key={m.id} className={`sx-profile-row ${reached ? 'reached' : ''} ${isNext ? 'next' : ''}`}>
<i />
<span
key={m.id}
className={`sx-timeline-node ${reached ? 'reached' : ''} ${isNext ? 'next' : ''}`}
style={{ left: at }}
title={`${m.code} ${m.label} · ${reached ? formatTime(time as number).replace('T+', '+') : '待执行'}`}
>
<em />
<b>{m.code}</b>
<span>{m.label}</span>
<time>{reached ? formatTime(time as number).replace('T+', '+') : '--:--'}</time>
</div>
</span>
);
})}
</div>
<span className="sx-timeline-pct">{progress.toFixed(0)}%</span>
</div>
);
}
@ -481,7 +492,6 @@ function RocketMission({ rockets }: { rockets: RocketConfig[] }) {
{/* Left: mission profile + vehicle stack */}
<aside className="sx-left">
<MissionProfile events={state.events} next={nextMilestone} running={state.isRunning} milestones={milestones} />
<VehiclePanel rocket={rocket} mode={stackMode} stage1FuelPct={stage1FuelPct} stage2FuelPct={stage2FuelPct} />
</aside>
@ -508,10 +518,13 @@ function RocketMission({ rockets }: { rockets: RocketConfig[] }) {
<div className="sx-bottom-center">
<div className="sx-clock">{clockText}</div>
<div className="sx-realtime"><Clock3 size={12} />MISSION TIME · REAL TIME</div>
<div className="sx-progress">
<div className="sx-progress-track"><i style={{ width: `${progress}%` }} /></div>
<span>{progress.toFixed(0)}%</span>
</div>
<MissionTimeline
events={state.events}
next={nextMilestone}
running={state.isRunning}
milestones={milestones}
progress={progress}
/>
</div>
<div className="sx-bottom-right">

View File

@ -5,12 +5,13 @@
* 右侧内容区(顶部只有语言与明暗开关,页面信息统一由页面自己的 Header 卡片承载)。
* 管理员与普通用户共用同一套布局。
*/
import { useCallback, useEffect, useMemo, useState } from 'react';
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { Outlet, useLocation, useNavigate } from 'react-router-dom';
import { Avatar, ConfigProvider, Layout, Menu, Popover, Spin } from 'antd';
import zhCN from 'antd/locale/zh_CN';
import enUS from 'antd/locale/en_US';
import {
ApiOutlined,
CalendarOutlined,
ClockCircleOutlined,
ControlOutlined,
@ -67,6 +68,7 @@ const iconMap: Record<string, React.ReactNode> = {
star: <StarOutlined />,
rocket: <RocketOutlined />,
schedule: <ScheduleOutlined />,
device: <ApiOutlined />,
// 后端菜单里也直接存了组件名,这里一并兼容
DashboardOutlined: <DashboardOutlined />,
DatabaseOutlined: <DatabaseOutlined />,
@ -96,6 +98,9 @@ function AdminShell() {
const [loadingMenus, setLoadingMenus] = useState(true);
const [userMenuOpen, setUserMenuOpen] = useState(false);
const [user, setUser] = useState(() => auth.getUser());
// 退出登录时路由更新走 startTransition,页面会比跳转先渲染一次,
// 用它挡掉这段时间里的菜单请求与失败提示。
const loggingOutRef = useRef(false);
const navigate = useNavigate();
const location = useLocation();
const toast = useToast();
@ -116,15 +121,21 @@ function AdminShell() {
}, []);
const loadMenus = useCallback(async () => {
if (loggingOutRef.current || !auth.isLoggedIn()) {
setLoadingMenus(false);
return;
}
setLoadingMenus(true);
try {
const { data } = await authAPI.getMenus();
if (loggingOutRef.current) return;
setMenus(Array.isArray(data) ? data : []);
} catch {
if (loggingOutRef.current) return;
setMenus([]);
toast.error('加载菜单失败');
} finally {
setLoadingMenus(false);
if (!loggingOutRef.current) setLoadingMenus(false);
}
}, [toast]);
@ -174,14 +185,15 @@ function AdminShell() {
const handleLogout = useCallback(async () => {
setUserMenuOpen(false);
loggingOutRef.current = true;
try {
await authAPI.logout();
} catch {
// 后端不可用时也要清理本地登录态。
}
auth.logout();
toast.success('已退出登录');
navigate('/login', { replace: true });
toast.success('已退出登录');
}, [navigate, toast]);
const go = (path: string) => {
@ -206,7 +218,7 @@ function AdminShell() {
<button type="button" className="adm-user-menu-item" onClick={() => go('/')}>
<HomeOutlined />
{t('返回可视化首页')}
{t('返回首页')}
</button>
<div className="adm-user-menu-divider" />
<button type="button" className="adm-user-menu-item is-danger" onClick={() => void handleLogout()}>

View File

@ -44,6 +44,22 @@ export function AdminPrefsProvider({ children }: { children: ReactNode }) {
localStorage.setItem(STORAGE_KEY, JSON.stringify(prefs));
}, [prefs]);
/*
* Popover / Modal / Select 面板等弹层挂在 body 下,只能从 <html> 继承 CSS 变量。
* 主题只写在 .adm-shell 上的话,深色模式的弹层仍会读到浅色变量(重点色、底色全错),
* 所以这里把主题同步镜像到根元素,离开管理端时再摘掉。
*/
useEffect(() => {
document.documentElement.dataset.admTheme = prefs.themeMode;
}, [prefs.themeMode]);
useEffect(
() => () => {
delete document.documentElement.dataset.admTheme;
},
[],
);
const setLang = useCallback((lang: AdminLang) => setPrefs((current) => ({ ...current, lang })), []);
const setThemeMode = useCallback(
(themeMode: AdminThemeMode) => setPrefs((current) => ({ ...current, themeMode })),

View File

@ -51,6 +51,8 @@ export function CelestialBodies() {
const [refreshResources, setRefreshResources] = useState(0);
const [form] = Form.useForm();
const toast = useToast();
// 静态 Modal.warning 在 ConfigProvider 之外渲染,深色模式会退回浅色主题,改用带上下文的实例。
const [modal, modalContextHolder] = Modal.useModal();
const filteredData = useMemo(() => filterBodies(data, keyword), [data, keyword]);
@ -118,14 +120,14 @@ export function CelestialBodies() {
const existingBody = data.find((body) => body.id === result.data.id);
if (existingBody) {
Modal.warning({
modal.warning({
title: '天体已存在',
content: (
<div>
<p>找到天体: <strong>{result.data.full_name}</strong></p>
<p>ID: <strong>{result.data.id}</strong></p>
<p style={{ color: '#faad14', marginTop: 10 }}>该天体已在数据库中,名称为: <strong>{existingBody.name}</strong></p>
<p style={{ fontSize: 12, color: '#888' }}>如需修改,请在列表中直接编辑该天体。</p>
<p style={{ color: 'var(--adm-warning)', marginTop: 10 }}>该天体已在数据库中,名称为: <strong>{existingBody.name}</strong></p>
<p style={{ fontSize: 12, color: 'var(--adm-text-muted)' }}>如需修改,请在列表中直接编辑该天体。</p>
</div>
),
});
@ -136,14 +138,14 @@ export function CelestialBodies() {
if (/^-?\d+$/.test(result.data.id)) {
toast.success(`找到天体: ${result.data.full_name}`);
} else {
Modal.warning({
modal.warning({
title: '找到天体,但请确认 ID',
content: (
<div>
<p>找到天体: <strong>{result.data.full_name}</strong></p>
<p>自动填充的 ID 为: <strong>{result.data.id}</strong></p>
<p style={{ color: '#faad14' }}>建议手动确认数字 ID,以便后续查询位置数据。</p>
<p style={{ fontSize: 12, color: '#888' }}>
<p style={{ color: 'var(--adm-warning)' }}>建议手动确认数字 ID,以便后续查询位置数据。</p>
<p style={{ fontSize: 12, color: 'var(--adm-text-muted)' }}>
可在 <a href="https://ssd.jpl.nasa.gov/horizons/" target="_blank" rel="noopener noreferrer">NASA Horizons</a> 查询准确 ID。
</p>
</div>
@ -307,6 +309,7 @@ export function CelestialBodies() {
<AdminPage
icon={<GlobalOutlined />}
title="天体数据管理" description="按恒星系统维护天体基础信息、显示资源与轨道数据">
{modalContextHolder}
<DataTable
columns={columns}
dataSource={filteredData}
@ -327,7 +330,7 @@ export function CelestialBodies() {
pageSize={systemPageSize}
toolbar={
<Space size={8}>
<StarOutlined style={{ color: 'var(--adm-primary)' }} />
<StarOutlined style={{ color: 'var(--adm-primary-text)' }} />
<Select
showSearch
style={{ width: 260 }}

View File

@ -9,6 +9,7 @@ import { ReloadOutlined, RocketOutlined, StarFilled, StarOutlined } from '@ant-d
import type { ColumnsType } from 'antd/es/table';
import { request } from '../../utils/request';
import { fetchBodyResources } from '../../utils/api';
import { useToast } from '../../contexts/ToastContext';
import { AdminPage } from '../../components/admin/AdminPage';
@ -18,6 +19,8 @@ interface FollowedBody {
name_zh?: string | null;
type: string;
is_active: boolean;
/** 后端关注记录里的关注时间 */
created_at?: string;
followed_at?: string;
}
@ -68,6 +71,64 @@ const EVENT_TYPE_COLORS: Record<string, string> = {
transit: 'green',
};
/** 没有贴图时的兜底:按天体类型画一颗星球,列表里始终不出现文字。 */
const BODY_THUMB_FALLBACKS: Record<string, string> = {
star: 'radial-gradient(circle at 32% 30%, #f2e2b0, #b3924f 58%, #57431d)',
planet: 'radial-gradient(circle at 32% 30%, #bcccd9, #5d7f9e 58%, #223b52)',
dwarf_planet: 'radial-gradient(circle at 32% 30%, #c5d9dc, #5d97a1 58%, #204a52)',
satellite: 'radial-gradient(circle at 32% 30%, #dae0e6, #8892a0 58%, #3a434f)',
comet: 'radial-gradient(circle at 32% 30%, #d9d1e3, #7f7499 58%, #38314d)',
asteroid: 'radial-gradient(circle at 32% 30%, #ded1c5, #9a7f6a 58%, #453529)',
probe: 'radial-gradient(circle at 32% 30%, #d7dce1, #7e8a95 58%, #364048)',
};
/** 关注列表里的天体图像,与 3D 场景取同一张 surface 贴图。 */
function BodyTextureThumb({ bodyId, bodyType }: { bodyId: string; bodyType: string }) {
const [thumb, setThumb] = useState<{ bodyId: string; src: string | null } | null>(null);
useEffect(() => {
let active = true;
fetchBodyResources(bodyId, 'texture')
.then(({ resources }) => {
if (!active) return;
const surface = resources.find(
(resource) =>
!resource.extra_data?.layer ||
resource.extra_data.layer === 'surface' ||
resource.extra_data.layer === 'base',
);
setThumb({ bodyId, src: surface ? `/upload/${surface.file_path}` : null });
})
.catch(() => {
if (active) setThumb({ bodyId, src: null });
});
return () => {
active = false;
};
}, [bodyId]);
// 只认当前天体的贴图结果,切换选中时先显示占位星球。
const src = thumb?.bodyId === bodyId ? thumb.src : null;
if (!src) {
return (
<span
className="adm-body-thumb adm-body-thumb--fallback"
style={{ background: BODY_THUMB_FALLBACKS[bodyType] || BODY_THUMB_FALLBACKS.satellite }}
/>
);
}
return (
<img
className="adm-body-thumb"
src={src}
alt=""
draggable={false}
onError={() => setThumb({ bodyId, src: null })}
/>
);
}
export function MyCelestialBodies() {
const [loading, setLoading] = useState(false);
const [bodies, setBodies] = useState<FollowedBody[]>([]);
@ -93,7 +154,7 @@ export function MyCelestialBodies() {
setLoading(true);
try {
const { data } = await request.get<FollowedBody[]>('/social/follows');
const list = data || [];
const list = (data || []).map((item) => ({ ...item, followed_at: item.followed_at ?? item.created_at }));
setBodies(list);
if (list.length > 0) {
const next = list.find((item) => item.id === selectedBody?.id) ?? list[0];
@ -185,39 +246,19 @@ export function MyCelestialBodies() {
<div className="adm-cell-sub">在可视化首页点击天体,进入详情后即可关注</div>
</Empty>
) : (
<div className="adm-list">
<div className="adm-body-grid">
{bodies.map((body) => (
<div
<button
key={body.id}
className={`adm-list-item ${selectedBody?.id === body.id ? 'is-selected' : ''}`}
type="button"
className={`adm-body-tile ${selectedBody?.id === body.id ? 'is-selected' : ''}`}
title={body.name_zh || body.name}
aria-label={body.name_zh || body.name}
aria-pressed={selectedBody?.id === body.id}
onClick={() => void handleSelectBody(body)}
>
<StarFilled style={{ color: '#d4a72c', fontSize: 18 }} />
<div className="adm-list-item-body">
<div className="adm-list-item-title">
<span className="adm-cell-strong">{body.name_zh || body.name}</span>
<Tag color={BODY_TYPE_COLORS[body.type] || 'default'}>
{BODY_TYPE_LABELS[body.type] || body.type}
</Tag>
</div>
<div className="adm-cell-sub">
{body.followed_at
? `关注于 ${new Date(body.followed_at).toLocaleDateString('zh-CN')}`
: body.name}
</div>
</div>
<Button
type="text"
danger
size="small"
onClick={(event) => {
event.stopPropagation();
void handleUnfollow(body.id);
}}
>
取消关注
</Button>
</div>
<BodyTextureThumb bodyId={body.id} bodyType={body.type} />
</button>
))}
</div>
)}
@ -239,6 +280,18 @@ export function MyCelestialBodies() {
</span>
) : '天体资料'
}
extra={
selectedBody ? (
<Button
size="small"
danger
icon={<StarFilled />}
onClick={() => void handleUnfollow(selectedBody.id)}
>
取消关注
</Button>
) : undefined
}
>
{selectedBody ? (
<Descriptions column={2} size="small" bordered>

View File

@ -0,0 +1,183 @@
/**
* 我的设备(普通用户)
*
* 列出接入当前账号的 ESP32 终端,可用终端屏幕上的 6 位配对码绑定新设备,也可解除绑定。
*/
import { useCallback, useEffect, useState } from 'react';
import { Input, Tag } from 'antd';
import { AdminModal } from '../../components/admin/AdminModal';
import { ApiOutlined, CheckCircleOutlined, MinusCircleOutlined } from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';
import { AdminPage, HeaderStat } from '../../components/admin/AdminPage';
import { DataTable } from '../../components/admin/DataTable';
import {
bindTerminalDevice,
fetchMyDevices,
unbindTerminalDevice,
type TerminalDevice,
} from '../../utils/api';
import { useToast } from '../../contexts/ToastContext';
/** 后端返回的是不带时区标记的 UTC 时间,补上 Z 才能正确转成本地时间。 */
function formatTime(value: string | null): string {
if (!value) return '--';
const date = new Date(value.endsWith('Z') ? value : `${value}Z`);
if (Number.isNaN(date.getTime())) return '--';
return date.toLocaleString('zh-CN');
}
function errorMessage(err: unknown, fallback: string): string {
const detail = (err as { response?: { data?: { detail?: unknown } } })?.response?.data?.detail;
if (typeof detail === 'string') return detail;
if (Array.isArray(detail) && detail.length > 0) return JSON.stringify(detail);
return fallback;
}
export function MyDevices() {
const [devices, setDevices] = useState<TerminalDevice[]>([]);
const [loading, setLoading] = useState(false);
const [bindOpen, setBindOpen] = useState(false);
const [code, setCode] = useState('');
const [binding, setBinding] = useState(false);
const toast = useToast();
const load = useCallback(async () => {
setLoading(true);
try {
setDevices(await fetchMyDevices());
} catch (err) {
toast.error(errorMessage(err, '设备列表加载失败'));
} finally {
setLoading(false);
}
}, [toast]);
useEffect(() => {
void load();
}, [load]);
const openBindModal = () => {
setCode('');
setBindOpen(true);
};
const handleBind = async () => {
setBinding(true);
try {
const device = await bindTerminalDevice(code);
toast.success(`设备已绑定:${device.name || device.id}`);
setBindOpen(false);
setCode('');
await load();
} catch (err) {
toast.error(errorMessage(err, '绑定失败,请检查配对码是否正确'));
} finally {
setBinding(false);
}
};
const handleUnbind = async (device: TerminalDevice) => {
try {
await unbindTerminalDevice(device.id);
toast.success('已解除绑定,该终端的访问令牌立即失效');
await load();
} catch (err) {
toast.error(errorMessage(err, '解绑失败'));
}
};
const columns: ColumnsType<TerminalDevice> = [
{
title: '设备',
key: 'device',
render: (_, record) => (
<div>
<div>{record.name || '未命名终端'}</div>
<div className="adm-cell-sub">{record.id}</div>
</div>
),
},
{
title: '连接状态',
dataIndex: 'online',
key: 'online',
width: 120,
render: (online: boolean) =>
online ? (
<Tag color="green" icon={<CheckCircleOutlined />}>在线</Tag>
) : (
<Tag icon={<MinusCircleOutlined />}>离线</Tag>
),
},
{
title: '绑定时间',
dataIndex: 'bound_at',
key: 'bound_at',
width: 200,
render: (value: string | null) => formatTime(value),
},
{
title: '最后同步',
dataIndex: 'last_seen_at',
key: 'last_seen_at',
width: 200,
render: (value: string | null) => formatTime(value),
},
];
const onlineCount = devices.filter((device) => device.online).length;
return (
<AdminPage
icon={<ApiOutlined />}
title="我的设备"
description="管理接入当前账号的终端,可绑定新设备或解除绑定"
actions={
<>
<HeaderStat label="已绑定" value={devices.length} />
<HeaderStat label="在线" value={onlineCount} tone="primary" />
</>
}
>
<DataTable
columns={columns}
dataSource={devices}
loading={loading}
rowKey="id"
onRefresh={() => void load()}
onAdd={openBindModal}
addText="绑定终端"
onDelete={handleUnbind}
deleteConfirmTitle="确认解除绑定该终端?"
deleteConfirmDescription="解绑后终端需重新配对才能继续同步数据"
/>
<AdminModal
title="绑定终端设备"
open={bindOpen}
onCancel={() => setBindOpen(false)}
okText="绑定"
cancelText="取消"
okButtonProps={{ disabled: code.length !== 6, loading: binding }}
onOk={() => void handleBind()}
destroyOnHidden
>
<div className="adm-cell-sub" style={{ marginBottom: 12 }}>
输入终端配对页面显示的 6 位配对码,绑定后终端自动同步你关注的天体。
</div>
<Input
autoFocus
value={code}
onChange={(event) => setCode(event.target.value.replace(/\D/g, '').slice(0, 6))}
onPressEnter={() => code.length === 6 && void handleBind()}
placeholder="000000"
inputMode="numeric"
autoComplete="off"
maxLength={6}
style={{ textAlign: 'center', fontSize: 24, letterSpacing: 12 }}
/>
</AdminModal>
</AdminPage>
);
}

View File

@ -27,6 +27,8 @@ export function NASADownload() {
const [loadingDateData, setLoadingDateData] = useState(false);
const toast = useToast();
const { cutoffDate } = useDataCutoffDate();
// 静态 Modal.confirm 读不到 ConfigProvider 的深色主题,改用带上下文的实例。
const [modal, modalContextHolder] = Modal.useModal();
const loadBodies = useCallback(async () => {
setLoading(true);
@ -149,7 +151,7 @@ export function NASADownload() {
const dates = getDatesInRange(false);
if (dates.length === 0) return;
Modal.confirm({
modal.confirm({
title: '确认删除',
content: `确定要删除 ${selectedBodies.length} 个天体在 ${dates.length} 天内的所有位置数据吗?此操作不可恢复。`,
okText: '确认删除',
@ -215,29 +217,32 @@ export function NASADownload() {
};
return (
<NasaDownloadView
cutoffDate={cutoffDate}
loading={loading}
bodies={bodies}
selectedBodies={selectedBodies}
dateRange={dateRange}
loadingDates={loadingDates}
downloading={downloading}
deleting={deleting}
downloadProgress={downloadProgress}
activeBodyForCalendar={activeBodyForCalendar}
viewingDateData={viewingDateData}
loadingDateData={loadingDateData}
onBodySelect={handleBodySelect}
onTypeSelectAll={handleTypeSelectAll}
onDateRangeChange={handleDateRangeChange}
onDelete={handleDelete}
onDownload={() => void handleDownload()}
onActiveBodyChange={setActiveBodyForCalendar}
onCalendarDateClick={(date) => void handleCalendarDateClick(date)}
onDateCellRender={dateCellRender}
onCloseDateData={() => setViewingDateData(null)}
disabledDate={(date) => date.isAfter(dayjs(), 'day')}
/>
<>
{modalContextHolder}
<NasaDownloadView
cutoffDate={cutoffDate}
loading={loading}
bodies={bodies}
selectedBodies={selectedBodies}
dateRange={dateRange}
loadingDates={loadingDates}
downloading={downloading}
deleting={deleting}
downloadProgress={downloadProgress}
activeBodyForCalendar={activeBodyForCalendar}
viewingDateData={viewingDateData}
loadingDateData={loadingDateData}
onBodySelect={handleBodySelect}
onTypeSelectAll={handleTypeSelectAll}
onDateRangeChange={handleDateRangeChange}
onDelete={handleDelete}
onDownload={() => void handleDownload()}
onActiveBodyChange={setActiveBodyForCalendar}
onCalendarDateClick={(date) => void handleCalendarDateClick(date)}
onDateCellRender={dateCellRender}
onCloseDateData={() => setViewingDateData(null)}
disabledDate={(date) => date.isAfter(dayjs(), 'day')}
/>
</>
);
}

View File

@ -1,5 +1,6 @@
import { useEffect, useState } from 'react';
import { Button, Col, Form, Input, InputNumber, Modal, Row, Switch, Tabs } from 'antd';
import { Button, Col, Form, Input, InputNumber, Row, Switch, Tabs } from 'antd';
import { AdminModal } from '../../components/admin/AdminModal';
import { RocketOutlined } from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';
import { DataTable } from '../../components/admin/DataTable';
@ -152,7 +153,7 @@ export function Rockets() {
deleteConfirmTitle="确认删除该火箭?"
deleteConfirmDescription="删除后前台发射模拟将不再显示该运载器"
/>
<Modal
<AdminModal
title={editing ? '编辑火箭配置' : '新增火箭配置'}
open={open}
onCancel={() => setOpen(false)}
@ -169,7 +170,7 @@ export function Rockets() {
{ key: 'stage2', label: '二级参数', children: <StageFields index={2} /> },
]} />
</Form>
</Modal>
</AdminModal>
</AdminPage>
);
}

View File

@ -2,7 +2,8 @@
* Static Data Management Page
*/
import { useCallback, useEffect, useMemo, useState } from 'react';
import { Modal, Form, Input, Select } from 'antd';
import { Form, Input, Select } from 'antd';
import { AdminModal } from '../../components/admin/AdminModal';
import { DatabaseOutlined } from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';
import { DataTable } from '../../components/admin/DataTable';
@ -171,7 +172,7 @@ export function StaticData() {
pageSize={systemPageSize}
/>
<Modal
<AdminModal
title={editingRecord ? '编辑静态数据' : '新增静态数据'}
open={isModalOpen}
onOk={handleModalOk}
@ -236,7 +237,7 @@ export function StaticData() {
<Input.TextArea rows={15} className="font-mono" />
</Form.Item>
</Form>
</Modal>
</AdminModal>
</AdminPage>
);
}

View File

@ -1,5 +1,6 @@
import { useCallback, useEffect, useMemo, useState } from 'react';
import { Modal, Form, Input, InputNumber, Switch, Select, Button, Badge, Popconfirm } from 'antd';
import { Form, Input, InputNumber, Switch, Select, Button, Badge, Popconfirm } from 'antd';
import { AdminModal } from '../../components/admin/AdminModal';
import { ClearOutlined, SettingOutlined, SyncOutlined } from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';
import { DataTable } from '../../components/admin/DataTable';
@ -314,7 +315,7 @@ export function SystemSettings() {
scroll={{ x: 1200 }}
/>
<Modal
<AdminModal
title={editingRecord ? '编辑参数' : '新增参数'}
open={isModalOpen}
onOk={handleModalOk}
@ -440,7 +441,7 @@ export function SystemSettings() {
<Input.TextArea rows={3} placeholder="参数说明" />
</Form.Item>
</Form>
</Modal>
</AdminModal>
</AdminPage>
);
}

View File

@ -4,7 +4,8 @@
* 列表每 3 秒静默刷新一次,运行中的任务进度会自动更新。
*/
import { useCallback, useEffect, useMemo, useState } from 'react';
import { Badge, Button, Descriptions, Modal, Progress, Tag, Tooltip } from 'antd';
import { Badge, Button, Descriptions, Progress, Tag, Tooltip } from 'antd';
import { AdminModal } from '../../components/admin/AdminModal';
import type { BadgeProps } from 'antd';
import { EyeOutlined, ScheduleOutlined } from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';
@ -138,7 +139,7 @@ export function Tasks() {
)}
/>
<Modal
<AdminModal
title={`任务详情 #${currentTask?.id ?? ''}`}
open={Boolean(currentTask)}
onCancel={() => setCurrentTask(null)}
@ -166,7 +167,7 @@ export function Tasks() {
)}
{currentTask.error_message && (
<Descriptions.Item label="错误信息">
<span style={{ color: '#cf222e' }}>{currentTask.error_message}</span>
<span style={{ color: 'var(--adm-danger)' }}>{currentTask.error_message}</span>
</Descriptions.Item>
)}
<Descriptions.Item label="结果">
@ -178,7 +179,7 @@ export function Tasks() {
</Descriptions.Item>
</Descriptions>
)}
</Modal>
</AdminModal>
</AdminPage>
);
}

View File

@ -1,12 +1,20 @@
/**
* 个人资料
*
* 管理员与普通用户共用,可修改姓名、邮箱与头像。
* 管理员与普通用户共用:左侧身份区 + 右侧「基本信息 / 修改密码」两个分节,
* 三者合并在同一张卡片里,每个分节右上角就是它自己的提交按钮。
*/
import { useCallback, useEffect, useState } from 'react';
import { Avatar, Button, Card, Col, Descriptions, Form, Input, Row, Tag, Upload } from 'antd';
import { Avatar, Button, Card, Form, Input, Tag, Upload } from 'antd';
import type { UploadProps } from 'antd';
import { IdcardOutlined, LockOutlined, MailOutlined, UploadOutlined, UserOutlined } from '@ant-design/icons';
import {
IdcardOutlined,
LockOutlined,
MailOutlined,
SafetyOutlined,
UploadOutlined,
UserOutlined,
} from '@ant-design/icons';
import { request } from '../../utils/request';
import { auth } from '../../utils/auth';
@ -118,53 +126,65 @@ export function UserProfile() {
}
};
const avatarUrl = profile?.avatar_url
? `/upload/${profile.avatar_url}?t=${avatarStamp}`
: undefined;
const roleName = profile?.role === 'admin' || profile?.roles?.includes('admin') ? '管理员' : '普通用户';
const avatarUrl = profile?.avatar_url ? `/upload/${profile.avatar_url}?t=${avatarStamp}` : undefined;
const isAdmin = profile?.role === 'admin' || Boolean(profile?.roles?.includes('admin'));
const roleName = isAdmin ? '管理员' : '普通用户';
return (
<AdminPage
icon={<IdcardOutlined />}
title="个人资料" description="维护头像、姓名、邮箱,并在此修改登录密码">
<Row gutter={[16, 16]}>
<Col xs={24} md={9} lg={7}>
<Card className="adm-panel" loading={loading} styles={{ body: { padding: 24 } }}>
<div style={{ textAlign: 'center' }}>
<Avatar size={96} src={avatarUrl} icon={<UserOutlined />} />
<h2 style={{ margin: '16px 0 4px', fontSize: 18 }}>{profile?.full_name || profile?.username || '用户'}</h2>
<div className="adm-cell-sub">@{profile?.username}</div>
<Tag color={roleName === '管理员' ? 'green' : 'default'} style={{ marginTop: 10 }}>
{roleName}
</Tag>
<div style={{ marginTop: 16 }}>
<Upload
name="avatar"
showUploadList={false}
customRequest={handleAvatarUpload}
accept="image/*"
>
<Button icon={<UploadOutlined />} loading={uploading}>
更换头像
</Button>
</Upload>
title="个人资料"
description="维护头像、姓名、邮箱,并在此修改登录密码"
>
<Card className="adm-panel adm-profile" loading={loading}>
<div className="adm-profile-grid">
{/* 身份区:头像 + 姓名 + 账号信息 */}
<aside className="adm-profile-id">
<Avatar size={88} src={avatarUrl} icon={<UserOutlined />} />
<div className="adm-profile-name">{profile?.full_name || profile?.username || '用户'}</div>
<div className="adm-profile-handle">@{profile?.username}</div>
<Tag className="adm-profile-role" color={isAdmin ? 'green' : 'default'}>
{roleName}
</Tag>
<Upload name="avatar" showUploadList={false} customRequest={handleAvatarUpload} accept="image/*">
<Button className="adm-profile-upload" icon={<UploadOutlined />} loading={uploading}>
更换头像
</Button>
</Upload>
<dl className="adm-profile-meta">
<div className="adm-profile-meta-row">
<dt>用户名</dt>
<dd>{profile?.username || '-'}</dd>
</div>
</div>
<div className="adm-profile-meta-row">
<dt>角色</dt>
<dd>{roleName}</dd>
</div>
<div className="adm-profile-meta-row">
<dt>注册时间</dt>
<dd>{profile?.created_at ? new Date(profile.created_at).toLocaleString('zh-CN') : '-'}</dd>
</div>
</dl>
</aside>
<Descriptions column={1} size="small" style={{ marginTop: 24 }}>
<Descriptions.Item label="用户名">{profile?.username || '-'}</Descriptions.Item>
<Descriptions.Item label="角色">{roleName}</Descriptions.Item>
<Descriptions.Item label="注册时间">
{profile?.created_at ? new Date(profile.created_at).toLocaleString('zh-CN') : '-'}
</Descriptions.Item>
</Descriptions>
</Card>
</Col>
{/* 账号设置:基本信息与修改密码合并成同一张卡片里的两个分节 */}
<div className="adm-profile-settings">
<Form form={form} layout="vertical" onFinish={handleSubmit} autoComplete="off" className="adm-profile-section">
<div className="adm-profile-section-head">
<div>
<h2 className="adm-profile-section-title">
<IdcardOutlined />
基本信息
</h2>
<p className="adm-profile-section-desc">姓名与邮箱用于界面展示与账号通知</p>
</div>
<Button type="primary" htmlType="submit" loading={saving}>
保存修改
</Button>
</div>
<Col xs={24} md={15} lg={17}>
<div className="adm-stack">
<Card className="adm-panel" title="基本信息" loading={loading}>
<Form form={form} layout="vertical" onFinish={handleSubmit} autoComplete="off" style={{ maxWidth: 460 }}>
<div className="adm-profile-fields">
<Form.Item label="姓名" name="full_name" rules={[{ required: true, message: '请输入姓名' }]}>
<Input prefix={<IdcardOutlined />} placeholder="请输入您的姓名" />
</Form.Item>
@ -172,27 +192,30 @@ export function UserProfile() {
<Form.Item label="邮箱" name="email" rules={[{ type: 'email', message: '请输入有效的邮箱地址' }]}>
<Input prefix={<MailOutlined />} placeholder="请输入邮箱地址(可选)" />
</Form.Item>
</div>
</Form>
<Form.Item style={{ marginBottom: 0 }}>
<Button type="primary" htmlType="submit" loading={saving}>
保存修改
</Button>
</Form.Item>
</Form>
</Card>
<Card
className="adm-panel"
title="修改密码"
extra={<span className="adm-cell-sub">修改后请使用新密码登录</span>}
<Form
form={passwordForm}
layout="vertical"
onFinish={handlePasswordSubmit}
autoComplete="off"
className="adm-profile-section"
>
<Form
form={passwordForm}
layout="vertical"
onFinish={handlePasswordSubmit}
autoComplete="off"
style={{ maxWidth: 460 }}
>
<div className="adm-profile-section-head">
<div>
<h2 className="adm-profile-section-title">
<SafetyOutlined />
修改密码
</h2>
<p className="adm-profile-section-desc">修改后请使用新密码重新登录</p>
</div>
<Button type="primary" htmlType="submit" loading={changingPassword}>
更新密码
</Button>
</div>
<div className="adm-profile-fields">
<Form.Item
label="当前密码"
name="old_password"
@ -236,23 +259,13 @@ export function UserProfile() {
}),
]}
>
<Input.Password
prefix={<LockOutlined />}
placeholder="请再次输入新密码"
autoComplete="new-password"
/>
<Input.Password prefix={<LockOutlined />} placeholder="请再次输入新密码" autoComplete="new-password" />
</Form.Item>
<Form.Item style={{ marginBottom: 0 }}>
<Button htmlType="submit" loading={changingPassword}>
确认修改
</Button>
</Form.Item>
</Form>
</Card>
</div>
</Form>
</div>
</Col>
</Row>
</div>
</Card>
</AdminPage>
);
}

View File

@ -10,11 +10,24 @@
--adm-primary: #238636;
--adm-primary-hover: #2ea043;
--adm-primary-soft: rgba(35, 134, 54, 0.12);
/*
* 重点色分两种用途:
* --adm-primary 填充(主按钮底色等,配白字)
* --adm-primary-text 前景(文字 / 图标 / 描边,配表面底色)
* 深色背景上 #238636 几乎读不出来,所以两套主题各取一值。
*/
--adm-primary-text: #1a7f37;
/* 语义色 */
--adm-danger: #cf222e;
--adm-danger-soft: rgba(207, 34, 46, 0.08);
--adm-warning: #9a6700;
/* 中性色 */
--adm-bg: #f5f6f8;
--adm-surface: #ffffff;
--adm-surface-muted: #fafbfc;
--adm-surface-sunken: #f0f1f3;
--adm-border: #e5e7eb;
--adm-border-strong: #d0d7de;
--adm-text: #1f2328;
@ -39,6 +52,10 @@
--adm-row-hover: rgba(35, 134, 54, 0.06);
/* 固定列必须用不透明色,才能在悬停时继续遮住横向滚动的内容 */
--adm-row-hover-solid: #f2f8f3;
/* 阴影 */
--adm-shadow-card: 0 1px 2px rgba(31, 35, 40, 0.04);
--adm-shadow-popover: 0 -4px 16px rgba(31, 35, 40, 0.12);
}
/* 深色主题:只切换变量,页面结构与文案不变 */
@ -46,12 +63,17 @@
--adm-bg: #0d1117;
--adm-surface: #161b22;
--adm-surface-muted: #1c2128;
--adm-surface-sunken: #21262d;
--adm-border: #30363d;
--adm-border-strong: #3d444d;
--adm-text: #e6edf3;
--adm-text-secondary: #9ba7b4;
--adm-text-muted: #7d8590;
--adm-primary-soft: rgba(46, 160, 67, 0.18);
--adm-primary-text: #3fb950;
--adm-danger: #f85149;
--adm-danger-soft: rgba(248, 81, 73, 0.14);
--adm-warning: #d29922;
--adm-chrome-bg: #010409;
--adm-chrome-border: #21262d;
@ -63,6 +85,14 @@
--adm-pill-hover: rgba(255, 255, 255, 0.1);
--adm-row-hover: rgba(46, 160, 67, 0.14);
--adm-row-hover-solid: #192e27;
--adm-shadow-card: 0 1px 2px rgba(1, 4, 9, 0.5);
--adm-shadow-popover: 0 -4px 16px rgba(1, 4, 9, 0.75);
}
/* 深色下的原生滚动条、表单控件、日期选择器面板同步变暗 */
html[data-adm-theme='dark'] {
color-scheme: dark;
}
/* ------------------------------------------------------------ 布局骨架 */
@ -283,7 +313,7 @@
padding: 6px;
border: 1px solid var(--adm-border);
border-radius: var(--adm-radius);
box-shadow: 0 -4px 16px rgba(31, 35, 40, 0.12);
box-shadow: var(--adm-shadow-popover);
}
.adm-user-menu-content {
@ -314,16 +344,16 @@
.adm-user-menu-item.is-active {
background: var(--adm-primary-soft);
color: var(--adm-primary);
color: var(--adm-primary-text);
font-weight: 600;
}
.adm-user-menu-item.is-danger {
color: #cf222e;
color: var(--adm-danger);
}
.adm-user-menu-item.is-danger:hover {
background: rgba(207, 34, 46, 0.08);
background: var(--adm-danger-soft);
}
.adm-user-menu-divider {
@ -405,7 +435,7 @@
.adm-switch-group > button.is-active {
background: var(--adm-primary-soft);
color: var(--adm-primary);
color: var(--adm-primary-text);
}
.adm-icon-switch {
@ -424,8 +454,8 @@
}
.adm-icon-switch:hover {
color: var(--adm-primary);
border-color: var(--adm-primary);
color: var(--adm-primary-text);
border-color: var(--adm-primary-text);
}
.adm-content {
@ -474,7 +504,7 @@
flex: 0 0 auto;
border-radius: 9px;
background: var(--adm-primary-soft);
color: var(--adm-primary);
color: var(--adm-primary-text);
font-size: 16px;
}
@ -509,6 +539,29 @@
flex-wrap: wrap;
}
.adm-page-stat {
display: inline-flex;
align-items: baseline;
gap: 6px;
padding: 5px 12px;
border: 1px solid var(--adm-border);
border-radius: 999px;
background: var(--adm-surface-muted);
font-size: 12px;
color: var(--adm-text-secondary);
white-space: nowrap;
}
.adm-page-stat strong {
font-size: 14px;
font-weight: 600;
color: var(--adm-text);
}
.adm-page-stat--primary strong {
color: var(--adm-primary-text);
}
.adm-page-body {
display: flex;
flex-direction: column;
@ -516,11 +569,32 @@
min-width: 0;
}
/* ------------------------------------------------------------ 编辑窗体 */
/*
* 窗体(.adm-modal)整体高度受视口限制:标题与底部按钮常驻,
* 内容超出部分在 .ant-modal-body 内滚动,见 AdminModal 组件。
*/
.adm-modal .ant-modal-container {
display: flex;
flex-direction: column;
max-height: calc(100vh - 96px);
}
.adm-modal .ant-modal-body {
flex: 1 1 auto;
min-height: 0;
overflow-y: auto;
overscroll-behavior: contain;
/* 滚动条与表单控件之间留一点间隙,避免贴边 */
padding-inline-end: 4px;
}
/* 统一的卡片/面板外观 */
.adm-panel.ant-card {
border-radius: var(--adm-radius);
border: 1px solid var(--adm-border);
box-shadow: 0 1px 2px rgba(31, 35, 40, 0.04);
box-shadow: var(--adm-shadow-card);
}
.adm-panel .ant-card-head {
@ -662,7 +736,7 @@
border: 1px solid var(--adm-border);
border-radius: var(--adm-radius);
background: var(--adm-surface);
box-shadow: 0 1px 2px rgba(31, 35, 40, 0.04);
box-shadow: var(--adm-shadow-card);
}
.adm-stat-head {
@ -680,7 +754,7 @@
height: 34px;
border-radius: 9px;
background: var(--adm-primary-soft);
color: var(--adm-primary);
color: var(--adm-primary-text);
font-size: 16px;
}
@ -763,7 +837,7 @@
.adm-code-gutter {
padding: 4px 8px;
border-right: 1px solid var(--adm-border);
background: #f0f1f3;
background: var(--adm-surface-sunken);
color: var(--adm-text-muted);
text-align: right;
font-family: 'SFMono-Regular', Consolas, Menlo, monospace;
@ -800,7 +874,7 @@
.adm-inline-panel-title {
margin-bottom: 8px;
font-weight: 600;
color: var(--adm-primary);
color: var(--adm-primary-text);
}
.adm-resource-preview {
@ -900,6 +974,176 @@
background: var(--adm-primary-soft);
}
/* 我的天体:关注列表用真实天体贴图展示 */
.adm-body-grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(76px, 1fr));
gap: 14px;
padding: 16px;
}
.adm-body-tile {
aspect-ratio: 1 / 1;
padding: 0;
overflow: hidden;
border: 1px solid var(--adm-border);
border-radius: 50%;
background: var(--adm-surface-muted);
cursor: pointer;
transition: border-color 0.2s ease, box-shadow 0.2s ease, transform 0.2s ease;
}
.adm-body-tile:hover {
border-color: var(--adm-primary-text);
transform: translateY(-2px);
}
.adm-body-tile.is-selected {
border-color: var(--adm-primary-text);
box-shadow: 0 0 0 3px var(--adm-primary-soft);
}
.adm-body-thumb {
display: block;
width: 100%;
height: 100%;
object-fit: cover;
}
.adm-body-thumb--fallback {
border-radius: 50%;
/* 与真实贴图并排时也能读出球体的明暗 */
box-shadow: inset -7px -9px 16px rgba(0, 0, 0, 0.38), inset 4px 6px 10px rgba(255, 255, 255, 0.1);
}
/* ------------------------------------------------------------ 个人资料 */
/*
* 一张卡片同时承载身份区与账号设置:左列是身份,右列是「基本信息 / 修改密码」两个分节,
* 分节标题右侧就是该分节的提交按钮,避免拆成多张卡片后重点分散。
*/
.adm-profile.ant-card > .ant-card-body {
padding: 0;
}
/* 加载骨架仍需要自己的内边距,不能贴着卡片边框 */
.adm-profile.ant-card > .ant-card-body > .ant-skeleton {
padding: 24px;
}
.adm-profile-grid {
display: grid;
grid-template-columns: 264px minmax(0, 1fr);
}
.adm-profile-id {
display: flex;
flex-direction: column;
align-items: center;
padding: 26px 22px 20px;
border-right: 1px solid var(--adm-border);
border-radius: calc(var(--adm-radius) - 1px) 0 0 calc(var(--adm-radius) - 1px);
background: var(--adm-surface-muted);
}
.adm-profile-name {
margin-top: 14px;
font-size: 17px;
font-weight: 600;
color: var(--adm-text);
}
.adm-profile-handle {
margin-top: 2px;
font-size: 13px;
color: var(--adm-text-muted);
}
.adm-profile-role.ant-tag {
margin: 10px 0 0;
}
.adm-profile-upload.ant-btn {
margin-top: 16px;
}
/* 身份区底部的账号信息:左标签右取值 */
.adm-profile-meta {
display: grid;
gap: 9px;
width: 100%;
margin: 20px 0 0;
padding-top: 16px;
border-top: 1px dashed var(--adm-border);
}
.adm-profile-meta-row {
display: flex;
align-items: baseline;
justify-content: space-between;
gap: 12px;
font-size: 13px;
}
.adm-profile-meta-row dt {
flex: 0 0 auto;
color: var(--adm-text-muted);
}
.adm-profile-meta-row dd {
margin: 0;
color: var(--adm-text);
text-align: right;
word-break: break-all;
}
.adm-profile-settings {
display: flex;
flex-direction: column;
min-width: 0;
}
.adm-profile-section {
padding: 20px 24px;
}
.adm-profile-section + .adm-profile-section {
border-top: 1px solid var(--adm-border);
}
.adm-profile-section-head {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 16px;
margin-bottom: 18px;
}
.adm-profile-section-title {
display: flex;
align-items: center;
gap: 8px;
margin: 0;
font-size: 15px;
font-weight: 600;
color: var(--adm-text);
}
.adm-profile-section-desc {
margin: 4px 0 0;
font-size: 12px;
color: var(--adm-text-muted);
}
/* 表单列宽收紧,避免输入框在宽屏上被拉得过长 */
.adm-profile-fields {
max-width: 440px;
}
.adm-profile-fields .ant-form-item:last-child {
margin-bottom: 0;
}
/* 窄屏适配 */
@media (max-width: 900px) {
.adm-content {
@ -913,4 +1157,23 @@
.adm-page-head {
padding: 16px;
}
.adm-profile-grid {
grid-template-columns: minmax(0, 1fr);
}
.adm-profile-id {
border-right: none;
border-bottom: 1px solid var(--adm-border);
border-radius: calc(var(--adm-radius) - 1px) calc(var(--adm-radius) - 1px) 0 0;
}
.adm-profile-section-head {
align-items: center;
flex-wrap: wrap;
}
.adm-profile-fields {
max-width: none;
}
}

View File

@ -16,7 +16,7 @@ const EN: Record<string, string> = {
'平台管理': 'Platform',
'概览': 'Overview',
'个人资料': 'Profile',
'返回可视化首页': 'Back to Explorer',
'返回首页': 'Back to Explorer',
'退出登录': 'Sign out',
'收起菜单': 'Collapse menu',
'展开菜单': 'Expand menu',
@ -85,6 +85,21 @@ const EN: Record<string, string> = {
'维护头像、姓名、邮箱,并在此修改登录密码': 'Update avatar, name, email and login password',
'我的天体': 'My Bodies',
'查看已关注天体及其相关天象事件': 'Followed bodies and their events',
'我的设备': 'My Devices',
'管理接入当前账号的终端,可绑定新设备或解除绑定': 'Terminals linked to your account; bind new devices or release them',
'已绑定': 'Bound',
'设备': 'Device',
'未命名终端': 'Unnamed terminal',
'连接状态': 'Connection',
'在线': 'Online',
'离线': 'Offline',
'绑定时间': 'Bound at',
'最后同步': 'Last sync',
'绑定终端': 'Bind Terminal',
'绑定终端设备': 'Bind a Terminal',
'绑定': 'Bind',
'确认解除绑定该终端?': 'Release this terminal?',
'解绑后终端需重新配对才能继续同步数据': 'The terminal must be paired again before it can sync data',
// 通用控件
'新增': 'New',

View File

@ -1,5 +1,6 @@
import { useState } from 'react';
import { Alert, Button, Col, Form, Input, InputNumber, Modal, Row, Select, Space, Tabs } from 'antd';
import { Alert, Button, Col, Form, Input, InputNumber, Row, Select, Space, Tabs } from 'antd';
import { AdminModal } from '../../../components/admin/AdminModal';
import { SearchOutlined } from '@ant-design/icons';
import type { FormInstance } from 'antd';
import MarkdownIt from 'markdown-it';
@ -228,7 +229,7 @@ export function CelestialBodyModal({
);
return (
<Modal
<AdminModal
title={record ? '编辑天体' : '新增天体'}
open={open}
onOk={onOk}
@ -263,6 +264,6 @@ export function CelestialBodyModal({
/>
) : basicContent}
</Form>
</Modal>
</AdminModal>
);
}

View File

@ -1,5 +1,5 @@
import { useEffect, useState } from 'react';
import { Button, Form, InputNumber, Popconfirm, Space, Tag, Upload } from 'antd';
import { Button, Col, Form, InputNumber, Popconfirm, Row, Space, Tag, Upload } from 'antd';
import { DeleteOutlined, UploadOutlined } from '@ant-design/icons';
import type { ToastContextValue } from '../../../contexts/ToastContext';
@ -54,13 +54,13 @@ export function ResourceManager({
return (
<Form.Item label="资源配置">
<Space orientation="vertical" style={{ width: '100%' }} size="middle">
<Row gutter={16}>
{resourceTypes.map(({ key, label, type }) => {
const items = currentResources?.[key] ?? [];
const icon = items[0];
return (
<div key={key}>
<Col key={key} xs={24} md={8}>
<div style={{ marginBottom: 8, fontWeight: 500 }}>{label}</div>
{type === 'image' && icon ? (
@ -136,10 +136,10 @@ export function ResourceManager({
)}
</>
)}
</div>
</Col>
);
})}
</Space>
</Row>
</Form.Item>
);
}

View File

@ -4,10 +4,8 @@
* 左侧选择天体,右侧选择日期区间并查看每日数据可用性;
* 点击日历中的日期可直接下载该天的位置数据。
*/
import {
Badge, Button, Calendar, Card, Checkbox, Col, Collapse, DatePicker, Modal,
Progress, Row, Space, Spin, Table, Tag, Tooltip, Typography,
} from 'antd';
import { Badge, Button, Calendar, Card, Checkbox, Col, Collapse, DatePicker, Progress, Row, Space, Spin, Table, Tag, Tooltip, Typography } from 'antd';
import { AdminModal } from '../../../components/admin/AdminModal';
import { DeleteOutlined, DownloadOutlined, LoadingOutlined } from '@ant-design/icons';
import type { Dayjs } from 'dayjs';
@ -203,7 +201,7 @@ export function NasaDownloadView({
</Col>
</Row>
<Modal
<AdminModal
title={`位置数据 - ${viewingDateData?.date || ''}`}
open={Boolean(viewingDateData)}
onCancel={onCloseDateData}
@ -233,7 +231,7 @@ export function NasaDownloadView({
/>
</Spin>
)}
</Modal>
</AdminModal>
</AdminPage>
);
}

View File

@ -1,4 +1,5 @@
import { Alert, Card, Col, Form, Input, Modal, Row, Select, Space, Switch, Tabs, Tag, Tooltip } from 'antd';
import { Alert, Card, Col, Form, Input, Row, Select, Space, Switch, Tabs, Tag, Tooltip } from 'antd';
import { AdminModal } from '../../../components/admin/AdminModal';
import { InfoCircleOutlined, QuestionCircleOutlined } from '@ant-design/icons';
import type { ChangeEvent } from 'react';
import type { FormInstance } from 'antd';
@ -94,7 +95,7 @@ export function ScheduledJobModal({
<Space>
<span>Cron 表达式</span>
<Tooltip title="格式:分 时 日 月 周 (例如: 0 0 * * * 表示每天零点)">
<QuestionCircleOutlined style={{ color: '#8b949e' }} />
<QuestionCircleOutlined style={{ color: 'var(--adm-text-muted)' }} />
</Tooltip>
</Space>
)}
@ -179,7 +180,7 @@ export function ScheduledJobModal({
);
return (
<Modal
<AdminModal
title={record ? '编辑定时任务' : '新增定时任务'}
open={open}
onOk={onOk}
@ -199,6 +200,6 @@ export function ScheduledJobModal({
]}
/>
</Form>
</Modal>
</AdminModal>
);
}

View File

@ -1,7 +1,8 @@
/**
* 恒星系统详情:展示系统参数与该系统下的天体列表。
*/
import { Button, Descriptions, Empty, Modal, Table, Tag } from 'antd';
import { Button, Descriptions, Empty, Table, Tag } from 'antd';
import { AdminModal } from '../../../components/admin/AdminModal';
import type { ColumnsType } from 'antd/es/table';
import type { StarSystemBody, StarSystemWithBodies } from './types';
@ -57,7 +58,7 @@ export function StarSystemDetailsModal({
];
return (
<Modal
<AdminModal
title={`恒星系统详情 · ${record?.name_zh || record?.name || ''}`}
open={open}
onCancel={onClose}
@ -99,6 +100,6 @@ export function StarSystemDetailsModal({
/>
</div>
) : null}
</Modal>
</AdminModal>
);
}

View File

@ -1,5 +1,6 @@
import { useState } from 'react';
import { Col, Form, Input, InputNumber, Modal, Row, Tabs } from 'antd';
import { Col, Form, Input, InputNumber, Row, Tabs } from 'antd';
import { AdminModal } from '../../../components/admin/AdminModal';
import type { FormInstance } from 'antd';
import MdEditor from 'react-markdown-editor-lite';
import MarkdownIt from 'markdown-it';
@ -60,7 +61,7 @@ export function StarSystemModal({ form, record, open, onOk, onCancel }: StarSyst
const [activeTab, setActiveTab] = useState('basic');
return (
<Modal
<AdminModal
title={record ? '编辑恒星系统' : '创建恒星系统'}
open={open}
onOk={onOk}
@ -95,6 +96,6 @@ export function StarSystemModal({ form, record, open, onOk, onCancel }: StarSyst
/>
) : <StarSystemFields />}
</Form>
</Modal>
</AdminModal>
);
}

View File

@ -157,3 +157,29 @@ export async function register(username: string, password: string, email?: strin
const response = await api.post('/auth/register', { username, password, email, full_name });
return response.data;
}
/**
* Terminal device (ESP32) binding API methods
*/
export interface TerminalDevice {
id: string;
name: string | null;
status: string;
bound_at: string | null;
last_seen_at: string | null;
online: boolean;
}
export async function fetchMyDevices(): Promise<TerminalDevice[]> {
const response = await api.get('/devices');
return response.data;
}
export async function bindTerminalDevice(code: string): Promise<TerminalDevice> {
const response = await api.post('/devices/bind', { code });
return response.data;
}
export async function unbindTerminalDevice(deviceId: string): Promise<void> {
await api.delete(`/devices/${encodeURIComponent(deviceId)}`);
}

View File

@ -40,16 +40,25 @@ request.interceptors.request.use(
}
);
// 会话失效只需要跳转一次登录页,避免并发 401 触发整页反复刷新
let redirectingToLogin = false;
// Response interceptor - handle auth errors
request.interceptors.response.use(
(response) => {
return response;
},
(error) => {
if (error.response?.status === 401) {
const url: string = error.config?.url ?? '';
// 本地已经没有 token,说明是主动退出后残留的请求;/auth/logout 自身的 401 同样忽略。
const sessionExpired = error.response?.status === 401 && auth.getToken() && !url.includes('/auth/logout');
if (sessionExpired) {
// Unauthorized - clear auth and redirect to login
auth.logout();
window.location.href = '/login';
if (!redirectingToLogin && window.location.pathname !== '/login') {
redirectingToLogin = true;
window.location.href = '/login';
}
}
return Promise.reject(error);
}

View File

@ -0,0 +1,227 @@
# COSMO 轨道终端固件(ESP32-S3)
正点原子 ATK-DNESP32S3 + 2.4 寸 TFTLCD(ST7789V,横屏 320x240)上运行的终端固件。
联网后显示 6 位绑定码,网页端输入完成绑定,之后开机直接用长期 token 拉取该用户关注的天体。
## 硬件
| 项目 | 说明 |
| --- | --- |
| 主控 | ESP32-S3(8MB OPI PSRAM / 16MB flash) |
| 屏幕 | 2.4" ST7789V 模块,4 线 SPI:SCK=12 / MOSI=11 / MISO=13 / DC=40 / CS=21 |
| LCD 复位·供电·背光 | 板上 XL9555 IO 扩展器(I2C:SDA=41 / SCL=42,地址 0x20) |
| 按键 | KEY0..KEY3 走 XL9555(P1_4..P1_7),BOOT=GPIO0 |
| 触摸 | **无**。这块 2.4 寸屏只有 ST7789V,没有触摸层 |
| 串口 | CH340 → `/dev/cu.usbserial-210`,115200 |
`WIRE_DC / LCD_DC` 跳线帽必须短接(SPI 模式),引脚集中在 `src/board_config.h`。
### 输入方式:只有按键,没有触摸
设计稿里的底部按钮不能点——**这块屏不带触摸层**。两条证据:
1. 屏模块的 8 pin 插座只有 `PWR GND / CS 3V3 / WR SCK / RST SDA`,没有 TOUCH_PEN/TOUCH_CS;
2. 串口 `i2cscan` 在 I2C 上只扫到 `0x10 / 0x12 / 0x1E / 0x20(XL9555) / 0x50(EEPROM)`,
没有 GT911(0x5D/0x14)、FT6x36(0x38)、CST0xx(0x28) 之类的触摸控制芯片。
所以交互全部走板子右侧丝印的实体键(KEY0..KEY3)+ BOOT:
| 键 | 位置 | 列表页 | 详情页 | 配对页 |
| --- | --- | --- | --- | --- |
| KEY0 | 右侧最上 | 上移 | 上移 | — |
| KEY1 | 右侧第二 | 下移 | 下移 | — |
| KEY2 | 右侧第三 | 进详情 | 返回列表 | 查看配对码说明 |
| KEY3 | 右侧最下 | 立即刷新 | 右栏翻页 EVENTS/INFO | 重新要一个码 |
| BOOT | 板上 GPIO0 | 等同 KEY2 | 等同 KEY2 | 等同 KEY2 |
屏幕底部那一排方框(设计稿里 `[ORBIT][COMM][SYS]` 那个造型)就是这几颗键的**图例**:
金色描边金字,按下时整块变金底暗金字 250ms 作为反馈,键名直接印在框里(`KEY2 OK` / `KEY3 TAB`…)。
串口 `key 0xNNNN` 注入的按键走同一条路径,反馈一样。
排查按键(键没反应时先看这两条):
```sh
# xlreg 打印 XL9555 四个寄存器;空闲时 input 应为 0xFFxx(P1_4..7 全高)
# 依次按 KEY0..KEY3 / BOOT,每颗停一秒,日志里 [key] changed=0x.... 会直接指出是哪一位
~/esp-tools/pio_env/bin/python terminal/tools/key_watch.py 240 /tmp/keywatch.log
```
> **坑:XL9555 读寄存器必须先写地址指针。** `Wire.requestFrom()` 之前不写 pointer,
> 读到的是上一次写之后自增到的位置(output/config),按键永远读不到,屏幕对实体键毫无反应。
> `read_reg()` 里那句 `endTransmission(false)` + `requestFrom()` 就是修这个的。
> 空闲 `input=0xFFFD`:低字节 P0_0 是 ALS 光敏(悬空为低),所以按键只取高字节,避免幽灵按键。
## 构建 / 烧录
```sh
unset HTTP_PROXY HTTPS_PROXY http_proxy https_proxy # 本地代理端口是死的,会拖死下载
FQBN='esp32:esp32:esp32s3:PSRAM=opi,FlashSize=16M,FlashMode=dio,CDCOnBoot=default,PartitionScheme=app3M_fat9M_16MB,UploadSpeed=460800'
~/esp-tools/arduino-cli --config-file ~/esp-tools/arduino-cli.yaml compile --fqbn "$FQBN" terminal/firmware/cosmo_terminal
~/esp-tools/arduino-cli --config-file ~/esp-tools/arduino-cli.yaml upload --fqbn "$FQBN" --port /dev/cu.usbserial-210 terminal/firmware/cosmo_terminal
```
- `PSRAM=opi` 必须开:帧缓冲(320x240x2 = 150KB)放在 PSRAM。
- 烧录速率用 460800;921600 在这块 CH340 上会 `Unable to verify flash chip connection`。
- 分区表 `app3M_fat9M_16MB`:app 3MB,当前 `Sketch uses 1439650 bytes (45%)`(含内置图标 189KB + 中文字库 125KB)。
- 依赖:Arduino 核 `esp32:esp32 3.3.12` + `ArduinoJson 7.4.3`,其余都是核心自带库。
## 界面:设计稿语言与离线资源
版面常量在 `src/ui.cpp` 顶部,全局统一:状态栏 `y0..19`(下沿一条 `C_CYAN_DIM` 分隔线)、
内容区 `TOP_Y=22 .. BOT_Y=212`、按键条 `KEY_Y=216` 高 20。列表页 3 张卡
`y = 22 + n*65`、`h=60`、`cut=8`,右缘 2px 滚动条。详情页:标题 `y20`、POS/VEL 两块
`156x88`(`y40`,左青右金)、下方左侧 `88x81` 天体图(雷达底纹 + 64x64 图标叠加)、
右侧 `222x81` 分页面板,`[EVENTS]` / `[INFO]` 由 KEY3 循环切换(INFO 页 = 中文名 + 中文简介,
12 字/行 x 2 行,第二行末尾留一个字位给截断标记 `..`;面板高度放不下设计稿里的 3 行)。配色取自设计稿取色,见 `src/display.h` 的注释。
面板统一用**切角(chamfer)**图元 `disp_panel(x,y,w,h,cut,fill,border)`,需要辉光时先
`disp_panel_glow()` 在外侧描一圈低阶色。背景 `disp_bg()` = `C_BG` + 固定伪随机星点 +
角落电路走线,纯程序化,不占 flash。
内置图标和字库都是**离线生成、提交进仓库**的,编译时不需要 Pillow。
天体图标已经改成后台维护、运行时下载(见下一节),这套内置图标现在只当**兜底**:
```sh
/usr/bin/python3 terminal/tools/gen_assets.py # 只读 资源文件/*.jpeg 和本机字体,无联网
```
- `src/icons.{h,cpp}`:`资源文件/*小.jpeg`(320x320 纯黑底霓虹线稿)→ 亮度 bbox 裁切 → 补方
→ LANCZOS 缩到 40x40(列表)/ 64x64(详情)→ 黑底门限 → RGB565。**没有 alpha 通道**,
运行时 `disp_add_bitmap()` 做加色混合(逐通道饱和相加),所以源图必须是**纯黑底**,
否则灰底会把整块面板糊白。`icon_for(name, name_zh, type, detail)` 先按名字小写子串匹配,
命不中再按后端 6 种 `type` 兜底,最后 `planet`。没有专属图的天体(水星/天王星/冥王星系)
就用 `行星小.jpeg`,**不做假色相**。后台没维护图标的天体走的就是这张表,见下一节。
- `src/font_cjk.{h,cpp}`:16x16 点阵,GB2312 一级字 3755 + 常用中文标点和 `°×℃` =
**3775 字**(点阵 118KB + 索引 7.4KB)。STHeiti Medium 160pt 渲染 → 取 em 见方 158px 裁切
(字身中心下移 4px 找齐)→ BILINEAR 降到 16x16 → 阈值 130 二值化;
墨迹超过 55% 自动加严阈值防粘连,一点墨都没有则自动放宽。
按码位升序存 `s_codepoints[]` + `s_glyphs[][32]`,运行时二分查找,缺字画空心方框 `□`。
`disp_text()` 按 UTF-8 逐字符分流:ASCII 走 `font_asc2.h`(推进 9px),中文走点阵(推进 17px);
`size=32` 时中文按 2x2 块放大。截断一律走 `disp_text_clipped()` / `clip_chars()`,
保证不切断 UTF-8 序列。
## 天体图标:后台维护,运行时动态拉取
设计稿里的天体图标不是编译死的:**平台管理 -> 天体信息 -> 资源配置 -> 图标** 里换一张图,
终端下一次数据刷新(5 分钟轮询或串口 `reload`)就跟着换。
```
后台 resources 表里 resource_type='icon' 的行(文件在 backend/upload/icon/*)
-> 后端用 Pillow 现算成定长 RGB565 裸点阵(40x40=3200B / 64x64=8192B)
-> GET /api/terminal/bodies/{id}/icon?size=40|64 (Bearer 终端 token)
-> 固件直接喂 disp_add_bitmap() 加色混合,不解码 JPEG/PNG
```
- **渲染**:`app/services/terminal_icon.py:render_rgb565()`,流水线(亮度 bbox 裁切 → 补方 →
LANCZOS → luma<=10 归零 → RGB565)和 `terminal/tools/gen_assets.py` 的 `icon_pixels()` 一致,
同一个源文件两边输出**逐像素 0 差异**,所以后台传的图和内置图是同一套视觉语言。
源图照旧要求**纯黑底**(没有 alpha,灰底会把整块面板糊白)。Pillow 本来就在
`requirements.txt`(10.1.0),没新增依赖。
- **版本门控**:`/api/terminal/follows` 每个天体多返回一个 `icon_ver`(= 图标资源行的 id,
也是图标端点的 `ETag`)。固件只在 `icon_ver` 变化时下载,稳态零流量;实测一个天体
拉 40+64 两张 ~130ms。
- **一个天体维护了多张图标**时后端取**最新**(`created_at desc, id desc`)。
⚠️ 管理端 `ResourceManager.tsx` 的预览和删除用的是 `items[0]`(`created_at` **最旧**那条),
重复上传时两边指向的不是同一行,换完图要对一下 `stat` 里的版本号。
- **固件缓存** `src/iconstore.{h,cpp}`:一个关注天体一个槽(上限 `MAX_BODIES=6`),
点阵 `heap_caps_malloc(MALLOC_CAP_SPIRAM|MALLOC_CAP_8BIT)` 惰性分配,每槽
3200+8192=11392B,最坏 6 槽约 68KB PSRAM;取消关注的槽在下次 sync 时释放(缓冲区留着复用)。
`stat` 会给每个槽打一行 `icon : 599 v45 cached`。
- **字节序**:点阵按**大端**下发(和串口 `dump` 同一个约定),`api_icon()` 收完逐像素
`__builtin_bswap16()` 转回本机序——`disp_add_bitmap()` 吃的是普通 `uint16_t` RGB565 值。
忘了转会整屏颜色字节互换,`fb_check.py --raw` 实测最大逐像素误差 ~58000。
- **兜底**:后台没维护(404)/ 文件丢了(404)/ 解不开(502)/ 长度不符 / `size` 非法(400)
→ `icon_store_get()` 返回 NULL,UI 落回内置线稿,屏幕不会出现空洞。
Venus 后台没维护图标,正好当兜底的回归用例。
核对不用肉眼盯 960x720 的放大图,`fb_check.py --raw` 直接拿后端吐的裸点阵对屏幕:
```sh
curl --noproxy '*' -H "Authorization: Bearer $TOK" -o /tmp/ic_599_40.bin \
'http://192.168.31.2:8000/api/terminal/bodies/599/icon?size=40'
# 列表三张卡的图标左上角 = 13,32 / 13,97 / 13,162(40x40);详情 64x64 = 15,140
/usr/bin/python3 terminal/tools/fb_check.py /tmp/f_list --raw 13,32,40,/tmp/ic_599_40.bin
```
图标底下压着面板底色和雷达刻度,所以 `--raw` 是「在每个候选底色里取误差最小的再取 max」,
命中就是 0;拿土星图去核对木星详情位会得到 ~57000,说明这把尺子有效。
## 配网
首次开机或 NVS 里没有 SSID 时,终端开一个热点 `COSMO-SETUP-XXXX`:
1. 手机/电脑连这个热点;
2. 浏览器打开 `http://192.168.4.1`(多数系统会自动弹出强制门户);
3. 选 SSID、填密码和后端地址(默认 `http://192.168.31.2:8000/api`),保存后自动重启。
凭据、后端地址、token 都存在 NVS 命名空间 `cosmo`。
## 绑定与取数
```
开机 -> 连 WiFi -> POST /api/terminal/pair/code 拿 6 位码,屏幕上大字显示
-> GET /api/terminal/pair/status 每 2s 轮询
网页端 设备绑定入口输入 6 位码 -> POST /api/devices/bind
终端 轮询到 status=bound -> 立刻把 access_token 写入 NVS
之后 GET /api/terminal/follows (Bearer token) 显示关注天体列表 / 详情
```
防抢绑靠后端,不靠终端:码只能由已登录用户在 `/api/devices/bind` 消费,同码并发只有 1 个成功;码 10 分钟过期,剩余不足 10s 时终端主动换新码;换绑会轮换 token,解绑后旧 token 立即 401,终端自动回到配对页。
## 串口命令(115200)
`help` / `wifi <ssid> [pass]` / `api <url>` / `pair` / `reload` / `portal` / `stat` /
`keys` / `xlreg` / `key 0xNN` / `i2cscan` / `selftest` / `dump` / `swap 0|1` / `bgr 0|1` / `inv 0|1` / `mir 0|1` / `reset`
`key 0x8000|0x4000|0x2000|0x1000` 注入一次按键(上/下/确认/刷新),不接按键也能翻页;
`dump` 把当前 320x240 帧缓冲按 RGB565 大端从串口回传(约 14s),用来在电脑上看屏幕内容:
点屏调色:颜色整体反了用 `inv`,红蓝互换用 `bgr`,明暗/花屏用 `swap`,左右反了用 `mir`。
`selftest` 画四条色带自检,任意按键或命令退出。
```sh
# 一个终端:既能敲串口命令,又会在 dump 后自动出图
~/esp-tools/pio_env/bin/python terminal/tools/serial_term.py # -> /tmp/fb.raw
ffmpeg -f rawvideo -pixel_format rgb565be -video_size 320x240 -i /tmp/fb.raw \
-frames:v 1 -vf scale=960:720:flags=neighbor screen.png
```
注意:`dump` 读的是当前帧缓冲,切页后要等画面刷完再发,否则拿到的是上一页。
`dump` 内部按 128 字节分块写、写满前等 `Serial.availableForWrite()`,一次性灌会被 CH340 冲花。
抓屏脚本把「发命令 + 等画面 + dump + 出图」串成一行,状态机保证 `[FB]` 标记不被日志冲掉:
```sh
~/esp-tools/pio_env/bin/python terminal/tools/screen_shot.py /tmp/log \
"|2|-" # 先发空命令, drain 启动日志
"key 0x2000|0.8|-" # KEY2 确认 -> 进详情页
"dump|0.2|/tmp/fb_detail" # 抓详情页 -> /tmp/fb_detail.png
```
抓回来的裸数据用 `fb_check.py` 核对,不用肉眼在 960x720 的放大图里找茬:
```sh
# 列表页三张卡到底是哪张图(拿卡底色 + 内置图标做加色混合反算,残差 0 = 就是这张,兜底图一眼看穿)
# 后台维护过的图标会报「不属于任何内置图标」,那是正常的,改用 --raw 核对,见「天体图标」一节
/usr/bin/python3 terminal/tools/fb_check.py /tmp/r_list
# 中文字模逐像素核对(103,176 = 字模左上角,b77d = 前景色,后面是这一行该显示的字)
/usr/bin/python3 terminal/tools/fb_check.py /tmp/r_info --glyph 103,176,b77d,木星,太阳系中最大的行星
```
它直接读 `src/icons.cpp` / `src/font_cjk.cpp` 的点阵反推期望像素,所以「中文画成了空心方框」
「图标走错兜底」这类问题会直接报出来;选中卡前景是 `C_WHITE`、未选中是 `C_TEXT`,别填错。
每帧约 14s;要抓按键反色,就在发键后 250ms 内 dump。
**两个坑**:① 每个 `dump` 必须单独占一步(`"key 0x2000|1.5|-"` 之后另起一步 `"dump|1.5|/tmp/x"`),
写在同一步里抓到的是按键前的画面;② `[FB]` 标记后面的残留字节必须丢掉再写文件,
留着会让整幅图右移 2px 且末行丢 2px(脚本里 `d=bytes(buf); buf=bytearray()` 就是干这个的)。
## 已知限制
- **没有触摸**:设计稿里所有「点击」交互都改成按键,见上面「输入方式」。
- **中文只有 16x16 点阵**,覆盖 GB2312 一级字 + 常用标点;生僻字/二级字会画成 `□`,
同行英文不受影响。事件标题里的中文现在能显示,但仍然只截到 `ev[28]`(约 9 个汉字)。
- 后端只在**首次绑定**时下发 token。NVS 被清空但数据库仍是绑定状态时,屏幕会提示先在网页端解绑再重新要码。
- HTTP 请求是阻塞的,拉数据时按键响应会停顿 1 秒左右;图标版本变化那一次会多两次下载(~130ms/天体)。
- 动态图标要在后台维护过才有,没维护的天体用的是内置那 ~20 张线稿,水星/天王星/冥王星这类只能吃兜底图。
- 事件列表按后端返回顺序显示,包含已过期的(`is_upcoming=false` 也在列)。
- 未做:频道消息页、设置页、OTA、设计稿里的 STATUS 数据格(表面温度、自转周期等后端没有数据源)。

View File

@ -0,0 +1,554 @@
/**
* COSMO 轨道终端(ESP32-S3 + 2.4寸横屏 320x240)
*
* 流程:开机 -> 有 WiFi 凭据就连接,没有就开热点配网
* -> 联网后向后端要 6 位绑定码并显示
* -> 轮询绑定结果,拿到长期 token 立刻写入 NVS
* -> 之后开机直接用 token 拉取该用户关注的天体数据
*
* 串口 115200,输入 help 看调试命令。
*/
#include <Arduino.h>
#include <WiFi.h>
#include <esp_mac.h>
#include <string.h>
#include <stdlib.h>
#include "src/board_config.h"
#include "src/expander.h"
#include "src/display.h"
#include "src/store.h"
#include "src/api.h"
#include "src/portal.h"
#include "src/ui.h"
#include "src/iconstore.h"
#define DEFAULT_API "http://192.168.31.2:8000/api"
#define DEVICE_NAME "Cosmo Terminal"
#define TOKEN_CAP 320 /* 后端下发的 terminal token 约 200 字符 */
#define POLL_MS 2000 /* 后端 pair/status 建议 poll_interval=2s */
#define DATA_REFRESH 300000UL /* 天体数据 5 分钟刷新一次 */
#define WIFI_TIMEOUT 20000UL
#define CODE_RENEW 10 /* 配对码剩余不足 10 秒主动换新 */
#define KEY_DEBOUNCE 20
#define KEY_FLASH_MS 250 /* 底部按键条按下反馈时长 */
/* ---------------- 全局状态 ---------------- */
static UiState g_ui;
static Snapshot g_snap;
static char g_token[TOKEN_CAP];
static char g_ap_ssid[24];
static uint32_t g_deadline = 0; /* 配对码到期时刻 */
static uint32_t g_next_poll = 0;
static uint32_t g_next_data = 0;
static uint32_t g_retry_at = 0; /* 无码时的下次重试时刻 */
static uint32_t g_wifi_since = 0;
static bool g_dirty = true;
static bool g_ui_paused = false; /* selftest 期间不要被状态界面覆盖 */
static const char *screen_name(Screen s)
{
static const char *n[] = { "SPLASH", "PROVISION", "CONNECTING", "PAIR",
"LOADING", "LIST", "DETAIL", "ERROR" };
return (s <= SC_ERROR) ? n[s] : "?";
}
static void set_screen(Screen s, const char *msg = nullptr)
{
if (msg) strlcpy(g_ui.message, msg, sizeof(g_ui.message));
if (g_ui.screen != s) Serial.printf("[ui] %s -> %s\n", screen_name(g_ui.screen), screen_name(s));
g_ui.screen = s;
g_dirty = true;
}
/* ---------------- 前向声明 ---------------- */
static void start_provision();
static void wifi_connect();
static void start_pairing();
static void request_code();
static void load_data(bool show_loading);
/* ---------------- 启动 ---------------- */
static void build_identity()
{
uint8_t mac[6] = { 0 };
esp_read_mac(mac, ESP_MAC_WIFI_STA);
char dev[24], ap[24];
snprintf(dev, sizeof(dev), "ESP32S3-%02X%02X%02X%02X%02X%02X",
mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);
snprintf(ap, sizeof(ap), "COSMO-SETUP-%02X%02X", mac[4], mac[5]);
strlcpy(g_ui.device_id, dev, sizeof(g_ui.device_id));
strlcpy(g_ap_ssid, ap, sizeof(g_ap_ssid));
strlcpy(g_ui.ap_ssid, g_ap_ssid, sizeof(g_ui.ap_ssid));
if (!store_get_str(K_API, g_ui.api, sizeof(g_ui.api)))
strlcpy(g_ui.api, DEFAULT_API, sizeof(g_ui.api));
if (store_get_str(K_USER, g_ui.owner, sizeof(g_ui.owner)) == false) g_ui.owner[0] = 0;
Serial.printf("[dev] id=%s ap=%s api=%s\n", g_ui.device_id, g_ap_ssid, g_ui.api);
}
/* ---------------- 配网 ---------------- */
static void start_provision()
{
portal_start(g_ap_ssid, DEFAULT_API);
g_ui.wifi_up = false; /* 配网时 STA 已断开,状态栏不能再显示 NET:ONLINE */
set_screen(SC_PROVISION);
Serial.printf("[portal] AP=%s -> http://192.168.4.1\n", g_ap_ssid);
}
static void wifi_connect()
{
char ssid[33], pass[65];
if (!store_get_str(K_SSID, ssid, sizeof(ssid)) || !ssid[0]) { start_provision(); return; }
store_get_str(K_PASS, pass, sizeof(pass));
strlcpy(g_ui.ssid, ssid, sizeof(g_ui.ssid));
g_ui.wifi_up = false;
WiFi.mode(WIFI_STA);
WiFi.setSleep(false);
WiFi.begin(ssid, pass);
g_wifi_since = millis();
set_screen(SC_CONNECTING);
Serial.printf("[wifi] connecting %s\n", ssid);
}
static void wifi_tick()
{
if (WiFi.status() == WL_CONNECTED) {
g_ui.wifi_up = true;
g_ui.rssi = WiFi.RSSI();
Serial.printf("[wifi] online ip=%s rssi=%d\n",
WiFi.localIP().toString().c_str(), g_ui.rssi);
if (g_token[0]) load_data(true);
else start_pairing();
return;
}
if (millis() - g_wifi_since > WIFI_TIMEOUT) {
Serial.println("[wifi] timeout, retrying");
WiFi.disconnect();
wifi_connect();
}
}
/* ---------------- 绑定 ---------------- */
static void start_pairing()
{
g_ui.code[0] = 0;
set_screen(SC_PAIR);
request_code();
}
static void request_code()
{
char code[8];
int ttl = 0;
bool bound = false;
if (api_pair_code(g_ui.api, g_ui.device_id, DEVICE_NAME, code, sizeof(code),
&ttl, &bound, g_ui.owner, sizeof(g_ui.owner))) {
if (bound) {
/* 后端只在首次绑定时下发 token:NVS 被清空且 DB 仍绑定时需要先在网页端解绑 */
char msg[140];
snprintf(msg, sizeof(msg),
"ALREADY BOUND AS %s BUT THIS TERMINAL LOST ITS TOKEN. UNBIND IT IN THE WEB UI, THEN PRESS [CODE].",
g_ui.owner[0] ? g_ui.owner : "?");
strlcpy(g_ui.message, msg, sizeof(g_ui.message));
g_ui.code[0] = 0;
g_retry_at = millis() + 30000;
g_dirty = true;
Serial.printf("[pair] already bound as %s\n", g_ui.owner);
return;
}
strlcpy(g_ui.code, code, sizeof(g_ui.code));
g_ui.code_left = ttl;
g_ui.code_total = ttl;
g_deadline = millis() + (uint32_t)ttl * 1000UL;
g_next_poll = millis() + POLL_MS;
g_dirty = true;
return;
}
char msg[140];
snprintf(msg, sizeof(msg), "CANNOT GET CODE FROM %s. CHECK THE BACKEND, THEN PRESS [CODE].", g_ui.api);
strlcpy(g_ui.message, msg, sizeof(g_ui.message));
g_ui.code[0] = 0;
g_retry_at = millis() + 5000;
g_dirty = true;
}
static void pair_tick(uint32_t now)
{
if (!g_ui.code[0]) {
if ((int32_t)(now - g_retry_at) >= 0) request_code();
return;
}
int left = (g_deadline > now) ? (int)((g_deadline - now) / 1000) : 0;
if (left != g_ui.code_left) { g_ui.code_left = left; g_dirty = true; }
if (left <= CODE_RENEW) { Serial.println("[pair] code about to expire, requesting a new one"); request_code(); return; }
if ((int32_t)(now - g_next_poll) < 0) return;
g_next_poll = now + POLL_MS;
char token[TOKEN_CAP], owner[24];
PairResult r = api_pair_status(g_ui.api, g_ui.device_id, g_ui.code,
token, sizeof(token), owner, sizeof(owner));
if (r == PR_BOUND) {
strlcpy(g_token, token, sizeof(g_token));
store_set_str(K_TOKEN, g_token); /* token 只下发一次,马上落盘 */
if (owner[0]) strlcpy(g_ui.owner, owner, sizeof(g_ui.owner));
store_set_str(K_USER, g_ui.owner);
g_ui.code[0] = 0;
Serial.printf("[pair] bound as %s (token %d bytes)\n", g_ui.owner, (int)strlen(g_token));
load_data(true);
} else if (r == PR_EXPIRED || r == PR_INVALID) {
Serial.printf("[pair] code %s -> new code\n", (r == PR_EXPIRED) ? "expired" : "stale");
request_code();
}
/* PR_PENDING / PR_ERROR:下个周期继续轮询 */
}
/* ---------------- 数据 ---------------- */
static void load_data(bool show_loading)
{
if (!g_token[0]) { start_pairing(); return; }
if (show_loading || !g_snap.count) set_screen(SC_LOADING);
int http = 0;
if (api_follows(g_ui.api, g_token, &g_snap, &http)) {
strlcpy(g_ui.owner, g_snap.username, sizeof(g_ui.owner));
store_set_str(K_USER, g_ui.owner);
g_ui.snap = &g_snap;
if (g_ui.sel >= g_snap.count) g_ui.sel = (g_snap.count ? g_snap.count - 1 : 0);
g_ui.rssi = WiFi.RSSI();
g_ui.wifi_up = (WiFi.status() == WL_CONNECTED);
/* 后台换过图标才下载(每个图标两张图,只在版本变化时走一次 HTTP) */
icon_store_sync(g_ui.api, g_token, &g_snap);
g_next_data = millis() + DATA_REFRESH;
set_screen(SC_LIST);
return;
}
if (http == 401 || http == 403) {
Serial.println("[api] token rejected, go back to pairing");
g_token[0] = 0;
store_erase(K_TOKEN);
start_pairing();
return;
}
char msg[140];
snprintf(msg, sizeof(msg), "DATA FETCH FAILED (HTTP %d), API %s. [REF] RETRIES.", http, g_ui.api);
g_next_data = millis() + 15000; /* 有旧数据时后台定时重试 */
set_screen(g_snap.count ? SC_LIST : SC_ERROR, msg);
}
static void run_tick(uint32_t now)
{
if ((int32_t)(now - g_next_data) >= 0) { g_next_data = now + DATA_REFRESH; load_data(false); }
}
/* ---------------- 按键 ---------------- */
static uint16_t s_keys_stable = 0, s_keys_last = 0xFFFF;
static uint32_t s_keys_edge = 0, s_keys_sample = 0;
static uint32_t s_flash_until = 0;
static uint32_t s_anim_last = 0;
/* 底部按键条槽位:0=KEY0 1=KEY1 2=KEY2/BOOT 3=KEY3 */
static uint8_t flash_slot_bits(uint16_t keys)
{
uint8_t f = 0;
if (keys & XL_IO_KEY0) f |= 1;
if (keys & XL_IO_KEY1) f |= 2;
if ((keys & XL_IO_KEY2) || (keys & 0x0001)) f |= 4;
if (keys & XL_IO_KEY3) f |= 8;
return f;
}
static void on_key_press(uint16_t bits)
{
g_ui.key_flash = flash_slot_bits(bits);
if (g_ui.key_flash) { s_flash_until = millis() + KEY_FLASH_MS; g_dirty = true; }
if (g_ui_paused) { g_ui_paused = false; g_dirty = true; return; }
bool up = bits & XL_IO_KEY0;
bool dn = bits & XL_IO_KEY1;
bool ok = (bits & XL_IO_KEY2) || (bits & 0x0001); /* BOOT 也当 OK */
bool ref = bits & XL_IO_KEY3;
switch (g_ui.screen) {
case SC_CONNECTING:
if (ref) { Serial.println("[key] reprovision from CONNECTING"); start_provision(); }
break;
case SC_PAIR:
if (ok) Serial.printf("[info] dev=%s api=%s user=%s token=%d\n",
g_ui.device_id, g_ui.api, g_ui.owner, (int)strlen(g_token));
if (ref) request_code();
break;
case SC_LIST:
if (up && g_ui.sel > 0) { g_ui.sel--; g_dirty = true; }
if (dn && g_snap.count && g_ui.sel < g_snap.count - 1) { g_ui.sel++; g_dirty = true; }
if (ok) { g_ui.screen = SC_DETAIL; g_ui.detail_tab = 0; g_dirty = true; }
if (ref) load_data(true);
break;
case SC_DETAIL:
/* 详情页 KEY3 改成右栏分页;刷新由进入列表时的 5 分钟轮询覆盖 */
if (up && g_ui.sel > 0) { g_ui.sel--; g_dirty = true; }
if (dn && g_snap.count && g_ui.sel < g_snap.count - 1) { g_ui.sel++; g_dirty = true; }
if (ok) { g_ui.screen = SC_LIST; g_dirty = true; }
if (ref) { g_ui.detail_tab ^= 1; g_dirty = true; }
break;
case SC_ERROR:
case SC_LOADING:
if (ref) load_data(true);
break;
default:
break;
}
}
static void keys_tick(uint32_t now)
{
if (now - s_keys_sample < 10) return;
s_keys_sample = now;
uint16_t raw = xl_keys_read();
if (raw != s_keys_last) { s_keys_last = raw; s_keys_edge = now; return; }
if (now - s_keys_edge < KEY_DEBOUNCE) return;
if (raw == s_keys_stable) return;
uint16_t prev = s_keys_stable;
uint16_t pressed = raw & ~prev;
s_keys_stable = raw;
/* 打印整字变化:按键真接在别的脚上时也能一眼看到是哪一位 */
Serial.printf("[key] changed=0x%04X -> 0x%04X (xl input=0x%04X)\n", prev, raw, xl_keys_raw());
on_key_press(pressed);
}
/* ---------------- 串口命令 ---------------- */
static void print_help()
{
Serial.println(F("help this text"));
Serial.println(F("wifi <ssid> [pass] set credentials and connect"));
Serial.println(F("api <url> backend base url, e.g. http://192.168.31.2:8000/api"));
Serial.println(F("pair drop token and request a new binding code"));
Serial.println(F("reload refetch followed bodies"));
Serial.println(F("portal open the setup hotspot"));
Serial.println(F("stat print current state"));
Serial.println(F("keys print raw key bitmap (check polarity)"));
Serial.println(F("xlreg dump all XL9555 registers (input/output/config)"));
Serial.println(F("i2cscan list I2C slaves (touch controller check)"));
Serial.println(F("key 0xNN inject key bits: 0x8000=UP 0x4000=DN 0x2000=OK 0x1000=REF"));
Serial.println(F("selftest colour bars on screen; any key/command resumes"));
Serial.println(F("dump stream current 320x240 framebuffer over serial"));
Serial.println(F("swap 0|1 SPI byte order (colors wrong -> try 0)"));
Serial.println(F("bgr 0|1 red/blue order (red<->blue -> try 1)"));
Serial.println(F("inv 0|1 panel color invert"));
Serial.println(F("mir 0|1 X mirror (layout mirrored -> try 0)"));
Serial.println(F("reset wipe NVS and reboot"));
}
static void print_stat()
{
Serial.println(F("--- stat ---"));
Serial.printf("device : %s\n", g_ui.device_id);
Serial.printf("screen : %s\n", screen_name(g_ui.screen));
Serial.printf("wifi : %s ssid=%s rssi=%d\n",
WiFi.status() == WL_CONNECTED ? "connected" : "down", g_ui.ssid, g_ui.rssi);
Serial.printf("ip : %s\n", WiFi.localIP().toString().c_str());
Serial.printf("api : %s\n", g_ui.api);
Serial.printf("token : %d bytes user=%s\n", (int)strlen(g_token), g_ui.owner);
if (g_ui.code[0]) Serial.printf("pair code : %s (%ds left)\n", g_ui.code, g_ui.code_left);
else Serial.println(F("pair code : -"));
Serial.printf("bodies : %d, sel=%d\n", g_snap.count, g_ui.sel);
icon_store_dump();
Serial.printf("uptime : %lus\n", (unsigned long)(millis() / 1000));
}
static void handle_command(char *line)
{
while (*line == ' ') line++;
char *sp = strchr(line, ' ');
if (sp) *sp++ = 0;
static char s_none[1] = "";
char *args = sp ? sp : s_none;
g_ui_paused = false;
if (!strcmp(line, "help")) {
print_help();
} else if (!strcmp(line, "wifi")) {
char *pass = strchr(args, ' ');
if (pass) { *pass++ = 0; while (*pass == ' ') pass++; }
if (!args[0]) { Serial.println(F("usage: wifi <ssid> [password]")); return; }
store_set_str(K_SSID, args);
store_set_str(K_PASS, pass ? pass : "");
Serial.printf("[cmd] wifi ssid=%s pass=%d chars\n", args, pass ? (int)strlen(pass) : 0);
WiFi.disconnect();
wifi_connect();
} else if (!strcmp(line, "api")) {
if (!args[0]) { Serial.println(F("usage: api <url>")); return; }
store_set_str(K_API, args);
strlcpy(g_ui.api, args, sizeof(g_ui.api));
Serial.printf("[cmd] api=%s\n", g_ui.api);
if (g_token[0]) load_data(true); else start_pairing();
} else if (!strcmp(line, "pair")) {
g_token[0] = 0;
store_erase(K_TOKEN);
start_pairing();
} else if (!strcmp(line, "reload")) {
load_data(true);
} else if (!strcmp(line, "portal")) {
start_provision();
} else if (!strcmp(line, "stat")) {
print_stat();
} else if (!strcmp(line, "keys")) {
Serial.printf("raw=0x%04X read=0x%04X stable=0x%04X (KEY0=8000 KEY1=4000 KEY2=2000 KEY3=1000 BOOT=bit0)\n",
xl_keys_raw(), xl_keys_read(), s_keys_stable);
} else if (!strcmp(line, "xlreg")) {
xl_dump_regs();
} else if (!strcmp(line, "i2cscan")) {
xl_i2c_scan();
} else if (!strcmp(line, "selftest")) {
disp_selftest();
g_ui_paused = true;
Serial.println(F("[disp] selftest on screen; send any command or press a key to resume"));
return;
} else if (!strcmp(line, "key")) {
uint16_t bits = (uint16_t)strtoul(args, NULL, 0);
if (!bits) { Serial.println(F("usage: key 8000|4000|2000|1000")); return; }
Serial.printf("[cmd] inject key 0x%04X\n", bits);
on_key_press(bits);
} else if (!strcmp(line, "dump")) {
const uint16_t *fb = disp_fb_ptr();
if (!fb) { Serial.println(F("[dump] no framebuffer")); return; }
const uint8_t *p = (const uint8_t *)fb;
const int total = LCD_WIDTH * LCD_HEIGHT * 2;
Serial.print(F("[FB]"));
/* 一次 write 15 万字节会挤爆 UART 发送缓冲(丢字节 -> 抓屏错位),分块限速发 */
for (int off = 0; off < total; off += 128) {
int n = (total - off < 128) ? (total - off) : 128;
while (Serial.availableForWrite() < n) delay(1);
Serial.write(p + off, n);
}
Serial.println(F("[FBEND]"));
return;
} else if (!strcmp(line, "swap")) {
disp_set_byteswap(atoi(args)); Serial.printf("[disp] byteswap=%d\n", atoi(args));
} else if (!strcmp(line, "bgr")) {
disp_set_bgr(atoi(args)); Serial.printf("[disp] bgr=%d\n", atoi(args));
} else if (!strcmp(line, "inv")) {
disp_set_invert(atoi(args)); Serial.printf("[disp] invert=%d\n", atoi(args));
} else if (!strcmp(line, "mir")) {
disp_set_mirror(atoi(args), false); Serial.printf("[disp] mirror_x=%d\n", atoi(args));
} else if (!strcmp(line, "reset")) {
Serial.println(F("[cmd] wiping NVS"));
store_erase(K_SSID); store_erase(K_PASS); store_erase(K_API);
store_erase(K_TOKEN); store_erase(K_USER);
delay(200);
ESP.restart();
} else {
Serial.printf("[cmd] unknown '%s' (help)\n", line);
}
g_dirty = true;
}
static void serial_tick()
{
static char buf[160];
static size_t len = 0;
while (Serial.available()) {
char c = (char)Serial.read();
if ((unsigned char)c < 0x20 && c != '\r' && c != '\n') continue; /* 丢掉噪声控制字符 */
if (c == '\r') continue;
if (c == '\n') {
buf[len] = 0;
if (len) handle_command(buf);
len = 0;
} else if (len < sizeof(buf) - 1) {
buf[len++] = c;
}
}
}
/* ---------------- Arduino 入口 ---------------- */
void setup()
{
Serial.begin(115200);
delay(400);
Serial.println(F("\n=== COSMO ORBITAL TERMINAL ==="));
store_begin();
if (!xl_begin()) Serial.println(F("[xl] XL9555 not responding (keys/LCD power may fail)"));
pinMode(PIN_KEY_BOOT, INPUT_PULLUP);
build_identity();
if (!disp_init()) Serial.println(F("[disp] init failed"));
bool has_token = store_get_str(K_TOKEN, g_token, sizeof(g_token));
if (!has_token) g_token[0] = 0;
Serial.printf("[store] token=%s\n", g_token[0] ? "loaded" : "none");
set_screen(SC_SPLASH);
ui_draw(g_ui);
delay(900);
char ssid[33];
if (!store_get_str(K_SSID, ssid, sizeof(ssid)) || !ssid[0]) start_provision();
else wifi_connect();
}
void loop()
{
serial_tick();
uint32_t now = millis();
if (!g_ui_paused) {
switch (g_ui.screen) {
case SC_PROVISION:
portal_loop();
if (portal_saved()) {
Serial.println(F("[portal] saved, rebooting"));
delay(800);
ESP.restart();
}
break;
case SC_CONNECTING:
wifi_tick();
break;
case SC_PAIR:
pair_tick(now);
break;
case SC_LIST:
case SC_DETAIL:
run_tick(now);
break;
case SC_ERROR:
if ((int32_t)(now - g_retry_at) >= 0) { g_retry_at = now + 15000; load_data(true); }
break;
default:
break;
}
keys_tick(now);
}
/* 连接 / 加载页有动画,按 250ms 节拍重绘 */
if ((g_ui.screen == SC_CONNECTING || g_ui.screen == SC_LOADING) && (now / 250) != (s_anim_last / 250)) {
s_anim_last = now;
g_dirty = true;
}
if (s_flash_until && (int32_t)(now - s_flash_until) >= 0) {
s_flash_until = 0;
g_ui.key_flash = 0;
g_dirty = true;
}
if (g_dirty && !g_ui_paused) {
g_dirty = false;
ui_draw(g_ui);
}
delay(5);
}

View File

@ -0,0 +1,221 @@
#include <Arduino.h>
#include <HTTPClient.h>
#include <ArduinoJson.h>
#include <string.h>
#include "api.h"
/* 中文标题被过滤空了就用 event_type 兜底:"close_approach" -> "CLOSE APPROACH" */
static void copy_upper(char *dst, size_t cap, const char *src)
{
size_t j = 0;
for (const char *p = src; *p && j + 1 < cap; p++) {
unsigned char c = (unsigned char)*p;
if (c >= 0x80) continue;
if (c == '_') c = ' ';
if (c >= 'a' && c <= 'z') c -= 32;
dst[j++] = (char)c;
}
dst[j] = 0;
}
static void copy_iso(char *dst, size_t cap, const char *src)
{
/* "2026-09-20T08:00:00" -> "2026-09-20 08:00" */
strncpy(dst, src, cap - 1);
dst[cap - 1] = 0;
for (char *p = dst; *p; p++) if (*p == 'T') *p = ' ';
if (strlen(dst) > 16) dst[16] = 0;
}
/* UTF-8 安全截断:不能把一个汉字的多字节序列切一半 */
static void copy_utf8(char *dst, size_t cap, const char *src)
{
size_t j = 0;
while (src[j] && j < cap - 1) {
unsigned char c = (unsigned char)src[j];
int l = (c >= 0xF0) ? 4 : (c >= 0xE0) ? 3 : (c >= 0xC0) ? 2 : 1;
for (int k = 0; k < l; k++) if (!src[j + k]) { l = k; break; }
if (!l || j + l > cap - 1) break;
memcpy(dst + j, src + j, l);
j += l;
}
dst[j] = 0;
}
/* 事件标题优先中文:屏宽有限,含中文时丢掉括号里的英文别名
("木星 冲 (Jupiter Opposition)" -> "木星 冲") */
static void copy_title(char *dst, size_t cap, const char *src)
{
bool has_cjk = false;
for (const unsigned char *p = (const unsigned char *)src; *p; p++) if (*p >= 0x80) { has_cjk = true; break; }
char buf[72];
size_t n = 0;
for (; src[n] && n + 1 < sizeof(buf); n++) {
if (has_cjk && src[n] == '(') break;
buf[n] = src[n];
}
buf[n] = 0;
while (n && (buf[n - 1] == ' ' || buf[n - 1] == '(')) buf[--n] = 0;
copy_utf8(dst, cap, buf);
}
static bool http_json(const char *url, const char *body, const char *token,
JsonDocument &doc, int *status)
{
HTTPClient http;
http.setConnectTimeout(6000);
http.setTimeout(8000);
http.begin(url);
http.addHeader("Content-Type", "application/json");
if (token && *token) http.addHeader("Authorization", String("Bearer ") + token);
int code = body ? http.POST(body) : http.GET();
if (status) *status = code;
/* 只认 2xx:401「设备已解绑」这类错误响应体同样是合法 JSON,
当成成功会让关注列表被清空成 0 个天体,掩盖掉重新配对的流程 */
if (code < 200 || code >= 300) { http.end(); return false; }
DeserializationError err = deserializeJson(doc, http.getStream());
http.end();
if (err) { Serial.printf("[api] json: %s\n", err.c_str()); return false; }
return true;
}
bool api_pair_code(const char *base, const char *device_id, const char *name,
char *code, int code_cap, int *expires_in, bool *bound,
char *owner, size_t owner_cap)
{
if (owner && owner_cap) owner[0] = 0;
if (code && code_cap) code[0] = 0;
if (expires_in) *expires_in = 0;
if (bound) *bound = false;
JsonDocument req;
req["device_id"] = device_id;
req["name"] = name;
String payload;
serializeJson(req, payload);
String url = String(base) + "/terminal/pair/code";
JsonDocument doc;
int status = 0;
if (!http_json(url.c_str(), payload.c_str(), NULL, doc, &status)) {
Serial.printf("[api] pair/code http=%d\n", status);
return false;
}
const char *st = doc["status"] | "";
if (strcmp(st, "bound") == 0) {
if (bound) *bound = true;
strlcpy(owner, doc["username"] | "", owner_cap);
return true;
}
strlcpy(code, doc["code"] | "", code_cap);
if (expires_in) *expires_in = doc["expires_in"] | 0;
Serial.printf("[api] code=%s expires=%ds\n", code, expires_in ? *expires_in : 0);
return code[0] != 0;
}
PairResult api_pair_status(const char *base, const char *device_id, const char *code,
char *token, size_t token_cap, char *owner, size_t owner_cap)
{
if (token && token_cap) token[0] = 0;
if (owner && owner_cap) owner[0] = 0;
String url = String(base) + "/terminal/pair/status?device_id=" + device_id + "&code=" + code;
JsonDocument doc;
int status = 0;
if (!http_json(url.c_str(), NULL, NULL, doc, &status)) {
Serial.printf("[api] pair/status http=%d\n", status);
return PR_ERROR;
}
const char *st = doc["status"] | "";
if (owner && owner_cap) strlcpy(owner, doc["username"] | "", owner_cap);
if (strcmp(st, "bound") == 0) {
strlcpy(token, doc["access_token"] | "", token_cap);
return token[0] ? PR_BOUND : PR_ERROR;
}
if (strcmp(st, "pending") == 0) return PR_PENDING;
if (strcmp(st, "expired") == 0) return PR_EXPIRED;
/* invalid_code / unknown / unbound:屏幕上的码已经不是当前有效码 */
return PR_INVALID;
}
bool api_follows(const char *base, const char *token, Snapshot *out, int *http_status)
{
String url = String(base) + "/terminal/follows";
JsonDocument doc;
if (!http_json(url.c_str(), NULL, token, doc, http_status)) {
Serial.printf("[api] follows http=%d\n", http_status ? *http_status : 0);
return false;
}
memset(out, 0, sizeof(*out));
strlcpy(out->username, doc["username"] | "", sizeof(out->username));
copy_iso(out->server_time, sizeof(out->server_time), doc["server_time"] | "");
out->count = 0;
out->fetched_ms = millis();
for (JsonVariant b : doc["bodies"].as<JsonArray>()) {
if (out->count >= MAX_BODIES) break;
BodyData &d = out->bodies[out->count++];
strlcpy(d.id, b["id"] | "", sizeof(d.id));
d.icon_ver = b["icon_ver"] | 0u;
strlcpy(d.name, b["name"] | "?", sizeof(d.name));
copy_utf8(d.name_zh, sizeof(d.name_zh), b["name_zh"] | "");
copy_utf8(d.desc, sizeof(d.desc), b["description"] | "");
strlcpy(d.type, b["type"] | "", sizeof(d.type));
d.active = b["is_active"].as<bool>();
JsonVariant p = b["position"];
if (!p.isNull()) {
d.x = p["x"] | 0.0f; d.y = p["y"] | 0.0f; d.z = p["z"] | 0.0f;
d.dist = p["distance_au"] | 0.0f;
d.speed = p["speed_km_s"] | 0.0f;
d.has_vel = !p["vx"].isNull();
if (d.has_vel) { d.vx = p["vx"] | 0.0f; d.vy = p["vy"] | 0.0f; d.vz = p["vz"] | 0.0f; }
copy_iso(d.pos_time, sizeof(d.pos_time), p["time"] | "");
}
for (JsonVariant e : b["events"].as<JsonArray>()) {
if (d.ev_count >= MAX_EVENTS) break;
copy_title(d.ev[d.ev_count], sizeof(d.ev[0]), e["title"] | "");
if (!d.ev[d.ev_count][0])
copy_upper(d.ev[d.ev_count], sizeof(d.ev[0]), e["event_type"] | "");
copy_iso(d.ev_date[d.ev_count], sizeof(d.ev_date[0]), e["event_time"] | "");
if (strlen(d.ev_date[d.ev_count]) > 10) d.ev_date[d.ev_count][10] = 0;
d.ev_count++;
}
}
Serial.printf("[api] follows user=%s bodies=%d\n", out->username, out->count);
return true;
}
bool api_icon(const char *base, const char *token, const char *body_id, int size,
void *dst, size_t cap, int *http_status)
{
String url = String(base) + "/terminal/bodies/" + body_id + "/icon?size=" + size;
HTTPClient http;
http.setConnectTimeout(6000);
http.setTimeout(8000);
http.begin(url);
if (token && *token) http.addHeader("Authorization", String("Bearer ") + token);
int code = http.GET();
if (http_status) *http_status = code;
if (code != 200) { http.end(); return false; }
/* 后端给的是定长裸数据,Content-Length 不符就说明版本/尺寸对不上 */
int len = http.getSize();
if (len >= 0 && (size_t)len != cap) { http.end(); return false; }
Stream &s = http.getStream();
size_t got = 0;
while (got < cap) {
int n = s.readBytes((char *)dst + got, cap - got);
if (n <= 0) break;
got += (size_t)n;
}
http.end();
if (got != cap) return false;
/* 后端按大端发(和串口 dump 同一个约定),disp_add_bitmap 要的是本机字节序 */
uint16_t *px = (uint16_t *)dst;
for (size_t i = 0; i < cap / 2; i++) px[i] = __builtin_bswap16(px[i]);
return true;
}

View File

@ -0,0 +1,53 @@
/** 后端 terminal 接口:拿配对码 / 轮询绑定结果 / 拉取关注天体快照 */
#pragma once
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
#define MAX_BODIES 6
#define MAX_EVENTS 3
struct BodyData {
char id[16]; /* 后端天体 id,拉取后台维护的图标要用 */
uint32_t icon_ver; /* 后台维护图标的资源号,0=没维护,用固件内置线稿 */
char name[24];
char name_zh[24]; /* 中文名,缺失时为空串 */
char type[16];
char desc[108]; /* 中文简介,UTF-8 安全截断到 36 个汉字 */
float x, y, z;
float vx, vy, vz;
float dist, speed;
bool has_vel;
bool active;
char pos_time[20]; /* "2026-09-20 08:00" */
char ev[MAX_EVENTS][28];
char ev_date[MAX_EVENTS][12];
uint8_t ev_count;
};
struct Snapshot {
char username[24];
char server_time[20];
uint8_t count;
uint32_t fetched_ms;
BodyData bodies[MAX_BODIES];
};
enum PairResult { PR_PENDING, PR_BOUND, PR_EXPIRED, PR_INVALID, PR_ERROR };
/** 请求 6 位配对码;已绑定时 bound=true 且回填 owner */
bool api_pair_code(const char *base, const char *device_id, const char *name,
char *code, int code_cap, int *expires_in, bool *bound,
char *owner, size_t owner_cap);
/** 轮询绑定状态;PR_BOUND 时 token 已写入(token 只下发一次,调用方必须立刻落盘) */
PairResult api_pair_status(const char *base, const char *device_id, const char *code,
char *token, size_t token_cap, char *owner, size_t owner_cap);
/** 拉取关注天体;失败时返回 false,http 非 0 时为状态码(401 表示 token 失效) */
bool api_follows(const char *base, const char *token, Snapshot *out, int *http_status);
/** 拉取后台维护的天体图标:size x size 的 RGB565 裸点阵(接口按大端发,这里转成本机
* 字节序),可直接喂给 disp_add_bitmap。尺寸不符或读不满都算失败(404=没维护图标) */
bool api_icon(const char *base, const char *token, const char *body_id, int size,
void *dst, size_t cap, int *http_status);

View File

@ -0,0 +1,41 @@
/**
* 正点原子 ATK-DNESP32S3 + 2.4寸 TFTLCD 模块(ATK-MD0240 / ST7789V) 引脚定义
* 依据官方例程 Standard Routine/10_spilcd 的 BSP 头文件,横屏 320x240
*/
#pragma once
#include <stdint.h>
/* SPI2 总线(与 SD 卡共用) */
#define PIN_SPI_SCK 12
#define PIN_SPI_MOSI 11
#define PIN_SPI_MISO 13
#define LCD_SPI_HOST SPI2_HOST
/* 4 线 SPI LCD 控制脚:RST/PWR 由板上 XL9555 扩展IO控制 */
#define PIN_LCD_DC 40
#define PIN_LCD_CS 21
/* 板上 I2C(MYIIC):XL9555 IO 扩展器 */
#define PIN_I2C_SDA 41
#define PIN_I2C_SCL 42
#define XL9555_ADDR 0x20
/* XL9555 寄存器 */
#define XL_REG_INPUT0 0x00
#define XL_REG_OUTPUT0 0x02
#define XL_REG_CONFIG0 0x06
/* XL9555 扩展脚(bit 掩码:低字节=P0,高字节=P1) */
#define XL_IO_LCD_BL 0x0100
#define XL_IO_SLCD_RST 0x0400
#define XL_IO_SLCD_PWR 0x0800
#define XL_IO_KEY3 0x1000
#define XL_IO_KEY2 0x2000
#define XL_IO_KEY1 0x4000
#define XL_IO_KEY0 0x8000
/* BOOT 按键 = GPIO0 */
#define PIN_KEY_BOOT 0
#define LCD_WIDTH 320
#define LCD_HEIGHT 240

View File

@ -0,0 +1,465 @@
#include <Arduino.h>
#include <string.h>
#include <stdlib.h>
#include <esp_heap_caps.h>
#include "driver/spi_master.h"
#include "esp_lcd_panel_io.h"
#include "esp_lcd_panel_ops.h"
#include "esp_lcd_panel_st7789.h"
#include "board_config.h"
#include "display.h"
#include "expander.h"
#include "font_asc2.h"
#include "font_cjk.h"
/* 官方例程跑 40MHz,这里用 20MHz:杜邦/排针连接下更稳,整屏刷新仍只要 ~12ms */
#define LCD_PCLK_HZ 20000000
#define FLUSH_ROWS 20
static esp_lcd_panel_io_handle_t s_io;
static esp_lcd_panel_handle_t s_panel;
static uint16_t *s_fb;
static bool s_byteswap = true; /* SPI 先发高字节,帧缓冲按大端存放 */
static bool s_bgr = false; /* ST7789 红蓝序,点屏后用 swap/bgr 命令校正 */
static bool s_mx = true, s_my = false;
static inline uint16_t pack(uint16_t c)
{
if (s_bgr) c = (uint16_t)(((c & 0xF800) >> 11) | (c & 0x07E0) | ((c & 0x001F) << 11));
if (s_byteswap) c = (uint16_t)((c >> 8) | (c << 8));
return c;
}
bool disp_init()
{
s_fb = (uint16_t *)heap_caps_malloc(LCD_WIDTH * LCD_HEIGHT * 2, MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT);
if (!s_fb) { Serial.println(F("[disp] PSRAM alloc failed")); return false; }
/* 屏的 RST/PWR 由 XL9555 提供,时序照官方 spilcd_init */
xl_pin_write(XL_IO_SLCD_RST, 0); delay(100);
xl_pin_write(XL_IO_SLCD_RST, 1); delay(100);
esp_err_t e;
spi_bus_config_t bus;
memset(&bus, 0, sizeof(bus));
bus.mosi_io_num = PIN_SPI_MOSI;
bus.miso_io_num = PIN_SPI_MISO;
bus.sclk_io_num = PIN_SPI_SCK;
bus.quadwp_io_num = -1;
bus.quadhd_io_num = -1;
bus.max_transfer_sz = LCD_WIDTH * FLUSH_ROWS * 2;
e = spi_bus_initialize(LCD_SPI_HOST, &bus, SPI_DMA_CH_AUTO);
if (e != ESP_OK) { Serial.printf("[disp] spi_bus_initialize: %d\n", e); return false; }
esp_lcd_panel_io_spi_config_t io_cfg;
memset(&io_cfg, 0, sizeof(io_cfg));
io_cfg.cs_gpio_num = PIN_LCD_CS;
io_cfg.dc_gpio_num = PIN_LCD_DC;
io_cfg.spi_mode = 0;
io_cfg.pclk_hz = LCD_PCLK_HZ;
io_cfg.trans_queue_depth = 2;
io_cfg.lcd_cmd_bits = 8;
io_cfg.lcd_param_bits = 8;
e = esp_lcd_new_panel_io_spi((esp_lcd_spi_bus_handle_t)LCD_SPI_HOST, &io_cfg, &s_io);
if (e != ESP_OK) { Serial.printf("[disp] new_panel_io_spi: %d\n", e); return false; }
esp_lcd_panel_dev_config_t p_cfg;
memset(&p_cfg, 0, sizeof(p_cfg));
p_cfg.reset_gpio_num = -1; /* 复位已由 XL9555 做过 */
p_cfg.rgb_ele_order = LCD_RGB_ELEMENT_ORDER_RGB;
p_cfg.data_endian = LCD_RGB_DATA_ENDIAN_BIG;
p_cfg.bits_per_pixel = 16;
e = esp_lcd_new_panel_st7789(s_io, &p_cfg, &s_panel);
if (e != ESP_OK) { Serial.printf("[disp] new_panel_st7789: %d\n", e); return false; }
esp_lcd_panel_reset(s_panel);
esp_lcd_panel_invert_color(s_panel, true); /* ST7789V 需要色反转 */
esp_lcd_panel_init(s_panel);
esp_lcd_panel_disp_on_off(s_panel, true);
esp_lcd_panel_swap_xy(s_panel, true); /* 竖屏控制器 -> 320x240 横屏 */
esp_lcd_panel_mirror(s_panel, s_mx, s_my);
xl_pin_write(XL_IO_SLCD_PWR, 1); /* 背光随屏电源打开 */
Serial.printf("[disp] ST7789 %dx%d ok, fb=%p\n", LCD_WIDTH, LCD_HEIGHT, (void *)s_fb);
return true;
}
void disp_clear(uint16_t color)
{
disp_fill(0, 0, LCD_WIDTH, LCD_HEIGHT, color);
}
void disp_pixel(int x, int y, uint16_t color)
{
if ((unsigned)x >= LCD_WIDTH || (unsigned)y >= LCD_HEIGHT) return;
s_fb[y * LCD_WIDTH + x] = pack(color);
}
void disp_fill(int x, int y, int w, int h, uint16_t color)
{
if (x < 0) { w += x; x = 0; }
if (y < 0) { h += y; y = 0; }
if (x + w > LCD_WIDTH) w = LCD_WIDTH - x;
if (y + h > LCD_HEIGHT) h = LCD_HEIGHT - y;
if (w <= 0 || h <= 0) return;
uint16_t c = pack(color);
for (int row = y; row < y + h; row++) {
uint16_t *dst = s_fb + row * LCD_WIDTH + x;
for (int col = 0; col < w; col++) dst[col] = c;
}
}
void disp_rect(int x, int y, int w, int h, uint16_t color)
{
disp_hline(x, y, w, color);
disp_hline(x, y + h - 1, w, color);
for (int row = y; row < y + h; row++) { disp_pixel(x, row, color); disp_pixel(x + w - 1, row, color); }
}
void disp_hline(int x, int y, int w, uint16_t color)
{
disp_fill(x, y, w, 1, color);
}
void disp_disc(int cx, int cy, int r, uint16_t color)
{
for (int dy = -r; dy <= r; dy++) {
int dx = (int)sqrtf((float)(r * r - dy * dy));
disp_fill(cx - dx, cy + dy, dx * 2 + 1, 1, color);
}
}
/* ---- 背景 / 切角面板 / 图标叠加 ---------------------------------------- */
static uint32_t s_rng;
static uint32_t lcg(void) { s_rng = s_rng * 1664525u + 1013904223u; return s_rng >> 8; }
void disp_bg(void)
{
disp_clear(C_BG);
s_rng = 20261004u; /* 固定种子:每帧星点位置不变,不闪 */
static const uint16_t lvl[3] = { C_TRACE, C_STAR, C_CYAN_DIM };
for (int i = 0; i < 110; i++) {
int x = lcg() % LCD_WIDTH, y = lcg() % LCD_HEIGHT;
int r = lcg() % 100;
uint16_t c = lvl[(r < 4) ? 2 : (r < 30) ? 1 : 0];
disp_pixel(x, y, c);
if (r < 4) { disp_pixel(x + 1, y, c); disp_pixel(x, y + 1, c); disp_pixel(x + 1, y + 1, c); }
}
/* 四角电路走线:3 点折线,端点一个过孔 */
static const int tr[4][6] = {
{ 2, 34, 30, 34, 30, 52 },
{ 317, 40, 292, 40, 292, 20 },
{ 4, 208, 38, 208, 38, 200 },
{ 316, 202, 288, 202, 288, 214 },
};
for (int i = 0; i < 4; i++) {
int px = tr[i][0], py = tr[i][1];
for (int k = 2; k <= 4; k += 2) {
int nx = tr[i][k], ny = tr[i][k + 1];
if (ny == py) disp_hline(min(px, nx), py, abs(nx - px) + 1, C_TRACE);
else for (int y = min(py, ny); y <= max(py, ny); y++) disp_pixel(px, y, C_TRACE);
px = nx; py = ny;
}
disp_pixel(tr[i][4], tr[i][5], C_CYAN_DIM);
}
}
static int cham_inset(int j, int h, int cut)
{
if (j < cut) return cut - j;
if (j >= h - cut) return j - (h - cut - 1);
return 0;
}
static void cham_outline(int x, int y, int w, int h, int cut, uint16_t color)
{
for (int j = 0; j < h; j++) {
int in = cham_inset(j, h, cut);
if (j == 0 || j == h - 1) {
for (int i = cut; i < w - cut; i++) disp_pixel(x + i, y + j, color);
} else {
disp_pixel(x + in, y + j, color);
disp_pixel(x + w - 1 - in, y + j, color);
}
}
}
static int clamp_cut(int w, int h, int cut)
{
if (cut * 2 >= h) cut = (h - 1) / 2;
if (cut * 2 >= w) cut = (w - 1) / 2;
return cut < 0 ? 0 : cut;
}
void disp_panel(int x, int y, int w, int h, int cut, uint16_t fill, uint16_t border)
{
cut = clamp_cut(w, h, cut);
for (int j = 0; j < h; j++) {
int in = cham_inset(j, h, cut);
disp_fill(x + in, y + j, w - 2 * in, 1, fill);
}
cham_outline(x, y, w, h, cut, border);
}
void disp_panel_glow(int x, int y, int w, int h, int cut, uint16_t glow)
{
cham_outline(x - 1, y - 1, w + 2, h + 2, clamp_cut(w + 2, h + 2, cut + 1), glow);
}
/* 帧缓冲按 pack() 后的样子存放,叠加前先还原成普通 RGB565 */
static inline uint16_t unpack(uint16_t v)
{
if (s_byteswap) v = (uint16_t)((v >> 8) | (v << 8));
if (s_bgr) v = (uint16_t)(((v & 0xF800) >> 11) | (v & 0x07E0) | ((v & 0x001F) << 11));
return v;
}
void disp_add_bitmap(int x, int y, int w, int h, const uint16_t *px)
{
if (!px) return;
for (int j = 0; j < h; j++) {
int yy = y + j;
if ((unsigned)yy >= LCD_HEIGHT) continue;
const uint16_t *src = px + (size_t)j * w;
uint16_t *dst = s_fb + (size_t)yy * LCD_WIDTH;
for (int i = 0; i < w; i++) {
uint16_t s = src[i];
int xx = x + i;
if (!s || (unsigned)xx >= LCD_WIDTH) continue; /* 黑底直接不加 */
uint16_t d = unpack(dst[xx]);
int r = ((d >> 11) & 0x1F) + ((s >> 11) & 0x1F);
int g = ((d >> 5) & 0x3F) + ((s >> 5) & 0x3F);
int b = (d & 0x1F) + (s & 0x1F);
if (r > 31) r = 31;
if (g > 63) g = 63;
if (b > 31) b = 31;
dst[xx] = pack((uint16_t)((r << 11) | (g << 5) | b));
}
}
}
void disp_ring(int cx, int cy, int r, uint16_t color)
{
int x = r, y = 0, err = 1 - r;
while (x >= y) {
disp_pixel(cx + x, cy + y, color); disp_pixel(cx - x, cy + y, color);
disp_pixel(cx + x, cy - y, color); disp_pixel(cx - x, cy - y, color);
disp_pixel(cx + y, cy + x, color); disp_pixel(cx - y, cy + x, color);
disp_pixel(cx + y, cy - x, color); disp_pixel(cx - y, cy - x, color);
y++;
if (err < 0) err += 2 * y + 1;
else { x--; err += 2 * (y - x) + 1; }
}
}
void disp_radar(int cx, int cy, int r)
{
disp_ring(cx, cy, r, C_CYAN_DIM);
disp_ring(cx, cy, r * 2 / 3, C_TRACE);
disp_ring(cx, cy, r / 3, C_TRACE);
disp_hline(cx - r - 4, cy, 2 * r + 9, C_TRACE);
for (int dy = -r - 4; dy <= r + 4; dy++) disp_pixel(cx, cy + dy, C_TRACE);
for (int k = 0; k < 8; k++) {
float a = k * 3.1415926f / 4.0f;
for (int t = 0; t <= 5; t++) {
float rr = (float)(r - 2 - t);
disp_pixel(cx + (int)(cosf(a) * rr), cy + (int)(sinf(a) * rr), C_CYAN_DIM);
}
}
}
/* ---- 字模:行式,每行 (width+7)/8 字节,MSB 为最左像素 ---- */
static const uint8_t *glyph_of(char ch, uint8_t size, int *bytes_per_row)
{
int idx = (uint8_t)ch - ' ';
if (idx < 0 || idx > 94) idx = 0;
*bytes_per_row = (size >= 32) ? 2 : 1;
return (size >= 32) ? asc2_3216[idx] : asc2_1608[idx];
}
static int utf8_next(const char *s, uint32_t *cp)
{
uint8_t c = (uint8_t)s[0];
if (c < 0x80) { *cp = c; return 1; }
if ((c & 0xE0) == 0xC0 && ((uint8_t)s[1] & 0xC0) == 0x80) {
*cp = ((uint32_t)(c & 0x1F) << 6) | ((uint8_t)s[1] & 0x3F);
return 2;
}
if ((c & 0xF0) == 0xE0 && ((uint8_t)s[1] & 0xC0) == 0x80 && ((uint8_t)s[2] & 0xC0) == 0x80) {
*cp = ((uint32_t)(c & 0x0F) << 12) | ((uint32_t)((uint8_t)s[1] & 0x3F) << 6)
| ((uint8_t)s[2] & 0x3F);
return 3;
}
*cp = c;
return 1;
}
static void glyph_blit(int x, int y, const uint8_t *rows, int bpr, int gw, int gh,
int f, uint16_t fg, uint16_t bg)
{
for (int row = 0; row < gh; row++) {
const uint8_t *lr = rows + row * bpr;
for (int col = 0; col < gw; col++) {
uint16_t c = (lr[col / 8] & (0x80 >> (col % 8))) ? fg : bg;
if (f == 1) disp_pixel(x + col, y + row, c);
else disp_fill(x + col * f, y + row * f, f, f, c);
}
}
}
/** 一个字符占的横向推进(含 1px 字距) */
static int char_advance(uint32_t cp, uint8_t size, uint8_t scale)
{
if (scale < 1) scale = 1;
if (cp < 0x80) return (size / 2 + 1) * scale;
return (CJK_CELL + 1) * ((size >= 32) ? 2 * scale : scale);
}
static const uint8_t kMissingGlyph[32] = {
0xFF, 0xFF,
0x80, 0x01, 0x80, 0x01, 0x80, 0x01, 0x80, 0x01, 0x80, 0x01, 0x80, 0x01, 0x80, 0x01,
0x80, 0x01, 0x80, 0x01, 0x80, 0x01, 0x80, 0x01, 0x80, 0x01, 0x80, 0x01, 0x80, 0x01,
0xFF, 0xFF,
};
static int disp_char(int x, int y, uint32_t cp, uint8_t size, uint8_t scale,
uint16_t fg, uint16_t bg)
{
if (scale < 1) scale = 1;
if (cp < 0x80) {
int bpr = 1;
glyph_blit(x, y, glyph_of((char)cp, size, &bpr), bpr, size / 2, size, scale, fg, bg);
} else {
int f = (size >= 32) ? 2 * scale : scale;
const uint8_t *g = cjk_glyph(cp);
glyph_blit(x, y, g ? g : kMissingGlyph, 2, CJK_CELL, CJK_CELL, f, fg, bg);
}
return char_advance(cp, size, scale);
}
int disp_text_width(const char *s, uint8_t size, uint8_t scale)
{
if (!s) return 0;
int total = 0;
while (*s) {
uint32_t cp;
s += utf8_next(s, &cp);
total += char_advance(cp, size, scale);
}
return total;
}
void disp_text(int x, int y, const char *s, uint8_t size, uint16_t fg, uint16_t bg, uint8_t scale)
{
if (!s) return;
while (*s) {
uint32_t cp;
int l = utf8_next(s, &cp);
x += disp_char(x, y, cp, size, scale, fg, bg);
s += l;
}
}
void disp_text_center(int x, int y, int w, const char *s, uint8_t size, uint16_t fg, uint16_t bg, uint8_t scale)
{
disp_text(x + (w - disp_text_width(s, size, scale)) / 2, y, s, size, fg, bg, scale);
}
/** 放不下就在字符边界截断并补 ".."(不能按字节切,否则中文成半个 UTF-8 序列) */
void disp_text_clipped(int x, int y, int maxw, const char *s, uint8_t size, uint16_t fg, uint16_t bg)
{
if (!s) return;
if (disp_text_width(s, size, 1) <= maxw) { disp_text(x, y, s, size, fg, bg); return; }
int dots = disp_text_width("..", size, 1);
int used = 0;
while (*s) {
uint32_t cp;
int l = utf8_next(s, &cp);
int adv = char_advance(cp, size, 1);
if (used + adv + dots > maxw) break;
disp_char(x + used, y, cp, size, 1, fg, bg);
used += adv;
s += l;
}
disp_text(x + used, y, "..", size, fg, bg);
}
int disp_text_wrap(int x, int y, int maxw, const char *s, uint8_t size, uint16_t fg, uint16_t bg, int max_lines)
{
if (!s) return y;
char line[192];
int n = 0, cur = 0, rows = 0;
const char *p = s;
while (*p && rows < max_lines) {
int tl = 0, tadv = 0;
if ((uint8_t)*p >= 0x80) { /* 中文:一个字一个 token */
uint32_t cp;
tl = utf8_next(p, &cp);
tadv = char_advance(cp, size, 1);
} else { /* 英文:整个词(连尾部空格)*/
while (p[tl] && (uint8_t)p[tl] < 0x80 && p[tl] != ' ') {
tadv += char_advance((uint8_t)p[tl], size, 1);
tl++;
}
while (p[tl] == ' ') { tadv += char_advance(' ', size, 1); tl++; }
}
if (cur && cur + tadv > maxw) {
line[n] = 0;
disp_text(x, y, line, size, fg, bg);
y += size + 3;
rows++;
n = 0; cur = 0;
if (rows >= max_lines) break;
}
for (int i = 0; i < tl && n < (int)sizeof(line) - 4; i++) line[n++] = p[i];
cur += tadv;
p += tl;
}
line[n] = 0;
if (n) { disp_text(x, y, line, size, fg, bg); y += size + 3; }
return y;
}
const uint16_t *disp_fb_ptr() { return s_fb; }
void disp_flush()
{
if (!s_panel) return;
for (int y0 = 0; y0 < LCD_HEIGHT; y0 += FLUSH_ROWS) {
int rows = (LCD_HEIGHT - y0 < FLUSH_ROWS) ? (LCD_HEIGHT - y0) : FLUSH_ROWS;
esp_lcd_panel_draw_bitmap(s_panel, 0, y0, LCD_WIDTH, y0 + rows, s_fb + (size_t)y0 * LCD_WIDTH);
}
delay(20); /* 等最后一块 DMA 走完,避免下一次重绘踩到在途缓冲 */
}
void disp_set_byteswap(bool on) { s_byteswap = on; }
void disp_set_bgr(bool on) { s_bgr = on; }
void disp_set_invert(bool on) { if (s_panel) esp_lcd_panel_invert_color(s_panel, on); }
void disp_set_mirror(bool mx, bool my)
{
s_mx = mx; s_my = my;
if (s_panel) esp_lcd_panel_mirror(s_panel, s_mx, s_my);
}
/* 点屏自检:4 条色带 + 边界 + 文字,拍照即可判断字节序/色序/镜像 */
void disp_selftest()
{
static const uint16_t bars[] = { C_RED, C_GREEN, C_BLUE, C_WHITE };
static const char *names[] = { "RED", "GRN", "BLU", "WHT" };
disp_clear(C_BLACK);
for (int i = 0; i < 4; i++) {
int bx = 8 + i * 78;
disp_fill(bx, 30, 70, 90, bars[i]);
disp_text_center(bx, 126, 70, names[i], 16, C_CYAN, C_BLACK);
}
disp_rect(1, 1, LCD_WIDTH - 2, LCD_HEIGHT - 2, C_ORANGE);
disp_text_center(0, 4, LCD_WIDTH, "ATK-DNESP32S3 ST7789 320x240", 16, C_GREEN, C_BLACK);
char msg[48];
snprintf(msg, sizeof(msg), "SWAP=%d BGR=%d MX=%d", (int)s_byteswap, (int)s_bgr, (int)s_mx);
disp_text_center(0, 150, LCD_WIDTH, msg, 16, C_WHITE, C_BLACK);
disp_text_center(0, 172, LCD_WIDTH, "1234567890 ABCDEFGHIJKLMNOP", 16, C_ORANGE, C_BLACK);
disp_disc(160, 214, 14, C_CYAN);
disp_flush();
}

View File

@ -0,0 +1,70 @@
/**
* 320x240 横屏 ST7789V 帧缓冲图形层(帧缓冲放 PSRAM,分块 flush 到屏)
* 设计稿语言:深海军蓝底 + 星点、切角发光面板、青=常态 / 金=强调
*/
#pragma once
#include <stdint.h>
#include <stdbool.h>
/* 配色取自设计稿取色:青=常态信息 金=强调/按键 绿=配网绑定终端风 dim=次要 dim 后缀=弱化 */
#define C_BLACK 0x0000
#define C_WHITE 0xFFFF
#define C_CYAN 0x66DE /* 主青 rgb(98,218,246) 设计稿 #67d9f1 */
#define C_GREEN 0x07E0
#define C_ORANGE 0xFD20
#define C_RED 0xF800
#define C_BLUE 0x001F
#define C_DIM 0x4208 /* 次要文字 rgb(64,64,64) */
#define C_BG 0x0063 /* 屏幕底色 深海军蓝 rgb(0,12,24) */
#define C_PANEL 0x10A4 /* 卡片底色 rgb(16,20,32) */
#define C_SEL 0x10E4 /* 选中卡片底色 rgb(20,30,34) */
#define C_TEXT 0xB77D /* 主文字 浅青白 rgb(181,222,238) 设计稿 #b5edee */
#define C_CYAN_DIM 0x330C /* 未选中边框 / 辉光 rgb(48,97,96) 设计稿 #336161 */
#define C_GOLD 0xE549 /* 主金 rgb(230,170,72) 设计稿 #e4aa49 */
#define C_GOLD_LT 0xFF12 /* 亮金 rgb(255,250,148) 按下/高亮 */
#define C_GOLD_DK 0x6201 /* 暗金 rgb(96,64,16) 金底填充 */
#define C_GOLD_DIM 0x7A80 /* 金色弱化 rgb(120,80,0) */
#define C_STAR 0x1966 /* 中档星点 rgb(24,44,48) */
#define C_TRACE 0x0105 /* 背景电路走线 rgb(0,32,40) */
bool disp_init();
void disp_clear(uint16_t color);
void disp_pixel(int x, int y, uint16_t color);
void disp_fill(int x, int y, int w, int h, uint16_t color);
void disp_rect(int x, int y, int w, int h, uint16_t color);
void disp_hline(int x, int y, int w, uint16_t color);
void disp_disc(int cx, int cy, int r, uint16_t color); /* 实心圆 */
void disp_ring(int cx, int cy, int r, uint16_t color); /* 空心圆 */
/** 整屏背景:C_BG + 固定星点 + 角落走线,替代 disp_clear(C_BLACK) */
void disp_bg(void);
/** 切角(chamfer)面板:cut 为四角切掉的像素边长 */
void disp_panel(int x, int y, int w, int h, int cut, uint16_t fill, uint16_t border);
/** 面板外侧再描一圈低阶色边框,模拟设计稿的辉光 */
void disp_panel_glow(int x, int y, int w, int h, int cut, uint16_t glow);
/** 叠加混合贴内置图标(无 alpha:黑色加上去等于没画,霓虹线条自动发光) */
void disp_add_bitmap(int x, int y, int w, int h, const uint16_t *px);
/** 详情页天体底纹:同心圆 + 十字 + 刻度 */
void disp_radar(int cx, int cy, int r);
/** size=16 -> 8x16 字模, size=32 -> 16x32 字模; scale 把 1 个像素放大成 scale*scale
* 字符串按 UTF-8 解析:ASCII 走 asc2 字模,其余走 16x16 中文字库(缺字画空心方框) */
void disp_text(int x, int y, const char *s, uint8_t size, uint16_t fg, uint16_t bg, uint8_t scale = 1);
/** 含末尾 1px 字距;宽度足够时原样输出,否则在字符边界截断并补 ".." */
int disp_text_width(const char *s, uint8_t size, uint8_t scale = 1);
void disp_text_center(int x, int y, int w, const char *s, uint8_t size, uint16_t fg, uint16_t bg, uint8_t scale = 1);
void disp_text_clipped(int x, int y, int maxw, const char *s, uint8_t size, uint16_t fg, uint16_t bg);
/** 按词(ASCII)/按字(中文)换行绘制,返回最后一行下方的 y */
int disp_text_wrap(int x, int y, int maxw, const char *s, uint8_t size, uint16_t fg, uint16_t bg, int max_lines = 8);
/* 调试用:直接取帧缓冲(RGB565 大端存放),串口可整屏回传 */
const uint16_t *disp_fb_ptr();
void disp_flush();
void disp_selftest();
/* 首次点屏调试开关:不必为了字节序/色序/镜像反复重烧 */
void disp_set_byteswap(bool on);
void disp_set_invert(bool on);
void disp_set_mirror(bool mx, bool my);
void disp_set_bgr(bool on);

View File

@ -0,0 +1,86 @@
#include "expander.h"
#include <Wire.h>
static TwoWire &bus = Wire;
static uint16_t s_output = 0xFFFF; /* 输出寄存器影子 */
static bool write_reg(uint8_t reg, uint16_t value)
{
bus.beginTransmission(XL9555_ADDR);
bus.write(reg);
bus.write((uint8_t)(value & 0xFF)); /* P0 */
bus.write((uint8_t)(value >> 8)); /* P1 */
return bus.endTransmission() == 0;
}
static bool read_reg(uint8_t reg, uint16_t &value)
{
/* 必须先把地址指针指到 reg(重复起始,不释放总线):
XL9555 的指针会跟着上一次写自增,直接 requestFrom 读到的是 output/config,
按键永远读不出来。 */
bus.beginTransmission(XL9555_ADDR);
bus.write(reg);
if (bus.endTransmission(false) != 0) return false;
if (bus.requestFrom((uint8_t)XL9555_ADDR, (uint8_t)2) != 2) return false;
value = (uint16_t)(bus.read() | (bus.read() << 8));
return true;
}
void xl_dump_regs()
{
static const struct { uint8_t reg; const char *name; } kRegs[] = {
{ 0x00, "input (1=high)" },
{ 0x02, "output" },
{ 0x04, "polarity" },
{ 0x06, "config (1=input)" },
};
for (const auto &r : kRegs) {
uint16_t v = 0;
if (read_reg(r.reg, v)) Serial.printf("[xl] %s = 0x%04X\n", r.name, v);
else Serial.printf("[xl] %s READ FAIL\n", r.name);
}
Serial.println(F("[xl] keys are P1_7..P1_4 = KEY0..KEY3 -> bits 0x8000 0x4000 0x2000 0x1000"));
}
bool xl_begin()
{
bus.begin(PIN_I2C_SDA, PIN_I2C_SCL, 400000);
if (!write_reg(XL_REG_CONFIG0, 0xF003)) { /* P1_4..7(KEY)/P0_0,P0_1 输入,其余输出 */
return false;
}
s_output = 0xF7FF; /* SLCD_RST=0,其余为 1 */
write_reg(XL_REG_OUTPUT0, s_output);
return true;
}
void xl_pin_write(uint16_t pin, int level)
{
if (level) s_output |= pin; else s_output &= ~pin;
write_reg(XL_REG_OUTPUT0, s_output);
}
uint16_t xl_keys_raw()
{
uint16_t v = 0xFFFF;
read_reg(XL_REG_INPUT0, v);
return v;
}
void xl_i2c_scan()
{
int n = 0;
for (uint8_t a = 0x08; a <= 0x77; a++) {
bus.beginTransmission(a);
if (bus.endTransmission() == 0) { Serial.printf("[i2c] ack 0x%02X\n", a); n++; }
}
Serial.printf("[i2c] %d device(s) on SDA=%d SCL=%d\n", n, PIN_I2C_SDA, PIN_I2C_SCL);
}
uint16_t xl_keys_read()
{
uint16_t raw = xl_keys_raw();
/* 低字节是 ALS/PS 传感器(悬空会乱跳),只取 P1:按键按下=0,另外顺手把 BOOT 记在 bit0 */
uint16_t pressed = (~raw) & 0xFF00;
if (digitalRead(PIN_KEY_BOOT) == LOW) pressed |= 0x0001; /* bit0 留给 BOOT */
return pressed;
}

View File

@ -0,0 +1,13 @@
/* 板上 XL9555 I2C IO 扩展器:负责 LCD 复位/供电 和 4 个按键 */
#pragma once
#include <Arduino.h>
#include "board_config.h"
bool xl_begin();
void xl_pin_write(uint16_t pin, int level);
/* 读按键位图(KEY0..KEY3 + BOOT),按下为 1;极性未知时先靠日志判断 */
uint16_t xl_keys_read();
uint16_t xl_keys_raw();
/* 扫描 I2C 总线上应答的从机地址(排查板上有没有触摸/其他芯片) */
void xl_i2c_scan();
void xl_dump_regs(); /* 打印全部寄存器,排查按键到底接在哪个脚 */

View File

@ -0,0 +1,198 @@
/* ASCII 点阵字模,取自正点原子 DNESP32S3 官方例程 10_spilcd/components/BSP/SPILCD/spilcdfont.h */
/* 行式排列:每行 (width+7)/8 字节,MSB 为最左像素;字符集从 0x20 空格开始 */
#pragma once
#include <stdint.h>
static const uint8_t asc2_1608[95][16] = {
{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, /* " ",0 */
{0x00, 0x00, 0x00, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x00, 0x00, 0x10, 0x10, 0x00, 0x00}, /* "!",1 */
{0x00, 0x12, 0x24, 0x24, 0x48, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, /* """,2 */
{0x00, 0x00, 0x00, 0x12, 0x12, 0x12, 0x7E, 0x24, 0x24, 0x24, 0x7E, 0x24, 0x24, 0x24, 0x00, 0x00}, /* "#",3 */
{0x00, 0x00, 0x08, 0x3C, 0x4A, 0x4A, 0x48, 0x38, 0x0C, 0x0A, 0x0A, 0x4A, 0x4A, 0x3C, 0x08, 0x08}, /* "$",4 */
{0x00, 0x00, 0x00, 0x44, 0xA4, 0xA8, 0xA8, 0xB0, 0x54, 0x1A, 0x2A, 0x2A, 0x4A, 0x44, 0x00, 0x00}, /* "%",5 */
{0x00, 0x00, 0x00, 0x30, 0x48, 0x48, 0x48, 0x50, 0x6E, 0xA4, 0x94, 0x98, 0x89, 0x76, 0x00, 0x00}, /* "&",6 */
{0x00, 0x60, 0x20, 0x20, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, /* "'",7 */
{0x00, 0x02, 0x04, 0x08, 0x08, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x08, 0x08, 0x04, 0x02, 0x00}, /* "(",8 */
{0x00, 0x40, 0x20, 0x10, 0x10, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x10, 0x10, 0x20, 0x40, 0x00}, /* ")",9 */
{0x00, 0x00, 0x00, 0x00, 0x10, 0x10, 0xD6, 0x38, 0x38, 0xD6, 0x10, 0x10, 0x00, 0x00, 0x00, 0x00}, /* "*",10 */
{0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x08, 0x08, 0x7F, 0x08, 0x08, 0x08, 0x00, 0x00, 0x00, 0x00}, /* "+",11 */
{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x60, 0x20, 0x20, 0x40}, /* ",",12 */
{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7E, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, /* "-",13 */
{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x60, 0x60, 0x00, 0x00}, /* ".",14 */
{0x00, 0x00, 0x02, 0x04, 0x04, 0x04, 0x08, 0x08, 0x10, 0x10, 0x10, 0x20, 0x20, 0x40, 0x40, 0x00}, /* "/",15 */
{0x00, 0x00, 0x00, 0x18, 0x24, 0x42, 0x42, 0x42, 0x42, 0x42, 0x42, 0x42, 0x24, 0x18, 0x00, 0x00}, /* "0",16 */
{0x00, 0x00, 0x00, 0x08, 0x38, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x3E, 0x00, 0x00}, /* "1",17 */
{0x00, 0x00, 0x00, 0x3C, 0x42, 0x42, 0x42, 0x02, 0x04, 0x08, 0x10, 0x20, 0x42, 0x7E, 0x00, 0x00}, /* "2",18 */
{0x00, 0x00, 0x00, 0x3C, 0x42, 0x42, 0x02, 0x04, 0x18, 0x04, 0x02, 0x42, 0x42, 0x3C, 0x00, 0x00}, /* "3",19 */
{0x00, 0x00, 0x00, 0x04, 0x0C, 0x0C, 0x14, 0x24, 0x24, 0x44, 0x7F, 0x04, 0x04, 0x1F, 0x00, 0x00}, /* "4",20 */
{0x00, 0x00, 0x00, 0x7E, 0x40, 0x40, 0x40, 0x78, 0x44, 0x02, 0x02, 0x42, 0x44, 0x38, 0x00, 0x00}, /* "5",21 */
{0x00, 0x00, 0x00, 0x18, 0x24, 0x40, 0x40, 0x5C, 0x62, 0x42, 0x42, 0x42, 0x22, 0x1C, 0x00, 0x00}, /* "6",22 */
{0x00, 0x00, 0x00, 0x7E, 0x42, 0x04, 0x04, 0x08, 0x08, 0x10, 0x10, 0x10, 0x10, 0x10, 0x00, 0x00}, /* "7",23 */
{0x00, 0x00, 0x00, 0x3C, 0x42, 0x42, 0x42, 0x24, 0x18, 0x24, 0x42, 0x42, 0x42, 0x3C, 0x00, 0x00}, /* "8",24 */
{0x00, 0x00, 0x00, 0x38, 0x44, 0x42, 0x42, 0x42, 0x46, 0x3A, 0x02, 0x02, 0x24, 0x18, 0x00, 0x00}, /* "9",25 */
{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0x18, 0x00, 0x00, 0x00, 0x00, 0x18, 0x18, 0x00, 0x00}, /* ":",26 */
{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x10, 0x10}, /* ";",27 */
{0x00, 0x00, 0x00, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x20, 0x10, 0x08, 0x04, 0x02, 0x00, 0x00}, /* "<",28 */
{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7E, 0x00, 0x00, 0x7E, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, /* "=",29 */
{0x00, 0x00, 0x00, 0x40, 0x20, 0x10, 0x08, 0x04, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x00, 0x00}, /* ">",30 */
{0x00, 0x00, 0x00, 0x3C, 0x42, 0x42, 0x62, 0x04, 0x08, 0x08, 0x08, 0x00, 0x18, 0x18, 0x00, 0x00}, /* "?",31 */
{0x00, 0x00, 0x00, 0x38, 0x44, 0x5A, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0x5C, 0x42, 0x3C, 0x00, 0x00}, /* "@",32 */
{0x00, 0x00, 0x00, 0x10, 0x10, 0x18, 0x28, 0x28, 0x24, 0x3C, 0x44, 0x42, 0x42, 0xE7, 0x00, 0x00}, /* "A",33 */
{0x00, 0x00, 0x00, 0xF8, 0x44, 0x44, 0x44, 0x78, 0x44, 0x42, 0x42, 0x42, 0x44, 0xF8, 0x00, 0x00}, /* "B",34 */
{0x00, 0x00, 0x00, 0x3E, 0x42, 0x42, 0x80, 0x80, 0x80, 0x80, 0x80, 0x42, 0x44, 0x38, 0x00, 0x00}, /* "C",35 */
{0x00, 0x00, 0x00, 0xF8, 0x44, 0x42, 0x42, 0x42, 0x42, 0x42, 0x42, 0x42, 0x44, 0xF8, 0x00, 0x00}, /* "D",36 */
{0x00, 0x00, 0x00, 0xFC, 0x42, 0x48, 0x48, 0x78, 0x48, 0x48, 0x40, 0x42, 0x42, 0xFC, 0x00, 0x00}, /* "E",37 */
{0x00, 0x00, 0x00, 0xFC, 0x42, 0x48, 0x48, 0x78, 0x48, 0x48, 0x40, 0x40, 0x40, 0xE0, 0x00, 0x00}, /* "F",38 */
{0x00, 0x00, 0x00, 0x3C, 0x44, 0x44, 0x80, 0x80, 0x80, 0x8E, 0x84, 0x44, 0x44, 0x38, 0x00, 0x00}, /* "G",39 */
{0x00, 0x00, 0x00, 0xE7, 0x42, 0x42, 0x42, 0x42, 0x7E, 0x42, 0x42, 0x42, 0x42, 0xE7, 0x00, 0x00}, /* "H",40 */
{0x00, 0x00, 0x00, 0x7C, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x7C, 0x00, 0x00}, /* "I",41 */
{0x00, 0x00, 0x00, 0x3E, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x88, 0xF0}, /* "J",42 */
{0x00, 0x00, 0x00, 0xEE, 0x44, 0x48, 0x50, 0x70, 0x50, 0x48, 0x48, 0x44, 0x44, 0xEE, 0x00, 0x00}, /* "K",43 */
{0x00, 0x00, 0x00, 0xE0, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x42, 0xFE, 0x00, 0x00}, /* "L",44 */
{0x00, 0x00, 0x00, 0xEE, 0x6C, 0x6C, 0x6C, 0x6C, 0x6C, 0x54, 0x54, 0x54, 0x54, 0xD6, 0x00, 0x00}, /* "M",45 */
{0x00, 0x00, 0x00, 0xC7, 0x62, 0x62, 0x52, 0x52, 0x4A, 0x4A, 0x4A, 0x46, 0x46, 0xE2, 0x00, 0x00}, /* "N",46 */
{0x00, 0x00, 0x00, 0x38, 0x44, 0x82, 0x82, 0x82, 0x82, 0x82, 0x82, 0x82, 0x44, 0x38, 0x00, 0x00}, /* "O",47 */
{0x00, 0x00, 0x00, 0xFC, 0x42, 0x42, 0x42, 0x42, 0x7C, 0x40, 0x40, 0x40, 0x40, 0xE0, 0x00, 0x00}, /* "P",48 */
{0x00, 0x00, 0x00, 0x38, 0x44, 0x82, 0x82, 0x82, 0x82, 0x82, 0x82, 0xB2, 0x4C, 0x38, 0x06, 0x00}, /* "Q",49 */
{0x00, 0x00, 0x00, 0xFC, 0x42, 0x42, 0x42, 0x7C, 0x48, 0x48, 0x44, 0x44, 0x42, 0xE3, 0x00, 0x00}, /* "R",50 */
{0x00, 0x00, 0x00, 0x3E, 0x42, 0x42, 0x40, 0x20, 0x18, 0x04, 0x02, 0x42, 0x42, 0x7C, 0x00, 0x00}, /* "S",51 */
{0x00, 0x00, 0x00, 0xFE, 0x92, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x38, 0x00, 0x00}, /* "T",52 */
{0x00, 0x00, 0x00, 0xE7, 0x42, 0x42, 0x42, 0x42, 0x42, 0x42, 0x42, 0x42, 0x42, 0x3C, 0x00, 0x00}, /* "U",53 */
{0x00, 0x00, 0x00, 0xE7, 0x42, 0x42, 0x44, 0x24, 0x24, 0x28, 0x28, 0x18, 0x10, 0x10, 0x00, 0x00}, /* "V",54 */
{0x00, 0x00, 0x00, 0xD6, 0x54, 0x54, 0x54, 0x54, 0x54, 0x6C, 0x28, 0x28, 0x28, 0x28, 0x00, 0x00}, /* "W",55 */
{0x00, 0x00, 0x00, 0xE7, 0x42, 0x24, 0x24, 0x18, 0x18, 0x18, 0x24, 0x24, 0x42, 0xE7, 0x00, 0x00}, /* "X",56 */
{0x00, 0x00, 0x00, 0xEE, 0x44, 0x44, 0x28, 0x28, 0x10, 0x10, 0x10, 0x10, 0x10, 0x38, 0x00, 0x00}, /* "Y",57 */
{0x00, 0x00, 0x00, 0x7E, 0x84, 0x04, 0x08, 0x08, 0x10, 0x20, 0x20, 0x42, 0x42, 0xFC, 0x00, 0x00}, /* "Z",58 */
{0x00, 0x1E, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x1E, 0x00}, /* "[",59 */
{0x00, 0x00, 0x40, 0x20, 0x20, 0x20, 0x10, 0x10, 0x10, 0x08, 0x08, 0x04, 0x04, 0x04, 0x02, 0x02}, /* "\",60 */
{0x00, 0x78, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x78, 0x00}, /* "]",61 */
{0x00, 0x18, 0x24, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, /* "^",62 */
{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF}, /* "_",63 */
{0x00, 0x60, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, /* "`",64 */
{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x38, 0x44, 0x0C, 0x34, 0x44, 0x4C, 0x36, 0x00, 0x00}, /* "a",65 */
{0x00, 0x00, 0x00, 0x00, 0xC0, 0x40, 0x40, 0x58, 0x64, 0x42, 0x42, 0x42, 0x64, 0x58, 0x00, 0x00}, /* "b",66 */
{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x1C, 0x22, 0x40, 0x40, 0x40, 0x22, 0x1C, 0x00, 0x00}, /* "c",67 */
{0x00, 0x00, 0x00, 0x00, 0x06, 0x02, 0x02, 0x3E, 0x42, 0x42, 0x42, 0x42, 0x46, 0x3B, 0x00, 0x00}, /* "d",68 */
{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3C, 0x42, 0x42, 0x7E, 0x40, 0x42, 0x3C, 0x00, 0x00}, /* "e",69 */
{0x00, 0x00, 0x00, 0x00, 0x0C, 0x12, 0x10, 0x7C, 0x10, 0x10, 0x10, 0x10, 0x10, 0x7C, 0x00, 0x00}, /* "f",70 */
{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3E, 0x44, 0x44, 0x38, 0x40, 0x3C, 0x42, 0x42, 0x3C}, /* "g",71 */
{0x00, 0x00, 0x00, 0x00, 0xC0, 0x40, 0x40, 0x5C, 0x62, 0x42, 0x42, 0x42, 0x42, 0xE7, 0x00, 0x00}, /* "h",72 */
{0x00, 0x00, 0x00, 0x30, 0x30, 0x00, 0x00, 0x70, 0x10, 0x10, 0x10, 0x10, 0x10, 0x7C, 0x00, 0x00}, /* "i",73 */
{0x00, 0x00, 0x00, 0x0C, 0x0C, 0x00, 0x00, 0x1C, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x44, 0x78}, /* "j",74 */
{0x00, 0x00, 0x00, 0x00, 0xC0, 0x40, 0x40, 0x4E, 0x48, 0x50, 0x70, 0x48, 0x44, 0xEE, 0x00, 0x00}, /* "k",75 */
{0x00, 0x00, 0x00, 0x10, 0x70, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x7C, 0x00, 0x00}, /* "l",76 */
{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFE, 0x49, 0x49, 0x49, 0x49, 0x49, 0xED, 0x00, 0x00}, /* "m",77 */
{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xDC, 0x62, 0x42, 0x42, 0x42, 0x42, 0xE7, 0x00, 0x00}, /* "n",78 */
{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3C, 0x42, 0x42, 0x42, 0x42, 0x42, 0x3C, 0x00, 0x00}, /* "o",79 */
{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xD8, 0x64, 0x42, 0x42, 0x42, 0x64, 0x58, 0x40, 0xE0}, /* "p",80 */
{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x1A, 0x26, 0x42, 0x42, 0x42, 0x26, 0x1A, 0x02, 0x07}, /* "q",81 */
{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xEE, 0x32, 0x20, 0x20, 0x20, 0x20, 0xF8, 0x00, 0x00}, /* "r",82 */
{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3E, 0x42, 0x40, 0x3C, 0x02, 0x42, 0x7C, 0x00, 0x00}, /* "s",83 */
{0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x10, 0x7C, 0x10, 0x10, 0x10, 0x10, 0x12, 0x0C, 0x00, 0x00}, /* "t",84 */
{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xC6, 0x42, 0x42, 0x42, 0x42, 0x46, 0x3B, 0x00, 0x00}, /* "u",85 */
{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xEE, 0x44, 0x44, 0x28, 0x28, 0x10, 0x10, 0x00, 0x00}, /* "v",86 */
{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xDB, 0x89, 0x4A, 0x5A, 0x54, 0x24, 0x24, 0x00, 0x00}, /* "w",87 */
{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x76, 0x24, 0x18, 0x18, 0x18, 0x24, 0x6E, 0x00, 0x00}, /* "x",88 */
{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xE7, 0x42, 0x24, 0x24, 0x18, 0x18, 0x10, 0x10, 0x60}, /* "y",89 */
{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7E, 0x44, 0x08, 0x10, 0x10, 0x22, 0x7E, 0x00, 0x00}, /* "z",90 */
{0x00, 0x03, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x08, 0x04, 0x04, 0x04, 0x04, 0x04, 0x03, 0x00}, /* "{",91 */
{0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08}, /* "|",92 */
{0x00, 0xC0, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x10, 0x20, 0x20, 0x20, 0x20, 0x20, 0xC0, 0x00}, /* "}",93 */
{0x20, 0x5A, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, /* "~",94 */};
static const uint8_t asc2_3216[95][64] = {
{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, /* " ",0 */
{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0xC0, 0x03, 0xC0, 0x03, 0xC0, 0x03, 0xC0, 0x03, 0xC0, 0x03, 0xC0, 0x01, 0xC0, 0x01, 0x80, 0x01, 0x80, 0x01, 0x80, 0x01, 0x80, 0x01, 0x80, 0x01, 0x80, 0x01, 0x80, 0x01, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x80, 0x03, 0xC0, 0x03, 0xC0, 0x01, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, /* "!",1 */
{0x00, 0x00, 0x00, 0x00, 0x03, 0x18, 0x07, 0x38, 0x07, 0x38, 0x0E, 0x70, 0x0C, 0x60, 0x18, 0xC0, 0x31, 0x80, 0x21, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, /* """,2 */
{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x08, 0x04, 0x08, 0x04, 0x08, 0x04, 0x08, 0x04, 0x08, 0x7F, 0xFE, 0x7F, 0xFE, 0x7F, 0xFE, 0x08, 0x10, 0x08, 0x10, 0x08, 0x10, 0x08, 0x10, 0x08, 0x10, 0x08, 0x10, 0x7F, 0xFE, 0x7F, 0xFE, 0x7F, 0xFE, 0x18, 0x30, 0x10, 0x20, 0x10, 0x20, 0x10, 0x20, 0x10, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, /* "#",3 */
{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0x03, 0xC0, 0x0D, 0x30, 0x09, 0x18, 0x19, 0x18, 0x19, 0x38, 0x19, 0x38, 0x1D, 0x00, 0x0D, 0x00, 0x0F, 0x00, 0x07, 0x00, 0x03, 0xC0, 0x01, 0xE0, 0x01, 0xF0, 0x01, 0x30, 0x01, 0x38, 0x01, 0x18, 0x39, 0x18, 0x39, 0x18, 0x31, 0x18, 0x31, 0x30, 0x19, 0x60, 0x07, 0xC0, 0x01, 0x00, 0x01, 0x00, 0x01, 0x00, 0x00, 0x00}, /* "$",4 */
{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x38, 0x10, 0x6C, 0x10, 0x44, 0x20, 0xC6, 0x20, 0xC6, 0x40, 0xC6, 0x40, 0xC6, 0x40, 0xC6, 0x80, 0xC6, 0x80, 0x44, 0x80, 0x6D, 0x38, 0x39, 0x6C, 0x02, 0x44, 0x02, 0xC6, 0x02, 0xC6, 0x04, 0xC6, 0x04, 0xC6, 0x08, 0xC6, 0x08, 0xC6, 0x08, 0x44, 0x10, 0x6C, 0x10, 0x38, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, /* "%",5 */
{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0F, 0x00, 0x19, 0x00, 0x31, 0x80, 0x31, 0x80, 0x31, 0x80, 0x31, 0x80, 0x31, 0x00, 0x33, 0x00, 0x3A, 0x00, 0x1C, 0x00, 0x38, 0x7C, 0x3C, 0x10, 0x4C, 0x10, 0xCE, 0x10, 0xC6, 0x20, 0xC7, 0x20, 0xC3, 0x20, 0xC1, 0xC0, 0xC1, 0xC2, 0x60, 0xE6, 0x31, 0x7C, 0x1E, 0x38, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, /* "&",6 */
{0x00, 0x00, 0x00, 0x00, 0x38, 0x00, 0x3C, 0x00, 0x3C, 0x00, 0x0C, 0x00, 0x0C, 0x00, 0x08, 0x00, 0x30, 0x00, 0x60, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, /* "'",7 */
{0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x04, 0x00, 0x08, 0x00, 0x18, 0x00, 0x30, 0x00, 0x20, 0x00, 0x60, 0x00, 0x40, 0x00, 0xC0, 0x00, 0xC0, 0x01, 0x80, 0x01, 0x80, 0x01, 0x80, 0x01, 0x80, 0x01, 0x80, 0x01, 0x80, 0x01, 0x80, 0x01, 0x80, 0x01, 0x80, 0x00, 0xC0, 0x00, 0xC0, 0x00, 0x40, 0x00, 0x60, 0x00, 0x20, 0x00, 0x30, 0x00, 0x18, 0x00, 0x08, 0x00, 0x04, 0x00, 0x02, 0x00, 0x00}, /* "(",8 */
{0x00, 0x00, 0x00, 0x00, 0x40, 0x00, 0x20, 0x00, 0x10, 0x00, 0x18, 0x00, 0x0C, 0x00, 0x04, 0x00, 0x06, 0x00, 0x02, 0x00, 0x03, 0x00, 0x03, 0x00, 0x01, 0x80, 0x01, 0x80, 0x01, 0x80, 0x01, 0x80, 0x01, 0x80, 0x01, 0x80, 0x01, 0x80, 0x01, 0x80, 0x01, 0x80, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x06, 0x00, 0x04, 0x00, 0x0C, 0x00, 0x18, 0x00, 0x10, 0x00, 0x20, 0x00, 0x40, 0x00, 0x00, 0x00}, /* ")",9 */
{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xC0, 0x01, 0xC0, 0x01, 0xC0, 0x30, 0xC6, 0x38, 0x8E, 0x1C, 0x9C, 0x06, 0xB0, 0x01, 0xC0, 0x01, 0xC0, 0x06, 0xB0, 0x1C, 0x9C, 0x38, 0x8E, 0x31, 0x86, 0x01, 0xC0, 0x01, 0xC0, 0x01, 0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, /* "*",10 */
{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x00, 0x80, 0x00, 0x80, 0x00, 0x80, 0x00, 0x80, 0x00, 0x80, 0x00, 0x80, 0x3F, 0xFE, 0x00, 0x80, 0x00, 0x80, 0x00, 0x80, 0x00, 0x80, 0x00, 0x80, 0x00, 0x80, 0x00, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, /* "+",11 */
{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x38, 0x00, 0x3C, 0x00, 0x3C, 0x00, 0x0C, 0x00, 0x0C, 0x00, 0x08, 0x00, 0x30, 0x00, 0x60, 0x00}, /* ",",12 */
{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7F, 0xFE, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, /* "-",13 */
{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0x00, 0x3C, 0x00, 0x3C, 0x00, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, /* ".",14 */
{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x06, 0x00, 0x04, 0x00, 0x0C, 0x00, 0x08, 0x00, 0x18, 0x00, 0x10, 0x00, 0x30, 0x00, 0x20, 0x00, 0x60, 0x00, 0x40, 0x00, 0xC0, 0x00, 0x80, 0x01, 0x80, 0x01, 0x00, 0x03, 0x00, 0x02, 0x00, 0x06, 0x00, 0x04, 0x00, 0x0C, 0x00, 0x08, 0x00, 0x18, 0x00, 0x10, 0x00, 0x30, 0x00, 0x20, 0x00, 0x60, 0x00, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00}, /* "/",15 */
{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0xC0, 0x06, 0x20, 0x0C, 0x30, 0x18, 0x18, 0x18, 0x18, 0x18, 0x08, 0x30, 0x0C, 0x30, 0x0C, 0x30, 0x0C, 0x30, 0x0C, 0x30, 0x0C, 0x30, 0x0C, 0x30, 0x0C, 0x30, 0x0C, 0x30, 0x0C, 0x30, 0x0C, 0x18, 0x08, 0x18, 0x18, 0x18, 0x18, 0x0C, 0x30, 0x06, 0x20, 0x03, 0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, /* "0",16 */
{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x01, 0x80, 0x1F, 0x80, 0x01, 0x80, 0x01, 0x80, 0x01, 0x80, 0x01, 0x80, 0x01, 0x80, 0x01, 0x80, 0x01, 0x80, 0x01, 0x80, 0x01, 0x80, 0x01, 0x80, 0x01, 0x80, 0x01, 0x80, 0x01, 0x80, 0x01, 0x80, 0x01, 0x80, 0x01, 0x80, 0x01, 0x80, 0x03, 0xC0, 0x1F, 0xF8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, /* "1",17 */
{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x07, 0xE0, 0x08, 0x38, 0x10, 0x18, 0x20, 0x0C, 0x20, 0x0C, 0x30, 0x0C, 0x30, 0x0C, 0x00, 0x0C, 0x00, 0x18, 0x00, 0x18, 0x00, 0x30, 0x00, 0x60, 0x00, 0xC0, 0x01, 0x80, 0x03, 0x00, 0x02, 0x00, 0x04, 0x04, 0x08, 0x04, 0x10, 0x04, 0x20, 0x0C, 0x3F, 0xF8, 0x3F, 0xF8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, /* "2",18 */
{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x07, 0xC0, 0x18, 0x60, 0x30, 0x30, 0x30, 0x18, 0x30, 0x18, 0x30, 0x18, 0x00, 0x18, 0x00, 0x18, 0x00, 0x30, 0x00, 0x60, 0x03, 0xC0, 0x00, 0x70, 0x00, 0x18, 0x00, 0x08, 0x00, 0x0C, 0x00, 0x0C, 0x30, 0x0C, 0x30, 0x0C, 0x30, 0x08, 0x30, 0x18, 0x18, 0x30, 0x07, 0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, /* "3",19 */
{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x60, 0x00, 0x60, 0x00, 0xE0, 0x00, 0xE0, 0x01, 0x60, 0x01, 0x60, 0x02, 0x60, 0x04, 0x60, 0x04, 0x60, 0x08, 0x60, 0x08, 0x60, 0x10, 0x60, 0x30, 0x60, 0x20, 0x60, 0x40, 0x60, 0x7F, 0xFC, 0x00, 0x60, 0x00, 0x60, 0x00, 0x60, 0x00, 0x60, 0x00, 0x60, 0x03, 0xFC, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, /* "4",20 */
{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0F, 0xFC, 0x0F, 0xFC, 0x10, 0x00, 0x10, 0x00, 0x10, 0x00, 0x10, 0x00, 0x10, 0x00, 0x10, 0x00, 0x13, 0xE0, 0x14, 0x30, 0x18, 0x18, 0x10, 0x08, 0x00, 0x0C, 0x00, 0x0C, 0x00, 0x0C, 0x00, 0x0C, 0x30, 0x0C, 0x30, 0x0C, 0x20, 0x18, 0x20, 0x18, 0x18, 0x30, 0x07, 0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, /* "5",21 */
{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0xE0, 0x06, 0x18, 0x0C, 0x18, 0x08, 0x18, 0x18, 0x00, 0x10, 0x00, 0x10, 0x00, 0x30, 0x00, 0x33, 0xE0, 0x36, 0x30, 0x38, 0x18, 0x38, 0x08, 0x30, 0x0C, 0x30, 0x0C, 0x30, 0x0C, 0x30, 0x0C, 0x30, 0x0C, 0x18, 0x0C, 0x18, 0x08, 0x0C, 0x18, 0x0E, 0x30, 0x03, 0xE0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, /* "6",22 */
{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x1F, 0xFC, 0x1F, 0xFC, 0x10, 0x08, 0x30, 0x10, 0x20, 0x10, 0x20, 0x20, 0x00, 0x20, 0x00, 0x40, 0x00, 0x40, 0x00, 0x40, 0x00, 0x80, 0x00, 0x80, 0x01, 0x00, 0x01, 0x00, 0x01, 0x00, 0x01, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, /* "7",23 */
{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x07, 0xE0, 0x0C, 0x30, 0x18, 0x18, 0x30, 0x0C, 0x30, 0x0C, 0x30, 0x0C, 0x38, 0x0C, 0x38, 0x08, 0x1E, 0x18, 0x0F, 0x20, 0x07, 0xC0, 0x18, 0xF0, 0x30, 0x78, 0x30, 0x38, 0x60, 0x1C, 0x60, 0x0C, 0x60, 0x0C, 0x60, 0x0C, 0x60, 0x0C, 0x30, 0x18, 0x18, 0x30, 0x07, 0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, /* "8",24 */
{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x07, 0xC0, 0x18, 0x20, 0x30, 0x10, 0x30, 0x18, 0x60, 0x08, 0x60, 0x0C, 0x60, 0x0C, 0x60, 0x0C, 0x60, 0x0C, 0x60, 0x0C, 0x70, 0x1C, 0x30, 0x2C, 0x18, 0x6C, 0x0F, 0x8C, 0x00, 0x0C, 0x00, 0x18, 0x00, 0x18, 0x00, 0x10, 0x30, 0x30, 0x30, 0x60, 0x30, 0xC0, 0x0F, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, /* "9",25 */
{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x80, 0x03, 0xC0, 0x03, 0xC0, 0x01, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x80, 0x03, 0xC0, 0x03, 0xC0, 0x01, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, /* ":",26 */
{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0x80, 0x03, 0x80, 0x03, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0x80, 0x03, 0x80, 0x03, 0x80, 0x01, 0x80, 0x03, 0x00, 0x03, 0x00, 0x00, 0x00}, /* ";",27 */
{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x00, 0x08, 0x00, 0x10, 0x00, 0x20, 0x00, 0x40, 0x00, 0x80, 0x01, 0x00, 0x02, 0x00, 0x04, 0x00, 0x08, 0x00, 0x10, 0x00, 0x10, 0x00, 0x08, 0x00, 0x04, 0x00, 0x02, 0x00, 0x01, 0x00, 0x00, 0x80, 0x00, 0x40, 0x00, 0x20, 0x00, 0x10, 0x00, 0x08, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, /* "<",28 */
{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7F, 0xFE, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7F, 0xFE, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, /* "=",29 */
{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x20, 0x00, 0x10, 0x00, 0x08, 0x00, 0x04, 0x00, 0x02, 0x00, 0x01, 0x00, 0x00, 0x80, 0x00, 0x40, 0x00, 0x20, 0x00, 0x10, 0x00, 0x08, 0x00, 0x08, 0x00, 0x10, 0x00, 0x20, 0x00, 0x40, 0x00, 0x80, 0x01, 0x00, 0x02, 0x00, 0x04, 0x00, 0x08, 0x00, 0x10, 0x00, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, /* ">",30 */
{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0xE0, 0x0C, 0x18, 0x18, 0x0C, 0x10, 0x06, 0x30, 0x06, 0x38, 0x06, 0x38, 0x06, 0x38, 0x06, 0x00, 0x0C, 0x00, 0x18, 0x00, 0x70, 0x00, 0xC0, 0x00, 0x80, 0x00, 0x80, 0x00, 0x80, 0x00, 0x80, 0x00, 0x00, 0x00, 0x00, 0x01, 0x80, 0x03, 0xC0, 0x03, 0xC0, 0x01, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, /* "?",31 */
{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0xE0, 0x06, 0x10, 0x0C, 0x08, 0x18, 0x04, 0x30, 0xD4, 0x31, 0xB2, 0x21, 0x32, 0x63, 0x32, 0x63, 0x22, 0x66, 0x22, 0x66, 0x22, 0x66, 0x22, 0x66, 0x62, 0x66, 0x64, 0x66, 0x64, 0x26, 0xE8, 0x33, 0x30, 0x30, 0x02, 0x10, 0x04, 0x18, 0x0C, 0x0C, 0x18, 0x03, 0xE0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, /* "@",32 */
{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0x80, 0x03, 0x80, 0x03, 0x80, 0x03, 0x80, 0x04, 0xC0, 0x04, 0xC0, 0x04, 0xC0, 0x04, 0xC0, 0x0C, 0x40, 0x08, 0x60, 0x08, 0x60, 0x08, 0x60, 0x08, 0x20, 0x1F, 0xF0, 0x10, 0x30, 0x10, 0x30, 0x10, 0x30, 0x20, 0x18, 0x20, 0x18, 0x20, 0x18, 0x60, 0x1C, 0xF8, 0x3E, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, /* "A",33 */
{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7F, 0xE0, 0x18, 0x38, 0x18, 0x18, 0x18, 0x0C, 0x18, 0x0C, 0x18, 0x0C, 0x18, 0x0C, 0x18, 0x0C, 0x18, 0x18, 0x18, 0x30, 0x1F, 0xE0, 0x18, 0x18, 0x18, 0x0C, 0x18, 0x04, 0x18, 0x06, 0x18, 0x06, 0x18, 0x06, 0x18, 0x06, 0x18, 0x06, 0x18, 0x0C, 0x18, 0x18, 0x7F, 0xF0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, /* "B",34 */
{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0xE0, 0x06, 0x1C, 0x08, 0x0C, 0x18, 0x06, 0x30, 0x02, 0x30, 0x02, 0x30, 0x00, 0x60, 0x00, 0x60, 0x00, 0x60, 0x00, 0x60, 0x00, 0x60, 0x00, 0x60, 0x00, 0x60, 0x00, 0x60, 0x00, 0x60, 0x00, 0x30, 0x02, 0x30, 0x02, 0x10, 0x04, 0x18, 0x08, 0x0C, 0x10, 0x03, 0xE0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, /* "C",35 */
{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7F, 0xC0, 0x18, 0x70, 0x18, 0x18, 0x18, 0x08, 0x18, 0x0C, 0x18, 0x0C, 0x18, 0x06, 0x18, 0x06, 0x18, 0x06, 0x18, 0x06, 0x18, 0x06, 0x18, 0x06, 0x18, 0x06, 0x18, 0x06, 0x18, 0x06, 0x18, 0x04, 0x18, 0x0C, 0x18, 0x0C, 0x18, 0x18, 0x18, 0x18, 0x18, 0x60, 0x7F, 0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, /* "D",36 */
{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7F, 0xFC, 0x18, 0x0C, 0x18, 0x04, 0x18, 0x02, 0x18, 0x02, 0x18, 0x00, 0x18, 0x00, 0x18, 0x10, 0x18, 0x10, 0x18, 0x30, 0x1F, 0xF0, 0x18, 0x30, 0x18, 0x10, 0x18, 0x10, 0x18, 0x00, 0x18, 0x00, 0x18, 0x00, 0x18, 0x02, 0x18, 0x02, 0x18, 0x04, 0x18, 0x0C, 0x7F, 0xFC, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, /* "E",37 */
{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7F, 0xFC, 0x18, 0x1C, 0x18, 0x04, 0x18, 0x02, 0x18, 0x02, 0x18, 0x00, 0x18, 0x00, 0x18, 0x10, 0x18, 0x10, 0x18, 0x30, 0x1F, 0xF0, 0x18, 0x30, 0x18, 0x10, 0x18, 0x10, 0x18, 0x10, 0x18, 0x00, 0x18, 0x00, 0x18, 0x00, 0x18, 0x00, 0x18, 0x00, 0x18, 0x00, 0x7E, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, /* "F",38 */
{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0xC0, 0x0C, 0x30, 0x08, 0x10, 0x18, 0x18, 0x30, 0x08, 0x30, 0x08, 0x20, 0x00, 0x60, 0x00, 0x60, 0x00, 0x60, 0x00, 0x60, 0x00, 0x60, 0x00, 0x60, 0x7E, 0x60, 0x18, 0x60, 0x18, 0x20, 0x18, 0x30, 0x18, 0x30, 0x18, 0x10, 0x18, 0x18, 0x18, 0x0C, 0x20, 0x07, 0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, /* "G",39 */
{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFC, 0x3F, 0x30, 0x0C, 0x30, 0x0C, 0x30, 0x0C, 0x30, 0x0C, 0x30, 0x0C, 0x30, 0x0C, 0x30, 0x0C, 0x30, 0x0C, 0x30, 0x0C, 0x3F, 0xFC, 0x30, 0x0C, 0x30, 0x0C, 0x30, 0x0C, 0x30, 0x0C, 0x30, 0x0C, 0x30, 0x0C, 0x30, 0x0C, 0x30, 0x0C, 0x30, 0x0C, 0x30, 0x0C, 0xFC, 0x3F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, /* "H",40 */
{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x1F, 0xF8, 0x01, 0x80, 0x01, 0x80, 0x01, 0x80, 0x01, 0x80, 0x01, 0x80, 0x01, 0x80, 0x01, 0x80, 0x01, 0x80, 0x01, 0x80, 0x01, 0x80, 0x01, 0x80, 0x01, 0x80, 0x01, 0x80, 0x01, 0x80, 0x01, 0x80, 0x01, 0x80, 0x01, 0x80, 0x01, 0x80, 0x01, 0x80, 0x01, 0x80, 0x1F, 0xF8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, /* "I",41 */
{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x07, 0xFE, 0x00, 0x60, 0x00, 0x60, 0x00, 0x60, 0x00, 0x60, 0x00, 0x60, 0x00, 0x60, 0x00, 0x60, 0x00, 0x60, 0x00, 0x60, 0x00, 0x60, 0x00, 0x60, 0x00, 0x60, 0x00, 0x60, 0x00, 0x60, 0x00, 0x60, 0x00, 0x60, 0x00, 0x60, 0x00, 0x60, 0x00, 0x60, 0x00, 0x60, 0x00, 0x60, 0x70, 0x60, 0x70, 0xC0, 0x71, 0x80, 0x3F, 0x00}, /* "J",42 */
{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7E, 0x7C, 0x18, 0x30, 0x18, 0x20, 0x18, 0x60, 0x18, 0x40, 0x18, 0x80, 0x18, 0x80, 0x19, 0x00, 0x19, 0x00, 0x1B, 0x00, 0x1D, 0x80, 0x1D, 0x80, 0x18, 0xC0, 0x18, 0xC0, 0x18, 0x60, 0x18, 0x60, 0x18, 0x30, 0x18, 0x30, 0x18, 0x30, 0x18, 0x18, 0x18, 0x18, 0x7E, 0x3E, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, /* "K",43 */
{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7E, 0x00, 0x18, 0x00, 0x18, 0x00, 0x18, 0x00, 0x18, 0x00, 0x18, 0x00, 0x18, 0x00, 0x18, 0x00, 0x18, 0x00, 0x18, 0x00, 0x18, 0x00, 0x18, 0x00, 0x18, 0x00, 0x18, 0x00, 0x18, 0x00, 0x18, 0x00, 0x18, 0x00, 0x18, 0x02, 0x18, 0x02, 0x18, 0x04, 0x18, 0x0C, 0x7F, 0xFC, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, /* "L",44 */
{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xF0, 0x0F, 0x38, 0x1C, 0x38, 0x1C, 0x38, 0x1C, 0x38, 0x1C, 0x38, 0x2C, 0x2C, 0x2C, 0x2C, 0x2C, 0x2C, 0x2C, 0x2C, 0x4C, 0x2C, 0x4C, 0x26, 0x4C, 0x26, 0x4C, 0x26, 0x4C, 0x26, 0x8C, 0x22, 0x8C, 0x23, 0x8C, 0x23, 0x8C, 0x23, 0x0C, 0x23, 0x0C, 0x21, 0x0C, 0xF1, 0x3F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, /* "M",45 */
{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xF0, 0x1F, 0x38, 0x04, 0x38, 0x04, 0x2C, 0x04, 0x2C, 0x04, 0x26, 0x04, 0x26, 0x04, 0x23, 0x04, 0x23, 0x04, 0x21, 0x84, 0x21, 0x84, 0x20, 0xC4, 0x20, 0xC4, 0x20, 0x64, 0x20, 0x64, 0x20, 0x34, 0x20, 0x34, 0x20, 0x1C, 0x20, 0x1C, 0x20, 0x0C, 0x20, 0x0C, 0xF8, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, /* "N",46 */
{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0xC0, 0x0C, 0x30, 0x18, 0x18, 0x10, 0x08, 0x30, 0x0C, 0x30, 0x0C, 0x60, 0x04, 0x60, 0x06, 0x60, 0x06, 0x60, 0x06, 0x60, 0x06, 0x60, 0x06, 0x60, 0x06, 0x60, 0x06, 0x60, 0x06, 0x20, 0x06, 0x30, 0x0C, 0x30, 0x0C, 0x10, 0x08, 0x18, 0x18, 0x0C, 0x30, 0x03, 0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, /* "O",47 */
{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7F, 0xF0, 0x18, 0x18, 0x18, 0x0C, 0x18, 0x06, 0x18, 0x06, 0x18, 0x06, 0x18, 0x06, 0x18, 0x06, 0x18, 0x06, 0x18, 0x0C, 0x18, 0x18, 0x1F, 0xE0, 0x18, 0x00, 0x18, 0x00, 0x18, 0x00, 0x18, 0x00, 0x18, 0x00, 0x18, 0x00, 0x18, 0x00, 0x18, 0x00, 0x18, 0x00, 0x7E, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, /* "P",48 */
{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0xC0, 0x0C, 0x30, 0x18, 0x18, 0x10, 0x08, 0x30, 0x0C, 0x30, 0x0C, 0x60, 0x06, 0x60, 0x06, 0x60, 0x06, 0x60, 0x06, 0x60, 0x06, 0x60, 0x06, 0x60, 0x06, 0x60, 0x06, 0x60, 0x06, 0x60, 0x06, 0x27, 0x84, 0x38, 0xCC, 0x38, 0x6C, 0x18, 0x78, 0x0C, 0x70, 0x03, 0xE0, 0x00, 0x32, 0x00, 0x3C, 0x00, 0x1C, 0x00, 0x00}, /* "Q",49 */
{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7F, 0xE0, 0x18, 0x38, 0x18, 0x18, 0x18, 0x0C, 0x18, 0x0C, 0x18, 0x0C, 0x18, 0x0C, 0x18, 0x0C, 0x18, 0x18, 0x18, 0x30, 0x1F, 0xE0, 0x18, 0xC0, 0x18, 0xC0, 0x18, 0x60, 0x18, 0x60, 0x18, 0x60, 0x18, 0x30, 0x18, 0x30, 0x18, 0x30, 0x18, 0x18, 0x18, 0x18, 0x7E, 0x1E, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, /* "R",50 */
{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0F, 0xC8, 0x18, 0x78, 0x30, 0x18, 0x60, 0x18, 0x60, 0x08, 0x60, 0x08, 0x60, 0x00, 0x70, 0x00, 0x3C, 0x00, 0x1F, 0x00, 0x07, 0xC0, 0x01, 0xF0, 0x00, 0x78, 0x00, 0x18, 0x00, 0x1C, 0x40, 0x0C, 0x40, 0x0C, 0x60, 0x0C, 0x20, 0x0C, 0x30, 0x18, 0x38, 0x30, 0x27, 0xE0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, /* "S",51 */
{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3F, 0xFC, 0x31, 0x84, 0x21, 0x86, 0x41, 0x82, 0x41, 0x82, 0x01, 0x80, 0x01, 0x80, 0x01, 0x80, 0x01, 0x80, 0x01, 0x80, 0x01, 0x80, 0x01, 0x80, 0x01, 0x80, 0x01, 0x80, 0x01, 0x80, 0x01, 0x80, 0x01, 0x80, 0x01, 0x80, 0x01, 0x80, 0x01, 0x80, 0x01, 0x80, 0x07, 0xE0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, /* "T",52 */
{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFC, 0x3E, 0x30, 0x08, 0x30, 0x08, 0x30, 0x08, 0x30, 0x08, 0x30, 0x08, 0x30, 0x08, 0x30, 0x08, 0x30, 0x08, 0x30, 0x08, 0x30, 0x08, 0x30, 0x08, 0x30, 0x08, 0x30, 0x08, 0x30, 0x08, 0x30, 0x08, 0x30, 0x08, 0x30, 0x08, 0x30, 0x08, 0x18, 0x10, 0x1C, 0x20, 0x07, 0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, /* "U",53 */
{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7C, 0x1E, 0x18, 0x0C, 0x18, 0x08, 0x18, 0x08, 0x18, 0x08, 0x0C, 0x10, 0x0C, 0x10, 0x0C, 0x10, 0x0C, 0x10, 0x0C, 0x20, 0x06, 0x20, 0x06, 0x20, 0x06, 0x20, 0x06, 0x40, 0x03, 0x40, 0x03, 0x40, 0x03, 0x40, 0x03, 0x80, 0x01, 0x80, 0x01, 0x80, 0x01, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, /* "V",54 */
{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xF3, 0xCF, 0x61, 0x86, 0x61, 0x84, 0x21, 0x84, 0x20, 0x84, 0x30, 0xC4, 0x31, 0xC4, 0x31, 0xC4, 0x31, 0xC8, 0x31, 0xC8, 0x11, 0xC8, 0x12, 0x48, 0x1A, 0x68, 0x1A, 0x68, 0x1A, 0x70, 0x1C, 0x70, 0x0C, 0x70, 0x0C, 0x70, 0x0C, 0x30, 0x0C, 0x20, 0x08, 0x20, 0x08, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, /* "W",55 */
{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7C, 0x3E, 0x18, 0x08, 0x18, 0x10, 0x0C, 0x10, 0x0C, 0x20, 0x06, 0x20, 0x06, 0x40, 0x03, 0x40, 0x03, 0x80, 0x01, 0x80, 0x01, 0x80, 0x01, 0x80, 0x01, 0xC0, 0x02, 0xC0, 0x02, 0x60, 0x04, 0x60, 0x04, 0x70, 0x08, 0x30, 0x08, 0x30, 0x18, 0x18, 0x10, 0x1C, 0x7C, 0x3E, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, /* "X",56 */
{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7E, 0x3E, 0x38, 0x08, 0x18, 0x08, 0x18, 0x10, 0x0C, 0x10, 0x0C, 0x10, 0x0C, 0x20, 0x06, 0x20, 0x06, 0x20, 0x03, 0x40, 0x03, 0x40, 0x03, 0x80, 0x01, 0x80, 0x01, 0x80, 0x01, 0x80, 0x01, 0x80, 0x01, 0x80, 0x01, 0x80, 0x01, 0x80, 0x01, 0x80, 0x01, 0x80, 0x07, 0xE0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, /* "Y",57 */
{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x1F, 0xFE, 0x1C, 0x0C, 0x18, 0x0C, 0x30, 0x18, 0x20, 0x18, 0x00, 0x30, 0x00, 0x60, 0x00, 0x60, 0x00, 0xC0, 0x00, 0xC0, 0x01, 0x80, 0x01, 0x80, 0x03, 0x00, 0x03, 0x00, 0x06, 0x00, 0x06, 0x00, 0x0C, 0x00, 0x18, 0x02, 0x18, 0x06, 0x30, 0x04, 0x30, 0x1C, 0x7F, 0xFC, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, /* "Z",58 */
{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0xFC, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0xFC, 0x00, 0x00, 0x00, 0x00}, /* "[",59 */
{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0x00, 0x18, 0x00, 0x08, 0x00, 0x0C, 0x00, 0x04, 0x00, 0x06, 0x00, 0x06, 0x00, 0x02, 0x00, 0x03, 0x00, 0x01, 0x00, 0x01, 0x80, 0x01, 0x80, 0x00, 0x80, 0x00, 0xC0, 0x00, 0x40, 0x00, 0x60, 0x00, 0x60, 0x00, 0x30, 0x00, 0x30, 0x00, 0x30, 0x00, 0x18, 0x00, 0x18, 0x00, 0x0C, 0x00, 0x0C, 0x00, 0x0C, 0x00, 0x06, 0x00, 0x00}, /* "\",60 */
{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3F, 0xC0, 0x00, 0xC0, 0x00, 0xC0, 0x00, 0xC0, 0x00, 0xC0, 0x00, 0xC0, 0x00, 0xC0, 0x00, 0xC0, 0x00, 0xC0, 0x00, 0xC0, 0x00, 0xC0, 0x00, 0xC0, 0x00, 0xC0, 0x00, 0xC0, 0x00, 0xC0, 0x00, 0xC0, 0x00, 0xC0, 0x00, 0xC0, 0x00, 0xC0, 0x00, 0xC0, 0x00, 0xC0, 0x00, 0xC0, 0x00, 0xC0, 0x00, 0xC0, 0x00, 0xC0, 0x00, 0xC0, 0x3F, 0xC0, 0x00, 0x00, 0x00, 0x00}, /* "]",61 */
{0x00, 0x00, 0x00, 0x00, 0x03, 0xC0, 0x03, 0xE0, 0x06, 0x20, 0x08, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, /* "^",62 */
{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF}, /* "_",63 */
{0x00, 0x00, 0x00, 0x00, 0x1E, 0x00, 0x03, 0x00, 0x00, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, /* "`",64 */
{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x07, 0xE0, 0x18, 0x30, 0x30, 0x18, 0x30, 0x18, 0x30, 0x18, 0x00, 0x38, 0x07, 0xD8, 0x1C, 0x18, 0x30, 0x18, 0x60, 0x18, 0x60, 0x18, 0x60, 0x18, 0x60, 0x19, 0x30, 0x79, 0x1F, 0x8E, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, /* "a",65 */
{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x00, 0x78, 0x00, 0x18, 0x00, 0x18, 0x00, 0x18, 0x00, 0x18, 0x00, 0x18, 0x00, 0x18, 0x00, 0x19, 0xE0, 0x1A, 0x38, 0x1C, 0x18, 0x1C, 0x0C, 0x18, 0x0C, 0x18, 0x0C, 0x18, 0x0C, 0x18, 0x0C, 0x18, 0x0C, 0x18, 0x0C, 0x18, 0x0C, 0x18, 0x08, 0x1C, 0x18, 0x1C, 0x30, 0x13, 0xE0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, /* "b",66 */
{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0xE0, 0x0E, 0x10, 0x0C, 0x18, 0x18, 0x18, 0x30, 0x18, 0x30, 0x00, 0x30, 0x00, 0x30, 0x00, 0x30, 0x00, 0x30, 0x00, 0x30, 0x04, 0x18, 0x04, 0x18, 0x08, 0x0C, 0x10, 0x03, 0xE0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, /* "c",67 */
{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x00, 0x78, 0x00, 0x18, 0x00, 0x18, 0x00, 0x18, 0x00, 0x18, 0x00, 0x18, 0x00, 0x18, 0x07, 0xD8, 0x0C, 0x38, 0x18, 0x18, 0x18, 0x18, 0x30, 0x18, 0x30, 0x18, 0x30, 0x18, 0x30, 0x18, 0x30, 0x18, 0x30, 0x18, 0x30, 0x18, 0x10, 0x18, 0x18, 0x38, 0x0C, 0x5E, 0x07, 0x90, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, /* "d",68 */
{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0xC0, 0x0C, 0x30, 0x08, 0x18, 0x18, 0x08, 0x30, 0x0C, 0x30, 0x0C, 0x30, 0x0C, 0x3F, 0xFC, 0x30, 0x00, 0x30, 0x00, 0x30, 0x00, 0x18, 0x04, 0x18, 0x08, 0x0E, 0x18, 0x03, 0xE0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, /* "e",69 */
{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7C, 0x01, 0x86, 0x01, 0x06, 0x03, 0x06, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x3F, 0xF8, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x1F, 0xF0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, /* "f",70 */
{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0xEE, 0x0C, 0x36, 0x08, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x08, 0x18, 0x0C, 0x30, 0x0F, 0xE0, 0x18, 0x00, 0x18, 0x00, 0x1F, 0xC0, 0x0F, 0xF8, 0x18, 0x1C, 0x30, 0x0C, 0x30, 0x0C, 0x30, 0x0C, 0x18, 0x18, 0x07, 0xE0}, /* "g",71 */
{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x00, 0x78, 0x00, 0x18, 0x00, 0x18, 0x00, 0x18, 0x00, 0x18, 0x00, 0x18, 0x00, 0x18, 0x00, 0x19, 0xE0, 0x1A, 0x30, 0x1C, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x7E, 0x7E, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, /* "h",72 */
{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x80, 0x03, 0xC0, 0x01, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x1F, 0x80, 0x01, 0x80, 0x01, 0x80, 0x01, 0x80, 0x01, 0x80, 0x01, 0x80, 0x01, 0x80, 0x01, 0x80, 0x01, 0x80, 0x01, 0x80, 0x01, 0x80, 0x01, 0x80, 0x01, 0x80, 0x01, 0x80, 0x1F, 0xF8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, /* "i",73 */
{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x38, 0x00, 0x78, 0x00, 0x30, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x03, 0xF0, 0x00, 0x30, 0x00, 0x30, 0x00, 0x30, 0x00, 0x30, 0x00, 0x30, 0x00, 0x30, 0x00, 0x30, 0x00, 0x30, 0x00, 0x30, 0x00, 0x30, 0x00, 0x30, 0x00, 0x30, 0x00, 0x30, 0x00, 0x30, 0x00, 0x30, 0x18, 0x60, 0x18, 0x40, 0x0F, 0x80}, /* "j",74 */
{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x00, 0x78, 0x00, 0x18, 0x00, 0x18, 0x00, 0x18, 0x00, 0x18, 0x00, 0x18, 0x00, 0x18, 0x00, 0x18, 0x7C, 0x18, 0x30, 0x18, 0x20, 0x18, 0x40, 0x18, 0x80, 0x19, 0x80, 0x1B, 0x80, 0x1E, 0xC0, 0x1C, 0xC0, 0x18, 0x60, 0x18, 0x30, 0x18, 0x30, 0x18, 0x18, 0x18, 0x1C, 0x7E, 0x3E, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, /* "k",75 */
{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x1F, 0x80, 0x01, 0x80, 0x01, 0x80, 0x01, 0x80, 0x01, 0x80, 0x01, 0x80, 0x01, 0x80, 0x01, 0x80, 0x01, 0x80, 0x01, 0x80, 0x01, 0x80, 0x01, 0x80, 0x01, 0x80, 0x01, 0x80, 0x01, 0x80, 0x01, 0x80, 0x01, 0x80, 0x01, 0x80, 0x01, 0x80, 0x01, 0x80, 0x01, 0x80, 0x1F, 0xF8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, /* "l",76 */
{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x20, 0x00, 0xEF, 0x3C, 0x71, 0xC6, 0x61, 0x86, 0x61, 0x86, 0x61, 0x86, 0x61, 0x86, 0x61, 0x86, 0x61, 0x86, 0x61, 0x86, 0x61, 0x86, 0x61, 0x86, 0x61, 0x86, 0x61, 0x86, 0x61, 0x86, 0xF3, 0xCF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, /* "m",77 */
{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x09, 0xE0, 0x7A, 0x30, 0x1C, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x7E, 0x7E, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, /* "n",78 */
{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0xC0, 0x0C, 0x30, 0x08, 0x18, 0x18, 0x18, 0x10, 0x0C, 0x30, 0x0C, 0x30, 0x0C, 0x30, 0x0C, 0x30, 0x0C, 0x30, 0x0C, 0x30, 0x0C, 0x18, 0x18, 0x18, 0x18, 0x0C, 0x30, 0x03, 0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, /* "o",79 */
{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x09, 0xE0, 0x7A, 0x30, 0x1C, 0x18, 0x18, 0x08, 0x18, 0x0C, 0x18, 0x0C, 0x18, 0x0C, 0x18, 0x0C, 0x18, 0x0C, 0x18, 0x0C, 0x18, 0x0C, 0x18, 0x18, 0x1C, 0x18, 0x1E, 0x30, 0x19, 0xE0, 0x18, 0x00, 0x18, 0x00, 0x18, 0x00, 0x7E, 0x00}, /* "p",80 */
{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0xC8, 0x0C, 0x78, 0x18, 0x38, 0x18, 0x18, 0x30, 0x18, 0x30, 0x18, 0x30, 0x18, 0x30, 0x18, 0x30, 0x18, 0x30, 0x18, 0x30, 0x18, 0x10, 0x18, 0x18, 0x38, 0x0C, 0x78, 0x07, 0x98, 0x00, 0x18, 0x00, 0x18, 0x00, 0x18, 0x00, 0x7E}, /* "q",81 */
{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x06, 0x1C, 0x7E, 0x66, 0x06, 0x86, 0x07, 0x80, 0x07, 0x00, 0x06, 0x00, 0x06, 0x00, 0x06, 0x00, 0x06, 0x00, 0x06, 0x00, 0x06, 0x00, 0x06, 0x00, 0x06, 0x00, 0x06, 0x00, 0x7F, 0xE0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, /* "r",82 */
{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0xE4, 0x06, 0x1C, 0x0C, 0x0C, 0x0C, 0x04, 0x0C, 0x04, 0x0E, 0x00, 0x07, 0xC0, 0x01, 0xF0, 0x00, 0x78, 0x00, 0x1C, 0x10, 0x0C, 0x10, 0x0C, 0x18, 0x0C, 0x1C, 0x18, 0x13, 0xF0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, /* "s",83 */
{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0x01, 0x00, 0x03, 0x00, 0x07, 0x00, 0x3F, 0xF8, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x04, 0x03, 0x04, 0x01, 0x88, 0x00, 0xF0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, /* "t",84 */
{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x08, 0x78, 0x78, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x38, 0x0C, 0x5E, 0x07, 0x90, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, /* "u",85 */
{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7C, 0x3E, 0x18, 0x0C, 0x18, 0x08, 0x18, 0x18, 0x0C, 0x10, 0x0C, 0x10, 0x04, 0x20, 0x06, 0x20, 0x06, 0x20, 0x03, 0x40, 0x03, 0x40, 0x03, 0xC0, 0x01, 0x80, 0x01, 0x80, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, /* "v",86 */
{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFB, 0xCF, 0x61, 0x86, 0x21, 0x84, 0x31, 0x84, 0x31, 0x84, 0x31, 0xC8, 0x11, 0xC8, 0x1A, 0xC8, 0x1A, 0x48, 0x1A, 0x70, 0x0E, 0x70, 0x0C, 0x70, 0x0C, 0x30, 0x0C, 0x20, 0x04, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, /* "w",87 */
{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3E, 0x7C, 0x0C, 0x10, 0x0E, 0x10, 0x06, 0x20, 0x03, 0x40, 0x03, 0x40, 0x01, 0x80, 0x01, 0x80, 0x01, 0xC0, 0x02, 0x60, 0x04, 0x60, 0x04, 0x30, 0x08, 0x18, 0x18, 0x18, 0x7C, 0x7E, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, /* "x",88 */
{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7C, 0x3E, 0x18, 0x18, 0x18, 0x10, 0x08, 0x10, 0x0C, 0x10, 0x04, 0x20, 0x06, 0x20, 0x06, 0x20, 0x02, 0x40, 0x03, 0x40, 0x01, 0x40, 0x01, 0x80, 0x01, 0x80, 0x01, 0x00, 0x01, 0x00, 0x01, 0x00, 0x02, 0x00, 0x3E, 0x00, 0x3C, 0x00}, /* "y",89 */
{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3F, 0xF8, 0x30, 0x38, 0x30, 0x30, 0x20, 0x60, 0x20, 0xE0, 0x00, 0xC0, 0x01, 0x80, 0x03, 0x80, 0x03, 0x00, 0x06, 0x00, 0x0E, 0x04, 0x0C, 0x04, 0x18, 0x0C, 0x30, 0x18, 0x3F, 0xF8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, /* "z",90 */
{0x00, 0x00, 0x00, 0x00, 0x00, 0x0C, 0x00, 0x10, 0x00, 0x20, 0x00, 0x20, 0x00, 0x20, 0x00, 0x20, 0x00, 0x20, 0x00, 0x20, 0x00, 0x20, 0x00, 0x20, 0x00, 0x20, 0x00, 0x20, 0x00, 0x20, 0x00, 0xC0, 0x01, 0x80, 0x00, 0x40, 0x00, 0x20, 0x00, 0x20, 0x00, 0x20, 0x00, 0x20, 0x00, 0x20, 0x00, 0x20, 0x00, 0x20, 0x00, 0x20, 0x00, 0x20, 0x00, 0x20, 0x00, 0x20, 0x00, 0x10, 0x00, 0x0C, 0x00, 0x00}, /* "{",91 */
{0x00, 0x80, 0x00, 0x80, 0x00, 0x80, 0x00, 0x80, 0x00, 0x80, 0x00, 0x80, 0x00, 0x80, 0x00, 0x80, 0x00, 0x80, 0x00, 0x80, 0x00, 0x80, 0x00, 0x80, 0x00, 0x80, 0x00, 0x80, 0x00, 0x80, 0x00, 0x80, 0x00, 0x80, 0x00, 0x80, 0x00, 0x80, 0x00, 0x80, 0x00, 0x80, 0x00, 0x80, 0x00, 0x80, 0x00, 0x80, 0x00, 0x80, 0x00, 0x80, 0x00, 0x80, 0x00, 0x80, 0x00, 0x80, 0x00, 0x80, 0x00, 0x80, 0x00, 0x80}, /* "|",92 */
{0x00, 0x00, 0x00, 0x00, 0x18, 0x00, 0x04, 0x00, 0x02, 0x00, 0x02, 0x00, 0x02, 0x00, 0x02, 0x00, 0x02, 0x00, 0x02, 0x00, 0x02, 0x00, 0x02, 0x00, 0x02, 0x00, 0x02, 0x00, 0x02, 0x00, 0x01, 0x80, 0x00, 0xC0, 0x01, 0x00, 0x02, 0x00, 0x02, 0x00, 0x02, 0x00, 0x02, 0x00, 0x02, 0x00, 0x02, 0x00, 0x02, 0x00, 0x02, 0x00, 0x02, 0x00, 0x02, 0x00, 0x02, 0x00, 0x04, 0x00, 0x18, 0x00, 0x00, 0x00}, /* "}",93 */
{0x00, 0x00, 0x1E, 0x00, 0x23, 0x00, 0x41, 0x82, 0x40, 0x82, 0x00, 0xE4, 0x00, 0x38, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, /* "~",94 */};

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,12 @@
// 由 terminal/tools/gen_assets.py 生成,请勿手改。
/* 16x16 点阵中文字库:GB2312 一级字 + 常用标点,行式 2 字节/行,MSB 为最左像素。 */
#pragma once
#include <stdint.h>
#include <stdbool.h>
#define CJK_CELL 16
#define CJK_COUNT 3775
/** 按码位二分;缺字返回 NULL(调用字画空心方框) */
const uint8_t *cjk_glyph(uint32_t cp);

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,50 @@
// 由 terminal/tools/gen_assets.py 生成,请勿手改。
/* 天体霓虹线稿图标:无 alpha 的 RGB565,固件用叠加混合绘制(黑色不落地)。 */
#pragma once
#include <stdint.h>
#define ICON_LIST_W 40
#define ICON_LIST_H 40
#define ICON_DETAIL_W 64
#define ICON_DETAIL_H 64
typedef struct { const uint16_t *px; uint8_t w, h; } IconArt;
extern const IconArt ic_planet_list; /* 行星小.jpeg */
extern const IconArt ic_jupiter_list; /* 木星小.jpeg */
extern const IconArt ic_saturn_list; /* 土星小.jpeg */
extern const IconArt ic_mars_list; /* 火星小.jpeg */
extern const IconArt ic_earth_list; /* 地球小.jpeg */
extern const IconArt ic_earth_icon_list; /* 地球-图标小.jpeg */
extern const IconArt ic_venus_list; /* 金星(图标)小.jpeg */
extern const IconArt ic_neptune_list; /* 海王星小.jpeg */
extern const IconArt ic_sun_list; /* 太阳小.jpeg */
extern const IconArt ic_star_list; /* 恒星小.jpeg */
extern const IconArt ic_comet_list; /* 彗星小.jpeg */
extern const IconArt ic_halley_list; /* 哈雷彗星小.jpeg */
extern const IconArt ic_galaxy_list; /* 星系小.jpeg */
extern const IconArt ic_satellite_list; /* 卫星小.jpeg */
extern const IconArt ic_probe_list; /* 通信卫星小.jpeg */
extern const IconArt ic_shuttle_list; /* 航天飞机小.jpeg */
extern const IconArt ic_rover_list; /* 火星车小.jpeg */
extern const IconArt ic_planet_detail;
extern const IconArt ic_jupiter_detail;
extern const IconArt ic_saturn_detail;
extern const IconArt ic_mars_detail;
extern const IconArt ic_earth_detail;
extern const IconArt ic_earth_icon_detail;
extern const IconArt ic_venus_detail;
extern const IconArt ic_neptune_detail;
extern const IconArt ic_sun_detail;
extern const IconArt ic_star_detail;
extern const IconArt ic_comet_detail;
extern const IconArt ic_halley_detail;
extern const IconArt ic_galaxy_detail;
extern const IconArt ic_satellite_detail;
extern const IconArt ic_probe_detail;
extern const IconArt ic_shuttle_detail;
extern const IconArt ic_rover_detail;
/** name/name_zh 小写子串命中优先,其次按 type 兜底;detail!=0 取大图 */
const IconArt *icon_for(const char *name, const char *name_zh, const char *type, int detail);

View File

@ -0,0 +1,103 @@
#include <Arduino.h>
#include <esp_heap_caps.h>
#include <string.h>
#include "iconstore.h"
#define SLOT_ART 2 /* [0]=列表 40x40 [1]=详情 64x64 */
typedef struct {
char id[16]; /* 占位的天体 id,空槽为空串 */
uint32_t ver; /* 已缓存的图标资源号,0 = 数据不可用 */
uint16_t *px[SLOT_ART];
IconArt art[SLOT_ART];
} IconSlot;
/* 关注数上限就是槽位数:一个天体一个槽,换图标只是重新下载,不额外占内存 */
static IconSlot s_slot[MAX_BODIES];
static const uint8_t s_size[SLOT_ART] = { ICON_LIST_W, ICON_DETAIL_W };
static IconSlot *slot_find(const char *id)
{
for (int i = 0; i < MAX_BODIES; i++)
if (s_slot[i].id[0] && !strcmp(s_slot[i].id, id)) return &s_slot[i];
return NULL;
}
/* 先丢掉已经不在关注列表里的槽(缓冲区留着复用),再找一个能用的槽给这个天体 */
static IconSlot *slot_claim(const char *id, const Snapshot *snap)
{
for (int i = 0; i < MAX_BODIES; i++) {
IconSlot *s = &s_slot[i];
if (!s->id[0]) continue;
bool still_followed = false;
for (int n = 0; n < snap->count; n++)
if (!strcmp(snap->bodies[n].id, s->id)) { still_followed = true; break; }
if (!still_followed) { s->id[0] = 0; s->ver = 0; }
}
IconSlot *free_slot = NULL;
for (int i = 0; i < MAX_BODIES; i++) {
IconSlot *s = &s_slot[i];
if (s->id[0] && !strcmp(s->id, id)) return s;
if (!s->id[0] && !free_slot) free_slot = s;
}
if (!free_slot) free_slot = &s_slot[0]; /* 满员(关注数超过 MAX_BODIES 才会)就抢占 */
strlcpy(free_slot->id, id, sizeof(free_slot->id));
free_slot->ver = 0;
return free_slot;
}
static bool slot_fetch(IconSlot *s, const char *base, const char *token,
const char *body_id, uint32_t ver)
{
for (int k = 0; k < SLOT_ART; k++) {
if (!s->px[k]) {
size_t bytes = (size_t)s_size[k] * s_size[k] * 2;
s->px[k] = (uint16_t *)heap_caps_malloc(bytes, MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT);
if (!s->px[k]) { Serial.printf("[icon] %s no PSRAM for %dx%d\n", body_id, s_size[k], s_size[k]); return false; }
}
int http = 0;
size_t bytes = (size_t)s_size[k] * s_size[k] * 2;
if (!api_icon(base, token, body_id, s_size[k], s->px[k], bytes, &http)) {
Serial.printf("[icon] %s %dx%d fetch failed http=%d\n", body_id, s_size[k], s_size[k], http);
return false;
}
s->art[k] = IconArt{ s->px[k], s_size[k], s_size[k] };
}
s->ver = ver;
return true;
}
const IconArt *icon_store_get(const BodyData *b, int detail)
{
if (!b->icon_ver || !b->id[0]) return NULL;
IconSlot *s = slot_find(b->id);
if (!s || s->ver != b->icon_ver) return NULL;
int k = detail ? 1 : 0;
return s->px[k] ? &s->art[k] : NULL;
}
void icon_store_sync(const char *base, const char *token, const Snapshot *snap)
{
if (!base || !base[0] || !token || !token[0] || !snap) return;
for (int i = 0; i < snap->count; i++) {
const BodyData &b = snap->bodies[i];
if (!b.icon_ver || !b.id[0]) continue; /* 后台没维护图标 */
IconSlot *s = slot_claim(b.id, snap);
if (s->ver == b.icon_ver) continue; /* 已经是最新,一个字节都不拉 */
uint32_t t0 = millis();
if (slot_fetch(s, base, token, b.id, b.icon_ver))
Serial.printf("[icon] %s v%lu ok %lums\n", b.id, (unsigned long)b.icon_ver,
(unsigned long)(millis() - t0));
}
}
void icon_store_dump(void)
{
for (int i = 0; i < MAX_BODIES; i++) {
IconSlot *s = &s_slot[i];
if (!s->id[0]) continue;
Serial.printf("icon : %s v%lu %s\n", s->id, (unsigned long)s->ver,
s->ver ? "cached" : "empty");
}
}

View File

@ -0,0 +1,15 @@
/** 后台(平台管理 -> 天体信息)维护的天体图标的运行时缓存
* 快照里的 icon_ver 变了才重新下载;没维护/下载失败时退回固件内置线稿。
* 点阵放 PSRAM,和内置图标一样是"叠加混合"用的 RGB565 大端裸数据。 */
#pragma once
#include "api.h"
#include "icons.h"
/** 缓存里有这个天体的图就返回它,否则返回 NULL;detail!=0 要 64x64 大图 */
const IconArt *icon_store_get(const BodyData *b, int detail);
/** 下载快照里缺的 / 版本变了的图标(走 HTTP,放在 5 分钟数据刷新里调用) */
void icon_store_sync(const char *base, const char *token, const Snapshot *snap);
/** 串口调试:逐槽打印 id / 版本 / 是否已缓存 */
void icon_store_dump(void);

View File

@ -0,0 +1,101 @@
#include <Arduino.h>
#include <string.h>
#include <WiFi.h>
#include <DNSServer.h>
#include <WebServer.h>
#include "portal.h"
#include "store.h"
static DNSServer s_dns;
static WebServer s_server(80);
static bool s_saved = false;
static const char *PAGE_HEAD =
"<meta name=viewport content='width=device-width,initial-scale=1'>"
"<style>body{font-family:system-ui;background:#04121a;color:#cfe;padding:16px}"
"input,select,button{width:100%;padding:10px;margin:6px 0;font-size:16px}"
"h3{color:#4ee}</style>";
static void handle_root()
{
char api[96] = {0};
if (!store_get_str(K_API, api, sizeof(api))) strcpy(api, "http://192.168.31.2:8000/api");
int n = WiFi.scanNetworks();
String opts;
for (int i = 0; i < n; i++) {
opts += "<option value='";
opts += WiFi.SSID(i);
opts += "'>";
opts += WiFi.SSID(i);
opts += " (";
opts += String(WiFi.RSSI(i));
opts += " dBm)</option>";
}
String page = "<html><head><meta charset=utf-8>";
page += PAGE_HEAD;
page += "</head><body><h3>COSMO \xe7\xbb\x88\xe7\xab\xaf\xe9\x85\x8d\xe7\xbd\x91</h3>"; /* 终端配网 */
page += "<form method=POST action=/join>";
page += "<label>WiFi</label><select name=ssid>" + opts + "</select>";
page += "<label>\xe5\xaf\x86\xe7\xa0\x81</label><input name=pass type=text>"; /* 密码 */
page += "<label>\xe5\x90\x8e\xe7\xab\xaf\xe5\x9c\xb0\xe5\x9d\x80</label><input name=api value='"; /* 后端地址 */
page += api;
page += "'><br><button type=submit>\xe4\xbf\x9d\xe5\xad\x98</button></form>"; /* 保存 */
page += "<p style='color:#8ab;font-size:13px'>\xe4\xbf\x9d\xe5\xad\x98\xe5\x90\x8e\xe8\xae\xbe\xe5\xa4\x87\xe8\x87\xaa\xe5\x8a\xa8\xe9\x87\x8d\xe5\x90\xaf</p>";
page += "</body></html>";
s_server.send(200, "text/html", page);
}
static void handle_join()
{
String ssid = s_server.hasArg("ssid") ? s_server.arg("ssid") : "";
String pass = s_server.hasArg("pass") ? s_server.arg("pass") : "";
String api = s_server.hasArg("api") ? s_server.arg("api") : "";
ssid.trim(); api.trim();
if (!ssid.length()) {
s_server.send(400, "text/plain", "missing ssid");
return;
}
store_set_str(K_SSID, ssid.c_str());
store_set_str(K_PASS, pass.c_str());
if (api.length()) store_set_str(K_API, api.c_str());
Serial.printf("[portal] saved ssid=%s api=%s\n", ssid.c_str(), api.c_str());
s_server.send(200, "text/html",
"<html><meta charset=utf-8><body style='font-family:system-ui'>"
"\xe5\xb7\xb2\xe4\xbf\x9d\xe5\xad\x98\xef\xbc\x8c\xe8\xae\xbe\xe5\xa4\x87\xe6\xad\xa3\xe5\x9c\xa8\xe9\x87\x8d\xe5\x90\xaf</body></html>");
s_saved = true;
}
/* 手机/系统探测门户时回到配网页 */
static void handle_captive()
{
s_server.sendHeader("Location", "http://192.168.4.1/", true);
s_server.send(302, "text/plain", "");
}
void portal_start(const char *ap_ssid, const char *api_default)
{
WiFi.mode(WIFI_MODE_AP);
WiFi.softAP(ap_ssid);
s_dns.start(53, "*", WiFi.softAPIP());
s_server.on("/", HTTP_GET, handle_root);
s_server.on("/join", HTTP_POST, handle_join);
s_server.on("/generate_204", handle_captive);
s_server.on("/hotspot-detect.html", handle_captive);
s_server.on("/connecttest.txt", handle_captive);
s_server.onNotFound(handle_captive);
s_server.begin();
Serial.printf("[portal] AP=%s api=%s ip=%s\n", ap_ssid, api_default, WiFi.softAPIP().toString().c_str());
}
void portal_loop()
{
s_dns.processNextRequest();
s_server.handleClient();
}
bool portal_saved()
{
return s_saved;
}

View File

@ -0,0 +1,7 @@
/** 无凭据时开热点,用手机强制门户配网(SSID/密码/后端地址存 NVS) */
#pragma once
#include <stdbool.h>
void portal_start(const char *ap_ssid, const char *api_default);
void portal_loop();
bool portal_saved(); /* 收到表单后置位,主循环据此重启 */

View File

@ -0,0 +1,29 @@
#include <Preferences.h>
#include <string.h>
#include "store.h"
static Preferences s_prefs;
void store_begin()
{
s_prefs.begin("cosmo", false);
}
bool store_get_str(const char *key, char *out, size_t cap)
{
if (!s_prefs.isKey(key)) return false;
String v = s_prefs.getString(key, "");
strncpy(out, v.c_str(), cap - 1);
out[cap - 1] = 0;
return out[0] != 0;
}
void store_set_str(const char *key, const char *val)
{
s_prefs.putString(key, val);
}
void store_erase(const char *key)
{
s_prefs.remove(key);
}

View File

@ -0,0 +1,15 @@
/** NVS 持久化:WiFi 凭据、后端地址、终端 token */
#pragma once
#include <stdbool.h>
#include <stddef.h>
void store_begin();
bool store_get_str(const char *key, char *out, size_t cap);
void store_set_str(const char *key, const char *val);
void store_erase(const char *key);
#define K_SSID "ssid"
#define K_PASS "pass"
#define K_API "api"
#define K_TOKEN "token"
#define K_USER "user"

View File

@ -0,0 +1,397 @@
#include <Arduino.h>
#include <math.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include "ui.h"
#include "iconstore.h"
#include "display.h"
#include "icons.h"
#include "board_config.h"
/* 版面:状态栏 0..19 / 内容区 22..212 / 按键条 216..235(切角金色按钮=板上物理按键图例) */
#define TOP_Y 22
#define BOT_Y 212
#define KEY_Y 216
#define KEY_H 20
#define LIST_ROWS 3 /* 3 张卡:y=22+n*65,h=60,正好铺到 212 */
static void text_right(int x_right, int y, const char *s, uint8_t size, uint16_t fg, uint16_t bg)
{
disp_text(x_right - disp_text_width(s, size, 1), y, s, size, fg, bg);
}
/* 取前 max_chars 个字符(UTF-8 安全),截断了就在末尾补 ".." */
static void clip_chars(char *dst, size_t cap, const char *src, int max_chars)
{
int used = 0, n = 0, chars = 0;
while (src[n] && chars < max_chars && used + 4 < (int)cap) {
unsigned char c = (unsigned char)src[n];
int l = (c >= 0xF0) ? 4 : (c >= 0xE0) ? 3 : (c >= 0xC0) ? 2 : 1;
for (int k = 0; k < l; k++) dst[used + k] = src[n + k];
used += l; n += l; chars++;
}
dst[used] = 0;
if (src[n] && used + 2 < (int)cap) { dst[used++] = '.'; dst[used++] = '.'; dst[used] = 0; }
}
/* 中文名与英文名不同时才中英并列(系外行星的 name_zh 往往就是英文名) */
static void body_title(const BodyData &b, char *dst, size_t cap)
{
if (b.name_zh[0] && strcmp(b.name_zh, b.name)) snprintf(dst, cap, "%s %s", b.name_zh, b.name);
else strlcpy(dst, b.name, cap);
}
/* 图标优先用后台「平台管理 -> 天体信息」里维护的那张(已缓存到 PSRAM),
没维护或还没拉下来时退回固件内置线稿,尺寸一致所以版面不用分叉 */
static const IconArt *body_art(const BodyData &b, int detail)
{
const IconArt *dyn = icon_store_get(&b, detail);
return dyn ? dyn : icon_for(b.name, b.name_zh, b.type, detail);
}
static void status_bar(const UiState &st, const char *right)
{
if (st.wifi_up) {
char sig[24];
snprintf(sig, sizeof(sig), "NET:ONLINE RSSI:%d", st.rssi);
disp_text(4, 2, sig, 16, C_CYAN, C_BG);
} else {
disp_text(4, 2, "NET:OFFLINE", 16, C_RED, C_BG);
}
if (right && right[0]) text_right(LCD_WIDTH - 4, 2, right, 16, C_CYAN, C_BG);
disp_hline(0, 19, LCD_WIDTH, C_CYAN_DIM);
}
/* 这块屏没有触摸层,底部四条是板上物理按键的说明,按下时整块反色做反馈 */
static void key_bar(const char *const *labels, uint8_t flash)
{
const int x0 = 3, gap = 2, right = LCD_WIDTH - x0;
int w[4], sum = 0;
for (int i = 0; i < 4; i++) {
w[i] = disp_text_width(labels[i][0] ? labels[i] : "KEYn XXX", 16, 1) + 14;
sum += w[i];
}
int avail = (right - x0) - 3 * gap, x = x0;
for (int i = 0; i < 4; i++) {
int bw = (i == 3) ? (right - x) : avail * w[i] / sum;
bool hit = flash & (1 << i);
uint16_t bg = hit ? C_GOLD : C_PANEL;
disp_panel(x, KEY_Y, bw, KEY_H, 5, bg, hit ? C_GOLD_LT : C_GOLD);
if (labels[i][0]) disp_text_center(x, KEY_Y + 2, bw, labels[i], 16, hit ? C_GOLD_DK : C_GOLD, bg);
x += bw + gap;
}
}
static const char *const KEYS_NAV[] = { "KEY0 UP", "KEY1 DN", "KEY2 OK", "KEY3 REF" };
static const char *const KEYS_DETAIL[] = { "KEY0 UP", "KEY1 DN", "KEY2 BACK", "KEY3 TAB" };
static const char *const KEYS_PAIR[] = { "", "", "KEY2 INFO", "KEY3 CODE" };
static const char *const KEYS_EMPTY[] = { "", "", "", "" };
static void fmt_au(char *buf, size_t cap, float v)
{
if (v >= 100.0f) snprintf(buf, cap, "%.1f", v);
else if (v >= 10.0f) snprintf(buf, cap, "%.2f", v);
else snprintf(buf, cap, "%.3f", v);
}
static void draw_splash(const UiState &st)
{
/* 两条程序化轨道打底,面板压在轨道之上 */
for (int i = 0; i < 180; i++) {
float a = i * 3.1415926f / 90.0f;
disp_pixel(160 + (int)(cosf(a) * 150), 120 + (int)(sinf(a) * 58), C_TRACE);
disp_pixel(160 + (int)(cosf(a) * 116), 120 + (int)(sinf(a) * 40), C_TRACE);
}
disp_disc(160 + (int)(cosf(3.6f) * 150), 120 + (int)(sinf(3.6f) * 58), 2, C_CYAN_DIM);
disp_disc(160 + (int)(cosf(0.7f) * 116), 120 + (int)(sinf(0.7f) * 40), 2, C_GOLD_DIM);
disp_panel_glow(52, 52, 216, 76, 12, C_CYAN_DIM);
disp_panel(52, 52, 216, 76, 12, C_PANEL, C_CYAN);
/* 辉光 = 同一字模向四个方向用低阶色先印一遍,最后覆盖亮色 */
static const int off[4][2] = { { -1, 0 }, { 1, 0 }, { 0, -1 }, { 0, 1 } };
for (int i = 0; i < 4; i++)
disp_text_center(52 + off[i][0], 58 + off[i][1], 216, "COSMO", 32, C_CYAN_DIM, C_PANEL, 2);
disp_text_center(52, 58, 216, "COSMO", 32, C_GREEN, C_PANEL, 2);
disp_text_center(0, 140, LCD_WIDTH, "ORBITAL TERMINAL", 16, C_CYAN, C_BG);
disp_text_center(0, 164, LCD_WIDTH, st.device_id, 16, C_DIM, C_BG);
if (st.ssid[0]) {
char msg[48];
snprintf(msg, sizeof(msg), "WIFI %s", st.ssid);
disp_text_center(0, 186, LCD_WIDTH, msg, 16, C_DIM, C_BG);
}
}
static void draw_provision(const UiState &st)
{
const int px = 8, py = 26, pw = LCD_WIDTH - 16, ph = 184;
disp_panel_glow(px, py, pw, ph, 10, C_CYAN_DIM);
disp_panel(px, py, pw, ph, 10, C_PANEL, C_GOLD);
disp_text(px + 12, py + 8, "NO WIFI CONFIG", 16, C_GOLD, C_PANEL);
char msg[64];
disp_text(px + 12, py + 36, "1. JOIN HOTSPOT", 16, C_DIM, C_PANEL);
snprintf(msg, sizeof(msg), "%s", st.ap_ssid);
disp_text_clipped(px + 12, py + 54, pw - 24, msg, 16, C_GOLD, C_PANEL);
disp_text(px + 12, py + 78, "2. OPEN IN BROWSER", 16, C_DIM, C_PANEL);
disp_text(px + 12, py + 96, "http://192.168.4.1", 16, C_CYAN, C_PANEL);
disp_text(px + 12, py + 120, "3. SAVE WIFI + BACKEND SETTINGS", 16, C_DIM, C_PANEL);
disp_text_wrap(px + 12, py + 138, pw - 24,
"The terminal reboots and shows a 6 digit binding code, enter it on the web site to finish.",
16, C_TEXT, C_PANEL, 2);
snprintf(msg, sizeof(msg), "API %s", st.api);
disp_text_clipped(px + 12, py + 162, pw - 24, msg, 16, C_CYAN_DIM, C_PANEL);
}
static void draw_connecting(const UiState &st)
{
const int px = 40, py = 64, pw = 240, ph = 112;
disp_panel(px, py, pw, ph, 10, C_PANEL, C_CYAN);
disp_text_center(px, py + 10, pw, "CONNECTING", 16, C_CYAN, C_PANEL);
/* 环形进度:一圈刻度 + 随 millis 转动的指针 */
disp_ring(160, 92, 14, C_CYAN_DIM);
float a = (millis() % 1600) / 1600.0f * 2 * 3.1415926f;
disp_disc(160 + (int)(cosf(a) * 14), 92 + (int)(sinf(a) * 14), 3, C_GREEN);
char msg[48];
uint32_t dots = (millis() / 400) % 4;
snprintf(msg, sizeof(msg), "%s%.*s", st.ssid, (int)dots, "...");
disp_text_clipped(px + 8, py + 62, pw - 16, msg, 16, C_GREEN, C_PANEL);
snprintf(msg, sizeof(msg), "API %s", st.api);
disp_text_clipped(px + 8, py + 82, pw - 16, msg, 16, C_DIM, C_PANEL);
}
static void draw_pair(const UiState &st)
{
const int px = 8, py = 28, pw = LCD_WIDTH - 16, ph = 180;
disp_panel_glow(px, py, pw, ph, 10, C_CYAN_DIM);
disp_panel(px, py, pw, ph, 10, C_PANEL, C_GREEN);
disp_text_center(px, py + 8, pw, "DEVICE BINDING", 16, C_GREEN, C_PANEL);
if (!st.code[0]) {
disp_text_wrap(px + 14, py + 40, pw - 28, st.message, 16, C_ORANGE, C_PANEL, 5);
return;
}
const int bx = px + 22, bw = pw - 44;
disp_panel(bx, py + 28, bw, 76, 6, C_BG, C_CYAN_DIM);
int adv = 34; /* 16x32 字模放大 2 倍 = 32x64 */
int cw = (int)strlen(st.code) * adv - 2;
int x = (LCD_WIDTH - cw) / 2;
for (const char *p = st.code; *p; p++, x += adv) disp_text(x, py + 34, p, 32, C_GREEN, C_BG, 2);
/* 有效期倒计时条:最后 15 秒转红 */
int fill = 0;
if (st.code_total > 0) fill = bw * st.code_left / st.code_total;
disp_fill(bx + 12, py + 112, bw - 24, 6, C_TRACE);
disp_fill(bx + 12, py + 112, (bw - 24) * fill / (bw ? bw : 1), 6, st.code_left < 15 ? C_RED : C_GOLD);
char msg[48];
snprintf(msg, sizeof(msg), "EXPIRES IN %ds", st.code_left);
disp_text_center(px, py + 126, pw, msg, 16, st.code_left < 15 ? C_RED : C_GOLD, C_PANEL);
snprintf(msg, sizeof(msg), "ENTER CODE ON WEB / USER: %s", st.owner[0] ? st.owner : "?");
disp_text_clipped(px + 10, py + 146, pw - 20, msg, 16, C_TEXT, C_PANEL);
snprintf(msg, sizeof(msg), "DEV %s", st.device_id);
disp_text_clipped(px + 10, py + 164, pw - 20, msg, 16, C_CYAN_DIM, C_PANEL);
}
static void draw_loading(const UiState &st)
{
const int px = 40, py = 68, pw = 240, ph = 100;
disp_panel(px, py, pw, ph, 10, C_PANEL, C_CYAN);
uint32_t tick = (millis() / 200) % 8;
char msg[56];
snprintf(msg, sizeof(msg), "SYNCING DATA");
disp_text_center(px, py + 12, pw, msg, 16, C_CYAN, C_PANEL);
/* 8 格跑马刻度 */
for (int i = 0; i < 8; i++)
disp_fill(px + 40 + i * 20, py + 42, 14, 8, ((i + tick) % 8 < 3) ? C_CYAN : C_CYAN_DIM);
snprintf(msg, sizeof(msg), "USER: %s", st.owner[0] ? st.owner : "?");
disp_text_clipped(px + 10, py + 62, pw - 20, msg, 16, C_GREEN, C_PANEL);
snprintf(msg, sizeof(msg), "API %s", st.api);
disp_text_clipped(px + 10, py + 80, pw - 20, msg, 16, C_DIM, C_PANEL);
}
static void draw_list(const UiState &st)
{
const Snapshot *s = st.snap;
if (!s || !s->count) {
disp_text_center(0, 84, LCD_WIDTH, "NO FOLLOWED BODIES", 16, C_ORANGE, C_BG);
disp_text_center(0, 108, LCD_WIDTH, "FOLLOW ONE ON THE WEB UI", 16, C_DIM, C_BG);
return;
}
int scroll = st.sel;
if (scroll > s->count - LIST_ROWS) scroll = s->count - LIST_ROWS;
if (scroll < 0) scroll = 0;
for (int i = scroll; i < s->count && i < scroll + LIST_ROWS; i++) {
const BodyData &b = s->bodies[i];
int y = TOP_Y + (i - scroll) * 65;
bool sel = (i == st.sel);
uint16_t bg = sel ? C_SEL : C_PANEL;
if (sel) disp_panel_glow(3, y, 314, 60, 8, C_CYAN_DIM);
disp_panel(3, y, 314, 60, 8, bg, sel ? C_CYAN : C_CYAN_DIM);
disp_fill(6, y + 9, 3, 42, sel ? C_GOLD : C_TRACE);
const IconArt *ic = body_art(b, 0);
if (ic) disp_add_bitmap(13, y + 10, ic->w, ic->h, ic->px);
char title[56];
body_title(b, title, sizeof(title));
disp_text_clipped(60, y + 8, 188, title, 16, sel ? C_WHITE : C_TEXT, bg);
char line[32], v[16];
fmt_au(v, sizeof(v), b.dist);
snprintf(line, sizeof(line), "DIST: %s AU", v);
disp_text(60, y + 34, line, 16, sel ? C_GOLD : C_CYAN_DIM, bg);
/* 订阅状态胶囊:只读,跟随后端 is_active */
bool on = b.active;
uint16_t sc = on ? C_GOLD : C_DIM;
disp_panel(256, y + 8, 46, 20, 8, on ? C_GOLD_DK : bg, sc);
disp_disc(256 + (on ? 35 : 10), y + 18, 6, sc);
disp_text_center(252, y + 34, 54, on ? "ON" : "OFF", 16, sc, bg);
}
/* 右缘滚动条取代原来的 v+N 文字 */
int sbh = BOT_Y - TOP_Y + 1;
disp_fill(317, TOP_Y, 2, sbh, C_TRACE);
int th = sbh * LIST_ROWS / s->count;
if (th > sbh) th = sbh;
if (th < 12) th = 12;
int span = s->count - LIST_ROWS;
int ty = TOP_Y + (span > 0 ? (sbh - th) * scroll / span : 0);
disp_fill(317, ty, 2, th, C_CYAN);
}
static void draw_detail(const UiState &st)
{
const Snapshot *s = st.snap;
if (!s || st.sel >= s->count) return;
const BodyData &b = s->bodies[st.sel];
/* 标题:中文名 + 英文名 + 类型,右端是位置历元(年份省掉,屏太窄) */
char time_s[16];
strlcpy(time_s, (strlen(b.pos_time) >= 10) ? b.pos_time + 5 : b.pos_time, sizeof(time_s));
int timew = disp_text_width(time_s, 16, 1);
char title[72], name[56], typ[17];
body_title(b, name, sizeof(name));
int tn = 0;
for (; b.type[tn] && tn < (int)sizeof(typ) - 1; tn++) typ[tn] = toupper((unsigned char)b.type[tn]);
typ[tn] = 0;
snprintf(title, sizeof(title), "%s (%s)", name, typ);
disp_text_clipped(4, 20, LCD_WIDTH - 8 - timew - 8, title, 16, C_CYAN, C_BG);
text_right(LCD_WIDTH - 4, 20, time_s, 16, C_DIM, C_BG);
const int pw = 156, ph = 88, by = 40;
const int lx = 3, rx = 161;
disp_panel(lx, by, pw, ph, 6, C_PANEL, C_CYAN);
disp_panel(rx, by, pw, ph, 6, C_PANEL, C_GOLD);
disp_text(lx + 8, by + 4, "POS (AU)", 16, C_GOLD, C_PANEL);
disp_text(rx + 8, by + 4, "VEL (KM/S)", 16, C_GOLD, C_PANEL);
char v[20];
const int rows[4] = { by + 21, by + 37, by + 53, by + 69 };
const char *lp[4] = { "X", "Y", "Z", "DIST" };
float lv[4] = { b.x, b.y, b.z, b.dist };
const char *rp[4] = { "VX", "VY", "VZ", "SPEED" };
float rv[4] = { b.vx, b.vy, b.vz, b.speed };
for (int i = 0; i < 4; i++) {
disp_text(lx + 8, rows[i], lp[i], 16, C_CYAN_DIM, C_PANEL);
fmt_au(v, sizeof(v), lv[i]);
text_right(lx + pw - 8, rows[i], v, 16, (i == 3) ? C_WHITE : C_TEXT, C_PANEL);
disp_text(rx + 8, rows[i], rp[i], 16, C_GOLD_DIM, C_PANEL);
if (b.has_vel) snprintf(v, sizeof(v), "%.1f", rv[i]);
else snprintf(v, sizeof(v), "--");
text_right(rx + pw - 8, rows[i], v, 16, (i == 3) ? C_WHITE : C_TEXT, C_PANEL);
}
const int py = 132, bh = BOT_Y - py + 1;
/* 左:霓虹线稿天体图标 + 雷达底纹 */
disp_panel(3, py, 88, bh, 6, C_PANEL, C_CYAN_DIM);
disp_radar(47, py + bh / 2, 34);
const IconArt *ic = body_art(b, 1);
if (ic) disp_add_bitmap(47 - ic->w / 2, py + bh / 2 - ic->h / 2, ic->w, ic->h, ic->px);
/* 右:EVENTS / INFO 分页,KEY3 切换 */
const int qx = 95, qw = 222;
disp_panel_glow(qx, py, qw, bh, 6, C_CYAN_DIM);
disp_panel(qx, py, qw, bh, 6, C_PANEL, C_CYAN);
const char *tabs[2] = { "[EVENTS]", "[INFO]" };
int tx = qx + 8;
for (int i = 0; i < 2; i++) {
bool on = (st.detail_tab == i);
disp_text(tx, py + 4, tabs[i], 16, on ? C_GOLD : C_DIM, C_PANEL);
if (on) disp_hline(tx, py + 22, disp_text_width(tabs[i], 16, 1) - 1, C_GOLD);
tx += disp_text_width(tabs[i], 16, 1) + 12;
}
if (st.detail_tab == 0) {
if (!b.ev_count) {
disp_text(qx + 8, py + 24, "NO EVENTS", 16, C_DIM, C_PANEL);
return;
}
for (int i = 0; i < b.ev_count && i < MAX_EVENTS; i++) {
int y = py + 24 + i * 18;
char ds[8];
snprintf(ds, sizeof(ds), "%s ", (strlen(b.ev_date[i]) >= 10) ? b.ev_date[i] + 5 : b.ev_date[i]);
disp_text(qx + 8, y, ds, 16, C_CYAN_DIM, C_PANEL);
int used = disp_text_width(ds, 16, 1);
disp_text_clipped(qx + 8 + used, y, qw - 16 - used, b.ev[i], 16,
(i == 0) ? C_WHITE : C_TEXT, C_PANEL);
}
} else {
disp_text_clipped(qx + 8, py + 24, qw - 16, name, 16, C_WHITE, C_PANEL);
if (!b.desc[0]) {
disp_text(qx + 8, py + 44, "NO DESCRIPTION", 16, C_DIM, C_PANEL);
return;
}
char desc[96];
/* 两行 12 字:留一个字位给 clip_chars 补的 "..",否则截断标记会被行宽吃掉 */
clip_chars(desc, sizeof(desc), b.desc, 23);
disp_text_wrap(qx + 8, py + 44, qw - 16, desc, 16, C_TEXT, C_PANEL, 2);
}
}
static void draw_error(const UiState &st)
{
const int px = 8, py = 32, pw = LCD_WIDTH - 16, ph = 168;
disp_panel_glow(px, py, pw, ph, 10, C_RED);
disp_panel(px, py, pw, ph, 10, C_PANEL, C_RED);
disp_text_center(px, py + 10, pw, "FAULT", 32, C_RED, C_PANEL, 1);
disp_text_wrap(px + 14, py + 56, pw - 28, st.message, 16, C_ORANGE, C_PANEL, 5);
char msg[96];
snprintf(msg, sizeof(msg), "API %s", st.api);
disp_text_clipped(px + 14, py + ph - 24, pw - 28, msg, 16, C_DIM, C_PANEL);
}
void ui_draw(const UiState &st)
{
disp_bg();
const char *right = "COSMO";
if (st.screen == SC_LIST || st.screen == SC_DETAIL || st.screen == SC_LOADING) right = st.owner;
if (st.screen != SC_SPLASH) status_bar(st, right);
switch (st.screen) {
case SC_SPLASH: draw_splash(st); break;
case SC_PROVISION: draw_provision(st); break;
case SC_CONNECTING: draw_connecting(st); break;
case SC_PAIR: draw_pair(st); break;
case SC_LOADING: draw_loading(st); break;
case SC_LIST: draw_list(st); break;
case SC_DETAIL: draw_detail(st); break;
case SC_ERROR: draw_error(st); break;
}
const char *const *keys = KEYS_EMPTY;
if (st.screen == SC_LIST) keys = KEYS_NAV;
else if (st.screen == SC_DETAIL) keys = KEYS_DETAIL;
else if (st.screen == SC_PAIR) keys = KEYS_PAIR;
if (st.screen != SC_SPLASH) key_bar(keys, st.key_flash);
disp_flush();
}

View File

@ -0,0 +1,36 @@
/** 320x240 横屏版面:状态栏 + 内容区 + 底部按键条(对齐设计稿配色,去掉无数据源的模块) */
#pragma once
#include "api.h"
enum Screen {
SC_SPLASH = 0,
SC_PROVISION, /* 无 WiFi 凭据,开热点配网 */
SC_CONNECTING, /* 正在连接 WiFi */
SC_PAIR, /* 显示 6 位配对码,等待网页端绑定 */
SC_LOADING, /* 正在拉取订阅数据 */
SC_LIST, /* 关注天体列表 */
SC_DETAIL, /* 单个天体的位置/速度/事件 */
SC_ERROR
};
struct UiState {
Screen screen = SC_SPLASH;
char device_id[24] = "";
char ssid[33] = "";
char ap_ssid[33] = "";
char api[96] = "";
char code[8] = ""; /* 配对码 */
int code_left = 0; /* 配对码剩余秒 */
int code_total = 0; /* 配对码有效期总秒数,用于倒计时条 */
char owner[24] = ""; /* 已绑定用户 */
char message[140] = "";
const Snapshot *snap = nullptr;
int sel = 0;
int scroll = 0;
int detail_tab = 0; /* 详情页右栏分页:0=EVENTS 1=INFO */
int rssi = 0;
bool wifi_up = false;
uint8_t key_flash = 0; /* 底部按键条:bit0..bit3 = 被按下的槽位(含 BOOT) */
};
void ui_draw(const UiState &st);

View File

@ -0,0 +1,7 @@
{
"device_id": "SIM-E2E-0001",
"access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIzIiwidXNlcm5hbWUiOiJwZXBwZXJkb2ciLCJ0eXAiOiJ0ZXJtaW5hbCIsImRpZCI6IlNJTS1FMkUtMDAwMSIsImV4cCI6MTgyMjY0MzAxOX0.xw_BdOpvko7hMXFmoc-ot75k5x2qBuxiYWK8dI4nKI0",
"username": "pepperdog",
"token_expires_at": "2027-10-04T09:43:39.579360",
"saved_at": "2026-10-04T09:43:39.643973Z"
}

View File

@ -0,0 +1,44 @@
#!/usr/bin/env python3
"""用命令行完成网页端那一步:登录账号 -> 输入屏幕上的 6 位码 -> 绑定终端。
用法:
python3 terminal/tools/bind_code.py <6位码> [用户名] [密码] [--api URL]
默认账号 pepperdog/cosmo,默认后端 http://127.0.0.1:8000/api
"""
import argparse
import json
import sys
import urllib.error
import urllib.request
def post(url, payload, token=None):
data = json.dumps(payload).encode()
req = urllib.request.Request(url, data=data, headers={"Content-Type": "application/json"})
if token:
req.add_header("Authorization", "Bearer " + token)
with urllib.request.urlopen(req, timeout=15) as r:
body = r.read().decode()
return r.status, (json.loads(body) if body else {})
def main():
ap = argparse.ArgumentParser()
ap.add_argument("code")
ap.add_argument("username", nargs="?", default="pepperdog")
ap.add_argument("password", nargs="?", default="cosmo")
ap.add_argument("--api", default="http://127.0.0.1:8000/api")
a = ap.parse_args()
st, login = post(a.api + "/auth/login", {"username": a.username, "password": a.password})
token = login.get("access_token") or login.get("token")
if not token:
sys.exit("login failed: %s %s" % (st, login))
st, dev = post(a.api + "/devices/bind", {"code": a.code}, token)
print("HTTP %s -> %s" % (st, json.dumps(dev, ensure_ascii=False)))
return 0 if st < 400 else 1
if __name__ == "__main__":
sys.exit(main())

View File

@ -0,0 +1,183 @@
#!/usr/bin/env python3
"""核对抓屏结果(screen_shot.py dump 出来的 320x240 RGB565 大端裸数据)。
# 颜色普查 + 列表页三张卡的图标身份(加色混合反算,残差 0 = 就是这张图)
python3 terminal/tools/fb_check.py /tmp/r_list
# 逐像素核对中文字模:位置=字模左上角,fg=前景色 hex,后面跟要显示的中文
python3 terminal/tools/fb_check.py /tmp/r_info --glyph 103,176,b77d,木星,太阳系中最大的行
# 核对屏上贴的是不是后台「平台管理」里维护的图标(裸点阵从接口直接拉)
curl -s -H "Authorization: Bearer $TOKEN" -o /tmp/ic_599_40.bin \
'http://127.0.0.1:8000/api/terminal/bodies/599/icon?size=40'
python3 terminal/tools/fb_check.py /tmp/r_list --raw 13,32,40,/tmp/ic_599_40.bin
用来回答两件事:中文有没有画成空心方框,图标有没有走错兜底图。
"""
import os, re, sys
import numpy as np
SRC = os.path.join(os.path.dirname(__file__), '..', 'firmware',
'cosmo_terminal', 'src')
ICON_NAMES = 'planet jupiter saturn mars earth earth_icon venus neptune sun star ' \
'comet halley galaxy satellite probe shuttle rover'.split()
BG = {0x0063, 0x10A4, 0x10E4, 0x0105, 0x1966, 0x330C, 0x6201} # 底色/边框/星点
def load_icons():
txt = open(os.path.join(SRC, 'icons.cpp')).read()
out = {}
for m in re.finditer(r'static const uint16_t px_(\w+)_(list|detail)\[\d+\]\s*=\s*\{(.*?)\};', txt, re.S):
v = np.array([int(x, 16) for x in re.findall(r'0x([0-9A-Fa-f]{4})', m.group(3))], np.uint16)
out['ic_%s_%s' % (m.group(1), m.group(2))] = v
return out
def load_font():
txt = open(os.path.join(SRC, 'font_cjk.cpp')).read()
cps = [int(x, 16) for x in re.findall(r'0x([0-9A-Fa-f]{4})',
txt[txt.index('s_codepoints[]'):txt.index('s_glyphs[')])]
raw = re.search(r's_glyphs\[\]\[\d+\]\s*=\s*\{(.*?)\n\};', txt, re.S).group(1)
b = np.array([int(x, 16) for x in re.findall(r'0x([0-9A-Fa-f]{2})', raw)], np.uint8)
g = [b[i:i + 32] for i in range(0, len(b) - 31, 32)]
assert len(cps) == len(g), (len(cps), len(g))
return dict(zip(cps, g))
def glyph_bits(font, ch):
d = font.get(ord(ch))
if d is None:
return None
# 2 字节/行,MSB 为最左像素(与 display.cpp 的 glyph_blit 一致)
return np.array([[(d[r * 2 + c // 8] >> (7 - c % 8)) & 1 for c in range(16)]
for r in range(16)], np.uint8)
_box_rows = np.array([0xFF, 0xFF] + [0x80, 0x01] * 14 + [0xFF, 0xFF], np.uint8)
BOX = np.array([[((_box_rows[r * 2 + c // 8]) >> (7 - c % 8)) & 1 for c in range(16)]
for r in range(16)], np.uint8)
def satadd(bg, ic, w, h):
ic = ic.reshape(h, w).astype(np.int32)
b = bg.astype(np.int32)
r = np.minimum(31, ((b >> 11) & 31) + ((ic >> 11) & 31))
g = np.minimum(63, ((b >> 5) & 63) + ((ic >> 5) & 63))
l = np.minimum(31, (b & 31) + (ic & 31))
return (((r << 11) | (g << 5) | l) & 0xFFFF).astype(np.uint16)
def check_icons(img, icons):
"""列表页 3 张卡:卡底 + 内置图标加色混合,逐个候选反算,残差 0 即为所用图"""
for n, y0 in enumerate((22, 87, 152)):
reg = img[y0 + 10:y0 + 50, 13:53].astype(np.uint16)
if not reg.any():
continue
res = []
for name, px in icons.items():
if not name.endswith('_list') or px.size != 1600:
continue
for bgc in (0x10E4, 0x10A4):
e = satadd(np.full((40, 40), bgc, np.uint16), px, 40, 40)
res.append((int(np.abs(e.astype(int) - reg.astype(int)).mean()), name, bgc))
res.sort()
d0, n0, _ = res[0]
if d0 > 50:
print(' card%d y=%3d -> 不属于任何内置图标'
' (后台维护的图标已覆盖,用 --raw 核对)'
% (n, y0)); continue
print(' card%d y=%3d -> %-18s 残差%d' % (n, y0, n0, d0))
def check_raw(img, raws):
"""和外部给的裸点阵(后端 /terminal/bodies/{id}/icon 拉下来的 RGB565 大端)对。
叠加混合下 obs = 底色 + 图标(逐通道饱和相加),底色不止面板一种(详情页图标底下
还有雷达刻度),所以逐像素在已知底色集合里取最近的那个再比。图标贴对了每像素误差
必然是 0,贴错则整片笔画都对不上。
"""
bad = 0
for x, y, size, path in raws:
blob = open(path, 'rb').read()
if len(blob) != size * size * 2:
print(' %s: %d 字节,和 %dx%d 不符' % (path, len(blob), size, size)); bad += 1; continue
px = np.frombuffer(blob, '>u2')
reg = img[y:y + size, x:x + size].astype(np.uint16).reshape(-1)
cands = np.array(sorted(BG), np.uint16) # 面板/选中/底/星点/走线/雷达/金底
# 逐像素在所有候选底色里取最接近的,再看最大偏差:贴对了必然处处为 0
worst = int(np.minimum.reduce([np.abs(satadd(np.full((size, size), bgc, np.uint16),
px, size, size).astype(int).reshape(-1)
- reg.astype(int)) for bgc in cands]).max())
ink = int((px != 0).sum())
print(' %-16s @%d,%d %dx%d 墨点%d 最大逐像素误差%s -> %s'
% (os.path.basename(path), x, y, size, size, ink, worst,
'命中(就是这张后台维护的图)' if worst == 0 else '不是这张图'))
bad += worst != 0
return bad
def check_glyphs(img, font, spec):
x, y, fg = spec[0], spec[1], spec[2]
bad = drawn = 0
for ch in spec[3]:
if ord(ch) < 0x80:
x += 9 # ASCII 字模不在本工具职责内,跳过
continue
e = glyph_bits(font, ch)
if e is None:
print(' x=%-3d %r 字库里没有' % (x, ch)); bad += 1; x += 17; continue
c = img[y:y + 16, x:x + 16]
miss = int((c[e == 1] != fg).sum())
leak = int((c[e == 0] == fg).sum())
isbox = bool((e == BOX).all())
note = 'OK'
if miss == 0 and leak == 0 and isbox:
note = '空心方框(缺字)'
elif miss or leak:
note = '不匹配 miss=%d leak=%d' % (miss, leak)
print(' x=%-3d %s ink=%2d %s' % (x, ch, int(e.sum()), note))
bad += miss + leak
if isbox:
bad += 1
drawn += 1
x += 17
print(' 核对 %d 字:%s' % (drawn, '全部逐像素命中' if bad == 0 else '%d 处不对' % bad))
return bad
def main():
args = sys.argv[1:]
glyph = None
if '--glyph' in args:
i = args.index('--glyph')
x, y, fg, s = args[i + 1].split(',', 3)
glyph = [int(x), int(y), int(fg, 16), s]
args = args[:i] + args[i + 2:]
if not args:
print(__doc__); return 2
raws = []
while '--raw' in args:
i = args.index('--raw')
x, y, n, f = args[i + 1].split(',')
raws.append((int(x), int(y), int(n), f))
args = args[:i] + args[i + 2:]
icons, font = load_icons(), load_font()
rc = 0
for path in args:
raw = open(path, 'rb').read()
if len(raw) != 320 * 240 * 2:
print('%s: %d 字节,不是整屏(应为 153600)' % (path, len(raw))); rc = 1; continue
img = np.frombuffer(raw, '>u2').reshape(240, 320).astype(np.uint16)
top = sorted(((int((img == c).sum()), c) for c in np.unique(img)), reverse=True)[:8]
print('%s 非背景像素 %d' % (path, int((~np.isin(img, list(BG))).sum())))
print(' 主色:', ' '.join('%04X:%d' % (c, n) for n, c in top))
check_icons(img, icons)
if raws:
rc |= check_raw(img, raws) != 0
if glyph:
rc |= check_glyphs(img, font, glyph) != 0
return rc
if __name__ == '__main__':
sys.exit(main())

View File

@ -0,0 +1,322 @@
#!/usr/bin/env python3
"""生成 COSMO 终端的内置美术:霓虹线稿天体图标 + 16x16 中文字库。
/usr/bin/python3 terminal/tools/gen_assets.py
输出(提交进仓库,编译时不需要 PIL):
terminal/firmware/cosmo_terminal/src/icons.{h,cpp}
terminal/firmware/cosmo_terminal/src/font_cjk.{h,cpp}
图标约定:源图必须是自己发光的霓虹线稿 + 纯黑底(资源文件/*小.jpeg)。
存成不带 alpha 的 RGB565,固件按"叠加混合"贴到帧缓冲上——黑色加上去等于没画,
霓虹线条自动发光,省掉一半 flash 和一次 alpha 乘法。
"""
from pathlib import Path
from PIL import Image, ImageDraw, ImageFont
ROOT = Path(__file__).resolve().parents[2]
ART_DIR = ROOT / "资源文件"
OUT = ROOT / "terminal/firmware/cosmo_terminal/src"
FONT_PATH = "/System/Library/Fonts/STHeiti Medium.ttc"
FONT_PT = 160 # 大字号渲染再降到 16x16;64pt 时字身只有 9px,缩下去必然糊死
FONT_CANVAS = 320
FONT_CROP = 158 # 截取 em 见方:满宽字(木/行)字身 149px -> 15px
FONT_DY = 4 # STHeiti 的字身比 anchor="mm" 的中心低几个像素,往下找齐
FONT_THR = 130 # 主阈值:再低笔画就粘在一起;过密往上试,没墨往下试
LIST_SIZE = 40
DETAIL_SIZE = 64
# 图标素材:key -> 源文件名(都是 320x320 纯黑底霓虹线稿)
ART = {
"planet": "行星小.jpeg",
"jupiter": "木星小.jpeg",
"saturn": "土星小.jpeg",
"mars": "火星小.jpeg",
"earth": "地球小.jpeg",
"earth_icon": "地球-图标小.jpeg",
"venus": "金星(图标)小.jpeg",
"neptune": "海王星小.jpeg",
"sun": "太阳小.jpeg",
"star": "恒星小.jpeg",
"comet": "彗星小.jpeg",
"halley": "哈雷彗星小.jpeg",
"galaxy": "星系小.jpeg",
"satellite": "卫星小.jpeg",
"probe": "通信卫星小.jpeg",
"shuttle": "航天飞机小.jpeg",
"rover": "火星车小.jpeg",
}
# 按 name / name_zh 小写子串命中(从上到下优先)
NAMES = [
# 先匹配更具体的名字:火星车/探测器里的"火星""太阳"不能抢先命中行星图标
("curiosity", "rover"), ("perseverance", "rover"), ("zhurong", "rover"),
("yutu", "rover"), ("毅力", "rover"), ("好奇号", "rover"), ("祝融", "rover"),
("月球车", "rover"), ("火星车", "rover"), ("巡视器", "rover"),
("shuttle", "shuttle"), ("航天飞机", "shuttle"),
("voyager", "probe"), ("pioneer", "probe"), ("new horizons", "probe"),
("parker", "probe"), ("cassini", "probe"), ("juno", "probe"),
("messenger", "probe"), ("bepicolombo", "probe"), ("juice", "probe"),
("旅行者", "probe"), ("新视野", "probe"), ("帕克", "probe"), ("卡西尼", "probe"),
("朱诺", "probe"), ("信使号", "probe"), ("欧空", "probe"),
("telescope", "satellite"), ("webb", "satellite"), ("hubble", "satellite"),
("望远镜", "satellite"), ("卫星", "satellite"),
("halley", "halley"), ("哈雷", "halley"),
("moon", "earth_icon"), ("luna", "earth_icon"), ("月球", "earth_icon"),
("jupiter", "jupiter"), ("木星", "jupiter"),
("saturn", "saturn"), ("土星", "saturn"),
("mars", "mars"), ("火星", "mars"),
("earth", "earth"), ("地球", "earth"),
("venus", "venus"), ("金星", "venus"),
("neptune", "neptune"), ("海王星", "neptune"),
("uranus", "planet"), ("天王星", "planet"),
("mercury", "planet"), ("水星", "planet"),
("pluto", "planet"), ("冥王", "planet"),
("sun", "sun"), ("太阳", "sun"),
]
# 类型兜底:后端 type 见 backend/app/models/celestial.py
TYPES = {
"planet": "planet",
"dwarf_planet": "planet",
"star": "star",
"comet": "comet",
"satellite": "satellite",
"probe": "probe",
}
FALLBACK = "planet"
def rgb565(r, g, b):
return ((r >> 3) << 11) | ((g >> 2) << 5) | (b >> 3)
def icon_pixels(path, size):
"""亮度 bbox 裁切 -> 补方 -> 缩放 -> 黑底门限 -> RGB565 列表"""
im = Image.open(path).convert("RGB")
bbox = Image.open(path).convert("L").point(lambda v: 255 if v > 40 else 0).getbbox()
if bbox:
im = im.crop(bbox)
w, h = im.size
side = max(w, h)
sq = Image.new("RGB", (side, side), (0, 0, 0))
sq.paste(im, ((side - w) // 2, (side - h) // 2))
sq = sq.resize((size, size), Image.LANCZOS)
out = []
for r, g, b in sq.getdata():
if (r * 299 + g * 587 + b * 114) // 1000 <= 10:
out.append(0) # 黑底 -> 叠加混合时不落地
else:
out.append(rgb565(r, g, b))
return out
def emit_icons():
keys = list(ART)
data = {k: {s: icon_pixels(ART_DIR / ART[k], s) for s in (LIST_SIZE, DETAIL_SIZE)}
for k in keys}
h = ["// 由 terminal/tools/gen_assets.py 生成,请勿手改。",
"/* 天体霓虹线稿图标:无 alpha 的 RGB565,固件用叠加混合绘制(黑色不落地)。 */",
"#pragma once",
"#include <stdint.h>",
"",
f"#define ICON_LIST_W {LIST_SIZE}",
f"#define ICON_LIST_H {LIST_SIZE}",
f"#define ICON_DETAIL_W {DETAIL_SIZE}",
f"#define ICON_DETAIL_H {DETAIL_SIZE}",
"",
"typedef struct { const uint16_t *px; uint8_t w, h; } IconArt;",
""]
for k in keys:
h.append(f"extern const IconArt ic_{k}_list; /* {ART[k]} */")
for k in keys:
h.append(f"extern const IconArt ic_{k}_detail;")
h += ["",
"/** name/name_zh 小写子串命中优先,其次按 type 兜底;detail!=0 取大图 */",
"const IconArt *icon_for(const char *name, const char *name_zh, const char *type, int detail);",
""]
c = ["// 由 terminal/tools/gen_assets.py 生成,请勿手改。",
"#include <string.h>",
"#include <ctype.h>",
'#include "icons.h"',
""]
for k in keys:
for s, tag in ((LIST_SIZE, "list"), (DETAIL_SIZE, "detail")):
px = data[k][s]
c.append(f"static const uint16_t px_{k}_{tag}[{len(px)}] = {{")
for i in range(0, len(px), 16):
c.append(",".join("0x%04X" % v for v in px[i:i + 16]) + ",")
c.append("};")
c.append("")
for k in keys:
c.append(f"const IconArt ic_{k}_list = {{ px_{k}_list, {LIST_SIZE}, {LIST_SIZE} }};")
for k in keys:
c.append(f"const IconArt ic_{k}_detail = {{ px_{k}_detail, {DETAIL_SIZE}, {DETAIL_SIZE} }};")
c += ["", "struct NameRule { const char *needle; const IconArt *list, *detail; };",
"struct TypeRule { const char *type; const IconArt *list, *detail; };", "",
"static const NameRule s_names[] = {"]
for needle, key in NAMES:
c.append(f' {{ "{needle}", &ic_{key}_list, &ic_{key}_detail }},')
c += ["};", "", "static const TypeRule s_types[] = {"]
for t, key in TYPES.items():
c.append(f' {{ "{t}", &ic_{key}_list, &ic_{key}_detail }},')
c += ["};", "",
"static void lower_utf8(const char *s, char *buf, size_t cap)",
"{",
" size_t i = 0;",
" for (; *s && i + 1 < cap; s++)",
" buf[i++] = ((unsigned char)*s < 0x80) ? (char)tolower((unsigned char)*s) : *s;",
" buf[i] = 0;",
"}",
"",
"static const IconArt *match(const char *hay, int detail)",
"{",
" char low[48];",
" if (!hay || !hay[0]) return NULL;",
" lower_utf8(hay, low, sizeof(low));",
" for (unsigned i = 0; i < sizeof(s_names) / sizeof(s_names[0]); i++)",
" if (strstr(low, s_names[i].needle))",
" return detail ? s_names[i].detail : s_names[i].list;",
" return NULL;",
"}",
"",
"const IconArt *icon_for(const char *name, const char *name_zh, const char *type, int detail)",
"{",
" const IconArt *a = match(name, detail);",
" if (!a) a = match(name_zh, detail);",
" if (a) return a;",
" if (type) {",
" for (unsigned i = 0; i < sizeof(s_types) / sizeof(s_types[0]); i++)",
" if (!strcmp(type, s_types[i].type))",
" return detail ? s_types[i].detail : s_types[i].list;",
" }",
" return detail ? &ic_planet_detail : &ic_planet_list;",
"}",
""]
(OUT / "icons.h").write_text("\n".join(h) + "\n", encoding="utf-8")
(OUT / "icons.cpp").write_text("\n".join(c) + "\n", encoding="utf-8")
total = sum(len(v[s]) * 2 for v in data.values() for s in (LIST_SIZE, DETAIL_SIZE))
print(f"icons: {len(keys)} 张 x2 尺寸 ({LIST_SIZE}/{DETAIL_SIZE}),{total // 1024} KB flash")
def cjk_codepoints():
"""GB2312 一级字库(0xB0A1-0xD7F9)+ 常用中文标点/单位"""
cps = set()
for hi in range(0xB0, 0xD8):
for lo in range(0xA1, 0xFF):
try:
u = bytes([hi, lo]).decode("gb2312")
except UnicodeDecodeError:
continue
if len(u) == 1:
cps.add(ord(u))
cps |= {ord(c) for c in ",。:;、!?()—…·%℃°××ⅠⅡⅢⅣ"}
return sorted(cps)
BLANK_BOX = [0x00, 0x00] + [0x81, 0x00] * 7 + [0x81, 0x00] * 6 + [0x00, 0x00]
def _threshold(small, thr):
"""16x16 灰度 -> 点阵行(2 字节/行,MSB 为最左像素)"""
rows = []
for y in range(16):
hi = lo = 0
for x in range(8):
hi = hi << 1 | (1 if small.getpixel((x, y)) >= thr else 0)
lo = lo << 1 | (1 if small.getpixel((x + 8, y)) >= thr else 0)
rows += [hi, lo]
return rows
def _pick_threshold(small):
"""主阈值优先;点阵超过 55% 有墨(笔画糊成一团)就加严,一点墨都没有就放宽"""
rows = _threshold(small, FONT_THR)
ink = sum(bin(v).count("1") for v in rows) / 256.0
if ink > 0.55:
for thr in (FONT_THR + 40, FONT_THR + 70):
dense = _threshold(small, thr)
if sum(bin(v).count("1") for v in dense) / 256.0 <= 0.55:
return dense
return dense if sum(dense) else rows
if ink == 0:
for thr in (FONT_THR - 30, FONT_THR - 50, FONT_THR - 70):
light = _threshold(small, thr)
if sum(light):
return light
return BLANK_BOX # 字体里根本没有这个字
return rows
def cjk_rows(ch, font):
"""em 见方等比降到 16x16:满宽字字身 ~15px,标点自然只占几像素。缺字返回空心方框"""
big = Image.new("L", (FONT_CANVAS, FONT_CANVAS), 0)
ImageDraw.Draw(big).text((FONT_CANVAS // 2, FONT_CANVAS // 2 + FONT_DY), ch,
fill=255, font=font, anchor="mm")
c, r = FONT_CANVAS // 2, FONT_CROP // 2
small = big.crop((c - r, c + FONT_DY - r, c + r, c + FONT_DY + r)).resize((16, 16), Image.BILINEAR)
return _pick_threshold(small)
def emit_font():
cps = cjk_codepoints()
font = ImageFont.truetype(FONT_PATH, FONT_PT, index=0)
glyphs, missing = [], []
for cp in cps:
rows = cjk_rows(chr(cp), font)
if rows == BLANK_BOX:
missing.append(chr(cp))
glyphs.append(rows)
h = ["// 由 terminal/tools/gen_assets.py 生成,请勿手改。",
"/* 16x16 点阵中文字库:GB2312 一级字 + 常用标点,行式 2 字节/行,MSB 为最左像素。 */",
"#pragma once",
"#include <stdint.h>",
"#include <stdbool.h>",
"",
"#define CJK_CELL 16",
f"#define CJK_COUNT {len(cps)}",
"",
"/** 按码位二分;缺字返回 NULL(调用字画空心方框) */",
"const uint8_t *cjk_glyph(uint32_t cp);",
""]
c = ["// 由 terminal/tools/gen_assets.py 生成,请勿手改。",
"#include <stddef.h>",
'#include "font_cjk.h"', "",
"static const uint16_t s_codepoints[] = {"]
for i in range(0, len(cps), 16):
c.append(",".join("0x%04X" % v for v in cps[i:i + 16]) + ",")
c += ["};", "", "static const uint8_t s_glyphs[][32] = {"]
for g in glyphs:
c.append(" " + ",".join("0x%02X" % v for v in g) + ",")
c += ["};", "",
"const uint8_t *cjk_glyph(uint32_t cp)",
"{",
" unsigned lo = 0, hi = sizeof(s_codepoints) / sizeof(s_codepoints[0]);",
" while (lo < hi) {",
" unsigned mid = (lo + hi) / 2;",
" if (s_codepoints[mid] == cp) return s_glyphs[mid];",
" if (s_codepoints[mid] < cp) lo = mid + 1; else hi = mid;",
" }",
" return NULL;",
"}",
""]
(OUT / "font_cjk.h").write_text("\n".join(h) + "\n", encoding="utf-8")
(OUT / "font_cjk.cpp").write_text("\n".join(c) + "\n", encoding="utf-8")
print(f"font_cjk: {len(cps)} 字 @16x16,{len(cps) * 34 // 1024} KB flash,"
f"缺字 {len(missing)} {missing[:8]}")
def main():
OUT.mkdir(parents=True, exist_ok=True)
emit_icons()
emit_font()
if __name__ == "__main__":
main()

View File

@ -0,0 +1,32 @@
"""按键排查:打开串口 -> 打印 XL9555 寄存器 -> 持续把设备日志带时间戳落盘。
依次按 KEY0/KEY1/KEY2/KEY3/BOOT,每颗停一秒,日志里就能看到每颗键触发的是哪一位。
用法: key_watch.py [监听秒数=240] [日志=/tmp/keywatch.log]
"""
import serial, sys, time
PORT = '/dev/cu.usbserial-210'
BAUD = 115200
dur = float(sys.argv[1]) if len(sys.argv) > 1 else 240
path = sys.argv[2] if len(sys.argv) > 2 else '/tmp/keywatch.log'
t0 = time.time()
log = open(path, 'a', buffering=1)
s = serial.Serial(PORT, BAUD, timeout=0.2, write_timeout=5)
time.sleep(1.0)
for c in ('xlreg', 'keys'):
s.write(c.encode() + b'\r\n')
s.flush()
log.write('\n===== key_watch %s 请按 KEY0 KEY1 KEY2 KEY3 BOOT,每颗停一秒 =====\n' % time.strftime('%H:%M:%S'))
buf = b''
while time.time() - t0 < dur:
d = s.read(4096)
if not d:
continue
buf += d
while b'\n' in buf:
line, buf = buf.split(b'\n', 1)
text = line.decode('utf8', 'replace').rstrip()
if text:
log.write('%7.2f %s\n' % (time.time() - t0, text))
s.close()
log.write('===== key_watch end =====\n')

View File

@ -0,0 +1,114 @@
{
"username": "pepperdog",
"device_id": "SIM-E2E-0001",
"server_time": "2026-10-04T09:43:39.744395",
"follow_count": 3,
"bodies": [
{
"id": "599",
"name": "Jupiter",
"name_zh": "木星",
"type": "planet",
"description": "木星,太阳系中最大的行星",
"is_active": true,
"position": {
"time": "2026-09-20T00:00:00",
"x": -3.426488071926383,
"y": 4.047380979721933,
"z": 0.05985018591837531,
"vx": -10.139,
"vy": -7.832,
"vz": 0.259,
"distance_au": 5.3034,
"speed_km_s": 12.814,
"source": "nasa_horizons_cron"
},
"events": [
{
"id": 6,
"title": "木星 冲 (Jupiter Opposition)",
"event_type": "opposition",
"event_time": "2026-01-10T08:42:09.436398",
"description": "木星将发生冲现象。处于冲日位置,是观测的最佳时机。",
"is_upcoming": false
}
]
},
{
"id": "699",
"name": "Saturn",
"name_zh": "土星",
"type": "planet",
"description": "土星,拥有美丽的光环",
"is_active": true,
"position": {
"time": "2026-09-20T00:00:00",
"x": 9.27386522923323,
"y": 1.706539354236648,
"z": -0.3988761114306671,
"vx": -2.28,
"vy": 9.477,
"vz": -0.075,
"distance_au": 9.438,
"speed_km_s": 9.748,
"source": "nasa_horizons_cron"
},
"events": [
{
"id": 7,
"title": "土星 合 (Saturn Conjunction)",
"event_type": "conjunction",
"event_time": "2026-03-25T08:55:13.880343",
"description": "土星将发生合现象。与地球的角距离约177.64°。",
"is_upcoming": false
}
]
},
{
"id": "299",
"name": "Venus",
"name_zh": "金星",
"type": "planet",
"description": "金星,太阳系中最热的行星",
"is_active": true,
"position": {
"time": "2026-09-20T00:00:00",
"x": 0.6638884598322305,
"y": -0.2951749316584505,
"z": -0.04236089894000954,
"vx": 14.469,
"vy": 31.651,
"vz": -0.4,
"distance_au": 0.7278,
"speed_km_s": 34.804,
"source": "nasa_horizons_cron"
},
"events": [
{
"id": 20,
"title": "金星与火星接近",
"event_type": "close_approach",
"event_time": "2026-01-13T11:45:29.888265",
"description": "金星与火星的角距离约4.84°,这是较为罕见的天象。",
"is_upcoming": false
},
{
"id": 19,
"title": "金星与火星接近",
"event_type": "close_approach",
"event_time": "2026-01-12T11:45:29.888265",
"description": "金星与火星的角距离约3.86°,这是较为罕见的天象。",
"is_upcoming": false
},
{
"id": 18,
"title": "金星与火星接近",
"event_type": "close_approach",
"event_time": "2026-01-11T11:45:29.888265",
"description": "金星与火星的角距离约2.89°,这是较为罕见的天象。",
"is_upcoming": false
}
]
}
]
}

View File

@ -0,0 +1,48 @@
"""发命令并按需抓屏:fbshot.py <log> "cmd|等待秒|输出png(或-)" ...
状态机保证 [FB] 标记不会被日志冲掉。"""
import serial, sys, time, os
PORT='/dev/cu.usbserial-210'; BAUD=115200; N=320*240*2
log=open(sys.argv[1],'ab',buffering=0)
steps=[a.split('|') for a in sys.argv[2:]]
s=serial.Serial(PORT,BAUD,timeout=0.1,write_timeout=10)
buf=bytearray()
def pump(dur, path=None):
"""读串口 dur 秒;path 不为空时遇到 [FB] 就抓 N 字节并渲染"""
global buf
end=time.time()+dur; f=None; got=0
while time.time()<end or f is not None:
d=s.read(4096)
if not d:
if f is None and time.time()>end: break
continue
if f is None:
buf.extend(d)
i=buf.find(b'[FB]')
if i<0:
keep=6; n=max(0,len(buf)-keep)
if n: log.write(bytes(buf[:n])); del buf[:n]
continue
log.write(bytes(buf[:i])); del buf[:i+4]
if path is None:
continue # 不抓屏就丢掉这段二进制
f=open(path,'wb'); print('[fb] capturing...',flush=True)
d=bytes(buf); buf=bytearray() # 只写标记之后的数据,否则整幅图右移 2px 且末行丢 2px
take=len(d) if f.tell()+len(d)<=N else N-f.tell()
f.write(d[:take]); got+=take
if f.tell()>=N:
f.close(); log.write(d[take:])
print('[fb] %s %d bytes'%(path,got),flush=True)
os.system('/usr/local/bin/ffmpeg -y -loglevel error -f rawvideo -pixel_format rgb565be '
'-video_size 320x240 -i %s -frames:v 1 -vf "scale=960:720:flags=neighbor" %s.png'%(path,path))
print('[fb] rendered %s.png'%(path,),flush=True)
buf=bytearray(); return True
if path: print('[fb] TIMEOUT',flush=True)
return False
pump(1.5)
for st in steps:
cmd=st[0]; wait=float(st[1]) if len(st)>1 else 0.2
out=st[2] if len(st)>2 and st[2]!='-' else None
if cmd:
print('[send] %s'%cmd,flush=True); s.write(cmd.encode()+b'\r\n'); s.flush()
pump(wait, out)
s.close()

View File

@ -0,0 +1,49 @@
import serial, sys, threading, time, os, re
PORT='/dev/cu.usbserial-210'; BAUD=115200
OUT=sys.argv[1] if len(sys.argv)>2 else '/tmp/fb.raw'
N=320*240*2
s=serial.Serial(); s.port=PORT; s.baudrate=BAUD; s.timeout=0.1; s.write_timeout=5
s.open()
state=['text']; buf=bytearray(); f=None
def reader():
while True:
try: d=s.read(4096)
except Exception as e:
print('\n[serial error] %s'%e,flush=True); return
if not d: continue
buf.extend(d)
while True:
if state[0]=='text':
i=buf.find(b'[FB]')
if i<0:
keep=6
n=max(0,len(buf)-keep)
out=bytes(buf[:n]); del buf[:n]
if out: sys.stdout.write(out.decode('utf-8','replace')); sys.stdout.flush()
break
head=bytes(buf[:i]); del buf[:i+4]
if head: sys.stdout.write(head.decode('utf-8','replace')); sys.stdout.flush()
f=open(OUT,'wb'); state[0]='raw'; print('\n[fb] capturing %d bytes...'%N,flush=True)
elif state[0]=='raw':
take=min(N-f.tell(),len(buf))
f.write(bytes(buf[:take])); del buf[:take]
if f.tell()>=N:
f.close(); state[0]='tail'; print('\n[fb] got %s (%d bytes)'%(OUT,N),flush=True)
else: break
else:
i=buf.find(b'[FBEND]')
if i<0:
n=max(0,len(buf)-8)
out=bytes(buf[:n]); del buf[:n]
if out: sys.stdout.write(out.decode('utf-8','replace')); sys.stdout.flush()
break
tail=bytes(buf[:i+7]); del buf[:i+7]
print(tail.decode('utf-8','replace'),flush=True)
os.system('/usr/local/bin/ffmpeg -y -loglevel error -f rawvideo -pixel_format rgb565be -video_size 320x240 -i %s -frames:v 1 -vf "scale=960:720:flags=neighbor" %s.png'%(OUT,OUT))
print('[fb] rendered %s.png'%OUT,flush=True)
state[0]='text'
threading.Thread(target=reader,daemon=True).start()
print('[term] attached %s -> %s'%(PORT,OUT),flush=True)
for line in sys.stdin:
try: s.write(line.rstrip('\n').encode()+b'\r\n'); s.flush()
except Exception as e: print('[write failed] %s'%e,flush=True)

View File

@ -0,0 +1,233 @@
#!/usr/bin/env python3
"""
终端配对流程模拟器:用 ESP32-S3 完全相同的 HTTP 调用序列跑通全流程。
python3 terminal_sim.py pair # 申请配对码 -> 轮询 -> 拿长期 token -> 拉取关注天体
python3 terminal_sim.py follows # 模拟重启:只用本地保存的 token(等价于 NVS)
--api 默认 http://127.0.0.1:8000/api,--device 默认模拟一个 MAC 地址。
token 保存在 terminal/tools/.terminal_nvs.json,模拟设备的 NVS 分区。
"""
import argparse
import json
import sys
import time
import urllib.error
import urllib.parse
import urllib.request
from datetime import datetime
from pathlib import Path
# 设备侧不走任何系统代理,模拟器保持一致,避免 HTTP_PROXY 把 127.0.0.1 请求转发掉
OPENER = urllib.request.build_opener(urllib.request.ProxyHandler({}))
NVS_FILE = Path(__file__).with_name(".terminal_nvs.json")
DEFAULT_DEVICE = "ESP32S3-AABBCCDDEEFF"
POLL_SECONDS = 2
def call(api: str, method: str, path: str, *, json_body=None, params=None, token=None, timeout=20):
url = api.rstrip("/") + path
if params:
url += "?" + urllib.parse.urlencode(params)
data = json.dumps(json_body).encode() if json_body is not None else None
req = urllib.request.Request(url, data=data, method=method)
req.add_header("Content-Type", "application/json")
if token:
req.add_header("Authorization", f"Bearer {token}")
try:
with OPENER.open(req, timeout=timeout) as resp:
body = resp.read().decode()
return resp.status, json.loads(body) if body else None
except urllib.error.HTTPError as exc:
raw = exc.read().decode()
try:
return exc.code, json.loads(raw)
except json.JSONDecodeError:
return exc.code, {"detail": raw}
except urllib.error.URLError as exc:
sys.exit(f"无法访问 {url}: {exc.reason}(请确认后端已启动,或用 --api 指定地址)")
def read_nvs() -> dict:
if NVS_FILE.exists():
return json.loads(NVS_FILE.read_text())
return {}
def write_nvs(data: dict) -> None:
NVS_FILE.write_text(json.dumps(data, indent=2))
# ---------------------------------------------------------------- render
def render_pair_screen(code: str, expires_in: int, device_id: str) -> str:
"""What the 2.4寸 TFT shows while waiting for the user to bind."""
minutes, seconds = divmod(max(0, expires_in), 60)
return "\n".join(
[
"+------------------------------+",
"| NET: ONLINE PWR: 89% |",
"| |",
"| DEVICE BINDING |",
"| |",
f"|{(code[:3] + chr(32) + code[3:]):^30}|",
"| |",
f"| 等待网页端输入配对码 |",
f"| 剩余 {minutes:02d}:{seconds:02d} DEV {device_id[-4:]} |",
"| |",
"| [ORBIT] [COMM] [SYS]|",
"+------------------------------+",
]
)
def render_follows(payload: dict) -> str:
"""Text preview of the follow list page + the detail page of the first body."""
bodies = payload["bodies"]
lines = [
"",
"=== 关注天体列表页 (SUBSCRIBED) ===",
f"NET: ONLINE USER: {payload['username']} 服务器时间: {payload['server_time'][:19]}",
f"共 {payload['follow_count']} 个关注天体",
"",
]
for body in bodies:
pos = body.get("position")
dist = f"DIST: {pos['distance_au']:.2f} AU" if pos else "DIST: -- AU"
zh = f" / {body['name_zh']}" if body.get("name_zh") else ""
events = body.get("events") or []
lines.append(f" [ON ] {body['name']}{zh} ({body['type']})")
lines.append(f" {dist}")
for event in events[:2]:
flag = "将要发生" if event["is_upcoming"] else "已发生"
lines.append(f" · {event['title']} {event['event_time'][:10]} [{flag}]")
if not events:
lines.append(" · 暂无事件记录")
lines.append("")
if bodies:
body = bodies[0]
pos = body.get("position")
lines.append(f"=== 天体详情页 (DETAIL): TARGET: {body['name']} ({body['type'].upper()}) ===")
if pos:
speed = f"{pos['speed_km_s']:.1f}" if pos.get("speed_km_s") is not None else "--"
lines += [
f"POS (AU) X: {pos['x']:.2f} Y: {pos['y']:.2f} Z: {pos['z']:.2f}",
f"VEL (KM/S) VX: {pos['vx'] if pos['vx'] is not None else '--'}"
f" VY: {pos['vy'] if pos['vy'] is not None else '--'}"
f" VZ: {pos['vz'] if pos['vz'] is not None else '--'}",
f"DIST: {pos['distance_au']:.3f} AU SPEED: {speed} km/s",
f"数据时间(UTC): {pos['time'][:19]} 来源: {pos['source']}",
]
else:
lines.append("POS/VEL: 暂无位置数据")
if body.get("description"):
lines.append(f"INFO: {body['description']}")
lines.append("EVENTS:")
for event in body.get("events") or []:
lines.append(f" {event['event_time'][:10]} {event['title']} ({event['event_type']})")
if not body.get("events"):
lines.append(" --")
lines.append("")
lines.append("[ORBIT] [COMM] [SYS]")
return "\n".join(lines)
# ---------------------------------------------------------------- commands
def cmd_pair(args) -> None:
nvs = read_nvs()
device_id = args.device or nvs.get("device_id") or DEFAULT_DEVICE
status_code, data = call(
args.api, "POST", "/terminal/pair/code", json_body={"device_id": device_id, "name": "Cosmo Terminal"}
)
if status_code != 200:
sys.exit(f"申请配对码失败 {status_code}: {data}")
if data["status"] == "bound":
print(f"设备已绑定到 {data['username']},无需重新配对(如需换人绑定,请先在网页端解绑)。")
cmd_follows(args)
return
code = data["code"]
if not code:
sys.exit(f"服务端没有返回配对码: {data}")
deadline = time.time() + args.wait
print(f"设备 ID: {device_id}\n请在网页端『绑定设备』输入下面的 6 位码({args.wait}s 内有效于轮询):\n")
print(render_pair_screen(code, data["expires_in"], device_id))
while time.time() < deadline:
time.sleep(POLL_SECONDS)
status_code, data = call(
args.api, "GET", "/terminal/pair/status", params={"device_id": device_id, "code": code}
)
if status_code != 200:
sys.exit(f"轮询失败 {status_code}: {data}")
state = data["status"]
if state == "pending":
print(f" ... 等待绑定中(剩余 {data['expires_in']}s)", flush=True)
continue
if state == "expired":
print("配对码已过期,重新运行本命令获取新码。")
return
if state in ("unknown", "invalid_code", "unbound"):
sys.exit(f"配对状态异常: {data}")
if state == "bound":
print(f"\nLINK ESTABLISHED — 已绑定用户: {data['username']}")
token = data.get("access_token")
if token:
write_nvs(
{
"device_id": device_id,
"access_token": token,
"username": data["username"],
"token_expires_at": data.get("expires_at"),
"saved_at": datetime.utcnow().isoformat() + "Z",
}
)
print(f"长期 token 已写入 NVS({NVS_FILE.name}),有效期见 token_expires_at。")
else:
print("该设备此前已领取过 token,继续使用本地 NVS 中的 token。")
cmd_follows(args)
return
print(f"\n超时 {args.wait}s 未检测到绑定,退出。")
def cmd_follows(args) -> None:
nvs = read_nvs()
token = nvs.get("access_token")
if not token:
sys.exit("NVS 中没有 token,请先运行: python3 terminal_sim.py pair")
status_code, data = call(args.api, "GET", "/terminal/follows", token=token)
if status_code == 401:
sys.exit(f"token 已失效(很可能被解绑):{data['detail']}\n请重新运行 pair。")
if status_code != 200:
sys.exit(f"拉取失败 {status_code}: {data}")
print(render_follows(data))
raw = Path(__file__).with_name("last_follows.json")
raw.write_text(json.dumps(data, ensure_ascii=False, indent=2))
print(f"\n原始响应已保存: {raw}")
def main() -> None:
parser = argparse.ArgumentParser(description="Cosmo ESP32-S3 终端配对/数据流模拟器")
parser.add_argument("--api", default="http://127.0.0.1:8000/api")
parser.add_argument("--device", default=None, help="设备 ID,默认使用 NVS 中的值")
parser.add_argument("--wait", type=int, default=180, help="等待绑定的最长秒数")
parser.add_argument("command", choices=["pair", "follows"], nargs="?", default="pair")
args = parser.parse_args()
if args.command == "pair":
cmd_pair(args)
else:
cmd_follows(args)
if __name__ == "__main__":
main()