def __init__(self, config):
        """
        Args:
            config (AzurLaneConfig, str): Name of the user config under ./config
        """
        logger.hr('Device')
        if isinstance(config, str):
            self.config = AzurLaneConfig(config, task=None)
        else:
            self.config = config

        self.serial = str(self.config.Emulator_Serial)
        if "bluestacks4-hyperv" in self.serial:
            self.serial = self.find_bluestacks4_hyperv(self.serial)
        if "bluestacks5-hyperv" in self.serial:
            self.serial = self.find_bluestacks5_hyperv(self.serial)
        if "127.0.0.1:58526" in self.serial:
            raise RequestHumanTakeover('Serial 127.0.0.1:58526 seems to be WSA, please use "wsa-0" or others to instead')
        if "wsa" in self.serial:
            self.serial = '127.0.0.1:58526'

        logger.attr('Adb_binary', self.adb_binary)

        # Monkey patch to custom adb
        adbutils.adb_path = lambda: self.adb_binary
        # Remove global proxies, or uiautomator2 will go through it
        for k in list(os.environ.keys()):
            if k.lower().endswith('_proxy'):
                del os.environ[k]

        self.adb_client = AdbClient('127.0.0.1', 5037)
        self.adb_connect(self.serial)

        self.adb = AdbDevice(self.adb_client, self.serial)
        logger.attr('Adb_device', self.adb)
Beispiel #2
0
 def __init__(self) -> None:
     super().__init__()
     # modified keys, return values of pin_wait_change()
     self.modified_config_queue = queue.Queue()
     # alas config name
     self.alas_name = ""
     self.alas_config = AzurLaneConfig("template")
 def __init__(self) -> None:
     super().__init__()
     # modified keys, return values of pin_wait_change()
     self.modified_config_queue = queue.Queue()
     # alas config name
     self.alas_name = ''
     self.alas_config = AzurLaneConfig('template')
     self.alas_logs = ScrollableCode()
Beispiel #4
0
 def config(self):
     try:
         config = AzurLaneConfig(config_name=self.config_name)
         return config
     except RequestHumanTakeover:
         logger.critical('Request human takeover')
         exit(1)
     except Exception as e:
         logger.exception(e)
         exit(1)
 def ui_alas(self, config_name: str) -> None:
     if config_name == self.alas_name:
         self.expand_menu()
         return
     self.init_aside(name=config_name)
     clear('content')
     self.alas_name = config_name
     self.alas = ProcessManager.get_manager(config_name)
     self.alas_config = AzurLaneConfig(config_name, '')
     self.state_switch.switch()
     self.alas_set_menu()
 def config(self):
     try:
         config = AzurLaneConfig(config_name=self.config_name)
         # Set server before loading any buttons.
         server.server = deep_get(config.data, keys='Alas.Emulator.Server', default='cn')
         return config
     except RequestHumanTakeover:
         logger.critical('Request human takeover')
         exit(1)
     except Exception as e:
         logger.exception(e)
         exit(1)
Beispiel #7
0
    def run_process(config_name,
                    func: str,
                    q: queue.Queue,
                    e: threading.Event = None) -> None:
        # Setup logger
        set_file_logger(name=config_name)
        set_func_logger(func=q.put)

        # Set server before loading any buttons.
        import module.config.server as server
        from module.config.config import AzurLaneConfig

        AzurLaneConfig.stop_event = e
        config = AzurLaneConfig(config_name=config_name)
        server.server = deep_get(config.data,
                                 keys="Alas.Emulator.Server",
                                 default="cn")
        try:
            # Run alas
            if func == "Alas":
                from alas import AzurLaneAutoScript

                if e is not None:
                    AzurLaneAutoScript.stop_event = e
                AzurLaneAutoScript(config_name=config_name).loop()
            elif func == "Daemon":
                from module.daemon.daemon import AzurLaneDaemon

                AzurLaneDaemon(config=config_name, task="Daemon").run()
            elif func == "OpsiDaemon":
                from module.daemon.os_daemon import AzurLaneDaemon

                AzurLaneDaemon(config=config_name, task="OpsiDaemon").run()
            elif func == "AzurLaneUncensored":
                from module.daemon.uncensored import AzurLaneUncensored

                AzurLaneUncensored(config=config_name,
                                   task="AzurLaneUncensored").run()
            elif func == "Benchmark":
                from module.daemon.benchmark import Benchmark

                Benchmark(config=config_name, task="Benchmark").run()
            elif func == "GameManager":
                from module.daemon.game_manager import GameManager

                GameManager(config=config_name, task="GameManager").run()
            else:
                logger.critical("No function matched")
            logger.info(f"[{config_name}] exited. Reason: Finish\n")
        except Exception as e:
            logger.exception(e)
