script.py 17 KB

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