script.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449
  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. from typing import Callable
  15. from datetime import datetime, timedelta
  16. from pathlib import Path
  17. from cached_property import cached_property
  18. from pydantic import BaseModel, ValidationError
  19. from PySide6.QtGui import QImage
  20. from threading import Thread
  21. from module.config.utils import convert_to_underscore
  22. from module.config.config import Config
  23. from module.device.device import Device
  24. from module.base.utils import load_module
  25. from module.base.decorator import del_cached_property
  26. from module.logger import logger
  27. from module.exception import *
  28. class Script:
  29. def __init__(self, config_name: str ='oas') -> None:
  30. logger.hr('Start', level=0)
  31. self.server = None
  32. self.gui_update_task: Callable = None # 回调函数, gui进程注册当每次config更新任务的时候更新gui的信息
  33. self.config_name = config_name
  34. # Skip first restart
  35. self.is_first_task = True
  36. # Failure count of tasks
  37. # Key: str, task name, value: int, failure count
  38. self.failure_record = {}
  39. # 运行loop的线程
  40. self.loop_thread: Thread = None
  41. @cached_property
  42. def config(self) -> "Config":
  43. try:
  44. from module.config.config import Config
  45. config = Config(config_name=self.config_name)
  46. return config
  47. except RequestHumanTakeover:
  48. logger.critical('Request human takeover')
  49. exit(1)
  50. except Exception as e:
  51. logger.exception(e)
  52. exit(1)
  53. @cached_property
  54. def device(self) -> "Device":
  55. try:
  56. from module.device.device import Device
  57. device = Device(config=self.config)
  58. return device
  59. except RequestHumanTakeover:
  60. logger.critical('Request human takeover')
  61. exit(1)
  62. except Exception as e:
  63. logger.exception(e)
  64. exit(1)
  65. @cached_property
  66. def checker(self):
  67. """
  68. 占位函数,在alas中是检查服务器是否正常的
  69. :return:
  70. """
  71. return None
  72. def save_error_log(self):
  73. """
  74. Save last 60 screenshots in ./log/error/<timestamp>
  75. Save logs to ./log/error/<timestamp>/log.txt
  76. """
  77. from module.base.utils import save_image
  78. from module.handler.sensitive_info import (handle_sensitive_image,
  79. handle_sensitive_logs)
  80. if self.config.script.error.save_error:
  81. if not os.path.exists('./log/error'):
  82. os.mkdir('./log/error')
  83. folder = f'./log/error/{int(time.time() * 1000)}'
  84. logger.warning(f'Saving error: {folder}')
  85. os.mkdir(folder)
  86. for data in self.device.screenshot_deque:
  87. image_time = datetime.strftime(data['time'], '%Y-%m-%d_%H-%M-%S-%f')
  88. image = handle_sensitive_image(data['image'])
  89. save_image(image, f'{folder}/{image_time}.png')
  90. with open(logger.log_file, 'r', encoding='utf-8') as f:
  91. lines = f.readlines()
  92. start = 0
  93. for index, line in enumerate(lines):
  94. line = line.strip(' \r\t\n')
  95. if re.match('^═{15,}$', line):
  96. start = index
  97. lines = lines[start - 2:]
  98. lines = handle_sensitive_logs(lines)
  99. with open(f'{folder}/log.txt', 'w', encoding='utf-8') as f:
  100. f.writelines(lines)
  101. def init_server(self, port: int) -> int:
  102. """
  103. 初始化zerorpc服务,返回端口号
  104. :return:
  105. """
  106. self.server = zerorpc.Server(self)
  107. try:
  108. self.server.bind(f'tcp://127.0.0.1:{port}')
  109. return port
  110. except zmq.error.ZMQError:
  111. logger.error(f"Ocr server cannot bind on port {port}")
  112. return None
  113. def run_server(self) -> None:
  114. """
  115. 启动zerorpc服务
  116. :return:
  117. """
  118. self.server.run()
  119. def gui_args(self, task: str) -> str:
  120. """
  121. 获取给gui显示的参数
  122. :return:
  123. """
  124. return self.config.gui_args(task=task)
  125. def gui_menu(self) -> str:
  126. """
  127. 获取给gui显示的菜单
  128. :return:
  129. """
  130. return self.config.gui_menu
  131. def gui_task(self, task: str) -> str:
  132. """
  133. 获取给gui显示的任务 的参数的具体值
  134. :return:
  135. """
  136. return self.config.model.gui_task(task=task)
  137. def gui_set_task(self, task: str, group: str, argument: str, value) -> bool:
  138. """
  139. 设置给gui显示的任务 的参数的具体值
  140. :return:
  141. """
  142. task = convert_to_underscore(task)
  143. group = convert_to_underscore(group)
  144. argument = convert_to_underscore(argument)
  145. path = f'{task}.{group}.{argument}'
  146. task_object = getattr(self.config.model, task, None)
  147. group_object = getattr(task_object, group, None)
  148. argument_object = getattr(group_object, argument, None)
  149. if argument_object is None:
  150. logger.error(f'gui_set_task {task}.{group}.{argument}.{value} failed')
  151. return False
  152. try:
  153. setattr(group_object, argument, value)
  154. argument_object = getattr(group_object, argument, None)
  155. logger.info(f'gui_set_task {task}.{group}.{argument}.{argument_object}')
  156. self.config.save() # 我是没有想到什么方法可以使得属性改变自动保存的
  157. return True
  158. except ValidationError as e:
  159. logger.error(e)
  160. return False
  161. @zerorpc.stream
  162. def gui_mirror_image(self):
  163. """
  164. 获取给gui显示的镜像
  165. :return: cv2的对象将 numpy 数组转换为字节串。接下来MsgPack 进行序列化发送方将图像数据转换为字节串
  166. """
  167. # return msgpack.packb(cv2.imencode('.jpg', self.device.screenshot())[1].tobytes())
  168. img = cv2.cvtColor(self.device.screenshot(), cv2.COLOR_RGB2BGR)
  169. self.device.stuck_record_clear()
  170. ret, buffer = cv2.imencode('.jpg', img)
  171. yield buffer.tobytes()
  172. def _gui_update_tasks(self) -> None:
  173. """
  174. 获取更新任务后 pending waiting 的任务 和 当前的任务的数据。打包给gui显示
  175. :return:
  176. """
  177. data = {}
  178. pending = []
  179. waiting = []
  180. task = {}
  181. if self.config.task is not None and self.config.task.next_run < datetime.now():
  182. task["name"] = self.config.task.command
  183. task["next_run"] = str(self.config.task.next_run)
  184. data["task"] = task
  185. for p in self.config.pending_task[1:]:
  186. item = {"name": p.command, "next_run": str(p.next_run)}
  187. pending.append(item)
  188. for w in self.config.waiting_task:
  189. item = {"name": w.command, "next_run": str(w.next_run)}
  190. waiting.append(item)
  191. data["pending"] = pending
  192. data["waiting"] = waiting
  193. if self.gui_update_task is not None:
  194. self.gui_update_task(data)
  195. def _gui_set_status(self, status: str) -> None:
  196. """
  197. 设置给gui显示的状态
  198. :param status: 可以在gui中显示的状态 有 "Init", "Empty"(不显示), "Run"(运行中), "Error", "Free"(空闲)
  199. :return:
  200. """
  201. data = {"status": status}
  202. if self.gui_update_task is not None:
  203. self.gui_update_task(data)
  204. def wait_until(self, future):
  205. """
  206. Wait until a specific time.
  207. Args:
  208. future (datetime):
  209. Returns:
  210. bool: True if wait finished, False if config changed.
  211. """
  212. future = future + timedelta(seconds=1)
  213. self.config.start_watching()
  214. while 1:
  215. if datetime.now() > future:
  216. return True
  217. # if self.stop_event is not None:
  218. # if self.stop_event.is_set():
  219. # logger.info("Update event detected")
  220. # logger.info(f"[{self.config_name}] exited. Reason: Update")
  221. # exit(0)
  222. time.sleep(5)
  223. if self.config.should_reload():
  224. return False
  225. def get_next_task(self) -> str:
  226. """
  227. 获取下一个任务的名字, 大驼峰。
  228. :return:
  229. """
  230. while 1:
  231. task = self.config.get_next()
  232. self.config.task = task
  233. self._gui_update_tasks()
  234. # from module.base.resource import release_resources
  235. # if self.config.task.command != 'Alas':
  236. # release_resources(next_task=task.command)
  237. if task.next_run > datetime.now():
  238. logger.info(f'Wait until {task.next_run} for task `{task.command}`')
  239. # self.is_first_task = False
  240. method = self.config.script.optimization.when_task_queue_empty
  241. if method == 'close_game':
  242. logger.info('Close game during wait')
  243. self.device.app_stop()
  244. self.device.release_during_wait()
  245. if not self.wait_until(task.next_run):
  246. del_cached_property(self, 'config')
  247. continue
  248. self.run('start')
  249. elif method == 'goto_main':
  250. logger.info('Goto main page during wait')
  251. self.run('GotoMain')
  252. self.device.release_during_wait()
  253. if not self.wait_until(task.next_run):
  254. del_cached_property(self, 'config')
  255. continue
  256. else:
  257. logger.warning(f'Invalid Optimization_WhenTaskQueueEmpty: {method}, fallback to stay_there')
  258. self.device.release_during_wait()
  259. if not self.wait_until(task.next_run):
  260. del_cached_property(self, 'config')
  261. continue
  262. break
  263. return task.command
  264. def run(self, command: str) -> bool:
  265. """
  266. :param command: 大写驼峰命名的任务名字
  267. :return:
  268. """
  269. if command == 'start' or command == 'goto_main':
  270. logger.error(f'Invalid command `{command}`')
  271. try:
  272. self.device.screenshot()
  273. module_name = 'script_task'
  274. module_path = str(Path.cwd() / 'tasks' / command / (module_name+'.py'))
  275. logger.info(f'module_path: {module_path}, module_name: {module_name}')
  276. task_module = load_module(module_name, module_path)
  277. task_module.ScriptTask(config=self.config, device=self.device).run()
  278. except TaskEnd:
  279. return True
  280. except GameNotRunningError as e:
  281. logger.warning(e)
  282. self.config.task_call('Restart')
  283. return True
  284. except (GameStuckError, GameTooManyClickError) as e:
  285. logger.error(e)
  286. self.save_error_log()
  287. logger.warning(f'Game stuck, {self.device.package} will be restarted in 10 seconds')
  288. logger.warning('If you are playing by hand, please stop Alas')
  289. self.config.notifier.push(title='crashed', content=f"<{self.config_name}> GameStuckError or GameTooManyClickError")
  290. self.config.task_call('Restart')
  291. self.device.sleep(10)
  292. return False
  293. except GameBugError as e:
  294. logger.warning(e)
  295. self.save_error_log()
  296. logger.warning('An error has occurred in Azur Lane game client, Alas is unable to handle')
  297. logger.warning(f'Restarting {self.device.package} to fix it')
  298. self.config.task_call('Restart')
  299. self.device.sleep(10)
  300. return False
  301. except GamePageUnknownError:
  302. logger.info('Game server may be under maintenance or network may be broken, check server status now')
  303. # 这个还不重要 留着坑填
  304. logger.critical('Game page unknown')
  305. self.save_error_log()
  306. self.config.notifier.push(title='crashed', content=f"<{self.config_name}> GamePageUnknownError")
  307. exit(1)
  308. return False
  309. except ScriptError as e:
  310. logger.critical(e)
  311. logger.critical('This is likely to be a mistake of developers, but sometimes just random issues')
  312. self.config.notifier.push(title='crashed', content=f"<{self.config_name}> ScriptError")
  313. exit(1)
  314. except RequestHumanTakeover:
  315. logger.critical('Request human takeover')
  316. self.config.notifier.push(title='crashed', content=f"<{self.config_name}> RequestHumanTakeover")
  317. exit(1)
  318. except Exception as e:
  319. logger.exception(e)
  320. self.save_error_log()
  321. self.config.notifier.push(title='crashed', content=f"<{self.config_name}> Exception occured")
  322. exit(1)
  323. def loop(self):
  324. """
  325. Main loop of scheduler.
  326. :return:
  327. """
  328. logger.set_file_logger(self.config_name)
  329. logger.info(f'Start scheduler loop: {self.config_name}')
  330. while 1:
  331. # Check update event from GUI
  332. # if self.stop_event is not None:
  333. # if self.stop_event.is_set():
  334. # logger.info("Update event detected")
  335. # logger.info(f"Alas [{self.config_name}] exited.")
  336. # break
  337. # Check game server maintenance
  338. # self.checker.wait_until_available()
  339. # if self.checker.is_recovered():
  340. # # There is an accidental bug hard to reproduce
  341. # # Sometimes, config won't be updated due to blocking
  342. # # even though it has been changed
  343. # # So update it once recovered
  344. # del_cached_property(self, 'config')
  345. # logger.info('Server or network is recovered. Restart game client')
  346. # self.config.task_call('Restart')
  347. # Get task
  348. task = self.get_next_task()
  349. # 更新 gui的任务
  350. # Init device and change server
  351. _ = self.device
  352. # Skip first restart
  353. if self.is_first_task and task == 'Restart':
  354. logger.info('Skip task `Restart` at scheduler start')
  355. self.config.task_delay(task='Restart', success=True, server=True)
  356. del_cached_property(self, 'config')
  357. continue
  358. # Run
  359. logger.info(f'Scheduler: Start task `{task}`')
  360. self.device.stuck_record_clear()
  361. self.device.click_record_clear()
  362. logger.hr(task, level=0)
  363. success = self.run(inflection.camelize(task))
  364. logger.info(f'Scheduler: End task `{task}`')
  365. self.is_first_task = False
  366. # Check failures
  367. # failed = deep_get(self.failure_record, keys=task, default=0)
  368. failed = self.failure_record[task] if task in self.failure_record else 0
  369. failed = 0 if success else failed + 1
  370. # deep_set(self.failure_record, keys=task, value=failed)
  371. self.failure_record[task] = failed
  372. if failed >= 3:
  373. logger.critical(f"Task `{task}` failed 3 or more times.")
  374. logger.critical("Possible reason #1: You haven't used it correctly. "
  375. "Please read the help text of the options.")
  376. logger.critical("Possible reason #2: There is a problem with this task. "
  377. "Please contact developers or try to fix it yourself.")
  378. logger.critical('Request human takeover')
  379. exit(1)
  380. if success:
  381. del_cached_property(self, 'config')
  382. continue
  383. elif self.config.script.error.handle_error:
  384. # self.config.task_delay(success=False)
  385. del_cached_property(self, 'config')
  386. # self.checker.check_now()
  387. continue
  388. else:
  389. break
  390. def start_loop(self) -> None:
  391. """
  392. 创建一个线程,运行loop
  393. :return:
  394. """
  395. if self.loop_thread is None:
  396. self.loop_thread = Thread(target=self.loop, name='Script_loop')
  397. self.loop_thread.start()
  398. if __name__ == "__main__":
  399. script = Script("oas1")
  400. # print(script.get_next_task())
  401. # script.run("ActivityShikigami")
  402. script.run('AreaBoss')