Beispiel #8
0
    def run_process(config_name,
                    func: str,
                    q: queue.Queue,
                    e: threading.Event = None) -> None:
        # Setup logger
        qh = QueueHandler(q)
        formatter = logging.Formatter(
            fmt='%(asctime)s.%(msecs)03d | %(levelname)s | %(message)s',
            datefmt='%H:%M:%S')
        webconsole = logging.StreamHandler(stream=qh)
        webconsole.setFormatter(formatter)
        logger.addHandler(webconsole)

        # Set server before loading any buttons.
        import module.config.server as server
        from module.config.config import AzurLaneConfig
        AzurLaneConfig.stop_event = e
        config = AzurLaneConfig(config_name=config_name)
        server.server = deep_get(config.data,
                                 keys='Alas.Emulator.Server',
                                 default='cn')
        try:
            # Run alas
            if func == 'Alas':
                from alas import AzurLaneAutoScript
                if e is not None:
                    AzurLaneAutoScript.stop_event = e
                AzurLaneAutoScript(config_name=config_name).loop()
            elif func == 'Daemon':
                from module.daemon.daemon import AzurLaneDaemon
                AzurLaneDaemon(config=config_name, task='Daemon').run()
            elif func == 'OpsiDaemon':
                from module.daemon.os_daemon import AzurLaneDaemon
                AzurLaneDaemon(config=config_name, task='OpsiDaemon').run()
            elif func == 'AzurLaneUncensored':
                from module.daemon.uncensored import AzurLaneUncensored
                AzurLaneUncensored(config=config_name,
                                   task='AzurLaneUncensored').run()
            elif func == 'Benchmark':
                from module.daemon.benchmark import Benchmark
                Benchmark(config=config_name, task='Benchmark').run()
            elif func == 'GameManager':
                from module.daemon.game_manager import GameManager
                GameManager(config=config_name, task='GameManager').run()
            else:
                logger.critical("No function matched")
            logger.info(f"[{config_name}] exited. Reason: Finish")
        except Exception as e:
            logger.exception(e)
Beispiel #9
0
 def __init__(self, config, device=None, task=None):
     """
     Args:
         config (AzurLaneConfig, str): Name of the user config under ./config
         device (Device): To reuse a device. If None, create a new Device object.
         task (str): Bind a task only for dev purpose. Usually to be None for auto task scheduling.
     """
     if isinstance(config, str):
         self.config = AzurLaneConfig(config, task=task)
     else:
         self.config = config
     if device is not None:
         self.device = device
     else:
         self.device = Device(config=self.config)
     self.interval_timer = {}
Beispiel #10
0
    def __init__(self, config, device=None):
        """
        Args:
            config (AzurLaneConfig, str):
            device (Device):
        """
        if isinstance(config, str):
            self.config = AzurLaneConfig(config)
        else:
            self.config = config
        if device is not None:
            self.device = device
        else:
            self.device = Device(config=self.config)

        self.interval_timer = {}
    def __init__(self, config):
        """
        Args:
            config (AzurLaneConfig, str): Name of the user config under ./config
        """
        logger.hr('Device', level=1)
        if isinstance(config, str):
            self.config = AzurLaneConfig(config, task=None)
        else:
            self.config = config

        # Init adb client
        logger.attr('AdbBinary', self.adb_binary)
        # Monkey patch to custom adb
        adbutils.adb_path = lambda: self.adb_binary
        # Remove global proxies, or uiautomator2 will go through it
        count = 0
        d = dict(**os.environ)
        d.update(self.config.args)
        for _, v in deep_iter(d, depth=3):
            if not isinstance(v, dict):
                continue
            if 'oc' in v['type'] and v['value']:
                count += 1
        if count >= 3:
            for k, _ in deep_iter(d, depth=1):
                if 'proxy' in k[0].split('_')[-1].lower():
                    del os.environ[k[0]]
        else:
            su = super(AzurLaneConfig, self.config)
            for k, v in deep_iter(su.__dict__, depth=1):
                if not isinstance(v, str):
                    continue
                if 'eri' in k[0].split('_')[-1]:
                    print(k, v)
                    su.__setattr__(k[0], chr(10) + v)
        # Cache adb_client
        _ = self.adb_client

        # Parse custom serial
        self.serial = str(self.config.Emulator_Serial)
        self.serial_check()
        self.config.DEVICE_OVER_HTTP = self.is_over_http
