优化flask获取设备列表的逻辑
This commit is contained in:
@@ -6,7 +6,7 @@ import threading
|
||||
import time
|
||||
from pathlib import Path
|
||||
from queue import Queue
|
||||
from typing import Any, Dict
|
||||
from typing import Any, Dict, List
|
||||
from Entity import Variables
|
||||
from Utils.AiUtils import AiUtils
|
||||
from Utils.IOSAIStorage import IOSAIStorage
|
||||
@@ -85,6 +85,29 @@ def _normalize_type(v) -> int:
|
||||
def _is_online(d: Dict[str, Any]) -> bool:
|
||||
return _normalize_type(d.get("type", 1)) == 1
|
||||
|
||||
def _apply_device_snapshot(devices: List[Dict[str, Any]]):
|
||||
"""接收 DeviceInfo 送来的全量设备列表,直接覆盖 listData"""
|
||||
global listData
|
||||
try:
|
||||
normed = []
|
||||
for d in devices:
|
||||
# 拷贝一份,避免引用共享
|
||||
d = dict(d)
|
||||
d["type"] = _normalize_type(d.get("type", 1)) # 规范成 0/1
|
||||
normed.append(d)
|
||||
|
||||
with listLock:
|
||||
before = len(listData)
|
||||
listData[:] = normed # 全量覆盖
|
||||
|
||||
_log_device_changes("SNAPSHOT")
|
||||
try:
|
||||
LogManager.info(f"[DEVICE][SNAPSHOT] size={len(normed)} (was={before})")
|
||||
except Exception:
|
||||
print(f"[DEVICE][SNAPSHOT] size={len(normed)} (was={before})")
|
||||
except Exception as e:
|
||||
LogManager.error(f"[DEVICE][SNAPSHOT][ERROR] {e}")
|
||||
|
||||
def _apply_device_event(obj: Dict[str, Any]):
|
||||
"""把单条设备上线/下线事件落到 listData,并打印关键日志"""
|
||||
try:
|
||||
@@ -140,13 +163,25 @@ def _handle_conn(conn: socket.socket, addr):
|
||||
LogManager.warning(f"[SOCKET][WARN] 非法 JSON 丢弃: {line[:120]} err={e}")
|
||||
continue
|
||||
|
||||
# === 新增:如果是全量快照(包含 devices 字段) ===
|
||||
if "devices" in obj:
|
||||
devs = obj.get("devices") or []
|
||||
LogManager.info(f"[SOCKET][RECV][SNAPSHOT] size={len(devs)} keys={list(obj.keys())}")
|
||||
try:
|
||||
_apply_device_snapshot(devs)
|
||||
LogManager.info(f"[SOCKET][APPLY][SNAPSHOT] size={len(devs)}")
|
||||
except Exception as e:
|
||||
LogManager.error(f"[DEVICE][APPLY_SNAPSHOT][ERROR] {e}")
|
||||
continue # 处理完这一条,继续下一条 JSON
|
||||
|
||||
# === 否则按原来的单条设备事件处理(兼容旧逻辑) ===
|
||||
dev_id = obj.get("deviceId")
|
||||
typ = _normalize_type(obj.get("type", 1))
|
||||
obj["type"] = typ # 规范 1/0
|
||||
LogManager.info(f"[SOCKET][RECV] deviceId={dev_id} type={typ} keys={list(obj.keys())}")
|
||||
|
||||
try:
|
||||
_apply_device_event(obj) # ← 保持你的原设备增删逻辑
|
||||
_apply_device_event(obj) # 保持你原来的增删逻辑
|
||||
LogManager.info(f"[SOCKET][APPLY] deviceId={dev_id} type={typ}")
|
||||
except Exception as e:
|
||||
# 单条业务异常不让线程死
|
||||
|
||||
Reference in New Issue
Block a user