"""简化版后台截图服务,避免文件中重复定义导致的 linter 错误。""" from __future__ import annotations import os import threading import time from typing import Optional from datetime import datetime import path_config from operations.screenshot_operations import ScreenshotOperations class ScreenshotService: """后台截图服务(简化实现)。""" _instance: Optional["ScreenshotService"] = None _lock = threading.Lock() def __init__(self): self._running = False self._thread: Optional[threading.Thread] = None self._screenshot_ops = ScreenshotOperations() self._current_device_id: Optional[str] = None self._last_screenshot_time = time.time() - 10.0 self._screenshot_interval = 3.5 self._cache_valid_duration = 4.0 self._screenshot_path: Optional[str] = None self._last_success = False @classmethod def get_instance(cls) -> "ScreenshotService": if cls._instance is None: with cls._lock: if cls._instance is None: cls._instance = cls() assert cls._instance is not None return cls._instance def start(self, device_id: str, interval: float = 1.5): with self._lock: if self._running and self._current_device_id == device_id: return if self._running: self.stop() self._current_device_id = device_id self._screenshot_interval = max(0.5, interval) self._running = True try: self._screenshot_path = path_config.get_screenshot_path() except Exception: self._screenshot_path = os.path.join("pic", "screenshot.png") self._thread = threading.Thread(target=self._screenshot_loop, daemon=True, name="ScreenshotService") self._thread.start() self._last_screenshot_time = time.time() - self._cache_valid_duration - 1.0 timetag = datetime.now().strftime("%H:%M:%S") print(f"[{timetag}] [截图服务] 已启动后台截图服务,设备: {device_id}, 间隔: {interval}秒") def stop(self): with self._lock: if not self._running: return self._running = False if self._thread and self._thread.is_alive(): self._thread.join(timeout=2.0) timetag = datetime.now().strftime("%H:%M:%S") print(f"[{timetag}] [截图服务] 已停止后台截图服务") def _screenshot_loop(self): while self._running: try: if not self._current_device_id: time.sleep(0.1) continue start = time.time() success = self._screenshot_ops.get_screenshot(self._current_device_id, use_service=False) elapsed = (time.time() - start) * 1000 timetag = datetime.now().strftime("%H:%M:%S") if success: self._last_screenshot_time = time.time() self._last_success = True print(f"[{timetag}] [截图服务] 后台截图成功,耗时: {elapsed:.0f}ms") else: self._last_success = False print(f"[{timetag}] [截图服务] 后台截图失败,耗时: {elapsed:.0f}ms") time.sleep(max(0.5, self._screenshot_interval - elapsed / 1000)) except Exception as e: print(f"[截图服务] 异常: {e}") time.sleep(1.0) def get_screenshot(self, device_id: str, force: bool = False) -> bool: # 优先使用缓存判断,简化版保留核心逻辑 if self._current_device_id != device_id: self.start(device_id) time.sleep(0.1) now = time.time() if not force and now - self._last_screenshot_time < self._cache_valid_duration: if self._screenshot_path and os.path.exists(self._screenshot_path): try: if os.path.getsize(self._screenshot_path) >= 1024: return True except Exception: pass # 回退到直接截图 return self._screenshot_ops.get_screenshot(device_id, use_service=False) def is_running(self) -> bool: return self._running def get_last_screenshot_time(self) -> float: return self._last_screenshot_time def get_cache_info(self) -> dict: return { "running": self._running, "device_id": self._current_device_id, "last_screenshot_time": self._last_screenshot_time, "interval": self._screenshot_interval, "cache_valid_duration": self._cache_valid_duration, "last_success": self._last_success, } def get_optimal_workers() -> int: cpu_count = os.cpu_count() or 4 if cpu_count >= 12: return 10 if cpu_count >= 8: return 8 if cpu_count >= 4: return 6 if cpu_count >= 2: return 3 return 2