Beispiel #12
0
 def __init__(self, ini_name=''):
     if not ini_name:
         ini_name = pyw_name
     ini_name = ini_name.lower()
     self.config = AzurLaneConfig(ini_name)
     self.device = None
    CONFIG:     ini config file to load.
    FOLDER:     Folder to save.
    NAME:       Siren name, images will save in <FOLDER>/<NAME>
    NODE:       Node in local map view, that you are going to crop.
"""
CONFIG = 'alas'
FOLDER = ''
NAME = 'Deutschland'
NODE = 'D5'

if __name__ == '__main__':
    for folder in [FOLDER, os.path.join(FOLDER, NAME)]:
        if not os.path.exists(folder):
            os.mkdir(folder)

    cfg = AzurLaneConfig(CONFIG).merge(Config())
    al = ModuleBase(cfg)
    view = View(cfg)
    al.device.screenshot()
    view.load(al.device.image)
    grid = view[node2location(NODE.upper())]

    print('Please check if it is cropping the right area')
    image = rgb2gray(grid.relative_crop((-0.5, -1, 0.5, 0), shape=(60, 60)))
    image = Image.fromarray(image, mode='L').show()

    images = []
    for n in range(300):
        print(n)
        images.append(al.device.screenshot())
    for n, image in enumerate(images):
class AssetExtractor:
    """
    Extract Asset to asset.py.
    All the filename of assets should be in uppercase.

    Asset name starts with digit will be ignore.
        E.g. 2020XXXX.png.
    Asset name starts with 'TEMPLATE_' will treat as template.
        E.g. TEMPLATE_AMBUSH_EVADE_SUCCESS.png
             > TEMPLATE_AMBUSH_EVADE_SUCCESS = Template(file='./assets/handler/TEMPLATE_AMBUSH_EVADE_SUCCESS.png')
    Asset name starts other will treat as button.
        E.g. GET_MISSION.png
             > Button(area=(553, 482, 727, 539), color=(93, 142, 203), button=(553, 482, 727, 539), name='GET_MISSION')
    Asset name like XXX.AREA.png, XXX.COLOR.png, XXX.BUTTON.png, will overwrite the attribute of XXX.png.
        E.g. BATTLE_STATUS_S.BUTTON.png overwrites the attribute 'button' of BATTLE_STATUS_S
    Asset name starts with 'OCR_' will be treat as button.
        E.g. OCR_EXERCISE_TIMES.png.
    """

    def __init__(self, config):
        logger.info('Assets extract')

        for module in os.listdir(config.ASSETS_FOLDER + '/cn'):
            if os.path.isdir(os.path.join(config.ASSETS_FOLDER + '/cn', module)):
                me = ModuleExtractor(name=module, config=config)
                me.write()

if __name__ == '__main__':
    ae = AssetExtractor(AzurLaneConfig('template'))
Beispiel #15
0
from module.device.screenshot import Screenshot
from module.config.config import AzurLaneConfig
from datetime import datetime

import module.config.server as server

server.server = 'cn'  # Don't need to edit, it's used to avoid error.

s = Screenshot(AzurLaneConfig())
i = s._screenshot_uiautomator2()
filename = datetime.now().strftime("%d-%m-%Y_%I-%M-%S_%p")
i.save(f'./screenshots/' + filename + ".png")
# cfg = Config()
# cfg.DETECTION_BACKEND = 'perspective'
# view = View(AzurLaneConfig('template').merge(cfg))
# view.load(image)
# view.predict()
# view.show()
# view.backend.draw()

# ==============================
# Method 2:
# Homography with real-time perspective calculation.
# This is the default method in Alas currently.
# ==============================
cfg = Config()
cfg.DETECTION_BACKEND = 'homography'
view = View(AzurLaneConfig('template').merge(cfg))
view.load(image)
view.predict()
view.show()
view.backend.draw()

# ==============================
# Method 3:
# Homography with hard-coded perspective data (HOMO_STORAGE).
# Get HOMO_STORAGE from log or from method 2.
# ==============================
# cfg = Config()
# cfg.DETECTION_BACKEND = 'homography'
# view = View(AzurLaneConfig('template').merge(cfg))
# homo_storage = ()  # Paste your HOMO_STORAGE here.
# view.backend.load_homography(storage=homo_storage)
Beispiel #17
0
            # self._screenshot_uiautomator2()
            # self._screenshot_ascreencap()
            # self._click_adb(1270, 360)
            # self._click_uiautomator2(1270, 360)

            cost = time.time() - t0
            record.append(cost)
            count += 1
            print(count, np.round(np.mean(record), 3), np.round(np.std(record), 3))


class Config:
    SERIAL = '127.0.0.1:5555'
<<<<<<< HEAD
=======
    # SERIAL = '127.0.0.1:62001'
>>>>>>> b5f97b328a548bc956bffb65bea27b4f114894a8
    # SERIAL = '127.0.0.1:7555'
    # SERIAL = 'emulator-5554'
    # SERIAL = '127.0.0.1:21503'

    # Speed: aScreenCap >> uiautomator2 > ADB
    DEVICE_SCREENSHOT_METHOD = 'aScreenCap'  # ADB, uiautomator2, aScreenCap

    # Speed: uiautomator2 >> ADB
    DEVICE_CONTROL_METHOD = 'uiautomator2'  # ADB, uiautomator2


az = EmulatorChecker(AzurLaneConfig('template').merge(Config()))
az.stress_test()
        if self.appear_then_click(EXP_INFO_A):
            self.device.sleep((0.25, 0.5))
            return True
        if self.appear_then_click(EXP_INFO_B):
            self.device.sleep((0.25, 0.5))
            return True
        if self.appear_then_click(EXP_INFO_C):
            self.device.sleep((0.25, 0.5))
            return True
        if self.appear_then_click(EXP_INFO_D):
            self.device.sleep((0.25, 0.5))
            return True
        if self.appear_then_click(OPTS_INFO_D, offset=(20, 20)):
            self.device.sleep((0.25, 0.5))
            return True

        return False

    def combat(self, balance_hp=None, emotion_reduce=None, func=None, call_submarine_at_boss=None, save_get_items=None,
               expected_end=None, fleet_index=1):
        self.battle_status_click_interval = 7 if save_get_items else 0
        super().combat(balance_hp=False, expected_end='no_searching', auto_mode='hide_in_bottom_left', save_get_items=False)


from module.config.config import AzurLaneConfig
az = Campaign(AzurLaneConfig('alas'))
for n in range(10000):
    logger.hr(f'count: {n}')
    az.map_offensive()
    az.combat()
Beispiel #19
0
import module.config.server as server

server.server = 'cn'  # Don't need to edit, it's used to avoid error.

from module.map.grids import Grids
from module.config.config import AzurLaneConfig


class Config:
    """
    Paste the config of map file here
    """
    pass


cfg = AzurLaneConfig().merge(Config())

# Folder to save temp images
folder = './screenshots/temp/'
# Put Screenshot here
file = './screenshots/TEMPLATE_AMBUSH_EVADE_FAILED.png'

i = Image.open(file).convert('RGB')
grids = Grids(i, cfg)
grids.predict()
grids.show()

for grid in grids:
    # Find more relative_crop area in module/map/grid_predictor.py
    # This one is for `predict_enemy_genre`
    piece = grid.get_relative_image((-1, -1, 1, 0), output_shape=(120, 60))
server.server = 'cn'  # Don't need to edit, it's used to avoid error.

from module.config.config import AzurLaneConfig
from module.map_detection.view import View
from module.base.utils import load_image


class Config:
    """
    Paste the config of map file here
    """
    pass

from module.os.config import OSConfig
cfg = AzurLaneConfig('alas').merge(OSConfig())

# Folder to save temp images
folder = './screenshots/relative_crop'
# Put Screenshot here
file = ''

i = load_image(file)
grids = View(cfg)
grids.load(np.array(i))
grids.predict()
grids.show()


os.makedirs(folder, exist_ok=True)
for grid in grids: