合并前复核:补齐急停释放、整轮中止和计划任务时限

Browse Source
This commit is contained in:
yws
2026-10-22 07:32:58 +00:00
parent 8a9495b185
commit a74fda07e2
14 changed files with 324 additions and 111 deletions
+7 -2
View File
@@ -179,8 +179,7 @@ class DriverClickProxy:
sx, sy = self._screen_pos(x, y) sx, sy = self._screen_pos(x, y)
if not self._driver.move_to(sx, sy): if not self._driver.move_to(sx, sy):
return False return False
self._driver.down(1) return self._driver.down(1) is not False
return True
def mouse_up(self, x, y): def mouse_up(self, x, y):
try: try:
@@ -226,6 +225,12 @@ def install_driver_click(auto, screen, driver=None, log=print):
return drv return drv
def stop_driver_click(auto):
handler = auto.input_handler
if isinstance(handler, DriverClickProxy):
handler._driver.emergency_stop()
@contextmanager @contextmanager
def driver_click_tasks(scheme, auto, screen, cfg, log=print): def driver_click_tasks(scheme, auto, screen, cfg, log=print):
"""每次游戏初始化完成后接管, 包括 all 任务和故障重启。""" """每次游戏初始化完成后接管, 包括 all 任务和故障重启。"""
+39 -43
View File
@@ -9,11 +9,10 @@ import json
import os import os
import sys import sys
from . import preflight from . import killswitch, preflight
from .aalc_engine import bootstrap from .aalc_engine import bootstrap
from . import killswitch
from .aalc_patches import (WindowGuard, driver_click_tasks, install_exact_team_match, from .aalc_patches import (WindowGuard, driver_click_tasks, install_exact_team_match,
install_robust_set_foreground) install_robust_set_foreground, stop_driver_click)
# 任务 -> {参数名: AALC 配置项}; 参数只在本次运行内生效 # 任务 -> {参数名: AALC 配置项}; 参数只在本次运行内生效
TASKS = { TASKS = {
@@ -76,48 +75,45 @@ def run(task, params):
from tasks.battle import battle from tasks.battle import battle
from utils.path_manager import path_manager from utils.path_manager import path_manager
# 急停热键: 装得越早越好。驱动级点击期间鼠标被人和程序抢来抢去, with killswitch.listening(log=log, on_stop=lambda: stop_driver_click(auto)):
# 用户没法用鼠标点停止按钮, 键盘是唯一可靠的中断手段。 problems = preflight.check(preflight.collect(cfg), task,
kill_listener = killswitch.install(log=log) desktop=None if cfg.simulator else preflight.desktop_size())
if problems:
for p in problems:
log('[ERROR] [lc_mcp] preflight: %s' % p)
return PREFLIGHT_EXIT
problems = preflight.check(preflight.collect(cfg), task, install_exact_team_match(auto, log)
desktop=None if cfg.simulator else preflight.desktop_size()) install_robust_set_foreground(screen, log=log)
if problems: guard = WindowGuard(screen, cfg, log=log)
for p in problems: guard.start()
log('[ERROR] [lc_mcp] preflight: %s' % p) restore_path = os.environ.get(RESTORE_ENV)
return PREFLIGHT_EXIT originals = apply_overrides(cfg, task, params, restore_path)
with driver_click_tasks(scheme, auto, screen, cfg, log=log):
install_exact_team_match(auto, log) try:
install_robust_set_foreground(screen, log=log) if task == 'all':
guard = WindowGuard(screen, cfg, log=log) scheme.script_task()
guard.start() return 0
restore_path = os.environ.get(RESTORE_ENV) # 与 script_task() 相同的前置步骤
originals = apply_overrides(cfg, task, params, restore_path) scheme.init_game()
with driver_click_tasks(scheme, auto, screen, cfg, log=log): path_manager.initialize_paths()
try: auto.clear_img_cache()
if task == 'all': retry_monitor.start()
scheme.script_task() get_reward = None
if auto.click_element('battle/turn_assets.png', take_screenshot=True):
print('[lc_mcp] 检测到正在战斗, 先打完', flush=True)
get_reward = battle.fight()
{
'daily': scheme.Daily_task_wrapper(get_reward=get_reward),
'reward': scheme.to_get_reward,
'enkephalin': scheme.Buy_enkephalin,
'mirror': scheme.Mirror_task,
}[task]()
return 0 return 0
# 与 script_task() 相同的前置步骤 finally:
scheme.init_game() guard.stop()
path_manager.initialize_paths() retry_monitor.stop()
auto.clear_img_cache() restore(cfg, originals, restore_path)
retry_monitor.start()
get_reward = None
if auto.click_element('battle/turn_assets.png', take_screenshot=True):
print('[lc_mcp] 检测到正在战斗, 先打完', flush=True)
get_reward = battle.fight()
{
'daily': scheme.Daily_task_wrapper(get_reward=get_reward),
'reward': scheme.to_get_reward,
'enkephalin': scheme.Buy_enkephalin,
'mirror': scheme.Mirror_task,
}[task]()
return 0
finally:
guard.stop()
retry_monitor.stop()
restore(cfg, originals, restore_path)
def main(argv): def main(argv):
+33 -13
View File
@@ -22,6 +22,7 @@
import ctypes import ctypes
import os import os
import time import time
import threading
from ctypes import wintypes from ctypes import wintypes
from functools import lru_cache from functools import lru_cache
@@ -106,6 +107,9 @@ class DriverInput:
self.log = log self.log = log
self._dll = None self._dll = None
self._open = False self._open = False
self._stopped = False
self._input_lock = threading.RLock()
self._pressed = set()
# ---------------------------------------------------------------- 生命周期 # ---------------------------------------------------------------- 生命周期
@@ -131,7 +135,14 @@ class DriverInput:
@property @property
def ready(self): def ready(self):
return self._open and self._dll is not None return self._open and self._dll is not None and not self._stopped
def emergency_stop(self):
"""拒绝后续鼠标输入并释放本实例按住的按钮。急停线程另有退出超时。"""
self._stopped = True
with self._input_lock:
for button in tuple(self._pressed):
self.up(button)
def preflight(self): def preflight(self):
"""返回 (能否用, 原因)。用之前调一次, 把不能用的原因说清楚。""" """返回 (能否用, 原因)。用之前调一次, 把不能用的原因说清楚。"""
@@ -152,12 +163,13 @@ class DriverInput:
# ---------------------------------------------------------------- 移动 # ---------------------------------------------------------------- 移动
def move_relative(self, dx, dy): def move_relative(self, dx, dy):
if not self.ready: with self._input_lock:
return False if not self.ready:
if dx == 0 and dy == 0: return False
if dx == 0 and dy == 0:
return True
self._dll.moveR(int(dx), int(dy), True)
return True return True
self._dll.moveR(int(dx), int(dy), True)
return True
def move_to(self, sx, sy, tol=1, iters=10, settle=0.03): def move_to(self, sx, sy, tol=1, iters=10, settle=0.03):
"""把光标精确移到屏幕坐标 (sx, sy)。返回是否到位。""" """把光标精确移到屏幕坐标 (sx, sy)。返回是否到位。"""
@@ -177,12 +189,19 @@ class DriverInput:
# ---------------------------------------------------------------- 按键 # ---------------------------------------------------------------- 按键
def down(self, button=1): def down(self, button=1):
if self.ready: with self._input_lock:
self._dll.mouse_down(int(button)) if not self.ready:
return False
button = int(button)
self._pressed.add(button)
self._dll.mouse_down(button)
return True
def up(self, button=1): def up(self, button=1):
if self.ready: with self._input_lock:
self._dll.mouse_up(int(button)) if self._open and self._dll is not None:
self._dll.mouse_up(int(button))
self._pressed.discard(int(button))
def click(self, sx, sy, times=1, tol=1): def click(self, sx, sy, times=1, tol=1):
"""先确认到位置, 再按下抬起。没到位就不点, 免得点错地方。""" """先确认到位置, 再按下抬起。没到位就不点, 免得点错地方。"""
@@ -195,11 +214,12 @@ class DriverInput:
return False return False
for _ in range(int(times)): for _ in range(int(times)):
try: try:
self._dll.mouse_down(1) if not self.down(1):
return False
time.sleep(0.03) time.sleep(0.03)
finally: finally:
self._dll.mouse_up(1) self.up(1)
return True return not self._stopped
def key_down(self, key): def key_down(self, key):
if self.ready: if self.ready:
+39 -8
View File
@@ -9,25 +9,28 @@
里注册, lc_mcp 走的是命令行子进程, 那条路径上没有热键监听。 里注册, lc_mcp 走的是命令行子进程, 那条路径上没有热键监听。
默认 F12, 可用环境变量 LCP_KILL_KEY 改(取 pynput 的键名, 如 f11 / pause / esc)。 默认 F12, 可用环境变量 LCP_KILL_KEY 改(取 pynput 的键名, 如 f11 / pause / esc)。
按下后直接 os._exit —— 任务本来就是子进程, 硬退出不会留下锁或半截状态, 按下后终止任务子进程, 游戏保留。硬退出不会执行任务的 finally;
这正是 aalc_task.py 的设计前提("停止 = 杀进程树")。 临时配置由 TaskRunner 的恢复文件机制处理。退出前给驱动释放鼠标的短暂机会,
清理卡住时仍强制退出。
""" """
import os import os
import threading import threading
from contextlib import contextmanager
DEFAULT_KEY = 'f12' DEFAULT_KEY = 'f12'
EXIT_CODE = 130 # 与 SIGINT 一致, 便于上层识别"被用户中止" EXIT_CODE = 130 # 与 SIGINT 一致, 便于上层识别"被用户中止"
STOP_TIMEOUT = 0.25
def _key_spec(name): def _key_spec(name):
"""'f12' -> '<f12>',pynput 的 GlobalHotKeys 要求尖括号形式。""" """'f12' -> '<f12>',pynput 的 GlobalHotKeys 要求尖括号形式。"""
name = (name or DEFAULT_KEY).strip().lower() name = (name or '').strip().lower() or DEFAULT_KEY
if name.startswith('<') and name.endswith('>'): if name.startswith('<') and name.endswith('>'):
return name return name
return '<%s>' % name return '<%s>' % name
def install(log=print, key=None): def install(log=print, key=None, on_stop=None):
"""启动急停监听线程。返回监听器对象(可用于测试), 失败返回 None。 """启动急停监听线程。返回监听器对象(可用于测试), 失败返回 None。
任何异常都不向外抛 —— 急停装不上不该让任务起不来, 但必须把原因说清楚。 任何异常都不向外抛 —— 急停装不上不该让任务起不来, 但必须把原因说清楚。
@@ -48,10 +51,28 @@ def install(log=print, key=None):
if state['fired']: if state['fired']:
return return
state['fired'] = True state['fired'] = True
log('[lc_mcp] ⛔ 急停热键 %s 被按下, 立即终止任务' % key.upper()) # Windows 在系统输入线程上调用此函数, 不在这里写日志或等待清理。
# 即使日志锁/驱动清理卡住, 也必须按时退出。
timer = threading.Timer(STOP_TIMEOUT, os._exit, args=(EXIT_CODE,))
timer.daemon = True
def shutdown():
try:
if on_stop is not None:
on_stop()
finally:
try:
os._exit(EXIT_CODE)
finally:
timer.cancel() # 仅供 _exit 被测试替换的情况
try: try:
log('[lc_mcp] 游戏窗口会保留, 可用 run_task 重新开始') timer.start()
finally: worker = threading.Thread(target=shutdown, name='lc-mcp-emergency-stop', daemon=True)
state['worker'] = worker
worker.start()
except Exception:
timer.cancel()
os._exit(EXIT_CODE) os._exit(EXIT_CODE)
try: try:
@@ -63,7 +84,8 @@ def install(log=print, key=None):
% (type(e).__name__, e)) % (type(e).__name__, e))
return None return None
log('[lc_mcp] 急停热键已就绪: 按 %s 立即停止任务(键盘可用, 不需要鼠标)' % key.upper()) log('[lc_mcp] 急停监听已启动: 按 %s 终止任务, 游戏窗口保留; 可用 run_task 重新开始'
% key.upper())
listener._lc_state = state listener._lc_state = state
return listener return listener
@@ -76,3 +98,12 @@ def stop(listener):
listener.stop() listener.stop()
except Exception: except Exception:
pass pass
@contextmanager
def listening(log=print, on_stop=None):
listener = install(log=log, on_stop=on_stop)
try:
yield listener
finally:
stop(listener)
+3 -1
View File
@@ -12,6 +12,7 @@ import time
from collections import deque from collections import deque
from .aalc_task import RESTORE_ENV from .aalc_task import RESTORE_ENV
from .killswitch import EXIT_CODE as USER_ABORT_EXIT
REPO = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) REPO = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
IS_WIN = sys.platform.startswith('win') IS_WIN = sys.platform.startswith('win')
@@ -186,7 +187,8 @@ class TaskRunner:
state = 'running' state = 'running'
else: else:
self.info.setdefault('ended', time.time()) self.info.setdefault('ended', time.time())
state = 'stopped' if self.info['stopped_by_user'] else 'succeeded' if code == 0 else 'failed' state = ('stopped' if self.info['stopped_by_user'] or code == USER_ABORT_EXIT
else 'succeeded' if code == 0 else 'failed')
r = {'ok': True, 'state': state, 'task': self.info['task'], 'params': self.info['params'], r = {'ok': True, 'state': state, 'task': self.info['task'], 'params': self.info['params'],
'elapsed_s': int((self.info.get('ended') or time.time()) - self.info['started']), 'elapsed_s': int((self.info.get('ended') or time.time()) - self.info['started']),
'log': self.info['log'], 'log_tail': tail(self.info['log'], max(1, min(int(lines), 200)))} 'log': self.info['log'], 'log_tail': tail(self.info['log'], max(1, min(int(lines), 200)))}