|
@@ -5,6 +5,7 @@ import json
|
|
|
import traceback
|
|
|
from collections import deque
|
|
|
from typing import Optional, List
|
|
|
+import time
|
|
|
|
|
|
from common.sys_comm import LOGDBG, LOGINFO, LOGWARN, LOGERR
|
|
|
from common.sys_comm import (
|
|
@@ -176,6 +177,11 @@ class DeviceManager():
|
|
|
self.g_dev_map_lock = threading.Lock()
|
|
|
self.g_dev_map = {} # <dev_id: str, device: Device>
|
|
|
|
|
|
+ self.HEARTBEAT_TIMEOUT = 3600 * 24 # 超长保活时间
|
|
|
+
|
|
|
+ self.running_ = False
|
|
|
+ self.thread_ = None
|
|
|
+
|
|
|
def push_dev_map(self, dev_id:str, dev_instance:Device):
|
|
|
with self.g_dev_map_lock:
|
|
|
self.g_dev_map[dev_id] = dev_instance
|
|
@@ -199,6 +205,38 @@ class DeviceManager():
|
|
|
with self.g_dev_map_lock:
|
|
|
return list(self.g_dev_map.values())
|
|
|
|
|
|
+
|
|
|
+ # ------------------- 心跳检测相关 -------------------
|
|
|
+ def _heartbeat_monitor(self):
|
|
|
+ """后台线程:定时检查设备是否失活"""
|
|
|
+ while self.running_:
|
|
|
+ time.sleep(30)
|
|
|
+ now = int(time.time())
|
|
|
+ with self.g_dev_map_lock:
|
|
|
+ for dev_id, device in list(self.g_dev_map.items()):
|
|
|
+ last_keepalive = device.get_keepalive()
|
|
|
+ if now - last_keepalive > self.HEARTBEAT_TIMEOUT:
|
|
|
+
|
|
|
+ # device.online_ = 0 # 标记掉线
|
|
|
+
|
|
|
+ del self.g_dev_map[dev_id] # 直接销毁实例
|
|
|
+ LOGINFO(f"[WARN] Device {dev_id} heartbeat timeout destroy")
|
|
|
+
|
|
|
+ def start(self):
|
|
|
+ if not self.running_:
|
|
|
+ self.running_ = True
|
|
|
+ self.thread_ = threading.Thread(target=self._heartbeat_monitor, daemon=True)
|
|
|
+ self.thread_.start()
|
|
|
+ LOGINFO("[INFO] DeviceManager heartbeat task start")
|
|
|
+
|
|
|
+ def stop(self):
|
|
|
+ if self.running_:
|
|
|
+ self.running_ = False
|
|
|
+ if self.thread_:
|
|
|
+ self.thread_.join()
|
|
|
+ LOGINFO("[INFO] DeviceManager heartbeat task stop")
|
|
|
+
|
|
|
+
|
|
|
# 回调函数,处理查询结果:查询所有的设备信息
|
|
|
def cb_handle_query_all_dev_info(self, result, userdata):
|
|
|
try:
|