script.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735
  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. def get_next_task(self) -> str:
  282. """
  283. 获取下一个任务的名字, 大驼峰。
  284. :return:
  285. """
  286. while True:
  287. task = self.config.get_next()
  288. self.config.task = task
  289. if self.state_queue:
  290. self.state_queue.put({"schedule": self.config.get_schedule_data()})
  291. now = datetime.now()
  292. if not self._try_acquire_queue_token():
  293. del_cached_property(self, "config")
  294. continue
  295. # 任务时间到了返回任务名称
  296. if task.next_run <= now:
  297. return task.command
  298. # 根据策略执行等待逻辑
  299. if not self._handle_wait_during_idle(task.next_run):
  300. # 若等待被打断, 则刷新配置
  301. del_cached_property(self, "config")
  302. def _try_acquire_queue_token(self) -> bool:
  303. """
  304. 尝试获取排队执行权。
  305. 如果排队模式未启用,返回 True。
  306. 如果排队模式启用但未能获取到执行权,进入等待循环直到获取成功或配置变更。
  307. Returns:
  308. True: 获取得执行权,可以执行任务
  309. False: 等待被配置变更打断,调用方应重新加载配置后重试
  310. """
  311. # 是否开启排队模式
  312. if not self.config.script.optimization.queue_mode:
  313. if self.instance_guard:
  314. self.instance_guard.remove_from_queue()
  315. self.instance_guard = None
  316. return True
  317. # 懒加载instance_guard
  318. if self.instance_guard is None:
  319. try:
  320. self.instance_guard = InstanceGuard(self.config_name)
  321. logger.info(f"[Queue] Queue mode enabled for '{self.config_name}'")
  322. except Exception:
  323. self.instance_guard = None
  324. return True
  325. # 尝试获取执行权
  326. if self.instance_guard.try_acquire():
  327. return True
  328. # 执行权获取失败,关闭模拟器并进入等待循环
  329. logger.info(f"[Queue] '{self.config_name}' waiting for execution token...")
  330. if (self.config.script.optimization.when_task_queue_empty == 'close_game'
  331. and not self._emulator_down
  332. and 'device' in self.__dict__):
  333. try:
  334. self.device.emulator_stop()
  335. self._emulator_down = True
  336. logger.info(f"[Queue] Emulator closed during queue wait")
  337. except Exception:
  338. pass
  339. self.config.start_watching()
  340. while True:
  341. time.sleep(30)
  342. if self.config.should_reload():
  343. logger.info(f"[Queue] Config changed, re-evaluating")
  344. return False
  345. if self.instance_guard.try_acquire():
  346. return True
  347. def _handle_wait_during_idle(self, next_run: datetime) -> bool:
  348. """
  349. 处理任务空闲期间的行为策略
  350. :param next_run: 下一个任务的时间
  351. :return: True 表示等待成功完成, False 表示等待被中断
  352. """
  353. method = self.config.script.optimization.when_task_queue_empty
  354. strategy_map = {
  355. "close_game": self._wait_close_game,
  356. "goto_main": self._wait_goto_main,
  357. }
  358. func = strategy_map.get(method)
  359. if func is None:
  360. logger.warning(f"Invalid Optimization_WhenTaskQueueEmpty: {method}, fallback to stay_there")
  361. func = self._wait_stay_there
  362. return func(next_run)
  363. @staticmethod
  364. def _time_to_timedelta(value) -> timedelta:
  365. if value is None:
  366. return timedelta(0)
  367. return timedelta(hours=value.hour, minutes=value.minute, seconds=value.second)
  368. def _wait_until_with_emulator_preheat(self, next_run: datetime) -> bool:
  369. """Wait until next_run; if emulator is down, preheat startup before next task."""
  370. if not self._emulator_down:
  371. return self.wait_until(next_run)
  372. startup_lead = self._time_to_timedelta(self.config.script.optimization.emulator_startup_lead_time)
  373. now = datetime.now()
  374. wake_time = next_run - startup_lead if startup_lead > timedelta(0) else next_run
  375. if wake_time < now:
  376. wake_time = now
  377. now = datetime.now()
  378. if wake_time > now:
  379. logger.info(f"Wait before wake emulator: {wake_time.strftime('%Y-%m-%d %H:%M:%S')}")
  380. if not self.wait_until(wake_time):
  381. return False
  382. if self._emulator_down:
  383. logger.info("Wake emulator before next task")
  384. if not self._try_acquire_queue_token():
  385. return False
  386. self.device = Device(self.config)
  387. self._emulator_down = False
  388. if wake_time < next_run:
  389. return self.wait_until(next_run)
  390. return True
  391. def _wait_close_game(self, next_run: datetime) -> bool:
  392. if self._emulator_down:
  393. logger.info("Emulator is down, skip close_game/goto_main action and wait with preheat")
  394. return self._wait_until_with_emulator_preheat(next_run)
  395. close_game_wait_duration = self.config.script.optimization.close_game_wait_duration
  396. close_game_wait = self._time_to_timedelta(close_game_wait_duration)
  397. close_emulator_wait_duration = self.config.script.optimization.close_emulator_wait_duration
  398. close_emulator_wait = self._time_to_timedelta(close_emulator_wait_duration)
  399. if close_emulator_wait > timedelta(0) and next_run > datetime.now() + close_emulator_wait:
  400. logger.info("Close emulator during wait")
  401. self.device.emulator_stop()
  402. self._emulator_down = True
  403. if not self._wait_until_with_emulator_preheat(next_run):
  404. return False
  405. self.run("Restart")
  406. return True
  407. if close_game_wait <= timedelta(0):
  408. logger.info("Close game during wait")
  409. self.device.app_stop()
  410. self.device.release_during_wait()
  411. if not self.wait_until(next_run):
  412. return False
  413. self.run("Restart")
  414. return True
  415. if next_run > datetime.now() + close_game_wait:
  416. logger.info("Close game during wait")
  417. self.device.app_stop()
  418. self.device.release_during_wait()
  419. if not self.wait_until(next_run):
  420. return False
  421. self.run("Restart")
  422. return True
  423. logger.info("Wait without closing game (close_game wait duration not reached)")
  424. self.device.release_during_wait()
  425. if not self.wait_until(next_run):
  426. return False
  427. return True
  428. def _wait_goto_main(self, next_run: datetime) -> bool:
  429. if self._emulator_down:
  430. logger.info("Emulator is down, skip goto_main and wait with preheat")
  431. return self._wait_until_with_emulator_preheat(next_run)
  432. close_emulator_wait_duration = self.config.script.optimization.close_emulator_wait_duration
  433. close_emulator_wait = self._time_to_timedelta(close_emulator_wait_duration)
  434. if close_emulator_wait > timedelta(0) and next_run > datetime.now() + close_emulator_wait:
  435. logger.info("Close emulator during wait")
  436. self.device.emulator_stop()
  437. self._emulator_down = True
  438. if not self._wait_until_with_emulator_preheat(next_run):
  439. return False
  440. self.run("Restart")
  441. return True
  442. logger.info("Goto main page during wait")
  443. self.run("GotoMain")
  444. self.device.release_during_wait()
  445. return self.wait_until(next_run)
  446. def _wait_stay_there(self, next_run: datetime) -> bool:
  447. if self._emulator_down:
  448. logger.info("Stay_there during wait (emulator is down, with preheat)")
  449. return self._wait_until_with_emulator_preheat(next_run)
  450. logger.info("Stay_there (no action) during wait")
  451. self.device.release_during_wait()
  452. return self.wait_until(next_run)
  453. def exception_handler(self, e: Exception, command: str) -> None:
  454. # 处理御魂溢出
  455. from tasks.Utils.post_diagnotor import PostDiagnotor, AnalyzeType
  456. image = getattr(self.device, 'image', None)
  457. # image为None则不做处理
  458. if image is None:
  459. return
  460. analyse_type = PostDiagnotor().handle(e=e, command=command, image=image)
  461. if analyse_type == AnalyzeType.SoulOverflow:
  462. self.config.task_call('SoulsTidy')
  463. time.sleep(1)
  464. def run(self, command: str) -> bool:
  465. """
  466. :param command: 大写驼峰命名的任务名字
  467. :return:
  468. """
  469. if command == 'start' or command == 'goto_main':
  470. logger.error(f'Invalid command `{command}`')
  471. if not self._try_acquire_queue_token():
  472. return False
  473. if self.instance_guard and self.instance_guard.token_lost:
  474. logger.warning(f'Token lost, stopping emulator and rejoining queue')
  475. try:
  476. self.device.emulator_stop()
  477. except Exception:
  478. pass
  479. self._emulator_down = True
  480. self.instance_guard.release()
  481. return False
  482. try:
  483. self.device.screenshot()
  484. module_name = 'script_task'
  485. module_path = str(Path.cwd() / 'tasks' / command / (module_name+'.py'))
  486. logger.info(f'module_path: {module_path}, module_name: {module_name}')
  487. task_module = load_module(module_name, module_path)
  488. task_module.ScriptTask(config=self.config, device=self.device).run()
  489. except TaskEnd:
  490. return True
  491. except GameNotRunningError as e:
  492. logger.warning(e)
  493. self.exception_handler(e=e, command=command)
  494. self.config.task_call('Restart')
  495. return True
  496. except (GameStuckError, GameTooManyClickError) as e:
  497. logger.error(e)
  498. self.save_error_log()
  499. self.exception_handler(e=e, command=command)
  500. logger.warning(f'Game stuck, {self.device.package} will be restarted in 10 seconds')
  501. logger.warning('If you are playing by hand, please stop Alas')
  502. self.config.notifier.push(title=f'{I18n.trans_zh_cn(command)}{command}', content=f"<{self.config_name}> GameStuckError or GameTooManyClickError")
  503. self.config.task_call('Restart')
  504. self.device.sleep(10)
  505. return False
  506. except GameBugError as e:
  507. logger.warning(e)
  508. self.save_error_log()
  509. self.exception_handler(e=e, command=command)
  510. logger.warning('An error has occurred in Azur Lane game client, Alas is unable to handle')
  511. logger.warning(f'Restarting {self.device.package} to fix it')
  512. self.config.task_call('Restart')
  513. self.device.sleep(10)
  514. return False
  515. except GamePageUnknownError as e:
  516. logger.info('Game server may be under maintenance or network may be broken, check server status now')
  517. # 这个还不重要 留着坑填
  518. logger.critical('Game page unknown')
  519. self.save_error_log()
  520. self.exception_handler(e=e, command=command)
  521. self.config.notifier.push(title=f'{I18n.trans_zh_cn(command)}{command}', content=f"<{self.config_name}> GamePageUnknownError")
  522. self.config.task_call('Restart')
  523. self.device.sleep(10)
  524. return False
  525. except ScriptError as e:
  526. logger.critical(e)
  527. self.exception_handler(e=e, command=command)
  528. logger.critical('This is likely to be a mistake of developers, but sometimes just random issues')
  529. self.config.notifier.push(title=f'{I18n.trans_zh_cn(command)}{command}', content=f"<{self.config_name}> ScriptError")
  530. exit(1)
  531. except RequestHumanTakeover as e:
  532. logger.critical(e)
  533. self.exception_handler(e=e, command=command)
  534. logger.critical('Request human takeover')
  535. self.config.notifier.push(title=f'{I18n.trans_zh_cn(command)}{command}', content=f"<{self.config_name}> RequestHumanTakeover")
  536. exit(1)
  537. except Exception as e:
  538. logger.exception(e)
  539. self.exception_handler(e=e, command=command)
  540. self.save_error_log()
  541. self.config.notifier.push(title=f'{I18n.trans_zh_cn(command)}{command}', content=f"<{self.config_name}> Exception occured")
  542. exit(1)
  543. def loop(self):
  544. """
  545. Main loop of scheduler.
  546. :return:
  547. """
  548. with _log_switch_lock:
  549. logger.set_file_logger(self.config_name, do_cleanup=True)
  550. start_day = date.today()
  551. logger.info(f'Start scheduler loop: {self.config_name}')
  552. self.config.model.running_task = ''
  553. # Update GUI 防呆, 读取设置并立刻显示后台模拟器到前台
  554. if not self.config.script.device.run_background_only and IS_WINDOWS:
  555. from module.device.platform2.platform_windows import minimize_by_name, show_window_by_name
  556. target_window_name = self.config.script.device.handle # 在这里输入你的具体窗口名称
  557. if self.config.script.device.emulator_window_minimize:
  558. minimize_by_name(target_window_name)
  559. logger.info(f'重新显示: {target_window_name}')
  560. else:
  561. show_window_by_name(target_window_name)
  562. while 1:
  563. if date.today() > start_day:
  564. with _log_switch_lock:
  565. logger.set_file_logger(self.config_name, do_cleanup=True)
  566. start_day = date.today()
  567. # Check update event from GUI
  568. # if self.stop_event is not None:
  569. # if self.stop_event.is_set():
  570. # logger.info("Update event detected")
  571. # logger.info(f"Alas [{self.config_name}] exited.")
  572. # break
  573. # Check game server maintenance
  574. # self.checker.wait_until_available()
  575. # if self.checker.is_recovered():
  576. # # There is an accidental bug hard to reproduce
  577. # # Sometimes, config won't be updated due to blocking
  578. # # even though it has been changed
  579. # # So update it once recovered
  580. # del_cached_property(self, 'config')
  581. # logger.info('Server or network is recovered. Restart game client')
  582. # self.config.task_call('Restart')
  583. # Get task
  584. task = self.get_next_task()
  585. # Skip first restart
  586. if self.is_first_task and task == 'Restart':
  587. logger.info('Skip task `Restart` at scheduler start')
  588. self.config.task_delay(task='Restart', success=True, server=True)
  589. del_cached_property(self, 'config')
  590. continue
  591. if self._emulator_down:
  592. self.device = Device(self.config)
  593. self._emulator_down = False
  594. else:
  595. _ = self.device
  596. # Run
  597. logger.info(f'Scheduler: Start task `{task}`')
  598. self.device.stuck_record_clear()
  599. self.device.click_record_clear()
  600. logger.hr(task, level=0)
  601. self.config.model.running_task = task
  602. success = self.run(inflection.camelize(task))
  603. self.config.model.running_task = ''
  604. logger.info(f'Scheduler: End task `{task}`')
  605. self.is_first_task = False
  606. # Check failures
  607. # failed = deep_get(self.failure_record, keys=task, default=0)
  608. failed = self.failure_record[task] if task in self.failure_record else 0
  609. failed = 0 if success else failed + 1
  610. # deep_set(self.failure_record, keys=task, value=failed)
  611. self.failure_record[task] = failed
  612. if failed >= 3:
  613. logger.critical(f"Task `{task}` failed 3 or more times.")
  614. logger.critical("Possible reason #1: You haven't used it correctly. "
  615. "Please read the help text of the options.")
  616. logger.critical("Possible reason #2: There is a problem with this task. "
  617. "Please contact developers or try to fix it yourself.")
  618. logger.critical('Request human takeover')
  619. # 添加失败三次的推送通知
  620. self.config.notifier.push(
  621. title=f'{I18n.trans_zh_cn(task)}{task}',
  622. content=f"<{self.config_name}> 任务连续失败三次,请上线查看"
  623. )
  624. # 关闭模拟器
  625. if self.config.script.error.error_repeated:
  626. self.device.emulator_stop()
  627. exit(1)
  628. if success:
  629. del_cached_property(self, 'config')
  630. continue
  631. elif self.config.script.error.handle_error:
  632. # self.config.task_delay(success=False)
  633. del_cached_property(self, 'config')
  634. # self.checker.check_now()
  635. continue
  636. else:
  637. break
  638. def start_loop(self) -> None:
  639. """
  640. 创建一个线程,运行loop
  641. :return:
  642. """
  643. if self.loop_thread is None:
  644. self.loop_thread = Thread(target=self.loop, name='Script_loop')
  645. self.loop_thread.start()
  646. if __name__ == "__main__":
  647. ensure_ocr_server_started()
  648. script = Script("oas1")
  649. script.loop()