script.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491
  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. # 验证参数
  145. task = convert_to_underscore(task)
  146. group = convert_to_underscore(group)
  147. argument = convert_to_underscore(argument)
  148. # pandtic验证
  149. if isinstance(value, str):
  150. if len(value) == 8:
  151. try:
  152. value = datetime.strptime(value, '%H:%M:%S').time()
  153. except ValueError:
  154. pass
  155. path = f'{task}.{group}.{argument}'
  156. task_object = getattr(self.config.model, task, None)
  157. group_object = getattr(task_object, group, None)
  158. argument_object = getattr(group_object, argument, None)
  159. if argument_object is None:
  160. logger.error(f'Set arg {task}.{group}.{argument}.{value} failed')
  161. return False
  162. try:
  163. setattr(group_object, argument, value)
  164. argument_object = getattr(group_object, argument, None)
  165. logger.info(f'Set arg {task}.{group}.{argument}.{argument_object}')
  166. self.config.save() # 我是没有想到什么方法可以使得属性改变自动保存的
  167. return True
  168. except ValidationError as e:
  169. logger.error(e)
  170. return False
  171. @zerorpc.stream
  172. def gui_mirror_image(self):
  173. """
  174. 获取给gui显示的镜像
  175. :return: cv2的对象将 numpy 数组转换为字节串。接下来MsgPack 进行序列化发送方将图像数据转换为字节串
  176. """
  177. # return msgpack.packb(cv2.imencode('.jpg', self.device.screenshot())[1].tobytes())
  178. img = cv2.cvtColor(self.device.screenshot(), cv2.COLOR_RGB2BGR)
  179. self.device.stuck_record_clear()
  180. ret, buffer = cv2.imencode('.jpg', img)
  181. yield buffer.tobytes()
  182. def _gui_update_tasks(self) -> None:
  183. """
  184. 获取更新任务后 pending waiting 的任务 和 当前的任务的数据。打包给gui显示
  185. :return:
  186. """
  187. data = {}
  188. pending = []
  189. waiting = []
  190. task = {}
  191. if self.config.task is not None and self.config.task.next_run < datetime.now():
  192. task["name"] = self.config.task.command
  193. task["next_run"] = str(self.config.task.next_run)
  194. data["task"] = task
  195. for p in self.config.pending_task[1:]:
  196. item = {"name": p.command, "next_run": str(p.next_run)}
  197. pending.append(item)
  198. for w in self.config.waiting_task:
  199. item = {"name": w.command, "next_run": str(w.next_run)}
  200. waiting.append(item)
  201. data["pending"] = pending
  202. data["waiting"] = waiting
  203. if self.gui_update_task is not None:
  204. self.gui_update_task(data)
  205. def _gui_set_status(self, status: str) -> None:
  206. """
  207. 设置给gui显示的状态
  208. :param status: 可以在gui中显示的状态 有 "Init", "Empty"(不显示), "Run"(运行中), "Error", "Free"(空闲)
  209. :return:
  210. """
  211. data = {"status": status}
  212. if self.gui_update_task is not None:
  213. self.gui_update_task(data)
  214. def gui_task_list(self) -> str:
  215. """
  216. 获取给gui显示的任务列表
  217. :return:
  218. """
  219. result = {}
  220. for key, value in self.config.model.dict().items():
  221. if isinstance(value, str):
  222. continue
  223. if key == "restart":
  224. continue
  225. if "scheduler" not in value:
  226. continue
  227. scheduler = value["scheduler"]
  228. item = {"enable": scheduler["enable"],
  229. "next_run": str(scheduler["next_run"])}
  230. key = self.config.model.type(key)
  231. result[key] = item
  232. return json.dumps(result)
  233. def wait_until(self, future):
  234. """
  235. Wait until a specific time.
  236. Args:
  237. future (datetime):
  238. Returns:
  239. bool: True if wait finished, False if config changed.
  240. """
  241. future = future + timedelta(seconds=1)
  242. self.config.start_watching()
  243. while 1:
  244. if datetime.now() > future:
  245. return True
  246. # if self.stop_event is not None:
  247. # if self.stop_event.is_set():
  248. # logger.info("Update event detected")
  249. # logger.info(f"[{self.config_name}] exited. Reason: Update")
  250. # exit(0)
  251. time.sleep(5)
  252. if self.config.should_reload():
  253. return False
  254. def get_next_task(self) -> str:
  255. """
  256. 获取下一个任务的名字, 大驼峰。
  257. :return:
  258. """
  259. while 1:
  260. task = self.config.get_next()
  261. self.config.task = task
  262. self._gui_update_tasks()
  263. # from module.base.resource import release_resources
  264. # if self.config.task.command != 'Alas':
  265. # release_resources(next_task=task.command)
  266. if task.next_run > datetime.now():
  267. logger.info(f'Wait until {task.next_run} for task `{task.command}`')
  268. # self.is_first_task = False
  269. method = self.config.script.optimization.when_task_queue_empty
  270. if method == 'close_game':
  271. logger.info('Close game during wait')
  272. self.device.app_stop()
  273. self.device.release_during_wait()
  274. if not self.wait_until(task.next_run):
  275. del_cached_property(self, 'config')
  276. continue
  277. self.run('Restart')
  278. elif method == 'goto_main':
  279. logger.info('Goto main page during wait')
  280. self.run('GotoMain')
  281. self.device.release_during_wait()
  282. if not self.wait_until(task.next_run):
  283. del_cached_property(self, 'config')
  284. continue
  285. else:
  286. logger.warning(f'Invalid Optimization_WhenTaskQueueEmpty: {method}, fallback to stay_there')
  287. self.device.release_during_wait()
  288. if not self.wait_until(task.next_run):
  289. del_cached_property(self, 'config')
  290. continue
  291. break
  292. return task.command
  293. def run(self, command: str) -> bool:
  294. """
  295. :param command: 大写驼峰命名的任务名字
  296. :return:
  297. """
  298. if command == 'start' or command == 'goto_main':
  299. logger.error(f'Invalid command `{command}`')
  300. try:
  301. self.device.screenshot()
  302. module_name = 'script_task'
  303. module_path = str(Path.cwd() / 'tasks' / command / (module_name+'.py'))
  304. logger.info(f'module_path: {module_path}, module_name: {module_name}')
  305. task_module = load_module(module_name, module_path)
  306. task_module.ScriptTask(config=self.config, device=self.device).run()
  307. except TaskEnd:
  308. return True
  309. except GameNotRunningError as e:
  310. logger.warning(e)
  311. self.config.task_call('Restart')
  312. return True
  313. except (GameStuckError, GameTooManyClickError) as e:
  314. logger.error(e)
  315. self.save_error_log()
  316. logger.warning(f'Game stuck, {self.device.package} will be restarted in 10 seconds')
  317. logger.warning('If you are playing by hand, please stop Alas')
  318. self.config.notifier.push(title='crashed', content=f"<{self.config_name}> GameStuckError or GameTooManyClickError")
  319. self.config.task_call('Restart')
  320. self.device.sleep(10)
  321. return False
  322. except GameBugError as e:
  323. logger.warning(e)
  324. self.save_error_log()
  325. logger.warning('An error has occurred in Azur Lane game client, Alas is unable to handle')
  326. logger.warning(f'Restarting {self.device.package} to fix it')
  327. self.config.task_call('Restart')
  328. self.device.sleep(10)
  329. return False
  330. except GamePageUnknownError:
  331. logger.info('Game server may be under maintenance or network may be broken, check server status now')
  332. # 这个还不重要 留着坑填
  333. logger.critical('Game page unknown')
  334. self.save_error_log()
  335. self.config.notifier.push(title='crashed', content=f"<{self.config_name}> GamePageUnknownError")
  336. exit(1)
  337. return False
  338. except ScriptError as e:
  339. logger.critical(e)
  340. logger.critical('This is likely to be a mistake of developers, but sometimes just random issues')
  341. self.config.notifier.push(title='crashed', content=f"<{self.config_name}> ScriptError")
  342. exit(1)
  343. except RequestHumanTakeover:
  344. logger.critical('Request human takeover')
  345. self.config.notifier.push(title='crashed', content=f"<{self.config_name}> RequestHumanTakeover")
  346. exit(1)
  347. except Exception as e:
  348. logger.exception(e)
  349. self.save_error_log()
  350. self.config.notifier.push(title='crashed', content=f"<{self.config_name}> Exception occured")
  351. exit(1)
  352. def loop(self):
  353. """
  354. Main loop of scheduler.
  355. :return:
  356. """
  357. logger.set_file_logger(self.config_name)
  358. logger.info(f'Start scheduler loop: {self.config_name}')
  359. while 1:
  360. # Check update event from GUI
  361. # if self.stop_event is not None:
  362. # if self.stop_event.is_set():
  363. # logger.info("Update event detected")
  364. # logger.info(f"Alas [{self.config_name}] exited.")
  365. # break
  366. # Check game server maintenance
  367. # self.checker.wait_until_available()
  368. # if self.checker.is_recovered():
  369. # # There is an accidental bug hard to reproduce
  370. # # Sometimes, config won't be updated due to blocking
  371. # # even though it has been changed
  372. # # So update it once recovered
  373. # del_cached_property(self, 'config')
  374. # logger.info('Server or network is recovered. Restart game client')
  375. # self.config.task_call('Restart')
  376. # Get task
  377. task = self.get_next_task()
  378. # 更新 gui的任务
  379. # Init device and change server
  380. _ = self.device
  381. # Skip first restart
  382. if self.is_first_task and task == 'Restart':
  383. logger.info('Skip task `Restart` at scheduler start')
  384. self.config.task_delay(task='Restart', success=True, server=True)
  385. del_cached_property(self, 'config')
  386. continue
  387. # Run
  388. logger.info(f'Scheduler: Start task `{task}`')
  389. self.device.stuck_record_clear()
  390. self.device.click_record_clear()
  391. logger.hr(task, level=0)
  392. success = self.run(inflection.camelize(task))
  393. logger.info(f'Scheduler: End task `{task}`')
  394. self.is_first_task = False
  395. # Check failures
  396. # failed = deep_get(self.failure_record, keys=task, default=0)
  397. failed = self.failure_record[task] if task in self.failure_record else 0
  398. failed = 0 if success else failed + 1
  399. # deep_set(self.failure_record, keys=task, value=failed)
  400. self.failure_record[task] = failed
  401. if failed >= 3:
  402. logger.critical(f"Task `{task}` failed 3 or more times.")
  403. logger.critical("Possible reason #1: You haven't used it correctly. "
  404. "Please read the help text of the options.")
  405. logger.critical("Possible reason #2: There is a problem with this task. "
  406. "Please contact developers or try to fix it yourself.")
  407. logger.critical('Request human takeover')
  408. exit(1)
  409. if success:
  410. del_cached_property(self, 'config')
  411. continue
  412. elif self.config.script.error.handle_error:
  413. # self.config.task_delay(success=False)
  414. del_cached_property(self, 'config')
  415. # self.checker.check_now()
  416. continue
  417. else:
  418. break
  419. def start_loop(self) -> None:
  420. """
  421. 创建一个线程,运行loop
  422. :return:
  423. """
  424. if self.loop_thread is None:
  425. self.loop_thread = Thread(target=self.loop, name='Script_loop')
  426. self.loop_thread.start()
  427. if __name__ == "__main__":
  428. script = Script("oas1")
  429. print(script.gui_task_list())
  430. print(script.config.gui_menu)