Skip to content

Commit

Permalink
package change and func call timeout error handle method
Browse files Browse the repository at this point in the history
  • Loading branch information
pur1fying committed Dec 29, 2024
1 parent e132dbc commit 35bbdc7
Show file tree
Hide file tree
Showing 20 changed files with 134 additions and 49 deletions.
79 changes: 69 additions & 10 deletions core/Baas_thread.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import copy
from datetime import datetime
import cv2
from core.exception import ScriptError, RequestHumanTakeOver
from core.exception import ScriptError, RequestHumanTakeOver, FunctionCallTimeout, PackageIncorrect
from core.notification import notify, toast
from core.scheduler import Scheduler
from core import position, picture
Expand Down Expand Up @@ -431,7 +431,8 @@ def update_create_priority(self):
cfg_key_name = 'createPriority_phase' + str(phase)
current_priority = self.config[cfg_key_name]
res = []
default_priority = self.static_config['create_default_priority'][self.config_set.server_mode]["phase" + str(phase)]
default_priority = self.static_config['create_default_priority'][self.config_set.server_mode][
"phase" + str(phase)]
for i in range(0, len(current_priority)):
if current_priority[i] in default_priority:
res.append(current_priority[i])
Expand All @@ -442,13 +443,71 @@ def update_create_priority(self):
self.config_set.set(cfg_key_name, res)

def solve(self, activity) -> bool:
try:
return func_dict[activity](self)
except Exception as e:
if self.flag_run:
self.logger.error(e.__str__())
threading.Thread(target=self.simple_error, args=(e.__str__(),)).start()
return False
for i in range(0, 3):
if i != 0:
self.logger.info("Retry Task " + activity + " " + str(i))
try:
return func_dict[activity](self)
except FunctionCallTimeout:
if not self.deal_with_func_call_timeout():
threading.Thread(target=self.simple_error, args=("Failed to Restart Game",)).start()
return False
except PackageIncorrect as e:
pkg = e.message
if not self.deal_with_package_incorrect(pkg):
threading.Thread(target=self.simple_error, args=("Failed to Restart Game",)).start()
return False
except Exception as e:
if self.flag_run:
self.logger.error(e.__str__())
threading.Thread(target=self.simple_error, args=(e.__str__(),)).start()
return False

def deal_with_package_incorrect(self, curr_pkg):
"""
1. no exception
"""
self.logger.info("Handle package incorrect")
self.logger.warning("Package incorrect")
self.logger.warning("Expected: " + self.package_name)
self.logger.warning("Get : " + curr_pkg)
self.logger.warning("Restarting game")
for i in range(0, 3):
if i != 0: # skip first time check
package = self.connection.get_current_package()
if package == self.package_name:
self.logger.info("current app is target app, close the game and call task restart")
self.connection.close_current_app(package)
try:
func_dict['restart'](self)
return True
except RequestHumanTakeOver:
return False
except Exception as e:
pass
return False

def deal_with_func_call_timeout(self):
"""
deal with co_detect function time out with following logic
1.current app is target app --> close the game and call task restart
2.current app is not target app --> call task restart
3.this func will not raise exception
"""
self.logger.info("Handle function call timeout")
package = self.connection.get_current_package()
if package != self.package_name:
self.deal_with_package_incorrect(package)
else:
for i in range(0, 3):
self.logger.info("current app is target app, close the game and call task restart")
self.connection.close_current_app(package)
try:
func_dict['restart'](self)
return True
except Exception as e:
pass
return False

def simple_error(self, info: str):
push(self.logger, self.config, info)
Expand Down Expand Up @@ -545,7 +604,7 @@ def quick_method_to_main_page(self, skip_first_screenshot=False):
# "fighting_feature": (1226, 51)
}
picture.co_detect(self, "main_page", rgb_possibles, None, img_possibles, skip_first_screenshot,
tentitive_click=True)
tentative_click=True)

def init_image_resource(self):
return position.init_image_data(self)
Expand Down
19 changes: 14 additions & 5 deletions core/device/connection.py
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,6 @@ def revise_serial(serial):
serial = serial.replace('auto127.0.0.1', '127.0.0.1').replace('autoemulator', 'emulator')
return str(serial)


@staticmethod
def serial_port(serial):
try:
Expand Down Expand Up @@ -116,8 +115,6 @@ def detect_device(self):
self.logger.error("Multiple devices detected, please specify the device serial.")
raise RequestHumanTakeOver("Multiple devices detected.")



