script.py 18 KB

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