script.py 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782
  1. # This Python file uses the following encoding: utf-8
  2. # @author runhey
  3. # github https://github.com/runhey
  4. from functools import wraps
  5. import zerorpc
  6. import zmq
  7. import msgpack
  8. import random
  9. import re
  10. import cv2
  11. import time
  12. import os
  13. import inflection
  14. import asyncio
  15. import json
  16. from datetime import date
  17. import threading
  18. from typing import Callable
  19. from datetime import datetime, timedelta
  20. from pathlib import Path
  21. from cached_property import cached_property
  22. from pydantic import BaseModel, ValidationError
  23. from threading import Thread
  24. from multiprocessing.queues import Queue
  25. from module.config.utils import convert_to_underscore
  26. from module.config.config import Config
  27. from module.config.config_model import ConfigModel
  28. from module.config.instance_guard import InstanceGuard
  29. from module.device.device import Device
  30. from module.device.env import IS_WINDOWS
  31. from module.base.utils import load_module
  32. from module.base.decorator import del_cached_property
  33. from module.logger import logger
  34. from module.exception import *
  35. from module.server.i18n import I18n
  36. from module.ocr.rpc import ensure_ocr_server_started
  37. _log_switch_lock = threading.Lock()#线程锁
  38. class Script:
  39. def __init__(self, config_name: str ='oas') -> None:
  40. logger.hr('Start', level=0)
  41. self.server = None
  42. self.state_queue: Queue = None
  43. self._emulator_down = False
  44. self.gui_update_task: Callable = None # 回调函数, gui进程注册当每次config更新任务的时候更新gui的信息
  45. self.config_name = config_name
  46. # Skip first restart
  47. self.is_first_task = True
  48. # Failure count of tasks
  49. # Key: str, task name, value: int, failure count
  50. self.failure_record = {}
  51. # 运行loop的线程
  52. self.loop_thread: Thread = None
  53. # 跨进程排队管理器(仅在 queue_mode=True 时初始化)
  54. self.instance_guard: InstanceGuard = None
  55. @cached_property
  56. def config(self) -> "Config":
  57. try:
  58. from module.config.config import Config
  59. config = Config(config_name=self.config_name)
  60. return config
  61. except RequestHumanTakeover:
  62. logger.critical('Request human takeover')
  63. exit(1)
  64. except Exception as e:
  65. logger.exception(e)
  66. exit(1)
  67. @cached_property
  68. def device(self) -> "Device":
  69. try:
  70. from module.device.device import Device
  71. device = Device(config=self.config)
  72. return device
  73. except RequestHumanTakeover:
  74. logger.critical('Request human takeover')
  75. exit(1)
  76. except Exception as e:
  77. logger.exception(e)
  78. exit(1)
  79. @cached_property
  80. def checker(self):
  81. """
  82. 占位函数,在alas中是检查服务器是否正常的
  83. :return:
  84. """
  85. return None
  86. def save_error_log(self):
  87. """
  88. Save last 60 screenshots in ./log/error/<timestamp>
  89. Save logs to ./log/error/<timestamp>/log.txt
  90. """
  91. from module.base.utils import save_image
  92. from module.handler.sensitive_info import (handle_sensitive_image,
  93. handle_sensitive_logs)
  94. if self.config.script.error.save_error:
  95. if not os.path.exists('./log/error'):
  96. os.mkdir('./log/error')
  97. folder_name = str(int(time.time() * 1000))
  98. folder = f'./log/error/{folder_name}'
  99. logger.warning(f'Saving error: {folder}')
  100. logger.info('保存详细错误的日志和截图到路径:')
  101. logger.info(f'{str( Path.cwd() / "log" / "error" / folder_name)}')
  102. os.mkdir(folder)
  103. for data in self.device.screenshot_deque:
  104. image_time = datetime.strftime(data['time'], '%Y-%m-%d_%H-%M-%S-%f')
  105. image = handle_sensitive_image(data['image'])
  106. save_image(image, f'{folder}/{image_time}.png')
  107. with open(logger.log_file, 'r', encoding='utf-8') as f:
  108. lines = f.readlines()
  109. start = 0
  110. for index, line in enumerate(lines):
  111. line = line.strip(' \r\t\n')
  112. if re.match('^═{15,}$', line):
  113. start = index
  114. lines = lines[start - 2:]
  115. lines = handle_sensitive_logs(lines)
  116. with open(f'{folder}/log.txt', 'w', encoding='utf-8') as f:
  117. f.writelines(lines)
  118. def init_server(self, port: int) -> int:
  119. """
  120. 初始化zerorpc服务,返回端口号
  121. :return:
  122. """
  123. self.server = zerorpc.Server(self)
  124. try:
  125. self.server.bind(f'tcp://127.0.0.1:{port}')
  126. return port
  127. except zmq.error.ZMQError:
  128. logger.error(f"Ocr server cannot bind on port {port}")
  129. return None
  130. def run_server(self) -> None:
  131. """
  132. 启动zerorpc服务
  133. :return:
  134. """
  135. self.server.run()
  136. def gui_args(self, task: str) -> str:
  137. """
  138. 获取给gui显示的参数
  139. :return:
  140. """
  141. return self.config.gui_args(task=task)
  142. def gui_menu(self) -> str:
  143. """
  144. 获取给gui显示的菜单
  145. :return:
  146. """
  147. return self.config.gui_menu
  148. def gui_task(self, task: str) -> str:
  149. """
  150. 获取给gui显示的任务 的参数的具体值
  151. :return:
  152. """
  153. return self.config.model.gui_task(task=task)
  154. def gui_set_task(self, task: str, group: str, argument: str, value) -> bool:
  155. """
  156. 设置给gui显示的任务 的参数的具体值
  157. :return:
  158. """
  159. # 验证参数
  160. task = convert_to_underscore(task)
  161. group = convert_to_underscore(group)
  162. argument = convert_to_underscore(argument)
  163. # pandtic验证
  164. if isinstance(value, str):
  165. if len(value) == 8:
  166. try:
  167. value = datetime.strptime(value, '%H:%M:%S').time()
  168. except ValueError:
  169. pass
  170. path = f'{task}.{group}.{argument}'
  171. task_object = getattr(self.config.model, task, None)
  172. group_object = getattr(task_object, group, None)
  173. argument_object = getattr(group_object, argument, None)
  174. if argument_object is None:
  175. logger.error(f'Set arg {task}.{group}.{argument}.{value} failed')
  176. return False
  177. try:
  178. setattr(group_object, argument, value)
  179. argument_object = getattr(group_object, argument, None)
  180. logger.info(f'Set arg {task}.{group}.{argument}.{argument_object}')
  181. self.config.save() # 我是没有想到什么方法可以使得属性改变自动保存的
  182. return True
  183. except ValidationError as e:
  184. logger.error(e)
  185. return False
  186. @zerorpc.stream
  187. def gui_mirror_image(self):
  188. """
  189. 获取给gui显示的镜像
  190. :return: cv2的对象将 numpy 数组转换为字节串。接下来MsgPack 进行序列化发送方将图像数据转换为字节串
  191. """
  192. # return msgpack.packb(cv2.imencode('.jpg', self.device.screenshot())[1].tobytes())
  193. img = cv2.cvtColor(self.device.screenshot(), cv2.COLOR_RGB2BGR)
  194. self.device.stuck_record_clear()
  195. ret, buffer = cv2.imencode('.jpg', img)
  196. yield buffer.tobytes()
  197. def _gui_update_tasks(self) -> None:
  198. """
  199. 获取更新任务后 pending waiting 的任务 和 当前的任务的数据。打包给gui显示
  200. :return:
  201. """
  202. data = {}
  203. pending = []
  204. waiting = []
  205. task = {}
  206. if self.config.task is not None and self.config.task.next_run < datetime.now():
  207. task["name"] = self.config.task.command
  208. task["next_run"] = str(self.config.task.next_run)
  209. data["task"] = task
  210. for p in self.config.pending_task[1:]:
  211. item = {"name": p.command, "next_run": str(p.next_run)}
  212. pending.append(item)
  213. for w in self.config.waiting_task:
  214. item = {"name": w.command, "next_run": str(w.next_run)}
  215. waiting.append(item)
  216. data["pending"] = pending
  217. data["waiting"] = waiting
  218. if self.gui_update_task is not None:
  219. self.gui_update_task(data)
  220. def _gui_set_status(self, status: str) -> None:
  221. """
  222. 设置给gui显示的状态
  223. :param status: 可以在gui中显示的状态 有 "Init", "Empty"(不显示), "Run"(运行中), "Error", "Free"(空闲)
  224. :return:
  225. """
  226. data = {"status": status}
  227. if self.gui_update_task is not None:
  228. self.gui_update_task(data)
  229. def gui_task_list(self) -> str:
  230. """
  231. 获取给gui显示的任务列表
  232. :return:
  233. """
  234. result = {}
  235. for key, value in self.config.model.dict().items():
  236. if isinstance(value, str):
  237. continue
  238. if key == "restart":
  239. continue
  240. if "scheduler" not in value:
  241. continue
  242. scheduler = value["scheduler"]
  243. item = {"enable": scheduler["enable"],
  244. "next_run": str(scheduler["next_run"])}
  245. key = self.config.model.type(key)
  246. result[key] = item
  247. return json.dumps(result)
  248. def _release_token_before_wait(func):
  249. @wraps(func)
  250. def wrapper(self, future):
  251. if self.instance_guard and self.instance_guard.should_release(
  252. pending_task=self.config.pending_task,
  253. waiting_task=self.config.waiting_task,
  254. idle_threshold_minutes=self.config.script.optimization.queue_idle_threshold
  255. ):
  256. self.instance_guard.release()
  257. return func(self, future)
  258. return wrapper
  259. @_release_token_before_wait
  260. def wait_until(self, future):
  261. """
  262. Wait until a specific time.
  263. Args:
  264. future (datetime):
  265. Returns:
  266. bool: True if wait finished, False if config changed.
  267. """
  268. future = future + timedelta(seconds=1)
  269. self.config.start_watching()
  270. while 1:
  271. if datetime.now() > future:
  272. return True
  273. # if self.stop_event is not None:
  274. # if self.stop_event.is_set():
  275. # logger.info("Update event detected")
  276. # logger.info(f"[{self.config_name}] exited. Reason: Update")
  277. # exit(0)
  278. time.sleep(5)
  279. if self.config.should_reload():
  280. return False
  281. @staticmethod
  282. def _in_sleep_window(t, start, end) -> bool:
  283. if start == end:
  284. return False
  285. if start < end:
  286. return start <= t < end
  287. return t >= start or t < end
  288. @staticmethod
  289. def _next_time_point(now: datetime, end) -> datetime:
  290. candidate = now.replace(hour=end.hour, minute=end.minute, second=end.second, microsecond=0)
  291. if candidate <= now:
  292. candidate += timedelta(days=1)
  293. return candidate
  294. def _antiban_wake_time(self, now: datetime):
  295. ab = self.config.script.anti_ban
  296. if not ab.enable:
  297. return None
  298. wake = None
  299. if self._in_sleep_window(now.time(), ab.sleep_start, ab.sleep_end):
  300. wake = self._next_time_point(now, ab.sleep_end)
  301. limit = ab.daily_active_limit.total_seconds()
  302. if limit > 0:
  303. if getattr(self, '_active_date', None) != now.date():
  304. self._active_date = now.date()
  305. self._active_seconds_today = 0
  306. rest_until = getattr(self, '_rest_until', None)
  307. if rest_until and now < rest_until:
  308. wake = max(wake, rest_until) if wake else rest_until
  309. elif getattr(self, '_active_seconds_today', 0) >= limit:
  310. self._rest_until = now + ab.long_rest_duration
  311. self._active_seconds_today = 0
  312. wake = max(wake, self._rest_until) if wake else self._rest_until
  313. return wake
  314. def get_next_task(self) -> str:
  315. """
  316. 获取下一个任务的名字, 大驼峰。
  317. :return:
  318. """
  319. while True:
  320. task = self.config.get_next()
  321. self.config.task = task
  322. if self.state_queue:
  323. self.state_queue.put({"schedule": self.config.get_schedule_data()})
  324. now = datetime.now()
  325. antiban_wake = self._antiban_wake_time(now)
  326. if antiban_wake is not None:
  327. task.next_run = max(task.next_run, antiban_wake)
  328. if not self._try_acquire_queue_token():
  329. del_cached_property(self, "config")
  330. continue
  331. # 任务时间到了返回任务名称
  332. if task.next_run <= now:
  333. return task.command
  334. # 根据策略执行等待逻辑
  335. if not self._handle_wait_during_idle(task.next_run):
  336. # 若等待被打断, 则刷新配置
  337. del_cached_property(self, "config")
  338. def _try_acquire_queue_token(self) -> bool:
  339. """
  340. 尝试获取排队执行权。
  341. 如果排队模式未启用,返回 True。
  342. 如果排队模式启用但未能获取到执行权,进入等待循环直到获取成功或配置变更。
  343. Returns:
  344. True: 获取得执行权,可以执行任务
  345. False: 等待被配置变更打断,调用方应重新加载配置后重试
  346. """
  347. # 是否开启排队模式
  348. if not self.config.script.optimization.queue_mode:
  349. if self.instance_guard:
  350. self.instance_guard.remove_from_queue()
  351. self.instance_guard = None
  352. return True
  353. # 懒加载instance_guard
  354. if self.instance_guard is None:
  355. try:
  356. self.instance_guard = InstanceGuard(self.config_name)
  357. logger.info(f"[Queue] Queue mode enabled for '{self.config_name}'")
  358. except Exception:
  359. self.instance_guard = None
  360. return True
  361. # 尝试获取执行权
  362. if self.instance_guard.try_acquire():
  363. return True
  364. # 执行权获取失败,关闭模拟器并进入等待循环
  365. logger.info(f"[Queue] '{self.config_name}' waiting for execution token...")
  366. if (self.config.script.optimization.when_task_queue_empty == 'close_game'
  367. and not self._emulator_down
  368. and 'device' in self.__dict__):
  369. try:
  370. self.device.emulator_stop()
  371. self._emulator_down = True
  372. logger.info(f"[Queue] Emulator closed during queue wait")
  373. except Exception:
  374. pass
  375. self.config.start_watching()
  376. while True:
  377. time.sleep(30)
  378. if self.config.should_reload():
  379. logger.info(f"[Queue] Config changed, re-evaluating")
  380. return False
  381. if self.instance_guard.try_acquire():
  382. return True
  383. def _handle_wait_during_idle(self, next_run: datetime) -> bool:
  384. """
  385. 处理任务空闲期间的行为策略
  386. :param next_run: 下一个任务的时间
  387. :return: True 表示等待成功完成, False 表示等待被中断
  388. """
  389. method = self.config.script.optimization.when_task_queue_empty
  390. strategy_map = {
  391. "close_game": self._wait_close_game,
  392. "goto_main": self._wait_goto_main,
  393. }
  394. func = strategy_map.get(method)
  395. if func is None:
  396. logger.warning(f"Invalid Optimization_WhenTaskQueueEmpty: {method}, fallback to stay_there")
  397. func = self._wait_stay_there
  398. return func(next_run)
  399. @staticmethod
  400. def _time_to_timedelta(value) -> timedelta:
  401. if value is None:
  402. return timedelta(0)
  403. return timedelta(hours=value.hour, minutes=value.minute, seconds=value.second)
  404. def _wait_until_with_emulator_preheat(self, next_run: datetime) -> bool:
  405. """Wait until next_run; if emulator is down, preheat startup before next task."""
  406. if not self._emulator_down:
  407. return self.wait_until(next_run)
  408. startup_lead = self._time_to_timedelta(self.config.script.optimization.emulator_startup_lead_time)
  409. now = datetime.now()
  410. wake_time = next_run - startup_lead if startup_lead > timedelta(0) else next_run
  411. if wake_time < now:
  412. wake_time = now
  413. now = datetime.now()
  414. if wake_time > now:
  415. logger.info(f"Wait before wake emulator: {wake_time.strftime('%Y-%m-%d %H:%M:%S')}")
  416. if not self.wait_until(wake_time):
  417. return False
  418. if self._emulator_down:
  419. logger.info("Wake emulator before next task")
  420. if not self._try_acquire_queue_token():
  421. return False
  422. self.device = Device(self.config)
  423. self._emulator_down = False
  424. if wake_time < next_run:
  425. return self.wait_until(next_run)
  426. return True
  427. def _wait_close_game(self, next_run: datetime) -> bool:
  428. if self._emulator_down:
  429. logger.info("Emulator is down, skip close_game/goto_main action and wait with preheat")
  430. return self._wait_until_with_emulator_preheat(next_run)
  431. close_game_wait_duration = self.config.script.optimization.close_game_wait_duration
  432. close_game_wait = self._time_to_timedelta(close_game_wait_duration)
  433. close_emulator_wait_duration = self.config.script.optimization.close_emulator_wait_duration
  434. close_emulator_wait = self._time_to_timedelta(close_emulator_wait_duration)
  435. if close_emulator_wait > timedelta(0) and next_run > datetime.now() + close_emulator_wait:
  436. logger.info("Close emulator during wait")
  437. self.device.emulator_stop()
  438. self._emulator_down = True
  439. if not self._wait_until_with_emulator_preheat(next_run):
  440. return False
  441. self.run("Restart")
  442. return True
  443. if close_game_wait <= timedelta(0):
  444. logger.info("Close game during wait")
  445. self.device.app_stop()
  446. self.device.release_during_wait()
  447. if not self.wait_until(next_run):
  448. return False
  449. self.run("Restart")
  450. return True
  451. if next_run > datetime.now() + close_game_wait:
  452. logger.info("Close game during wait")
  453. self.device.app_stop()
  454. self.device.release_during_wait()
  455. if not self.wait_until(next_run):
  456. return False
  457. self.run("Restart")
  458. return True
  459. logger.info("Wait without closing game (close_game wait duration not reached)")
  460. self.device.release_during_wait()
  461. if not self.wait_until(next_run):
  462. return False
  463. return True
  464. def _wait_goto_main(self, next_run: datetime) -> bool:
  465. if self._emulator_down:
  466. logger.info("Emulator is down, skip goto_main and wait with preheat")
  467. return self._wait_until_with_emulator_preheat(next_run)
  468. close_emulator_wait_duration = self.config.script.optimization.close_emulator_wait_duration
  469. close_emulator_wait = self._time_to_timedelta(close_emulator_wait_duration)
  470. if close_emulator_wait > timedelta(0) and next_run > datetime.now() + close_emulator_wait:
  471. logger.info("Close emulator during wait")
  472. self.device.emulator_stop()
  473. self._emulator_down = True
  474. if not self._wait_until_with_emulator_preheat(next_run):
  475. return False
  476. self.run("Restart")
  477. return True
  478. logger.info("Goto main page during wait")
  479. self.run("GotoMain")
  480. self.device.release_during_wait()
  481. return self.wait_until(next_run)
  482. def _wait_stay_there(self, next_run: datetime) -> bool:
  483. if self._emulator_down:
  484. logger.info("Stay_there during wait (emulator is down, with preheat)")
  485. return self._wait_until_with_emulator_preheat(next_run)
  486. logger.info("Stay_there (no action) during wait")
  487. self.device.release_during_wait()
  488. return self.wait_until(next_run)
  489. def exception_handler(self, e: Exception, command: str) -> None:
  490. # 处理御魂溢出
  491. from tasks.Utils.post_diagnotor import PostDiagnotor, AnalyzeType
  492. image = getattr(self.device, 'image', None)
  493. # image为None则不做处理
  494. if image is None:
  495. return
  496. analyse_type = PostDiagnotor().handle(e=e, command=command, image=image)
  497. if analyse_type == AnalyzeType.SoulOverflow:
  498. self.config.task_call('SoulsTidy')
  499. time.sleep(1)
  500. def run(self, command: str) -> bool:
  501. """
  502. :param command: 大写驼峰命名的任务名字
  503. :return:
  504. """
  505. if command == 'start' or command == 'goto_main':
  506. logger.error(f'Invalid command `{command}`')
  507. if not self._try_acquire_queue_token():
  508. return False
  509. if self.instance_guard and self.instance_guard.token_lost:
  510. logger.warning(f'Token lost, stopping emulator and rejoining queue')
  511. try:
  512. self.device.emulator_stop()
  513. except Exception:
  514. pass
  515. self._emulator_down = True
  516. self.instance_guard.release()
  517. return False
  518. try:
  519. self.device.screenshot()
  520. module_name = 'script_task'
  521. module_path = str(Path.cwd() / 'tasks' / command / (module_name+'.py'))
  522. logger.info(f'module_path: {module_path}, module_name: {module_name}')
  523. task_module = load_module(module_name, module_path)
  524. task_module.ScriptTask(config=self.config, device=self.device).run()
  525. except TaskEnd:
  526. return True
  527. except GameNotRunningError as e:
  528. logger.warning(e)
  529. self.exception_handler(e=e, command=command)
  530. self.config.task_call('Restart')
  531. return True
  532. except (GameStuckError, GameTooManyClickError) as e:
  533. logger.error(e)
  534. self.save_error_log()
  535. self.exception_handler(e=e, command=command)
  536. logger.warning(f'Game stuck, {self.device.package} will be restarted in 10 seconds')
  537. logger.warning('If you are playing by hand, please stop Alas')
  538. self.config.notifier.push(title=f'{I18n.trans_zh_cn(command)}{command}', content=f"<{self.config_name}> GameStuckError or GameTooManyClickError")
  539. self.config.task_call('Restart')
  540. self.device.sleep(10)
  541. return False
  542. except GameBugError as e:
  543. logger.warning(e)
  544. self.save_error_log()
  545. self.exception_handler(e=e, command=command)
  546. logger.warning('An error has occurred in Azur Lane game client, Alas is unable to handle')
  547. logger.warning(f'Restarting {self.device.package} to fix it')
  548. self.config.task_call('Restart')
  549. self.device.sleep(10)
  550. return False
  551. except GamePageUnknownError as e:
  552. logger.info('Game server may be under maintenance or network may be broken, check server status now')
  553. # 这个还不重要 留着坑填
  554. logger.critical('Game page unknown')
  555. self.save_error_log()
  556. self.exception_handler(e=e, command=command)
  557. self.config.notifier.push(title=f'{I18n.trans_zh_cn(command)}{command}', content=f"<{self.config_name}> GamePageUnknownError")
  558. self.config.task_call('Restart')
  559. self.device.sleep(10)
  560. return False
  561. except ScriptError as e:
  562. logger.critical(e)
  563. self.exception_handler(e=e, command=command)
  564. logger.critical('This is likely to be a mistake of developers, but sometimes just random issues')
  565. self.config.notifier.push(title=f'{I18n.trans_zh_cn(command)}{command}', content=f"<{self.config_name}> ScriptError")
  566. exit(1)
  567. except RequestHumanTakeover as e:
  568. logger.critical(e)
  569. self.exception_handler(e=e, command=command)
  570. logger.critical('Request human takeover')
  571. self.config.notifier.push(title=f'{I18n.trans_zh_cn(command)}{command}', content=f"<{self.config_name}> RequestHumanTakeover")
  572. exit(1)
  573. except Exception as e:
  574. logger.exception(e)
  575. self.exception_handler(e=e, command=command)
  576. self.save_error_log()
  577. self.config.notifier.push(title=f'{I18n.trans_zh_cn(command)}{command}', content=f"<{self.config_name}> Exception occured")
  578. exit(1)
  579. def loop(self):
  580. """
  581. Main loop of scheduler.
  582. :return:
  583. """
  584. with _log_switch_lock:
  585. logger.set_file_logger(self.config_name, do_cleanup=True)
  586. start_day = date.today()
  587. logger.info(f'Start scheduler loop: {self.config_name}')
  588. self.config.model.running_task = ''
  589. self._active_seconds_today = 0
  590. self._active_date = date.today()
  591. self._rest_until = None
  592. # Update GUI 防呆, 读取设置并立刻显示后台模拟器到前台
  593. if not self.config.script.device.run_background_only and IS_WINDOWS:
  594. from module.device.platform2.platform_windows import minimize_by_name, show_window_by_name
  595. target_window_name = self.config.script.device.handle # 在这里输入你的具体窗口名称
  596. if self.config.script.device.emulator_window_minimize:
  597. minimize_by_name(target_window_name)
  598. logger.info(f'重新显示: {target_window_name}')
  599. else:
  600. show_window_by_name(target_window_name)
  601. while 1:
  602. if date.today() > start_day:
  603. with _log_switch_lock:
  604. logger.set_file_logger(self.config_name, do_cleanup=True)
  605. start_day = date.today()
  606. # Check update event from GUI
  607. # if self.stop_event is not None:
  608. # if self.stop_event.is_set():
  609. # logger.info("Update event detected")
  610. # logger.info(f"Alas [{self.config_name}] exited.")
  611. # break
  612. # Check game server maintenance
  613. # self.checker.wait_until_available()
  614. # if self.checker.is_recovered():
  615. # # There is an accidental bug hard to reproduce
  616. # # Sometimes, config won't be updated due to blocking
  617. # # even though it has been changed
  618. # # So update it once recovered
  619. # del_cached_property(self, 'config')
  620. # logger.info('Server or network is recovered. Restart game client')
  621. # self.config.task_call('Restart')
  622. # Get task
  623. task = self.get_next_task()
  624. # Skip first restart
  625. if self.is_first_task and task == 'Restart':
  626. logger.info('Skip task `Restart` at scheduler start')
  627. self.config.task_delay(task='Restart', success=True, server=True)
  628. del_cached_property(self, 'config')
  629. continue
  630. if self._emulator_down:
  631. self.device = Device(self.config)
  632. self._emulator_down = False
  633. else:
  634. _ = self.device
  635. # Run
  636. logger.info(f'Scheduler: Start task `{task}`')
  637. self.device.stuck_record_clear()
  638. self.device.click_record_clear()
  639. logger.hr(task, level=0)
  640. self.config.model.running_task = task
  641. _task_start = datetime.now()
  642. success = self.run(inflection.camelize(task))
  643. self.config.model.running_task = ''
  644. logger.info(f'Scheduler: End task `{task}`')
  645. self.is_first_task = False
  646. if self._active_date != date.today():
  647. self._active_date = date.today()
  648. self._active_seconds_today = 0
  649. self._active_seconds_today += (datetime.now() - _task_start).total_seconds()
  650. # Check failures
  651. # failed = deep_get(self.failure_record, keys=task, default=0)
  652. failed = self.failure_record[task] if task in self.failure_record else 0
  653. failed = 0 if success else failed + 1
  654. # deep_set(self.failure_record, keys=task, value=failed)
  655. self.failure_record[task] = failed
  656. if failed >= 3:
  657. logger.critical(f"Task `{task}` failed 3 or more times.")
  658. logger.critical("Possible reason #1: You haven't used it correctly. "
  659. "Please read the help text of the options.")
  660. logger.critical("Possible reason #2: There is a problem with this task. "
  661. "Please contact developers or try to fix it yourself.")
  662. logger.critical('Request human takeover')
  663. # 添加失败三次的推送通知
  664. self.config.notifier.push(
  665. title=f'{I18n.trans_zh_cn(task)}{task}',
  666. content=f"<{self.config_name}> 任务连续失败三次,请上线查看"
  667. )
  668. # 关闭模拟器
  669. if self.config.script.error.error_repeated:
  670. self.device.emulator_stop()
  671. exit(1)
  672. if success:
  673. del_cached_property(self, 'config')
  674. continue
  675. elif self.config.script.error.handle_error:
  676. # self.config.task_delay(success=False)
  677. del_cached_property(self, 'config')
  678. # self.checker.check_now()
  679. continue
  680. else:
  681. break
  682. def start_loop(self) -> None:
  683. """
  684. 创建一个线程,运行loop
  685. :return:
  686. """
  687. if self.loop_thread is None:
  688. self.loop_thread = Thread(target=self.loop, name='Script_loop')
  689. self.loop_thread.start()
  690. if __name__ == "__main__":
  691. ensure_ocr_server_started()
  692. script = Script("oas1")
  693. script.loop()