script.py 18 KB

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