script.py 28 KB

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