if self.is_mumu12_family():
matched = False
for device in available:
Expand All @@ -129,11 +126,11 @@ def detect_device(self):
port = self.serial_port(self.serial)
for device in available:
if abs(self.serial_port(device) - port) <= 2:
self.logger.info("MuMu12 device serial switched from [ " + self.serial + " ] to [ " + device + " ]")
self.logger.info(
"MuMu12 device serial switched from [ " + self.serial + " ] to [ " + device + " ]")
self.set_serial(device)
break


def set_activity(self):
pass

Expand Down Expand Up @@ -261,6 +258,11 @@ def get_server(self):
def get_activity_name(self):
return self.activity

def get_current_package(self):
self.logger.info("Get Current Package")
d = adb.device(self.serial)
return d.app_current().package

def adb_connect(self):
for device in self.list_devices():
if device.state == 'offline':
Expand Down Expand Up @@ -303,3 +305,10 @@ def adb_connect(self):

def get_serial(self):
return self.serial

def close_current_app(self, pkg_name=None):
self.logger.info("Close Current App")
d = adb.device(self.serial)
if pkg_name is None:
pkg_name = self.get_current_package()
d.app_stop(pkg_name)
13 changes: 13 additions & 0 deletions core/exception.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,18 @@ class RequestHumanTakeOver(Exception):
1. flag_run = false (click stop button)
2. unable to connect to emulator
"""

def __init__(self, message="Request Human Take Over"):
self.message = message
super().__init__(self.message)


class PackageIncorrect(Exception):
def __init__(self, message="Package Incorrect"):
self.message = message
super().__init__(self.message)


class ScriptError(Exception):
def __init__(self, message=None, context=None):
traceback.print_exc()
Expand All @@ -38,3 +45,9 @@ def log_into_file(self):

def __str__(self):
return self.message


class FunctionCallTimeout(Exception):
def __init__(self, message="Function Call Timeout"):
self.message = message
super().__init__(self.message)
12 changes: 1 addition & 11 deletions core/image.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,7 @@


def screenshot_cut(self, area):
return self.latest_img_array[int(area[1] * self.ratio):int(area[3] * self.ratio),
int(area[0] * self.ratio):int(area[2] * self.ratio), :]
return self.latest_img_array[int(area[1] * self.ratio):int(area[3] * self.ratio),int(area[0] * self.ratio):int(area[2] * self.ratio), :]


def img_cut(img, area):
Expand Down Expand Up @@ -74,15 +73,6 @@ def getImageByName(self, name):
return position.image_dic[self.server][name]


def click_to_disappear(self, img_possible, x, y):
msg = 'find : ' + img_possible
while self.flag_run and compare_image(self, img_possible, need_log=False):
self.logger.info(msg)
self.click(x, y, wait_over=True)
self.update_screenshot_array()
return True


def search_in_area(self, name, area=(0, 0, 1280, 720), threshold=0.8, rgb_diff=20, ret_max_val=False):
# search image "name" in area, return upper left point of template image if found, else return False
if name not in position.image_dic[self.server]:
Expand Down
28 changes: 21 additions & 7 deletions core/picture.py
Original file line number Diff line number Diff line change
@@ -1,17 +1,29 @@
import time
from core import color, image
from module.main_story import change_acc_auto
from core.exception import RequestHumanTakeOver
from core.exception import RequestHumanTakeOver, FunctionCallTimeout, PackageIncorrect


def co_detect(self, rgb_ends=None, rgb_possibles=None, img_ends=None, img_possibles=None, skip_first_screenshot=False,
tentitive_click=False, tentitivex=1238, tentitivey=45, max_fail_cnt=10, rgb_pop_ups=None,
img_pop_ups=None):
tentative_click=False, tentative_x=1238, tentative_y=45, max_fail_cnt=10, rgb_pop_ups=None,
img_pop_ups=None, time_out=600, check_pkg_interval=20):
fail_cnt = 0
self.last_click_time = 0
self.last_click_position = (0, 0)
self.last_click_name = ""
start_time = time.time()
feature_last_appear_time = start_time
last_check_pkg_time = start_time
while self.flag_run:
t_start_this_round = time.time()
if t_start_this_round - start_time > time_out:
raise FunctionCallTimeout("Co_detect function timeout reached.")
if t_start_this_round - feature_last_appear_time > check_pkg_interval and t_start_this_round - last_check_pkg_time > check_pkg_interval:
last_check_pkg_time = t_start_this_round
self.logger.info("Check package.")
pkg = self.connection.get_current_package()
if pkg != self.package_name:
raise PackageIncorrect(pkg)
if skip_first_screenshot:
skip_first_screenshot = False
else:
Expand Down Expand Up @@ -60,13 +72,14 @@ def co_detect(self, rgb_ends=None, rgb_possibles=None, img_ends=None, img_possib
else:
fail_cnt = 0
f = 1
feature_last_appear_time = time.time()
if time.time() - self.last_click_time <= 2 and self.last_click_position[0] == click[0] and \
self.last_click_position[1] == click[1] and self.last_click_name == position:
break
self.logger.info("find : " + position)
if click[0] >= 0 and click[1] >= 0:
self.last_click_time = feature_last_appear_time
self.click(click[0], click[1])
self.last_click_time = time.time()
self.last_click_position = (click[0], click[1])
self.last_click_name = position
break
Expand All @@ -84,24 +97,25 @@ def co_detect(self, rgb_ends=None, rgb_possibles=None, img_ends=None, img_possib
if image.compare_image(self, position, False, threshold, rgb_diff):
fail_cnt = 0
f = 1
feature_last_appear_time = time.time()
if time.time() - self.last_click_time <= 2 and self.last_click_position[0] == click[0] and \
self.last_click_position[1] == click[1] and self.last_click_name == position:
break
self.logger.info("find " + position)
if click[0] >= 0 and click[1] >= 0:
self.last_click_time = feature_last_appear_time
self.click(click[0], click[1])
self.last_click_time = time.time()
self.last_click_position = (click[0], click[1])
self.last_click_name = position
break
if f == 1:
continue
if not deal_with_pop_ups(self, rgb_pop_ups, img_pop_ups):
if tentitive_click:
if tentative_click:
fail_cnt += 1
if fail_cnt > max_fail_cnt:
self.logger.info("tentative clicks")
self.click(tentitivex, tentitivey)
self.click(tentative_x, tentative_y)
time.sleep(self.screenshot_interval)
fail_cnt = 0
if not self.flag_run:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -435,7 +435,7 @@ def to_set_exchange_times_menu(self, skip_first_screenshot=False):
def continue_exchange(self):
img_possibles = {"activity_continue-exchange": (931, 600)}
img_ends = "activity_continue-exchange-grey"
picture.co_detect(self, None, None, img_ends, img_possibles, True, tentitive_click=True, max_fail_cnt=5)
picture.co_detect(self, None, None, img_ends, img_possibles, True, tentative_click=True, max_fail_cnt=5)


def get_exchange_assets(self):
Expand Down
2 changes: 1 addition & 1 deletion module/activities/AbydosResortRestorationCommittee.py
Original file line number Diff line number Diff line change
Expand Up @@ -443,7 +443,7 @@ def to_set_exchange_times_menu(self, skip_first_screenshot=False):
def continue_exchange(self):
img_possibles = {"activity_continue-exchange": (931, 600)}
img_ends = "activity_continue-exchange-grey"
picture.co_detect(self, None, None, img_ends, img_possibles, True, tentitive_click=True, max_fail_cnt=5)
picture.co_detect(self, None, None, img_ends, img_possibles, True, tentative_click=True, max_fail_cnt=5)


def get_exchange_assets(self):
Expand Down
2 changes: 1 addition & 1 deletion module/activities/GetSetGoKivotosHaloGames.py
Original file line number Diff line number Diff line change
Expand Up @@ -435,7 +435,7 @@ def to_set_exchange_times_menu(self, skip_first_screenshot=False):
def continue_exchange(self):
img_possibles = {"activity_continue-exchange": (931, 600)}
img_ends = "activity_continue-exchange-grey"
picture.co_detect(self, None, None, img_ends, img_possibles, True, tentitive_click=True, max_fail_cnt=5)
picture.co_detect(self, None, None, img_ends, img_possibles, True, tentative_click=True, max_fail_cnt=5)


def get_exchange_assets(self):
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -448,7 +448,7 @@ def to_set_exchange_times_menu(self, skip_first_screenshot=False):
def continue_exchange(self):
img_possibles = {"activity_continue-exchange": (931, 600)}
img_ends = "activity_continue-exchange-grey"
picture.co_detect(self, None, None, img_ends, img_possibles, True, tentitive_click=True, max_fail_cnt=5)
picture.co_detect(self, None, None, img_ends, img_possibles, True, tentative_click=True, max_fail_cnt=5)


def get_exchange_assets(self):
Expand Down
2 changes: 1 addition & 1 deletion module/activities/PlayHideAndSeekAtImaginationLand.py
Original file line number Diff line number Diff line change
Expand Up @@ -440,7 +440,7 @@ def to_set_exchange_times_menu(self, skip_first_screenshot=False):
def continue_exchange(self):
img_possibles = {"activity_continue-exchange": (931, 600)}
img_ends = "activity_continue-exchange-grey"
picture.co_detect(self, None, None, img_ends, img_possibles, True, tentitive_click=True, max_fail_cnt=5)
picture.co_detect(self, None, None, img_ends, img_possibles, True, tentative_click=True, max_fail_cnt=5)


def get_exchange_assets(self):
Expand Down
2 changes: 1 addition & 1 deletion module/activities/PresidentHinasSummerVacation.py
Original file line number Diff line number Diff line change
Expand Up @@ -437,7 +437,7 @@ def to_set_exchange_times_menu(self, skip_first_screenshot=False):
def continue_exchange(self):
img_possibles = {"activity_continue-exchange": (931, 600)}
img_ends = "activity_continue-exchange-grey"
picture.co_detect(self, None, None, img_ends, img_possibles, True, tentitive_click=True, max_fail_cnt=5)
picture.co_detect(self, None, None, img_ends, img_possibles, True, tentative_click=True, max_fail_cnt=5)


def get_exchange_assets(self):
Expand Down
2 changes: 1 addition & 1 deletion module/activities/SummerSkysWishes.py
Original file line number Diff line number Diff line change
Expand Up @@ -446,7 +446,7 @@ def to_set_exchange_times_menu(self, skip_first_screenshot=False):
def continue_exchange(self):
img_possibles = {"activity_continue-exchange": (931, 600)}
img_ends = "activity_continue-exchange-grey"
picture.co_detect(self, None, None, img_ends, img_possibles, True, tentitive_click=True, max_fail_cnt=5)
picture.co_detect(self, None, None, img_ends, img_possibles, True, tentative_click=True, max_fail_cnt=5)


def get_exchange_assets(self):
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -448,7 +448,7 @@ def to_set_exchange_times_menu(self, skip_first_screenshot=False):
def continue_exchange(self):
img_possibles = {"activity_continue-exchange": (931, 600)}
img_ends = "activity_continue-exchange-grey"
picture.co_detect(self, None, None, img_ends, img_possibles, True, tentitive_click=True, max_fail_cnt=5)
picture.co_detect(self, None, None, img_ends, img_possibles, True, tentative_click=True, max_fail_cnt=5)


def get_exchange_assets(self):
Expand Down
2 changes: 1 addition & 1 deletion module/activities/TheCathedralsMerryChristmas.py
Original file line number Diff line number Diff line change
Expand Up @@ -435,7 +435,7 @@ def to_set_exchange_times_menu(self, skip_first_screenshot=False):
def continue_exchange(self):
img_possibles = {"activity_continue-exchange": (931, 600)}
img_ends = "activity_continue-exchange-grey"
picture.co_detect(self, None, None, img_ends, img_possibles, True, tentitive_click=True, max_fail_cnt=5)
picture.co_detect(self, None, None, img_ends, img_possibles, True, tentative_click=True, max_fail_cnt=5)


def get_exchange_assets(self):
Expand Down
2 changes: 1 addition & 1 deletion module/activities/bunnyChaserOnTheShip2.py
Original file line number Diff line number Diff line change
Expand Up @@ -428,7 +428,7 @@ def to_set_exchange_times_menu(self, skip_first_screenshot=False):
def continue_exchange(self):
img_possibles = {"activity_continue-exchange": (931, 600)}
img_ends = "activity_continue-exchange-grey"
picture.co_detect(self, None, None, img_ends, img_possibles, True, tentitive_click=True, max_fail_cnt=5)
picture.co_detect(self, None, None, img_ends, img_possibles, True, tentative_click=True, max_fail_cnt=5)


def get_exchange_assets(self):
Expand Down
2 changes: 1 addition & 1 deletion module/activities/no_227_kinosaki_spa.py
Original file line number Diff line number Diff line change
Expand Up @@ -434,7 +434,7 @@ def to_set_exchange_times_menu(self, skip_first_screenshot=False):
def continue_exchange(self):
img_possibles = {"activity_continue-exchange": (931, 600)}
img_ends = "activity_continue-exchange-grey"
picture.co_detect(self, None, None, img_ends, img_possibles, True, tentitive_click=True, max_fail_cnt=5)
picture.co_detect(self, None, None, img_ends, img_possibles, True, tentative_click=True, max_fail_cnt=5)


def get_exchange_assets(self):
Expand Down
Loading

0 comments on commit 35bbdc7

Please sign in to comment.