import asyncio from sqlalchemy import select, update, insert from utils.logger import session_logger from database.models import DeviceAuth from services.database_service_base import DatabaseServiceBase from typing import Optional class DeviceAuthManager(DatabaseServiceBase): def __init__(self): super().__init__(service_name="device_auth") self.auth_cache = {} # 缓存设备认证信息 self.lock = asyncio.Lock() async def authenticate_device(self, device_id: str, serial_number: str) -> bool: """验证设备凭据""" await self._init_database() if device_id in self.auth_cache: return self.auth_cache[device_id] == serial_number db_session = await self.get_session() try: query = select(DeviceAuth).where(DeviceAuth.device_id == device_id, DeviceAuth.is_active == True) result = await db_session.execute(query) device_auth = result.scalar_one_or_none() if device_auth and device_auth.serial_number == serial_number: self.auth_cache[device_id] = serial_number session_logger.info("system", "device_auth", f"设备 {device_id} 验证成功") return True session_logger.warning("system", "device_auth", f"设备 {device_id} 验证失败,无效的凭据") return False except Exception as e: session_logger.error("system", "device_auth", f"验证设备 {device_id} 时出错: {str(e)}") return False finally: await db_session.close() async def register_device(self, device_id: str, serial_number: str, batch_id: str = None, is_active: bool = True) -> bool: """注册新设备或更新已有设备""" await self._init_database() db_session = await self.get_session() try: query = select(DeviceAuth).where(DeviceAuth.device_id == device_id) result = await db_session.execute(query) existing_device = result.scalar_one_or_none() if existing_device: stmt = update(DeviceAuth).where( DeviceAuth.device_id == device_id ).values( serial_number=serial_number, batch_id=batch_id, is_active=is_active ) await db_session.execute(stmt) else: stmt = insert(DeviceAuth).values( device_id=device_id, serial_number=serial_number, batch_id=batch_id, is_active=is_active ) await db_session.execute(stmt) await db_session.commit() self.auth_cache[device_id] = serial_number session_logger.info("system", "device_auth", f"设备 {device_id} 注册成功,批次: {batch_id}") return True except Exception as e: await db_session.rollback() session_logger.error("system", "device_auth", f"注册设备 {device_id} 时出错: {str(e)}") return False finally: await db_session.close() async def get_device_info(self, device_id: str) -> Optional[dict]: """获取设备详细信息""" await self._init_database() db_session = await self.get_session() try: query = select(DeviceAuth).where(DeviceAuth.device_id == device_id) result = await db_session.execute(query) device = result.scalar_one_or_none() if not device: return None return { "device_id": device.device_id, "serial_number": device.serial_number, "batch_id": device.batch_id, "is_active": device.is_active, "created_at": device.created_at, "updated_at": device.updated_at } except Exception as e: session_logger.error("system", "device_auth", f"获取设备 {device_id} 信息时出错: {str(e)}") return None finally: await db_session.close() device_auth_manager = DeviceAuthManager()