mirror of
https://github.com/xinnan-tech/xiaozhi-esp32-server.git
synced 2026-11-28 04:59:52 +01:00
feat:device review done
This commit is contained in:
parent
86b6f76f60
commit
414dcc528e
5 changed files with 69 additions and 135 deletions
|
|
@ -5,7 +5,7 @@ Defines the Device database table structure and basic data operations.
|
|||
"""
|
||||
|
||||
from datetime import datetime, timezone
|
||||
from sqlalchemy import String, Text, DateTime, Boolean
|
||||
from sqlalchemy import String, Text, DateTime
|
||||
from sqlalchemy.orm import Mapped, mapped_column
|
||||
|
||||
from orm.base import Base
|
||||
|
|
@ -41,10 +41,10 @@ class Device(Base):
|
|||
comment="Device hardware ID"
|
||||
)
|
||||
|
||||
model: Mapped[str] = mapped_column(
|
||||
device_model: Mapped[str] = mapped_column(
|
||||
String(100),
|
||||
nullable=True,
|
||||
comment="Device model (e.g., PLAUD NOTE)"
|
||||
comment="Device model name (e.g., PLAUD NOTE, ESP32-S3)"
|
||||
)
|
||||
|
||||
firmware_version: Mapped[str] = mapped_column(
|
||||
|
|
@ -57,15 +57,8 @@ class Device(Base):
|
|||
status: Mapped[str] = mapped_column(
|
||||
String(20),
|
||||
nullable=False,
|
||||
default="active",
|
||||
comment="Device status (active, inactive, offline)"
|
||||
)
|
||||
|
||||
is_online: Mapped[bool] = mapped_column(
|
||||
Boolean,
|
||||
nullable=False,
|
||||
default=False,
|
||||
comment="Whether device is currently online"
|
||||
default="offline",
|
||||
comment="Device connection status (online, offline)"
|
||||
)
|
||||
|
||||
last_seen_at: Mapped[datetime] = mapped_column(
|
||||
|
|
@ -74,17 +67,16 @@ class Device(Base):
|
|||
comment="Last seen timestamp"
|
||||
)
|
||||
|
||||
# Additional Information
|
||||
description: Mapped[str] = mapped_column(
|
||||
Text,
|
||||
nullable=True,
|
||||
comment="Device description"
|
||||
)
|
||||
|
||||
extra_data: Mapped[str] = mapped_column(
|
||||
meta_data: Mapped[str] = mapped_column(
|
||||
Text,
|
||||
nullable=True,
|
||||
comment="Additional metadata (JSON format)"
|
||||
comment="Device metadata (JSON format)"
|
||||
)
|
||||
|
||||
# Timestamps
|
||||
|
|
@ -117,13 +109,12 @@ class Device(Base):
|
|||
"id": self.id,
|
||||
"name": self.name,
|
||||
"deviceId": self.device_id,
|
||||
"model": self.model,
|
||||
"deviceModel": self.device_model,
|
||||
"firmwareVersion": self.firmware_version,
|
||||
"status": self.status,
|
||||
"isOnline": self.is_online,
|
||||
"lastSeenAt": self.last_seen_at.isoformat() if self.last_seen_at else None,
|
||||
"description": self.description,
|
||||
"extraData": self.extra_data,
|
||||
"metaData": self.meta_data,
|
||||
"createdAt": self.created_at.isoformat() if self.created_at else None,
|
||||
"updatedAt": self.updated_at.isoformat() if self.updated_at else None,
|
||||
}
|
||||
|
|
|
|||
|
|
@ -6,7 +6,7 @@ Encapsulates all database operations for Device.
|
|||
"""
|
||||
|
||||
from typing import Optional
|
||||
from sqlalchemy import select, func, or_
|
||||
from sqlalchemy import select, func
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from orm.device.model import Device
|
||||
|
|
@ -58,19 +58,15 @@ class DeviceRepository:
|
|||
status: Optional[str] = None,
|
||||
page: int = 1,
|
||||
page_size: int = 20,
|
||||
sort_by: str = "created_at",
|
||||
sort_order: str = "desc",
|
||||
) -> tuple[list[Device], int]:
|
||||
"""
|
||||
Find all devices with filtering, pagination and sorting
|
||||
Find all devices with filtering and pagination (sorted by creation time desc)
|
||||
|
||||
Args:
|
||||
search: Search keyword (searches in name and device_id)
|
||||
status: Filter by status
|
||||
page: Page number (starting from 1)
|
||||
page_size: Number of items per page
|
||||
sort_by: Field to sort by
|
||||
sort_order: Sort direction ('asc' or 'desc')
|
||||
|
||||
Returns:
|
||||
Tuple of (devices list, total count)
|
||||
|
|
@ -81,13 +77,7 @@ class DeviceRepository:
|
|||
# Apply search filter
|
||||
if search:
|
||||
search_pattern = f"%{search}%"
|
||||
stmt = stmt.where(
|
||||
or_(
|
||||
Device.name.ilike(search_pattern),
|
||||
Device.device_id.ilike(search_pattern),
|
||||
Device.model.ilike(search_pattern),
|
||||
)
|
||||
)
|
||||
stmt = stmt.where(Device.name.ilike(search_pattern))
|
||||
|
||||
# Apply status filter
|
||||
if status:
|
||||
|
|
@ -98,12 +88,8 @@ class DeviceRepository:
|
|||
total_result = await self.db.execute(count_stmt)
|
||||
total = total_result.scalar_one()
|
||||
|
||||
# Apply sorting
|
||||
sort_column = getattr(Device, sort_by, Device.created_at)
|
||||
if sort_order == "desc":
|
||||
stmt = stmt.order_by(sort_column.desc())
|
||||
else:
|
||||
stmt = stmt.order_by(sort_column.asc())
|
||||
# Apply sorting (fixed: created_at desc)
|
||||
stmt = stmt.order_by(Device.created_at.desc())
|
||||
|
||||
# Apply pagination
|
||||
offset = (page - 1) * page_size
|
||||
|
|
|
|||
|
|
@ -35,22 +35,18 @@ async def get_device_list(
|
|||
search: Annotated[str | None, Query(description="Search keyword")] = None,
|
||||
status: Annotated[str | None, Query(description="Filter by status")] = None,
|
||||
page: Annotated[int, Query(ge=1, description="Page number")] = 1,
|
||||
pageSize: Annotated[int, Query(ge=1, le=100, alias="pageSize", description="Items per page")] = 10,
|
||||
sortBy: Annotated[str, Query(alias="sortBy", description="Sort field")] = "createdAt",
|
||||
sortOrder: Annotated[str, Query(alias="sortOrder", pattern="^(asc|desc)$", description="Sort order")] = "desc",
|
||||
pageSize: Annotated[int, Query(ge=1, le=100, alias="pageSize", description="Items per page")] = 20,
|
||||
db: AsyncSession = Depends(get_db),
|
||||
) -> ApiResponse:
|
||||
"""
|
||||
Get Device list with search, filtering, pagination and sorting
|
||||
Get Device list with search, filtering and pagination (sorted by creation time desc)
|
||||
|
||||
- **search**: Search keyword (searches in name, device_id, and model)
|
||||
- **status**: Filter by status (active, inactive, offline)
|
||||
- **search**: Search keyword (searches in device name only)
|
||||
- **status**: Filter by status (online, offline)
|
||||
- **page**: Page number (starting from 1)
|
||||
- **pageSize**: Number of items per page (1-100)
|
||||
- **sortBy**: Field to sort by (default: createdAt)
|
||||
- **sortOrder**: Sort order - asc or desc (default: desc)
|
||||
- **pageSize**: Number of items per page (1-100, default: 20)
|
||||
|
||||
Returns paginated list of devices with total count.
|
||||
Returns paginated list of devices sorted by creation time (newest first) with total count.
|
||||
"""
|
||||
try:
|
||||
# Create query object
|
||||
|
|
@ -59,8 +55,6 @@ async def get_device_list(
|
|||
status=status,
|
||||
page=page,
|
||||
page_size=pageSize,
|
||||
sort_by=sortBy,
|
||||
sort_order=sortOrder,
|
||||
)
|
||||
|
||||
# Get service
|
||||
|
|
@ -181,14 +175,13 @@ async def update_device(
|
|||
|
||||
- **device_id**: Device unique ID
|
||||
|
||||
Request body (all fields optional):
|
||||
- **name**: Device display name
|
||||
- **model**: Device model
|
||||
Request body:
|
||||
- **firmwareVersion**: Firmware version
|
||||
- **status**: Device status
|
||||
- **isOnline**: Whether device is online
|
||||
- **status**: Device connection status (online, offline)
|
||||
- **description**: Device description
|
||||
- **metadata**: Additional metadata
|
||||
- **metaData**: Additional metadata (JSON format)
|
||||
|
||||
Note: Device name and model cannot be modified after creation.
|
||||
|
||||
Returns the updated device information.
|
||||
"""
|
||||
|
|
|
|||
|
|
@ -25,10 +25,11 @@ class DeviceBase(BaseModel):
|
|||
max_length=255,
|
||||
description="Device hardware ID"
|
||||
)
|
||||
model: Optional[str] = Field(
|
||||
device_model: Optional[str] = Field(
|
||||
None,
|
||||
alias="deviceModel",
|
||||
max_length=100,
|
||||
description="Device model (e.g., PLAUD NOTE)"
|
||||
description="Device model name (e.g., PLAUD NOTE, ESP32-S3)"
|
||||
)
|
||||
firmware_version: Optional[str] = Field(
|
||||
None,
|
||||
|
|
@ -37,18 +38,18 @@ class DeviceBase(BaseModel):
|
|||
description="Firmware version"
|
||||
)
|
||||
status: str = Field(
|
||||
default="active",
|
||||
default="offline",
|
||||
max_length=20,
|
||||
description="Device status (active, inactive, offline)"
|
||||
description="Device connection status (online, offline)"
|
||||
)
|
||||
description: Optional[str] = Field(
|
||||
None,
|
||||
description="Device description"
|
||||
)
|
||||
extra_data: Optional[str] = Field(
|
||||
meta_data: Optional[str] = Field(
|
||||
None,
|
||||
alias="extraData",
|
||||
description="Additional metadata (JSON format)"
|
||||
alias="metaData",
|
||||
description="Device metadata (JSON format)"
|
||||
)
|
||||
|
||||
model_config = {
|
||||
|
|
@ -57,10 +58,11 @@ class DeviceBase(BaseModel):
|
|||
"example": {
|
||||
"name": "My PLAUD Device",
|
||||
"deviceId": "PLAUD-12345678",
|
||||
"model": "PLAUD NOTE",
|
||||
"deviceModel": "PLAUD NOTE",
|
||||
"firmwareVersion": "1.0.0",
|
||||
"status": "active",
|
||||
"description": "My personal voice recorder"
|
||||
"status": "offline",
|
||||
"description": "My personal voice recorder",
|
||||
"metaData": "{\"deviceType\": \"PLAUD NOTE\", \"firmwareVersion\": \"1.0.0\"}"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -91,26 +93,15 @@ class DeviceCreate(DeviceBase):
|
|||
@classmethod
|
||||
def validate_status(cls, v: str) -> str:
|
||||
"""Validate status value"""
|
||||
valid_statuses = ["active", "inactive", "offline"]
|
||||
valid_statuses = ["online", "offline"]
|
||||
if v not in valid_statuses:
|
||||
raise ValueError(f"Status must be one of: {', '.join(valid_statuses)}")
|
||||
return v
|
||||
|
||||
|
||||
class DeviceUpdate(BaseModel):
|
||||
"""Schema for updating a Device (all fields optional)"""
|
||||
"""Schema for updating a Device"""
|
||||
|
||||
name: Optional[str] = Field(
|
||||
None,
|
||||
min_length=1,
|
||||
max_length=255,
|
||||
description="Device display name"
|
||||
)
|
||||
model: Optional[str] = Field(
|
||||
None,
|
||||
max_length=100,
|
||||
description="Device model"
|
||||
)
|
||||
firmware_version: Optional[str] = Field(
|
||||
None,
|
||||
alias="firmwareVersion",
|
||||
|
|
@ -120,51 +111,36 @@ class DeviceUpdate(BaseModel):
|
|||
status: Optional[str] = Field(
|
||||
None,
|
||||
max_length=20,
|
||||
description="Device status"
|
||||
)
|
||||
is_online: Optional[bool] = Field(
|
||||
None,
|
||||
alias="isOnline",
|
||||
description="Whether device is online"
|
||||
description="Device connection status (online, offline)"
|
||||
)
|
||||
description: Optional[str] = Field(
|
||||
None,
|
||||
description="Device description"
|
||||
)
|
||||
extra_data: Optional[str] = Field(
|
||||
meta_data: Optional[str] = Field(
|
||||
None,
|
||||
alias="extraData",
|
||||
description="Additional metadata"
|
||||
alias="metaData",
|
||||
description="Additional metadata (JSON format)"
|
||||
)
|
||||
|
||||
model_config = {
|
||||
"populate_by_name": True,
|
||||
"json_schema_extra": {
|
||||
"example": {
|
||||
"name": "Updated Device Name",
|
||||
"status": "active",
|
||||
"isOnline": True,
|
||||
"firmwareVersion": "1.1.0"
|
||||
"status": "online",
|
||||
"firmwareVersion": "1.1.0",
|
||||
"description": "Updated device description",
|
||||
"metaData": "{\"deviceType\": \"PLAUD NOTE\", \"firmwareVersion\": \"1.1.0\"}"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@field_validator('name')
|
||||
@classmethod
|
||||
def validate_name(cls, v: Optional[str]) -> Optional[str]:
|
||||
"""Validate and clean device name"""
|
||||
if v is not None:
|
||||
v = v.strip()
|
||||
if not v:
|
||||
raise ValueError("Device name cannot be empty")
|
||||
return v
|
||||
|
||||
@field_validator('status')
|
||||
@classmethod
|
||||
def validate_status(cls, v: Optional[str]) -> Optional[str]:
|
||||
"""Validate status value"""
|
||||
if v is not None:
|
||||
valid_statuses = ["active", "inactive", "offline"]
|
||||
valid_statuses = ["online", "offline"]
|
||||
if v not in valid_statuses:
|
||||
raise ValueError(f"Status must be one of: {', '.join(valid_statuses)}")
|
||||
return v
|
||||
|
|
@ -176,24 +152,27 @@ class DeviceResponse(BaseModel):
|
|||
id: str = Field(..., description="Device unique ID")
|
||||
name: str = Field(..., description="Device display name")
|
||||
device_id: str = Field(..., alias="deviceId", description="Device hardware ID")
|
||||
model: Optional[str] = Field(None, description="Device model")
|
||||
device_model: Optional[str] = Field(
|
||||
None,
|
||||
alias="deviceModel",
|
||||
description="Device model name"
|
||||
)
|
||||
firmware_version: Optional[str] = Field(
|
||||
None,
|
||||
alias="firmwareVersion",
|
||||
description="Firmware version"
|
||||
)
|
||||
status: str = Field(..., description="Device status")
|
||||
is_online: bool = Field(..., alias="isOnline", description="Whether device is online")
|
||||
status: str = Field(..., description="Device connection status (online, offline)")
|
||||
last_seen_at: Optional[datetime] = Field(
|
||||
None,
|
||||
alias="lastSeenAt",
|
||||
description="Last seen timestamp"
|
||||
)
|
||||
description: Optional[str] = Field(None, description="Device description")
|
||||
extra_data: Optional[str] = Field(
|
||||
meta_data: Optional[str] = Field(
|
||||
None,
|
||||
alias="extraData",
|
||||
description="Additional metadata"
|
||||
alias="metaData",
|
||||
description="Device metadata (JSON format)"
|
||||
)
|
||||
created_at: datetime = Field(
|
||||
...,
|
||||
|
|
@ -214,13 +193,12 @@ class DeviceResponse(BaseModel):
|
|||
"id": "1234567890",
|
||||
"name": "My PLAUD Device",
|
||||
"deviceId": "PLAUD-12345678",
|
||||
"model": "PLAUD NOTE",
|
||||
"deviceModel": "PLAUD NOTE",
|
||||
"firmwareVersion": "1.0.0",
|
||||
"status": "active",
|
||||
"isOnline": True,
|
||||
"status": "online",
|
||||
"lastSeenAt": "2024-01-01T00:00:00",
|
||||
"description": "My personal voice recorder",
|
||||
"metadata": None,
|
||||
"metaData": "{\"deviceType\": \"PLAUD NOTE\", \"firmwareVersion\": \"1.0.0\"}",
|
||||
"createdAt": "2024-01-01T00:00:00",
|
||||
"updatedAt": "2024-01-01T00:00:00"
|
||||
}
|
||||
|
|
@ -252,17 +230,6 @@ class DeviceListQuery(BaseModel):
|
|||
le=100,
|
||||
description="Number of items per page"
|
||||
)
|
||||
sort_by: str = Field(
|
||||
default="createdAt",
|
||||
alias="sortBy",
|
||||
description="Sort field"
|
||||
)
|
||||
sort_order: str = Field(
|
||||
default="desc",
|
||||
alias="sortOrder",
|
||||
pattern="^(asc|desc)$",
|
||||
description="Sort order (asc or desc)"
|
||||
)
|
||||
|
||||
model_config = {
|
||||
"populate_by_name": True
|
||||
|
|
|
|||
|
|
@ -48,8 +48,6 @@ class DeviceService:
|
|||
status=query.status,
|
||||
page=query.page,
|
||||
page_size=query.page_size,
|
||||
sort_by=query.sort_by,
|
||||
sort_order=query.sort_order,
|
||||
)
|
||||
|
||||
logger.info(
|
||||
|
|
@ -121,11 +119,11 @@ class DeviceService:
|
|||
id=device_id,
|
||||
name=device_data.name,
|
||||
device_id=device_data.device_id,
|
||||
model=device_data.model,
|
||||
device_model=device_data.device_model,
|
||||
firmware_version=device_data.firmware_version,
|
||||
status=device_data.status,
|
||||
description=device_data.description,
|
||||
extra_data=device_data.extra_data,
|
||||
meta_data=device_data.meta_data,
|
||||
)
|
||||
|
||||
# Persist to database
|
||||
|
|
@ -160,14 +158,13 @@ class DeviceService:
|
|||
for field, value in update_data.items():
|
||||
# Convert camelCase to snake_case
|
||||
db_field = field.replace("firmwareVersion", "firmware_version")
|
||||
db_field = db_field.replace("isOnline", "is_online")
|
||||
db_field = db_field.replace("extraData", "extra_data")
|
||||
db_field = db_field.replace("metaData", "meta_data")
|
||||
|
||||
if hasattr(device, db_field):
|
||||
setattr(device, db_field, value)
|
||||
|
||||
# Business logic: Update last_seen_at if device comes online
|
||||
if device_data.is_online is True:
|
||||
if "status" in update_data and update_data["status"] == "online":
|
||||
device.last_seen_at = datetime.now(timezone.utc)
|
||||
|
||||
# Business logic: Update timestamp
|
||||
|
|
@ -207,14 +204,14 @@ class DeviceService:
|
|||
async def update_device_status(
|
||||
self,
|
||||
device_id: str,
|
||||
is_online: bool
|
||||
status: str
|
||||
) -> Optional[Device]:
|
||||
"""
|
||||
Update device online status
|
||||
Update device connection status
|
||||
|
||||
Args:
|
||||
device_id: Device unique ID
|
||||
is_online: Whether device is online
|
||||
status: Device connection status (online, offline)
|
||||
|
||||
Returns:
|
||||
Updated device instance or None if not found
|
||||
|
|
@ -223,13 +220,13 @@ class DeviceService:
|
|||
if not device:
|
||||
return None
|
||||
|
||||
device.is_online = is_online
|
||||
device.status = status
|
||||
device.last_seen_at = datetime.now(timezone.utc)
|
||||
device.updated_at = datetime.now(timezone.utc)
|
||||
|
||||
device = await self.repo.save(device)
|
||||
|
||||
logger.info(f"Updated device status: {device_id} (online={is_online})")
|
||||
logger.info(f"Updated device status: {device_id} (status={status})")
|
||||
|
||||
return device
|
||||
|
||||
|
|
|
|||
Loading…
Reference in a new issue