36 lines
1.3 KiB
Python
36 lines
1.3 KiB
Python
from datetime import datetime
|
|
from typing import Dict, Any, Optional
|
|
|
|
class DeviceStatusManager:
|
|
def __init__(self):
|
|
self._status: Dict[int, Dict[str, Any]] = {}
|
|
self._last_update: Dict[int, datetime] = {}
|
|
|
|
def update_status(self, device_id: int, status: Dict[str, Any]) -> None:
|
|
"""更新设备状态"""
|
|
self._status[device_id] = status
|
|
self._last_update[device_id] = datetime.utcnow()
|
|
|
|
def get_status(self, device_code: str) -> Optional[Dict[str, Any]]:
|
|
"""获取设备状态"""
|
|
status = self._status.get(device_code)
|
|
if status:
|
|
tim = self.get_last_update(device_code)
|
|
# 如果最后更新时间大于1分钟,则认为设备离线
|
|
if tim:
|
|
if (datetime.utcnow() - tim).total_seconds() > 60:
|
|
status["online"] = False
|
|
else:
|
|
return status
|
|
else:
|
|
return {}
|
|
else:
|
|
return {}
|
|
|
|
def get_last_update(self, device_code: str) -> Optional[datetime]:
|
|
"""获取设备最后更新时间"""
|
|
return self._last_update.get(device_code)
|
|
|
|
|
|
# 创建全局状态管理器实例
|
|
device_status_manager = DeviceStatusManager() |