nex_buddy/server/app/models/device.py

62 lines
3.0 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters!

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

"""设备:芯片指纹、固件版本、绑定关系、最近活跃(01-总体设计.md 4.2)。"""
from __future__ import annotations
import uuid
from datetime import datetime, timezone
from typing import TYPE_CHECKING
from sqlalchemy import DateTime, ForeignKey, Integer, String, func
from sqlalchemy.dialects.postgresql import UUID
from sqlalchemy.orm import Mapped, mapped_column, relationship
from app.db.session import Base
if TYPE_CHECKING:
from app.models.user import User
def _utcnow() -> datetime:
return datetime.now(timezone.utc)
class Device(Base):
__tablename__ = "devices"
id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
# 芯片 efuse MAC,作设备指纹;一台设备只有一条记录
chip_id: Mapped[str] = mapped_column(String(32), unique=True, index=True)
model: Mapped[str] = mapped_column(String(64), default="JC3636K518C_I_W")
fw_version: Mapped[str] = mapped_column(String(32), default="")
bound_user_id: Mapped[uuid.UUID | None] = mapped_column(
UUID(as_uuid=True), ForeignKey("users.id", ondelete="SET NULL"), index=True
)
bound_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True))
last_active_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True))
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())
# ---- OTA 升级状态 ----
# target_firmware_id 是管理员「点名下发」的目标包;设备来 check 时优先拿它,
# 这样可以在不做灰度系统的情况下,先把某一版推给一台设备验证。
target_firmware_id: Mapped[uuid.UUID | None] = mapped_column(UUID(as_uuid=True), index=True)
target_version: Mapped[str] = mapped_column(String(32), default="")
# ""(无任务) / pending(已下发待设备取) / downloading / success / failed / canceled
upgrade_state: Mapped[str] = mapped_column(String(16), default="")
upgrade_error: Mapped[str] = mapped_column(String(160), default="")
upgrade_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True))
# 设备上报的启动分区(app0/app1),排查「烧了没生效」时很有用
boot_slot: Mapped[str] = mapped_column(String(8), default="")
fw_updated_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True))
# ---- TF 卡媒体同步(用户点「同步」才动,不做定时自动同步)----
# seq 是用户按下同步的次数;设备每 15 秒轻量探一次,只有 seq > ack 才真同步。
# ack 是设备回报的「已处理到第几次」;rev 是设备同步完的清单指纹,
# 两者一起用来判断「有没有新增/删除待同步」——不用设备频繁上报全量清单。
media_sync_seq: Mapped[int] = mapped_column(Integer, default=0)
media_sync_ack: Mapped[int] = mapped_column(Integer, default=0)
media_synced_rev: Mapped[str] = mapped_column(String(32), default="")
bound_user: Mapped["User | None"] = relationship(back_populates="devices")