Files
douyi_guaji_main/operations/screenshot_service.py
T
2026-01-01 13:25:50 +08:00

232 lines
9.2 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""operations.screenshot_service
简洁、类型良好的后台截图服务实现。
功能:
- 单例后台线程持续截图(避免主流程等待)
- 缓存验证与直接截图回退
- 对外导出 get_optimal_workers 工具函数
"""
from __future__ import annotations
import os
import threading
import time
from typing import Optional, Dict, Any
from datetime import datetime
from operations.screenshot_operations import ScreenshotOperations
import json
import path_config
def _streaming_enabled() -> bool:
"""从 config.json 动态读取 enable_streaming_screenshot(默认 True)。"""
try:
cfg_path = path_config.get_config_path()
if cfg_path and os.path.exists(cfg_path):
with open(cfg_path, "r", encoding="utf-8") as f:
cfg = json.load(f)
return bool(cfg.get("enable_streaming_screenshot", True))
except Exception:
pass
return True
class ScreenshotService:
"""后台截图服务(单例)"""
_instance: Optional["ScreenshotService"] = None
_lock = threading.Lock()
def __init__(self) -> None:
self._running: bool = False
self._thread: Optional[threading.Thread] = None
self._screenshot_ops: ScreenshotOperations = ScreenshotOperations()
self._current_device_id: Optional[str] = None
self._last_screenshot_time: float = time.time() - 10.0
self._screenshot_interval: float = 1.5
self._cache_valid_duration: float = 2.0
self._screenshot_path: Optional[str] = None
self._last_success: bool = False
# 缓存配置读取结果以避免每次调用都读取文件并频繁打印相同日志
self._streaming_enabled_cached: Optional[bool] = None
self._last_streaming_state_log_ts: float = 0.0
self._last_streaming_check_ts: float = 0.0
def _check_streaming_enabled(self) -> bool:
"""内部缓存检查配置,避免每次调用都读取文件。短时间内重复调用会复用缓存。"""
now = time.time()
# 刷新间隔:3 秒
try:
if self._streaming_enabled_cached is None or (now - self._last_streaming_check_ts) > 3.0:
try:
enabled = _streaming_enabled()
except Exception:
enabled = True
self._streaming_enabled_cached = bool(enabled)
self._last_streaming_check_ts = now
except Exception:
# 任何异常时默认启用以不阻塞主流程
self._streaming_enabled_cached = True
self._last_streaming_check_ts = now
return bool(self._streaming_enabled_cached)
@classmethod
def get_instance(cls) -> "ScreenshotService":
if cls._instance is None:
with cls._lock:
if cls._instance is None:
cls._instance = cls()
return cls._instance
def start(self, device_id: str, interval: float = 1.5) -> None:
"""启动后台截图服务"""
if not self._check_streaming_enabled():
timetag = datetime.now().strftime("%H:%M:%S")
# 仅在状态变化或首次检测时打印日志,避免重复冗余信息
now = time.time()
if now - self._last_streaming_state_log_ts > 30:
print(f"[{timetag}] [截图服务] 流式后台截图已被禁用(config),忽略 start() 请求")
self._last_streaming_state_log_ts = now
return
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={device_id}, interval={self._screenshot_interval}s")
def stop(self) -> None:
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) -> None:
loop_count = 0
while self._running:
try:
device_id = self._current_device_id
if not device_id:
time.sleep(0.1)
continue
loop_count += 1
timetag = datetime.now().strftime("%H:%M:%S")
start = time.time()
try:
success = self._screenshot_ops.get_screenshot(device_id, use_service=False) # type: ignore[arg-type]
except Exception:
success = False
elapsed_ms = (time.time() - start) * 1000
if success and self._screenshot_path and os.path.exists(self._screenshot_path):
try:
size = os.path.getsize(self._screenshot_path)
if size >= 1024:
with open(self._screenshot_path, "rb") as f:
header = f.read(4)
if header == b"\x89PNG":
self._last_screenshot_time = time.time()
self._last_success = True
print(f"[{timetag}] [截图服务] 完成 #{loop_count},{elapsed_ms:.0f}ms, {size}B")
else:
self._last_success = False
else:
self._last_success = False
except Exception:
self._last_success = False
else:
self._last_success = False
wait = max(0.5, self._screenshot_interval - elapsed_ms / 1000)
time.sleep(wait)
except Exception:
time.sleep(1.0)
def get_screenshot(self, device_id: str, force: bool = False) -> bool:
"""尝试从缓存返回截图状态;否则执行直接截图回退"""
if not self._check_streaming_enabled():
# 如果配置关闭但后台线程仍在运行,尝试停止它(仅在需要时)
if self._running:
try:
self.stop()
except Exception:
pass
timetag = datetime.now().strftime("%H:%M:%S")
now = time.time()
# 节流:30 秒内只打印一次此日志,避免重复输出
if now - self._last_streaming_state_log_ts > 30:
print(f"[{timetag}] [截图服务] 流式后台截图被禁用(config),get_screenshot() 返回 False,调用方应回退到直接截图")
self._last_streaming_state_log_ts = now
return False
if self._current_device_id != device_id:
self.start(device_id)
time.sleep(0.1)
if not force:
now = time.time()
if now - self._last_screenshot_time < self._cache_valid_duration and self._screenshot_path and os.path.exists(self._screenshot_path):
try:
size = os.path.getsize(self._screenshot_path)
if size >= 1024:
with open(self._screenshot_path, "rb") as f:
header = f.read(4)
if header == b"\x89PNG":
# If the cached file is a valid recent PNG, treat it as a successful cached screenshot.
# Do not rely on _last_success which may have been overwritten by later failed attempts.
return True
except Exception:
pass
try:
return bool(self._screenshot_ops.get_screenshot(device_id, use_service=False)) # type: ignore[arg-type]
except Exception:
return False
def is_running(self) -> bool:
return self._running
def get_cache_info(self) -> Dict[str, Any]:
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