kodi_alive_thread.py 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145
  1. import threading
  2. import time
  3. from utils.logger_config import logger
  4. from hardware.kodi_module import KodiClientManager
  5. class KodiAliveThreadSingleton:
  6. """Kodi心跳检测线程单例类,每秒检查一次心跳,如果检测不到Kodi在线则启动Kodi应用"""
  7. _instance = None
  8. _lock = threading.Lock()
  9. def __new__(cls):
  10. if cls._instance is None:
  11. with cls._lock:
  12. if cls._instance is None:
  13. cls._instance = super(KodiAliveThreadSingleton, cls).__new__(cls)
  14. return cls._instance
  15. def __init__(self):
  16. # 避免重复初始化
  17. if hasattr(self, '_initialized'):
  18. return
  19. self._initialized = True
  20. self.thread = None
  21. self.is_running = False
  22. self._should_stop = False
  23. self.manager: KodiClientManager = None
  24. # 配置参数
  25. self.check_interval_seconds = 1 # 每秒检查一次
  26. # 启动工作线程
  27. self._start_worker_thread()
  28. def _start_worker_thread(self):
  29. """启动工作线程"""
  30. if self.thread is None or not self.thread.is_alive():
  31. self.is_running = True
  32. self._should_stop = False
  33. self.thread = threading.Thread(target=self._worker_loop, daemon=True)
  34. self.thread.start()
  35. logger.info("Kodi心跳检测线程已启动")
  36. def _initialize_manager(self):
  37. """初始化KodiClientManager"""
  38. if self.manager is None:
  39. self.manager = KodiClientManager()
  40. logger.info("KodiClientManager 初始化成功")
  41. def _worker_loop(self):
  42. """工作线程主循环"""
  43. logger.info("Kodi心跳检测线程开始运行,每秒检查一次心跳")
  44. try:
  45. # 确保Manager已初始化
  46. self._initialize_manager()
  47. while self.is_running and not self._should_stop:
  48. try:
  49. # 检查所有Kodi客户端是否在线
  50. offline_client_index = self.manager.check_all_kodi_clients_online()
  51. if offline_client_index >= 0:
  52. # 检测到不在线的客户端,启动对应的Kodi应用
  53. logger.warning(f"检测到Kodi客户端 {offline_client_index} 不在线,尝试启动Kodi应用")
  54. try:
  55. # 根据client_index获取对应的客户端并启动
  56. if offline_client_index < len(self.manager.kodi_clients):
  57. client = self.manager.kodi_clients[offline_client_index]
  58. result = client.start_kodi()
  59. logger.info(f"已尝试启动客户端 {offline_client_index} 的Kodi应用,响应: {result}")
  60. else:
  61. logger.error(f"客户端索引 {offline_client_index} 超出范围,客户端总数: {len(self.manager.kodi_clients)}")
  62. except Exception as e:
  63. logger.error(f"启动客户端 {offline_client_index} 的Kodi应用时发生异常: {e}")
  64. else:
  65. # 所有客户端都在线
  66. logger.debug("所有Kodi客户端在线")
  67. # 等待指定时间后再次检查
  68. time.sleep(self.check_interval_seconds)
  69. if self._should_stop:
  70. logger.info("收到停止信号,退出循环")
  71. break
  72. except Exception as e:
  73. logger.error(f"工作线程循环异常: {e}")
  74. time.sleep(self.check_interval_seconds)
  75. except Exception as e:
  76. logger.error(f"工作线程异常: {e}")
  77. finally:
  78. self.is_running = False
  79. logger.info("Kodi心跳检测线程结束")
  80. def stop(self):
  81. """停止线程"""
  82. self._should_stop = True
  83. self.is_running = False
  84. logger.info("停止Kodi心跳检测线程")
  85. # 全局单例实例
  86. _kodi_alive_thread = KodiAliveThreadSingleton()
  87. def start_kodi_alive_check() -> bool:
  88. """
  89. 启动Kodi心跳检测
  90. 启动后,线程会每秒自动检查所有Kodi客户端的心跳
  91. 如果检测到不在线的客户端,会自动尝试启动对应的Kodi应用
  92. Returns:
  93. bool: 启动是否成功
  94. """
  95. if not _kodi_alive_thread.is_running:
  96. _kodi_alive_thread._start_worker_thread()
  97. return _kodi_alive_thread.is_running
  98. def stop_kodi_alive_check() -> bool:
  99. """
  100. 停止Kodi心跳检测
  101. Returns:
  102. bool: 停止是否成功
  103. """
  104. _kodi_alive_thread.stop()
  105. return True
  106. def is_alive_check_running() -> bool:
  107. """
  108. 检查心跳检测线程是否正在运行
  109. Returns:
  110. bool: 线程是否正在运行
  111. """
  112. return _kodi_alive_thread.is_running